/* attach behaviors */
$(document).bind("ready", function() {
	if (document.getElementById("popupContainer")) return;
	$("a.shortFormLink").attr("href", function(){return this.href.indexOf('?') >= 0 ? this.href + "&" + cd1_query_string :  this.href + "?" + cd1_query_string});
	$("#contact").bind("click", function() { headerMenuSpecialistToggle(); } );
	$("#contact").bind("mouseout", function() { headerMenuSpecialistMouseOut(); } );
	$("#contact").bind("mouseover", function() { headerMenuSpecialistMouseOver(); headerMenuSpecialistOn();} );
	$("#contact a").bind("click", function() { headerMenuSpecialistToggle(); return false; } );
	$("#contact_es").bind("click", function() { headerMenuSpecialistToggle(); } );
	$("#contact_es").bind("mouseout", function() { headerMenuSpecialistMouseOut(); } );
	$("#contact_es").bind("mouseover", function() { headerMenuSpecialistMouseOver(); headerMenuSpecialistOn();} );
	$("#contact_es a").bind("click", function() { headerMenuSpecialistToggle(); return false; } );
	$("#headerMenuSpecialist").bind("mouseover", function() { headerMenuSpecialistMouseOver(); } );
	$("#headerMenuSpecialist").bind("mouseout", function() { headerMenuSpecialistMouseOut(); } );
	$("#headerMenuSpecialist").bind("click", function() { headerMenuSpecialistClose(); } );

	$("#foot .menu .popup").bind("click", function() { return popup(this.href); });
	$("#reference .popup").bind("click", function() { return popup(this.href); });
	$(".sitemapnav .popup").bind("click", function() { return popup(this.href); });
	$(".TakeACloserLook").bind("click", function() {return popup(contextPath + "/en/clarity-commitment.html", 970, 552); });
	$(".VeaMasDeCerca").bind("click", function() {return popup(contextPath + "/es/clarity-commitment.html", 970, 552); });

	$("a.external").bind("click", externalLinkInterstitial);
	$("a.englishOnly").bind("click", englishOnlyLinkInterstitial);
	$("a.externalEnglishOnly").bind("click", externalEnglishOnlyLinkInterstitial);

	$("#noflashlink").bind("click", function() {toggleNoFlash(); return false; } );
	setNoFlashLink();
	//TN: when pages are localized, each page will have a custom locale switch link
	setupToggleLanguage();
	setupLeftNavigation();
	initVideoMultiplayer();
	$('.tfn_replace').html(cd1_afid_tfn);
	RateDataWidget.init();
	topNavHighlight();
	popupClarityCommitment();
	//display anchors if specified
	window.setTimeout(displayAnchors, 300);
	setupBookmarkLinks();
	setupPrintButton();

	// replaced with TabFocusManager
	//$("a").bind("click", function() { this.blur(); });
});
$(window).bind("load", function() {
	// set up image headings
	checkImages();
	// setupAnalytics
	CMMap.setupTags(window.location.pathname, document.title);
});
$(window).bind("load", alignSidebar); // if you don't want it, don't put #sidebar-align in the content!
$(window).bind("resize", recenter);
$(document).bind("ready", recenter);
if (document.body && document.body.attachEvent) {
	document.body.attachEvent(
		"onclick",
		function() {
			window.setTimeout(
				function() {
					if (m_oheaderMenuSpecialistTimer != null)
						headerMenuSpecialistClose();
				},
				1
			);
		}
	);
}

//////////////////////////////////////////////////////////////////////////////
//
// header begin
//
// (used by jcr/[website]/include/header/content)
//

var m_oheaderMenuSpecialistTimer = null;
var m_cheaderMenuSpecialistDivId = "headerMenuSpecialist";
var noflash = null;

