// JavaScript Document

// suckerfish dropdowns - http://www.htmldog.com/articles/suckerfish/dropdowns/ - thank you htmldog!!!
sfHover = function() {
	var nav = document.getElementById("mainNav"); 
	if (nav) {
		var sfEls = document.getElementById("mainNav").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// js for switching content on and off under a specific id
function clickObject(name,elementId) { 
	if (!document.getElementById) return;
	var navRoot = document.getElementById(elementId);
	if (navRoot) {
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.id == name) {
				node.className = "texton";			
			} else {
				node.className = "textoff";
			}
		}
	}
}

// turn items on or off, displayed or not displayed
function textOn(name) {
	var item = document.getElementById(name);
	item.className= "texton";
}
function textOff(name) {
	var item = document.getElementById(name);
	item.className= "textoff";
}
// show items as selected
function selected(item,child) {
	for (i=0; i<item.childNodes.length; i++) {
		node = item.childNodes[i];
		if (child == node.id)
			node.className += " selected";
	}		
}
function selectItem(name) {
	var item = document.getElementById(name);
	item.className= "selected";
}

// hide mainNav and utilties for simple eloan background
function hideNav(trigger) {
	var trigger = getQueryVariable(trigger);
	if (trigger) {  
		document.write("<style>\#mainNav, \#utilities \{ display: none; \}\#header \{margin-bottom: -30px;border-bottom: 4px solid \#006699;}</style>");
	}
}

//////////////////// determines page and sets tab to selected
// grabs variables from the address bar
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
    } 
      //alert('Query Variable ' + variable + ' not found');
}

// grabs variable from url and populates form field, add this to your page: window.onload = getVariables("formName","inputName")
function getVariables(formName,inputName) {
	var fromURL = unescape(getQueryVariable(inputName));
	var cleanURL = fromURL.replace("undefined"," ");
	if (cleanURL) {		
		if (cleanURL != " ")
			eval('document.'+formName+'.'+inputName+'.value = '+'cleanURL');
	}
}

function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = ""
}

function commify(formItem) {
	var formItem = formItem;
    var Num = eval('document.quote.'+formItem+'.value');
    var newNum = "";
    var newNum2 = "";
    var count = 0;
    
    //check for decimal number
    if (Num.indexOf('.') != -1){  //number ends with a decimal point
        if (Num.indexOf('.') == Num.length-1){
            Num += "00";
        }
        if (Num.indexOf('.') == Num.length-2){ //number ends with a single digit
            Num += "0";
        }
        
        var a = Num.split("."); 
        Num = a[0];   //the part we will commify
        var end = a[1] //the decimal place we will ignore and add back later
    }
    else {var end = "00";}  
 
    //this loop actually adds the commas   
    for (var k = Num.length-1; k >= 0; k--){
      var oneChar = Num.charAt(k);
      if (count == 3){
        newNum += ",";
        newNum += oneChar;
        count = 1;
        continue;
      }
      else {
        newNum += oneChar;
        count ++;
      }
   }  //but now the string is reversed!
   
  //re-reverse the string
  for (var k = newNum.length-1; k >= 0; k--){
      var oneChar = newNum.charAt(k);
      newNum2 += oneChar;
  }
   
   // add dollar sign and decimal ending from above
   newNum2 = "$" + newNum2 + "." + end;
   if (formItem == "loanamount") {
   document.quote.loanamount.value = newNum2;
   }
   if (formItem == "propValue") {
   document.quote.propValue.value = newNum2;
   }
}

function init() {    
	// define the variables
	var nav = document.getElementById("mainNav");
	var nav2 = document.getElementById("smallNav"); // for smaller navs
	var context = getQueryVariable('context'); //gets context from function above
	var moduleOption = getQueryVariable('moduleOption'); //gets moduleOption from function above
	
		
	if (nav) {
		selected(nav,context);
	}
	if (nav2) {
		selected(nav2,context);
	}	
	if (moduleOption) {
		clickObject(moduleOption,"switchModules");
	} else {
		clickObject("Main","switchModules");
	}	
	
	// loans landing page - shows user what they are applying for (displays on setup.wm and shortapp.wm)
	var landingloanamount = getQueryVariable('landingloanamount');
	var state = getQueryVariable('state');
	var landingLoan = document.getElementById('landingLoan');
	if ((landingloanamount) || (state)) {
		if (landingLoan) {
			textOn("landingLoan");
		}
	}	
	
	changeUrl();// for landing pages
}

