// set a variable to say if what type of page we are on
var pageType = "";
var nextPageType = "";
var minimumHeight = 103;
var maximumHeight = 244;
var portfolioItems = new Array();
var portfolioIndex = 0;
var defaultFormName = "";
var defaultFormPhone = "";
var currentPreviewItem = 0;
var previewItemWidth = 356;
var finishedLoading = true;

function showPage(xmlData){
	$("#content .inner").show({queue:"pagetrans",complete:function(){
		if (nextPageType == "portfolio"){
			$("#content .inner").addClass("portfolio");
		} else {
			$("#content .inner").removeClass("portfolio");
		}

		$("#content .inner").html('<div style="display:none">' + $("pagecontent",xmlData).text() + '</div>');

		var newHeight = 0;
		if (nextPageType == "home") {
			newHeight = ((minimumHeight >= $("#content .inner > div").innerHeight()) ? minimumHeight : $("#content .inner > div").innerHeight());
		} else {
			newHeight = ((maximumHeight >= $("#content .inner > div").innerHeight()) ? maximumHeight : $("#content .inner > div").innerHeight());
		}
		newHeight += "px";
		if(newHeight != $("#content .inner").css("height")){
			$("#content .inner").animate({height:newHeight,minHeight:newHeight},{duration:700,easing:"swing",queue:"pagetrans"});
		}

		switch(pageType){
			case "home":
				switch(nextPageType){
					case "general":
						$("#footer a.portfolio-preview-next, #footer a.portfolio-preview-prev").fadeOut({duration:300});
						break;
					case "portfolio":
						$("#footer a.portfolio-preview-next, #footer a.portfolio-preview-prev").hide();
						$("#footer a.portfolio-next, #footer a.portfolio-prev").show();
						break;
				}
				break;
			case "general":
				switch(nextPageType){
					case "home":
						$("#footer a.portfolio-preview-next, #footer a.portfolio-preview-prev").fadeIn({duration:300});
						break;
					case "portfolio":
						$("#footer a.portfolio-next, #footer a.portfolio-prev").fadeIn({duration:300});
						break;
				}
				break;
			case "portfolio":
				switch(nextPageType){
					case "home":
						$("#footer a.portfolio-next, #footer a.portfolio-prev").hide();
						$("#footer a.portfolio-preview-next, #footer a.portfolio-preview-prev").show();
						break;
					case "general":
						$("#footer a.portfolio-next, #footer a.portfolio-prev").fadeOut({duration:300});
						break;
				}
				break;
		}

		// Set external links to open in new window/tab
		$("a[rel='external']").attr("target","_blank");

		$("#content .inner > *").fadeIn({duration:500,queue:"pagetrans"});
		// new image object 
		var img = new Image(); 
		// image onload 
		$(img).load(function () { 
			// hide first 
			$(this).css('display','none'); // since .hide() failed in safari 
			$("img#loader").remove();
			$("img#page-image").attr("src",$(this).attr("src")).fadeIn({duration:500,queue:"pagetrans"});
		}).attr('src', $("pageimage",xmlData).text()); 

		pageType = nextPageType;
		nextPageType = "";
		finishedLoading = true;
	}});
}

Array.prototype.has=function(v){
	for (i=0; i<this.length; i++){
		if (this[i]==v) return i;
	}
	return -1;
}

