// Global Vars
	var today;
	var sTime;
	var siteName = "";
	
// Top Nav
function topNavHover(e){
	if ($(this).hasClass("closed")&&e.type=="mouseenter"){
		setOffset(this, e.type);
		$(this).removeClass("closed");
		$(this).addClass("opened");
		
		if($(this).hasClass("prodResFly")){
			document.getElementById("prodResFlyShim").style.display="none";
		}else if($(this).hasClass("prodComFly")){
			document.getElementById("prodComFlyShim").style.display="none";
		}else if($(this).hasClass("aboutCareersFly")){
			//document.getElementById("aboutCareersFlyShim").style.display="none";
		}else if($(this).hasClass("aboutNewsFly")){
			//document.getElementById("aboutNewsFlyShim").style.display="none";
		}
	}else{
		$(this).addClass("closed");
		$(this).removeClass("opened");
		
		if($(this).hasClass("prodResFly")){
			document.getElementById("prodResFlyShim").style.display="block";
		}else if($(this).hasClass("prodComFly")){
			document.getElementById("prodComFlyShim").style.display="block";
		}else if($(this).hasClass("aboutCareersFly")){
			//document.getElementById("aboutCareersFlyShim").style.display="block";
		}else if($(this).hasClass("aboutNewsFly")){
			//document.getElementById("aboutNewsFlyShim").style.display="block";
		}
	}
}
function setOffset(topNavContainer, e){
	var t = topNavContainer;
	var tFly = t.getElementsByTagName("TABLE")[0];
	if(t.tagName!="LI"){
		tFly.style.left = t.offsetWidth-14+"px";
		// come back		
		//if(parseFloat($D.getX(tFly)+tFly.offsetWidth) > parseFloat($D.getViewportWidth()))
		//	tFly.style.left = parseFloat(-tFly.offsetWidth+14)+"px";
	}
}

// Star Rating Functions
function setStars(el){
	var elId = el.id;
	if(elId=="star5"){
		stars = $("#star1,#star2,#star3,#star4,#star5");
	}else if(elId=="star4"){
		stars = $("#star1,#star2,#star3,#star4");
	}else if(elId=="star3"){
		stars = $("#star1,#star2,#star3");
	}else if(elId=="star2"){
		stars = $("#star1,#star2");
	}else if(elId=="star1"){
		stars = $("#star1");
	}
}
function starHover(e){
	setStars(this);
	stars.toggleClass("over");
}
function checkPageRating(){
	var thisPage = document.location.pathname;
	if(readCookie("ratedPage-"+thisPage)){
		var savedRating = readCookie("ratedPage-"+thisPage);
		if(savedRating!=""){
			var el = document.getElementById(savedRating);
			setStars(el);
			stars.addClass("at");	
		}
	}
}
function setPageRating(e){
	var el = this;	
	var rating = el.id;
	
	allStars = $("#star1,#star2,#star3,#star4,#star5");
	$(allStars).removeClass("at");
	
	setStars(el);
	stars.addClass("at");	
	
	var ratedPage = document.location.pathname;
	createCookie("ratedPage-"+ratedPage,rating,10000);
	
	$("#ratingConfirm").show();
	//thisEl.innerHTML = oldMan+"<div id='ratingConfirm'>Thanks for the info!</div>";
	var t=setTimeout("$('#ratingConfirm').hide();",3000);
}
// End Star Rating Functions

// Left Nav functions
function leftNavClick(e){
	if ($(this).hasClass("closed")){
		$(this).addClass("opened");
		$(this).removeClass("closed");
	}else{
		$(this).addClass("closed");
		$(this).removeClass("opened");
	}
}

// Font Switcher functions
function fontSwitcher(size){
	if (size){
		$("#fontSm,#fontMed,#fontLrg").removeClass("at");
		$("#font"+size).addClass("at");
		
		$("link[id*='fontSizer']").attr("disabled",true);
		$("#fontSizer"+size).attr("disabled",false);
		
		createCookie("fontsize",size,10000);
	}
}
function fontSizeRead(){
	if(readCookie("fontsize")){
		var fontSize = readCookie("fontsize");
		fontSwitcher(fontSize);
	}else{
		$("link[id*='fontSizer']").attr("disabled",true);
	}
}

