// This file includes all the objects(functions) needed for the website functionality

// -------------------------------------------------------------------------------------------------------------------------------------------

// setPage() will use the variable(s) passed in the () to change the content of the elements in the html page; it returns false to prevent the html attempt to change the location when the function is called from an anchor.

function setPage( element1, content1, element2, content2, element3, content3, element4, content4, element5, content5 ) {

	if (( content1 ) && ( element1 )) document.getElementById(element1).innerHTML = content1;
	if (( content2 ) && ( element2 )) document.getElementById(element2).innerHTML = content2;
	if (( content3 ) && ( element3 )) document.getElementById(element3).innerHTML = content3;
	if (( content4 ) && ( element4 )) document.getElementById(element4).innerHTML = content4;
	if (( content5 ) && ( element5 )) document.getElementById(element5).innerHTML = content5;

	return false;
}

// -------------------------------------------------------------------------------------------------------------------------------------------

// The following 3 functions manipulate cookies

function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

function delCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// -------------------------------------------------------------------------------------------------------------------------------------------

// validateForm() ensures that there is an entry for each field

function validateForm(form)
{
	var showValues = ''; // for testing

	for(var i=0; i<form.elements.length; i++) {
		if (form.elements[i].value == "" && form.elements[i].type != 'hidden') {
			alert("Please complete the missing information.");
			form.elements[i].focus();
			return false;
		}
		showValues += (form.elements[i].name + ' = ' + form.elements[i].value + '\n'); // for testing
	} 
	prepareSplittedFields(form);
//	alert(showValues); //return false; // for testing
	return true;
}

// -------------------------------------------------------------------------------------------------------------------------------------------

