



var isIE = navigator.userAgent.indexOf("MSIE")!=-1&&navigator.userAgent.toLowerCase().indexOf("opera")==-1;
var isFF=navigator.userAgent.indexOf("Firefox")!=-1;
var mainForm=null;

function getElement(attrName){
    return isIE?document.getElementById(attrName):getForm().elements[attrName];
};

function nonemptyStringRule(attrName, errorMessage) {
	return notThisValueRule(attrName, errorMessage, "");
};

function notThisValueRule(attrName, errorMessage, valToCheck){
    var elm=getElement(attrName);
    var stringValue=elm.value.trim();
    if (stringValue==valToCheck){
        elm.focus();
        if (elm.type=='text')elm.select();
        if(!checkVal||(checkVal&&validationError_S==1)) alert(errorMessage);
        return false;
    }
    if(checkVal&&validationError_S>=2) changeDisplay(attrName);
	return true;
};

function getForm(){
		if(mainForm!=null) return mainForm;
    var mForm=null;
		for (var i=0;i<document.forms.length; i++) {
			if(document.forms[i].name=="subrfq_1"||document.forms[i].name=="p1Form")
				mForm=document.forms[i];
		}
     if(mForm==null) mForm=document.forms[0];
     mainForm=mForm; 
     return mForm;     
};

function nonemptyStringsRule(errorMessage, numFields){
    var attr=arguments[2];
    var ok=false;
    for (var i=2;i<2+numFields; i++) {
        if (stringAttrValue(arguments[i])!="")ok=true;
    }
    if (!ok) {
        var elm=getElement(attr);
        elm.focus();
        if (elm.type=='text')elm.select();
        alert(errorMessage);
		return false;
    }
    return true;
};

function nonemptyRadioButtonRule(attrName, errorMessage) {
	var grp = getForm().elements[attrName];
    if (grp.length==0)return true;

    for (var ix=0;ix<grp.length;ix++){
        if (grp[ix].type=='hidden'||grp[ix].checked){
        	if(checkVal&&validationError_S>=2) changeDisplay(attrName);
        	return true;
        }
    }
	if(!checkVal||(checkVal&&validationError_S==1)) alert(errorMessage);
	grp[0].focus();
	return false;
};

function privacyRule(attrName, errorMessage){
    var elm=getElement(attrName);
    if (!elm.checked){
        alert(errorMessage);
        return false;
    }
    return true;
};

function stringAttrValue(attrName){
    return getElement(attrName).value.trim();
};

function numberAttrValue(attrName){
	return parseFloat(stringAttrValue(attrName));
};

function cleanUp(unclean) {
    var cleaned="",c;
    for (var i=0;i<unclean.length;i++){
        c=unclean.charAt(i);
        if (c=='.')break;
        if (c>='0'&&c<='9')
            cleaned+=c;
    }
    return cleaned;
};

function addCommasNoEvent(field) {
  	var newString=cleanUp(field.value);
  	if (newString.length>3){
		var i=newString.length;
		while(i-3>0){
			i=i-3;
			newString=newString.substring(0,i)+","+newString.substring(i);
		}
  	}
	field.value=newString;
};

function addCommasValue(value) {
	var newString=cleanUp(value);
   	if (newString.length>3){
       var i=newString.length;
       while(i-3>0){
        	i=i-3;
            newString=newString.substring(0, i)+","+newString.substring(i);
       }
    }
    value=newString;
    return newString;
};

function addCommas(field) {
    if (isIE){
        if (event!=null)addCommasNoEvent(field);
    }
    else addCommasNoEvent(field);
};

function numOnly(elm){elm.value=elm.value.replace(/[^0-9]/g, "");};

function popWindow(url,title,scroll,resz,w,h){
    var prop = "toolbar=no,menubar=no,directories=no,location=no,status=no,scrollbars="+scroll+",resizable="+resz+",width="+w+",height="+h;
    window.open(url,title,prop);
};

function pushBelowFold(el) {
    var div=document.getElementById(el);
    if(div==null) return;
    if(div.style.position=="relative"){
	div.style.display="none";
	}
    var winH=0;
    var bodyH=bodyHt();
    var elH=0;
    if(typeof(div.offsetHeight)=="number"){elH=div.offsetHeight;}
    if(typeof(window.innerWidth)=="number"){winH=window.innerHeight;}
    else if(document.documentElement&&(document.documentElement.clientHeight))winH=document.documentElement.clientHeight;
    else if(document.body&&(document.body.clientHeight))winH=document.body.clientHeight;
	if(div.style.position=="relative"){
	div.style.display="block";
	}else{
	bodyH=bodyH-elH;
	div.style.position="relative";
	}
    if(winH<=bodyH){
   	 winH=0;
    }else{
    winH=winH-bodyH;
    }
    div.style.marginTop=winH+"px";
};

function bodyHt() {
	var sht = document.body.scrollHeight;
	var oht = document.body.offsetHeight;
	if (sht > oht) return sht;
		
	return oht;
};

[].indexOf || (Array.prototype.indexOf = function(v,n){
  n = (n==null)?0:n; var m = this.length;
  for(var i = n; i < m; i++)
    if(this[i] == v)
       return i;
  return -1;
});

function isDigit(c) {
	if (c.length==1){
		var string='1234567890';
		if (string.indexOf(c)!=-1) return true;
	}
	return false;
};

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";

	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
};

function setCheckedValue(radioObj, newValue) {
	if(!radioObj) return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		if (radioObj[i].type == 'hidden' || radioObj[i].type == 'HIDDEN'){
				radioObj[i].value = newValue.toString();		
				return;
		}
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
};

function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }
  return elements;
};

function expandSelect(opt, curWid, expand){
    if(!needExp(opt, curWid)) return;
   	if (expand) {
        opt.style.position = 'absolute';
        opt.style.width = 'auto';
    } else {
        opt.style.position = 'relative';
        opt.style.width = curWid;
    }
};

function expandSelect2(opt, curWid, expand){
   	if(!needExp(opt, curWid)) return;
   	opt.style.position = 'relative';
   	if (expand) opt.style.width = 'auto';
    else opt.style.width = curWid;
};

function needExp(opt, curWid){
	if(!isIE) return false;
	var needsExp = false;
	for(var i=0;i < opt.options.length; i++) {
		if (opt.options[i].text.length*7.5 > curWid) {
          	needsExp = true;
        }
    }       
   	return needsExp;
};

function fixDD(opt, curWid){
	if(!isIE || !opt.options) return;
	var numCharsVis = Math.round(curWid/7.5);
	for(var i=0;i < opt.options.length; i++) {
		var dispText = opt.options[i].text;
		if (dispText.length > numCharsVis) {
          	opt.options[i].text = dispText.substring(0, numCharsVis) + ' ..';
        }
    }
};

function changeZipAttributes(){
	zipc=document.getElementById('zipcode');
	if(zipc==null) return;
 	if(document.getElementById('country').value!="US"){
    	zipc.size="10";
    	zipc.maxLength="10";
   	}else{
    	zipc.size="5";
    	zipc.maxLength="5";
    }
};
function viewDesc(url, winName) {
    if (url) popWindow(url, winName,"yes","yes","800","600"); 
};

function viewPrivacyStatement(url) {
    if (!url)url="/buyer/help/prPrivacyPolicy.jsp";
    popWindow(url,"privacystatement","yes","yes","800","600");
};

function viewCalibexPrivacyStatement(url) {
    if(!url ) url = "/serv/calibex2/buyer/help/calibexPrivacyPolicy.jsp";
    else if('1' == url ) url = "/serv/calibex1/buyer/help/calibexPrivacyPolicy.jsp";
    popWindow(url,"privacystatement","yes","yes","805","600");
};

function trim(str){return str.replace(/^\s*|\s*$/g,"");};
function rtrim(str) { return str.replace(/\s+$/, '');};
function ltrim(str){ return str.replace(/^\s+/, '');};

function isFirstLetterVowel(str){
	firstChar = str.toLowerCase().substring(0, 1);
	vowels = 'aeiou';
	return vowels.indexOf(firstChar)!=-1;
};

function getFieldValue(field) {
	fieldObj = getForm()[field];
	if(!fieldObj) return '';

    tagType = fieldObj.type;
    tag = fieldObj.tagName;

    if( tag == "SELECT" || (tag=="INPUT" && tagType=="text" ))
        return  fieldObj.value;

	if( fieldObj.length > 1)
        return getCheckedValue(fieldObj);

    return '';
};


function onMOverSel(eventObj, sel){
	if (eventObj) sel.focus();
	
};