// Stock Ticker Functions
function getStockXML(){
	$.ajax({
		type: "GET",
		url: "/webservices/AjaxStreamingProxy/RegularProxy.ashx?u=" + escape("http://xml.corporate-ir.net/irxmlclient.asp?compid=233852&reqtype=quotes") + "&c=0",
		dataType: "xml",
		success: parseStockXml
	});
}
function  parseStockXml(xml){
	var stockChange = $(xml).find("Stock_Quote[Ticker*='FAF'] > Change").text();
	stockChange = (stockChange>=0)?"+"+stockChange:stockChange;
	
	if($(xml).find("Stock_Quote[Ticker*='FAF'] > Trade").text()!=""){
		$("#fafQuote").text("FAF: " + $(xml).find("Stock_Quote[Ticker*='FAF'] > Trade").text());
		$("#stockTicker").attr("title",stockChange + "  " + $(xml).find("Stock_Quote[Ticker*='FAF'] > Date").text() + " ET");
		
		if(stockChange >= 0)
			$('#stockTicker').css({'background':'url(/assets/images/ico-stock-up.png) right 18px no-repeat'});
		else
			$('#stockTicker').css({'background':'url(/assets/images/ico-stock-down.png) right 18px no-repeat'});
	}
}

function initStockTicker() { // Init Stock Ticker Controls 
	getStockXML();
	setInterval(getStockXML, 20000);
	$("#stockTicker").bind("click",function(){location.href="http://investors.firstam.com/phoenix.zhtml?c=233852&p=irol-stockQuote"});
}
// End Stock Ticker Functions

// Utility functions
function elementHover(e){
	$(this).toggleClass("over");
}
function elementExpand(e){
	if ($(this).hasClass("at"))
		$(this).removeClass("at");
	else
		$(this).addClass("at");
}
function toggleDisplay(elId,display){// Toggle Display of Page Elements
	var el=document.getElementById(elId).style;
	if(el.display!='none'&&display!='show'){
		el.display='none';
	}else{
		el.display='';
	}
}
function toggleClass(el,elClass){
	if(!$(el).hasClass(elClass)){
		$(el).addClass(elClass);
	}else{
		$(el).removeClass(elClass);
	}
}
		
