var errorSet = null;

FieldObj = function() {
   var Field;
   this.get_Field = function() { return Field; }
   this.set_Field = function(val) { Field = val; }

   var ErrorMessage;
   this.get_ErrorMessage = function() { return ErrorMessage; }
   this.set_ErrorMessage = function(val) { ErrorMessage = val; }
}

function ResetHighlight() {
   var field;

   if (errorSet != null) {
      for (var i = 0; i < errorSet.length; i++) {
         errorSet[i].Field.className = 'elqField'
      }
    }
   errorSet = new Array();
}

function DisplayErrorSet(ErrorSet) {
   var element;
   var ErrorMessage = '';

   for (var i = 0; i < ErrorSet.length; i++) {
      ErrorMessage = ErrorMessage + ErrorSet[i].ErrorMessage + '\n';
      ErrorSet[i].Field.className = 'elqFieldValidation';
   }

   if (ErrorMessage != '')
      alert(ErrorMessage);
}

function ValidateRequiredField(Element) {
   if (Element.value == null || Element.value == "") {
     return false;
   } else
   return true;
}

function ValidateEmailAddress(Element) {
   var varRegExp='^[A-Z0-9!#\\$%&\'\\*\\+\\-/=\\?\\^_`\\{\\|\\}~][A-Z0-9!#\\$%&\'\\*\\+\\-/=\\?\\^_`\\{\\|\\}~\\.]{0,62}@([A-Z0-9](?:[A-Z0-9\\-]{0,61}[A-Z0-9])?(\\.[A-Z0-9](?:[A-Z0-9\\-]{0,61}[A-Z0-9])?)+)$';
   if ((Element) && (Element.value != '')) {
      var reg = new RegExp(varRegExp,"i");
      var match = reg.exec(Element.value);
         if ((match) && (match.length=3) && (match[1].length<=255) && ((match[2].length>=3) & (match[2].length<=7)))
            return true;
   }
   return false;
}