function headerMenuSpecialistClose() {
	headerMenuSpecialistMouseOver();
	document.getElementById(m_cheaderMenuSpecialistDivId).style.display = "none";
	m_oheaderMenuSpecialistTimer = null;
}
function headerMenuSpecialistMouseOut() {
	if (m_oheaderMenuSpecialistTimer == null)
		m_oheaderMenuSpecialistTimer = window.setTimeout(headerMenuSpecialistClose, 500);
}
function headerMenuSpecialistMouseOver() {
	if (m_oheaderMenuSpecialistTimer != null) {
		window.clearTimeout(m_oheaderMenuSpecialistTimer);
		m_oheaderMenuSpecialistTimer = null;
	}
}
function headerMenuSpecialistToggle() {
	if (isDoubleClick("headerMenuSpecialistToggle", arguments)) return;
	headerMenuSpecialistMouseOver();
	document.getElementById(m_cheaderMenuSpecialistDivId).style.display = (document.getElementById(m_cheaderMenuSpecialistDivId).style.display != "none") ? "none" : "block";
}
function headerMenuSpecialistOn() {
	document.getElementById(m_cheaderMenuSpecialistDivId).style.display = "block";
}

/* footer functions */

function toggleNoFlash(){
	//set cookie
	if (noflash){
		noflash = null;
		$.cookies.del('noflash');
	} else {
		noflash = 'true';
		$.cookies.set('noflash', 'true');
	}
	//reload page?
	//window.location.reload( true );
	setNoFlashLink(noflash);
	return false;
}
function setNoFlashLink(noflashValue){
	noflash = noflashValue ? noflashValue : $.cookies.get('noflash');
	if (noflash){
		$("#noflashlink").html('Enable Flash');
	} else {
		$("#noflashlink").html('No Flash');
	}
}
/* Change the href of the footer link to es/en version of current page. */
function setupToggleLanguage() {
	var lang = getLang();
	var otherHref = window.location.pathname.replace("/" + lang + "/", (lang=="es"?"/en/":"/es/"));
	$('.localelink').attr("href", otherHref);
}
function expandProductNav(e){

	if ($(e.target).parents('.level2').length >0){
		//clicked on a navigable page
		return true;
	} else {
		//clicked on a nav-expansion

		//get the leafindexclass of the clicked category
		var classes = e.currentTarget.className.split(" ");
		//default leaf is display:none
		$('li.leaf').css("display", "none");
		//default open is no trail
		$('.trail').removeClass("trail");
		for (i=0;i<classes.length;i++){
			if (classes[i].indexOf("leafindex")==0){
				//classes[i] will be leafindex0 or leafindex1 or ...
				$('li.'+classes[i]).css("display", "block");
			}
		}
		//set the style on the clicked category
		$(e.currentTarget).addClass("trail");
		return false;
	}
}
//////////////////////////////////////////////////////////////////////////////
//
// library functions begin
//
function isDoubleClick(p_cfnName, p_aargs) {
	/*
	 * example:
	 *
	 * function xxx(p_nclicked, p_cuuid) {
	 *		if (isDoubleClick("xxx", arguments)) return;
	 *		...
	 */

	var nnow = new Date().getTime();
	var i;
	if (window.adoubleClick)
		if ((nnow - window.adoubleClick[0] < 50) && (p_cfnName == window.adoubleClick[1]) && ((i = p_aargs.length) == window.adoubleClick[2].length))
			do
				if (--i < 0)
					return true;
			while (p_aargs[i] == window.adoubleClick[2][i]);
	window.adoubleClick = [nnow, p_cfnName, p_aargs];
	return false;
}

