$(document).ready(function() { //jQuery Setup
	
	// Check to see if user used browser's back or forward button
	var timer = setInterval("checkHash()",500);
	
	// === NAV SCRIPTS ===
	// ===================
	// Handle Hash value in URL
	var hash = window.location.hash.substr(1);
	// This next part is a little different because we're replacing the nav with a flash nav (orig worked in FF but not IE. stupid IE.)
	var sections = new Array("index","case","spec");
	$(sections).each(function(){
		if(hash==this){  
			var toLoad = hash+'.cfm #content';
			// Load content to Content Div and then Load function to handle Contact Us Form
			$('#content').hide();
			$('#content').load(toLoad,handleContactForm);
			$('#content').fadeIn();
			curPage = hash;
			navState();
			updatePageTitle(curPage);
		}
	});
	/*
	ORIGINAL CODE that the code above replaced
	var href = $('#nav ul li a').each(function(){
		var href = $(this).attr('href');  
		if(hash==href.substr(0,href.length-4)){  
			var toLoad = hash+'.cfm #content';
			// Load content to Content Div and then Load function to handle Contact Us Form
			$('#content').load(toLoad,handleContactForm);
					
			navState();
		}   
	});*/
	
	
	// Incase someone goes directly to something like case.cfm
	if(hash.length == 0){
		handleContactForm();
	}
	
	// Set the onclick action for the nav (when no flash is available)
	$("#nav ul li a").click(function(event){
		event.preventDefault();
		nav(this);
	})
	
	
	// Update Flash Nav State
	internalLinks();

	
	// === FORM SCRIPTS ===
	// ====================
	// NOTE: Don't need this because the validation script will trigger the sendForm()
	// Hijack submit of form if the user lands directly on a page with the form
	//$("#contactForm").submit(sendForm);
	
}); //End of jQuery Setup








// === NAV SCRIPTS ===
// ===================
// Nav Handling Script
function nav(t,f){
	// Is it Flash passing the link?
	if(f==undefined){
		// Get href from the link clicked
		var href = t.toString().substring(t.toString().lastIndexOf("/")+1);
	} else {
		// If the user clicked a link in Flash....
		href = t;
	}
	// Check to see if it's the homepage and if so change 'index' to 'home'
	if(href == "index.cfm") href = "home.cfm";
	var toLoad = href+' #content';  
	// Check which page is currently active and terminate script if user is calling this page, UNLESS it's handling the browser's back button [f!=2]
	if(f!=2 && href.substr(0,href.indexOf(".")) == window.location.hash.substr(1)){
		return;
	}
	// Hide current content and then loadContent
	$("#content").fadeOut("fast",loadContent);
	// Setup Hash Link for the browser URL
	window.location.hash = href.substr(0,href.length-4);
	// Load new content and fadeIn
	function loadContent() {  
		// Create and Show 'Loading...' status
		$("#loading").remove();
		$("#content").before('<div id="loading"></div>'); 
		// Show "Loading..."
		$("#loading").show();
		$('#content').load(toLoad,'#content',showNewContent());
	}
	function showNewContent() {
		$('#content').fadeIn('normal',hideLoader());  
	}
	function hideLoader(){
		// Fade out loading div and then Load function to handle Contact Us Form
		$("#loading").fadeOut("normal",function(){
			handleContactForm();
			// Update Flash Nav State
			internalLinks();
		}); 
	}
	curPage = href.substr(0,href.indexOf("."));
	navState();
	
	// If this was triggered by the BACK button... and Flash was loaded on the page
	if(f==2 && $("#touchAndNav").html().indexOf("ul")==-1){
		callExternalInterface(curPage)
	}
	
	// Update Page Title
	updatePageTitle(curPage)
	
	// Trigger Google Analytics code
	var pageTracker = _gat._getTracker("UA-3986833-1");
	pageTracker._initData();
	pageTracker._trackPageview("/touch/"+curPage+".cfm");
}


// Set Nav Active State
function navState(){
	var active = window.location.hash.substr(1);
	$("#nav ul li").removeClass("active");
	$("#nav ul li#nav_"+active).addClass("active");
}



