﻿// adds .naturalWidth() and .naturalHeight() methods to jQuery
// for retreaving a normalized naturalWidth and naturalHeight.
(function($){
  var
  props = ['Width', 'Height'],
  prop;
 
  while (prop = props.pop()) {
    (function (natural, prop) {
      $.fn[natural] = (natural in new Image()) ? 
      function () {
        return this[0][natural];
      } : 
      function () {
        var 
        node = this[0],
        img,
        value;
 
        if (node.tagName.toLowerCase() === 'img') {
          img = new Image();
          img.src = node.src,
          value = img[prop];
        }
        return value;
      };
    }('natural' + prop, prop.toLowerCase()));
  }
}(jQuery));

var url = window.location.pathname;

$(document).ready(function () {

	// Show loading icon
	$("#slides").addClass("loadingContent");
	
	// Hide all the slide images to avoid the flicker
	$("#slides li").css("visibility", "hidden");
	
	// Show the first image
	var firstImage = $("#slides img:first");
	var firstImageLoaded = function() {
		setTimeout(function() {
			storeImageSize(firstImage);
			//Hide loader icon
			$("#slides").removeClass("loadingContent");
			$("#moreInfoButton:not(.galleryLeft)").delay(1000).fadeIn();
			
			if (url.indexOf("photo-gallery") == -1) {
				$("#slides li").css({ visibility: "visible", opacity: 0});
				//$("#slides li").css("visibility", "").hide().first().addClass("active").delay(100).fadeIn(800, "easeInQuart");
				showSlide(0);
			} else {
				$("#slides li").hide().css({ visibility: "visible" }).fadeIn(800);
			}
			
			firstImageLoaded = null;
		}, 500);
	};
	if(firstImage[0].width > 0) firstImageLoaded();
	else firstImage[0].onload = firstImageLoaded;
	
	// center #moreInfoBox
	$(window).resize(function(){

		$('#moreInfoBox').css({
			position:'absolute',
			left: ($(window).width() - $('#moreInfoBox').outerWidth())/2,
			top: ($(window).height() - $('#moreInfoBox').outerHeight())/2
		});
		
		$('.galleryBox').css({
			position:'absolute',
			left: ($(window).width() - $('.galleryBox').outerWidth())/2
		});

	});
	
	// To initially run the function:
	$(window).resize();

	// hide sub navigation and more info box
	$('header nav ul ul, #moreInfoBox').hide();
	
	// show content box
	$('.showInfoBox, .reservationForm, .newsletterForm').show();


    // Expand the sub nav on main menu click
	var lastSelected = "";
    $("header nav > ul > li > a").click(function (e) {
        if ($(this).attr("href") === "#" && $(this).parent().attr("data-baseurl") != lastSelected) {
            e.preventDefault();
			var time = 600 + $("li", $(this).parent()).length * 80;
			$("header nav ul ul").slideUp(time, "easeOutQuart");
			$(this).next().stop().slideToggle(time, "easeOutQuart");
			lastSelected = $(this).parent().attr("data-baseurl");
		}
    });
	
	// Show the current sub nav on load and highlight section(
	$("nav > ul > li[data-baseurl='" + url.split('/')[1] + "'] ul")
		.show()
		.find("li a[href='" + url + "']")
		.parent()
		.show()
		.addClass("active");
	lastSelected = url.split('/')[1];

    // More info button
	$("#moreInfoButton").css( { right:0 } );
    $("#moreInfoButton:not(.galleryLeft):not(.galleryRight), .closeButton a").live("click", function () {
        $("#moreInfoBox").fadeToggle("fast");
        $("#moreInfoButton").toggleClass("open");
		$("#moreInfoButton").fadeToggle("fast");
        return false;
    });

	// Hide the more info box if you 'click off' - ie on the header/body
	$(document).click(function(event){
		if(event.target == $('header')[0] || event.target == $('body')[0])
		{
			//$("#moreInfoBox:not(.reservationForm):not(.showInfoBox), .galleryBox").fadeOut("fast");
			//$("#moreInfoButton").removeClass("open");
		}
	});
	
	// Gallery thumb clicks
	$(".slidesThumbWrap img").click(function(e) {
		e.preventDefault();
		
		if ($(this).attr("src") != $("#moreInfoButton img").attr("src")) {
			var path = $(this).attr("src").replace("/content/images/gallery_thumbs/", "/content/images/backgrounds/photo-gallery/").replace("thumb", "gallery");
			$("#slides img").fadeOut(800, function() {
				$("#slides").addClass("loadingContent");
				$(this).hide().attr("src", path).load(function() {
					$(this).hide().fadeIn(800, function() {
						$("#slides").removeClass("loadingContent");
					});
				});
			});
			
			//$("#moreInfoBox, .galleryBox").fadeToggle("fast");
			$("#moreInfoButton img").attr("src", $(this).attr("src"));
			//$("#moreInfoButton").fadeToggle("fast");
		}
	});
	
	var galleryCount = 2;
	
	$(".galleryRight").delay(1000).fadeIn();
	
	$(".galleryRight a").click(function(e){
		if (galleryCount < 20) {
			galleryCount++;
			galleryImage(galleryCount);
			
			if (galleryCount == 3) $(".galleryLeft").fadeToggle();
			if (galleryCount == 20) $(".galleryRight").fadeToggle();
		}
	});
	
	$(".galleryLeft a").click(function(e){
		if (galleryCount > 2 ) {
			galleryCount--;
			galleryImage(galleryCount);
			
			if (galleryCount == 2) $(".galleryLeft").fadeToggle();
		}
	});
});

