/*** TEMP --- REMOVE AFTER REQUESTED LEADS WEB ADD CLASS CHANGE AND DEPLOYMENT ***/
if(location.href.indexOf("leads-web") > 0 ) jQuery('body').attr('id','leads-web');
/*******************************************/
/********  Version: 3.2.2           ********/
/*******************************************/
//Target Safari or Chrome Only
var userAgent = navigator.userAgent.toLowerCase();
isChrome = false;
isSafari = false;

//Safari sniffer
if(userAgent.indexOf("webkit")!=-1 && userAgent.indexOf("chrome")==-1) {
	jQuery('h2').addClass('safari');
	isSafari = true;
}
//Chrome sniffer
if(userAgent.indexOf("chrome")!=-1) {
	jQuery('h2').addClass('chrome');
	isChrome = true;
}
//Change Weblogic links to include "https".  Otherwise in IE when the link reroutes to its https counterpart the #tab-... is stripped and the user is navigated to the default tab.
jQuery('#wrapper a').each(function(i) {
    var attr = $(this).attr('href');
	if (typeof attr !== 'undefined' && attr !== false) {
		if($(this).attr('href').indexOf("hhstart.htm#") > 0)  {
			$(this).attr('href',('https://' + location.href.split('/')[2] + $(this).attr('href')));
		}
	}
});

/*** Erase Search when selected ***/
jQuery("#sitesearch .search_field").click(function() {
	jQuery("#sitesearch .search_field").attr("value","")
});
/*** Erase Username when selected ***/
jQuery("#hdrlog .hdrlogfld").click(function() {
	jQuery("#hdrlog .hdrlogfld").attr("value","")
});
var loginSingleclick = true;
jQuery('#hdrlog').submit(function() {
	if(loginSingleclick){loginSingleclick = false;setHeaderMfaVars();}
	else{return false;}
});
/*** Erase Username in Login Box when selected ***/
jQuery("#j_usernameAjax").click(function() {
	if(jQuery("#j_usernameAjax").attr("value")=="Username") jQuery("#j_usernameAjax").attr("value","");
});

/** Set focus to 'log in' button if user presses tab key for username field in header **/
jQuery(document).ready(function(){ 
	if (jQuery('#j_username')) {
		jQuery('#j_username').keydown(function(event) {
			if (event.which=="9") {
				event.preventDefault();
				jQuery('#hdrlogbtn').focus();
			}
		});
	}
})


/*** BREADCRUMBS ***/
if(jQuery("#breadcrumbs a")){
	jQuery("#breadcrumbs a").each(function() {
	  jQuery(this).after(" &gt;");
	});
}

/*** FORM LEGEND BLOCK ELEMENT WORKAROUND FOR IE ***/
//add a span within legend for each legend element
jQuery('legend').each(function(i) {
	if(jQuery(this).children('span').length==0) jQuery(this).wrapInner('<span />');
});
/*** Style form elements ***/
jQuery("#hdr select, #hdr input, .recontent #wrapper select, .recontent #wrapper input").uniform();  //styles recontent forms and header
if((window.location.pathname).match(/leads-web/)!=null) {  //styles leads-web and enrollment forms
	jQuery("select, input").uniform();
}

/*** WHICH LOAN QUESTION 5 SELECTION ***/
var howlong = '';
var vet = '';
var howmuch = '';
var buyrefi = '';
var downpmt = '';
var equity = '';
jQuery('#conditionals').css('display','none');
jQuery('#conditional-buy').css('display','none');
jQuery('#conditional-refi').css('display','none');
jQuery('input[name="q4"]').click(function() { /* reveals correct question(s) based on radio button selected */
	var sRadioId='#conditional-' + jQuery(this).attr('id');
	jQuery('#conditionals').css('display','list-item').attr('class', jQuery(this).attr('id'));
	jQuery('#conditional-buy').css('display','none');
	jQuery('#conditional-refi').css('display','none');
	jQuery('input:radio[name=q5]:checked').val('undefined');
	jQuery('input:radio[name=q6]:checked').val('undefined');
	jQuery(sRadioId).css('display','block');
});

/*** Which Loan is Right for Me?  reset button ***/
jQuery('.reset-btn').click(function(){
	jQuery("#which-loan-questions")[0].reset();
	jQuery.uniform.update(jQuery('input')); 
	jQuery('#conditionals').css('display','none');
	jQuery('#conditional-buy').css('display','none');
	jQuery('#conditional-refi').css('display','none'); 
});

/*** Which Loan is Right for Me? ***/
jQuery('#wl-submit').click(function(){
	howlong = jQuery('input:radio[name=q1]:checked').val();
	howmuch = jQuery('input:radio[name=q2]:checked').val();
	vet = jQuery('input:radio[name=q3]:checked').val();
	buyrefi = jQuery('input:radio[name=q4]:checked').val();
	downpmt = jQuery('input:radio[name=q5]:checked').val();
	equity = jQuery('input:radio[name=q6]:checked').val();
	chatLP.wlirfmSubmit(buyrefi,howmuch);
	document.location.href = "compare-mortgages-results.html?"+howlong+"-"+howmuch+"-"+vet+"-"+buyrefi+"-"+downpmt+"-"+equity;
});

