﻿google.setOnLoadCallback(function() {
    $(document).ready(function() {
        initGallery();
    });
});

var currentImage;

function initGallery() {
	//Add click events to the option images top open the overlay
	$(".gallery a").click(function() { loadGalleryImage(this); }).attr("href", "#");
	$(".galleryLink a").click(function() { loadGalleryImage(this); }).attr("href", "#");
	$("a.galleryOverlayLink").click(function() { loadGalleryImage(this); }).attr("href", "#");

	$(".galleryAll").hide();

	$(".galleryOne .button a").click(function() { $(".galleryAll").slideDown("slow"); $(".galleryOne").slideUp("slow"); });
	$(".galleryAll .button a").click(function() { $(".galleryAll").slideUp("slow"); $(".galleryOne").slideDown("slow"); });
}

function loadGalleryImage(what) {
	currentImage = what;
	var imageId = $(what).find("img").attr("class").split("id-")[1];
	if ($(what).hasClass("video")) {
		$("#overlay").load("/gallery/video/" + imageId, function() { showGalleryImage() });
	}
	else {
		$("#overlay").load("/gallery/image/" + imageId, function() { showGalleryImage() });
	}
}

function showGalleryImage() {
	$("#overlay .closeButton").click(function() { hideGalleryImage(); });

	if ($(".galleryInner a").length >= 2)
	{
		$("#overlay .back").click(function() { previousImage(); });
		$("#overlay .next").click(function() { nextImage(); });
	}
	else
	{
		$("#overlay .back").hide();
		$("#overlay .next").hide();
	}
	
	showOverlay();
}

function hideGalleryImage() {
	hideOverlay();
}

function previousImage() {
	if ($(currentImage).prev().length <= 0) {
		loadGalleryImage($(".galleryInner").find("a:last"));
	}
	else {
		loadGalleryImage($(currentImage).prev());
	}
}

function nextImage() {
	if ($(currentImage).next().length <= 0) {
		loadGalleryImage($(currentImage).parent().find("a:first"));
	}
	else {
		loadGalleryImage($(currentImage).next());
	}
}