
/**
* A simple jQuery slideshow. Apply it to a <ul> element and it will take care of the rest
*/
(function( $ ){
  $.fn.slideshow = function( options ) {

    return this.each(function() {
      var list = this;
      var paused = false, pauseTripped = false;
      var timer, pages, pagination, paginationWrapper, container, maxHeight = 0, width;
      var $container, $list;
      
      var selected = { page: null, pagination: null }

      if( list.nodeName != "UL" ){
        list = $(list).find("ul").get(0);
      }
      if( !list ){
        return;
      }
      $list = $(list);
      
      // Options
      var settings = {
        'delay': 4000,
        'animateSpeed': 550,
		'loadDelay': -1,
        'transition': 'slide',
		'pauseOnMouseover': true
      };
      if ( options ) { 
        $.extend( settings, options );
      }
      
      // Create a unique ID for an element
      function createUniqueId(el){
        if( el.id != "" ){
          return;
        }
        
        var index = 0;
        var id;;
        while( (id = "slideshow-page-"+ index) && document.getElementById(id) != null ){
          index++;
        }
        
        el.id = id;
        return id;
      }
      
      // Update max height of container with this loaded list item
      function updateMaxDimension(li){
        li = $(li);
        if( li.height() > maxHeight ){
          maxHeight = li.height();
          $container.css("height", maxHeight +"px");
        }  
      }
      
      // Build containers
      container = document.createElement("div");
      container.className = "slideshow-wrapper";
      $container = $(container);
      
      paginationWrapper = document.createElement("ol");
      paginationWrapper.className = "slideshow-pagination";
      
      list.parentNode.insertBefore(container, list);
      container.appendChild(list);
      container.appendChild(paginationWrapper);
      
      // Add pagination
      pages = $list.find("li");
      pagination = [];
      for( var i = 0, len = pages.length; i < len; i++ ){
        var $page = $(pages[i]);
        var id = createUniqueId( pages[i] );
        var li = document.createElement("li");
        var a = document.createElement("a");
        
        pages[i]._position = width;
        pages[i]._index = i;
        
        // Create HTML
        a.href = "#"+ id;
        a.innerHTML = (i + 1);
        a._index = i;
        $(a).click( function(){ 
          gotoPage(this._index); 
          return false; 
        });
        
        li.appendChild(a);
        paginationWrapper.appendChild(li);
        pagination.push( li );
        
        // Calculate height/width
        updateMaxDimension(pages[i]);
        width += $page.width();
        
        // Update when images load
        $page.find("img").load(function(){
          updateMaxDimension($(this).parent("li").get(0))
        });
        
        // CSS
        if( settings.transition == "slide" ){
          $page.css("float", "left"); 
        }
        else if( settings.transition == "fade" ){
          $page.css("position", "absolute");
          $page.css("top", "0");
          $page.css("left", "0");
          $page.css("display", "none"); 
        }
      }
      if( settings.transition == "fade" ){
        $(pages[0]).css("display", "block"); 
      }
    
      // Set styles
      $container.css("position", "relative");
      if( settings.transition == "slide" ){
        $container.css("height", maxHeight +"px");
        $container.css("overflow", "hidden");
      }
      
      if( settings.transition == "slide" ){
        $list.css("width", width +"px");
        $list.css("position", "absolute");
        $list.css("top", 0);
        $list.css("left", 0);
      }
      
      // Animate to a page
      function gotoPage( index ){
        var lastPage;
        clearTimeout(timer);
        timer = null;
        
        if( paused ){
          pauseTripped = true;
          return;
        }
        pauseTripped = false;
        
        // Reset last selected
        if( selected.page ){
          lastPage = selected.page;
          $(selected.page).removeClass("active");
          $(selected.pagination).removeClass("active");
        }
        
        // Get page
        var page = pages[index];
        if( !page ){
          return;
        }
        
        function animationCleanup(){
          selected.page = page;
          selected.pagination = pagination[index];
          timer = setTimeout(function(){ nextPage() }, settings.delay);
        }
        
        // Animate and start the next one
        $(pagination[index]).addClass("active");
        if( settings.transition == "slide" ){
          $list.animate( { left: (page._position * -1) }, settings.animateSpeed, "swing", animationCleanup);
        } else if( settings.transition == "fade" ){
          if( lastPage ){
            $(lastPage).fadeOut(settings.animateSpeed); 
          }
          $(page).fadeIn(settings.animateSpeed, animationCleanup);
        }
      }
      
      // Scroll to the next page
      function nextPage(){
        var index = -1;
        if( selected.page ){
          index = selected.page._index;
        }
        index++;
        
        if( index >= pages.length ){
          index = 0;
        }
        
        gotoPage(index);
      }
      
      // Pause animation onmouseover
	  if( settings.pauseOnMouseover ){
		  $list.hover(function(){
			paused = true;
		  },
		  function(){
			paused = false;
			
			if( pauseTripped ){
			  nextPage();
			}
			else{
			  clearTimeout(timer);
			  timer = setTimeout(nextPage, settings.delay); 
			}
		  });
	  }
	  
      // Start animation
	  if(settings.loadDelay > 0){
		pages[0].style.display = "none";
        setTimeout(function(){ nextPage() }, settings.loadDelay);  
	  }
	  else{
	    gotoPage(0);
	  }
    });

  };
})( jQuery );

