(function ($) {
  $.fn.fadeTransition = function(options) {
    var transitionObject,
        options = $.extend({pauseTime: 5000,
                            transitionTime: 2000,
                            ignore: null,
							
							/* added by R'phael Spindel <rspindel@webspin.biz> */
							debug: false,
							maxIterations: 1,
							clickToProgress:  false,
							
							pauseButton: null,
							prevButton: null,
							nextButton: null,

							pauseButtonId: 'pauseButton',
							prevButtonId:  'prevButton',
							nextButtonId:  'nextButton',							
							
							pauseButtonText: 'Play/Pause',
							prevButtonText:  'Previous',
							nextButtonText:  'Next',
							/* ---------------------------------------------- */

                            delayStart: 0,	
                            pauseOnMouseOver: false,
                            manualNavigation: false,
                            createNavButtons: false}, options);
                            
    function fader(obj) {
      var timer = null,
          current = 0;
		  iterations = 0;  /* added by RS */
          els = (options.ignore)?$("> *:not(" + options.ignore + ")", obj):$("> *", obj);
      
      function setup() {
        $(obj).css("position", "relative");
        els.css("display", "none").css("left", "0").css("top", "0").css("position", "absolute");
        
        if (options.createNavButtons) {
          createNavButtons();
        }
      
        if (options.pauseOnMouseOver) {
          $(obj).mouseover(pause).mouseout(cue);
        }
      
        if (options.delayStart > 0) {
          setTimeout(showFirst, options.delayStart);
        }
        else {
          showFirst();
        }

		/* added by RS - feature supports clicking on slide to go forward */
		if ( options.clickToProgress ) 
			els.click( function() { transition((current + 1) % els.length | 0); } ); 
      }
      
      setup();
	  
	  
      
      function createNavButtons() {
        var i, nav = $('<div class="fadenav"></div>');
		var nav_extras = $('<div class="fadenav_extras"/>');  /* added by RS */
		var nav_outer = $('<div class="fadenav_outer" />' );  /* added by RS, used to contain all nav button divs */
		
        for (i=0; i<els.length; i++)
          $('<a href="#">&nbsp;</a>').click(manualNav).appendTo(nav);
         
		/* added by R'phael Spindel <rspindel@webspin.biz> */

		/* next button last (they are appended in reverse order )*/
		if ( options.nextButton ) {
			$( '<a href="#">' + options.nextButtonText + '</a>' ).click( function() { 
				// allow for wrapping!!
				if ( ! ( ( current + 1 ) > ( els.length - 1 ) ) )
					transition(current+1); 
				else
					transition( 0 );
				} ).attr( 'id', options.nextButtonId ).appendTo( nav_extras );
		}
		
		
		/* play pause button in the middle */
		if ( !options.manualNavigation && options.pauseButton ) {
			pausebutton = $( '<a href="#">' + options.pauseButtonText + '</a>' ).click( function() {
				if ( $(this).hasClass( 'paused' ) )
					{
					$(this).removeClass( 'paused' );
					$(this).addClass( 'playing' );
					cue();
					}
				else
					{
					$(this).removeClass( 'playing' );
					$(this).addClass( 'paused' );
					pause();
					}
				}).attr( 'id', options.pauseButtonId ).addClass( 'playing' ).appendTo(nav_extras);
		}


		/* previous button first */
		if ( options.prevButton ) {
			$( '<a href="#">' + options.prevButtonText + '</a>' ).click( function() { 
				// allow for wrapping!!
				if ( ! ( (current-1) < 0 ) )
					transition(current-1); 
				else 
					transition( els.length - 1 );
				} ).attr( 'id', options.prevButtonId ).appendTo( nav_extras );
		}
		

		/* chain append all the nav divs within the nav_outer div and then add the whole to the slideshow) */
		nav_outer.append( nav );
		nav_outer.append( nav_extras );
		nav_outer.appendTo( obj );
		
		/* ------------------------------------------------ */
        
      }
      
      function manualNav(e) {
        var item;
        e = e || window.event;
        $(e.target).blur();
        item = $('.fadenav a', obj).index(e.target);
        if (timer) {
          clearTimeout(timer);
        }
        transition(item);
        return false;
      }
      
      function pause() {
		if ( pausebutton )			
			$( pausebutton ).removeClass( 'playing' ).addClass( 'paused' );
	  
        if (timer)
          clearTimeout(timer);
      }
      
      function highlightNav() {
        if (options.createNavButtons) {
          $('.fadenav a', obj).removeClass('current');
          $('.fadenav a:nth-child(' + (1 + current) + ')', obj).addClass('current');
        }
      }
      
      function showFirst() {
        if (options.ignore) {
          $(options.ignore, obj).fadeOut(options.transitionTime);
          $(els[current]).fadeIn(options.transitionTime, cue);
        }
        else {
          $(els[current]).css("display", "block");
		  cue();
        }
        
        highlightNav();
      }

      function transition(next) {		
	  
	    /* Added by RS ----------------- */
		
		// track iterations
		if ( 0 == next ) 
			{
			iterations++;
			if ( options.debug ) console.log( 'new iteration:' + iterations );
			}
		
		/* stop slideshow if maxIterations reached */
		if ( options.maxIterations )
			{
			if ( iterations == options.maxIterations )
				{
				if ( options.debug ) console.log( 'stopping. max iterations:' + iterations );
				pause();
				iterations = 0; // reset iterations so user can navigate manually
				return;
				}
			}
			
		
		/* ------------------------------*/
		
        $(els[current]).fadeOut(options.transitionTime);
        $(els[next]).fadeIn(options.transitionTime);
		
        current = next;
        highlightNav();
        cue();
      }

      function cue() {
		if ( pausebutton )			
			$( pausebutton ).removeClass( 'paused' ).addClass( 'playing' );
		
		
        if ($("> *", obj).length < 2) {
          return false;
        }
        
        if (timer) {
          clearTimeout(timer);
        }
        
        if (!options.manualNavigation) {
          timer = setTimeout(function() { transition((current + 1) % els.length | 0)} , options.pauseTime);
        }
      }
    }

    return this.each(function() {
      new fader(this);
    });
  }

})(jQuery);


