(function( $ ){

  var methods = {
    init : function( options ) {
      var settings = {
        'animation'         : 'fadeIn',
        'controls'          :  false, //False, or object
        'backgrounds'       :  false,
        'refresh'           : 10000,
        'startIndex'        : 0
      };

      var selector = this.selector;

      return this.each(function(){
        
        if ( options ) { 
          $.extend( settings, options );
        }

        var $this = $(this),
          data = $this.data('backgroundRoller');

          $this.selector = selector;


        // If the plugin hasn't been initialized yet
        if ( ! data ) {

          data = {
            index : settings.startIndex,
            settings: settings,
            multiple: (settings.backgrounds.length>1),
            containers: []
          };
          
          
           // Multiple backgrounds in effect
           
          $.each(data.settings.backgrounds,function(index,background) {
            var bgitem = $("<div></div>");
            bgitem.attr("id","backgroundRoller-background-"+index);
            bgitem.attr("rel",index);
            bgitem.addClass("backgroundRoller-background");
            bgitem.css({"z-index":index-3}); //start at -2

            bgitem.css({
              "position":"absolute",
              "top":"0px",
              "left":"0px",
              "text-align":"center",
              "width":"100%",
              "overflow":"hidden"
            });

            bgitem.html("<img src='"+background+"'>");
            if(index != data.index){
              bgitem.hide();
            }
            else {
              data.active = bgitem;
            }

            
            $this.append(bgitem);
            data.containers.push(bgitem);          
          });

          

          if(data.multiple && settings.controls) {
            var back = $("<a href='#back'></a>").attr("id","backgroundRoller-back").addClass("backgroundRoller-control");
            var forward = $("<a href='#forward'></a>").attr("id","backgroundRoller-forward").addClass("backgroundRoller-control");
            
            back.html(settings.controls.backHTML);
            forward.html(settings.controls.forwardHTML); 
            
            back.bind("click.backgroundRoller",function(){ $($this.selector).backgroundRoller("back");});
            forward.bind("click.backgroundRoller",function(){$($this.selector).backgroundRoller("forward");});
            
            data.controls = {
              back: back,
              forward: forward
            };
          }
         
          $(settings.controls.selector).append(back).append(forward); 

          $this.data('backgroundRoller', data);


        }
 
        if(data.multiple) {      
          $this.bind("back.backgroundRoller",methods.back);
          $this.bind("forward.backgroundRoller",methods.forward);
          $this.bind("start.backgroundRoller",methods.start);
          $this.bind("stop.backgroundRoller",methods.stop);
        } 

        if(data.multiple && settings.refresh) {
          $this.backgroundRoller("start");
        }

      });

    },
    
    destroy : function( ) {

      return this.each(function(){
        var $this = $(this),
          data = $this.data('backgroundRoller');

        // Namespacing FTW
        $(this).unbind('.backgroundRoller');
        data.backgroundRoller.remove();
        $this.removeData('backgroundRoller');
         
      })

    },
    
    stop : function( ) { 
      var $this = $(this),
        data = $this.data('backgroundRoller');
      if(data.interval) {  
        clearInterval(data.interval);
      }
    },
    
    start : function( ) { 
      var $this = $(this),
        data = $this.data('backgroundRoller');

        
      if(!data.multiple) {
        return false;
      }                
      $this.backgroundRoller("stop"); //Stop before starting
      
      if(data.settings.refresh) {
        data.interval = setInterval("jQuery('"+$this.selector+"').backgroundRoller('forward')",data.settings.refresh);
      }
    },
    
    back : function( ) { 
      var $this = $(this),
        data = $this.data('backgroundRoller');
                
      if(!data.multiple) {
        return false;
      }
      
      if(data.last) {
        //Push back to original position and hide
        data.last.hide().css({"z-index":data.last.attr("rel")-3});
      }
      
      //Store last active, cause we need to edit z-index later..
      data.last = data.active;
      data.last.css({"z-index":"-2"});
      
      //traversing elements...or should I use the containers array instead..?
      if(data.active.prev(".backgroundRoller-background").length){
        data.active = data.active.prev(".backgroundRoller-background");        
      }
      else {
        data.active = data.active.nextAll(".backgroundRoller-background").last();
      }
      
      data.active.hide().css({"z-index":"-1"}); //Hide this before changing..otherwhise will show through
      
      data.active.fadeIn();   

    },
    
    forward : function( ) { 
      var $this = $(this),
        data = $this.data('backgroundRoller');
        
      if(!data.multiple) {
        return false;
      }
      
     if(data.last) {
        //Push back to original position and hide
        data.last.hide().css({"z-index":data.last.attr("rel")-3});
      }
      
      //Store last active, cause we need to edit z-index later..
      data.last = data.active;
      data.last.css({"z-index":"-2"});
      
      //traversing elements...or should I use the containers array instead..?
      if(data.active.next(".backgroundRoller-background").length){
        data.active = data.active.next(".backgroundRoller-background");        
      }
      else {
        data.active = data.active.prevAll(".backgroundRoller-background").last();
      }
      
      data.active.hide().css({"z-index":"-1"}); //Hide this before changing..otherwhise will show through
      
      data.active.fadeIn();     
      
    }

    
  };

  $.fn.backgroundRoller = function( method ) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.backgroundRoller' );
    }    
  
  };

})( jQuery );

