// Generic Form Validation
// Jacob Hage (jacob@hage.dk)
var checkObjects	= new Array();
var errors		= "";
var returnVal		= false;
var language		= new Array();
language["header"]	= "Please check the following:"
language["start"]	= "->";
language["field"]	= "";
language["require"]	= " is required";
language["min"]		= " and must consist of at least ";
language["max"]		= " and must not contain more than ";
language["minmax"]	= " and no more than ";
language["chars"]	= " characters";
language["num"]		= " and must contain a number";
language["email"]	= " must contain a valid e-mail address";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, d) {
var p;
var i;
var x;
if (!d) d = document;
if ((p=n.indexOf("?"))>0&&parent.frames.length) {
d = parent.frames[n.substring(p+1)].document;
n = n.substring(0,p);
}
if (!(x = d[n]) && d.all) x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++) {
x = d.forms[i][n];
}
for (i = 0; !x && d.layers && i < d.layers.length; i++) {
x = define(n, type, HTMLname, min, max, d.layers[i].document);
return x;       
}
eval("V_"+n+" = new formResult(x, type, HTMLname, min, max);");
checkObjects[eval(checkObjects.length)] = eval("V_"+n);
}
function formResult(form, type, HTMLname, min, max) {
this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.min  = min;
this.max  = max;
}

function validate() {
	if (checkObjects.length > 0) {
		errorObject = "";
		for (i = 0; i < checkObjects.length; i++) {
			validateObject = new Object();
			validateObject.form = checkObjects[i].form;
			validateObject.HTMLname = checkObjects[i].HTMLname;
			validateObject.val = checkObjects[i].form.value;
			validateObject.len = checkObjects[i].form.value.length;
			validateObject.min = checkObjects[i].min;
			validateObject.max = checkObjects[i].max;
			validateObject.type = checkObjects[i].type;
			if (validateObject.type == "num" || validateObject.type == "string") {
			if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == "num" && isNaN(validateObject.val))) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
			} else if (validateObject.min && validateObject.max && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'] + "\n";
			} else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
			} else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
			} else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n"; }
			} else if(validateObject.type == "email") {
				// Checking existense of "@" and ".". 
				// Length of must >= 5 and the "." must 
				// not directly precede or follow the "@"
				if ( (validateObject.val.indexOf("@") == -1) 
					|| (validateObject.val.charAt(0) == ".") 
					|| (validateObject.val.charAt(0) == "@") 
					|| (validateObject.len < 6) 
					|| (validateObject.val.indexOf(".") == -1) 
					|| (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") 
					|| (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")
				) { 
					errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n";
				}
			}
		}
	}
	if (errors) {
		alert(language["header"].concat("\n" + errors));
		errors = "";
		return returnVal = false;
	} else {
		var zform = document.forms["app"];
		var zunsecured = zform.debtamount.value;
		var st = zform.state.value;
		var zip = zform.zipcode.value;
		var ph1a = zform.pp1.value;
		var ph1b = zform.pp2.value;
		var ph1c = zform.pp3.value;
		var ph1d = zform.ppx.value;
		var ph2a = zform.sp1.value;
		var ph2b = zform.sp2.value;
		var ph2c = zform.sp3.value;
		var ph2d = zform.spx.value;
		var ph1 = ph1a.concat(ph1b, ph1c, "x", ph1d);
		var ph2 = ph2a.concat(ph2b, ph2c, "x", ph2d);
		var ph3 = ph1a.concat(ph1b, ph1c);
		var ph4 = ph2a.concat(ph2b, ph2c);
		if(st == "select") {
			alert("Please select a state from the list.");
			return returnVal = false;
		}
		if(zip.length < 5) {
			alert("Please enter a zipcode.");
			return returnVal = false;
		}
		if(ph1a.length < 3 || ph1b.length < 3 || ph1c.length < 4) {
			alert("Please enter your Primary phone number");
			return returnVal = false;
		}
		if(ph2a == "" && ph2b == "" && ph2c == "") {
			zform.phone2.value = "";
		} else {
			if(ph2a.length < 3 || ph2b.length < 3 || ph2c.length < 4) {
				alert("Please check that your Other phone number is correct.  Are you missing numbers?")
				return returnVal = false;
			}
			if(ph2d == "") {
				zform.phone2.value = ph4;
			} else {
				zform.phone2.value = ph2;
			}
		}
		if(ph1d == "") {
			zform.phone1.value = ph3;
		} else {
			zform.phone1.value = ph1;
		}
		
		zform.good_url.value = "http://www.debtshield.com/thankyou.html";
		switch(zunsecured) {
			case "999":
				alert("Please select an unsecured debt amount.");
				return returnVal = false;
				break;
			case "2999":
				zform.good_url.value = "http://www.debtshield.com/thankyou_return.html";
				return returnVal = true;
				break;
			case "7500":
				zform.good_url.value = "http://www.debtshield.com/thankyou_refer.html";
				return returnVal = true;
				break;
			default:
				launchPTT(zform);
				return returnVal = true;
		}
	}
}