if(document.location.pathname == '/compare-mortgages-results.html'){
	var wlirfm = document.location.href.split('?')[1];
	var callus = '<p>We were unable to find a loan program based on the information you gave us. Please call us to discuss your loan needs at 1-877-941-4622 (see <a href="/includes/definitions.html#hours-of-operation-sales" class="dejargonator">hours of operation</a>).</p>';
	jQuery('#loanoptions').load('includes/loans.html .'+wlirfm, function(){
		if(jQuery('#loanoptions').html().length < 1){
			jQuery('.iconed p').html(callus);
		}
		if(jQuery('#callus').length != 0){
			jQuery('#about-these-rates').css('display','none');
		}
		setTimeout("bindModalClick()",200);
		parseRateCodes();
	});
	
	if(wlirfm.split('-')[0] == '1'){
		jQuery('#yld-q1').html('Less than 7 years');
	} else {
		jQuery('#yld-q1').html('More than 7 years');
	}
	if(wlirfm.split('-')[1] == '1'){
		jQuery('#yld-q2').html('Less than $417,000');
	} else {
		jQuery('#yld-q2').html('More than $417,000');
	}
	if(wlirfm.split('-')[2] == '1'){
		jQuery('#yld-q3').html('Yes');
	} else {
		jQuery('#yld-q3').html('No');
	}
	if(wlirfm.split('-')[3] == '1'){
		jQuery('#yld-q4').html('Buying');
	} else {
		jQuery('#yld-q4').html('Refinancing');
	}
	if(wlirfm.split('-')[4] == 'undefined'){
		jQuery('.q5').css('display','none');
	} else if(wlirfm.split('-')[4] == '1'){
		jQuery('#yld-q5').html('Less than 5%');
	} else if(wlirfm.split('-')[4] == '2'){
		jQuery('#yld-q5').html('5%–15%');
	} else {
		jQuery('#yld-q5').html('More than 15% ');
	}
	if(wlirfm.split('-')[5] == 'undefined'){
		jQuery('.q6').css('display','none');
	} else if(wlirfm.split('-')[5] == '1'){
		jQuery('#yld-q6').html('Less than 10% of its value');
	} else if(wlirfm.split('-')[5] == '2'){
		jQuery('#yld-q6').html('10%–20% of its value');
	} else {
		jQuery('#yld-q6').html('More than 20% of its value');
	}
	
}
jQuery('#edit').click(function(){
	document.location.href = "compare-mortgages.html?"+document.location.href.split('?')[1];
});

if(document.location.pathname == '/compare-mortgages.html'){
	if(document.location.href.split('?')[1]){
		var wlirfm = document.location.href.split('?')[1];
		if(wlirfm.split('-')[0] == '1'){
			jQuery('input[name="q1"]')[0].checked = true;
		} else {
			jQuery('input[name="q1"]')[1].checked = true;
		}
		if(wlirfm.split('-')[1] == '1'){
			jQuery('input[name="q2"]')[0].checked = true;
		} else {
			jQuery('input[name="q2"]')[1].checked = true;
		}
		if(wlirfm.split('-')[2] == '1'){
			jQuery('input[name="q3"]')[0].checked = true;
		} else {
			jQuery('input[name="q3"]')[1].checked = true;
		}
		if(wlirfm.split('-')[3] == '1'){
			jQuery('input[name="q4"]')[0].checked = true;
			jQuery('#conditionals').css('display','list-item');
			jQuery('#conditional-buy').css('display','block');
			jQuery('input[name="q5"]')[wlirfm.split('-')[4]-1].checked = true;
		} else {
			jQuery('input[name="q4"]')[1].checked = true;
			jQuery('#conditionals').css('display','list-item');
			jQuery('#conditional-refi').css('display','block');
			jQuery('input[name="q6"]')[wlirfm.split('-')[5]-1].checked = true;
		}
	}
}

/*** RECONTENT ... ZEBRA STRIPING ***/
if(jQuery("table.zebrarecon")){
	jQuery("table.zebrarecon tr:odd").addClass("zrodd");
}
/* AJH ... I am making a duplicate with class .zebra because I don't want first column styling (below) but am concerned that .zebracon has been used elsewhere.
Also, I need to add each function in case there is more than one zebra table on a page
then zebra-odd is assigned relative to each table's tr:odd */
if(jQuery("table.zebra")){
	jQuery("table.zebra").each(function() {
		jQuery(this).find("tr:odd").addClass("zebra-odd");
	});
}

/*** RECONTENT ... FIRST COLUMN STYLING ***/
jQuery(".calcsummary tr").find("td:first").addClass("tblleftcol");
jQuery(".zebrarecon tr").find("td:first").addClass("tblleftcol").end().find("th:first").addClass("tblleftcol");
jQuery(".rowdetails tr").find("td:first").addClass("tblleftcol");
jQuery(".yld tr").find("td:first").addClass("tblleftcol");

/*** 1003 ... FIRST COLUMN STYLING FOR FINANCIAL ASSETS ***/
jQuery("#financial_assets tr").find("th:first").css("border-left","none");

/*** COLUMN STYLING FOR 5.1.5 COMPARE RATES and ONE DATA COLUMN OPTION ***/
jQuery("#side-by-side-compare thead th:last-child").css("border-right","1px solid #d5d5d5");
jQuery("#side-by-side-compare .compare-detail td:last-child").css("border-right","1px solid #d5d5d5");
if(jQuery('#side-by-side-compare thead th').length==1) {
	jQuery('#side-by-side-compare thead th').closest('th').css('width','118px').find('a').remove();
}

/*** CALCULATOR LEFT NAV SELECTED ***/
jQuery('#wrapper.calculators .menuleft a').each(function(i) {
    var sCalculator = jQuery(this).text();
    if (jQuery('##wrapper.calculators .right2col>h2').text() == sCalculator) {
        jQuery(this).contents().unwrap();
    }
});

/*** BORDER STYLING FOR WHAT LOAN RESULTS ***/
jQuery(".compare-mortgages tbody td:last-child").css({
		"border-right":"1px solid #d5d5d5",
		"text-align":"right",
		"padding-right":"7px"
});
jQuery(".compare-mortgages tbody tr:last-child").children().css("border-bottom","1px solid #d5d5d5");