function galleryImage(index) {
	if (index.toString().length == 1) index = "0" + index;
	var path = "/content/images/backgrounds/photo-gallery/gallery_" + index + ".jpg";
	
	$("#slides img").clearQueue().fadeOut(800, function() {
		$("#slides").addClass("loadingContent");
		$(this).attr("src", path).load(function() {
			loadGate = false;
			$(this).delay(1000).fadeIn(800, function() {
				$("#slides").removeClass("loadingContent");
			});
		});
	});
}

$(window).load(function () {
    setUp();
    $(window).resize(scaleSlides);
});

function setUp() {

    // Create the pagination control - if there are more than 1
    if ($("#slides li").length > 1) {
        
        var pager = $("<ul/>").attr("id", "pager");
        for (var i = 0; i < $("#slides li").length; i++) {
            var a = $("<a/>").attr("href", "#").text("Go to image " + (i + 1)).click(function () {
                if (!$(this).parent().hasClass("active")) {
                    showSlide($(this).parent().prevAll().length);
                }
                return false;
            });
            var li = $("<li />").append(a);
            if (i == 0) {
                li.addClass("active");
            }
            pager.append(li);
        }
        $("#slides").after(pager);
		
		//Position the pager
		$("#pager").css({marginLeft:-($("#pager").width()/2)});
    }
	
    // Store the original image sizes and hide the slide images that aren't the first
    $("#slides img:gt(0)").each(function() {
		storeImageSize($(this));
	});

    // Wait for images to load and store original image sizes
    $("#slides img:gt(0)").load(function() {
		storeImageSize($(this));
	});
}

function storeImageSize(img) {
	if ($(img)[0].width > 0 && $(img)[0].height > 0 && $(img).data("width") == undefined && $(img).data("height") == undefined) {
		$(img).show();
        //$(img).data("width", $(img)[0].width);
        //$(img).data("height", $(img)[0].height);
		$(img).data("width", $(img).naturalWidth());
		$(img).data("height", $(img).naturalHeight());
        scaleSlides();
    }
}

function scaleSlides() {

    $("#slides img").each(function () {
		if($(this).data("width") != undefined && $(this).data("height") != undefined) {
			var windowAspect = $(window).width() / $(window).height();
			//var imageAspect = $(this).data("width") / $(this).data("height");
			// Hard code image-aspect
			var imageAspect = 1280.0 / 800.0;

			if (imageAspect > windowAspect) {
				$(this).width($(window).height() * imageAspect);
				$(this).height($(window).height());
				$(this).css("margin-left", -($(this).width() - $(window).width()) / 2);
				$(this).css("margin-top", "auto");
			}
			else {
				$(this).height($(window).width() / imageAspect);
				$(this).width($(window).width());
				$(this).css("margin-top", -($(this).height() - $(window).height()) / 2);
				$(this).css("margin-left", "auto");
			}
		}
    });
}
var pagerObj = { pagerFrame: 0 }

function animatePager() {
	$(pagerObj).stop(false, false);
	pagerObj.pagerFrame = 0;
	$(pagerObj)
		.delay(1000)
		.animate({ pagerFrame: 23 },
			{ easing: "linear",
				duration: 4000,
				step: function(now, fx) {
					$("#pager li.active a").css("background-position", "0 " + -(Math.round(now) * 11) + "px");
				}, complete: function() {
					var active = $("#pager li.active");
					showSlide(active.is(":last-child") ? 0 : (active.index() + 1));
				}
			});
}

function showSlide(toIndex) {
	$("#pager li").removeClass("active").find("a").css("background-position", "0 0");
    $("#pager li:eq(" + toIndex + ")").addClass("active");
	var slides = $("#slides");
    $(".active", slides)
		.removeClass("active")
		.delay(50)
		.animate({ opacity: 0 }, { duration: 800, easing: "easeInOutQuint" });
    $("li", slides)
		.eq(toIndex)
		.stop(true, false)
		.addClass("active")
		.delay(50)
		.animate({ opacity: 1 }, { duration: 800, easing: "easeInOutQuint" });
	animatePager();
}