function toggleClosedList(){
	var list = $(this).next();//$D.getNextSibling(this);
	if ($(list).hasClass("off")){
		$(this).addClass("opened");
		$(this).removeClass("closed");
		$(list).addClass("on");
		$(list).removeClass("off");
		this.id="at";
	}else if($(list).hasClass("on")){
		$(this).addClass("closed");
		$(this).removeClass("opened");
		$(list).addClass("off");
		$(list).removeClass("on");
		this.id="";
	}
}
function showHiddenListItems(){
	var hiddenLinks = $(this.parentNode + " .off")//D.getElementsByClassName("off","",this.parentNode);
	$(hiddenLinks).toggleClass("off");
	this.className = "off";
}
function listItemClick(e){
	var links = this.getElementsByTagName("A");
	if(links[0]){
		var aObj = links[0];
		if(whichElement(e).tagName!="A" && whichElement(e).parentNode.tagName!="A"){
			if(aObj.target=="_blank"){
				window.open(aObj.href);
			}else{
				document.location.href=aObj.href;
			}
		}
	}
}
function stopEvent(e){
	e.preventDefault();
	e.stopPropagation();
}
function openWin(url,name,attr){
	var w = window.open(url,name,attr);
	w.focus();
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// These four functions return document measurements when needed
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_scrollTop() {// Returns the user's Vertical scroll position
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_scrollLeft() {// Returns the user's horizontal scroll position
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


function checkPromosDates(){
	var promos = $("#rightCol div.promo");
	if (promos){
		var i=0;
		for (i=0;i<=promos.length-1;i++){
			var promo = promos[i];
			var promoStart = promo.getAttribute("startdate");
			var promoEnd = promo.getAttribute("enddate");		
		
			var startDate=new Date(promoStart);
			var endDate=new Date(promoEnd);			
			var today = new Date();
			if (startDate <= today && endDate >= today ){
				$(promo).removeClass("off");
			}
		}
	}
}

function whichElement(e){
	var targ;
	if (!e){
		var e=window.event;
	}if (e.target){
		targ=e.target;
	}else if (e.srcElement){
		targ=e.srcElement;
	}if (targ.nodeType==3){ // defeat Safari bug
		targ = targ.parentNode;
	}
	return targ;
}

// Toggle Modal Window
function initModals() {		
	var activeWin;
	var offsiteURL;
	
	//select all the a tag with name equal to modal
	$('a[name=modal],button[name=modal]').click(function(e) {
		
		e.preventDefault();//Cancel the link behavior
		e.stopPropagation();
		
		if($(this).hasClass("offsiteLink")){//For offsite links open modal window first before opening link
			if(this.href){
				offsiteURL = $(this).attr("offsiteurl");
			}else if(this.value=='Continue'){
				openWin(offsiteURL,'','');
				return true;
			}
		}
		
		var id = $(this).attr('href');//Get the A tag
		activeWin = $(id);
		
		if($(this).attr('id')=='feedbackLink'){
			$(id).find('#emailTo').val('FAWebMaster' + '@' + 'firstam.com');
			$('#contactFormName').val('feedback');
			$(id).find('h4').text('Feedback');
			$(id).find('#contactPrefEmail').removeAttr('checked');
		}else if($(this).attr('href')=='#modalContact'){
			$(id).find('#emailTo').val($(this).attr('id') + '@' + $(this).attr('domain'));
			$('#contactFormName').val('contact');
			$(id).find('h4').text($(this).text());
			$(id).find('#contactPrefEmail').attr('checked','checked');
		}
		
		var maskHeight = $(document).height();//Get the screen height and width
		var maskWidth = $(window).width();
		
		$('#mask').css({'width':maskWidth,'height':maskHeight});//Set heigth and width to mask to fill up the whole screen
		
		$('#mask').show();		
		
		var winH = $(window).height();//Get the window height and width
		var winW = $(window).width();
		var winTop = winH/2-$(id).height()/2 + f_scrollTop();
		var winLeft = winW/2-$(id).width()/2;
		
		activeWin.css({'top':winTop,'left':winLeft});//Set the popup window to center
		activeWin.toggleClass("show");
		
		activeWin.draggable();
		
		toggleSelect("hide");

	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		activeWin.toggleClass("show");
		
		toggleSelect("show");
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		activeWin.toggleClass("show");
		toggleSelect("show");
	});			
	
}
function closeWindow(modal){		
	$('#mask').hide();
	$(modal).toggleClass("show");
	$(modal).find('.confirm').addClass('off');
	$(modal).find('form').removeClass('off');
}

function gotoState(selectedState,stateCode){
	var mapArea = $("#Map area[name='"+selectedState+"']");
	var stateUrl = mapArea.attr("href");
		
	if(mapArea.attr("target")=="_blank"){
		window.open(stateUrl);
	}else if(mapArea.attr("href").indexOf(".")==-1){ // IF there is no URL go to office directory
		window.open('http://directory.firstam.com/directory/index.jsp?state=' + stateCode,'InteractiveDirectory','toolbar,resizable,scrollbars,width=1020,height=593').focus();
	}else{
		document.location.href=stateUrl;
	}
}
		
// Email Functions
function initEmailThisPage(){
	$("#emailPageForm").validate({
		errorPlacement: function(error, element) {
			error.insertBefore(element);
		},
		messages: {
			emailPageFromName: {
				required: 'Please enter your name.'
			},
			emailPageFrom:  'Please enter a valid email address.',
			emailPageTo:  'Please enter a valid email address.'
		},
		submitHandler: function(form) {
			var emailTo = $('#emailPageTo').val();
			var emailFromName = $('#emailPageFromName').val();
			var emailFrom = (document.location.host.indexOf('title')!=-1)?'do-not-reply.title@firstam.com':'do-not-reply@firstam.com';
			var emailSubject = emailFromName + " has sent you a message from the " + siteName + " website";
			
			var emailGreeting = '';
			if($("#emailPageToName").length!=0)
				emailGreeting = ($('#emailPageToName').val() != '')?'<p>Dear ' + $('#emailPageToName').val() + ',</p>':'';
			
			if($("#emailPageCC:checked").length!=0)
				emailTo = emailTo + ',' + $('#emailPageFrom').val();
				
			var emailMessage = ($('#emailPageMsg').val() != '')?'<p><b>The following message is from ' + emailFromName + ':</b><br>' + $('#emailPageMsg').val() + '</p>':'';
			var emailBody = '<style>p{font-family:Arial, Helvetica, sans-serif; color:black; font-size:11pt}</style>' + emailGreeting + '<p>' + emailFromName + ' thought you would be interested in viewing the following page on ' + siteName + '\'s  website.</p>' + '<p><a href="' + document.location.href + ' ">' + document.location.host + document.location.pathname + '</a></p>' + emailMessage + '<p style="color:silver">____________________________________</p><p><img src="http://www.firstam.com/assets/email/images/email-logo.gif" alt="First American" width="211" height="53" /></p><p style="color:gray; font-size:10pt">This is a one-time email from First American. You received this email because someone requested the link to be sent to you. No future email will be sent to you unless you or someone else make a request through First American\'s website.</p>' + ' ';
	
			email(emailTo, emailFrom, emailSubject, emailBody, $('#modalEmailPage'));
		}
	});	
}
function initContact(){
	$("#contactForm").validate({
		errorPlacement: function(error, element) {
			error.insertBefore(element);
		},
		messages: {
			contactName: {
				required: 'Please enter your name.'
			},
			contactEmail:  'Please enter a valid email address.'
		},
		submitHandler: function(form) {
			var emailFromName = $('#contactName').val();
			var emailSubject = siteName + " website message from " + emailFromName;
				if($('#formName').val()=='feedback')emailSubject = siteName + " website feedback from " + emailFromName;
			var emailBody = "<style>p{font-family:Arial, Helvetica, sans-serif; color:black; font-size:11pt}</style>"+
				"<p>" + emailFromName + " was viewing the following page on the " + siteName + " website: </p>" + 
				"<p><a href='" + document.location.href + "'>" + document.location.host + document.location.pathname + "</a></p>"+
				"<p><b>Message from " + emailFromName + ":</b><br>" + 
					$('#contactComments').val() + 
				"</p>"+
				"<p><b>Contact info:</b><br>" + 
					"Name: " + $('#contactName').val() +  "<br>" + 
					"Email: " + $('#contactEmail').val() +  "<br>" + 
					"Phone: " + $('#contactPhone').val() +  "<br>" + 
					"Contact Preference: " + $('#contactPref :checked').val() + 
				"</p>" + " ";

			email($('#modalContact').find('#emailTo').val(), 'do-not-reply.title@firstam.com', emailSubject, emailBody, $('#modalContact')); // this is for production
			//email($('#contactEmail').val(), $('#contactEmail').val(), emailSubject, emailBody, $('#modalContact')); // this one is for testing the contact gets their own email.
		}
	});	
}
function email(to, from, subject, body, modal, confmsg) {
	
	var htmlBody = encodeURIComponent(body);
  var mailSubject = encodeURIComponent(subject);
	
	$('#centerPage').css({'cursor':'wait'});
	$.ajax({
		type: "POST",
		url: "/webservices/FirstAMEmailService/EmailService.svc/Email",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: "{\"to\":" + "\"" + to + "\"" + ", \"from\":" + "\"" + from + "\"" + ", \"subject\":" + "\"" + mailSubject + "\"" + ", \"body\":" + "\"" + htmlBody + "\"" + "}",
		success: function(){confirmEmail(modal, confmsg)},
		error: jqueryError
	});
} 
function jqueryError(request, status, error) {
	if(request.responseText!=""){
		$('#modalEmailPage .error').removeClass('off');
		$('#modalEmailPage .error').html(request.responseText);
	}
} 
function confirmEmail(modal, confmsg) {
  if (modal != "") {
	$('#centerPage').css({'cursor':'auto'});
	$(modal).find('.confirm').removeClass('off');
	$(modal).find('.confirm').html('<label class="confirm">Your message was sent successfuly!</label>');
	$(modal).find('form').addClass('off');
	window.setTimeout(function(){closeWindow(modal)}, 2000);
  }
  else {
  $('#centerPage').css({'cursor':'auto'});
  $('#localStateForm').css({'display':'none'});
  $('div.confirmMsg').html(confmsg);
  $('div.confirmMsg').focus();
  }
}
// End Email this page Functions

	function getPrevViewed(){
		//short_description
		var cArray = new Array()
		var pageURL = "";
		var pageTitle = "";
		var pageDesc = "";
		var prevViewedHTML = "";
		
		// List Cookie Data on the Page
		var i=0;
		while (i<=4){
			if(readCookie("prevViewed"+i)){
				
				if (readCookie("prevViewed"+i).indexOf("::")!=-1)
					cArray = readCookie("prevViewed"+i).split("::");
				else
					cArray = readCookie("prevViewed"+i).split(",");
				
				pageURL = cArray[0];
				pageTitle = cArray[1];
				pageDesc = ''+cArray[2]+'';
				
				
				prevViewedHTML = '<a href="' + pageURL + '"><strong>' + pageTitle + '</strong> <br />' + pageDesc + '</a>';
				prevViewedDivider = '<div class="hr"><img src="/assets/images/spacer.gif" /></div>';
									
				$("#prevViewedWrapper").html($("#prevViewedWrapper").html() + prevViewedHTML);
				
				if(readCookie("prevViewed"+(i+1)))
					$("#prevViewedWrapper").html($("#prevViewedWrapper").html() + prevViewedDivider);
					
				$("#prevViewedBox").show();
			}
			i++;
		}
	}

// Dat / Time Webservice
	function getDateTime() {
        $.ajax({
            type: "GET",
            url: "/webservices/FirstAMDateTimeService/DateTimeService.svc/GetServerDateTime",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: updateDateTime,
            error: jqueryError
        });
    } 
    function updateDateTime(result) {
		today = new Date(result);
		sTime = today.getTime(); //returns seconds since 1970
    }
    function dateError(request, status, error) {
        //document.getElementById("divError").innerHTML = request.responseText;
    }

//Init Buttons / (disabled For IE6 or less)
function initButtons(){
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		if (ieversion>6){
			$(".btn").bind("mouseenter mouseleave", elementHover); 
		}
	}else{
		$(".btn").bind("mouseenter mouseleave", elementHover); 
	}
}
	
//Hide / Show the Select tags when Modal Window is enabled / disabled (For IE6 or less)
function toggleSelect(action){
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		if (ieversion<=6){
			var theRules = new Array();
			theRules = document.styleSheets[0].rules
			if (theRules[theRules.length-1].style.visibility == 'hidden' || action=="show"){
				theRules[theRules.length-1].style.visibility = 'visible';
			}else{
				theRules[theRules.length-1].style.visibility = 'hidden';
			}
			
			if (action=="hide"){
				theRules[theRules.length-1].style.visibility = 'hidden';
			}
		}
	}
}

function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

// Check Search Value and validate
function checkQ(q){
	if((q.value=="by keyword" || q.value=="") ){
		q.value="";
		q.focus();
		return false;
	}else{
		return true;
	}
}

function init() { // Init
	//alert($(this.parentNode + "> .off").className);
	$("#sysOrderCenter").bind("mouseenter mouseleave", function(){$("#sysOrderCenter .orderBoxOver").toggleClass("off");});
	var topNavContainers = $("#header .closed");//$D.getElementsByClassName("closed","","header");
	$(topNavContainers).bind("mouseenter mouseleave", topNavHover);
	$("#breadcrumb").bind("mouseenter mouseleave",  elementHover);
	$("#utilNav").bind("mouseenter mouseleave", elementHover);
			
	var allStars = $("#star1,#star2,#star3,#star4,#star5");
	allStars.bind("mouseenter mouseleave", starHover);
	allStars.bind("click", setPageRating);
	checkPageRating();
			
	checkPromosDates();
	
	initModals();
	initButtons();
	if($("#fontSizer").length!=0)
		fontSizeRead();
	if($("#sharePage").length!=0){
		fontSizeRead();
		$("#sharePage").bind("mouseenter", function(){$("#shareFly").show();toggleSelect("hide")});
		$("#shareFly").bind("mouseleave click", function(){
			$("#shareFly").hide();
			toggleSelect("show");
		});
	}
	if($("#emailPageForm").length!=0)
		initEmailThisPage();
	if($("#contactForm").length!=0)
		initContact();
	
	//$("a[target='_blank']").bind("click",function(){javascript: pageTracker._trackPageview(this.href);});
	$("a[target='_blank']").bind("click",function(){pageTracker._trackPageview(this.href);});
	
	MM_preloadImages('/assets/images/arrow-black.gif','/assets/images/ico-email-over.gif','/assets/images/ico-print-over.gif');
}
$(document).ready(init);