var pageSlideSpeed = 1000;
var sectonSlideSpeed = 300;
var fadeSpeed = 300;
var menuSlideSpeed = 200;
var keyboardNavigationEnabled = false;

$(document).ready(function() {
  $(".gallery-link").hide(); // For IE6, we set these as display: block in CSS and hide them immediately.

  var template = '<div class="bg">' +
    '<div class="wrapper">' +
      '<table cellspacing="0" cellpadding="0">' + 
        '<tr><td>' +
          '<img src="{SRC}" class="full-screen" />' + 
        '</td></tr>' + 
      '</table>' + 
    '</div></div>';

  var allContentString = ".displays-content, #navigation, #location-and-hours";
  
  $(".hide-all-content").live('click', function() {
    $(this).blur();
    
    $(allContentString).fadeOut(fadeSpeed);
    $("#show-all-content").fadeIn(fadeSpeed);

    setTimeout(function() { $(document).bind('click', showContentAgain); }, 500); // setTimeout is for IE. Sigh.
    return false;
  })

  var showContentAgain = function() {
    $(this).blur();
    
    $(allContentString).each(function() {
      if (!$(this).is(':empty')) { 
        $(this).fadeIn(fadeSpeed);
      }
    });
    
    $("#show-all-content").fadeOut(fadeSpeed);
    
    $(document).unbind('click', showContentAgain);
    return false;    
  }
  $("#show-all-content").click(showContentAgain);

  $('li.navigation-item').hoverIntent(function() {
    $(this).find('ul').slideDown(menuSlideSpeed); 
  }, function() {
    $(this).find("ul").slideUp(menuSlideSpeed);
  });

  var setBodyClass = function(bodyClass) {
    $(document.body).removeClass().addClass(bodyClass);
  }
  var setTitle = function(title) {
    document.title = title;
  }
    
  var slideBackgroundImage = function(backgroundImage, direction, callback) {
    if (!backgroundImage) { hideLoadingBox(); callback.call(); return; }
    
    var activeImage = $("#background-images .active");
    if (activeImage.find('img').attr('src').split('?')[0] == backgroundImage.split('?')[0]) { hideLoadingBox(); callback.call(); return; }
    
    if (!direction) { direction = 'next' }

    animating = true;
        
    activeImage.after(template.replace('{SRC}', backgroundImage));
    var nextImage = $("#background-images .active").next('.bg');
    
    nextImage.find('img').load(function() {
      var leftPoint = "-" + activeImage.width() + "px"
      if (direction != 'next') {
        nextImage.addClass('bg-before');
        leftPoint = activeImage.width() + "px";
      }
      
      hideLoadingBox();
      
      if ($(document.body).hasClass('galleries')) {
        keyboardNavigationEnabled = true;

        $(".displays-content").hide(); // so that gallery images don't try to appear below it

        var imagePlaceHolder = new Image();
        imagePlaceHolder.src = nextImage.find('img').attr('src');

        var imageHeight = imagePlaceHolder.height; 
        var imageWidth = imagePlaceHolder.width;
        var ratio = imageWidth / imageHeight;
        var height = $(window).height() - 130;
        var width = height * ratio;

        nextImage.find('img').wrap('<span class="image-wrapper"></span>")')
        nextImage.find(".image-wrapper, .image-wrapper img").css({ 
          height: height + "px", 
          width: width + "px"
        });
      }

      var endPoint = ($.browser.safari) ? '0%' : '0';
      activeImage.css({position: 'absolute'}).animate({ 'left': leftPoint }, pageSlideSpeed);
      nextImage.animate({ 'left': endPoint }, pageSlideSpeed);

      setTimeout(function() { 
        $("#background-images .active").removeClass('active')
        nextImage.addClass('active');
        if (callback) { callback.call(); }

        animating = false;
      }, pageSlideSpeed);
      
    });
  }
  
  var showContent = function(content) {
    if ($.trim(content.html()) != '') { content.fadeIn(fadeSpeed); }
  }
  
  var loadContent = function(content, container) {
    if (content) { container.html(content); }
    else { container.empty(); }
  }
  
  var pageLoaded = function() {
    keyboardNavigationEnabled = false;
    showContent($("#content"));
    showContent($("#secondary-content"));
    $(".scroll-pane").each(function() {
      var scrollableElement = $(this);
      var parentElement = scrollableElement.parent();

      if (parseInt(parentElement.height()) >= parseInt(parentElement.css('max-height'))) {
        scrollableElement.css({ height: parentElement.height() + 'px' });
        scrollableElement.jScrollPane({ reinitialiseOnImageLoad: true });
      }
    })
  }
  
  var animating = false;
  var galleryImages = [];
  var currentImageIndex;
  
  var setupGallery = function(images) {
    if (!images) { 
      $("#location-and-hours").fadeIn(fadeSpeed);
      $(document).trigger("gallery:exited");
      return; 
    }

    galleryImages = images;
    currentImageIndex = 0;

    $("#location-and-hours").fadeOut(fadeSpeed);
    $(".galleries .displays-content a").hover(function() {
      $(this).find('span').fadeIn(fadeSpeed);
    }, function() {
      $(this).find('span').fadeOut(fadeSpeed);
    });
  }
  
  var showLoadingBox = function() {
    $("#loading-box").show();
  }
  var hideLoadingBox = function() {
    $("#loading-box").hide();
  }
  
  $(".galleries .displays-content a").live('click', function() {
    var selectedImageHref = $(this).attr('href');

    for(var ii = 0; ii < galleryImages.length; ii++) {
      if (galleryImages[ii].image == selectedImageHref) { currentImageIndex = ii; break; }
    }
    
    slideBackgroundImage(galleryImages[currentImageIndex].image, 'next', function() {
      $(".gallery-link").show();
      showCaption(galleryImages[currentImageIndex]);
    });
    
    $("#content").fadeOut(fadeSpeed);
    return false; // prevent propagating the click
  });  
  
  $(".next-gallery-item").live('click', function() {
    $(this).blur();
    if (animating) { return; }
    
    showLoadingBox();
    hideCaption();
    
    currentImageIndex++;
    if (currentImageIndex == galleryImages.length) { currentImageIndex = 0; }
    slideBackgroundImage(galleryImages[currentImageIndex].image, 'next', function() {
      showCaption(galleryImages[currentImageIndex]);
    });
    
    return false;
  });

  $(".previous-gallery-item").live('click', function() {
    $(this).blur();
    if (animating) { return; }
    
    showLoadingBox();
    hideCaption();
    
    currentImageIndex--;
    if (currentImageIndex < 0) { currentImageIndex = galleryImages.length - 1; }
    slideBackgroundImage(galleryImages[currentImageIndex].image, 'previous', function() {
      showCaption(galleryImages[currentImageIndex]);
    });

    return false;
  });
  
  $(".thumbnail-link").live('click', function() {
    $(".gallery-link").fadeOut();
    hideCaption(function() {
      slideBackgroundImage('/images/gallery-background.gif', 'next', function() { 
        $("#content").fadeIn(fadeSpeed);
      });
      
    });
    return false;
  });
  
  var showCaption = function(image) {
    newHtml = '<a href="#" class="close-caption">x</a>' + image.title;
    if (image.description) { newHtml += "<br/><span>" + image.description + "</span>"; }
    newHtml +=  '<br/><a href="' + image.url + '">Download</a> | <a class="thumbnail-link" href="">Thumbnails</a>'
    
    $(".active .image-wrapper").append('<div class="caption" id="gallery-caption"></div>');
    $("#gallery-caption").html(newHtml).fadeIn(fadeSpeed);
  }
  
  var hideCaption = function(callback) { 
    $("#gallery-caption").fadeOut(fadeSpeed, function() { 
      if (callback) { callback.call(); }
    }).remove();
  }
  $(".close-caption").live('click', hideCaption);
  
    
  $(".sub-navigation-link, .displays-content a[href^='/'], .displays-content a[href^=window.location.host], .no-submenu a, h1 a").live('click', function() {
    if ($(this).attr('target')) { return true; }
    if ($(this).hasClass('download')) { return true; }
    
    var clickedLink = $(this);
    clickedLink.blur();
    var url = clickedLink.attr('href') + ".js";
    
    $(".gallery-link").hide();
    $("li.navigation-item ul").fadeOut(fadeSpeed);
    $("#secondary-content").fadeOut(fadeSpeed);
    $(".galleries .active").fadeOut(fadeSpeed);
    if (url.match(/galleries/)) {
      $(".active").animate({ opacity: 0 });
      $(document).trigger("gallery:entered");
    }
    hideCaption();
    
    $("#content").fadeOut(function(fadeSpeed) {
      showLoadingBox();
      
      $.getJSON(url, function(data) {
        setTitle(data.page_title);
        setBodyClass(data.body_class);
        
        // $(".displays-content").show(); // because we may have hidden it for galleries
        
        loadContent(data.content, $("#content"));
        loadContent(data.secondary_content, $("#secondary-content"));
        
        slideBackgroundImage(data.background_image, 'next', function() {
          pageLoaded();
          setupGallery(data.gallery_images);
        });
        
      });
    });
    
    return false;
  });

  pageLoaded();
  
  if ($(document.body).hasClass('galleries')) {
    $(document).trigger("gallery:entered");
    $.getJSON(window.location.href + ".js", function(data) {
      setupGallery(data.gallery_images);
    })
  }
  
  var handleKeyboardNavigation = function(objEvent) {
    if (!keyboardNavigationEnabled) { return true; }
    
    if ( objEvent == null ) {
      keycode = event.keyCode;
      escapeKey = 27;
    } else {
      keycode = objEvent.keyCode;
      escapeKey = objEvent.DOM_VK_ESCAPE;
    }
    
    if (keycode == 37) { //previous
      $(".previous-gallery-item").click();
      return false; // prevents background of page from moving
    } else if (keycode == 39) { // next
      $(".next-gallery-item").click();
      return false; // prevents background of page from moving
    }
    
  }
  $(document).keydown(handleKeyboardNavigation);
  
});