/** Adding ability to have tab with dejarg **/
jQuery('.tabdejarg').bind('mouseover', function(){
	this.href = this.title;
});
jQuery('.tabdejarg').click(function(){
	this.href= this.name;
});
/*** SET TAB WIDTHS ***/
if(jQuery('ul.tm1').length > 0) {
	var iFullWidth = jQuery('ul.tm1').width(); //width of the ul
	var aTabs = jQuery('ul.tm1>li'); //capture the tabs
	var iDenom = (aTabs.length > 4) ? aTabs.length : 4;
	var iPresetWidth = 0;
	aTabs.each(function(i) {
		if(jQuery(this).attr('style')) iPresetWidth += jQuery(this).innerWidth();
		jQuery(this).width(Math.floor((iFullWidth-1)/iDenom)); //tabs will be either distributed evenly if there are more than 4, otherwise they'll be 1/4 of the width of the ul (-1 to make room for border on right)
		jQuery(this).find('span').css({ //padding of 20 set in css so doesn't look crunched before js runs.  Then removed once run.
			'padding-right' : 0,
			'padding-left' : 0
		});
		if(i==aTabs.length-1) { //last tab styling and sizing
			jQuery(this).css({
			'border-right' : ((aTabs.length > 3) ? 1 : 0 ) + 'px solid #D3D3D3',
			'width' : (jQuery(this).width() + ((iFullWidth-1) - (jQuery(this).width()*iDenom))) // increase width to add any extra space on right
			}).find('span').css('background-position', ((aTabs.length > 3) ? (-1 + 'px') : 'right') + ' top'); //move background so line won't show next to right-border
		};
	});
}

/*** CONTENT TAB HIGHLIGHTING ***/
var currentTab = document.location.href;
if(currentTab.indexOf("#") > 0) {
	currentTab = currentTab.split("#")[1];
	//Added for refresh
	// only do the following if not in self-service
	if(jQuery("#hasLossmit").length < 1) {
		jQuery(".tm1 a").removeClass("active");
	}
	jQuery(".tm1 a[href=#"+currentTab+"]").addClass("active");
	jQuery(".tm1 a[name=#"+currentTab+"]").addClass("active");
	//Hide all tabbed content
	currentTab = currentTab.split("=")[1];
	jQuery(".tabshow").removeClass("tabshow").addClass("tabhide");
	//Show content for selected tab
	jQuery("#tab-"+currentTab).removeClass("tabhide").addClass("tabshow");
}
jQuery(".tm1 a").click(function() {
	jQuery(".tm1 a").removeClass("active"),
	currentTab=this.href.substring(this.href.indexOf("#")+1),
	jQuery(".tm1 a[href=#"+currentTab+"]").addClass("active"),
	//Hide all tabbed content
	currentTab = currentTab.split("=")[1],
	chatLP.tabSubmit(currentTab);
	jQuery(".tabshow").removeClass("tabshow").addClass("tabhide"),
	//Show content for selected tab
	jQuery("#tab-"+currentTab).removeClass("tabhide").addClass("tabshow"),
	//Remove outline
	this.blur(),
	jQuery('.ieboxshadow').remove()
	/** REMOVING BECAUSE WE ARE NOT USING THIS ANYMORE ieboxshadow() **/
});

/*  COMMENTING OUT FOR NOW BECAUSE IT IS BREAKING I.E. HOMEOWNER-ASSIST
jQuery(window).hashchange( function(){   //Scenarios for browser's back button
	if(location.hash.indexOf('#') >= 0){
		currentTab = location.hash.split("#")[1];
		if(currentTab == ''){
			location = location.pathname;   //Fix for IE leaving a rogue '#' sign at the end of the URL when browser's Back button is used
		}
		jQuery(".tm1 a").removeClass("active");
		jQuery(".tm1 a[href=#"+currentTab+"]").addClass("active");
		currentTab = currentTab.split("=")[1];
		jQuery(".tabshow").removeClass("tabshow").addClass("tabhide");
		jQuery("#tab-"+currentTab).removeClass("tabhide").addClass("tabshow");
	} else {	
		location.reload();   //Reloads the page when browser's Back button is used and there are no parameters 
	}
})
*/

/*** Loan Process Tab Switching ***/
jQuery('.lp-tabs li').click(function(){
	jQuery('.lp-tabs li').removeClass('active'),
	jQuery(this).addClass('active'),
	jQuery('.lp-step').removeClass('lp-tabshow').removeClass('lp-tabhide').addClass('lp-tabhide'),
	jQuery('#'+jQuery(this).attr('title')).removeClass('lp-tabhide').addClass('lp-tabshow')
});
/*** Mini Loan Process Tab Switching ***/
jQuery('.loan-process-mini ol li').click(function(){
	jQuery('.loan-process-mini .step').removeClass('show');
	jQuery('.loan-process-mini ol li').removeClass('active');
	jQuery(this).addClass('active');
	jQuery('.loan-process-mini .step' + jQuery(this).text().charAt(0)).addClass('show');
});

/*** Help Menu Item Highlighting ***/
if(typeof Title_Om != 'undefined'){jQuery(window).load(function() {jQuery('#hm-'+Title_Om).addClass('active');});}

/*** TOP NAVIGATION HIGHLIGHTING ***/
//find the url of the topnav tab that will be highlighted based on the pathname of the current location
currentTab = ((location.href.indexOf("mortgage-calculators") > 0 ) ? '/mortgage-calculators.htm?method=init':location.pathname);
currentTab = ((currentTab.indexOf('CalculatorServlet')>0)? '/mortgage-calculators.htm?method=init':currentTab);
currentTab = ((currentTab.indexOf('comparerates')>0)? '/comparerates/enterLoanData.html':currentTab);
currentTab = ((currentTab.indexOf('refinancing')>0)? '/mortgage-refinancing.html':currentTab);  //for refinancing products
currentTab = ((currentTab.indexOf('home-loan')>0)? '/mortgages.html':currentTab); //for mortgage products
//the following are for different resources
currentTab = ((currentTab.indexOf('home-financing')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('compare-mortgages')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('compare-mortgages-results')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('hhstart.htm')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('mortgage-glossary')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('mortgage-credit')>0)? '/mortgage-resources.html':currentTab);
currentTab = ((currentTab.indexOf('mortgage-assistance')>0)? '/mortgage-resources.html':currentTab);
//if one of the topnav anchor hrefs ends with the value of currentTab then set class to current
jQuery("#menumain a[href $='" + currentTab + "']").closest("li").addClass("current");

/*** Show hints when clicked ***/
jQuery('.hint').toggle(function() {
	jQuery(this).find('p').css('display','block');
	jQuery(this).css('background','url("/img/buttons/arrowdown.gif") 0px 4px no-repeat');
}, function() {
	jQuery(this).find('p').css('display','none');
	jQuery(this).css('background','url("/img/buttons/arrowright.gif") 0px 4px no-repeat');
});

