// Init Gallery Functionaliy, client's "cool" feature.
function initGallery()
{
	//Bind Colorbox image preview for any "a" with rel="gallery"
	$("a[rel='gallery']").colorbox({
		transition: "elastic",
		opacity: 0.5,
	});

	var prev = $("a[id='prevImage']");
	var next = $("a[id='nextImage']");
	var showColor = false;

	$("a[rel='gallery'], #maingallery").bind("click.casper", function(e){
		if (this.id == "maingallery")
		{
			showColor = true;
			$("#galleryImage" + currentImage).trigger("click");
			return false;
		}
		else if(showColor)
		{
			showColor = false;
			return true;
		}
		else
		{
			var id = this.id;
			var url = this.href;
			var surl = url.replace("\/big\/", "\/small\/");
			$("#maingallery").attr("href", url);
			$("#maingallery").attr("title", this.title);
			$("#maingallery img").attr("src", surl);
			SetCI(parseInt(id.replace("galleryImage", "")));
			ShowHideArrow();
			return false;
		}
	});

	ShowHideArrow();
	CIAddClass();

	prev.bind("click.casper", function(){
		var temp = currentImage - 1;
		if (temp < 1 && currentPage == 1)
		{
			prev.parent().hide();
		}
		else if (temp < 1)
		{
			var tt = $("#galleryPage" + (currentPage - 1));
			tt.attr("href", tt.attr("href") + "&prev=true");
			tt.trigger("click");
		}
		else
		{
			$("#galleryImage" + temp).trigger("click");
			SetCI(temp);
		}
		return false;
	});

	next.bind("click.casper", function(){
		var temp = currentImage + 1;
		if (temp > totalImage && currentPage == totalPages)
		{
			next.parent().hide();
		}
		else if (temp > totalImage)
		{
			$("#galleryPage" + (currentPage + 1)).trigger("click");
		}
		else
		{
			$("#galleryImage" + temp).trigger("click");
			SetCI(temp);
		}
		return false;
	});

	function ShowHideArrow()
	{
		if (currentPage != 1 || currentImage != 1)
		{
			prev.parent().show();
		}
		else
		{
			prev.parent().hide();
		}

		if (totalPages != currentPage || currentImage != totalImage)
		{
			next.parent().show();
		}
		else
		{
			next.parent().hide();
		}
	}

	function CIAddClass()
	{
		$("#galleryImage" + currentImage + " > img").addClass("active");
	}

	function CIRemoveClass()
	{
		$("#galleryImage" + currentImage + " > img").removeClass("active");
	}

	function SetCI(newVal)
	{
		CIRemoveClass()
		currentImage = newVal;
		CIAddClass()
	}
}

$(function(){
	$("a[rel='gallery']").colorbox({
		transition: "elastic",
		opacity: 0.5,
	});
});

