// set AJAX to not cache
$.ajaxSetup ({  
      cache: false  
  })  
//  load() functions 
var galleryLoadUrl = "load.php"  
var galleryHandle = false

var galleryTimeout

function adjustImage(targetImg) {
  var originalHeight  = $(targetImg).height()
  var originalWidth   = $(targetImg).width()

  if (originalHeight !== 0 && originalWidth !== 0) {
    var slideshowHeight = $("#slideshow").height()
    var slideshowWidth  = $("#slideshow").width()

    // We only scale down, not up
    if (originalHeight > slideshowHeight || originalWidth + 180 > slideshowWidth) {
      var widthHeightRatio = originalWidth / originalHeight
      var scaledWidth = widthHeightRatio * slideshowHeight
      // Will scaling up overwhelm the width of the container? 
      if (scaledWidth > slideshowWidth) {
        var correctedWidth = slideshowWidth - 180
        $(targetImg).css("height", "auto").css("width", correctedWidth)
      } else {
        $(targetImg).css("height", "100%").css("width", "auto")
      }
      $(targetImg).css("max-height", originalHeight).css("max-width", originalWidth)
    } 
  }
}

function resizeSlideshow() {
  var bottomHeight = 190 // This is the pixel height needed for the bottom nav and copyright
  var fullWidth = $(window).width()
	var fullHeight = $(window).height()
	var containerTopMargin = parseInt(fullHeight * 0.02)
	
	var newHeight = fullHeight - bottomHeight - containerTopMargin
	if (newHeight > 800) {
	  newHeight = 800
	}
	$("#slideshow, #info").css("height", newHeight)
	
	var infoTextHeight = $("#info .info-wrapper").height()
	var infoPadding = (newHeight - infoTextHeight) / 2
	$("#info .info-wrapper").css("paddingTop", infoPadding)

  adjustImage($("#slideshow img").first())
}

function loadGallery(galleryName) {
  // Our thumbnails container
  var thumbsTarget = $("#thumbnails #thumbs")
  thumbsTarget.hide().html("")
  // Temp hide the controls
  $("#controls").hide()
  
  // loading for thumbnails
  var thumbsLoading = $("#thumbnails .loading")
  thumbsLoading.fadeIn(100)

  if ("" !== galleryName) {
    $.get(  
			galleryLoadUrl,  
			{album: galleryName },  
			function(responseText){ 
			  // Fill in the thumbnail HTML
			  thumbsTarget.html(responseText)  
			  // Fade out the loading and fade in the thumbs
				thumbsLoading.fadeOut(300, function() {
				  thumbsTarget.fadeIn(100)
				})
				
				// Fade out whatever is in the slideshow container
				$("#preview_image").fadeOut(100, function(){
				  $(this).remove()
				})
				
				if (galleryHandle) { galleryHandle.pause() }
				// Attach the gallerific actions now
        galleryHandle = $('#thumbs').galleriffic({
        					delay:                     2500,
        					numThumbs:                 20,
        					preloadAhead:              10,
        					enableTopPager:            false,
        					enableBottomPager:         false,
        					enableKeyboardNavigation:  false,
        					maxPagesToShow:            1,
        					imageContainerSel:         '#slideshow',
        					controlsContainerSel:      '#controls',
        					renderSSControls:          true,
        					renderNavControls:         true,
        					playLinkText:              'Play',
        					pauseLinkText:             'Pause',
        					prevLinkText:              '&lsaquo;',
        					nextLinkText:              '&rsaquo;',
        					enableHistory:             false,
        					autoStart:                 false,
        					syncTransitions:           true,
        					defaultTransitionDuration: 400, 
        					onTransitionIn:            function(slide, caption, isSync) {
                    var inImage = slide.find("img")
                    if (inImage.height() > 0) {
                      adjustImage(inImage)
                    } else {
                      galleryTimeout = setTimeout(function() {
                        adjustImage(inImage)
                      }, 75)
                    }
        					  var duration = this.getDefaultTransitionDuration(isSync);
        						slide.fadeTo(duration, 1.0);
        					}
        				})
        $("#controls").show()
			},  
			"html"  
		)
  }
  
  return true
}

function toggleLinkActive(ele) {
  // Remove other active classes
  $(ele).parents("ul").find("li a").removeClass("active")
  // Add this active class
  $(ele).addClass("active")  
}

$("#slideshow img").imagesLoaded(function(){
  adjustImage(this)
})

// TODO re-show image wrap on non section link click
/* Here we initialize everything on page load */
$(function() {
  $("#nameplate").fadeOut(100)
  
  $(window).resize(resizeSlideshow)
  resizeSlideshow()
  
  // Set up the subnav links
  $(document).delegate("*", "click", function(){
   $("#nameplate").fadeIn(100)
  }).delegate("a.subnav_link[class!='active']", "click", function(e) {
    // Don't follow the link href
    e.preventDefault()
    toggleLinkActive(this)
    
    // Hide other subnavs
    $(".nav.subnav").hide().find("li a").removeClass("active")
    // Show the targeted subnav & select the first gallery for that subnav
    var targetSubnav = $($(this).attr("href"))
    targetSubnav.fadeIn(100)
      .find("ul li:first-child a").addClass("active")
        .click()
        
  }).delegate("a.gallery_link[class!='active']", "click", function(e){
    // Don't follow the link href
    e.preventDefault() 
    toggleLinkActive(this)
    // Which gallery do we want? 
    var galleryName = $(this).attr("id")
    
    // Hide any other info section
    $(".section").hide()
    // Get rid of current slideshow contents
    $("#slideshow").html("")
    // Show the hidden sections
    $("#thumbnails, #slideshow").fadeIn(100)

    if ("portfolio" === galleryName) {
      $("#thumbnails").addClass("portfolio")
      $(".nav.subnav").hide().find("li a").removeClass("active")
    } else {
      $("#thumbnails").removeClass("portfolio")
    }

    // Load up the gallery & start galleriffic
    loadGallery(galleryName)
   
  }).delegate("a.section_link[class!='active']", "click", function(e){
    // Don't follow the link href
    e.preventDefault()
    toggleLinkActive(this)
    
    // Hide all subnavs
    $(".nav.subnav").hide().find("li a").removeClass("active")
    // Get rid of the thumbnails & such
    $("#thumbnails").hide("")

    var targetSection = $($(this).attr("href"))
    // Get rid of the image wrap
    $("#slideshow").fadeOut(200, function() {
      // Show the targeted section
      targetSection.fadeIn(100)
      resizeSlideshow()
    }).delegate("img.portfolio_gallery_link", "click", function(e){
      e.preventDefault()
      $("a.gallery_link#portfolio").click()
    })
    
  }).delegate("img.portfolio_gallery_link", "click", function(e){
    e.preventDefault()
    $("a.gallery_link#portfolio").click()
  })
  
})

