﻿google.setOnLoadCallback(function() {
    $(document).ready(function() {
        initGallery();
    });
});

var currentImage;

function initGallery() {
	$(".galleryAll").hide();

	//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", "#");


	$(".galleryOne .button a").click(function() {
	    $.ajax({
	        type: "GET",
	        url: "/explore-our-trikes/GalleryAll",
	        success: function(theResponse) {
	        if ($(".galleryAll .gallery a img").length == 0) {
	            var $holder = theResponse;
	                $(".galleryAll .gallery").html($($holder).html());
	                $(".gallery a").click(function() { loadGalleryImage(this); }).attr("href", "#");
	            }
	            $(".galleryOne").slideUp("slow");
	            $(".galleryAll").slideDown("slow");	            
	        }
	    });
	});
	$(".galleryAll .button a").click(function () { $(".galleryAll").slideUp("slow"); $(".galleryOne").slideDown("slow"); });

	if (openGalleryImage) {
	    var imageToOpen = $(".id-" + getUrlVars()["value"]);
	    if ($(imageToOpen).length > 0) {
	        imageToOpen.parent('a').click();
	    }
	    else {
	        window.location = window.location.toString().split("#")[0] + "#";
        }
    }
}

function loadGalleryImage(what) {
    currentImage = what;
    var imageId = $(what).find("img").attr("class").split("id-")[1];
    if (window.location.toString().indexOf("overlay=") < 0) {
        window.location = window.location.toString().replace("#", "") + setHashTagParams("image", imageId);
    }
	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());
	}
}
