/*
JH Specialty, Inc. script to display a slideshow of images. Loads only 2 images
at a time to conserve page size. Image select controls can
be added anywhere on the page to control the slideshow.

Based on Dynamic Slideshow by Yusuf
URL: http://plugins.jquery.com/project/dynamicslideshow
URL2: http://ynzi.com/blog/dynamicslideshow/

Updated by: James X. Anderson
Initial Update: 2009-08-18

Update: 2009-12-29
  * added capability to display image thumbnail or numbers as the controller
Update: 2010-03-04
  * added capability to rotate content of a separte div. ex: rotate text at same time as image
Update: 2010-05-18
  * added capability to have controller blocks be empty
Update: 2010-06-01
  * added capability to apply an active class to the active controller
  * added capability to have a pause/play button

*/

jQuery.fn.dynamicSlideshow = function(options, fgImages) {
  
  options = options || {};
  options.duration = options.duration || 5000;
  var transitionDuration = options.transitionDuration || 1000;
  var titleTransitionDuration = transitionDuration / 2;
  /* default controller style is thumbnails */
  options.controllerStyle = options.controllerStyle || 'thumb';


  var fgContainer = $(this);
  fgImages = fgImages || [];
  var pause = 0;

  if (fgImages.length == 1) {
    pause = 1;
  }

  var curr = 0;
  var prevCurr = 0;
  var timer = '';
  
  function initSlider(fgContainer, fgImages) {
    // make sure only 1 image is in the foreground
    if ($(fgContainer).children().length > 1) {
      $(fgContainer).find('img:last').animate({
        opacity: 0.0
      }, transitionDuration, function() {
        $(this).remove();
      });
    }
    
    // update main foreground Images
    var fg = new Image();
    $(fg).css({
      width:fgImages[curr].imgWidth,
      height:fgImages[curr].imgHeight,
      position:fgImages[curr].imgPosition,
      top:fgImages[curr].imgTop,
      left:fgImages[curr].imgLeft,
      right:fgImages[curr].imgRight,
      bottom:fgImages[curr].imgBottom,
      'z-index':8
    }).load(function(){
      $(fgContainer).append(this);

      $(fgContainer).find('img:first').css({
        'z-index': 1
      });

      /* begin new image fade in */
      $(this).css({
        opacity: 0.0,
        'z-index': 2
      }).animate({
        opacity: 1.0
      }, transitionDuration, function() {
        $(this).css('opacity', '');
      });

      /* update the external title */
      var titleCurr = curr;

      if (options.externalTitleId){
        $('#'+ options.externalTitleId).fadeOut(titleTransitionDuration, function(){
          $('#'+ options.externalTitleId).html(fgImages[titleCurr].externalTitle);
          $('#'+ options.externalTitleId).fadeIn(titleTransitionDuration);
        });
      }

      /* begin old image fade out */
      if ($(fgContainer).children().length > 1) {
        $(fgContainer).find('img:first').animate({
          opacity: 0.0
        }, transitionDuration, function() {
          $(this).remove();
        });
      }


      /* update the image's link */
      if (fgImages[curr].imgHref == ''){
        $(fgContainer).removeAttr('href');
      }
      else {
        $(fgContainer).attr('href', fgImages[curr].imgHref);
      }

      /* update controller to active */
      if (options.controllerActiveClass) {
        $('#'+options.controllerIdPrefix + prevCurr).removeClass(options.controllerActiveClass);
        $('#'+options.controllerIdPrefix + curr).addClass(options.controllerActiveClass);
      }

      if (pause == 1) {
        // pause the show
        // display correct image
        clearTimeout(timer);
      }
      else {
        // continue slideshow
        if (curr >= fgImages.length - 1) {
          curr = 0;
        }
        else {
          curr++;
        }

        if (prevCurr >= fgImages.length - 1 || (prevCurr + 1) == curr) {
          prevCurr = 0;
        }
        else {
          prevCurr++;
        }

        timer = setTimeout(function (){
          initSlider(fgContainer, fgImages)
          } , options.duration );
      }

    /* end image load */
    }).attr({
      'src': options.imgPath + fgImages[curr].imgName,
      'alt': fgImages[curr].imgAlt
      });

  }

  // setup and start slideshow
  $(this).each(function(){
    var j = new Image();
    
    // load initial foreground, background, and start slideshow
    //
    $(j).css({
      width:fgImages[curr].imgWidth,
      height:fgImages[curr].imgHeight,
      position:fgImages[0].imgPosition,
      top:fgImages[0].imgTop,
      left:fgImages[0].imgLeft,
      right:fgImages[0].imgRight,
      bottom:fgImages[0].imgBottom
      }).load(function(){
      // start slideshow
      initSlider(fgContainer, fgImages);
    }).attr({
      'src': options.imgPath + fgImages[curr].imgName,
      'alt': fgImages[curr].imgAlt
      });
  });
  
  // setup controllers
  if (options.controllerClass != '' && options.controllerIdPrefix != ''){
    // fill the controller box with thumbnails
    if (options.controllerContainer != '' && options.autoControllers) {
      $('#' + options.controllerContainer).empty();
      if (options.controllerStyle == 'thumb') {
        jQuery.each(fgImages, function(index, imgObj){
          var thumb_prefix = imgObj.imgName.substring(0, imgObj.imgName.lastIndexOf("."));
          var thumb_ext = imgObj.imgName.substring(imgObj.imgName.lastIndexOf(".") + 1);
          $('#' + options.controllerContainer).append('<img id="'+ options.controllerIdPrefix + index +'" class="'+ options.controllerClass +'" src="'+ options.imgPath + thumb_prefix + options.controllerThumbSuffix +'.'+ thumb_ext +'"/>');
        });
      }
      else if (options.controllerStyle == 'number') {
        jQuery.each(fgImages, function(index){
          if (index != 0 && options.controllerSpacer && options.controllerSpacerClass){
            // add the spacer
            $('#' + options.controllerContainer).append('<span class="'+ options.controllerSpacerClass +'">'+ options.controllerSpacer +'</span>');
          }
          $('#' + options.controllerContainer).append('<span id="'+ options.controllerIdPrefix + index +'" class="'+ options.controllerClass +'">'+ (index+1) +'</span>');
        });
      }
      else if (options.controllerStyle == 'empty') {
        jQuery.each(fgImages, function(index){
          if (index != 0 && options.controllerSpacer && options.controllerSpacerClass){
            // add the spacer
            $('#' + options.controllerContainer).append('<span class="'+ options.controllerSpacerClass +'">'+ options.controllerSpacer +'</span>');
          }
          $('#' + options.controllerContainer).append('<span id="'+ options.controllerIdPrefix + index +'" class="'+ options.controllerClass +'"></span>');
        });
      }
    }


    $('.' + options.controllerClass).click(function(e){
      e.preventDefault();
      
      clearTimeout(timer);
      
      var tempCurr = $(this).attr('id').replace(options.controllerIdPrefix, '');

      if (tempCurr == 'pause') {
        $(this).attr('id', options.controllerIdPrefix + 'play');
        pause = 1;
        if (curr == 0) {
          curr = fgImages.length - 1;
        }
        else {
          curr = curr - 1;
        }
      }
      else if (tempCurr == 'play') {
        $(this).attr('id', options.controllerIdPrefix + 'pause');
        pause = 0;
        // continue slideshow
        prevCurr = curr;

        if (curr >= fgImages.length - 1) {
          curr = 0;
        }
        else {
          curr++;
        }

        initSlider(fgContainer, fgImages);
      }
      else {
        if (pause == 0) {
          if (curr > 0) {
            prevCurr = curr - 1;
          }
          else {
            prevCurr = fgImages.length - 1;
          }
        }
        else {
          prevCurr = curr;
        }

        $('#'+options.controllerIdPrefix + 'pause').attr('id', options.controllerIdPrefix + 'play');

        if ((tempCurr != curr && pause == 1) || (pause == 0)) {
          pause = 1;
          curr = tempCurr;
          $(fgContainer).find('img:first').animate({
            opacity: 0.0
          }, transitionDuration, function() {
            $(this).remove();
          });
          initSlider(fgContainer, fgImages);
        }
      }
    });

  }
}