window.onload = init;

// loans landing page - formats text showing user what they are applying for (displays on setup.wm and shortapp.wm)
function landingLoan(text) {	
	var landingloanamount = getQueryVariable('landingloanamount');
	if (!landingloanamount) landingloanamount = document.getElementById('loanamt').value;
	if (!landingloanamount) landingloanamount = 'Loan+Amount';
	var state = getQueryVariable('state');
	if(!state){
          state='';
    }
	var autoState = getQueryVariable('borrowers%5B0%5D.residences%5B0%5D.address.state');
	var autoAmount = getQueryVariable('product.loanamount');
	var purpose = getQueryVariable('purpose');
	if (!purpose) var purpose = getQueryVariable('context'); if (!purpose) var purpose = document.getElementById('purpose').value ; if (!purpose) var purpose = '';
	
	if ((landingloanamount) || (state)) {
		// this code changes the purpose trigger into some text that makes sense for the landing pages
		if (purpose == 'purch') { purpose = 'a Home Mortgage';}
		if (purpose == 'refi') { purpose = 'a Refinance';}
		if (purpose == 'equity') { purpose = 'a Home Equity';}
		if (purpose == 'debt') { purpose = 'a Debt Consolidation';}
		if (purpose == 'auto') { purpose = 'an Auto';}
		if (purpose == 'secondMortgage') { purpose = 'a Second Mortgage';}
		if (purpose == 'moto') { purpose = 'a Motorcycle';}
		if (purpose == 'autonew') { purpose = 'a New Auto';}
		if (purpose == 'autorefi') { purpose = 'an Auto Refinance';}
		if (purpose == 'autoused') { purpose = 'a Used Auto (Dealer)';}
		if (purpose == 'autousednondealer') { purpose = 'a Used Auto (Non-dealer)';}
		if (purpose == 'autolbo') { purpose = 'a Lease Buyout (Auto only)';}
		if (autoAmount) landingloanamount=autoAmount; // for auto
		if (landingloanamount == 'Loan%20Amount' || landingloanamount == 'Loan+Amount') landingloanamount = ''; else landingloanamount = (formatCurrency(landingloanamount)); 
		if (autoState) state=autoState; // for auto
		if (state == ('')) state = ''; else state = ' in ' + (getState(state));
		// REPLACED BY STATEMENT BELOW: var text = purpose + ' loan up to' + ' ' + landingloanamount + state + '.';
		// New statement created for the times when no loan amount is provided.	
		if (landingloanamount){
		var loanamount = ' up to '+ landingloanamount;
		var text = ' ' +  purpose + ' loan ' + loanamount + state + '.';	
		} else {
		var text = ' ' +  purpose + ' loan' + state + '.';	
		}
		return text;
	}
} 

// directs pages for loans landing page (for small_app.wm)
function changeUrl(purpose) {
	var form = document.form;
	if (!form) {
	} else { 
		var purpose = document.form.purpose.value;
		var name0;
		var name1;
		if (purpose == '') {name0="disabledLoanAmount"; name1="disabledStates";} 
		if (purpose == 'purch') {name0="homeLoanAmount"; name1="regularStates";}
		if (purpose == 'refi') {name0="homeLoanAmount"; name1="regularStates";}
		if (purpose == 'equity') {name0="homeLoanAmount"; name1="equityStates";}
		if (purpose == 'debt') {name0="homeLoanAmount"; name1="regularStates";}
		if (purpose == 'preapp') {name0="preappLoanAmount"; name1="regularStates";}
		if (purpose == 'auto') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'autonew') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'autoused') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'autousednondealer') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'autorefi') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'autolbo') {name0="autoLoanAmount"; name1="autoStates";}
		if (purpose == 'secondMortgage') {name0="homeLoanAmount"; name1="equityStates";}

		clickObject(name0,"loanAmount");
		clickObject(name1,"stateOptions");
				
		var context = purpose; 
		document.form.context.value = context;	
		
		return purpose;
	}
}

