/*********************************************************************************************\
*       COPYRIGHT © 2011 ENVISION INFORMATION TECHNOLOGIES, LLC.    ALL RIGHTS RESERVED       *
*       DISTRIBUTION, UNAUTHORIZED USE AND MODIFICATION IS STRICTLY PROHIBITED                *
*       ENVISION IT, MADISON, WI    http://www.envisionitllc.com   info@envisionitllc.com     *
\*********************************************************************************************/

(function( $ ){

  // Initializes the gallery, should be called from the container element
  $.fn.gallery_initialize = function ( fade_time, delay_between_fades, auto_play ) {

    this.data('gallery_slideshow_fade_time', fade_time);
    this.data('gallery_slideshow_delay_between_fades', delay_between_fades);
    this.data('gallery_slideshow_current_index', 0);
    this.data('gallery_slideshow_auto_play', auto_play);
    this.data('gallery_slideshow_jump_to_thumbnail', false); // Allow slideshow transitions to center the thumbnail in the slider? Default no

    // If we have a slideshow, set up the slideshow
    if (this.find(".gallery_slideshow").length)
    {
      // Hide all slides but the first
      var slides = this.find(".gallery_slide");

      // Set up colorbox for all slides
      slides.colorbox({
        onOpen:function(){
          clearTimeout($(this).parents(".gallery_container").data('gallery_slideshow_delay_timer')); // Clear existing Auto Play timer
        },
        onClosed:function(){
          var gallery = $(this).parents(".gallery_container");
          if (gallery.data('gallery_slideshow_auto_play'))
            gallery.data('gallery_slideshow_delay_timer', setTimeout("$(\"#" + gallery.attr('id') + "\").gallery_transitionToSlide()", gallery.data('gallery_slideshow_delay_between_fades')));
        }
      });

      slides.slice(0,1).css('opacity', 1.0); // Fix for IE 6 which doesn't recognize first child

      slides.slice(1).hide(); // hide all other slides

      // Centers first slide
      var first_slide = slides.first();
      var image = first_slide.find("img");
      image.css({'margin-top' : ((first_slide.height() - image.height()) / 2) + 'px', 'margin-left': ((first_slide.width() - image.width()) / 2) + 'px'});

      // Centers images as they load
      // Added this incase an image isn't loaded when it is being show and the show centers a blank image, or 0x0 image.
      slides.find("img").load(function() {
        var image = $(this);
        var slide = image.parent();
        image.css({'margin-top' : ((slide.height() - image.height()) / 2) + 'px', 'margin-left': ((slide.width() - image.width()) / 2) + 'px'});
      });

      // Preload next 2 images
      slides.slice(1,3).each(function(index) {
        $(this).find("img").attr('src', $(this).attr('href').replace('_full.jpg', '_slideshow.jpg'));
      });
    }

    // If we have slideshow controls do the logic to set up the controls
    if (this.find(".gallery_slideshow_controls").length)
    {
      this.data('gallery_slideshow_jump_to_thumbnail', true); // Allow slideshow transitions to center the thumbnail in the slider

      // Set width of slider
      var slideshow_control_thumbnails = this.find(".gallery_slideshow_control_thumbnail");
      var slider_width = slideshow_control_thumbnails.slice(0,1).outerWidth(true) + ((slideshow_control_thumbnails.length - 1) * slideshow_control_thumbnails.slice(1,2).outerWidth(true));
      this.find(".gallery_slideshow_control_thumbnails_slider").width(slider_width);

      // IE6 fix, first-child not working, also for some reason the slider needs to be 10px bigger
      // This kills both issues by allowing the extra margin while setting the slider width, then taking it away
      slideshow_control_thumbnails.first().css('margin', 0);

      // Set up slide transition for clicking on slideshow thumbnails
      slideshow_control_thumbnails.click(function() {
        $(this).parents(".gallery_container").gallery_transitionToSlide($(this).index());
      });

      // Centers all thumbnail images in their containers
      slideshow_control_thumbnails.each(function(index) {
        var image = $(this).find("img");
        image.css({'margin-top' : (($(this).height() - image.height()) / 2) + 'px', 'margin-left': (($(this).width() - image.width()) / 2) + 'px'});
      });

      // Set up slideshow controls thumbnail slider previous and next buttons
      this.find(".gallery_slideshow_control_scroll_left").click(function() {
        var gallery = $(this).parents(".gallery_container");
        gallery.data('gallery_slideshow_jump_to_thumbnail', false); // Stop moving the slider on slideshow transitions
        var slider_container = gallery.find(".gallery_slideshow_control_thumbnails");
        var slider = slider_container.find(".gallery_slideshow_control_thumbnails_slider");
        var new_left = slider.position().left + slider_container.width();
        if (new_left > 0)
          new_left = 0;
        slider.stop().animate({left: new_left}, gallery.data('gallery_slideshow_fade_time'));
      });
      this.find(".gallery_slideshow_control_scroll_right").click(function() {
        var gallery = $(this).parents(".gallery_container");
        gallery.data('gallery_slideshow_jump_to_thumbnail', false); // Stop moving the slider on slideshow transitions
        var slider_container = gallery.find(".gallery_slideshow_control_thumbnails");
        var slider = slider_container.find(".gallery_slideshow_control_thumbnails_slider");
        var new_left = slider.position().left - slider_container.width();
        if (new_left < slider_container.width() - slider.width())
          new_left = slider_container.width() - slider.width();
        slider.stop().animate({left: new_left}, gallery.data('gallery_slideshow_fade_time'));
      });
    }

    // Centers all thumbnail grid images
    var grid_thumbnails = this.find(".gallery_thumbnail");
    grid_thumbnails.each(function(index) {
      var image = $(this).find("img");
      image.css({'margin-top' : (($(this).height() - image.height()) / 2) + 'px', 'margin-left': (($(this).width() - image.width()) / 2) + 'px'});
    });

    // Set up colorbox for all thumbnails grid images
    grid_thumbnails.colorbox({
      onComplete: function() { 
        var ob_$link = $(this).parent('.gallery_thumbnail_wrapper').find('.gallery_thumbnail_link a').clone();
        if (ob_$link.length)
          $('#cboxTitle').append(' - ').append(ob_$link);
      }
    });


    // Start autoplay if enabled
    if (this.data('gallery_slideshow_auto_play') === true)
      this.data('gallery_slideshow_delay_timer', setTimeout("$(\"#" + this.attr('id') + "\").gallery_transitionToSlide()", this.data('gallery_slideshow_delay_between_fades')));

    this.data('gallery_initialized', true);

    return this;

  };

  // Changes the slideshow to a different slide, should be called from the container element
  $.fn.gallery_transitionToSlide = function ( new_index ) {

    if (this.data('gallery_initialized') !== true)
    {
      window.console && console.error && console.error('Gallery Transition called for uninitialized gallery: ' + this.attr('id'));
      return this;
    }

    var slides = this.find(".gallery_slide");
    var thumbnails = this.find(".gallery_slideshow_control_thumbnail");

    if (new_index == undefined)
      new_index = this.data('gallery_slideshow_current_index') + 1;
    else
    {
      // This branch gets called when a specific image has been clicked in the slideshow thumbnails
      this.data('gallery_slideshow_auto_play', false);  // Stop Auto Play
      clearTimeout(this.data('gallery_slideshow_delay_timer')); // Clear existing Auto Play timer
      this.data('gallery_slideshow_jump_to_thumbnail', true); // Allow slideshow transitions to center the thumbnail in the slider
    }

    if (!(new_index < slides.length))
      new_index = 0;

    if (new_index == this.data('gallery_slideshow_current_index'))
      return this;

    // Load this, plus preload next 2 images
    slides.slice(new_index, new_index + 3).each(function(index) {
      $(this).find("img").attr('src', $(this).attr('href').replace('_full.jpg', '_slideshow.jpg'));
    });

    // Fade in this slide
    var this_slide = slides.slice(new_index, new_index + 1)
    this_slide.stop(true).fadeTo(this.data('gallery_slideshow_fade_time'), 1, function() {
      var parent = $(this).parents(".gallery_container");
      if (parent.data('gallery_slideshow_auto_play'))
        parent.data('gallery_slideshow_delay_timer', setTimeout("$(\"#" + parent.attr('id') + "\").gallery_transitionToSlide()", parent.data('gallery_slideshow_delay_between_fades')));
    })

    // Centers this slide slide
    var image = this_slide.find("img");
    image.css({'margin-top' : ((this_slide.height() - image.height()) / 2) + 'px', 'margin-left': ((this_slide.width() - image.width()) / 2) + 'px'});

    // Select thumbnail in the slider controls
    thumbnails.slice(new_index, new_index + 1).addClass('gallery_slideshow_control_thumbnail_selected');

    // Possibly center this thumbnail in the slider controls
    if (this.data('gallery_slideshow_jump_to_thumbnail'))
    {
      var slider_container = this.find(".gallery_slideshow_control_thumbnails");
      var slider = slider_container.find(".gallery_slideshow_control_thumbnails_slider");
      var current_thumbnail = thumbnails.slice(new_index, new_index + 1);
      var new_left = (slider_container.width() / 2) - current_thumbnail.position().left - Number(current_thumbnail.css('margin-left').replace('px','')) - (current_thumbnail.outerWidth(false) / 2);
      if (new_left < slider_container.width() - slider.width())
        new_left = slider_container.width() - slider.width();
      if (new_left > 0)
        new_left = 0;
      slider.stop().animate({left: new_left}, this.data('gallery_slideshow_fade_time'));
    }

    // Fade out the previous slide
    slides.slice(this.data('gallery_slideshow_current_index'), this.data('gallery_slideshow_current_index') + 1).stop(true).fadeTo(this.data('gallery_slideshow_fade_time'), 0, function() {
      $(this).hide();
    });

    // Unselect previous thumbnail in the slider controls
    thumbnails.slice(this.data('gallery_slideshow_current_index'), this.data('gallery_slideshow_current_index') + 1).removeClass('gallery_slideshow_control_thumbnail_selected');

    this.data('gallery_slideshow_current_index', new_index);

    return this;

  };

})( jQuery );