function onMOutSel(win){
	if (win.event && win.event.toElement != null) win.focus();
};
        function NxtgHttpReq (url, options_){
	var options = {
		async: true,
		cb: null,
		handler: null,
		method: 'GET',
		contentType: null
	};

	if (options_){
		if (options_.async) { options.async = options_.async; }
		if (options_.cb) { options.cb = options_.cb; }
		if (options_.handler) { options.handler = options_.handler; }
		if (options_.method) { options.method = options_.method; }
		if (options_.contentType) { options.contentType = options_.contentType; }
	}

	var xhr = null;

	this.getURL = function(){return url;};
	this.setPost = function(){ options.method = 'POST';};
	this.setAsynchronous = function(async){ options.async = async; };
	this.getData = function(){
		if (xhr)
			return xhr.responseText;
		return null;
	};

	this.getStatus = function (){
		if (xhr)
			return xhr.status;
		return 0;
	};

	this.setAsynchronous = function(async){ options.async = async; };

	this.getXHR = function(){return xhr;};

	this.send = function(c){
		if(xhr && xhr.readyState!=0){
			xhr.abort();
		}
		try{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(sc) {
				xhr = null;
			}
		}
		if(!xhr && typeof XMLHttpRequest!="undefined"){
			xhr = new XMLHttpRequest()
		}
		if (options.cb || options.handler){
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					if (xhr.status == 200){
						if (options.cb)
							options.cb(xhr.responseText, xhr.responseXML);
						if (options.handler && options.handler.procdata)
							options.handler.procdata(xhr.responseText, xhr.responseXML);
					}
				}
			};
		}
		if(xhr){
			xhr.open(options.method,this.getURL(),options.async);
			var content = null;
			if (options.method == 'POST')
				content = c;
			if (options.contentType)
				xhr.setRequestHeader("Content-Type", options.contentType);
			xhr.send(content);
		}
	};
};


        function looksLikeAnAreacode(field1, field2){
    var elm=getElement(field1);
    var field1Value=cleanUp(elm.value.trim());
	if (field1Value.length==5){
        elm.focus();
        alert(field2);
        return false;
	}
	return true;
}

var alertedBefore=false;
function validateDownPayment(field1, field2, field3){
	var ABfield=document.getElementById("alertedBefore")
	var alertedBefore=false;
	if(stringAttrValue("alertedBefore")=="true")
		alertedBefore=true;
	var field1val=cleanUp(stringAttrValue(field1));
	var field2val=stringAttrValue(field2);
	var field3val=cleanUp(stringAttrValue(field3));
	var calculatedVal=Math.ceil(field1val * field2val /100);
	if (!alertedBefore&&field3val<calculatedVal){
		alertedBefore=true;
		ABfield.value="true";
		var calculatedValString=""+calculatedVal;
		var newString="";
	  	if (calculatedValString.length>3){
			var i=calculatedValString.length;
			while(i-3>0){
				i=i-3;
				calculatedValString=calculatedValString.substring(0, i)+","+calculatedValString.substring(i);
			}
	  	}
		alert("We can match you with more lenders if you can put at least $"+ calculatedValString +" down ("+field2val+"% of the estimated property value).");
		if (isIE){
			subrfq_1.downPayment.select();
		}
        popup = true;
		return false;
	}
	return true;
}

function phoneNumberRule(attr1, attr2, errorMessage){
    var elm=getElement(attr1);
    var stringValue=elm.value.trim();
	var stringValue2=stringAttrValue(attr2);
	if (stringValue==""&&stringValue2==""){
        elm.focus();
        if (elm.type=='text')elm.select();
		alert(errorMessage);
		return false;
	}
	return true;
}

function nondefaultCreditRule(attrName, errorMessage){
    var elm=getElement(attrName);
    var stringValue=elm.value.trim();
    if (stringValue==""||stringValue=="Select One"||stringValue=="Select"){
        elm.focus();
        if(!checkVal||(checkVal&&validationError_S==1)) alert(errorMessage);
		return false;
    }
    if(checkVal&&validationError_S>=2) changeDisplay(attrName);
	return true;
}

function computedownpayment() {
	var estvalue = parseInt(cleanUp(document.getElementById("estValue").value));
	var downpayment = document.getElementById("downPayment");
	var result = 0;

	result = parseInt(estvalue / 10);

	if (parseInt(cleanUp(downpayment.value)) > result) {
		result = downpayment.value;
	}

	downpayment.value = result;
	addCommasNoEvent(downpayment);
}

function estValueChange() {
	var downPaymentValue = document.getElementById("downPayment").value;

	document.getElementById("downPayment_rec").innerHTML =
		"(min. " + downPaymentValue + " recommended)";
}

var stateVarName;
var areacodeVarName;
function getStateInfoByZipCode(zipCode, stateVar){
    zipCode = trim(zipCode);
	stateVarName = stateVar;
	if(zipCode.length != 5) return;
    params = 'zip=' + zipCode;

	var options={cb:processGetObject};
    new NxtgHttpReq("/buyer/rfq/resources/getObject.jsp?"+params, options).send();
}

function getStateInfoByAreaCode(areaCode, stateVar){
    areaCode = trim(areaCode);
	stateVarName = stateVar;
	if(areaCode.length != 3) return;
    params = 'areacode=' + areaCode;

	var options={cb:processGetObject};
    new NxtgHttpReq("/buyer/rfq/resources/getObject.jsp?"+params, options).send();
}

function getAreaCodeInfoByZip(zipCode, areaCodeVar){
	zipCode = trim(zipCode);
    areacodeVarName = areaCodeVar;
    if(zipCode.length != 5) return;
    params = 'zip=' + zipCode + '&func=getAreaCode';
    var options={cb:processAreaCodeXML};
    new NxtgHttpReq("/buyer/rfq/resources/getObject.jsp?"+params, options).send();
}

var stateStyle;
function getStateInfo2(zipCode,len,style){
    stateStyle=style;
    if(zipCode.length != len) {
        document.getElementById('state1').innerHTML = "";
   		document.getElementById('state').value = "Select";
        return;
    }

	if(len == 3) {
		getStateInfoByAreaCode(zipCode);
	} else if(len == 5) {
		getStateInfoByZipCode(zipCode);
	}
}

function processGetObject(respText,respXml){
    var info=respXml.documentElement.getElementsByTagName("info")[0].firstChild.nodeValue;
    if(info != "-1") {
		if(stateVarName == undefined) {
			stateVarName = 'state';
		}
		document.getElementById(stateVarName).value = info;

        if (stateStyle==2){
            document.getElementById('state1').innerHTML=" in "+info;
        }else if (stateStyle==3){
            document.getElementById('state1').innerHTML=" in "+
                document.getElementById('state').options[document.getElementById('state').selectedIndex].innerHTML;
        }
    }
}

function processAreaCodeXML(respText,respXml){
	
    info=respXml.documentElement.getElementsByTagName("info")[0].firstChild.nodeValue;
    if(info != "-1") {
		if(areacodeVarName == undefined) {
			areacodeVarName = 'homePhone1';
		}
		document.getElementById(areacodeVarName).value = info;
    }
}

function logRecPop(estValue, fstMortBal, secMortBal, cashOut, logType){
	var options=null;
	if(logType==1) options={cb:processLog};
	var url='/buyer/rfq/resources/getObject.jsp?func=logrecpop&estValue='+estValue+'&fstMortBal='+fstMortBal+'&secMortBal='+secMortBal+'&cashOut='+cashOut+'&logType='+logType;
  new NxtgHttpReq(url,options).send();
}

function processLog(respText,respXml){
}
        function validate (){
	switch (type2){
	case "CobrandUtils.MortgageLoan":
        foundHome = document.getElementsByName('foundhome');
        evaluatePurchaseContract = (evaluateFoundHome && foundHome[0].checked && foundHome[0].value == 'true');

        if ((evaluateAreaCode&&!nonemptyStringRule("areacode", "Please enter your property's area code."))||
            (evaluateAreaCode&&!looksLikeAnAreacode("areacode", "It appears that you are trying to enter a zipcode.  Please enter your *areacode*."))||
            (evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))||
            (evaluateFirstTimeBuyer&&!nonemptyRadioButtonRule("firstTimeBuyer", "Please indicate if you are a first time buyer."))||
            (evaluateFoundHome&&!nonemptyRadioButtonRule("foundhome", "Please indicate whether you have found a home."))||
            (evaluatePurchaseContract&&!nonemptyRadioButtonRule("purchaseContract", "Please indicate if you have a purchase contract."))||
            (evaluateRealtor&&!nonemptyRadioButtonRule("realtor", "Please indicate whether you have a real estate agent."))||
            (evaluateEstValue&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))||
            (evaluateDownPayment&&!nonemptyStringRule("downPayment", "Please enter the down payment."))||
            (evaluateLoanRate&&!nonemptyRadioButtonRule("rateType", "Please indicate whether you would prefer a fixed or variable loan."))||
            (evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))||
            (evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))||
            (evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))||
            (!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))||
            (evaluateWhenNeedLoan&&!nonemptyStringRule("whenNeedLoan", "Please indicate how soon you want to close this loan."))||
            (evaluateDownPayment&&!validateDownPayment("estValue", "recommendedPercentage", "downPayment"))){
			return false;
		}
		break;
	case "CobrandUtils.MortgageRefinance":
        if ((moreQuestions&&!nonemptyStringRule("loanPurpose", "Please enter your loan purpose."))||
            (evaluateZip&&!nonemptyStringRule("propertyzip", "Please enter the zip code of your property."))||
            (evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))||
            (evaluateEstVal&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))||
            (moreQuestions&&!nonemptyStringRule("purchaseYear", "Please enter the year you purchased your property."))||
            (evaluateFstMortBal&&!nonemptyStringRule("fstMortBal", "Please enter your mortgage balance."))||
            (evaluateMonthPayment&&!nonemptyStringRule("monthPayment", "Please enter your monthly mortgage payment."))||
            (evaluateInterestRate&&!nonemptyStringRule("interestRate", "Please enter a valid interest rate."))||
            (evaluateRefiType&&!nondefaultCreditRule("refinanceType", "Please select a mortgage."))||
            (evaluateLoanRate&&!nonemptyRadioButtonRule("loanRate", "Please indicate whether you would prefer a fixed or variable loan."))||
            (evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))||
            (evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))||
            (evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))||
            (!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))){
            return false;
        }
		break;
	case "CobrandUtils.HomeEquity":
        if ((moreQuestions&&!nonemptyStringRule("loanPurpose", "Please enter your loan purpose."))||
            (evaluateZip&&!nonemptyStringRule("propertyzip", "Please enter the zip code of your property."))||
            (evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))||
            (evaluateEstVal&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))||
            (moreQuestions&&!nonemptyStringRule("purchaseYear", "Please enter the year you purchased your property."))||
            (evaluateFstMortBal&&!nonemptyStringRule("fstMortBal", "Please enter your mortgage balance."))||
            (evaluateMonthPayment&&!nonemptyStringRule("monthPayment", "Please enter your monthly mortgage payment."))||
            (evaluateInterestRate&&!nonemptyStringRule("interestRate", "Please enter a valid interest rate."))||
            (evaluateCashOut&&!nonemptyStringRule("cashOut", "Please enter the size of the new equity loan."))||
            (evaluateLoanRate&&!nonemptyRadioButtonRule("loanRate", "Please indicate whether you would prefer a fixed or variable loan."))||
            (evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))||
            (evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))||
            (evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))||
            (!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))){
			return false;
        }
		break;
	case "PersonalInfoMini":
	case "PersonalInfoMiniCalibex":
        if (!nonemptyStringRule("firstName", "Please enter your first name.")||
            !nonemptyStringRule("lastName", "Please enter your last name.")||
            !nonemptyStringRule("address1", "Please enter your street address.")||
            !nonemptyStringRule("city", "Please enter your city.")||
            !nonemptyStringRule("zipcode", "Please enter your zip code.")||
            !phoneCheck("Please enter your phone number.")){
			return false;
		}
		break;
	}
	return true;
}