function init(no_cmi) {
	define('firstname', 'string', 'First Name');
	define('debtamount', 'string', 'Unsecured Debt');
	define('lastname', 'string', 'Last Name');
	define('email', 'email', 'Email');
	if(!no_cmi){
		addCMIOption();
	}
}

function stringFilter (input) {
	var s = input.value;
	var filteredValues = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz()- !@#$%^&*\"?/><,.~_+=|\\'`{}[]:;";     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	input.value = returnString;
}

function stringFilter2 (input) {
	var s = input.value;
	var filteredValues = "\""     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	input.value = returnString;
}

function stringFilter3 (input) {
	var s = input.value;
	var filteredValues = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz()- !@#$%^&*\"?/><,~_+=|\\'`{}[]:;";    // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	input.value = returnString;
}

function checkCR(evt) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

document.onkeypress = checkCR;

function remove_XS_whitespace(item)
{
  var tmp = "";
  var item_length = item.value.length;
  var item_length_minus_1 = item.value.length - 1;
  for (index = 0; index < item_length; index++)
  {
    if (item.value.charAt(index) != ' ')
    {
      tmp += item.value.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.value.charAt(index+1) != ' ' && index != item_length_minus_1)
        {
          tmp += item.value.charAt(index);
        }
      }
    }
  }
  item.value = tmp;
}
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
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();
}

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 checkHours(){
	var t = new Date();

	// GMT version of total minutes today
	var utc_total_min_today = (t.getUTCHours()*60) + t.getUTCMinutes();
	var est_timezone_offset = 240;

	// check for thanksgiving
	if( t.getFullYear() == 2009 && t.getMonth() == 10 && (t.getDate() == 26 || t.getDate() == 27 || t.getDate() == 28) ) {
		return false;
	} 

	if( t.getFullYear() == 2009 && t.getMonth() == 10 && t.getDate() == 25 && utc_total_min_today >= ((18*60) + est_timezone_offset ) ) {
		return false;
	}

	// check for new years 
	if( t.getFullYear() == 2009 && t.getMonth() == 11 && t.getDate() == 31 ) {
		return false;
	} 
	
	if( t.getFullYear() == 2010 && t.getMonth() == 0 && t.getDate() == 1 ) {
		return false;
	} 


	// check for saturday, mar 27,2010 open 9:30 AM - 3 PM
	if( t.getFullYear() == 2010 && t.getMonth() == 2 && t.getDate() == 27 ) {
		if( utc_total_min_today >= ((9*60)+30) + est_timezone_offset &&
		    utc_total_min_today <= ((15*60)) + est_timezone_offset) {
			return true;
		}
	}
	
/*
Hours of Operation - DCs (Updated as of 10/28/2009)
Monday - Thursday 9:30 am to 9:30 pm
Friday 9:30 am to 6:00 pm
*/

	var mon_to_wed_open = (9*60) + 30;	// 9:30 am
	var mon_to_wed_close = (21*60);		// 9:30 pm

	var thr_open = (9*60) + 30;			// 9:30 am
	var thr_close = (21*60) + 30;		// 9:30 pm

	var fri_open = (9*60) + 30;		// 9:30 am
	var fri_close = (18*60);		// 6:00 pm

	if(t.getDay() >= 1 && t.getDay() <= 3){  // Monday - Wednesday
		if(utc_total_min_today >= mon_to_wed_open + est_timezone_offset &&
		   utc_total_min_today <= mon_to_wed_close + est_timezone_offset){
			return true;
		}
	}

	if(t.getDay() == 4){  // Thursday
		if(utc_total_min_today >= thr_open + est_timezone_offset &&
		   utc_total_min_today <= thr_close + est_timezone_offset){
			return true;
		}
	}
	
	if(t.getDay() == 5){  // Friday
		if(utc_total_min_today >= fri_open + est_timezone_offset &&
		   utc_total_min_today <= fri_close + est_timezone_offset){
			return true;
		}
	}
	return false;
}

