if (site==null || site =='undefined') {
	var site= {
		sessionWarningTimer:"",
		sessionLogoutTimer:"",
		warningVisible:0,
		win:"",
		winName:""
	};
}
// site.resetSessionTimer: Reset timeout clock when user interacts.
site.resetSessionTimer = function() {
	if (site.warningVisible==0) {
		clearTimeout(site.sessionWarningTimer);
		clearTimeout(site.sessionLogoutTimer);
		site.setSessionTimer();
	}
}
// site.setModalClickTrigger: trigger for modal-rc links which have an iteration number attached to end of ids.
site.setModalClickTrigger = function(modalName) {
	var re = new RegExp("^" + modalName + "-\\d$");
	jQuery('.modal-rc').each(function(i) {
		if((jQuery(this).attr('id').match(re))!=null) {
		jQuery(this).trigger('click');
			return false;
		}
	});
}
// site.setSessionTimer: Display session timeout warning.
site.setSessionTimer = function(){
	timeoutWarning = function(){
		jQuery('#timeout-message').css('display','none');
		jQuery('#warning-message').css('display','block');
		jQuery('#modal-timeout a.x').css('visibility','visible');
		site.setModalClickTrigger('timeout');
		clearTimeout(site.sessionWarningTimer);
		site.warningVisible=1;
		site.logoutUser();
	}
	site.sessionWarningTimer = setTimeout("timeoutWarning()", 600000);
	jQuery('#modal-timeout a.x').css('visibility','hidden');
}

// site.logoutUser: Logout user if no action after 15 minutes.
site.logoutUser = function(){
	timeoutLogout = function(){
		jQuery('#modal-timeout a.x').fadeOut('slow',function(){});
		jQuery('#warning-message').css('display','none');
		jQuery('#timeout-message').fadeIn('slow',function(){});
		if(site.win){
			if(site.winName.indexOf('orcc') < 0)
				{site.win.close();
			}
		}
	}
	site.sessionLogoutTimer = setTimeout("timeoutLogout()",300000); 
}

