/* Slideshow jQuery Plugin, Adam Szatrowski*/

// IE Fix for fadein/fadeout to keep cleartype font...
(function($) {
    $.fn.customFadeIn = function(speed, callback) {
	

	$(this).fadeIn(speed, function() {
            if(jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });
	
	
    };
    $.fn.customFadeOut = function(speed, callback) {
        $(this).fadeOut(speed, function() {
            if(jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });	
    };
})(jQuery);

(function($) {
  $.slideshow = {
    SCROLL_VERTICAL:false,
    SCROLL_HORIZONTAL:false,
    defaults: {
      scrollstyle:false,
      itemSize:-1, //Calculate it.
      perPage:5,
      targetDuration:4000,
      slideDuration:1000,
      fadeDuration:2000,
      disablePeriodicOnMouseEnter:true,
	  startAt:0
    }
  }
  var myC = 
    {log:function(){}};
    //window.console;
  /*
   * Images: An array of objects containing a url member and a src member.
   *    The src member defines the images location
   *    The url member deinfes the url to link to for that target
   *    Note: these should be in the same order as the corresponding thumb html in the tray.
   * Options: An object with optional paramaters:
   *    scrollstyle:$.slideshow.SCROLL_HORIZONTAL or $.slideshow.SCROLL_VERTICAL, which way the tray is to scroll
   *    itemSize:-1, The width of each item in the tray -1 will result in the width being calculated on the fly
   *    perPage:4, How many items to show in the tray at one time
   *    targetDuration:4000, How long each image is displayed in the target
   *    slideDuration:1000, How long the tray takes to slide from one page to the next
   *    fadeDuration:2000, How long each image fades out for between images in the target.
   *    disablePeriodicOnMouseEnter:true, if true, the slideshow will stop while the mouse is int he slideshow wrapper.
   */
  //DELETEME
  /* function _d(v) {
    alert(typeof v == 'object'?$.param(v):v);
  } */
  $.fn.slideshow = function(images,options) {
    options = $.extend(false, {}, $.slideshow.defaults, options);
    //options.targetDuration=50;
    //options.slideDuration=50;
    //options.fadeDuration=50;
    var root = this, 
        current = -1, //Which image is in the target?
        currentPage=0, //how many images off 0 are we?
        interval=false, //The interval set to handle periodic chaning of the image
        nextFrameTime=-1, //Time at which next photo should be shown.
        numImages=Math.max(
          images.length,
          $('.slideshow-thumbs li').length
        ),
        numPages = Math.ceil(numImages/options.perPage),
        scrolling = false
        //,currentlyBoundSwapper = null
        //,imgLoader = null
        ;
    if(options.itemSize<=0)
      options.itemSize = $('.slideshow-thumbs li:eq(0)',root).outerWidth(true);
    
    function swapimage(i,callingevent) {
		
      if(scrolling)
        return;
      i=(i+numImages)%numImages;
      if(current==i)
        return;
      var previous = current;
      current = i;
      resetperiodicframe();
      var f = function(e){
        if(current!=e.data.i)
          return;
        //currentlyBoundSwapper = null;
        i = current;
        images[i].loaded = true;
        //Unhighlight the current one
        $('ul.slideshow-thumbs li:neq('+current+')', root)
          .removeClass('slideshow-current-thumb');
        resetperiodicframe();
        scrollto(i); //Do this after current is set, so scroll to can call swapimage() if current isn't visible.
        $('ul.slideshow-thumbs li:eq('+i+')', root)
          .addClass('slideshow-current-thumb');
        
        var g = function(speed) {
          $('#slideshow-bottom-text', root)
            .html((images[current].relatedContent.length?'<img src="/images/featureWell_separator.gif" class="slideshow_separator" />':'') + '<div>'+images[current].title+'</div><span>'+images[current].text+'</span>');
		  if(images[current].relatedContent.length){	
			  $('#slideshow-related-content-inner span', root)
				.html(images[current].relatedContent);
//			  $('#slideshow-related-content-inner', root).show();	
		  }
		  else
		  	$('#slideshow-related-content-inner', root).hide();
        }
        if(images[previous]&&images[previous].title){
          $('.slideshowtext', root).customFadeOut(options.fadeDuration/(images[current].title?2:1), function() {
            if(images[current].title) {
              g(.5);
            }});
		  
		  $('##slideshow-related-content', root).customFadeOut(options.fadeDuration/(images[current].title?2:1), function() {
            if(images[current].title) {
              g(.5);
            }});
		  }
        else if(images[current].title)
          g(1);
        if(!images[current].title)
          $('.slideshowtext',root).hide();
	
		if(!($("img.slideshow-target").length)){
			// Doesn't exist...add it...
			var newImg = new Image();
			newImg.className = "slideshow-target";
			newImg.src="";
			newImg.alt="";
			$("#loader").replaceWith(newImg);
			newImg = undefined;
		}
		
        var src = images[i].src,
            t = $('img.slideshow-target',root);

			if(callingevent == 'mouseover'){
				$('.slideshow-target-link',root)
		          .attr('href',images[i].url).css({'background-image':'none'});
					t.replaceWith('<div id="loader" class="loading"></div>');
			}
			
			t.load(function(){							
				$("#loader").replaceWith(this);							
				$("#slideshow").fadeIn();
				 
				 
				});		
		$('.slideshowtext', root)
				.customFadeIn(options.fadeDuration*1);
        $('.slideshow-target-link',root)
          .attr('href',images[i].url).css({'background-image':'url(\''+src+'\')','background-repeat':'no-repeat'});
        t.customFadeOut(options.fadeDuration, function() {
          t.attr('src',images[current].src).show(); 
        });
      };  
      if(!images[i].loaded&&!$.browser.msie) {
        /*imgLoader = */$('<img>')
          .attr('src', images[i].src)
          .bind('load',{i:current},f);

      } else {
        f({data:{i:i}});

      }	  
	  // Cleanup...
	  src = undefined;
	  t = undefined;
	  g = undefined;
	  f = undefined;
	  return;
    }
    //Scrolls to page with the ith images
    function scrollto(i) {
      i=(i+numImages)%numImages;
      var page = Math.floor(i/options.perPage);
      scrolltopage(page);
    }
    //Scrolls to a given page if it can.
    function scrolltopage(page) {
      page = (page+numPages)%numPages;
      if(currentPage==page)
        return;
      if(current<(page*options.perPage)||current>=((page+1)*options.perPage))
        return swapimage(page*options.perPage,'');
      scrolling = true;
      endperiodic();
      $('.slideshow-navigation .slideshow-navigation-item:eq('+currentPage+')', root)
        .removeClass('slideshow-navigation-current');
      currentPage = page;
      $('.slideshow-navigation .slideshow-navigation-item:eq('+currentPage+')', root)
        .addClass('slideshow-navigation-current');
      cssMap = {};

      cssMap[$.slideshow.SCROLL_HORIZONTAL?'marginLeft':'marginTop'] 
        = -1*page*options.perPage*options.itemSize;

      $('ul.slideshow-thumbs', root).animate(cssMap, 
        options.slideDuration,
        'swing',
        function() {
          scrolling = false;
          startperiodic();
        }
      );    
    }
    //Scrolls to a page relative to the current one.
    function shiftpage(by) {
      scrolltopage(currentPage+by);	  
    }
    function startperiodic() {
      if(interval)
        return;
      resetperiodicframe();
      interval = setInterval(function() {
        var t = new Date().getTime();
        if(t>=nextFrameTime)
          swapimage(current+1,'');
      },250);
    }
    function endperiodic() {
      if(interval) {
        clearInterval(interval);
        interval = false;
      }
    }
    function resetperiodicframe() {
      nextFrameTime = options.targetDuration+(new Date().getTime());
    }
    //Attach thumb events
    $('ul.slideshow-thumbs li',this).each(function(i) {
      $(this).bind('click',{i:i},function(e){											  
        swapimage(e.data.i,'mouseover');
		return false;
      });
    });
    //Prev/next events
    $('.slideshow-button-previous',root).bind('click',function(e){
      shiftpage(-1);
    });
    $('.slideshow-button-next',root).bind('click',function(e){
      shiftpage(1);
    });
    //Nav button events
    var navWrapper = $('.slideshow-navigation', root),
        item = $('.slideshow-navigation-item:eq(0)', navWrapper);
    for(var i=0; i<numPages; i++) {
      item.bind('click', {i:i}, function(e){scrolltopage(e.data.i);});
      if(i==numPages-1)
        break;
      item=item.clone();
      navWrapper.append(item);
    }
    $('.slideshow-navigation-item:eq(0)', navWrapper)
      .addClass('slideshow-navigation-current'); //Mark the first one as current initially
    
    root.bind('mouseenter',function() {endperiodic();});
    root.bind('mouseleave',function() {startperiodic();});
    //set it in motion.

    swapimage(options.startAt,'');
    startperiodic();//Finally, start rotating through images.
    return this;
  }
})(jQuery);