/*** NEW HINT STYLING (also for dejargonator) ***/
jQuery('.hint-title').click(function() {
	jQuery(this).parent().find('.hint-text').css('display','block');
}).mouseout(function() {
	jQuery(this).parent().find('.hint-text').css('display','none');
});

/*** LIST OF BLINDS ***/
//IE workaround to make list of blinds links' chevrons clickable:
if(jQuery.browser.msie) {
	if (jQuery('.blind-link').length > 0) jQuery('.blind-link').prepend('<div></div>');
}
//link functionality
jQuery('.blind-link').click(function() {
	jQuery(this).closest('li').toggleClass('blind-open').children('div').slideToggle('slow');
	jQuery('.blind-open').not(jQuery(this).parent()).toggleClass('blind-open').children('div').slideToggle('slow');
});

/*** SINGLE BLIND ***/
jQuery('.blind').click(function() {
	jQuery(this).toggleClass('blind-open').next('div').slideToggle('slow');
});

/*** hide all but 3 rates results ***/
jQuery('.rate-fee-results').each(function() {
	var iResultsShown = 0;
	var iResultsTotal = jQuery(this).find('tr').length;
	if (iResultsTotal <= 3) {
		iResultsShown = iResultsTotal;
	} else {
		iResultsShown = 3;
		jQuery(this).find('.rates-shown').append(': <a href="#">show more</a>');
	}
	jQuery(this).find('.number-shown').text(iResultsShown);
	jQuery(this).find('.number-total').text(iResultsTotal);
	jQuery(this).find('tr').each(function(i) {
		if(i<3) {
			jQuery(this).addClass('show');
		} else {
			return false;
		}
	});
});

/*** blinds and link toggle for rates results ***/
jQuery('.rates-shown a').click(function() {
	jQuery(this).closest('table').toggleClass('show-all-results');
	var sMoreLess = jQuery(this).text();
	sResultsShown = (sMoreLess.match("more")) ? jQuery(this).siblings('.number-total').text() : "3";
	sMoreLess = (sMoreLess.match("more")) ? sMoreLess.replace(/\w*$/, "less") : sMoreLess.replace(/\w*$/, "more");
	jQuery(this).text(sMoreLess);
	jQuery(this).siblings('.number-shown').text(sResultsShown);
	return false;
});

/*** blinds for rates details ***/
jQuery(".compare-details-button").click(function() {
	jQuery(this).toggleClass('collapsed').closest("tbody").next(".compare-detail").toggle();
	return false;
});

/***dynamic height for rate result side by side compare product "table cell" height***/
var compareHeadHeight = 14;
jQuery('#side-by-side-compare thead th strong').each(function(i) {
    compareHeadHeight=(compareHeadHeight>jQuery(this).height())?compareHeadHeight:jQuery(this).height();
});
jQuery('#side-by-side-compare thead th strong').css('height',compareHeadHeight);
jQuery("#change-selection-cta a").css('margin-bottom',(5+(compareHeadHeight-14)));

/*** More style form elements ***/
jQuery.uniform.update(jQuery('input'));
	
/*** DYNAMICALLY SIZE THE WIDTH OF SELECTION BOXES ***/
if(jQuery(".recontent").length<1 && jQuery("#enroll").length<1) { /* removed from the recontent and enroll pages */
	if(jQuery("select").closest('#ratequote').length<1){
		jQuery("select").filter(function(index) {
			var tj_lo = 0;
			jQuery(this).find("option").filter(function(index) {
				if(jQuery(this).text().length > tj_lo){
					tj_lo = jQuery(this).text().length;
				}
			});
			tj_lo = (8*tj_lo)+40;
			if(tj_lo>400){tj_lo=400;}   //Fix for fields being too wide for their own good.
			jQuery(this).closest("div.selector").css("width",tj_lo-8).find("select").css("width",tj_lo).end().find("span").css("width",tj_lo-33);
			tj_lo = 0;
		});
	}
}

/*** SELECTION BOX ARROW OVERLAY for UNIFORM styled form select ***/
//when the content in the dropdown is too long the dropdown arrow no longer disappears.
jQuery('div.selector').prepend('<div class="phantom-select-arrow"></div>');

/*** insure that dropdown under SELECTION BOX isn't smaller than the SELECTION BOX ***/
jQuery('div.selector').each(function(i) {
	var iSelectMinWidth = jQuery(this).innerWidth();
	if(jQuery(this).children('select').width() < iSelectMinWidth) jQuery(this).children('select').width(iSelectMinWidth);
});

/*** Style form elements for ALERTS if they exist and are not empty ***/
var styleErrors = function() {
	jQuery('div.alert').filter(function(index) {
		var hasErrorText = jQuery(this).text().length > 0;
		var registrationErrorDiv = jQuery('div[id].alert',jQuery(this).closest('fieldset')).length > 0;
		if (hasErrorText) {
			return true;
		} else if (!hasErrorText && !registrationErrorDiv) {
			return true;
		} else {
			return false;
		}
	}).filter(":not(:has(#financial_assets))").closest('fieldset')
	.find('input.text,input.password').css('border','1px solid #cc0000').end()
	.find('span.currency').addClass("currencyalert").end()
	.find('div.selector').addClass("spritealert").end()
	.find('div.selector span').addClass("spritealert").end()
	.find('div.checker span').addClass("spritealert").end()
	.find('div.radio span').addClass("spritealert").end()
	.find('div.alert').filter(function(index) {
		return jQuery(this).text().length > 0;
	}).addClass('alerticon');
}

var styleFixedErrors = function(field) {
	jQuery(field).filter(function(index) {
		var hasErrorText = jQuery(this).text().length > 0;
		var registrationErrorDiv = jQuery('div[id].alert',jQuery(this).closest('fieldset')).length > 0;
		if (hasErrorText) {
			return true;
		} else if (!hasErrorText && !registrationErrorDiv) {
			return true;
		} else {
			return false;
		}
	}).filter(":not(:has(#financial_assets))").closest('fieldset')
	.find('input.text,input.password').css('border','1px solid #C6C6C6').end()
	.find('span.currency').removeClass("currencyalert").end()
	.find('div.selector').removeClass("spritealert").end()
	.find('div.selector span').removeClass("spritealert").end()
	.find('div.checker span').removeClass("spritealert").end()
	.find('div.radio span').removeClass("spritealert").end()
	.find('div.alert').removeClass('alerticon');
}