function AValidate (){
if (evaluateDownPayment&&!validateDownPayment("estValue", "recommendedPercentage", "downPayment")){
			return false;
	}
	return true;
}
function NAValidate (){
	switch (type2){
	case "CobrandUtils.MortgageLoan":
        foundHome = document.getElementsByName('foundhome');
        evaluatePurchaseContract = (evaluateFoundHome && foundHome[0].checked && foundHome[0].value == 'true');

        if ((evaluateWhenNeedLoan&&!nonemptyStringRule("whenNeedLoan", "Please indicate how soon you want to close this loan."))
        	|(!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))
        	|(evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))
        	|(evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))
        	|(evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))
        	|(evaluateLoanRate&&!nonemptyRadioButtonRule("rateType", "Please indicate whether you would prefer a fixed or variable loan."))
        	|(evaluateDownPayment&&!nonemptyStringRule("downPayment", "Please enter the down payment."))
        	|(evaluateEstValue&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))
        	|(evaluateRealtor&&!nonemptyRadioButtonRule("realtor", "Please indicate whether you have a real estate agent."))
        	|(evaluatePurchaseContract&&!nonemptyRadioButtonRule("purchaseContract", "Please indicate if you have a purchase contract."))
        	|(evaluateFoundHome&&!nonemptyRadioButtonRule("foundhome", "Please indicate whether you have found a home."))
        	|(evaluateFirstTimeBuyer&&!nonemptyRadioButtonRule("firstTimeBuyer", "Please indicate if you are a first time buyer."))
        	|(evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))
        	|(evaluateAreaCode&&!nonemptyStringRule("areacode", "Please enter your property's area code."))
            ){
            doCS();
			return false;
		}else{
			revDis();
			return AValidate();
		}		
		break;
	case "CobrandUtils.MortgageRefinance":
        if ((!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))|
        	(evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))|
        	(evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))|
        	(evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))|
        	(evaluateLoanRate&&!nonemptyRadioButtonRule("loanRate", "Please indicate whether you would prefer a fixed or variable loan."))|
        	(evaluateRefiType&&!nondefaultCreditRule("refinanceType", "Please select a mortgage."))|
        	(evaluateInterestRate&&!nonemptyStringRule("interestRate", "Please enter a valid interest rate."))|
        	(evaluateMonthPayment&&!nonemptyStringRule("monthPayment", "Please enter your monthly mortgage payment."))|
        	(evaluateFstMortBal&&!nonemptyStringRule("fstMortBal", "Please enter your mortgage balance."))|
        	(moreQuestions&&!nonemptyStringRule("purchaseYear", "Please enter the year you purchased your property."))|
        	(evaluateEstVal&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))|
        	(evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))|
        	(evaluateZip&&!nonemptyStringRule("propertyzip", "Please enter the zip code of your property."))|
        	(moreQuestions&&!nonemptyStringRule("loanPurpose", "Please enter your loan purpose."))            
            ){
            doCS();
            return false;
        }
		break;
	case "CobrandUtils.HomeEquity":
        if ((!emailOnSecondPage&&!nonemptyStringRule("email", "Please enter a valid email address."))|
        	(evaluateOweEachMonth&&!nonemptyStringRule("oweEachMonth", "Please enter your monthly debt."))|
        	(evaluateGrossIncome&&!nonemptyStringRule("grossIncome", "Please enter your annual gross income."))|
        	(evaluateCredit&&!nondefaultCreditRule("credit", "Please select a credit status."))|
        	(evaluateLoanRate&&!nonemptyRadioButtonRule("loanRate", "Please indicate whether you would prefer a fixed or variable loan."))|
        	(evaluateCashOut&&!nonemptyStringRule("cashOut", "Please enter the size of the new equity loan."))|
        	(evaluateInterestRate&&!nonemptyStringRule("interestRate", "Please enter a valid interest rate."))|
        	(evaluateMonthPayment&&!nonemptyStringRule("monthPayment", "Please enter your monthly mortgage payment."))|
        	(evaluateFstMortBal&&!nonemptyStringRule("fstMortBal", "Please enter your mortgage balance."))|
        	(moreQuestions&&!nonemptyStringRule("purchaseYear", "Please enter the year you purchased your property."))|
        	(evaluateEstVal&&!nonemptyStringRule("estValue", "Please enter your estimated property value."))|
        	(evaluateState&&!nondefaultCreditRule("state", "Please select a property location."))|
        	(evaluateZip&&!nonemptyStringRule("propertyzip", "Please enter the zip code of your property."))|       	
        	(moreQuestions&&!nonemptyStringRule("loanPurpose", "Please enter your loan purpose."))
            ){
            doCS();
			return false;
        }
		break;
	case "PersonalInfoMini":
	case "PersonalInfoMiniCalibex":
        if (!phoneCheck("Please enter your phone number.")|
        	!nonemptyStringRule("zipcode", "Please enter your zip code.")|
        	!nonemptyStringRule("city", "Please enter your city.")|
        	!nonemptyStringRule("address1", "Please enter your street address.")|
        	!nameVal()      	         
            ){
            doCS();
			return false;
		}
		break;
	}
	return true;
}

function nameVal(){
if(nonemptyStringRule("firstName", "Please enter your first name.")
	&&nonemptyStringRule("lastName", "Please enter your last name.")){
	 changeDisplay("name");
	 return true;
}

return false;
}
function phoneCheck(errorMessage){
	var homePhoneValue = "";
	var busPhoneValue = "";
	var prevHomePhoneValue = "";
	var prevBusPhoneValue = "";
	var showAlert = false;
	var fieldNum = 1;
	var hpp=false;
	var bpp=false;
	for (var i=1; i<=3 && !showAlert  ;i++){
		prevHomePhoneValue = homePhoneValue;
		prevBusPhoneValue = busPhoneValue;
		homePhoneValue = stringAttrValue("homePhone"+i);
		busPhoneValue = stringAttrValue("busPhone"+i);
		if (homePhoneValue=="" && busPhoneValue==""){
			showAlert = true;
			fieldNum = i;
		}else{
			if(homePhoneValue!="") hpp=true;
			else hpp=false;
			if(busPhoneValue!="") bpp=true;
			else bpp=false;
		}
		
	}

	if (showAlert){
		var elm = getElement("homePhone1");
		if (fieldNum==1 || (prevHomePhoneValue !="" && prevBusPhoneValue !=""))
			elm=getElement("homePhone1");
		else
			if (prevHomePhoneValue=="")
				elm=getElement("busPhone"+fieldNum);
			else
				elm=getElement("homePhone"+fieldNum);
		
		elm.focus();
        if (elm.type=='text')
        	elm.select();		
        	
	if(!checkVal||(checkVal&&validationError_S==1)) alert(errorMessage);
			
		return false;
	}
	if(checkVal&&validationError_S>=2){
	 if(hpp) changeDisplay("homePhone");
	 if(bpp) changeDisplay("busPhone");
	}
	return true;
	
}

        var url = "";
var channel="main";
var browserName=navigator.appName;//seems to be unused
var browserVer=parseInt(navigator.appVersion);//seems to be unused
var productTypeValue = "";
var rfqIDValue = "";
var scStyleTypeValue = ""; 
var publisherIdValue = "";
var visitIdValue = "";
var ipValue = ""; 
var initi = false;
var nxtgReq;