function launchPTT(form){
	if(form.debtamount.value >= 8500 &&
	   form.state.value != "DE" &&
	   form.state.value != "GA" &&
	   form.state.value != "HI" &&
	   form.state.value != "ID" &&
	   form.state.value != "KS" &&
	   form.state.value != "ME" &&
	   form.state.value != "MN" &&
	   form.state.value != "MS" &&
	   form.state.value != "NV" &&
	   form.state.value != "NH" &&
	   form.state.value != "NC" &&
	   form.state.value != "RI" &&
	   form.state.value != "SC" &&
	   form.state.value != "UT" &&
	   form.state.value != "VA" &&
	   form.state.value != "DC" &&
	   form.state.value != "WV" &&
	   form.state.value != "WI" &&
	   form.state.value != "WY" &&
	   checkHours() )
	{
		popup_url = 'https://services.debtshield.net/SubmitLead/process_call.php';
		popup_url += '?phone1=' + document.forms["app"].phone1.value;
		popup_url += '&phone2=' + document.forms["app"].phone2.value;
		popup_url += '&firstname=' + document.forms["app"].firstname.value;

		// remove the querystring from the current URL
		current_url_parts = window.location.href.split( "?" );
		current_url = current_url_parts[0];

		popup_url += '&from=' + current_url;

		window.open( popup_url,'PushToTalk','height=380,width=530,left=20,top=20,resizable=no,menubar=0,toolbar=0,status=0');

		if(form.Best_Time_to_Call.value == 'Immediately_pend'){
			form.Best_Time_to_Call.options[0].value = 'Immediately';
		}else{
			form.ptt.value = 'ptt';
		}
	}
}

function addCMIOption(){
	if(checkHours() && document.forms[0] && document.forms[0].Best_Time_to_Call){
		// Add Contact Now option
		var best_time_sel = document.forms[0].Best_Time_to_Call;
		best_time_sel.options[0].text = 'Contact Me ASAP';
		best_time_sel.options[0].value = 'Immediately_pend';
	}
}




/* GM Functions start here */ 

function displayPTTOption1(){
	displayTimezoneDropdown();
	displayPTTField();
	displayClickIDField();
	document.write('<label for="Best_Time_to_Call">Best Time to Call: </label>');
	document.write('<select name="Best_Time_to_Call" class="best-time">');
	document.write('<option selected="selected" value="select">Select One Please</option>');
	document.write('<option value="9 am - 10 am">9 am - 10 am</option>');
	document.write('<option value="10 am - 11 am">10 am - 11 am</option>');
	document.write('<option value="11 am -12 noon">11 am - 12 noon</option>');
   	document.write('<option value="12 pm - 1 pm">12 pm - 1 pm</option>');
   	document.write('<option value="1 pm - 2 pm">1 pm - 2 pm</option>');
   	document.write('<option value="2 pm - 3 pm">2 pm - 3 pm</option>');
   	document.write('<option value="3 pm - 4 pm">3 pm - 4 pm</option>');
	document.write('<option value="4 pm - 5 pm">4 pm - 5 pm</option>');
	document.write('<option value="5 pm - 6 pm">5 pm - 6 pm</option>');
	document.write('<option value="6 pm - 7 pm">6 pm - 7 pm</option>');
	document.write('<option value="7 pm - 8 pm">7 pm - 8 pm</option>');
	document.write('<option value="8 pm - 9 pm">8 pm - 9 pm</option>');
	document.write('<option value="9 pm - 10 pm">9 pm - 10 pm</option>');
	document.write('<option value="10 pm - 11 pm">10 pm - 11 pm</option>');
	document.write('</select>');
	addCMIOption();
}