/*** GLOSSARY and CALCULATOR TERMS ***/
//Populate terms for glossary or calculator
function deglossary(def){
	if (def == "glossary"){
		jQuery('#glossary').load('/includes/definitions.html .glossary');   //class="glossary" ... ignore all other classes in the definitions file
	} else if(def == "calcterms"){
		jQuery('#calcterms').load('/includes/definitions.html .calcterms');   //class="calcterms" ... ignore all other classes in the definitions file
	}
}
//Populate terms for glossary or calculator if the holder exists
if(jQuery('#calcterms').length != 0){
	deglossary("calcterms");
}
if(jQuery('#glossary').length != 0){
	deglossary("glossary");
}

/* STYLING RIGHT COLUMN */
/* begin: liquidcanvas used to create rounded corners in interface */
if (location.href.indexOf("leads-web") < 0) {
	jQuery(window).load(function() {
		jQuery(".rightcolcallout").liquidCanvas("[border{color:#dbdbdb; width:1} fill{color:#f5f5f5}] => roundedRect{radius:7}");
	});
/* end: liquidcanvas used to create rounded corners in interface */
	jQuery(document).ready(function(){
		jQuery('.rightcolcallout').append('<div class="bottom">&nbsp;</div>');
	})
}


/* VERTICAL POSITIONING OF FORM LABELS FOR UNIFORM INPUT AND SELECTION FIELDS */
jQuery('.label-inline-wrap label').each(function(i) {
	// first, change margin-top of selector label as well as margin top and bottom of its parent div 
	if (jQuery(this).next('.selector').length > 0) {
		jQuery(this).css('margin-top','5px').parent().css({
			'margin-top' : '-2px',
			'margin-bottom' : '8px'
		});
	}
	// if label wraps to two or more lines change margins for the label and its parent div
	if ((jQuery(this).height() - parseInt(jQuery(this).css('font-size')))>=parseInt(jQuery(this).css('font-size'))) {
		//margin-top of label will be 5 px less
		jQuery(this).css('margin-top',parseInt(jQuery(this).css('margin-top')) - 5 + 'px');
		//margin-bottom of label's parent will be either 3px less or 2px less if it contains a selector (parent's top will be -2px if it contains a selector)
		jQuery(this).parent().css('margin-bottom',parseInt(jQuery(this).parent().css('margin-bottom'))-3+parseInt(jQuery(this).parent().css('margin-top'))/-2+'px');
	}
});

/*** MODALS ***/
//first, make sure there are no duplicate modal id names by renaming all modal links and divs with an interval number
jQuery('.modal-rc').each(function(i) {
	var sModalId=(jQuery(this).attr('id') + '-' + i);
	jQuery(this).attr('id',sModalId);
});
//modal click function styles respective modal div, wraps it within a modal-wrap div and then liquidCanvas-s it with a nice shadow effect
function bindModalClick(){
jQuery('.modal-rc').click(function() { 
	var sThisModal = ('#modal-'+ (jQuery(this).attr('id').replace(/-\d+/,"")));
	var iThisModalWidth = (sThisModal.indexOf("loading")!=-1) ? 330 : 720;  //720px for all regular modals, 330px for loading modal
	if(jQuery(this).attr('id').indexOf("about-these-rates")!=-1){loadRateDisclosures(jQuery(this), jQuery(sThisModal));}
	
	var placeModalLeft;
	var placeModalTop;
	if (jQuery(this).attr('id').indexOf("loading-stationary") < 0) {
		placeModalLeft = (jQuery('#wrapper').offset().left + 140 + ((720-iThisModalWidth)/2)) + 'px';
		placeModalTop = '118px';
	}
	else
	{
		placeModalLeft = (jQuery('.upload-column').offset().left + 10 + ((720-iThisModalWidth)/2)) + 'px';
		placeModalTop = (jQuery('.upload-column').offset().top + 20);
	}
	
	jQuery.blockUI({
		message: jQuery(sThisModal),
		css: {
			position: 'absolute',
			top: placeModalTop,
			left: placeModalLeft,
			width:  iThisModalWidth + 'px',   
			padding: '0',
			border: 'none',
			background: 'none',
			textAlign: 'left',
			zIndex: '5000'
		}
	});
	if(iThisModalWidth ==720) {
		jQuery(sThisModal).wrapInner('<div id="modal-wrap" />').prepend('<a href="#" onclick="jQuery.unblockUI();oCloseX();return false;" class="x"><img src="/img/buttons/x.png" /></a>').liquidCanvas("[shadowWithOffset{width:12; shiftX:0; shiftY:0; alpha:'0.15'} fill{color:#dbdbdb}] => roundedRect{radius:13}");  //regular
	} else {
		jQuery(sThisModal).wrapInner('<div id="modal-wrap" />').liquidCanvas("[shadowWithOffset{width:10; shiftX:0; shiftY:0; alpha:'0.15'} fill{color:#f5f5f5}] => roundedRect{radius:20}");  // loading 
	}

	if (jQuery(this).attr('id').indexOf("loading-stationary") < 0) {
		jQuery( 'html, body' ).animate( { scrollTop: 0 }, 'slow' ); //scrolls page to the top so you can read the modal.
	}
});
}
bindModalClick();