//
// library functions end
//
////////////////////////////////////////////////////////////////////////////
function alignSidebar() {
	var gy = $("#sidebar-align").offset().top;
	if (gy) {
		var gh = $("#right-sidebar").height();
		var fy = $("#foot").offset().top;
		$("#right-sidebar").css("top", (gy) + "px");
		$("#right-sidebar").css("visibility", "visible");
		if (gy + gh - fy > 0)
			$("#body").height(gy + gh - fy + 185);
	}
}
function initVideoMultiplayer() {
	var jq = $('#video-multiplayer ul');
	if (jq && jq.accordion) {
		jq.accordion({
			header: '.head',
			navigation: true,
			event: 'mouseover',
			fillSpace: true,
			animated: 'easeslide'
		});
	}
}
function setupProductNav(){
	$('#productnav').each(function() {
		//hide open (but not active) li
		$("li.open").bind("click", function(e) { return expandProductNav(e); } );
		$('li.leaf').css('display', 'none');
		var selectedClass = 'leafindex0';
		var classes = $('li.active').length>0 ? $('li.active')[0].className.split(" ") : [];
		for (i=0;i<classes.length;i++){
			if (classes[i].indexOf("leafindex")==0){
				selectedClass = classes[i];
			}
		}
		$('li.'+selectedClass).css("display", "block");
		$('li.'+selectedClass).addClass("trail");

	});
}
function externalLinkInterstitial() {
	popupOutside(contextPath + "/" + locale + "/interstitial/external.html?" + this.href, 688, 447);
	return false;
}
function englishOnlyLinkInterstitial() {
	popupOutside(contextPath + "/" + locale + "/interstitial/english-only.html?" + this.href, 688, 447);
	return false;
}
function externalEnglishOnlyLinkInterstitial() {
	popupOutside(contextPath + "/" + locale + "/interstitial/external-english-only.html?" + this.href, 688, 447);
	return false;
}
function getRateFieldValue(rateData, product, field){
	if (rateData == undefined || rateData[product] == undefined || rateData[product][field]==undefined){
		return 'N/A';
	} else {
		return rateData[product][field]+'%';
	}

}

var g_ncheckImages = 0;
function checkImagesWorker() {
	//Comparing against the width of the logo in the upper left.  If width of that logo changes then alter it here.
	var IMGNAME = "bofaLogo";
	var IMGWIDTH = 174;

	var SCREENREADERONLYHIDE = "screenReaderOnly";
	var SCREENREADERONLYSHOW = "screenReaderEtAl";

	function isObj(p) { if (typeof(p) == typeof(window)) if (p != null) return true; return false; }
	function isBool(p) { if (typeof(p) == typeof(true)) if (p != null) return true; return false; }
	function showSRText() { $("." + SCREENREADERONLYHIDE).removeClass(SCREENREADERONLYHIDE).addClass(SCREENREADERONLYSHOW); }
	function hideSRText() { $("." + SCREENREADERONLYSHOW).removeClass(SCREENREADERONLYSHOW).addClass(SCREENREADERONLYHIDE); }

	var img;
	var wind = window;

	if (g_ncheckImages == 0) g_ncheckImages = new Date().getTime();
	do {
		if (isObj(img = wind.document.getElementById(IMGNAME)))
			if (img.offsetWidth == IMGWIDTH) return hideSRText();
			else if (isBool(img.complete))
				if (img.complete) break;
				else ;
			else if (img.readyState)
				if (img.readyState == "complete") break;
		if (isObj(wind.parent))
			if (wind.parent != wind) continue;
		if ((g_ncheckImages > 0) && (new Date().getTime() - g_ncheckImages > 1000)) {
			showSRText();
			g_ncheckImages = -1;
		}
		window.setTimeout(checkImagesWorker, 250);
		return;
	} while(true);
	showSRText();
}

function checkImages() {
	$("#bofaLogo").each( function() {
		checkImagesWorker();
	});
}
/* display particular home page drawer based on anchor or query
 * example: #view-current-rates or ?drawer=view-current-rates
 */
function displayAnchors(){
	var uri = parseUri(location.href);
	if (uri.file == "home.html") {
		var drawer = uri.queryKey.drawer ? uri.queryKey.drawer : uri.anchor;
		switch (drawer.toLowerCase()){
			case 'buy-a-home':
			case '':
				accordionToggle1(0, "accordion1");
				accordionToggle2(0, "accordion2");
				break;
			case 'refinance-your-home':
				accordionToggle1(0, "accordion1");
				accordionToggle2(1, "accordion2");
				break;
			case 'use-the-equity-in-your-home':
				accordionToggle1(0, "accordion1");
				accordionToggle2(2, "accordion2");
				break;
			case 'view-current-rates':
				accordionToggle1(1, 'accordion1');
				break;
			case 'get-help-if-youre-having-trouble-making-your-home-loan-payments':
				accordionToggle1(2, 'accordion1');
				break;
			default: //nothing
				break;
		}
	}
}
function setupLeftNavigation() {
	setupProductNav();
	// kill category psuedo-page links
	$(".navigation ul.level1 li.open > a").bind("click", function() { return false; });
}



