var galleryPath;
var currIndex;
var numImages;

$(document).ready(function() {
	$(".holiday_callout").click(function() {
		if(document.getElementById("galleryContainer") === null) $(document.body).append('<div id="galleryContainer"></div>');
		galleryPath = $(this).attr("galleryPath");
		openGallery();
	});
});

function openGallery() {
	$("#galleryContainer").click(function() {
		closeGallery();
	});
	$.ajaxSetup( {
	   timeout: 10000,
		error: function(xhr, status, error){
			console.log("AJAX error");
		}
	 } );
	$("#galleryContainer").load(galleryPath, {}, function(){ init() });
}

function init() {
	numImages = $("#galleryImages").children().length;
	initButtons();
	$("#galleryContainer").fadeIn("slow");
	openImage(0);
}

function openImage(index) {
	if(index < 0) index = numImages - 1;
	else if(index >= numImages) index = 0;
	if(document.getElementById("galleryImage"+index) !== null || typeof(document.getElementById("galleryImage"+index)) != "undefined") {
		currIndex = index;
		if(typeof($("#galleryImage"+currIndex).attr("src")) == "undefined" || $("#galleryImage"+currIndex).attr("src") == "") {
			var newImg = new Image();
			newImg.onload = function() {
				$("#galleryImage"+currIndex).attr("src", this.src);
				animateInImage(currIndex);
			};
			newImg.src = $("#galleryImage"+index).attr("imagePath");
		} else {
			animateInImage(currIndex);
		}
		if($("#galleryImage"+index).attr("imageLink") !== null) $("#galleryImage"+currIndex).click(function(e){
			window.location = $("#galleryImage"+index).attr("imageLink");
			e.stopPropagation();
		});
	}
}

function initButtons() {
	$("#galleryBackArrow").click(function(e){
		animateOutImage(currIndex);
		openImage(currIndex-1);
		e.stopPropagation();
	});
	$("#galleryForwardArrow").click(function(e){
		animateOutImage(currIndex);
		openImage(currIndex+1);
		e.stopPropagation();
	});
}

function animateInImage(index) {
	var scrollXY = getScrollXY();
	var mt = 200 + scrollXY[1];
	$("#galleryImage"+currIndex).attr("style", "margin-top:"+mt+"px");
	if(document.getElementById("galleryImage"+index) !== null) {
		$("#galleryImageContainer"+index).attr("style","display:block;z-index:1,opacity:0");
		$("#galleryImageContainer"+index).fadeIn("slow");
		$("#galleryBackArrow").fadeIn("slow");
		$("#galleryForwardArrow").fadeIn("slow");
	}
}

function animateOutImage(index) {
	if(document.getElementById("galleryImage"+index) !== null) {
		$("#galleryImageContainer"+index).attr("style","display:block;z-index:1,opacity:0");
		$("#galleryImageContainer"+index).fadeOut("fast");
	}
}

function closeGallery() {
	$("#galleryContainer").fadeOut("slow",function() {	
		$(this).remove();
	});
}