//copy of above for Interstitial, 'leaving site' modal. 
//to do: try to merge with above function.
jQuery('.modal-ext').click(function() { 
	var sThisModal = ('#modal-'+jQuery(this).attr('id'));
	jQuery.blockUI({
		message: jQuery(sThisModal),
		css: {
			position: 'absolute',
			top: '118px',
			left: (jQuery('#wrapper').offset().left + 140) + 'px',
			width:'720px',
			padding: '0',
			border: 'none',
			background: 'none',
			textAlign: 'left',
			zIndex: '5000'
		}
	});
	jQuery(sThisModal).wrapInner('<div id="modal-wrap" />').prepend('<a href="#" onclick="jQuery.unblockUI();oCloseX();return false;" class="x"><img src="/img/buttons/x.png" /></a>').liquidCanvas("[shadowWithOffset{width:12; shiftX:0; shiftY:0; alpha:'0.15'} fill{color:#dbdbdb}] => roundedRect{radius:13}");
	if (sThisModal=="#modal-interstitial-elynx") {
		jQuery(sThisModal).find('.btn').attr("href","javascript:"+jQuery(this).attr("name"));
	}
	else {
		jQuery(sThisModal).find('.btn').attr({'href':jQuery(this).attr('name'),'target':'_blank'});
	}
	jQuery( 'html, body' ).animate( { scrollTop: 0 }, 'slow' ); //scrolls page to the top so you can read the modal.
});
//end of interstitial duplicate

//begin ie6 login modal (we should also be able to merge this with above)
function ieSixModal(){
	var sThisModal = ('#modal-ie6-warning').replace(/-\d+/,"");
	jQuery.blockUI({
		message: jQuery(sThisModal),
		css: {
			position: 'absolute',
			top: '118px',
			left: (jQuery('#wrapper').offset().left + 140) + 'px',
			width:  '720px',   
			padding: '0',
			border: 'none',
			background: 'none',
			textAlign: 'left',
			zIndex: '5000'
		}
	});
	jQuery(sThisModal).wrapInner('<div id="modal-wrap" />').prepend('<a href="#" onclick="jQuery.unblockUI();oCloseX();return false;" class="x"><img src="/img/buttons/x.png" /></a>').liquidCanvas("[shadowWithOffset{width:12; shiftX:0; shiftY:0; alpha:'0.15'} fill{color:#dbdbdb}] => roundedRect{radius:13}");  //regular
	jQuery( 'html, body' ).animate( { scrollTop: 0 }, 'slow' ); //scrolls page to the top so you can read the modal.
}

if ( location.href.indexOf('logon')!=-1 && ((jQuery.browser.msie && jQuery.browser.version<7) || (jQuery.browser.mozilla && (jQuery.browser.version).indexOf("1.8") > -1))) {
	ieSixModal();
}
//end ie6 login modal

//begin ditech transfer (we should also be able to merge this with above)
function ditechTransferModal(){
	var sThisModal = ('#modal-ditech-transfer').replace(/-\d+/,"");
	jQuery.blockUI({
		message: jQuery(sThisModal),
		css: {
			position: 'absolute',
			top: '118px',
			left: (jQuery('#wrapper').offset().left + 140) + 'px',
			width:  '720px',   
			padding: '0',
			border: 'none',
			background: 'none',
			textAlign: 'left',
			zIndex: '5000'
		}
	});
	jQuery(sThisModal).wrapInner('<div id="modal-wrap" />').prepend('<a href="javascript:void(0);" onclick="clearTimeout(ditechModalTimer);jQuery.unblockUI();oCloseX();ditechOmnitureEvents(\'XClicked\');return false;" class="x"><img src="/img/buttons/x.png" /></a>').liquidCanvas("[shadowWithOffset{width:12; shiftX:0; shiftY:0; alpha:'0.15'} fill{color:#dbdbdb}] => roundedRect{radius:13}");  //regular
	jQuery( 'html, body' ).animate( { scrollTop: 0 }, 'slow' ); //scrolls page to the top so you can read the modal.
}
var ditechModalTimer;
function ditechTransferTest() {
	if (document.location.search.length != 0 && document.location.search.indexOf("ditech=true") != -1) {
		//start 10 second timer
		ditechModalTimer = setTimeout( "jQuery.unblockUI();oCloseX();ditechOmnitureEvents('ModalTimedOut');",15000);
		//add ditech transfer modal div conditionally
		jQuery('#wrapper').prepend('<div class="modal" id="modal-ditech-transfer"><div style="padding: 10px 0;"><img src="/img/logoGMAC.png" alt="GMAC logo" /><img src="/img/logoDitech.png" alt="ditech logo" style="float: right" /></div><h2>Looking for ditech.com?</h2><p>GMAC Mortgage is now helping all ditech customers.</p><p>For more than 25 years, GMAC Mortgage has been providing great service and loan solutions for homeowners and homebuyers.</p><p>And now, we look forward to serving you.</p><p style="overflow: hidden;"><a href="javascript:void(0);" onclick="clearTimeout(ditechModalTimer);jQuery.unblockUI();oCloseX();ditechOmnitureEvents(\'ButtonClicked\');return false;" class="btn"><span>continue</span></a></p><p class="smallprint" >Ditech, GMAC Mortgage, and Ally Bank are part of the Ally Financial Inc. family of companies.</p></div>');
		//modal appears on rendering redirected-to page.
		ditechTransferModal();
	}
}
//ditech omniture function to pass particular page name argument to s.tl variable
function ditechOmnitureEvents(sPageNameSuffix) {
	var s=s_gi(s_account);
	s.tl(this,'o',s.pageName+':'+sPageNameSuffix);
}
jQuery(function() { //wait until page fully loaded
	ditechTransferTest();
	//omniture redirect variable sent
	if (document.location.search.length != 0 && document.location.search.indexOf("ditech=true") != -1) {
		setTimeout("if(s.events!=undefined) ditechOmnitureEvents('Redirect');",1000);
	}
});
//end ditech transfer

//close modal function
function oCloseX() {
	jQuery('.x').closest('div').removeAttr('style');  //remove the style first so that you don't get the black halo in IE when hiding
	jQuery('.x').remove();  //removes the close anchor tag from the modal div
	jQuery('#modal-wrap > *:first-child').unwrap(); //removes modal wrapper div to restore modal to it's original structure for use again
}
//on resize the modal window stays centered horizontally
jQuery(window).resize(function() {
	if(jQuery('.blockMsg').length != 0) {
		jQuery('.blockMsg').css({
			left: (jQuery('#wrapper').offset().left + 140 + ((720-jQuery('.blockMsg').width())/2)) + 'px'
		});
	}
});