function recenter() {
	var opage = document.getElementById("page");
	var opageStyle = opage.style;
	var nwidth;
	var oheaderCheck = document.getElementById("nav1");

	if (("" + navigator.userAgent).indexOf("MSIE") > 0) return;
	if (typeof(oheaderCheck) == undefined) return;
	if (oheaderCheck == null) return;
	if (window.innerWidth) nwidth = window.innerWidth;
	else nwidth = document.body.clientWidth;

	opageStyle.left = Math.max(0, (nwidth - opage.offsetWidth - 24) >> 1) + "px";
	opageStyle.top = "0px";
	opageStyle.position = "absolute";
}

function setupBookmarkLinks() {
	$("a.jqbookmark").click(function(event){
		event.preventDefault(); // prevent the anchor tag from sending the user off to the link
		var url = this.href;
		var title = this.title;
		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else if(window.opera) { // Opera 7+
			return false; // do nothing - the rel="sidebar" should do the trick
		} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
			alert('Unfortunately, this browser does not support the requested action,'
					+ ' please bookmark this page manually.');
		}

		});
}


function topNavHighlight() {
	function highlight(p_cid, p_cphrase) {
		var cl = window.location + ".";
		var oa;
		if (cl.indexOf("/" + p_cphrase + ".") < 0)
		if (cl.indexOf("/" + p_cphrase + "/") < 0)
		if (cl.indexOf("/" + p_cphrase + "?") < 0)
		if (cl.indexOf("/" + p_cphrase + "#") < 0)
			return false;
		if (null == (oa = document.getElementById(p_cid)))
			return false;
		oa.className = "active";
		return true;
	} //end function

	highlight("nav1", "our-commitment");
	highlight("nav2", "home-loan-experience");
	highlight("nav3", "home-loan-options");
	highlight("nav4", "service-and-support");

	var oa;
	if (null != (oa = document.getElementById("nav4")))
		oa.title = oa.title.replace(/ and /gi, " & ");
} //end function

/* Popup Clarity Commitment if cc parameter in query */
function popupClarityCommitment() {
	var csearch = ("?" + window.location.search + "&").toLowerCase();
	if (csearch.indexOf("?cc=y&") >= 0 || csearch.indexOf("&cc=y&") >= 0) {
		var lang = getLang();
		popup(contextPath + (lang ? "/" + lang : "") + "/clarity-commitment.html", 970, 552);
	}
}

/* Return "en" or "es" based on window.location */
function getLang() {
	var parts = window.location.pathname.split("/");
	if (parts.length > 1 && parts[1] == "magnoliaAuthor")
		parts.shift();
	return lang = (parts.length > 1 && (parts[1] == "en" || parts[1] == "es"))
		? parts[1]
		: "";
}
function addPopupCloseButton() {
	if (getLang() == "es") {
		document.writeln('<a id="popupClose" title="cerrar esta ventana" href="javascript:void(window.parent.popupClose())"><img src="' + contextPath + '/docroot/images/popup_button_close.gif" border="0" width="32" height="32" alt="cerrar esta ventana" /></a>');
	} else {
		document.writeln('<a id="popupClose" title="close this window" href="javascript:void(window.parent.popupClose())"><img src="' + contextPath + '/docroot/images/popup_button_close.gif" border="0" width="32" height="32" alt="close this window" /></a>');
	}
}
function setupPrintButton() {
	if (getLang() == "es") {
		$("#printButton a").attr("title", "Imprimir artículo");
		$("#printButton span").html("Imprimir artículo");
	}
}
/* Takes the argument list and loads images relative to contextPath/docroot/images/ */
function preloadDocrootImages(pathList) {
	for (var i=0; i<arguments.length; i++)
		new Image().src = contextPath + "/docroot/images/" + arguments[i];
}