$(document).ready(function(){
	// Handles clearing the form fields upon entry
	defaultFormName = $("input#txtName").val();
	defaultFormPhone = $("input#txtPhone").val();
	$("input#txtName").focus(function(){
		if ($(this).val() == defaultFormName){
			$(this).val("");
		}
	});
	$("input#txtPhone").focus(function(){
		if ($(this).val() == defaultFormPhone){
			$(this).val("");
		}
	});
	$("input#txtName").blur(function(){
		if ($(this).val() == ""){
			$(this).val(defaultFormName);
		}
	});
	$("input#txtPhone").blur(function(){
		if ($(this).val() == ""){
			$(this).val(defaultFormPhone);
		}
	});

	// Add Navigation for portfolio and portfolio preview
	$("#portfolio-preview").after('<a href="" class="portfolio-prev" style="display:none">&lt; previous</a><a href="" class="portfolio-next" style="display:none">next &gt;</a>');
	$("#portfolio-preview").after('<a href="#" class="portfolio-preview-prev" style="display:none">&lt; previous</a><a href="#" class="portfolio-preview-next" style="display:none">next &gt;</a>');

	// Set the current page type
	switch($("body").attr("id")) {
		case "home-page":
			pageType = "home";
			$("#footer a.portfolio-preview-next").show();
			break;
		case "general-page":
			pageType = "general";
			break;
		case "portfolio-page":
			pageType = "portfolio";
			$("#footer a.portfolio-next, #footer a.portfolio-prev").show();
			break;
	}

	// Gets all Navigation links except portfolio links and home link
	$("#nav-bar a").filter(function(){
			return !$(this).parents("li.portfolio-links").length && !$(this).hasClass("home-link");
		})
		.click(function(){
			if (finishedLoading) {
				nextPageType = "general";
			}
		});

	// Gets all Navigation portfolio links
	$("#nav-bar a").filter(function(){
			return $(this).parents("li.portfolio-links").length && $(this).attr("href") != "#";
		})
		.each(function(){
			// Gets list of unique portfolio links in the nav for when we use
			// prev and next to go through portfolio pages
			if (portfolioItems.toString().search($(this).attr("href")) == -1) {
				portfolioItems.push($(this).attr("href"));
			}
		})
		.add("#footer a.portfolio-next, #footer a.portfolio-prev, p.view-link a")
		.click(function(){
			if (finishedLoading) {
				nextPageType = "portfolio";
			}
		});

	// Gets all home links
	$("a.home-link").click(function(){
			if (finishedLoading) {
				nextPageType = "home";
			}
		});

	// Overides clicking of links
	// Replaces with Ajax loading of the pages
	$("a").filter(function(){
			return $(this).attr("href") != "#" &&
				$(this).attr("href").search("#") == -1 &&
				$(this).attr("href").search("mailto:") == -1  &&
				$(this).attr("rel") != "external";
		})
		.click(function(){
			if (finishedLoading) {
				finishedLoading = false;
				$("#body").append('<img id="loader" src="' + siteRoot + 'images/ajax-loader.gif" alt="loading..." style="display:none;" />');
				$.ajax({
					type: "POST",
					url: $(this).attr("href"),
					data: "useAjax=yes",
					dataType: "xml",
					beforeSend: function(){
						$("#content .inner > *, img#page-image").fadeOut({duration:500,queue:"pagetrans",complete:function(){
							$("img#loader").show();
						}});
					},
					success: function(data,textStatus){
						showPage(data);
					},
					error: function(data,textStatus){
						finishedLoading = true;
						$("img#loader").remove();
//						alert("error " + textStatus);
					}
				});

				if (nextPageType == "portfolio"){
					var i = portfolioItems.has($(this).attr("href"));
					if (i != -1){
						if(i < (portfolioItems.length - 1)){
							$("#footer a.portfolio-next").attr("href",portfolioItems[i + 1]);
							$("#footer a.portfolio-next").show();
						} else {
							$("#footer a.portfolio-next").hide();
						}
						if(i > 0){
							$("#footer a.portfolio-prev").attr("href",portfolioItems[i - 1]);
							$("#footer a.portfolio-prev").show();
						} else {
							$("#footer a.portfolio-prev").hide();
						}
					}
				}
			}
			return false;
		});

	// Handles the call request form
	$("#footer form input.submit").click(function(){
		var txtNameVal = $("#txtName").val();
		var txtPhoneVal = $("#txtPhone").val();

		$.ajax({
			type: "POST",
			url: $("#footer form").attr("action"),
			data: "txtName=" + txtNameVal + "&txtPhone=" + txtPhoneVal + "&useAjax=yes",
			dataType: "html",
			beforeSend: function(){
				if (!$("#form-response").length) {
					$("#footer").append("<div id=\"form-response\" style=\"display:none;\"><h2>please wait...</h2></div>");
				}
				$("#footer form").fadeOut({duration:200,queue:"formsubmit"});
				$("#form-response").fadeIn({duration:200,queue:"formsubmit"});
			},
			success: function(data,textStatus){
				$("#form-response").fadeOut({duration:200,queue:"formsubmit",complete:function(){
					$("#form-response").html(data);

					// Adds an event for the users clicking on the link to return to the form
					$("#form-response p.refresh a").click(function(){
						$("#form-response").fadeOut("fast",function(){
							$("#form-response").remove();
							$("#txtName").val(defaultFormName);
							$("#txtPhone").val(defaultFormPhone);
							$("#footer form").fadeIn({duration:200});
						});
						return false;
					});
				}});
				$("#form-response").fadeIn({duration:200,queue:"formsubmit"});
			},
			error: function(data,textStatus){
				$("#form-response").fadeOut({duration:200,queue:"formsubmit",complete:function(){
					$("#form-response").html("<h2>error | apologies</h2>");
				}});
				$("#form-response").fadeIn({duration:200,queue:"formsubmit"});
			}
		});
		return false;
	});

	// Handles clicking prev and next on the portfolio preview
	$("#footer a.portfolio-preview-next, #footer a.portfolio-preview-prev").click(function(){
		if ($(this).hasClass("portfolio-preview-next")){
			currentPreviewItem++;
		} else {
			currentPreviewItem--;
		}
		var leftVal = ((previewItemWidth * currentPreviewItem) * -1);
		if (currentPreviewItem == 0){
			$("#footer a.portfolio-preview-prev").hide();
		} else {
			$("#footer a.portfolio-preview-prev").show();
		}
		if (currentPreviewItem < ($("#portfolio-preview ul > li").length - 1)){
			$("#footer a.portfolio-preview-next").show();
		} else {
			$("#footer a.portfolio-preview-next").hide();
		}
		leftVal += "px";
		$("#portfolio-preview ul").animate({marginLeft:leftVal},700,"swing");
		return false;
	});


	// Sub-nav handling (because of silly old IE6)
	$("ul.main-nav > li").hover(
		function(){
			$(this).addClass("hover");
		},
		function(){
			$(this).removeClass("hover");
		}
	);

	// Collapses sub-nav links
	$("ul.sub-nav-items").hide();
	$("ul.sub-nav > li > a").addClass("collapsed");
	$("ul.sub-nav > li > a").click(function(){
		if ($(this).hasClass("collapsed")) {
			$("ul.sub-nav > li > a:not(.collapsed)")
				.each(function(){
					$(this).text($(this).text().substr(0,$(this).text().length - 1));
				})
				.toggleClass("collapsed")
				.next("ul.sub-nav-items").slideUp("normal");
			$(this).next("ul.sub-nav-items").slideDown("normal");
			$(this).text($(this).text() + ":");
		} else {
			$(this).next("ul.sub-nav-items").slideUp("normal");
			$(this).text($(this).text().substr(0,$(this).text().length - 1));
		}
		$(this).toggleClass("collapsed");
		return false;
	});

	// Set external links to open in new window/tab
	$("a[rel='external']").attr("target","_blank");
});