function ValidateDataTypeLength(Element, args, ErrorMessage) {
   var elementVal = Element.value;
   var testPass = true;

   if (Element) {
      if (args.Type == 'text') {
         if ((args.Minimum != '') && (elementVal.length < args.Minimum))
            testPass = false;
         if ((args.Maximum != '') && (elementVal.length > args.Maximum))
            testPass = false;
      }
      else if (args.Type == 'numeric') {
         if ((elementVal != '') && (elementVal != parseFloat(elementVal)))
            testPass = false;
         if (args.Minimum != '') {
            if ((elementVal == '') || (parseFloat(elementVal) < args.Minimum))
            testPass = false;
         }
         if (args.Maximum != '') {
            if ((elementVal != '') && (parseFloat(elementVal) > args.Maximum))
               testPass = false;
         }
      }
   }
   else
      testPass = false;
   return testPass;
}
// ************   Validation for Generic Catch All Forms ******************
function CheckElqForm(elqForm) {
var args = null;
var allValid = true;

if (elqForm == null) {
   alert('Unable to execute form validation!\Unable to locate correct form');
   return false;
}
ResetHighlight();


formField = new FieldObj();
formField.Field = elqForm.elements['email'];
formField.ErrorMessage ='Form field Email Address contains an invalid email address'
if (formField.Field != null) {
   if (!ValidateEmailAddress(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
   else
	{
		setCookie('LeadEmail',formField.Field.value, '', '/', '.mortgagecoach.com');
	}
}

formField = new FieldObj();
formField.Field = elqForm.elements['first_name'];
formField.ErrorMessage ='Form field - First Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['last_name'];
formField.ErrorMessage ='Form field - Last Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['company'];
formField.ErrorMessage ='Form field - Company Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['phone'];
formField.ErrorMessage ='Form field - Phone Number is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['country'];
formField.ErrorMessage ='Form field - Country is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}


formField = new FieldObj();
formField.Field = elqForm.elements['city'];
formField.ErrorMessage ='Form field - City is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

if (elqForm.elements['role']) {
	formField = new FieldObj();
	formField.Field = elqForm.elements['role'];
	formField.ErrorMessage ='Form field - Job Role is required'
	if (formField.Field != null) {
	   if (!ValidateRequiredField(formField.Field)) {
		  errorSet.push(formField);
		  allValid = false;
	   }
	}
}

formField = new FieldObj();
formField.Field = elqForm.elements['years_in_business'];
formField.ErrorMessage ='Form field - Years in loan origination is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}


formField = new FieldObj();
formField.Field = elqForm.elements['past_clients'];
formField.ErrorMessage ='Form field - Past Clients in Database is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['training_expenses'];
formField.ErrorMessage ='Form field - Annual Training Expenses is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['monthly_marketing_budget'];
formField.ErrorMessage ='Form field - Monthly Marketing Budget is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['loans_last_month'];
formField.ErrorMessage ='Form field - # of Loans closed last month is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

if (!allValid) {
   DisplayErrorSet(errorSet);
   return false;
}

return true;
}
// ************   Validation for Basic Lead Forms ******************
function CheckBasicForm(elqForm) {
var args = null;
var allValid = true;

if (elqForm == null) {
   alert('Unable to execute form validation!\Unable to locate correct form');
   return false;
}
ResetHighlight();


formField = new FieldObj();
formField.Field = elqForm.elements['email'];
formField.ErrorMessage ='Form field Email Address contains an invalid email address'
if (formField.Field != null) {
   if (!ValidateEmailAddress(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
   else
	{
		setCookie('LeadEmail',formField.Field.value, '', '/', '.mortgagecoach.com');
	}
}

formField = new FieldObj();
formField.Field = elqForm.elements['first_name'];
formField.ErrorMessage ='Form field - First Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['last_name'];
formField.ErrorMessage ='Form field - Last Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['company'];
formField.ErrorMessage ='Form field - Company Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['phone'];
formField.ErrorMessage ='Form field - Phone Number is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

if (!allValid) {
   DisplayErrorSet(errorSet);
   return false;
}

return true;
}

// ************   Validation for Referral Forms ******************

function CheckFwd2FriendForm(elqForm) {
var args = null;
var allValid = true;

if (elqForm == null) {
   alert('Unable to execute form validation!\Unable to locate correct form');
   return false;
}
ResetHighlight();

formField = new FieldObj();
formField.Field = elqForm.elements['emailfrom'];
formField.ErrorMessage ='Form Field - Your Email Address is required'
if (formField.Field != null) {
   if (!ValidateEmailAddress(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['namefrom'];
formField.ErrorMessage ='Form field - Your Full Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}
formField = new FieldObj();
formField.Field = elqForm.elements['Name1'];
formField.ErrorMessage ='Form field - Friend Full Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['Email1'];
formField.ErrorMessage ='Form Field - Email Address of Friend is required'
if (formField.Field != null) {
   if (!ValidateEmailAddress(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}
formField = new FieldObj();
formField.Field = elqForm.elements['email'];
formField.ErrorMessage ='Form field - Friends Email is required'
if (formField.Field != null) {
   if (!ValidateEmailAddress(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['last_name'];
formField.ErrorMessage ='Form field - Last Name is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['company'];
formField.ErrorMessage ='Form field - Company Name is required!'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}

formField = new FieldObj();
formField.Field = elqForm.elements['phone'];
formField.ErrorMessage ='Form field - Phone Number is required'
if (formField.Field != null) {
   if (!ValidateRequiredField(formField.Field)) {
      errorSet.push(formField);
      allValid = false;
   }
}


if (!allValid) {
   DisplayErrorSet(errorSet);
   return false;
}

return true;
}

function submitBasicForm(elqForm) {
   if (CheckBasicForm(elqForm)) {
      return true;
   }
   else { return false; }
}

function submitForm(elqForm) {
   if (CheckElqForm(elqForm)) {
      return true;
   }
   else { return false; }
}

function submitFwd2FriendForm(elqForm) {
   if (CheckFwd2FriendForm(elqForm)) {
      return true;
   }
   else { return false; }
}


function prepareSelectsForEloqua(elqForm) {
   var selects = elqForm.getElementsByTagName("SELECT");
   for (var i = 0; i < selects.length; i++) {
       if (selects[i].multiple) {
           createEloquaSelectField(elqForm, selects[i]);
       }
   }
   return true;
}
function createEloquaSelectField(elqForm, sel) {
   var inputName = sel.name;
   var newInput = document.createElement('INPUT');
   newInput.style.display = "none";
   newInput.name = inputName;
   newInput.value = "";
   for (var i = 0; i < sel.options.length; i++) {
       if (sel.options[i].selected) {
           newInput.value += sel.options[i].value + "::";
       }
   }
   if (newInput.value.length > 0) {
       newInput.value = newInput.value.substr(0, newInput.value.length - 2);
   }
   sel.disabled = true;
   newInput.id = inputName;
   elqForm.insertBefore(newInput, elqForm.firstChild);
}

function prepareCheckboxesForEloqua(elqForm) {
	var checkboxes = elqForm.getElementsByTagName("INPUT");
	for (var i = 0; i < checkboxes.length; i++) {
	    if (checkboxes[i].type == "checkbox") {
		    if (getCountOfCheckboxes(checkboxes[i].name, checkboxes) > 1) {
			    // this checkbox has multiple definitions
			    createEloquaCheckboxField(elqForm, checkboxes[i].name, checkboxes);
		    }
		}
	}
	
	return true;
}

function getCountOfCheckboxes(name, checkboxArray) {
	var count = 0;
	for (var i = 0; i < checkboxArray.length; i++) {
		if (checkboxArray[i].name == name && !checkboxArray[i].disabled) {
			count++;
		}
	}
	
	return count;
}

function createEloquaCheckboxField(elqForm, name, checkboxes) {
	var inputName = name;           
    
    var newInput = document.createElement('INPUT');
    newInput.style.display = "none";
    newInput.name = inputName;
    newInput.value = "";
    
	for (var i = 0; i < checkboxes.length; i++) {
		if (checkboxes[i].name == name) {
			if (checkboxes[i].checked) {
				newInput.value += checkboxes[i].value + "::";  
			}
			checkboxes[i].disabled = true;
		}
	}
	
	newInput.id = inputName;
    elqForm.insertBefore(newInput, elqForm.firstChild);
}

function checkEmail(ea)
{
    var reEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if (!reEmail.test(ea)) {
        alert("Please enter a valid Email Address!")
        return false
    }
    return true
}

function changeCase(frmObj) {
var index;
var tmpStr;
var tmpChar;
var preString;
var postString;
var strlen;
tmpStr = frmObj.value.toLowerCase();
strLen = tmpStr.length;
if (strLen > 0)  {
for (index = 0; index < strLen; index++)  {
if (index == 0)  {
tmpChar = tmpStr.substring(0,1).toUpperCase();
postString = tmpStr.substring(1,strLen);
tmpStr = tmpChar + postString;
}
else {
tmpChar = tmpStr.substring(index, index+1);
if (tmpChar == " " && index < (strLen-1))  {
tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
preString = tmpStr.substring(0, index+1);
postString = tmpStr.substring(index+2,strLen);
tmpStr = preString + tmpChar + postString;
         }
      }
   }
}
frmObj.value = tmpStr;
}

function fixPhone(x) {

	//strip invalid characters
	for (i = 0; i < x.value.length; i++) {
		x.value = x.value.replace('-','');
		x.value = x.value.replace(' ','');
		x.value = x.value.replace('.','');
		x.value = x.value.replace('(','');
		x.value = x.value.replace(')','');
		x.value = x.value.replace('_','');
		x.value = x.value.replace('!','');
		x.value = x.value.replace('@','');
		x.value = x.value.replace('#','');
		x.value = x.value.replace('$','');
		x.value = x.value.replace('%','');
		x.value = x.value.replace('^','');
		x.value = x.value.replace('&','');
		x.value = x.value.replace('*','');
		x.value = x.value.replace('=','');

		//these must be in this order because they contain each other
		x.value = x.value.replace('ext','');
		x.value = x.value.replace('ex','');
		x.value = x.value.replace('x','');
	}

	//strip leading one
	if (x.value.substring(0,1) == "1") {
		x.value = x.value.substring(1,x.value.length);
	}

	//format number == 10
	if (x.value.length == 10) { 
		x.value = "(" + x.value.substring(0,3) + ") " + x.value.substring(3,6) + "-" + x.value.substring(6,x.value.length);
	}

	//format number > 10 (extension)
	else if (x.value.length > 10) { 
		x.value = "(" + x.value.substring(0,3) + ") " + x.value.substring(3,6) + "-" + x.value.substring(6,10) + " x" + x.value.substring(10,x.value.length);
	}


}
//end function fixPhone
function changeToLowerCase(Obj) {
	Obj.value=Obj.value.toLowerCase();
}

function doLink(url) {
//	alert(url);
	window.location.href = url;
}

function getTrackingParamValue(strQStrParam)
{
var strQStrParamValue = '';

		if	(strQStrParam == "EmailAddress")
		{
			if  (ReadCookie('LeadEmail'))
  			{
				strQStrParamValue = ReadCookie('LeadEmail');
				return strQStrParamValue;
  			}
			return getQueryStringParamValue(strQStrParam);
		}
}

function getQueryStringParamValue(strQStrParam)
{
var defaultValue=null;
var strURL = document.location.href;
var strQStrParamValue = '';
var useremail = null;
  
	if (strURL.indexOf('?') != -1)
	{
		strQStrParamValue = strURL.substr(strURL.indexOf('?') + 1);
		if (strQStrParamValue.indexOf(strQStrParam) != -1)
		{
			strQStrParamValue = strQStrParamValue.substr(strQStrParamValue.indexOf(strQStrParam));
			strQStrParamValue = strQStrParamValue.substr(strQStrParamValue.indexOf('=') + 1);
			if (strQStrParamValue.indexOf('&') != -1)
				strQStrParamValue = strQStrParamValue.substr(0,strQStrParamValue.indexOf('&'));
			return strQStrParamValue;
			}else{
			strQStrParamValue = defaultValue;
			return strQStrParamValue;
			}
		}else{
		strQStrParamValue = defaultValue;
		return strQStrParamValue;
	}
}
function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}



function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}			

function setCookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
else
{
expires = 20 * 365 * 1000 * 60 * 60 * 24;
}

var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