function openWindow(loc, name, width, height, features) {
	leftPos = (screen.width) ? (screen.width - width) / 2 : 0;
	topPos = (screen.height) ? ((screen.height- height) / 2) - 100 : 0;
	var win = window.open(loc, name, 'width=' + width + ', height=' + height + ', top=' + topPos + ', left=' + leftPos + ', ' + features);
	if (parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
}

/*** EMULATE INLINE OL COUNTER FOR IE ***/
if(jQuery.browser.msie) {
	jQuery('.get-loan-guide h3').each(function(i) {
		jQuery(this).addClass('ie-num').prepend('<span>' + (i+1) + '.</span>');
	});
}

/*** INNER BORDER FUNCTION***/
// creates inner border of specified color within specified object, can be used for 2-tone borders;
// oBlockObj defined in jQuery style such as 'div.callout-box' or just '.callout-box'
// sHexColor is the 6 digit numerical hex color (without the leading '#') such as 'fcfcfc'
//sLRTB is either 'left', 'right', 'top', 'bottom' for single line, or '' for full box
function innerBorder(oBlockObj,sHexColor,sLRTB) {
	// first, make sure container has absolute or relative positioning
	if(jQuery(oBlockObj).css('position')!='absolute') jQuery(oBlockObj).css('position','relative');
	var oInnerBorder = document.createElement('div');
	function borderPropertyName() {
		var sProperty = 'border';
		if(sLRTB!='') sProperty += ('-'+sLRTB);
		return sProperty;
	}
	//dynamic border property name based on sLRTB
	var curly = {};
	curly[borderPropertyName()] = ('1px solid #'+sHexColor);
	jQuery(oInnerBorder).css(curly);
	//fully bordered box will shrink by 2px;
	var iShrinkage = ((/\w/).test(sLRTB)) ? 0 : 2;
	//will this shift? default is 0 for both x and y
	var aBorderShiftCoordinates = [0,0];
	if ((/r|b/).test(sLRTB)) aBorderShiftCoordinates = ((/r/).test(sLRTB)) ? [-1,0] : [0,-1];
	jQuery(oInnerBorder).addClass('inner-border').css({
		'position':'absolute',
		'width':(jQuery(oBlockObj).innerWidth()-iShrinkage),
		'height':(jQuery(oBlockObj).innerHeight()-iShrinkage),
		'left':aBorderShiftCoordinates[0] + 'px',
		'top':aBorderShiftCoordinates[1] + 'px'
	});		
	jQuery(oBlockObj).prepend(oInnerBorder);
}

//innerBorder('.callout-box','fcfcfc','');
//innerBorder('.get-loan-guide ol>li','fcfcfc','right');

/* for uniformed selection boxes truncate selected option from "(" to end. i.e. "Excellent (750-800)" becomes just "Excellent" when rendered.
jQuery('.selector .selectInput').change(function() {
	str=jQuery(this).prev().text().replace(/\s\(.*$/, "");
	jQuery(this).prev().text(str);
});
jQuery('.selector .selectInput').blur(function() {
	str=jQuery(this).prev().text().replace(/\s\(.*$/, "");
	jQuery(this).prev().text(str);
});
*/

//RESET UNIFORM FORM SCRIPT
jQuery('.reset-btn').click(function() {
// location.reload();   for now use this until I can solve for Which Loan extra questions 
 
//the following script currently only removes radio button checks from a "Uniformed" form.
//later, if we use this for other forms I will add resets for other form elements
	oCurrentForm = jQuery(this).closest('form');
	oCurrentForm.find('.radio>span').removeClass('checked');
	oCurrentForm.find('#conditionals').css('display','none').children().css('display','none');
	jQuery('#which-loan-questions input[type="radio"]').checked = false;  // remove checked state from radios that were checked
});
jQuery('.print-window a').bind('click mouseover hoverIntent', function(event){
	event.preventDefault(); 
});
jQuery('.print-window a.dejargonator').removeClass("dejargonator");
/*** RATES Takes longer to load ***/
var ratesJson = '';
var ratesDisc = '';
var ratesLoaded = false;
//var ratesUrl = '/Utilities/rate.json';
var ratesUrl = '/Utilities/cachedrates/rates.json';
var callUs = '<a href="/custserv.htm">call us</a>'
//load rates xml
function loadRates(){
	if(jQuery(ratesJson).length == 0){
		jQuery.ajax({url: ratesUrl,
			dataType: "json",
			success: function(data){
				ratesJson = data;
				ratesLoaded=true;
				parseRateCodes();
				
				
			},
			 error: function(xhr, status, errorThrown) {
				jQuery(".ratedata").each(function() { jQuery(this).parent().html(callUs);});
				jQuery(".rateaprdata").each(function() { jQuery(this).parent().html(callUs);});
				//alert(errorThrown+'\n'+status+'\n'+xhr.statusText+'\n test:'+xhr.responseText);
				//alert("response trimmed: "+jQuery.trim( xhr.responseText ));
			}

		});
	}
	
}
if(jQuery('.minirates').length != 0 || jQuery('.ratedata') || jQuery('#which-loan-results')){	
	loadRates();
	if (!(typeof dejargonator === 'undefined')) dejargonator.prepDJ();
}
function parseRateCodes(){ 
	var loops = 0;
	var rateTryCount = setInterval(function() {
		if(ratesLoaded || loops>10){
			clearInterval(rateTryCount);
			jQuery(".minirates").each(function() { 
				var rateCodes = jQuery(this).attr("class").split(" ");
				if(rateCodes.length>1){
					parseRates(jQuery(this), rateCodes[1].split("-"));
				}
			}); 
			jQuery(".ratedata").each(function() { 
				var rateCode = jQuery(this).attr("class").split(" ");
				if(rateCode.length>1){
					parseSingleRate(jQuery(this), rateCode[1]);
				}
			});	
			jQuery(".rateaprdata").each(function() { 
				var rateCode = jQuery(this).attr("class").split(" ");
				if(rateCode.length>1){
					parseSingleAPR(jQuery(this), rateCode[1]);
				}
			});	
		}
		loops ++;
	}, 200);
}
function parseRates(section, rateCodes){
	if(jQuery(ratesJson).length > 0){
		var ratehtml="<thead><tr><th scope='col'>PROGRAM</th><th scope='col'>RATE</th><th scope='col'>APR</th></tr></thead>";
		var gotRates = 0;
		for (x in rateCodes){
		 	if(typeof(ratesJson[rateCodes[x]]) == "object"){
				ratehtml+="<tr><th scope='row'>"+ ratesJson[rateCodes[x]].description + "</th><td>"+ ratesJson[rateCodes[x]].calculation.rate + "%</td><td>"+ratesJson[rateCodes[x]].calculation.apr+"%</td></tr>";
				gotRates = gotRates+1;
			}
		}
		if (gotRates == 0) {
			ratehtml="<tbody><tr><td>Rates are temporarily unavailable &mdash; please check again later. We apologize for the inconvenience.</td></tr></tbody>";
		}
		section.html(ratehtml);
		jQuery(section).addClass("zebra");
		//remove .zebra from right column callout
		jQuery('.rightcolcallout').children(section).removeClass('zebra');
		jQuery("table.zebra tr:not(tr:odd)").addClass("zebra-odd");
	}
}		
function parseSingleRate(section, rateCode){
	if(jQuery(ratesJson).length > 0){
		var ratehtml="";
		if(typeof(ratesJson[rateCode]) == "object"){
			section.html(ratesJson[rateCode].calculation.rate);
		}
		else{
			section.parent().html(callUs);
		}
	}
	else{ 
		jQuery(section).parent().html(callUs);
	}
}
function parseSingleAPR(section, rateCode){
	if(jQuery(ratesJson).length > 0){
		var ratehtml="";
		if(typeof(ratesJson[rateCode]) == "object"){
			section.html(ratesJson[rateCode].calculation.apr);
		}
		else{
			section.parent().html(callUs);
		}
	}else{ 
		jQuery(section).parent().html(callUs);
	}
}
function getRateDisclosures(aboutRatesDiv, modal, inline){
	var rateCodes = aboutRatesDiv.attr("class").split(" ");
	if(rateCodes.length>1){
		parseRateDisclosures(modal, rateCodes[1].split("-"), inline);
	}
}
//load rates disclaimers
function loadRateDisclosures(aboutRatesDiv, modal, inline){
	if(jQuery(ratesDisc).length == 0){
		jQuery.ajax({url: "/includes/rate-disclaimers.html",
			async:   false,
			success: function(data){
				ratesDisc = data;
				if(inline){parseRateDisclosures(aboutRatesDiv, modal, inline);}
				else{getRateDisclosures(aboutRatesDiv, modal, inline);}				
			}
		});
	}
	else{
		getRateDisclosures(aboutRatesDiv, modal);
	}

}
jQuery.fn.parseTemplate = function(data)
{
    var str = (this).html();
    var _tmplCache = {}
    var err = "";
    try
    {
        var func = _tmplCache[str];
        if (!func)
        {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
}
function parseRateDisclosures(modal, rateCodes, inline){ 
	if(jQuery(ratesJson).length > 0){
		var rateDiscHtml='<script id="AssumptionsTemplate" type="text/html">';
		if(!inline){rateDiscHtml+="<h2>Disclosures and Assumptions</h2>";}
		var tempRateDiscHtml='';
		var type = "";
		var genericVerbiage = "#generic";
		for (x in rateCodes){
			if(typeof(ratesJson[rateCodes[x]]) == "object"){
				var tempHtml=jQuery(ratesDisc).find('#'+rateCodes[x]);
				if(typeof(tempHtml) == "object" && tempHtml.html()!=null){tempRateDiscHtml += tempHtml.html();}
			}
		}
		rateDiscHtml+=jQuery(ratesDisc).find(genericVerbiage).html();
		rateDiscHtml+=tempRateDiscHtml+'</script>';
		rateDiscHtml = rateDiscHtml.replace(/\&lt;/g, "<").replace(/\&gt;/g, ">");
		modal.html(jQuery(rateDiscHtml).parseTemplate(ratesJson));
	}
}
/* Added for rate disclosures page support mboxes */
if(jQuery('.ratedisclosures').length != 0){	
	var loops = 0;
	loadRates();
	var timer = setInterval(function() {
		if(ratesLoaded || loops>10){
			clearInterval(timer);
			if(ratesLoaded){
				var rateCode='';
				if(location.href.indexOf('GRC')!=-1){
					rateCode=location.href.substring(location.href.indexOf('GRC')+4,location.href.length);
				}else{
					rateCode=jQuery('.ratedisclosures').attr("class").split(" ")[1];
				}
				var rateCodeArray = (rateCode.indexOf('-')>0 ==-1) ? new Array(rateCode) : rateCode.split("-");
				loadRateDisclosures(jQuery('.ratedisclosures'),rateCodeArray,true);
			}
		}
		loops ++;
	}, 200);
}

//SET LIST ELEMENT HEIGHT FOR RATE RESULTS: YOUR CUSTOM RATE QUOTE
jQuery('#your-loan-details dt').each(function(i) {
    jQuery(this).next().height(jQuery(this).innerHeight());
});
//formate phone number on input
jQuery('input[name="phone"]').focusout(function(){jQuery(this).val(format_phone(this));});
function reformater(s){var arg;var pos=0;var str="";for(var i=1;i<reformater.arguments.length;i++){if (pos>=s.length){i=reformater.arguments.length;break;}else{arg=reformater.arguments[i];if(i%2==1){str+=arg;}else{str+=s.substring(pos,pos+arg);pos+=arg;}}}return str;}
function format_phone(node){var str=(node.value).replace(/[^a-zA-Z\d]/g, "");if(str.length>10&&(str.charAt(0)=='1')){str=str.substring(1);}node.value=reformater(str,"",3,"-",3,"-",4);}

//When using the Rates tabs on the 'Buy a home' page, change the loanType to purchase
if (/^\/mortgages.html/.test(location.pathname)) {
    jQuery('input[name="productManager.currentQuery.loanType"]').val(1);
}


jQuery('.anchor-form-submit').click(function() {
  $(this).closest('form').submit();
});