function displayPTTOption2(){
	displayPTTField();
	displayClickIDField();
	if(checkHours()){
		displayTimezoneDropdown();
		document.write('<label for="Best_Time_to_Call">Contact Me Immediately </label>');
		document.write('<div style="display: none;"><select name="Best_Time_to_Call"><option selected="selected" value="select">Select One Please</option></select></div>');
		document.write('<input type="checkbox" name="Best_Time_to_Call_CheckBox" checked/>');
	}
}

function displayPTTOption3(){
	displayPTTField();
	displayClickIDField();
	displayTimezoneDropdown();
	document.write('<div style="display: none;"><select name="Best_Time_to_Call"><option selected="selected" value="select">Select One Please</option></select></div>');
}

function displayTimezoneDropdown(){
	document.write('<div style="display: none;">');
	document.write('<select name="timezone" id="timezone"><option value=""></option>');
	document.write('<option value="EST">Eastern</option><option value="CST">Central</option><option value="MST">Mountain</option>');
	document.write('<option value="PST">Pacific</option><option value="AST">Pacific</option><option value="HST">Hawaii</option></select>');
	document.write('</div>');
}

function displayPTTField(){
	document.write('<input type="hidden" name="ptt" value="" />');
}

function displayClickIDField(){
	document.write('<input type="hidden" name="click_id" value="2985" />');
}

// for Global Media to use PTT
function validateGM(option){
	var form = document.forms[0];
	var newDebtAmount = new String();
	newDebtAmount = form.debtamount.value;
	newDebtAmount = newDebtAmount.replace(/,/,''); 
	newDebtAmount = newDebtAmount.replace(/\$/,''); 
	if(newDebtAmount >= 8500 &&
	   form.state.value != "DE" &&
	   form.state.value != "GA" &&
	   form.state.value != "HI" &&
	   form.state.value != "ID" &&
	   form.state.value != "KS" &&
	   form.state.value != "ME" &&
	   form.state.value != "MN" &&
	   form.state.value != "MS" &&
	   form.state.value != "NV" &&
	   form.state.value != "NH" &&
	   form.state.value != "NC" &&
	   form.state.value != "RI" &&
	   form.state.value != "SC" &&
	   form.state.value != "UT" &&
	   form.state.value != "VA" &&
	   form.state.value != "DC" &&
	   form.state.value != "WV" &&
	   form.state.value != "WI" &&
	   form.state.value != "WY" &&
	   checkHours() )
	{
		popup_url = 'https://services.debtshield.net/SubmitLead/process_call.php';
		var newPhone1 = new String();
		var newPhone2 = new String();
		newPhone1 = document.forms[0].phone1.value;
		newPhone1 = newPhone1.replace(/[^\d]/g,'');
		popup_url += '?phone1=' + newPhone1;
		if(document.forms[0].phone2){
			newPhone2 = document.forms[0].phone2.value;
			newPhone2 = newPhone2.replace(/[^\d]/g,'');			
			popup_url += '&phone2=' + newPhone2;
		}
		popup_url += '&firstname=' + document.forms[0].firstname.value;
		// remove the querystring from the current URL
		current_url_parts = window.location.href.split( "?" );
		current_url = current_url_parts[0];

		popup_url += '&from=' + current_url;
		// Include this click id so that Global Media aren't using the default 11221 IfByPhone click_id
		popup_url += '&click_id=2985';
		window.open( popup_url,'PushToTalk','height=380,width=530,left=20,top=20,resizable=no,menubar=0,toolbar=0,status=0');

		switch(option){
			case 1:
				if(form.Best_Time_to_Call.value == 'Immediately_pend'){
					form.Best_Time_to_Call.options[0].value = 'Immediately';
				}else{
					form.ptt.value = 'ptt';
				}
				break;
			case 2:
				if(form.Best_Time_to_Call_CheckBox.checked){
					form.Best_Time_to_Call.options[0].value = 'Immediately';
				}
				else{
					form.ptt.value = 'ptt';
				}
				break;
			case 3:
				form.Best_Time_to_Call.options[0].value = 'Immediately';
				break;
			default:
				break;
		}
	}

	returnVal = true;
	
}
