// JavaScript Document
function hashLinks(_select) {
	$(_select).each(function() {
		$(this).attr("href", "#/" + $(this).attr("href").replace(/^http:\/\/\w+\.wattsradiant\.com\/solutions\/applications\/casestudies\/?|^#\//,"") ).address();
	});
}

function handleCaseChange(_id, _dur) {
	var dur = (_dur) ? _dur : 600;
	$("#menu").find(".active-true").removeClass("active-true").addClass("active-false");
	$("#menu").find("a[id=" + _id + "]").closest("li").removeClass("active-false").addClass("active-true");
	$("#case .content").fadeOut(dur/2, function() {
		$(this).load( ("/solutions/applications/casestudies/casestudy/" + _id), {}, function() {
			$("#case .content .case-gallery-scrollable").each(function() {
				$(this).scrollable({
					size: "1",
					disabledClass: "disabled",
					items: ".case-gallery-items",
					next: ".case-gallery-next",
					prev: ".case-gallery-prev"
				}).find("a").overlay({
					target: ".overlay",
					expose: "#000",
					absolute: true,
					close: ".overlay-close",
					template: ""
				}).gallery({
					prev: ".overlay-prev",
					next: ".overlay-next",
					disabledClass: "disabled",
					opacity: "0.8",
					info: ".overlay-info",
					template: "<span>${index} of ${total}</span>"
				});
			});
			$(this).fadeIn(dur);
		});
	});
}

function makeHashParams() {
	var locHash = window.location.hash.replace(/^#\/?/,"");	
	return (locHash.length > 0) ? locHash.split("/") : null;
}

$(function() {

	// Determine hash value. We need to eliminate the deep pathing that is present in the url from the hash
	// incase the visitor book marked a page/link when visiting without JS enabled then foolwed that link with JS enabled.
	var locPath = window.location.pathname.replace(/\/$/, "").replace(/^\/solutions\/applications\/casestudies\/?/, "");
	var hashParams = makeHashParams();
	
	// Handle externel hash request
	$.address.externalChange(function(e){
		hashParams = makeHashParams();
		if(hashParams) {
			if(hashParams.length == 2) {
				handleCaseChange(hashParams[0],600,hashParams[1])
			} else {
				handleCaseChange(hashParams[0],600)
			}
		} else {
			$("#case .content").fadeOut(300, function(){ $(this).html(""); });
			$("#menu").find(".active-true").removeClass("active-true").addClass("active-false");
		}
	});
	/*
	$.address.internalChange(function(e){
		var hash = window.location.hash.replace(/^#\/?/,"").split("/");
		alert( hash.length );
		if(hash) {
			if(hash.length == 2) {
				handleDocumentChange(hash[1],2)
			} else {
				handleCaseChange(hash[0],2)
			}
		}
	});
	*/
	hashLinks(".case-menu a");
	
	// Make categories collapsable //
	// Setup Veil easing
	Veil.toOpen.easing = "easeInOutQuad";
	Veil.toClose.easing = "easeInOutQuad";
	// Make Step 1 AJAX links
	$("#menu a").click(function(e) {
		$this = $(this);
		handleCaseChange( $this.attr("id") );
		return false;
	});
	$(".case-menu li:eq(0) a").click();
});