// Handle any links that are internal to this site
function internalLinks(){
	$("a[href*='case'], a[href*='spec'], a[href*='index']").click(function(event){
		event.preventDefault();
		// Get new page name and send it to Flash
		var goto = this.href.substring(this.href.lastIndexOf("/")+1,this.href.lastIndexOf("."));
		if(goto == "index") goto = "home";
		// Update Flash Nav IF flash was loaded on the page
		if($("#touchAndNav").html().indexOf("<ul>")==-1){
			callExternalInterface(goto);
		}
		// Trigger the Nav handling script
		nav(this);
	})
}

// Update Flash Nav State
function callExternalInterface(w){
	thisMovie("touchAndNav").navState(w);
}
function thisMovie(movieName){
	if(navigator.appName.indexOf("Microsoft") != -1){
		return window[movieName]
	} else {
		return document[movieName]
	}
}

// For use when user click's browser's forward and back buttons
var curPage;
function checkHash(){
	var h = window.location.hash;
	if(h!=""){
		if(h.substring(1)!=curPage){
			var x = h.substring(1)+".cfm";
			nav(x,2);
		}
	} else {
		return;
	}
}


// Update Page Title of the browser
function updatePageTitle(curPage){
	if(curPage == "home") var title = ""
	if(curPage == "case") var title = "- Case Study"
	if(curPage == "spec") var title = "- Specs & Pricing"
	document.title="InSite Touch "+title;
}



	
// === CONTACT FORM SCRIPTS ===
// ============================

function handleContactForm(){
	if($("#contactForm").length!=0){
		// NOTE: Don't need this because the validation script will trigger the sendForm()
		// Hijack the submit of the form
		//$("#contactForm").submit(sendForm);
		
		// Clear form elements upon focus
		var formElements = $("input, textarea");
		$(formElements).focus(function(){
			var curVal = this.value;
			if(curVal == this.title){
				this.value = "";
			}
			this.style.color = "#fff";
			this.style.fontStyle = "normal";
		});
		// Reinstate form elements upon blur if user left blank
		$(formElements).blur(function(){
			var curVal = this.value;
			if(curVal == "" || curVal == this.title){
				this.value = this.title;
				this.style.color = "#999";
				this.style.fontStyle = "italic";
			}
		});
		// Replace Submit button with an image
		if($("#subButton")) {
			var newbutton = "<div id='subButtonDiv'><a href='#'><span>Submit</span></a></div>";
			$("#subButton").after(newbutton);
			$("#subButton").remove();
			// Make new button work
			$("#subButtonDiv").click(function(event){
				event.preventDefault();
				$("#contactForm").trigger("submit");
				$("#subButtonDiv").trigger("blur");
				return false;
			});
		}
		
		// Form Validation
		$("#contactForm").validate({
			//debug: true,
			errorElement: "span",
			ignoreTitle: true,
			highlight: function(element, errorClass) {
				$(element).css("border","1px solid #ffd400");
			},
			unhighlight: function(element, errorClass) {
				$(element).css("border","1px solid #1b1b1b");
			},
			messages: {
				name: "You forgot your name!"	
			},
			submitHandler: function() { sendForm(); }
		});
		
		jQuery.validator.addMethod("notDefaultValue", function(value, element) { 
			if(value.toLowerCase() == element.title.toLowerCase()){return false;}
			else return true;
			}, "Please enter the correct value");
	}
	
}
// Form Submit
function sendForm() {
	$.post('_contactFormProcess.cfm',$("#contactForm").serialize(),function(data,status){
		$("#result").html(data);
		data = $.trim(data)
		$("#results").html(data);
		if(result == "fail"){
			$("#fail").html($("#results").html())
			$("#fail").fadeIn("normal");
			
		} else {
			$("#contactForm").fadeOut("fast");
			$("#results").fadeIn("normal");
		}
	});
	return false;
}

// Grab URL for Flash
function getHash(){
	if(!window.location.hash){
		var url = window.location.href;
		var loc = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
		if(loc == "index") loc="home"
	} else {
		var loc = window.location.hash.substr(1);
	}
	return loc;
}