/***************confirmit survey ***************************/
var confirmit = {
    options: {
		surveyName: "gmac-mortgage-survey",
		uniqueIdLabel: "profile.gmacMortgage_uniqueId=",
		gmacmLoggedInLabel: "gmacMortgage_loggedIn=",
		survey_csat_sections: /loan details|logoff|EmailConfirm|ebpp dashboard|Home/,
		survey_leads_sections: /^Get started|Your Loan Requests|Loan Information|Property Information|Primary Borrower Information|Co-Borrower Information|Work History|Financial Assets|Next Steps|Review & Submit Your Information|You're Finished$/,
		survey_fulfillment_sections: /Splash|eDisclosures|Disclosures|Review|ConditionalApproval|UpdatedConditions|FinalReview|FinalApproval|Declined|Closing/
	},
    isSurveyPage:function(pageUrl) {
		if("undefined" != typeof(Title_Om)){
			if(this.options.survey_csat_sections.test(Title_Om) || this.options.survey_leads_sections.test(Title_Om) || this.options.survey_fulfillment_sections.test(Title_Om)){return true;}
		}
    	return false;
    },
	isLeadsPage:function() {
		pageUrl = document.location.toString();
    	if(location.href.indexOf("leads-web") > 0) return true;
    	return false;
    },
	isFulfillmentPage:function() {
		if(location.href.indexOf("loanStatus.htm") > 0) return true;
    	return false;
	},
	createLeadsMbox:function(){
		if("undefined" != typeof(Title_Om)){
			switch (Title_Om)
			{
				case "Get started":
					mboxTrack('eventTracker','event=iLead_start');
					break;
				case "Your Loan Requests":
					mboxTrack('eventTracker','event=iLead_loans');
					break;
				case "Loan Information":
					mboxTrack('eventTracker','event=iLead_info');
					break;
				case "Property Information":
					mboxTrack('eventTracker','event=iLead_prop');
					break;
				case "Primary Borrower Information":
					mboxTrack('eventTracker','event=iLead_bwr');
					break;
				case "Co-Borrower Information":
					mboxTrack('eventTracker','event=iLead_cbwr');
					break;
				case "Work History":
					mboxTrack('eventTracker','event=iLead_work');
					break;
				case "Financial Assets":
					mboxTrack('eventTracker','event=iLead_fin');
					break;
				case "Next Steps":
					mboxTrack('eventTracker','event=iLead_step');
					break;
				case "Review & Submit Your Information":
					mboxTrack('eventTracker','event=iLead_review');
					break;				  
				case "You're Finished":
				  mboxTrack('eventTracker','event=iLead_complete');
				  break;				  
			} 
		}
	},
	createFulfillmentMbox:function(){
		// If we havent already called mboxTrack this session
		if(jQuery.cookie('sentFulfillmentSurveyVars') == null) {
			var custTypeForSurvey;
			if ("undefined" != typeof(Customer_Type)) {
				if (Customer_Type.indexOf("Customer") > -1) {
					custTypeForSurvey = "Customer";
				}
				else {
					custTypeForSurvey = "Consumer";
				}
			}
			// Conditionally invoke mboxTrack based on if user has seen Fulfillment.
			if(jQuery.cookie('visitedFulfillment') != null) {
				mboxTrack('eventTracker','event=GMACMortgage_'+custTypeForSurvey+'&event2=GMACMortgage_Sales_Fulfillment');
			}
			else {
				mboxTrack('eventTracker','event=GMACMortgage_'+custTypeForSurvey);
			}
		}
		jQuery.cookie('sentFulfillmentSurveyVars', 'yes');
	},
	addSaveOnclick:function(){
		jQuery('#saveButton').mousedown(function() {      
			mboxTrack('eventTracker','event=Saved_App');
		});  
		jQuery('.btn').mousedown(function() {  
			if(this.href.indexOf("eventId=submit")!=-1){
				mboxTrack('eventTracker','event=Submit_App');
			}
		});
		jQuery('#saveButtonReview').mousedown(function() {      
			mboxTrack('eventTracker','event=Saved_App');
		});
	},
	onPageLoad:function(){
		if(this.isSurveyPage()){
			if(this.isLeadsPage()){
				this.createLeadsMbox();
			}
			if(this.isFulfillmentPage()){
				jQuery.cookie('visitedFulfillment', Customer_Type);
				this.createFulfillmentMbox();
			}
			function quickMboxDefine(mboxName) {
				var divId = mboxName + "-adobe-div";
                var mboxCount = mboxFactoryDefault.getMboxes().get(mboxName).length();
                if (!document.getElementById(divId)&& mboxCount==0) {
                    var div = document.createElement("div");
					div.style.position = "absolute";//adding position: absolute so that it doesnt push down the page, even for a moment//
                    div.id = divId;
                    document.body.insertBefore(div,document.body.firstChild);
                    mboxDefine(divId,mboxName).setFetcher(new mboxAjaxFetcher());
                }
            };
			quickMboxDefine(this.options.surveyName);
			if(jQuery.cookie('mrtgValue')!=null){
				mboxUpdate(this.options.surveyName, this.options.uniqueIdLabel+jQuery.cookie('mrtgValue'),this.options.gmacmLoggedInLabel+userLoggedIn);
			}
			else{
				mboxUpdate(this.options.surveyName,this.options.gmacmLoggedInLabel+userLoggedIn);
			}
		}
	}
};
/*** Header Log On Tab Content ***/
//Check for session cookie and switch header tab content
jQuery.ajax({url: "/checkSessionState.htm",
	type: "post",
	success: function(data){
		setHeaderLogin(data);
		confirmit.onPageLoad();
	 },
	 error: function(xhr, status, errorThrown) {
		//alert(errorThrown+'\n'+status+'\n'+xhr.statusText+'\n test:'+xhr.responseText);
		//alert("response trimmed: "+jQuery.trim( xhr.responseText ));
	}
});	 
jQuery(document).ready(function() {
	if(confirmit.isLeadsPage()){
		confirmit.addSaveOnclick();
	}
});
function setHeaderLogin(data){
	if(data!=null&& data.length>1){
		var allowed = /^[A-Za-z0-9=`+^~()$*,:!@\/ \'\._-]+$/;
		if(allowed.test(data) &&  data.length<54){
			jQuery("#hdrloginname, #hdrloginname_ss").text(data);
		}
		if(jQuery("#wrapper.accounts").length > 0 || (jQuery("#ignore-new-css").length > 0 && location.href.indexOf("/finform") < 0)) { // We are in Self Service or an Enrollment page.
			jQuery("#hdrtabloggedin_ss").css("display","block");
		} else { // We are in storefront or Loss Migitgation.
			jQuery("#hdrtabloggedin").css("display","block");
		}		
		userLoggedIn = 'Y';
		if ("undefined" != typeof(Web_User_Id)){jQuery.cookie('mrtgValue', Web_User_Id);}
	} else {
		jQuery("#hdrtab").css("display","block");
		userLoggedIn = 'N';
	}
}

//log user off of multipe apps on baseweb logoff
if ((window.location.pathname).indexOf('/logoff') != -1){logoffApps();};
function logoffApps(){
	jQuery.ajaxSetup({cache: false});
	jQuery.cookie('mrtgValue', null, { path: '/', expires: -10 });

	jQuery.get("https://" + document.domain + "/finform/resetlogin.htm?source=logoffPage",null,null,"html");
	jQuery.get("https://" + document.domain + "/leads-web/invalidateSession.htm",null,null,"html");
}

//Adding chat values code: lpAddVars('<Scope:page/session/visitor>','<Variable Name>','<Variable Value>');
var chatLP = {
    variables: {
		leads_chat_dd_text_vars: { 'LoanType':'loanType','State':'subjectProperty.address.state','PropertyUse':'subjectProperty.occupancyType','EmploymentStatus':'borrowers[0].borrowerScreen_EmploymentStatus'},
		leads_chat_dd_val_vars: { 'CreditRating':'borrowers[0].ficoScore'},
		leads_chat_val_vars: {'ZipCode':'subjectProperty.address.zipCode','ReservationID':'offerId'},
		leads_chat_val_numeric_vars: {'LoanAmt':'refinance.loanAmount','PropertyValue':'subjectProperty.propertyValue','HomeValue':'subjectProperty.propertyValue'},
		leads_chat_rdo_val: {'PurchaseAgreement':'purchase.purchaseAgreementExistsFlag','CoBorrower':'coborrowerFlag'},
		rate_chat_dd_text_vars: { 'LoanType':'loanType','PropertyType':'propertyType','PropertyUse':'occupancyType','PropertyTax':'impoundToggle'},
		rate_chat_dd_val_vars: { 'CreditRating':'ficodd'},
		rate_chat_val_vars: {'ZipCode':'zipCode'},
		rate_chat_val_numeric_vars: {'LoanAmt':'loanAmount','PropertyValue':'propertyValue'}
	},
	isLeadsPage:function() {
		return urlContainsString("leads-web");
    },
	isAccountsPage:function() {
		return urlContainsString("/accounts/index");
    },
	isCalcPage:function(){
		if(urlContainsString("mortgage-calculators.htm") && !urlContainsString("mortgage-calculators.htm?method=mortgageRentvsBuy")){
			return true;		
		}
		return false;
	},
	isRatesPage:function() {
		return urlContainsString("comparerates");
    },
	passErrorValues:function(errorMessage, errorCount){
		if(errorCount>0){
			lpMTagConfig.vars.push(['ErrorName',errorMessage]); 
			lpMTagConfig.vars.push(['ErrorCounter',errorCount]);
			lpSendData();
		}
	},
	ratesSubmit:function(){
		jQuery('.btn.modal-rc').click(function() { 
			jQuery.each( chatLP.variables.rate_chat_dd_text_vars, function( key,val ) {
				if('Select one' != jQuery('[name=productManager.currentQuery.'+val+'] option:selected').text()){
					lpMTagConfig.vars.push(['session',key,jQuery('[name=productManager.currentQuery.'+val+'] option:selected').text()]); 
				}
			});
			jQuery.each( chatLP.variables.rate_chat_dd_val_vars, function( key,val ) {
				if('Select one' != jQuery('[name=productManager.currentQuery.'+val+'] option:selected').text()){
					lpMTagConfig.vars.push(['session',key,jQuery('[name=productManager.currentQuery.'+val+'] option:selected').val()]); 
				}
			});
			jQuery.each( chatLP.variables.rate_chat_val_vars, function( key,val ) {
				if(jQuery('[name=productManager.currentQuery.'+val+']').val().length>0){
					lpMTagConfig.vars.push(['session',key,jQuery('[name=productManager.currentQuery.'+val+']').val()]); 
				}
			});
			jQuery.each( chatLP.variables.rate_chat_val_numeric_vars, function( key,val ) {
				if(priceAsFloat(jQuery('[name=productManager.currentQuery.'+val+']').val())>0){
					lpMTagConfig.vars.push(['session',key,priceAsFloat(jQuery('[name=productManager.currentQuery.'+val+']').val())]); 
				}
			});
			//add ltv
			if(jQuery('[name=productManager.currentQuery.loanAmount]').length>1 && jQuery('[name=productManager.currentQuery.propertyValue]').length>1 &&
				priceAsFloat(jQuery('[name=productManager.currentQuery.loanAmount]').val())>0 && priceAsFloat(jQuery('[name=productManager.currentQuery.propertyValue]').val())>0){
				lpMTagConfig.vars.push(['session','LTV',(priceAsFloat(jQuery('[name=productManager.currentQuery.loanAmount]').val())/priceAsFloat(jQuery('[name=productManager.currentQuery.propertyValue]').val()))*100]); 
			}
			lpSendData();
		});
		jQuery("#modify-search").click(function() {
			lpMTagConfig.vars.push(['ModifyCounter','1']); 
			lpSendData();
		});
	},
	wlirfmSubmit:function(buyrefi, howmuch){
		if(buyrefi != null){
			lpMTagConfig.vars.push(['session','LoanType',(buyrefi==1)?'Purchase':'Refinance']);
		}
		if(howmuch != null){
			lpMTagConfig.vars.push(['session','LoanAmt',(howmuch==1)?'416000':'420000']);
		}
		lpSendData();
	},
	tabSubmit:function(tab){
		lpMTagConfig.vars.push(['Tabs',tab]);
		lpSendData();
	},
	calcSubmit:function(){
		jQuery('.btn').mousedown(function() {  
			if(this.href.indexOf("mortgageRefinance")!=-1){
				lpMTagConfig.vars.push(['session','LoanType','Refinance']);
				if(jQuery('[name=new_loan_balance]').val()>1 && jQuery('[name=new_loan_appraised_value]').val()>1){
					lpMTagConfig.vars.push(['session','LTV',(priceAsFloat(jQuery('[name=new_loan_balance]').val())/priceAsFloat(jQuery('[name=new_loan_appraised_value]').val())*100)]);
				}
				if(jQuery('[name=new_loan_balance]').val()>0){
					lpMTagConfig.vars.push(['session','LoanAmt',priceAsFloat(jQuery('[name=new_loan_balance]').val())]);
				}
			}
			else if(this.href.indexOf("homeEquity")!=-1){
				if(priceAsFloat(jQuery('#mortgage').val())>1 && priceAsFloat(jQuery('#estimate').val())>1){
					lpMTagConfig.vars.push(['session','LTV',(priceAsFloat(jQuery('#mortgage').val())/priceAsFloat(jQuery('#estimate').val())*100)]);
				}
				if(priceAsFloat(jQuery('#mortgage').val())>0){
					lpMTagConfig.vars.push(['session','LoanAmt',priceAsFloat(jQuery('#mortgage').val())]);
				}
			}
			else{
				if(priceAsFloat(jQuery('[name=loan_amount]').val())>0){
					lpMTagConfig.vars.push(['session','LoanAmt',priceAsFloat(jQuery('[name=loan_amount]').val())]);
				}
			}
			lpSendData();
		});
	},
	addLeadsSaveOnclick:function(){
		jQuery('#saveButton,.btn,.btn2,#saveButtonReview').mousedown(function() {
			jQuery.each( chatLP.variables.leads_chat_dd_text_vars, function( key,val ) {
				if(jQuery('[name='+val+']').length>0 &&
					-1==jQuery('[name='+val+'] option:selected').text().indexOf('Please')){
					if('State'!=key){
						lpMTagConfig.vars.push(['session',key,jQuery('[name='+val+'] option:selected').text()]);
					}
					else{
						theValue = jQuery('[name='+val+'] option:selected').text();
						lpMTagConfig.vars.push(['session',key,StateAbbreviations[theValue.toLowerCase()] || theValue]);
					}
				}
			});
			jQuery.each( chatLP.variables.leads_chat_dd_val_vars, function( key,val ) {
				if(jQuery('[name='+val+']').length>0 &&
					-1==jQuery('[name='+val+'] option:selected').text().indexOf('Please')){
					lpMTagConfig.vars.push(['session',key,jQuery('[name='+val+'] option:selected').val()]);
				}
			});
			jQuery.each( chatLP.variables.leads_chat_val_vars, function( key,val ) {
				if(jQuery('[name='+val+']').length>0 && 
					jQuery('[name='+val+']').val().length>0){
					lpMTagConfig.vars.push(['session',key,jQuery('[name='+val+']').val()]);
				}
			});
			jQuery.each( chatLP.variables.leads_chat_rdo_val, function( key,val ) {
				if(jQuery('[name='+val+']').length>0){
					lpMTagConfig.vars.push(['session',key,('true'==jQuery('[name='+val+']:checked').val())?'Y':'N']);
				}
			});
			jQuery.each( chatLP.variables.leads_chat_val_numeric_vars, function( key,val ) {
				if(jQuery('[name='+val+']').length>0 &&
					priceAsFloat(jQuery('[name='+val+']').val()) > 0) {
					lpMTagConfig.vars.push(['session',key,priceAsFloat(jQuery('[name='+val+']').val())]);
				}
			});
			//add ltv
			if(jQuery('[name=refinance.loanAmount]').length>0 && jQuery('[name=subjectProperty.propertyValue]').length>0 &&
				priceAsFloat(jQuery('[name=refinance.loanAmount]').val())>0 && priceAsFloat(jQuery('[name=subjectProperty.propertyValue]').val())>0){
				lpMTagConfig.vars.push(['session','LTV',(priceAsFloat(jQuery('[name=refinance.loanAmount]').val())/priceAsFloat(jQuery('[name=subjectProperty.propertyValue]').val()))*100]);
			}
			lpSendData();
		});
	},
	surveyPop:function(){
		affHostName = window.location.host;
		var affArray = affHostName.split('.');
		var aff = affArray[1];
		var domainName = affArray[1] + "." + affArray[2];
		document.cookie = 'CHAT_MRTG_SRVY_POP=true' 
				+ '; path=/'
				+ '; domain='+domainName;
	}
};
var priceAsFloat = function (price) {
	return parseFloat(price.replace(/,/g,'').replace(/[^\d\.]/g,''));
}
var urlContainsString = function(url){
	pageUrl = document.location.toString();
	if(location.href.indexOf(url) > 0) return true;
	return false;
}
//add rates vars
if (chatLP.isRatesPage()){
	chatLP.ratesSubmit();
	lpMTagConfig.vars.push(["Section","Rates"]); 
	var pageArray = s.pageName.split(":");
	lpMTagConfig.vars.push(["PageName",pageArray[pageArray.length-1]]);
	//error messages:
	var errorMsgs = "";
	jQuery('.form-alert li').each(function(){
		errorMsgs += jQuery(this).text();
	});
	var errorCount = jQuery('.form-alert li').size();
	chatLP.passErrorValues(errorMsgs, errorCount);
}
else{
	if("undefined" != typeof(SubSection_Om)){
		lpMTagConfig.vars.push(["Section",SubSection_Om])
	} 
	if("undefined" != typeof(Title_Om)){
		lpMTagConfig.vars.push(["PageName",Title_Om])
	}
	if(chatLP.isAccountsPage()){
		lpMTagConfig.vars.push(['session','LoanNumber',jQuery('.acct-no').text()]);
	}
	else if(chatLP.isLeadsPage() && ("undefined" == typeof(rloId)) && ("undefined" == typeof(rloName))){
		lpMTagConfig.vars.push(['Section','ILEAD']);
		lpMTagConfig.vars.push(['PageName',jQuery('#wrapper h2').first().text()]);
		if(loanId != null && loanId.length>0){lpMTagConfig.vars.push(['WebAppId',loanId]);}
		if("undefined" != typeof(jQuery('#wrapper h2').first().text()) && jQuery('#wrapper h2').first().text() == "You're Finished"){
			lpMTagConfig.vars.push(["FormComplete","Y"]); 
		}
		chatLP.addLeadsSaveOnclick();
		ileadErrorCnt = 0;
		ileadErrorMsg='';
		jQuery.each(validationResult.messages, function(i, item) {
			if(validationResult.messages[i].severity=='ERROR'){
				ileadErrorCnt++;
				ileadErrorMsg += validationResult.messages[i].text+";";
			}
		});
		chatLP.passErrorValues(ileadErrorMsg, ileadErrorCnt);
	}
	else if(chatLP.isCalcPage()){
		chatLP.calcSubmit();
	}
}
lpSendData();
jQuery('#sitesearch').submit(function() {
	if(jQuery('.search_field').val().length>0){
		lpMTagConfig.vars.push(['Search',jQuery('.search_field').val()]); 
	}
	lpSendData();
});
jQuery('#sitesearchpage').submit(function() {
	if(jQuery('#sitesearchpage .text').val().length>0){
		lpMTagConfig.vars.push(['Search',jQuery('#sitesearchpage .text').val()]); 
	}
	lpSendData();
});
var StateAbbreviations =
{
  "alabama": "AL",
  "alaska": "AK",
  "arizona": "AZ",
  "arkansas": "AR",
  "california": "CA",
  "colorado": "CO",
  "connecticut": "CT",
  "delaware": "DE",
  "district of columbia": "DC",
  "florida": "FL",
  "georgia": "GA",
  "hawaii": "HI",
  "idaho": "ID",
  "illinois": "IL",
  "indiana": "IN",
  "iowa": "IA",
  "kansas": "KS",
  "kentucky": "KY",
  "louisiana": "LA",
  "maine": "ME",
  "maryland": "MD",
  "massachusetts": "MA",
  "michigan": "MI",
  "minnesota": "MN",
  "mississippi": "MS",
  "missouri": "MO",
  "montana": "MT",
  "nebraska": "NE",
  "nevada": "NV",
  "new hamspire": "NH",
  "new jersey": "NJ",
  "new mexico": "NM",
  "new york": "NY",
  "north carolina": "NC",
  "north dakota": "ND",
  "ohio": "OH",
  "oklahoma": "OK",
  "oregon": "OR",
  "pennsylvania": "PA",
  "rhode island": "RI",
  "south carolina": "SC",
  "south dakota": "SD",
  "tennessee": "TN",
  "texas": "TX",
  "utah": "UT",
  "vermont": "VT",
  "virginia": "VA",
  "washington": "WA",
  "west virginia": "WV",
  "wisconsin": "WI",
  "wyoming": "WY"
};

// insertSpinner: Add "Loading..." modal content to dom.
insertSpinner = function() {
	jQuery("body").prepend("<div id='wrapper' style='display:none;'></div><div class='modal' id='modal-loading'><h2>Loading...</h2><img src='/img/spinner.gif' alt='Loading...' /></div>");
}
// setSpinner: Display "Loading..." modal.
setSpinner = function(){
	jQuery( 'html, body' ).animate( { scrollTop: 0 }, 'fast' );
	jQuery("#loading-1").trigger('click');	
} 
	
jQuery(document).ready(function () {
// rates condo fix
// remove "condominium" from the "property-type" drop-down temporarily
    jQuery("select[name=productManager.currentQuery.propertyType] option[value='3']").remove();
	if (location.href.indexOf("leads-web") > 0) {
		insertSpinner();
		jQuery("a.btn:contains('next step')").click(function(){setSpinner();})
		jQuery("a.btn:contains('submit this loan request')").click(function(){setSpinner();})
	}
});
