/*
 * --------------------------------------------------------------------
 * Tiffany Slider
 * by Vukadin Njegos, vukadinsu@gmail.com
 * Version: 1.0, 29.09.2011 	
 * --------------------------------------------------------------------
 */
(function($){
    
    $.fn.tiffanySlider = function( options ){
      
      var settings =  {
          slideSpeed : 400,
          thumbSpeed : 900,
          duration : 4000,
          thumbsHeight : 187,
          autorun : true
      }
      
      var opts = $.extend(settings,options);
      
      return this.each(function(){
         
         var $images = $(".gallery img",this);
	 var $thumbsContainer = $(".thumbs",this);
         $thumbsContainer.scrollTop(0);
	 var $thumbs = $("img",$thumbsContainer);
         var total = $thumbs.size();
         $thumbs.slice(0,3).clone(true).appendTo($thumbsContainer);
         $thumbs = $("img",$thumbsContainer);
         var currentIndex = -1;
         var imgHeight = opts.thumbsHeight;
         var timeout;
         
         $thumbs.each(function( index ){
             
             $(this).click(function(e){
                 show(index);
            });
            
         });
         
         
         function show( newIndex ){
             
             var nextIndex = newIndex;
             
             if(newIndex >= total  ){
                 nextIndex=newIndex - total;
             }
             
             if(currentIndex!=nextIndex){
                 
                clearTimeout(timeout);
                
                $images.not($images.eq(nextIndex)).fadeOut(opts.slideSpeed);
                
                $images.eq(nextIndex).fadeIn(opts.slideSpeed);

                $thumbsContainer.stop().animate({scrollTop: newIndex * imgHeight }, opts.thumbSpeed,function(){
                    
                        $thumbsContainer.scrollTop( nextIndex* imgHeight);
                        
                         if(opts.autorun){
                             queue();
                         }
                    
                });
                
                currentIndex=nextIndex;
                
             }
                
         };
         
         function queue(){
             
             timeout = setTimeout(function(){
                 
                 show(currentIndex + 1);
                 
             },opts.duration)
             
         }
         
         show(0);
         
         if(opts.autorun){
             queue();
         }
         
         
      });
      
    };
    
})(jQuery);

var jx = jQuery.noConflict();

jx(document).ready(function($) 
{	 
	$("#gallery_container").tiffanySlider({
          slideSpeed : 400,
          thumbSpeed : 900,
          duration : 4000,
          thumbsHeight : 187,
          autorun : true
      })
});