// goes with small_app.wm landing pages
function selectState(state) {
	var regularStates = document.form.regularStates.value;
	var equityStates = document.form.equityStates.value;
	if (state == 'regularStates') state = regularStates;	
	if (state == 'equityStates') state = equityStates;	
	document.form.state.value = state;
	return state;
}
function completeFields() {
	if (document.form.purpose.value == '') {alert("Please choose a Loan Purpose.");  return false;}
}

// for auto calculator
function autoCalc(name) {
	if (name == "loanamount") { 
		document.autoform.calculateBy[0].checked = true;
		document.autoform.calculateBy[1].checked = false;
		document.autoform.monthly.className="";
		document.autoform.loanamount.className="autoFocus";
		document.autoform.monthly.disabled=true; 
		document.autoform.loanamount.disabled=false; 
		document.autoform.loanamount.focus();
		document.autoform.monthly.value='';} 
	if (name == "monthly") { 
		document.autoform.calculateBy[0].checked = false;
		document.autoform.calculateBy[1].checked = true;
		document.autoform.monthly.className="autoFocus";
		document.autoform.loanamount.className="";
		document.autoform.monthly.disabled=false; 
		document.autoform.loanamount.disabled=true; 
		document.autoform.monthly.focus(); 
		document.autoform.loanamount.value='';} 
}

// auto calc - if user selects lease buyout and then trys to select motorcycle, alert them
function lbo(loantype) {
	var loantype = document.autoform.loantype.value;
	if (loantype == "vlbo") {
		alert("Sorry, Lease Buyout is for Auto only");
		document.autoform.vehicletype.value="auto";
	}
}

// turn help items on or off, displayed or not displayed, used on auto calc 
function helptext(name) {
	var item = document.getElementById(name);
	if (item.className == "helptextOn") {
		item.className= "helptextOff";
		if (name == "help_loanamount") { textOn("monthly_img"); }// special case, turn on question mark img
	} else {
		item.className= "helptextOn";
		if (name == "help_loanamount") { textOff("monthly_img"); }// special case, turn on question mark img
	}
}

// switches out the differenct credit level definitions on auto calc page
function creditLevel(level) {
	var level = document.autoform.creditlevel.value;
	clickObject(level,"help_creditlevel");
}

// takes amount from url and puts it on the calculator page
function showCalcAmount(text) {
	var monthly = getQueryVariable('monthly');
	var loanamount = getQueryVariable('loanamount');
	if (loanamount) { text = formatCurrency(loanamount); }
	if (monthly) { text = formatCurrency(monthly); }
	return text;
}

// auto app PowerCheck delivery options: changes how the check will be sent based on oversees selection
function changeOffshore(offshoreOptions) { 
	// set original choice for "when" options, in case user choses yes, then changes his/her mind
	var options;
	if (offshoreOptions == 'overnight') {options = 'overnight';}	
	if (offshoreOptions == 'usps') {options = 'usps';}
	// if user choses yes, set delivery option to yes
	if (offshoreOptions == 'y') {
		document.appform["processing.powercheck.delivery.when"][0].checked = true;
		document.appform["processing.powercheck.delivery.when"][1].disabled = true;
	}
	// if user choses no, return "when" option to original choice
	if (offshoreOptions == 'n' && options == 'overnight') {
		document.appform["processing.powercheck.delivery.when"][0].checked = true;
		document.appform["processing.powercheck.delivery.when"][1].disabled = false;
	}
	if (offshoreOptions == 'n' && options == 'usps') {
		document.appform["processing.powercheck.delivery.when"][1].checked = true;
		document.appform["processing.powercheck.delivery.when"][1].disabled = false;
	}
	if (offshoreOptions == 'n' && !options) {
		document.appform["processing.powercheck.delivery.when"][1].disabled = false;
	}

	return offshoreOptions;
}