function checkNumeric(field,minLength) {
	if(field.value.length < 1) return;
	if(field.value.length<minLength){
		alert("This field must have minimum " + minLength + " digits.");
		field.select();
		return false;
	}
	for (var i=0; i<field.value.length; i++) {
		var c = field.value.charAt(i);
      	if (((c < "0") || (c > "9"))) {
			alert("Numeric characters only please.\nNo commas, periods or other characters.");
			field.select();
			return false;
		}
	}
	return true;
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function noenter() {
	return !(window.event && window.event.keyCode == 13);
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function noBackSpace() {
	return !(window.event && window.event.keyCode == 8);
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function checkABA(s) {

  var i, n, t;

  // First, remove any non-numeric characters.

  t = "";
  for (i = 0; i < s.length; i++) {
    c = parseInt(s.charAt(i), 10);
    if (c >= 0 && c <= 9)
      t = t + c;
  }

  // Check the length, it should be nine digits.

  if (t.length != 9)
    return false;

  // Now run through each digit and calculate the total.

  n = 0;
  for (i = 0; i < t.length; i += 3) {
    n += parseInt(t.charAt(i),     10) * 3
      +  parseInt(t.charAt(i + 1), 10) * 7
      +  parseInt(t.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.

  if (n != 0 && n % 10 == 0)
	return true;
  else
	return false;
}

// -----------------------------------------------------------------------------------------------------------------------------------------

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
if(isNN)
  document.captureEvents(Event.KEYPRESS);

function autoTab(input,len, e){
  var keyCode = (isNN)?e.which:e.keyCode;
  var filter = (isNN)?[0,8,9]:[0,8,9,16,17,18,37,38,39,40,46];
  if(input.value.length >= len && !containsElement(filter,keyCode)){
    input.value = input.value.slice(0,len);
    input.form[(getIndex(input)+1)%input.form.length].focus();
    input.form[(getIndex(input)+1)%input.form.length].select();
  }
  function containsElement(arr, ele){
    var found = false, index = 0;
    while(!found && index < arr.length)
      if(arr[index]==ele)
        found = true;
      else
        index++;
    return found;
  }
  function getIndex(input){
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index==-1)
      if (input.form[i] == input)index = i;
      else i++;
    return index;
  }
  return true;
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function checkEmail(field)
{
		if(field.value == '') return false;
		var str=field.value;
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail")
			field.focus();
			return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail")
			field.focus();
			return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail")
		   	field.focus();
			return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail")
			field.focus();
			return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail")
		  	field.focus();
			return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail")
		    	field.focus();
			return false
		 }

		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail")
		    	field.focus();
			return false
		 }

 		 return true
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function prepareSplittedFields(form) {
	var alphabet = "abcdefghijklmnopqrstuvwxyz";

	// clean hidden splitted fields if they already have some values

	for(var i=0; i < form.elements.length; i++) {
		if(form.elements[i].name.indexOf('_split') != -1) {
			var concatenated_field_name = new Array();
			for (var l=0; l<=25; l++){
				var string = '_' + alphabet.charAt(l) + '_split';
				if(form.elements[i].name.indexOf(string) != -1) {
					concatenated_field_name = form.elements[i].name.split(string); 
					break;
				}
			}
	
			for(var j=0; j < form.elements.length; j++) {
				if(form.elements[j].name == concatenated_field_name[0]) form.elements[j].value = '';
			}
		}
	}
	
	// get values for splitted fields
	
	for(var i=0; i < form.elements.length; i++) {
		if(form.elements[i].name.indexOf('_split') != -1) {
			var concatenated_field_name = new Array();
			for (var l=0; l<=25; l++){
				var string = '_' + alphabet.charAt(l) + '_split';
				if(form.elements[i].name.indexOf(string) != -1) {
					concatenated_field_name = form.elements[i].name.split(string); 
					break;
				}
			}
	
			for(var j=0; j < form.elements.length; j++) {
				if(form.elements[j].name == concatenated_field_name[0]) form.elements[j].value += form.elements[i].value;
			}
		}
	}
}

// -----------------------------------------------------------------------------------------------------------------------------------------

function trackShareAsale() {

	// set the cookie lifespan; this will result in having the cookie phisically writen on the client machine
	var expDays = 30;
	var expDate = new Date();
	expDate.setTime(expDate.getTime() +  (24 * 60 * 60 * 1000 * expDays));

	// separate the elements found in the querystring into pairs and look for the "Source" value
	var pairs = location.search.substring(1, location.search.length).split("&");
	var SSAID = "";
	for (var i=0; i<pairs.length; i++) {
		if (pairs[i].indexOf("SSAID=") != -1) {
			SSAID = pairs[i].substring(pairs[i].indexOf("=")+1, pairs[i].length);
		}
	}

	// check if the visitor is new and record the new visit
	var oldSSAID = getCookie('SSAID');

	if (( SSAID != oldSSAID ) && ( SSAID != "" )) {
		setCookie('SSAID', SSAID, expDate, '/');
		setCookie('Source', SSAID, expDate, '/');
	}
}

// -----------------------------------------------------------------------------------------------------------------------------------------


function start(siteName) {
	setPage('hiddenForm', hiddenForm );
	trackOrigin(siteName, 'track', '');
	document.hiddenForm.Site.value = siteName;
	document.hiddenForm.Source.value = getCookie('Source');
	document.hiddenForm.Referrer.value = getCookie('Referrer');
	next();
}

// trackOrigin() will save the new visitor's tracking information as cookies and call the server script to record it in a database. The function needs the cookies manipulation functions too

function trackOrigin( site, trackingElement, recordingScript ) {

	// set the cookie lifespan; this will result in having the cookie phisically writen on the client machine
	var expDays = 360;
	var expDate = new Date();
	expDate.setTime(expDate.getTime() +  (24 * 60 * 60 * 1000 * expDays));

	// separate the elements found in the querystring into pairs and look for the "Source" value
	var pairs = location.search.substring(1, location.search.length).split("&");
	var newSource = "";
	for (var i=0; i<pairs.length; i++) {
		if (pairs[i].indexOf("Source=") != -1) {
			newSource = pairs[i].substring(pairs[i].indexOf("=")+1, pairs[i].length);
		}
	}

	// get the page referrer
	var newReferrer = document.referrer;
	var oldReferrer = getCookie('Referrer');

	// check if the visitor is new and record the new visit
	var oldSource = getCookie('Source');

	if((newReferrer.indexOf(site+"/") == -1)&&(newReferrer != "")&&(oldReferrer != newReferrer)) {
		setCookie('Referrer', newReferrer, null, '/');
		document.getElementById(trackingElement).innerHTML="<img src=http://www.mortgageloanpage.com/cgi-bin/trackVisitor.pl?Site=" + site + "&Source=" + newSource + "&Referrer=" + newReferrer + " height=1 width=1>";
	}

	if (( newSource != oldSource ) && ( newSource != "" )) {
		setCookie('Site', site, null, '/');
		setCookie('Source', newSource, null, '/');
	}

}

// -------------------------------------------------------------------------------------------------------------------------------------------


// countCharacters() limits the space available in a textArea input with the value passed to the function, and, if requested, displays the remaining space available

function countCharacters(field, length, element) {

	var remaining = length - field.value.length;
	if (remaining<1) {
		field.value = field.value.substring(0, length);
		remaining = 0;
	}

	if(element) document.getElementById(element).innerHTML = "Remaining space available: " + remaining + " characters";
}


// -------------------------------------------------------------------------------------------------------------------------------------------