function processFields() {
  var unloadHandler = (window.onunload)? window.onunload: function() {};
  var onBeforeUnloadHandler = (window.onbeforeunload)? window.onbeforeunload: function() {};
  window.onbeforeunload = function() {sendRequest(), onBeforeUnloadHandler()};
  if(isIE){
  	window.onunload = function() {unloadHandler(), cleanUpXhr()};
  }else{
  	window.onunload = function() {sendRequest(), unloadHandler()};
  }
  var browserName=navigator.appName;

  if (browserName!='Microsoft Internet Explorer') {
    document.captureEvents(Event.CHANGE);
    document.captureEvents(Event.FOCUS);
    document.captureEvents(Event.BLUR);
  }

  var onchangeglobaldownpayment;
  var onchangePropertyZip;

  var objForm = getForm();
  var objField = objForm.elements;
  for (var i=0; i<objField.length; i++){
    if (objField[i].id || objField[i].name) {
      var objId = objField[i].id;
      var objName = objField[i].name;
      if (objField[i].onchange!=null) {        	
       if (objId == "state" || objName == "state") {
            objField[i].onchange = ajaxRedirectUser3;
        }else{
       		document['prCh'+(objId?objId:objName)] = objField[i].onchange;
       		objField[i].onchange = function(event) {handleEvent(event), document['prCh'+(getEventSrcIdOrName(event))]()};
       	}
      }else {
        	//fixme should check if the function is autoTab or not
        	if (objField[i].onkeyup &&
            	!(objField[i].id == "propertyzip" ||  objField[i].id == "areacode" || //for 'propertyzip' and 'areacode'we want to log the event
              	objField[i].name == "propertyzip" || objField[i].name == "areacode")) {
            	//do not set onchange as autoTab will call handle event
        	}else{
            	objField[i].onchange=handleEvent;
        	}
      }
      if (objField[i].type == "submit" || objField[i].type == "button" ) {
      	if (objField[i].onclick!=null) {
       		document['prCl'+(objId?objId:objName)] = objField[i].onclick;
       		objField[i].onclick = function(event) {handleEvent(event), document['prCl'+(getEventSrcIdOrName(event))]()};
       	}else{
            objField[i].onclick=handleEvent;
       	}
      }
    }
  }
}

function sendRequest() {
	if(url == '') return;
    var options = {method:'POST',contentType:'application/x-www-form-urlencoded'};
	var dat = new Date();
	var rndStr = dat.getTime();
	var rfqUserEvtUrl = '/rfquserevent?rnd=' + rndStr;
	nxtgReq = new NxtgHttpReq(rfqUserEvtUrl, options);
    nxtgReq.send(url);
}

function cleanUpXhr(){
	try{
		if(nxtgReq){
			var xhr = nxtgReq.getXHR();
			nxtgReq.getStatus();
			if(xhr && isIE){
			 	xhr.abort();
			 	xhr = null;
			}
		}
	}catch(e){
	
	}
}

function handleEvent(event) {
	setCommonVars();
    var eventSrcID = getEventSrcIdOrName(event);
    var eventtype = (isIE)?window.event.type:event.type;
    var inputElement = getEventSrc(event);
    var newValue = inputElement.value;
    if (inputElement.type == "checkbox" && inputElement.name.indexOf("node")!=0) {
        newValue = ""+inputElement.checked;
    }
    logEvent(eventtype, eventSrcID, newValue);
}

function setCommonVars(){
	if(initi) return;
    var myForm=getForm();
    if (myForm.mortgageChoice) {
        productTypeValue = myForm.mortgageChoice.value
    }else if (myForm.rfqType) {
        productTypeValue = myForm.rfqType.value
    }
    if (document.ajaxRequests){
	    if (document.ajaxRequests.rfqIDValue){
		    rfqIDValue=document.ajaxRequests.rfqIDValue.value;
	    }
	    if (document.ajaxRequests.scStyleTypeValue){
		    scStyleTypeValue=document.ajaxRequests.scStyleTypeValue.value;
	    }
	    if (productTypeValue == "" && document.ajaxRequests.productTypeValue){
		    productTypeValue = document.ajaxRequests.productTypeValue.value;
	    }
	    if (document.ajaxRequests.publisherIdValue){
		    publisherIdValue=document.ajaxRequests.publisherIdValue.value;
	    }
	    if (document.ajaxRequests.visitIdValue){
		    visitIdValue=document.ajaxRequests.visitIdValue.value;
	    }
	    if (document.ajaxRequests.ipValue){
		    ipValue=document.ajaxRequests.ipValue.value;
	    }
    }
    initi = true;
}

function logDumEvent(eventtype, eventSrcID, newValue){
	setCommonVars();
	logEvent(eventtype, eventSrcID, newValue);
}

function logEvent(eventtype, eventSrcID, newValue){
    var dateStr = getDateStr();
	url = url + "&productTypeValue="+productTypeValue+"&rfqIDValue="+rfqIDValue+"&scStyleTypeValue="+scStyleTypeValue+"&publisherIdValue="+publisherIdValue+"&visitIdValue="+visitIdValue+"&ipValue="+ipValue+"&time="+dateStr+"&event="+eventtype+"&element="+eventSrcID+"&newValue="+newValue.trim().escape();
}

function getDateStr(){
    var eventDate = new Date();
    var dateStr = (eventDate.getUTCMonth()+1)+"-"+eventDate.getUTCDate()+"-"+eventDate.getUTCFullYear()+" "+ eventDate.getUTCHours()+":"+eventDate.getUTCMinutes()+":"+eventDate.getUTCSeconds();
    return dateStr;
}

function getEventSrc(event){
    var eventSrc;
	if (!event) event = window.event;
	if (event.target) eventSrc = event.target;
	else if (event.srcElement) eventSrc = event.srcElement;
	if (eventSrc.nodeType == 3)
		eventSrc = eventSrc.parentNode;
    return eventSrc;
}

function getEventSrcIdOrName(event){
    var eventSrc = getEventSrc(event);
    return eventSrc.id?eventSrc.id:eventSrc.name;
}

function ajaxRedirectUser3(event) {
    var state = '';
    if (event) {
        state = event.target.value;
    }else {
        state = window.event.srcElement.value
    }
    handleEvent(event);
    redirectUser3(state);
}