// Bolt|Peters popup functions for surveys and usability studys
function popUp(URL) {
	var day = new Date();
	var id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=450,height=520');");
}

function stateOptions(purpose) {
	if (purpose == 'equity') {
		document.form.state[4].disabled = true;
	}
	return purpose;
}

function getState(id) {
	if (id == '1') {id = 'Alabama';}
	if (id == '2') {id = 'Alaska';}
	if (id == '3') {id = 'Arizona';}
	if (id == '4') {id = 'Arkansas';}
	if (id == '5') {id = 'California';}
	if (id == '6') {id = 'Colorado';}
	if (id == '7') {id = 'Connecticut';}
	if (id == '8') {id = 'Delaware';}
	if (id == '9') {id = 'District of Columbia';}
	if (id == '10') {id = 'Florida';}
	if (id == '11') {id = 'Georgia';}
	if (id == '12') {id = 'Hawaii';}
	if (id == '13') {id = 'Idaho';}
	if (id == '14') {id = 'Illinois';}
	if (id == '15') {id = 'Indiana';}
	if (id == '16') {id = 'Iowa';}
	if (id == '17') {id = 'Kansas';}
	if (id == '18') {id = 'Kentucky';}
	if (id == '19') {id = 'Louisiana';}
	if (id == '20') {id = 'Maine';}
	if (id == '21') {id = 'Maryland';}
	if (id == '22') {id = 'Massachusetts';}
	if (id == '23') {id = 'Michigan';}
	if (id == '24') {id = 'Minnesota';}
	if (id == '25') {id = 'Mississippi';}
	if (id == '26') {id = 'Missouri';}
	if (id == '27') {id = 'Montana';}
	if (id == '28') {id = 'Nebraska';}
	if (id == '29') {id = 'Nevada';}
	if (id == '30') {id = 'New Hampshire';}
	if (id == '31') {id = 'New Jersey';}
	if (id == '32') {id = 'New Mexico';}
	if (id == '33') {id = 'New York';}
	if (id == '34') {id = 'North Carolina';}
	if (id == '35') {id = 'North Dakota';}
	if (id == '36') {id = 'Ohio';}
	if (id == '37') {id = 'Oklahoma';}
	if (id == '38') {id = 'Oregon';}
	if (id == '39') {id = 'Pennsylvania';}
	if (id == '40') {id = 'Rhode Island';}
	if (id == '41') {id = 'South Carolina';}
	if (id == '42') {id = 'South Dakota';}
	if (id == '43') {id = 'Tennessee';}
	if (id == '44') {id = 'Texas';}
	if (id == '45') {id = 'Utah';}
	if (id == '46') {id = 'Vermont';}
	if (id == '47') {id = 'Virginia';}
	if (id == '48') {id = 'Washington';}
	if (id == '49') {id = 'West Virginia';}
	if (id == '50') {id = 'Wisconsin';}
	if (id == '51') {id = 'Wyoming';}
	return id;
}

// CHANGES CURRENCY FORMAT
function formatCurrency(num) {

    var num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";

    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();

    if(cents<10)
        cents = "0" + cents;

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    }

    return (((sign)?'':'-') + '$' + num);
}

// CHANGES CURRENCY FORMAT - no $ or commas
function formatCurrency2(num) {

    var num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";

    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();

    if(cents<10)
        cents = "0" + cents;

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
        num = num.substring(0,num.length-(4*i+3))+ num.substring(num.length-(4*i+3));
    }

    return (((sign)?'':'-') + num);
}

function go() { 
	top.location.href = document.helpForm.links.options[document.helpForm.links.selectedIndex].value; 
}

function go3() { 
	top.location.href = document.testform.links1.options[document.testform.links1.selectedIndex].value; 
}
