(function($) {

  
  $.fn.looper = function(options) {
    var defaults = {
      speed				:	100, // transition between slides, in milliseconds
      pause				:	1000, // length of time to remain on each slide, in milliseconds
      transition		:	'crossfade', // crossfade is the only option right now
      navigation		:	true, // set to false to turn off the navigation
      slide_reset		:	true,
      slide_captions	:	true,
      slide_counter		:	true,
      speed_controls	:	true,
      forward_backward	:	true,
      autoplay			:	false
    },
    
    options = $.extend(defaults, options);
    
    if (options.pause <= options.speed) options.pause = options.speed + 100;
    
    return this.each(function() {

      var $this = $(this);
      
      var $interval = ''; // variable used in the setInterval method
      var $curr_pause = options.pause; // take the start value from defaults. this is used for the speed controls
      
      $this.wrap('<div class="looper_wrap" />');
      
      var $paused = '';
      if (options.autoplay === true) {
        $paused = false;
      } else {
        $paused = true;
      }
      
      // PREP THE OVERLAY
      if ($this.children('.overlay').length > 0) {
        var $overlay = $this.children('.overlay');
        $overlay.insertBefore($this).hide();
        var $overlay_link = $overlay.attr('src');
        $this.parent().prepend('<a href="">Show overlay</a>');
        var $overlay_btn = $this.parent().children('a');
        $overlay_btn.addClass('overlay_toggle');
        $overlay_btn.attr('href',$overlay_link);
      
        $overlay_btn.toggle(function(){
          $this.siblings('.overlay').fadeIn(200);
          $this.siblings('.overlay_toggle').html('Hide overlay');
        }, function(){
          $this.siblings('.overlay').fadeOut(200);
          $this.siblings('.overlay_toggle').html('Show overlay');
          return false;
        });
      }
      
      // GRAB DIMENSIONS FROM THE FIRST IMAGE
      var $image_width = $this.children('img:first').width()+'px';
      var $image_height = $this.children('img:first').height()+'px';
      $this.css({
        'position'	:	'relative',
        'width'		:	$image_width,
        'height'	:	$image_height
      });
      $this.parent('.looper_wrap').css({
      	'width'		:	$image_width
      });
      
      // THE DEFAULT CROSSFADE EFFECT
      if (options.transition === 'crossfade') {
        
        var $images = $this.children('img');
        
        for (var i = 0; i<$images.length; i++){
          $images[i].setAttribute('id', i+1);
        }
        
        $this.children().css({
          'position'	:	'absolute',
          'left'		:	0
        });
        
        $this.children(':first').appendTo($this).show();
        
        if (options.navigation === true) {
          createNavigation();

          var $nav = $this.siblings('.navigation');
          
          // PLAY PAUSE BUTTON
          $nav.children('.nav_left').children('.pauseplay').click(function() {
            if ($paused === false) {
              stopIt();  
            } else {
              moveIt();
            }
          });
          
          // NEXT BUTTON
          $nav.children('.nav_right').children('.next').click(function() {
            stopIt();
            forward();
          });
          
          // PREVIOUS BUTTON
          $nav.children('.nav_right').children('.prev').click(function() {
            stopIt();
            backward();
          });
          
          /// RESET BUTTON
          $nav.children('.nav_right').children('.reset').click(function() {
			stopIt();
            resetSlides();
          });
          
          /// SPEED CONTROLS
        
          var $slower = $nav.children('.nav_right').children('.speed').children('.slower');
          var $faster = $nav.children('.nav_right').children('.speed').children('.faster');
          $slower.click(function() {
            if ($curr_pause < 2000) {
              clearInterval($interval);
              $curr_pause = $curr_pause * 1.5;
              moveIt();
            }
          });
          $faster.click(function() {
            if ($curr_pause > 100) {
              clearInterval($interval);
              $curr_pause = $curr_pause / 1.5;
              moveIt();
            }
          });
        }
        
      if (options.autoplay === false) {
          stopIt();
        } else {
          $interval = setInterval(function() {
            forward();
          }, options.pause);
        }
      }
      
      
      
      // PAUSE THE CYCLING
      function stopIt() {
        $this
          .siblings('.navigation')
          .children('.nav_left')
          .children('.pauseplay')
          .removeClass('pause');
        $this
          .siblings('.navigation')
          .children('.nav_left')
          .children('.pauseplay')
          .addClass('play');
        clearInterval($interval);
        $paused = true;
      }
      
      
      // START THE CYCLING	
      function moveIt() {
        $this
          .siblings('.navigation')
          .children('.nav_left')
          .children('.pauseplay')
          .removeClass('play');
        $this
          .siblings('.navigation')
          .children('.nav_left')
          .children('.pauseplay')
          .addClass('pause');
        $interval = setInterval(function() {
          forward();
        }, $curr_pause);
        $paused = false;
      }
      
      
      // STEP FORWARD
      function forward() {
        var $curr_first = $this.children(':first');
        $curr_first.hide().appendTo($this).fadeIn(options.speed);
          if (options.navigation === true) {
            fetchSlideNumber();
          }
          if (options.slide_captions === true) {
            updateCaption();
          }
      }

      // STEP BACKWARD
      function backward() {
          var $curr_last = $this.children(':last');
          $curr_last.fadeOut(options.speed, function(){
          $curr_last.show().prependTo($this);
          if (options.navigation === true) {
            if (options.slide_counter === true) {
              fetchSlideNumber();
            }
            if (options.slide_captions === true) {
              updateCaption();
            }
          }
        });
      }
      
      // RESET SLIDES
      function resetSlides() {
      	
        // gather all the slides and stuff them into an array
        var $collectedSlides = new Array();
        var $slidesToCollect = $this.children('img');
        for (var i = 0; i < $slidesToCollect.length; i++) {
          var $curr_slide = $slidesToCollect[i].getAttribute('id');
          $collectedSlides[i] = $this.children('#'+(i+1));
		  
        }
        
        // sort the array numerically and ascending
        $collectedSlides.sort(function(a,b){return a-b});
        
        // loop through the array and append them in order
        for (var x in $collectedSlides) {
          $this.append($collectedSlides[x]);
        }
        
        // take the first slide and move it to the end
        $this.children(':first').appendTo($this).show();
        
        if (options.navigation === true) {
          if (options.slide_counter === true) {
            fetchSlideNumber();
          }
          if (options.slide_captions === true) {
            updateCaption();
          }
        }
      }

      // UPDATE SLIDE NUMBER
      function fetchSlideNumber(){
        var $slideID = $this.children(':last').attr('id');
        var $slideNumber = $this.siblings('.navigation').children('.nav_right').children('.counter').children('.slidenumber');
        $slideNumber.html($slideID);
      }
      
      // UPDATE CAPTION
      function updateCaption(){
        var $slideAlt = $this.children(':last').attr('alt');
        var $slideCaption = $this.siblings('.navigation').children('.nav_left').children('.caption');
        $slideCaption.html($slideAlt);
      }
      
      
      // CREATE THE NAVIGATION DIV
      function createNavigation() {
        $this.parent().append('<div class="navigation"></div>');
        
        var $nav = $this.siblings('.navigation');
        
        $nav.append('<div class="nav_left"></div>');
        $nav.append('<div class="nav_right"></div>');
        
        var $nav_left = $nav.children('.nav_left');
        var $nav_right = $nav.children('.nav_right');
        
        $nav_left.append('<span class="pauseplay pause">Pause</span>');
        
        if (options.slide_captions === true) {
          $nav_left.append('<span class="caption"></span>');
          $nav_left.children('.caption').html($this.children('img:last').attr('alt'));
        }
        
        if (options.slide_reset === true) {
          $nav_right.append('<span class="reset">Reset</span>');
        }
        
        if (options.forward_backward === true) {
          $nav_right.append('<span class="prev">Prev</span>');
        }
        
        if (options.slide_counter === true) {
          $nav_right.append('<span class="counter"><b class="slidenumber"></b>/<b class="totalslides"></b></span>');
		  $nav_right.children('.counter').children('.slidenumber').html(1);
		  $nav_right.children('.counter').children('.totalslides').html($this.children('img').size());
		}
		
		if (options.forward_backward === true) {
          $nav_right.append('<span class="next">Next</span>');
        }
        
		if (options.speed_controls === true) {
          $nav_right.append('<span class="speed"><b class="slower">Slower</b><b class="faster">Faster</b></span>');
        }
      }
      
    });
   
  }
})(jQuery);