/* remove the focus rectangle on click (and enter key), but preserve for tab key */
TabFocusManager = new Object();
TabFocusManager.lastClickElement = undefined;
TabFocusManager.init = function() {
	$(document).ready(function() {
		$("a").each(function() {
			$(this).keydown(TabFocusManager.handleElementKeyDownEvent);
			$(this).click(TabFocusManager.handleElementClickEvent);
		});
		$(document).keydown(TabFocusManager.handleDocumentKeyDownEvent);
	});
};
TabFocusManager.handleElementKeyDownEvent = function(e) {
	if (e.keyCode == 13) {
		TabFocusManager.lastClickElement = $(this);
	}
};
TabFocusManager.handleElementClickEvent = function(e) {
	TabFocusManager.lastClickElement = $(this);
	$(this).blur();
};
TabFocusManager.handleDocumentKeyDownEvent = function(e) {
	if (e.keyCode == 9) {
		if (TabFocusManager.lastClickElement != undefined) {
			TabFocusManager.lastClickElement.focus();
			TabFocusManager.lastClickElement = undefined;
		}
	}
};
TabFocusManager.init();

/* rate data widget */
RateDataWidget = new Object();
RateDataWidget.defaultState = "NC";
RateDataWidget.defaultPurpose = "PURCHASE";
RateDataWidget.selectedPurpose;
RateDataWidget.selectedState;
RateDataWidget.init = function() {
	// N.B. change() on IE is broken
	$("input[name='purpose']").click(function() {
		var purpose = $("input[name='purpose']:checked").val();
		RateDataWidget.displayRateData(RateDataWidget.selectedState, purpose);
	});
	$('#stateSelector').bind("change", function(evt){ RateDataWidget.displayRateData(this.value, RateDataWidget.selectedPurpose);});
	$('#stateSelector').bind("keyup", function(evt){ RateDataWidget.displayRateData(this.value, RateDataWidget.selectedPurpose);});

	//display default data
	$('#stateSelector').val(RateDataWidget.defaultState);
	$("input[name='purpose'][value='" + RateDataWidget.defaultPurpose + "']").attr("checked", "checked");
	RateDataWidget.displayRateData(RateDataWidget.defaultState, RateDataWidget.defaultPurpose);
};
RateDataWidget.displayRateData = function(stateSelection, purposeSelection){
	//rateData var defined in rates.jsp
	// N.B. checking for bare variable undefined fails in IE6
	if (window.statePurposeProductRateData) {
		var stateData = statePurposeProductRateData[stateSelection][purposeSelection];
		$('#rateTable .30YF .rate').html(getRateFieldValue(stateData, '30 Year Fixed', 'rate'));
		$('#rateTable .30YF .apy').html(getRateFieldValue(stateData, '30 Year Fixed', 'apy'));
		$('#rateTable .15YF .rate').html(getRateFieldValue(stateData, '15 Year Fixed', 'rate'));
		$('#rateTable .15YF .apy').html(getRateFieldValue(stateData, '15 Year Fixed', 'apy'));
		$('#rateTable .51ARM .rate').html(getRateFieldValue(stateData, '5/1 ARM', 'rate'));
		$('#rateTable .51ARM .apy').html(getRateFieldValue(stateData, '5/1 ARM', 'apy'));
		$('#rateTable .31ARM .rate').html(getRateFieldValue(stateData, '3/1 ARM', 'rate'));
		$('#rateTable .31ARM .apy').html(getRateFieldValue(stateData, '3/1 ARM', 'apy'));
		var lastModifiedLabel = (locale == "es") ? "al " : "Last updated: ";
		$('#ratesAsOf').html(lastModifiedLabel + rateDataLastModified);
	}
	RateDataWidget.selectedPurpose = purposeSelection;
	RateDataWidget.selectedState = stateSelection;
}