function calcTime(localTime) {
    //server time UTC offset in hours
    offset = 420;
    nd = new Date(localTime.getTime() + (localTime.getTimezoneOffset()-offset) * 60000);
    return nd;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.escape = function() {return escape(this);};

function autoRefresh() {
    setTimeout("checkIfRefresh(true)",540000);
    if($('submit_button')) $('submit_button').disabled = false;
}

function checkIfRefresh(doRefresh) {
    shouldPop = false;
    if(doRefresh) {
        if (navigator.vendor && navigator.vendor.indexOf("Apple") != -1) {
            $('cmd').value = 'refresh';
            getForm().submit();
        }
        else {
            sendDummyRequest();
        }
    }
}

function sendDummyRequest() {
    var nhr=new NxtgHttpReq("/rfquserevent?1=1");
    nhr.setPost();
    nhr.send();
    setTimeout("sendDummyRequest()",540000);
}

        var alreadySubmitted = 0;
var alreadyRedirected=false;
var alreadyRedirected2=false;
var checkVal=	false;
var uagent = navigator.userAgent.toLowerCase();
var appver = "";
if (navigator.appVersion) appver = navigator.appVersion.substring(0,1);

function showTip(ctrl, tiptext) {
    var tipdiv;
    if (isIE && appver>3) {
        ctrl.title = tiptext;
    } else {} //other browser
}
function hideTip() {}

function populateSecMortAndCashOut() {
    estValue = document.getElementById('estValue');
    fstMort = document.getElementById('fstMortBal');
    secMort = document.getElementById('secMortBal');
    addCash = document.getElementById('cashOut');

    if( estValue.value == '') estValue.value = '0';
    if( fstMort.value == '') fstMort.value = '0';
    if( secMort.value == '') secMort.value = '0';
    if( addCash.value == '') addCash.value = '0';

    diff = parseInt(estValue.value) * 1.25 - parseInt(fstMort.value);

    secMort.options.length = 0;
    addCash.options.length = 0;

    counter = 2;
    secMort.options[0] = new Option('Select', '');
    addCash.options[0] = new Option('Select', '' );
    secMort.options[1] = new Option('0', '0');
    addCash.options[1] = new Option('0', '0');
    range = 10000;
    total = 0;

    while( total < diff ) {
        midpt = Math.round( total +  range * .5 );
        secMort.options[counter] = new Option( addCommasValue((1+total) + '') + '-' + addCommasValue( (total+range) + '' ), midpt );
        addCash.options[counter] = new Option( addCommasValue((1+total) + '') + '-' + addCommasValue( (total+range) + ''), midpt );
        counter++;
        total = total + range;
    }
}

function checkTotalMortValueIs100k() {

    if( document.getElementById('pageToRender').value == "1" )
        return;

    if( (document.getElementById('fourPages').value == 'true' &&
            (document.getElementById('pageToRender').value == "1" || document.getElementById('pageToRender').value == "2")))
        return;

    estValue =  document.getElementById('estValue').value;
    fstMort =  document.getElementById('fstMortBal').value;
    secMort = document.getElementById('secMortBal').value;
    addCash = document.getElementById('cashOut').value;

    if( estValue == '') estValue = '0';
    if( fstMort == '') fstMort = '0';
    if( secMort == '') secMort = '0';
    if( addCash == '') addCash = '0';

    total = parseInt(fstMort) + parseInt(secMort) + parseInt(addCash);

    shouldPop = (total / parseInt(estValue) < mortgageMaxRatio && total < mortgageMaxValue );
    selected = 0;

    MortgageCheckAlreadyPopped = !(document.getElementById('shouldPop100k').value == "true");
    if( shouldPop && MortgageCheckAlreadyPopped ) {
        diff = parseInt(addCash) + mortgageMaxValue - total;
        document.getElementById('shouldPop100k').value = "true";
        cashOptions = document.getElementById('cashOut');

        for(i=1; i<cashOptions.options.length;i++) {
            if( parseInt(cashOptions.options[i].value) >= diff ) {
                selected = i;
                break;
            }
        }
		if(selected==0)
			selected=cashOptions.options.length-1;//If the diff is insanely high (which should happen only in testing), we show the highest amount in dropdown!

        answer = confirm('You could take out up to $' + document.getElementById('cashOut').options[selected].value + ' in cash.  Click "OK" to increase your loan inquiry to this amount, or click "cancel" for no change.');

        if( answer ) {
            document.getElementById('cashOut').options[selected].selected = true;
        }
    }
}

function submitOnce() {
	if(window.validationError_S) checkVal=true;
	var rcmd= document.getElementById("cmd");
	if(!rcmd) rcmd=getForm().cmd;
    if (rcmd!=null&&rcmd.value) {
        rcmd.value = "submit";
    }

    if (alreadySubmitted == 1) return false;

    alreadySubmitted = 1;
    var buttonElm=document.getElementById("submit_button");
    if (buttonElm)buttonElm.disabled=true;

    var validated = false;
    var valFun=function(){return validate()};
    if(checkVal&&validationError_S!=null&&validationError_S>=2) valFun=function(){return NAValidate()};
    if (!valFun()){
        alreadySubmitted=0;
       	if (buttonElm)buttonElm.disabled=false;
       	popup=true;
        validated=false;
    }else{
    	if (checkVal&&validationError_S!=null&&validationError_S>=2) revDis();
        validated=true;
    }

    if(validated && (type2=="CobrandUtils.HomeEquity" || type2=="CobrandUtils.MortgageRefinance")){
    	if(showRecommendation_S==2&&document.getElementById('pageToRender').value == "2")
    		return showRecommendation();
    	else
        	return checkTotalMortValueIs100k();
	}
	
	if (validated && (type2=="PersonalInfoMini" || type2=="PersonalInfoMiniCalibex") && showSSNPopUp){
		return showSSN();
	}
	
    return validated;
}

function disable(){return alreadySubmitted != 1;}

function viewDisclaimer(){popWindow("/buyer/rfq/disclaimer.jsp","disclaimer","yes","yes","400","400");}
function viewPrivacyStatement(url) {
    if (!url)url="/buyer/help/prPrivacyPolicy.jsp";
    popWindow(url,"privacystatement","yes","yes","805","600");
}
function viewTermsOfUse(){popWindow("/buyer/service_agreement.jsp","privacystatement","yes","yes","800","600");}
function viewAboutNexTag(){popWindow("/serv/main/about/about.jsp","about","yes","yes","800","600");}
function viewExplanation1(){popWindow("/buyer/rfq/explanation1.htm","explanation1","no","no","380","125");}
function viewExplanation2(){popWindow("/buyer/rfq/explanation2.htm","explanation2","no","no","350","110");}
function viewfaqs(url){
	if (!url)url="/buyer/rfq/faq.jsp";
	popWindow(url,"faqs","yes","yes","640","600");
}
function viewCreditProfiles() {popWindow("/buyer/help/creditProfiles.jsp","credit","no","no","320","470");}
function viewStateLicenses(url){
	if (!url)url="/buyer/mortgage_state_licenses.jsp";
	popWindow(url,"statelicense","yes","yes","805","600");
}

function viewServiceAgreement(url){popWindow("/buyer/service_agreement.jsp","credit","yes","yes","640","600");}
function viewTerms(url){
    if (!url)url="/buyer/service_agreement.jsp";
    popWindow(url,"","yes","yes","805","600");
}
function viewSample(url){
if (!url)url="/buyer/rfq/sampleLenders.jsp"
popWindow(url,"","yes","yes","340","240");
}
function viewDiscPopup(url,winName){popWindow(url,winName,"yes","no","500","300");}

/*function anchorMe(){location.hash="topAnchor";}*/

function redirectUser() {
		disableSubmit();
		var mform=getForm();
    if (!alreadyRedirected){
        alreadyRedirected=true;
        mform.cmd.value = "redirectUser";
        popup=false;
        mform.hidethetype.value="TRUE";
        mform.submit();
    }
}
function redirectUser2() {
		var mform=getForm();
    if (!alreadyRedirected2){
        alreadyRedirected2=true;
        mform.cmd.value = "redirectUser";
        popup=false;
        mform.submit();
    }
}

function setTORefresh(){
    if (navigator.vendor && navigator.vendor.indexOf("Apple") != -1) {
        setTimeout("refresh()",540000);
    }
    else {
        setTimeout("sendDummyRequest()",540000);
    }
    
    if("CobrandUtils.MortgageLoan"==type2||"CobrandUtils.UKPurchase"==type2){
        showPurchaseSubQuestions("realtor");
        showPurchaseSubQuestions("foundhome");
     } 
     if("CobrandUtils.UKReMortgage"==type2){
        showRefiCreditQuestions('creditProblems');
     } 
}



function refresh() {
		var mform=getForm();
    mform.cmd.value = "refresh";
    popup=false;
    mform.submit();
}

function sendDummyRequest() {
    var nhr=new NxtgHttpReq("/rfquserevent?1=1");
    nhr.setPost();
    nhr.send();
    setTimeout("sendDummyRequest()",540000);
}

function focusFirstEmptyField(){
    var emptyFieldIdx = -1;
    var mform=getForm();
    for (var i=0; i<mform.elements.length; i++) {
        var element = mform.elements[i];
        if ("text" == element.type || "select-one" == element.type || "select-multiple" == element.type) {
            if (element.value == null || "" == element.value) {
                emptyFieldIdx = i;
                break;
            }
        }
        else if ("checkbox" == element.type) {
            if (!element.checked) {
                emptyFieldIdx = i;
                break;
            }
        }
    }
    if (emptyFieldIdx != -1)
        mform.elements[emptyFieldIdx].focus();
}

function showPurchaseSubQuestions(attrName){
	if(type2=="CobrandUtils.UKPurchase"&&hideOptionalQuestionsUK==false) return;
	var attrField1=document.getElementById(attrName+"1");
	var attrField2=document.getElementById(attrName+"2");
	if (document.getElementById){
                var grp = document.subrfq_1.elements[attrName];
                var result="false";
                if (grp!=null){
                        if (grp.type=="select-one"){
                                if (grp.value == "true"){
                                        result="true";
                               		 }
                            }
                      	else{
                                if (grp[0]){
                                        if (grp[0].checked){
                                                result="true";
                                        	}
                                	}
                        	}
                	}

                if (result=="false"){
                        if (attrField1){
                                attrField1.style.display="none";
                        	}
                        if (attrField2){
                                attrField2.style.display="none";
                                attrField2.style.position="relative";
                        	}
                	}
                else{
                        if (attrField1){
                                attrField1.style.display="";
                        	}
                        if (attrField2){
                                attrField2.style.display="";
                                attrField2.style.position="relative";
            				}
                	}
                if (attrField1){
                        attrField1.style.position="relative";
                }
        }
}

function showRefiCreditQuestions(attrName){
	if(type2!="CobrandUtils.UKReMortgage") return;
	var attrField1=document.getElementById(attrName+"1");
	var attrField2=document.getElementById(attrName+"2");
	var attrField3=document.getElementById(attrName+"3");
	if (document.getElementById&&attrField1&&attrField2&&attrField3){
        var grp = document.subrfq_1.elements[attrName];
        var result="false";
        if (grp!=null && grp[0] && grp[0].checked) result="true";
        if(result=="false"){
           attrField1.style.display="none";
           attrField2.style.display="none";
           attrField3.style.display="none";           
       }else{
           attrField1.style.display="";
           attrField2.style.display="";
           attrField3.style.display="";
       }
    }
}

function disableSubmit(){
	var buttonElm=document.getElementById("submit_button");
    if (buttonElm)buttonElm.disabled=true;
    return true;
}

function onLoadEvts(){
setTORefresh();
if(isBelowFold) pushBelowFold("disc-div");
}

var popupwb=false;
function initialize(){
		popupwb=(popup!=null&&popup==true);
		iDH();
		dhtmlHistory.initialize();
  	 	dhtmlHistory.addListener(historyChange);
  	 	initPage();
}
function historyChange(newLocation,historyData) {
if(popupwb) popup=false;
if(newLocation==""&&document.getElementById('pageToRender').value == "1"){
	history.forward();
}
if(popup!=null&&popupwb!=popup) popup=popupwb;
}

function initPage(){
  	 	dhtmlHistory.add("BD1",1);
}

var ces=null;
var nrQns=null;
function initVal(){
ces=new Array();
nrQns=new Array();
}

function changeDisplay(attr){
var QN=document.getElementById(attr+"Qn");
if(QN==null){
if(attr=="purchaseContract") QN=document.getElementById("foundhome1");
}
if(QN!=null){
QN.style.display="none";
if(ces.indexOf(QN)==-1) ces.push(QN);
}
}
function doCS(){
changeDisplayEH();
changeDisplayNRQ();
pushBelowFold("disc-div");
}

function changeDisplayEH(){
var errorHeader=document.getElementById("errorHeader");
if(errorHeader!=null) {
errorHeader.style.display="";
document.getElementById("errorHeaderMsg").innerHTML="Please answer the following questions before proceeding&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
}
}

function changeDisplayNRQ(){
for(var k=0;k<nrQns.length;k++){
nrQns[k].style.display="none";
if(ces.indexOf(nrQns[k])==-1) ces.push(nrQns[k]);
}
}

function clickNRQ(id,val){
if(val!=null&&getElement(val).value.trim()=="") return;
var fd=document.getElementById(id);
if(nrQns.indexOf(fd)==-1) nrQns.push(fd);
}

function revDis(){
while(ces.length>0){
elm=ces.pop();
elm.style.display="";
}
var errorHeader=document.getElementById("errorHeader");
if(errorHeader!=null) {
errorHeader.style.display="none";
}
pushBelowFold("disc-div");
}

        var popup=true;
function feedback(destURL, destParams) {
    destURL = destURL.replace(/&amp;/g, "&");
    if (popup){
        open(destURL, "", destParams);
    }
}

function loadMortgagePopUnder(url) {
	if (isIE){
		var load = window.open(url+'&popunder=true','mortgage_pop_under','scrollbars=no,menubar=no,height=560,width=640,resizable=yes,toolbar=no,location=no,status=no');
		load.blur();
	}
	else{
		var load = window.open(url+'&popunder=true','mortgage_pop_under','scrollbars=no,menubar=no,height=475,width=640,resizable=yes,toolbar=no,location=no,status=no');
		load.blur();
	}
}

function closePopUnderWindow(){
    if (window.opener && !window.opener.closed && window.opener.name=='mortgage_pop_under'){
        window.opener.close();
    }
}

function getOriginalWinAttributes(window){
    var attribs;
    if (isIE){attribs='';}
    else{
        var scrollbars='yes';
        var menubar='yes';
        var toolbar='yes';
        var locationbar='yes';
        var statusbar='yes';
        var personalbar='yes';
        var height=screen.availHeight;
        var width=screen.availWidth;
        if (window.opener){
            if (window.opener.scrollbars.visible) scrollbars='yes';
            else scrollbars='no';

            if (window.opener.menubar.visible) menubar='yes';
            else menubar='no';

            if (window.opener.toolbar.visible) toolbar='yes';
            else toolbar='no';

            if (window.opener.locationbar.visible) locationbar='yes';
            else locationbar='no';

            if (window.opener.statusbar.visible) statusbar='yes';
            else statusbar='no';

            if (window.opener.personalbar.visible) personalbar='yes';
            else personalbar='no';
        }
        attribs = 'scrollbars='+scrollbars+',menubar='+menubar+',height='+height+',width='+width+',toolbar='+toolbar+',directories='+personalbar+',location='+locationbar+',status='+statusbar+',resizable=yes';
    }
    return attribs;
}

        var	currQn = -1;
var questionIds = new Array();
var extraQuestionIds = new Array();
var toValidate = new Array();
var hG=!historyDisabled&&(isIE||isFF);
var osp = null;
var msgs = new Array();
var adv1 = new Array();
var adv2 = new Array();
var currAdv1=-1;
var currAdv2=-1;
var servErr=false;

function showPrevQn(){
	if(hG){
		history.back();
	}else{
		var CQN = document.getElementById(questionIds[currQn]);
		if(CQN!=null) CQN.style.display="none";
		var PQN = document.getElementById(questionIds[currQn-1]);
	
		if(PQN!=null){ 
			PQN.style.display="";
			currQn=currQn-1;
		}
		if(currQn==0) document.getElementById("backButton").style.display = "none";

		document.getElementById("progBar").style.width = (100*currQn)/questionIds.length+"%";
	}
	ddqs();
	setHeaderText();
	dispNextagAdv();
	if(questionIds[currQn]=="group5"&&"CobrandUtils.MortgageLoan"==type2){
        showPurchaseSubQuestions("realtor");
        showPurchaseSubQuestions("foundhome");
    }
    showEmailDisc(questionIds[currQn]); 
}

function showNextQn(sp){
	if(sp!=null) osp=sp;
	if(!valQn()) return;
	var CQN=document.getElementById(questionIds[currQn]);
	var NQN=document.getElementById(questionIds[currQn+1]);
	var spDone=(parseInt(osp)==currQn-1);
	if(spDone) NQN=null;
	if(NQN!=null){ 
		NQN.style.display="";
		currQn=currQn+1;
	}
	if(NQN!=null&&CQN!=null) CQN.style.display="none";
	
	if(currQn>0&&parseInt(osp)!=currQn-1) document.getElementById("backButton").style.display="";
	if((NQN==null&&currQn==questionIds.length-1)||spDone){ 
			popup=false;
			getForm().submit();	
	}else{
		var cqn=currQn;
		if(parseInt(osp)==currQn-1) cqn=questionIds.length-1;	
		document.getElementById("progBar").style.width=(100*cqn)/questionIds.length+"%";
		if(hG&&currQn>0){
			if(sp==null) dhtmlHistory.add("HQ"+currQn,currQn);
		}		
	}
	ddqs();
	setHeaderText();
	dispNextagAdv();
	if(questionIds[currQn]=="group5"&&"CobrandUtils.MortgageLoan"==type2){
       showPurchaseSubQuestions("realtor");
       showPurchaseSubQuestions("foundhome");
    }
    showEmailDisc(questionIds[currQn]);       
}

function showEmailDisc(grp){
    if(emailSlide(grp)) $('emailDisc').style.display = '';
    else  $('emailDisc').style.display = 'none';  
}

function initSS(qn, sp){
	document.getElementById("submitMain").style.display="none";
	document.getElementById("submitSS").style.display="";
	document.getElementById("SSprogress").style.display="";
	document.getElementById("backButton").style.display="none";
	initVariables();
	currQn=qn;
	if(hG&&dhtmlHistory.currentLocation=="HQ"+(questionIds.length-1)&&qn==-1){
		if(!sse) initsse();
	 	if(sse) currQn=questionIds.length-2;
	}	
	showNextQn(sp);
	if(sp=='true') servErr=true;
	popup=false;
}

function initHistory(){
	if(hG){
		iDH();
		dhtmlHistory.initialize();
  		dhtmlHistory.addListener(historyChange);
  	}
}
function historyChange(newLocation,historyData) {
	var CQN=document.getElementById(questionIds[currQn]);
	if(CQN!=null) CQN.style.display="none";
	if(historyData!=null) initSS(historyData-1);
	else if(newLocation!=null&&newLocation!=""&&sse){
 		var newL=parseInt(newLocation.substring(2));
 		if(isNaN(newL)||newL>questionIds.length-1||newL<1) initSS(-1);
 		else initSS(newL-1);
	}	
	else initSS(-1);
}

function initVariables(){
	msgs = new Array('<span class="emphasis">Free and Fast</span>- our service may take as little as one minute.', 
					 'Licensed or permitted in All States except Montana.', 
					 'NexTag\'s network has hundreds of lenders, so we can match most borrowers with lenders.', 
					 '<span class="emphasis">Bad Credit OK</span>- you don\'t need excellent credit to get a loan. We can usually match you with lenders, regardless of your credit.', 
					 '<div class="expSectionContent">NexTag is the leading comparison shopping site on the internet - for mortgages, products, travel and more...</div>', 
					 'Over 17 million people use NexTag every month (Nielsen-NetRatings).');
    if("CobrandUtils.MortgageRefinance"==type2){
		questionIds = new Array("mortgageChoiceQn", "propertyTypeQn", "estValueQn", "group1", "secMortBalQn", "cashOutQn", "group2", "group3", "group4");
		toValidate = new Array(0, 0, 1, 1, 0, 1, 1, 1, 1);
		extraQuestionIds = new Array();
		adv1 = new Array(0, 0, 0, 2, 2, 2, 2, 3, 1);
		adv2 = new Array(5, 5, 5, 4, 4, 4, 5, 5, 5);
	}
    if("CobrandUtils.HomeEquity"==type2){
		questionIds = new Array("mortgageChoiceQn", "propertyTypeQn", "estValueQn", "group1", "secMortBalQn", "cashOutQn", "equityTypeQn", "group2", "group3", "group4");
		toValidate = new Array(0, 0, 1, 1, 0, 1, 0, 1, 1, 1);
		extraQuestionIds = new Array();
		adv1 = new Array(0, 0, 0, 2, 2, 2, 2, 2, 3, 1);
		adv2 = new Array(5, 5, 5, 4, 4, 4, 4, 5, 5, 5);		
	}
	if("CobrandUtils.MortgageLoan"==type2){
		questionIds = new Array("mortgageChoiceQn", "propertyTypeQn", "propertyPurposeQn",  "group1", "group2", "group3", "group4", "group5", "group6", "group7");
		extraQuestionIds = new Array("foundhome1", "realtor1", "realtor2");
		toValidate = new Array(0, 0, 0, 1, 1, 1, 1, 1, 1, 1);
		adv1 = new Array(0, 0, 0, 2, 2, 3, 2, 2, 2, 1);
		adv2 = new Array(5, 5, 5, 4, 4, 5, 5, 5, 5, 5);	
	}
}

function emailSlide(grp){
	if('CobrandUtils.MortgageLoan'==type2) return grp=='group7';
	else return grp=='group4';
}

function ddqs(){
	ddqsH(questionIds);
	ddqsH(extraQuestionIds);
}

function ddqsH(qIds){	
	var qn = -1;
	while(qn<qIds.length-1){
		qn=qn+1;
		if(qn==currQn) continue;
		document.getElementById(qIds[qn]).style.display="none";
	}
}

function setHeaderText(){
	var headerText = 'Your Loan and Financial Information';
	if(questionIds[currQn]=='mortgageChoiceQn'||questionIds[currQn]=='propertyTypeQn'||questionIds[currQn]=='estValueQn'||questionIds[currQn]=='group4'||questionIds[currQn]=='group7'){
		headerText = 'Your Property Information';
	}
	document.getElementById('headerText').innerHTML = headerText;
}


function valQn(){
	switch (type2){
		case "CobrandUtils.MortgageRefinance":
			if(currQn==-1||toValidate[currQn]==0) return true;
			if(questionIds[currQn]=="group1"){
				if(!valAndDisplay("interestRate")|!valAndDisplay("monthPayment")|!valAndDisplay("fstMortBal")) return false;
				else return true;
			}
			if(questionIds[currQn]=="estValueQn"){
				if(!valAndDisplay("estValue")) return false;
				if(!checkValueIsAtleast('estValue', 10001)){
					document.getElementById("estValueQnErr2").style.display="";
					return false;
				}
				return true;
			}
			if(questionIds[currQn]=="cashOutQn"){
				if(!checkTotalMortValueIsAtleast10k()){
					document.getElementById("commonErr").style.display="";
					return false;
				}
				return true;
			}
			if(questionIds[currQn]=="group2"){
				if(!valAndDisplay("oweEachMonth")|!valAndDisplay("grossIncome")|(evaluateBirthYear && !valAndDisplay("birthYear"))) return false;
				else return true;
			}
			if(questionIds[currQn]=="group3"){
				if(!valAndDisplay("credit")) return false;
				else return true;
			}
			if(questionIds[currQn]=="group4"){
				if(servErr) return true;
				if(!valAndDisplay("email")|!valAndDisplay("state")|!valAndDisplay("propertyzip")) return false;
				else return true;
			}
			return valAndDisplay(questionIds[currQn].substr(0, questionIds[currQn].length-2));
			
		case "CobrandUtils.HomeEquity":
			if(currQn==-1||toValidate[currQn]==0) return true;
			if(questionIds[currQn]=="group1"){
				if(!valAndDisplay("interestRate")|!valAndDisplay("monthPayment")|!valAndDisplay("fstMortBal")) return false;
				return true;
			}
			if(questionIds[currQn]=="estValueQn"){
				if(!valAndDisplay("estValue")) return false;
				if(!checkValueIsAtleast('estValue', 10001)){
					document.getElementById("estValueQnErr2").style.display="";
					return false;
				}
				return true;
			}
			if(questionIds[currQn]=="cashOutQn"){
				if(!valAndDisplay("cashOut")) return false;
				if(!checkValueIsAtleast('cashOut', 10000)){
					document.getElementById("cashOutQnErr2").style.display="";
					return false;
				}
				return true;
			}
			if(questionIds[currQn]=="group2"){
				if(!valAndDisplay("oweEachMonth")|!valAndDisplay("grossIncome")) return false;
				else return true;
			}
			if(questionIds[currQn]=="group3"){
				if(!valAndDisplay("credit")) return false;
				else return true;
			}
			if(questionIds[currQn]=="group4"){
				if(servErr) return true;
				if(!valAndDisplay("email")|!valAndDisplay("state")|!valAndDisplay("propertyzip")) return false;
				else return true;
			}
			return valAndDisplay(questionIds[currQn].substr(0, questionIds[currQn].length-2));
				
		case "CobrandUtils.MortgageLoan":
			if(currQn==-1||toValidate[currQn]==0) return true;
			if(questionIds[currQn]=="group1"){
				if(!valAndDisplay("downPayment") | !valAndDisplay("estValue") ) return false;
				if(questionIds[currQn]=="estValueQn"){
					if(!valAndDisplay("estValue")) return false;
					if(!checkValueIsAtleast('estValue', 10001)){
						document.getElementById("estValueQnErr2").style.display="";
						return false;
					}
					return true;
				}
				if(isAttr1GreaterThanAttr2("downPayment", "estValue")){
				  document.getElementById("estValueQnErr2").style.display="none";
				  document.getElementById("downPaymentGreaterErr").style.display="";
				  return false;
				}				
				if(!validateDownPayment("estValue", "recommendedPercentage", "downPayment")) return false;
				return true;
			}
			if(questionIds[currQn]=="group2"){
				if(!valAndDisplayRadio("rateType")) return false;
				return true;
			}
			if(questionIds[currQn]=="group3"){
				if(!valAndDisplay("credit")) return false;
				return true;
			}
			if(questionIds[currQn]=="group4"){
				if(!valAndDisplay("whenNeedLoan")) return false;
				return true;
			}
			if(questionIds[currQn]=="group5"){
				if(!valAndDisplayRadio("realtor")|!valAndDisplayRadio("foundhome")|!valAndDisplayRadio("firstTimeBuyer")) return false;
				foundHome = document.getElementsByName('foundhome');
        		evaluatePurchaseContract = (evaluateFoundHome && foundHome[0].checked && foundHome[0].value == 'true');
				if(evaluatePurchaseContract&&!valAndDisplayRadio("purchaseContract")) return false;
				return true;
			}
			if(questionIds[currQn]=="group6"){
				if(!valAndDisplay("oweEachMonth")|!valAndDisplay("grossIncome")|(evaluateBirthYear && !valAndDisplay("birthYear"))) return false;
				else return true;
			}
			if(questionIds[currQn]=="group7"){
			    if(servErr) return true;
				if(!valAndDisplay("email")|!valAndDisplay("state")|!valAndDisplay("areacode")) return false;
				else return true;
			}
			return true;						
	}
	return true;
}

function valAndDisplay(attrName){
	var elm=getElement(attrName);
    var stringValue=elm.value.trim();
    if (stringValue==""||stringValue=="Select"){
        elm.focus();
        document.getElementById(attrName+"QnErr").style.display="";
        return false;
    }
    document.getElementById(attrName+"QnErr").style.display="none";
    return true;
}

function valAndDisplayRadio(attrName) {
	var grp = document.subrfq_1.elements[attrName];
    if (grp.length==0) return true;

    for (var ix=0;ix<grp.length;ix++){
        if (grp[ix].type=='hidden'||grp[ix].checked){
         document.getElementById(attrName+"QnErr").style.display="none";
         return true;
        }
    }
	grp[0].focus();
	document.getElementById(attrName+"QnErr").style.display="";
	return false;
}

function checkTotalMortValueIsAtleast10k() {

    fstMort =  document.getElementById('fstMortBal').value;
    secMort = document.getElementById('secMortBal').value;
    addCash = document.getElementById('cashOut').value;

    if( fstMort == '') fstMort = '0';
    if( secMort == '') secMort = '0';
    if( addCash == '') addCash = '0';

    total = parseInt(fstMort) + parseInt(secMort) + parseInt(addCash);
	
	if(total<10000) return false;
	
	return true;
}

function checkValueIsAtleast(attrName, minValue) {
    var val = document.getElementById(attrName).value;
    if( val == '') val = '0';
    val = cleanUp(val);	
	if(parseInt(val)< minValue) return false;	
	return true;
}

function isAttr1GreaterThanAttr2(attr1, attr2) {
    var val1 = document.getElementById(attr1).value;
    if( val1 == '') val1 = '0';
    val1 = cleanUp(val1);	
    
    var val2 = document.getElementById(attr2).value;
    if( val2 == '') val2 = '0';
	val2 = cleanUp(val2);
	
	if(parseInt(val1)> parseInt(val2)) return true;	
	return false;
}

function initsse(){
	var options={cb:processSSXML};
  	new NxtgHttpReq("/buyer/rfq/resources/getObject.jsp?func=sse", options).send();
}

function processSSXML(respText, respXml){
	var info=respXml.documentElement.getElementsByTagName("info")[0].firstChild.nodeValue;
  	if(info == "true"){
       sse=true;
       initSS(-1);
	}
}

function dispNextagAdv(){
var msg1Idx = adv1[currQn];
var msg2Idx = adv2[currQn];
if(currAdv1==msg1Idx&&currAdv2==msg2Idx) return;
currAdv1 = msg1Idx;
currAdv2 = msg2Idx;
var msg1Elem = document.getElementById('advText1');
if(msg1Elem!=null){
	msg1Elem.innerHTML=msgs[msg1Idx];
}
var msg2Elem = document.getElementById('advText2');
if(msg2Elem!=null){
	msg2Elem.innerHTML=msgs[msg2Idx];
}

}/** 
   Copyright (c) 2005, Brad Neuberg, bkn3@columbia.edu
   http://codinginparadise.org
   
   Permission is hereby granted, free of charge, to any person obtaining 
   a copy of this software and associated documentation files (the "Software"), 
   to deal in the Software without restriction, including without limitation 
   the rights to use, copy, modify, merge, publish, distribute, sublicense, 
   and/or sell copies of the Software, and to permit persons to whom the 
   Software is furnished to do so, subject to the following conditions:
   
   The above copyright notice and this permission notice shall be 
   included in all copies or substantial portions of the Software.
   
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 
   OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
   THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   
   The JSON class near the end of this file is
   Copyright 2005, JSON.org
*/

window.dhtmlHistory={initialize:function(){if(this.isInternetExplorer()==false){return}if(historyStorage.hasKey("DhtmlHistory_pageLoaded")==false){this.fireOnNewListener=false;this.firstLoad=true;historyStorage.put("DhtmlHistory_pageLoaded",true)}else{this.fireOnNewListener=true;this.firstLoad=false}},addListener:function(callback){this.listener=callback;if(this.fireOnNewListener==true){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false}},add:function(newLocation,historyData){var self=this;var addImpl=function(){if(self.currentWaitTime>0)self.currentWaitTime=self.currentWaitTime-self.WAIT_TIME;newLocation=self.removeHash(newLocation);var idCheck=document.getElementById(newLocation);if(idCheck!=undefined||idCheck!=null){var message="Exception: History locations can not have "+"the same value as _any_ id's "+"that might be in the document, "+"due to a bug in Internet "+"Explorer; please ask the "+"developer to choose a history "+"location that does not match "+"any HTML id's in this "+"document. The following ID "+"is already taken and can not "+"be a location: "+newLocation;throw message;}historyStorage.put(newLocation,historyData);self.ignoreLocationChange=true;this.ieAtomicLocationChange=true;self.currentLocation=newLocation;window.location.hash=newLocation;if(self.isInternetExplorer())self.iframe.src="/buyer/rfq/educationforms/blank.html?"+newLocation;this.ieAtomicLocationChange=false};window.setTimeout(addImpl,this.currentWaitTime);this.currentWaitTime=this.currentWaitTime+this.WAIT_TIME},isFirstLoad:function(){if(this.firstLoad==true){return true}else{return false}},isInternational:function(){return false},getVersion:function(){return"0.05"},getCurrentLocation:function(){var currentLocation=this.removeHash(window.location.hash);return currentLocation},currentLocation:null,listener:null,iframe:null,ignoreLocationChange:null,WAIT_TIME:200,currentWaitTime:0,fireOnNewListener:null,firstLoad:null,ieAtomicLocationChange:null,create:function(){var initialHash=this.getCurrentLocation();this.currentLocation=initialHash;if(this.isInternetExplorer()){document.write("<iframe style='border: 0px; width: 1px; "+"height: 1px; position: absolute; bottom: 0px; "+"right: 0px; visibility: visible;' "+"name='DhtmlHistoryFrame' id='DhtmlHistoryFrame' "+"src='/buyer/rfq/educationforms/blank.html?"+initialHash+"'>"+"</iframe>");this.WAIT_TIME=400}var self=this;var unloadHandlerDHH=function(){self.firstLoad=null;};var unloadHandlerDHH2=(window.onunload)?window.onunload:function(){};window.onunload=function(){unloadHandlerDHH();unloadHandlerDHH2();};if(this.isInternetExplorer()==false){if(historyStorage.hasKey("DhtmlHistory_pageLoaded")==false){this.ignoreLocationChange=true;this.firstLoad=true;historyStorage.put("DhtmlHistory_pageLoaded",true)}else{this.ignoreLocationChange=false;this.fireOnNewListener=true}}else{this.ignoreLocationChange=true}if(this.isInternetExplorer()){this.iframe=document.getElementById("DhtmlHistoryFrame")}var self=this;var locationHandler=function(){self.checkLocation()};setInterval(locationHandler,100)},fireHistoryEvent:function(newHash){var historyData=historyStorage.get(newHash);this.listener.call(null,newHash,historyData)},checkLocation:function(){if(this.isInternetExplorer()==false&&this.ignoreLocationChange==true){this.ignoreLocationChange=false;return}if(this.isInternetExplorer()==false&&this.ieAtomicLocationChange==true){return}var hash=this.getCurrentLocation();if(hash==this.currentLocation)return;this.ieAtomicLocationChange=true;if(this.isInternetExplorer()&&this.getIFrameHash()!=hash){this.iframe.src="/buyer/rfq/educationforms/blank.html?"+hash}else if(this.isInternetExplorer()){return}this.currentLocation=hash;this.ieAtomicLocationChange=false;this.fireHistoryEvent(hash)},getIFrameHash:function(){var historyFrame=document.getElementById("DhtmlHistoryFrame");var doc=historyFrame.contentWindow.document;var hash=new String(doc.location.search);if(hash.length==1&&hash.charAt(0)=="?")hash="";else if(hash.length>=2&&hash.charAt(0)=="?")hash=hash.substring(1);return hash},removeHash:function(hashValue){if(hashValue==null||hashValue==undefined)return null;else if(hashValue=="")return"";else if(hashValue.length==1&&hashValue.charAt(0)=="#")return"";else if(hashValue.length>1&&hashValue.charAt(0)=="#")return hashValue.substring(1);else return hashValue},iframeLoaded:function(newLocation){if(this.ignoreLocationChange==true){this.ignoreLocationChange=false;return}var hash=new String(newLocation.search);if(hash.length==1&&hash.charAt(0)=="?")hash="";else if(hash.length>=2&&hash.charAt(0)=="?")hash=hash.substring(1);if(this.pageLoadEvent!=true){window.location.hash=hash}this.fireHistoryEvent(hash)},isInternetExplorer:function(){var userAgent=navigator.userAgent.toLowerCase();if(document.all&&userAgent.indexOf('msie')!=-1){return true}else{return false}}};window.historyStorage={debugging:false,storageHash:new Object(),hashLoaded:false,put:function(key,value){this.assertValidKey(key);if(this.hasKey(key)){this.remove(key)}this.storageHash[key]=value;this.saveHashTable()},get:function(key){this.assertValidKey(key);this.loadHashTable();var value=this.storageHash[key];if(value==undefined)return null;else return value},remove:function(key){this.assertValidKey(key);this.loadHashTable();delete this.storageHash[key];this.saveHashTable()},reset:function(){this.storageField.value="";this.storageHash=new Object()},hasKey:function(key){this.assertValidKey(key);this.loadHashTable();if(typeof this.storageHash[key]=="undefined")return false;else return true},isValidKey:function(key){return(typeof key=="string")},storageField:null,init:function(){var styleValue="position: absolute; top: -1000px; left: -1000px;";if(this.debugging==true){styleValue="width: 30em; height: 30em;"}var newContent="<form id='historyStorageForm' "+"method='GET' "+"style='"+styleValue+"'>"+"<textarea id='historyStorageField' "+"style='"+styleValue+"'"+" name='historyStorageField'></textarea>"+"</form>";document.write(newContent);this.storageField=document.getElementById("historyStorageField")},assertValidKey:function(key){if(this.isValidKey(key)==false){throw"Please provide a valid key for "+"window.historyStorage, key= "+key;}},loadHashTable:function(){if(this.hashLoaded==false){var serializedHashTable=this.storageField.value;if(serializedHashTable!=""&&serializedHashTable!=null){this.storageHash=eval('('+serializedHashTable+')')}this.hashLoaded=true}},saveHashTable:function(){this.loadHashTable();var serializedHashTable=JSON.stringify(this.storageHash);this.storageField.value=serializedHashTable}};Array.prototype.______array='______array';var JSON={org:'http://www.JSON.org',copyright:'(c)2005 JSON.org',license:'http://www.crockford.com/JSON/license.html',stringify:function(arg){var c,i,l,s='',v;switch(typeof arg){case'object':if(arg){if(arg.______array=='______array'){for(i=0;i<arg.length;++i){v=this.stringify(arg[i]);if(s){s+=','}s+=v}return'['+s+']'}else if(typeof arg.toString!='undefined'){for(i in arg){v=arg[i];if(typeof v!='undefined'&&typeof v!='function'){v=this.stringify(v);if(s){s+=','}s+=this.stringify(i)+':'+v}}return'{'+s+'}'}}return'null';case'number':return isFinite(arg)?String(arg):'null';case'string':l=arg.length;s='"';for(i=0;i<l;i+=1){c=arg.charAt(i);if(c>=' '){if(c=='\\'||c=='"'){s+='\\'}s+=c}else{switch(c){case'\b':s+='\\b';break;case'\f':s+='\\f';break;case'\n':s+='\\n';break;case'\r':s+='\\r';break;case'\t':s+='\\t';break;default:c=c.charCodeAt();s+='\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)}}}return s+'"';case'boolean':return String(arg);default:return'null'}},parse:function(text){var at=0;var ch=' ';function error(m){throw{name:'JSONError',message:m,at:at-1,text:text}}function next(){ch=text.charAt(at);at+=1;return ch}function white(){while(ch!=''&&ch<=' '){next()}}function str(){var i,s='',t,u;if(ch=='"'){outer:while(next()){if(ch=='"'){next();return s}else if(ch=='\\'){switch(next()){case'b':s+='\b';break;case'f':s+='\f';break;case'n':s+='\n';break;case'r':s+='\r';break;case't':s+='\t';break;case'u':u=0;for(i=0;i<4;i+=1){t=parseInt(next(),16);if(!isFinite(t)){break outer}u=u*16+t}s+=String.fromCharCode(u);break;default:s+=ch}}else{s+=ch}}}error("Bad string")}function arr(){var a=[];if(ch=='['){next();white();if(ch==']'){next();return a}while(ch){a.push(val());white();if(ch==']'){next();return a}else if(ch!=','){break}next();white()}}error("Bad array")}function obj(){var k,o={};if(ch=='{'){next();white();if(ch=='}'){next();return o}while(ch){k=str();white();if(ch!=':'){break}next();o[k]=val();white();if(ch=='}'){next();return o}else if(ch!=','){break}next();white()}}error("Bad object")}function num(){var n='',v;if(ch=='-'){n='-';next()}while(ch>='0'&&ch<='9'){n+=ch;next()}if(ch=='.'){n+='.';while(next()&&ch>='0'&&ch<='9'){n+=ch}}if(ch=='e'||ch=='E'){n+='e';next();if(ch=='-'||ch=='+'){n+=ch;next()}while(ch>='0'&&ch<='9'){n+=ch;next()}}v=+n;if(!isFinite(v)){error("Bad number")}else{return v}}function word(){switch(ch){case't':if(next()=='r'&&next()=='u'&&next()=='e'){next();return true}break;case'f':if(next()=='a'&&next()=='l'&&next()=='s'&&next()=='e'){next();return false}break;case'n':if(next()=='u'&&next()=='l'&&next()=='l'){next();return null}break}error("Syntax error")}function val(){white();switch(ch){case'{':return obj();case'[':return arr();case'"':return str();case'-':return num();default:return ch>='0'&&ch<='9'?num():word()}}return val()}};function iDH(){window.historyStorage.init();window.dhtmlHistory.create();}