$(function() {
  $('#gallery_controls').show();
  $("#controls").show();

  // gracefully degrade by having thumbnail hrefs go to gallery urls,
  // but if javascript is on, have them go straight to the image
  $("#thumbs ul li a").each(function(){
    $(this).attr("href", $(this).attr("title"));
  });
  $("#slideshow img").data("loaded", "true");

  // Initially set opacity on thumbs and add
  // additional styling for hover effect on thumbs
  var onMouseOutOpacity = 0.8;
  $('#thumbs ul.thumbs li').css('opacity', onMouseOutOpacity).hover(
    function () {
      $(this).not('.selected').fadeTo('fast', 1.0);
    },
    function () {
      $(this).not('.selected').fadeTo('fast', onMouseOutOpacity);
    }
  );

  $("#thumbs li a").each(function(i) {
    if($(this).attr("title") == $("#slideshow a.advance-link img").attr("src")) {
      $("#slideshow a.advance-link").attr("href", "#"+(i+1));
      window.location.href = "#" + i;
    }
  });

  $('#gallery_controls').galleriffic('#thumbs', {
    delay:                  2000,
    numThumbs:              200,
    preloadAhead:           0,
    enableTopPager:         false,
    enableBottomPager:      false,
    imageContainerSel:      '#slideshow',
    controlsContainerSel:   '#controls',
    captionContainerSel:    '#caption',
    loadingContainerSel:    '#loading',
    renderSSControls:       false,
    renderNavControls:      false,
    playLinkText:           'Play Slideshow',
    pauseLinkText:          'Pause Slideshow',
    prevLinkText:           '&lsaquo;',
    nextLinkText:           '&rsaquo;',
    nextPageLinkText:       'Next &rsaquo;',
    prevPageLinkText:       '&lsaquo; Prev',
    enableHistory:          false,
    autoStart:              false,
    onChange:               function(prevIndex, nextIndex) {
      $('#thumbs ul.thumbs').children()
        .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
        .eq(nextIndex).fadeTo('fast', 1.0);
    },
    onTransitionOut:        function(callback) {
      if($("#slideshow img").data("loaded") == "true") {
        $("#slideshow img").data("loaded", "false"); // page load we set an image, galleriffic doesn't usually work that way.
      } else {
        $('#caption').fadeTo('fast', 0.0);
        $('#slideshow').fadeTo('fast', 0.0, callback);
      }
    },
    onTransitionIn:         function() {
      $("#current_prices").html("");
      $("#current_prices").append($("#thumbs ul li.selected form").clone());

      $('#slideshow').fadeTo('fast', 1.0);
      $('#caption').fadeTo('fast', 1.0);
    }
  });
});

