String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var agt = navigator.userAgent.toLowerCase();

var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
var check=/@[\w\-]+\./;
var checkend=/\.[a-zA-Z]{2,3}$/;


var forceExitAffs = false;

window.onbeforeunload = confirmExit;
function confirmExit(){
	if (forceExitAffs) {
		forceExitAffs = false;
		showAlert('-exitPageAff');
		reveal_alert_pop(true);
		return "Hit " + cancelBtnCaptn + " to get access to rate quotes from leading providers right now.";
	}
}


//============================================================================================================
//============================================================================================================
//============================================================================================================
//=========  GENERAL ===========================================
//============================================================================================================
//============================================================================================================
//============================================================================================================
function more(myPage, windowName, myWidth, myHeight, scroll, resize){
	LeftPosition= (screen.width*0.5)-(myWidth*0.5);
	TopPosition= (screen.height*0.4)-(myHeight*0.5);
	window.open(myPage, windowName, 'width='+myWidth+',height='+myHeight+',top='+TopPosition+',left='+LeftPosition+',scrollbars=' + scroll + ',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=' + resize);
}

function empt(){}

function expend_dyn(elem){
	elem = document.getElementById(elem);
	if (elem.className == 'hidden') elem.className = '';
	else elem.className = 'hidden';
}

function expend(elem, cond){
	elem = document.getElementById(elem);
	if (cond) elem.className = '';
	else elem.className = 'hidden';
}

function grayed_check(elem, def_class){
	elem = document.getElementById(elem);
	if (elem.value != '') {
		if (elem.value != elem.defaultValue) elem.className = def_class;
	} else {
		elem.className = def_class + ' grayed';
		elem.value = elem.defaultValue;
	}
}

function reveal_valid(elem, cond){
	alert(cond);
}

function changeToNumeric(nowField, max_val){
	tmpValue = document.getElementById(nowField).value;
	tmpValue = tmpValue.replace(/[^-^0-9]/ig, "");
	if (document.getElementById(nowField).value != tmpValue) document.getElementById(nowField).value=tmpValue;
	if(max_val!=-1)if(parseInt(document.getElementById(nowField).value)*1>max_val)document.getElementById(nowField).value=max_val;
}

function changeToDouble(nowField, max_val){
	tmpValue = document.getElementById(nowField).value;
	tmpValue = tmpValue.replace(/[^.^0-9]/ig, "");
	if (document.getElementById(nowField).value != tmpValue) document.getElementById(nowField).value=tmpValue;
	if(max_val!=-1)if(parseInt(document.getElementById(nowField).value)*1>max_val)document.getElementById(nowField).value=max_val;
}

function changeToMoney(nowField){
	tmpValue2=""
	tmpValue = document.getElementById(nowField).value;
	tmpValue = tmpValue.replace(/[^0-9]/ig,"");
	if(tmpValue > 999){
		countNo=0;
		for (i=tmpValue.length; i>=0; i--){
			countNo++;
			tmpValue2 = tmpValue.substr(i,1) + tmpValue2;
			if (countNo>=4){
				countNo=1;
				tmpValue2 = "," + tmpValue2;
				}
			}
		tmpValue = tmpValue2;
		}
	if (tmpValue.substr(0,1)==",") tmpValue=tmpValue.substr(1,tmpValue.length-1);
	if (tmpValue.length>1) if (tmpValue.substr(0,1)=="0") tmpValue=tmpValue.substr(1,tmpValue.length-1);
	document.getElementById(nowField).value=tmpValue;
}

function maxWords(nowField, max_val){
	tmpValue = document.getElementById(nowField).value.trim();
	pos = 0;
	num = -1;
	i = -1;
	while (pos != -1) {
		pos = tmpValue.indexOf(" ", i + 1);
		num += 1;
		i = pos;
		if (num >= max_val) {
			if (i!=-1) tmpValue = tmpValue.substring(-1, i);
			document.getElementById(nowField).value=tmpValue;
			pos = -1;
		}
	}
}

function minWords(nowField, min_val){
	tmpValue = document.getElementById(nowField).value.trim();
	pos = 0;
	num = -1;
	i = -1;
	while (pos != -1) {
		pos = tmpValue.indexOf(" ", i + 1);
		num += 1;
		i = pos;
	}
	if (num < min_val) {
		alert("Not enough words entered");
		return false;
	}
	else return true;
}

function isNumeric(str){
	var valid_chars = "0123456789";
  	var isnumber = true;
	var curr_char;
	for (i = 0; i < str.length && isnumber; i++) { 
      curr_char = isnumber.charAt(i); 
      if (valid_chars.indexOf(curr_char) == -1) isnumber = false;
	  }
   return isnumber;
}

var now=new Date();
now.setDate(now.getDate() + 1); //add a day to the date so the bDay will be matched exactly!
Month=now.getMonth();              
Day=now.getDate();                 
Year=now.getYear();
function dateToAge(str){
	if(document.getElementById('birthMonth').value!=""&&document.getElementById('birthDay').value!=""&&document.getElementById('birthYear').value!=""){
		if(Year<1000)Year+=1900;
		by=document.getElementById('birthYear').value;
		bm=document.getElementById('birthMonth').value;
		bd=document.getElementById('birthDay').value;
		BDate=Date.UTC(by,bm,bd);
		if(Year<2000)CDate = Date.UTC(Year,Month,Day);
		else CDate = Date.UTC(Year,Month,Day);
		Age=CDate-BDate + (1000*60*60*24*30); 
		Age=parseInt(((((Age/1000)/60)/60)/24)/365.25,10);
		return Age;
	}
}

function show(elem){
	document.getElementById(elem).className = 'visible';
}
function showMe(elem){
	document.getElementById(elem).className = 'visible';
}
function hide(elem){
	document.getElementById(elem).className = 'hidden';
}
function hideMe(elem){
	document.getElementById(elem).className = 'hidden';
}

/*function jsAutoSelect(elem, val){
	for (i = 0; i < document.getElementById(elem).length; i++) {
		alert(document.getElementById(elem).options[i].value);
	}
}*/

//=====================================================HTML POPUPS (ALERTS, SUB FORMS, ETC)
function reveal_alert_pop(cond){
	if(cond){
		var agt=navigator.userAgent.toLowerCase();
		if (agt.indexOf("msie")!=-1){
			elem=document.getElementsByTagName('input');
			for(i in elem)if(elem[i].name!=undefined)elem[i].style.visibility='hidden';
			elem=document.getElementsByTagName('select');
			for(i in elem)if(elem[i].name!=undefined)elem[i].style.visibility='hidden';
		}
		document.getElementById('alert_pop').className='visible';
	}else{
		var agt=navigator.userAgent.toLowerCase();
		if (agt.indexOf("msie")!=-1){
			elem=document.getElementsByTagName('input');
			for(i in elem)if(elem[i].name!=undefined)elem[i].style.visibility='visible';
			elem=document.getElementsByTagName('select');
			for(i in elem)if(elem[i].name!=undefined)elem[i].style.visibility='visible';
		}
		document.getElementById('alert_pop').className='hidden';
	}
}

function showAlert(alertElem){
	document.getElementById('alert_pop_wide').className = '';
	if (alertElem.indexOf("-") > -1) document.getElementById('alert_pop_wide').className = 'on';
	alertElem = alertElem.replace("-", "");
	
	showMe('alert_pop_bg');
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("msie 6") > -1){
		elem = document.getElementById('wrapper').getElementsByTagName('input');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'hidden';
		elem = document.getElementById('wrapper').getElementsByTagName('select');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'hidden';
		document.getElementById('alert_pop').style.position = "absolute";
		document.getElementById('alert_pop_bg').style.position = "absolute";
		document.getElementById('alert_pop_bg').style.height = "90000px"
	}
	location = "#";
	
	//showMe(alertElem); showMe('alert_pop');

	showMe(alertElem);
	if(document.getElementById('alert_pop').className == 'hidden') showMe('alert_pop'); document.getElementById('alert_pop').style.display = 'none';
	$('alert_pop').appear({duration: 0.3});
}

function showAlertEase(alertElem){
	document.getElementById('alert_pop_wide').className = '';
	if (alertElem.indexOf("-") > -1) document.getElementById('alert_pop_wide').className = 'on';
	alertElem = alertElem.replace("-", "");
	
	showMe('alert_pop_bg');
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("msie 6") > -1){
		elem = document.getElementById('wrapper').getElementsByTagName('input');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'hidden';
		elem = document.getElementById('wrapper').getElementsByTagName('select');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'hidden';
		document.getElementById('alert_pop').style.position = "absolute";
		document.getElementById('alert_pop_bg').style.position = "absolute";
		document.getElementById('alert_pop_bg').style.height = "90000px"
	}
	location = "#";
	
	//showMe(alertElem); showMe('alert_pop');
	
	showMe('alert_pop');
	$(alertElem).fade();
}

function hideAlert(alertElem){
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("msie 6") > -1){
		elem = document.getElementById('wrapper').getElementsByTagName('input');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'visible';
		elem = document.getElementById('wrapper').getElementsByTagName('select');
		for(i in elem)if(elem[i].name != undefined)elem[i].style.visibility = 'visible';
	}
	
	//hideMe('alert_pop');
	//hideMe(alertElem);
	//hideMe('alert_pop_bg');
	//document.getElementById('alert_pop_wide').className = '';
	
	$('alert_pop').fade({duration: 0.3, afterFinish:function(){hideMe(alertElem); hideMe('alert_pop_bg'); document.getElementById('alert_pop_wide').className = '';}});
}

//=========== PROMO UPS ===============================================
function promoup(myPage, windowName, myWidth, myHeight, dayLength){
	//alert(currentPromoZip);
	//alert(windowName);
	if (getCookie(windowName) != "true"){
		more(myPage, windowName, myWidth, myHeight, 'no', 'no');
		setCookie(windowName, "true", dayLength);
		window.focus();
	}
}
/*
var liveLeadsPhone = true;
window.onload = promoupLiveLeads;
function promoupLiveLeads(){
	if (liveLeadsPhone) {
		tmpElems = document.getElementsByTagName('body');
		for (var i = 0; i < tmpElems.length; i++) tmpElem = tmpElems[i].onclick = function(){ promoup('promoup.asp', 'promoup', 500, 160, 1);}
	}
}
*/

function removeAllOptionsButFirst(elem){
	for(i = document.getElementById(elem).options.length - 1; i > 0; i--) document.getElementById(elem).remove(i);
}



//=========== ANIMATED - FADE IN - SLIDESHOW ===============================================
function anim_slideshow_fade_xml(id, host, xmlPath){
	//== Reading XML
	//== XML doc must hold the related elements tags with the name > elements > elem > image
	if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
	else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //== For IE6, IE5
	xmlhttp.open("GET", xmlPath, false);
	xmlhttp.send();
	xmlDoc = xmlhttp.responseXML;
	
	//== Assign elems to public array
	var x = xmlDoc.getElementsByTagName("elem");
	for (i = 0; i < x.length; i++) eval(id + '_array')[i] = x[i].attributes.getNamedItem('image').value;
	
	//== Format host & preview first elem
	document.getElementById(host).innerHTML = '<div id="' + id + '_1"></div><div id="' + id + '_2" style="display: none"></div>';
	document.getElementById(id + '_1').innerHTML = '<img src="/images/_trans.gif" alt="" />';
	document.getElementById(id + '_2').innerHTML = '<img src="' + eval(id + '_array')[0] + '" alt="" />';
	
	anim_slideshow_fade_xml_engine(id, id + '_2', id + '_1');
	//anim_slideshow_fade_xml_organizer(id);
}

function anim_slideshow_fade_xml_engine(id, elemToTurnOn, elemToTurnOff){
	Effect.Fade(elemToTurnOff, {
		duration: 0.2, 
		afterFinish:function(){
			Effect.Appear(elemToTurnOn, {
				duration: 0.2, 
				afterFinish:function(){
					//setTimeout('anim_slideshow_fade_xml_organizer("' + id + '")', 2000);
					anim_slideshow_fade_xml_organizer(id)
				}
			})
		}
	});
}

function anim_slideshow_fade_xml_organizer(id){
	var slideNow = eval(id + '_now');
	if (slideNow + 1 <= eval(id + '_array').length - 1) slideNow++;
	else slideNow = 0;
	
	var elemToTurnOn = id + '_2';
	var elemToTurnOff = id + '_1';
	if (document.getElementById(id + '_1').style.display == 'none') {
		elemToTurnOn = id + '_1';
		elemToTurnOff = id + '_2';
	}
	
	document.getElementById(elemToTurnOn).innerHTML = '<img src="' + eval(id + '_array')[slideNow] + '" alt="" />';
	eval(id + '_now = slideNow');
	
	//anim_slideshow_fade_xml_engine(id, elemToTurnOn, elemToTurnOff);
	setTimeout('anim_slideshow_fade_xml_engine("' + id + '", "' + elemToTurnOn + '", "' + elemToTurnOff + '")', 2000);
}


home_lastWidget = "";
function openWidget(elem){
	if (home_lastWidget != "") {
		Effect.BlindUp(home_lastWidget, {
			duration: 0.2,
			afterFinish:function(){
				if (home_lastWidget != elem) {
					home_lastWidget = elem;
					Effect.BlindDown(elem, {duration: 0.4});
				} else home_lastWidget = "";
			}
		})
	} else {
		home_lastWidget = elem;
		Effect.BlindDown(elem, {duration: 0.4});
	}
}




//============================================================================================================
//============================================================================================================
//============================================================================================================
//=========  GENERAL VERIFICATIONS ===========================================
//============================================================================================================
//============================================================================================================
//============================================================================================================
var last_cap_err = "";
var last_error = "", last_error_elem = "";
function error_me(element, message, caption){
	last_error_elem=element;
	if(caption==undefined)caption=element;
	if(last_error!="")last_error.className="";
	
	alert(message);

	last_error=document.getElementById('lbl_'+caption); last_error.className="highlight_error";
	if(!navigator.userAgent.indexOf("MSIE")) location.href="#"+'lbl_'+caption;
	location.href = "#";
	document.getElementById(element).focus();
	return false;
}

var err_error_me_multi = false;
//var collect_error_me_multi = "";
var first_element_error_me_multi = "";
var first_message_error_me_multi = "";
var first_caption_error_me_multi = "";
function error_me_multi(element, message, caption){
	if(caption==undefined)caption=element;
	err_error_me_multi = true;
	if (first_message_error_me_multi == ""){
		first_message_error_me_multi = message;
		first_element_error_me_multi = element;
		if (first_caption_error_me_multi == "") first_caption_error_me_multi = caption;
	}
	if (document.getElementById('lbl_'+caption)) document.getElementById('lbl_'+caption).className = "req highlight_error";
}

function error_me_multi_alert(){
	alert(first_message_error_me_multi);
	//if(!navigator.userAgent.indexOf("MSIE")) location.href="#"+'lbl_'+first_caption_error_me_multi;
	////location.href = "#";
	if (document.getElementById('lbl_'+first_caption_error_me_multi)) Effect.ScrollTo('lbl_'+first_caption_error_me_multi, { offset:-100 });
	document.getElementById(first_element_error_me_multi).focus();
}

function error_me_multi_clean(){
	err_error_me_multi = false;
	first_element_error_me_multi = "";
	first_message_error_me_multi = "";
	first_caption_error_me_multi = "";
	elem = document.getElementsByTagName("label");
	for (i = 0; i < elem.length; i++) {
		//alert(elem[i].className);
		if (elem[i]) {
			if (elem[i].className == "req highlight_error") elem[i].className = "req";
		}
	}
}

var currentDynPlan = "1";
function verify_phone(phoneNo) {
//	changeToNumeric(elem, -1);
//	elem = document.getElementById(elem);
	document.getElementById('lbl_phone1a').className = '';
	if (phoneNo.length == 10) {
		val_string = "";
		val_string += "plan=" + currentDynPlan + "|~|";
		val_string += "checkfor=phone|~|";
		val_string += "v=" + phoneNo + "|~|";
		doAjax('/ws/dataValidations.asp', val_string, "POST", true, "phone");
	} else document.getElementById('lbl_phone1a').className = "valid no";
}

function verify_live_phone() {
	document.getElementById('lbl_phone1a').className = '';
	var phone = document.getElementById("phone1a").value + 
				document.getElementById("phone1b").value + 
				document.getElementById("phone1c").value
	if(parseInt(phone) && (phone.length == 10))
		verify_phone(phone);
	else if (phone.length == 10)
		document.getElementById('lbl_phone1a').className = 'valid no';
}

function checkLivePhone(elemID, nextElemID, step) {
	var elem = document.getElementById(elemID);
	switch (step) {
		case 1:
		case 2:
			if (elem.value.length == 3)
				//document.getElementById(nextElemID).focus();
			break;
		case 3:
			if (elem.value.length == 4)
				//document.getElementById(nextElemID).focus();
			break;
	}
}

function verify_email(elmnt) {
	elem = document.getElementById(elmnt);
	if (elem.value == '') {}
	else if (((elem.value.search(exclude) != -1)||(elem.value.search(check)) == -1)||(elem.value.search(checkend) == -1)){}
	else {
		val_string = "";
		val_string += "plan=1|~|";
		val_string += "checkfor=email|~|";
		val_string += "v=" + elem.value + "|~|";
		doAjax('/ws/dataValidations.asp', val_string, "POST", true, "email");
	}
}

function verEmail(elem, caption){
	if (document.getElementById(elem).value == '') return false;
	else if(((document.getElementById(elem).value.search(exclude) != -1)||(document.getElementById(elem).value.search(check)) == -1)||(document.getElementById(elem).value.search(checkend) == -1)) return false;
	return true;
}

function verify_zip(elmnt) {
	changeToNumeric(elmnt, -1);
	elem = document.getElementById(elmnt);
	if (elem.value.trim().length == 5) {
		val_string = "";
		val_string += "plan=1|~|";
		val_string += "checkfor=zip|~|";
		val_string += "v=" + elem.value + "|~|";
		doAjax('/ws/dataValidations.asp', val_string, "POST", true, "zip");
	} else ajaxFail("zip")
}

function generalHomeCheckZip(){
	if (document.getElementById('quoteFor').value=='') {alert('Please enter quote type'); document.getElementById('quoteFor').focus();return false;}
	if (document.getElementById('zipMe').value=='') {alert('Please enter zip'); document.getElementById('zipMe').focus(); return false;}
	return true;
}
//document.onload = document.getElementById('zipMe').focus();

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function generalHomeCheckZipPop(gotoPage){
	if ($('quoteFor').value=='') {alert('Please enter quote type'); $('quoteFor').focus();return false;}
	if ($('zipMe').value=='' || !isNumber(($('zipMe').value))) {alert('Please enter zip'); $('zipMe').focus(); return false;}
	
	//alert('d');
	tmpStr = "";
	if ($('goTo')) if (document.getElementById('goTo').value != '') tmpStr = '&goTo=/' + $('goTo').value;
	window.open('/xt_checkZip_pop.asp?zipMe=' + $('zipMe').value + '&quoteFor=' + $('quoteFor').value + tmpStr);
	
	forceExitAffs = false;
	
	return true;
}

function generalHomeCheckZipAgePop(gotoPage){
	if ($('quoteFor').value=='') {alert('Please enter quote type'); $('quoteFor').focus();return false;}
	if (!$('age641').checked && !$('age640').checked) {alert('Please specify if you are over 65 years old'); $('age641').focus();return false;}
	if ($('zipMe').value=='' || !isNumber(($('zipMe').value))) {alert('Please enter zip'); $('zipMe').focus(); return false;}
	
	//alert('d');
	tmpStr = "";
	if ($('goTo')) if (document.getElementById('goTo').value != '') tmpStr = '&goTo=/' + $('goTo').value;
	window.open('/xt_checkZip_pop.asp?zipMe=' + $('zipMe').value + '&quoteFor=' + $('quoteFor').value + tmpStr);
	
	forceExitAffs = false;
	
	return true;
}

function generalHomeCheckZipPop2(gotoPage){
	if ($('quoteFor2').value=='') {alert('Please enter quote type'); $('quoteFor2').focus();return false;}
	if ($('zipMe2').value=='' || !isNumber(($('zipMe2').value))) {alert('Please enter zip'); $('zipMe2').focus(); return false;}
	
	//alert('d');
	tmpStr = "";
	if ($('goTo')) if ($('goTo').value != '') tmpStr = '&goTo=/' + $('goTo').value;
	window.open('/xt_checkZip_pop.asp?zipMe=' + $('zipMe2').value + '&quoteFor=' + $('quoteFor2').value + tmpStr);
	
	forceExitAffs = false;
	
	return true;
}

function generalHomeCheckZipPop3(gotoPage){
	if ($('quoteFor3').value=='') {alert('Please enter quote type'); $('quoteFor3').focus();return false;}
	if ($('zipMe3').value=='' || !isNumber(($('zipMe3').value))) {alert('Please enter zip'); $('zipMe3').focus(); return false;}
	
	//alert('d');
	tmpStr = "";
	if ($('goTo')) if ($('goTo').value != '') tmpStr = '&goTo=/' + $('goTo').value;
	window.open('/xt_checkZip_pop.asp?zipMe=' + $('zipMe3').value + '&quoteFor=' + $('quoteFor3').value + tmpStr);
	
	forceExitAffs = false;
	
	return true;
}

function generalHomeCheckZipPop4(gotoPage){
	if ($('quoteFor4').value=='') {alert('Please enter quote type'); $('quoteFor4').focus();return false;}
	if ($('zipMe4').value=='' || !isNumber(($('zipMe4').value))) {alert('Please enter zip'); $('zipMe4').focus(); return false;}
	
	//alert('d');
	tmpStr = "";
	if (document.getElementById('goTo')) if (document.getElementById('goTo').value != '') tmpStr = '&goTo=/' + document.getElementById('goTo').value;
	window.open('/xt_checkZip_pop.asp?zipMe=' + document.getElementById('zipMe4').value + '&quoteFor=' + document.getElementById('quoteFor4').value + tmpStr);
	
	forceExitAffs = false;
	
	return true;
}

function verifyContactData(){
	first_element_error_me_multi = ""
	first_message_error_me_multi = "";
	first_caption_error_me_multi = "";
	err_error_me_multi = false;
	error_me_multi_clean();
	
	now_field="qEmail";
		if (((document.getElementById(now_field).value.search(exclude) != -1)||(document.getElementById(now_field).value.search(check)) == -1)||(document.getElementById(now_field).value.search(checkend) == -1)) error_me_multi(now_field, 'Please enter a valid Email');
		
	now_field="phone1";
		if(document.getElementById(now_field + 'a').value.length != 3 || document.getElementById(now_field + 'b').value.length != 3 || document.getElementById(now_field + 'c').value.length != 4) error_me_multi(now_field+'a', 'Please enter Phone');
	
	now_field="qQuery";
		if(document.getElementById(now_field).value=="") error_me_multi(now_field, 'Please enter Question or Comment');
	
	//return true;
	if (err_error_me_multi) {
		error_me_multi_alert();
		return false;
	}
	else {
		
		forceExitAffs = false;
		
		document.getElementById('contact_us_form').action = 'xt_contact_us.asp';
		return true;
		
	}
}

//============================================================================================================
//============================================================================================================
//============================================================================================================
//=========  AJAX ===========================================
//============================================================================================================
//============================================================================================================
//============================================================================================================
function getHTTPObject() {
	var xhr = false;
	if(window.XMLHttpRequest) {
		var xhr = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		try {
			var xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				var xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	return xhr;
}

var ajaxWorking = false;

function doAjax(httpPath, vals, method, sync, flag, successFunction, failFunction) {

	/*============================
	FUNCTION INFO:	
	httpPath => url of execution page
	vals => values to pass to the above page
		all values i'm entering. all value must transferred as string; devided by  |~|. 
		//ex: 'state=AR|~|phone=212-111-1111|~|active=1'
	method => POST or GET
	sync => true (for sync executing) or false (for async executing)
	flag => cursor to the location withing the success / fail functions. (optional)
	successFunction => on success, go to this function (optional, if not defined, goes to ajaxSuccess)
	failFunction => on failure, go to this function (optional, if not defined, goes to ajaxFail)
	==============================*/

	var http = getHTTPObject();

	if (http && !ajaxWorking) {
		vals_break = "";
		if (vals != "") {
			vals = vals.split("|~|");
			for (i = 0; i < vals.length; i++) {
				variable = vals[i].substr(0, vals[i].indexOf("="));
				value = "";
				value = vals[i].substr(vals[i].indexOf("=") + 1, vals[i].length);
				if (value != "") {
					if (vals_break != "") vals_break += "&";
					vals_break += variable + "=" + escape(value);
				}
			}
		}
		if (vals_break=="") vals_break = null;
		
		http.open(method, httpPath, sync);
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		////http.setRequestHeader('Content-Type',  "text/xml");
		ajaxWorking = true;
		http.send(vals_break);
		http.onreadystatechange = function(){
			if (http.readyState == 4) {
				ajaxWorking = false;
				//alert('VALUES:\n' + vals_break + '\n\nHTML:\n' + http.responseText);
				if (http.status == 200){
					if (successFunction) eval(successFunction + "(http.responseXML, flag)");
					else ajaxSuccess(http.responseXML, flag);
					}
				else {
					if (failFunction) eval(failFunction(flag));
					else ajaxFail(flag);
					}
			}
		}
	}
}

function ajaxSuccess(xmlDocument, flag){
	var err_here = false;
	switch(flag){
		case "phone":
			
			if (xmlDocument.getElementsByTagName('valid').item(0)) {
				var valid = xmlDocument.getElementsByTagName('valid').item(0).firstChild.data;
				//alert(xmlDocument.getElementsByTagName('response').item(0).firstChild.data);
		    	if (valid == "Yes") {
					document.getElementById('vld_phone1').className = "valid";
					document.getElementById('vld_phone1').innerHTML = "";
					document.getElementById('val_phone1').value = "ok";
					}
		    	else err_here = true;
			} else err_here = true;
			if (err_here) ajaxFailXml(xmlDocument, flag);
			
			break;
			
		case "email":
			if (xmlDocument.getElementsByTagName('valid').item(0)) {
				var valid = xmlDocument.getElementsByTagName('valid').item(0).firstChild.data;
		    	if (valid == "Yes") {
					//document.getElementById('vld_email').className = "valid ok";
					//document.getElementById('vld_email').innerHTML = "valid";
					}
		    	else err_here = true;
			} else err_here = true;
			if (err_here) ajaxFail(flag)
			
			break;
			
		case "zip":
			document.getElementById('val_zip').value = "";
			if (xmlDocument.getElementsByTagName('valid').item(0)) {
				var valid = xmlDocument.getElementsByTagName('valid').item(0).firstChild.data;
		    	if (valid == "1") {
					var state = xmlDocument.getElementsByTagName('state').item(0).firstChild.data;
					var city = xmlDocument.getElementsByTagName('city').item(0).firstChild.data;
					document.getElementById('vld_city').innerHTML = city + ", ";
					//document.getElementById('vld_city').style.display = "block"
					document.getElementById('vld_state').innerHTML = state;
					//document.getElementById('vld_state').style.display = "block"
					document.getElementById('dyn_location').className = 'elem visible';
					document.getElementById('val_zip').value = state;
					if (state=="OR") {
						document.getElementById('alert_pop').style.top = "300px";
						document.getElementById('alert_oregon').className='visible';
						reveal_alert_pop(true);
						}
					}
					currentPromoZip = xmlDocument.getElementsByTagName('zip').item(0).firstChild.data;
					if (liveAlterAffCombo) promoupLiveLeads();
					
				else err_here = true;
			} else err_here = true;
			if (err_here) ajaxFail(flag)
			
			break;
			
		case "zipToCityState":
			if (xmlDocument.getElementsByTagName('valid').item(0)) {
				var valid = xmlDocument.getElementsByTagName('valid').item(0).firstChild.data;
		    	if (valid == "1") {
					var state = xmlDocument.getElementsByTagName('state').item(0).firstChild.data;
					var city = xmlDocument.getElementsByTagName('city').item(0).firstChild.data;
					document.getElementById(str_zipToCityState_addressElem).innerHTML = city + ", " + state;
					}
				else err_here = true;
			} else err_here = true;
			if (err_here) ajaxFail(flag)
			
			break;
	}
}

function ajaxFailXml(xmlDocument, flag) {
	switch(flag){
		case "phone":
			document.getElementById('vld_phone1').className = "valid no";
			document.getElementById('vld_phone1').innerHTML = "invalid";
			document.getElementById('val_phone1').value = "0";
			if (xmlDocument.getElementsByTagName('duplicate').item(0)) {
				var dup = xmlDocument.getElementsByTagName('duplicate').item(0).firstChild.data;
				if (dup == "true"){
					document.getElementById('invalid-phone-div').className = 'visible';
					reveal_alert_pop(true);
				}
			}
			break;
			
		case "email":
			document.getElementById('vld_email').className = "valid no";
			document.getElementById('vld_email').innerHTML = "invalid";
			break;
			
		case "zip":
			document.getElementById('vld_city').innerHTML = "";
			document.getElementById('vld_state').innerHTML = "";
			document.getElementById('dyn_location').className = 'hidden';
			document.getElementById('val_zip').value = "0";
			break;
	}
}

function ajaxFail(flag){
	switch(flag){
		case "phone":
			document.getElementById('vld_phone1').className = "valid no";
			//document.getElementById('invalid-phone-div').className = "";
			document.getElementById('vld_phone1').innerHTML = "invalid";
			document.getElementById('val_phone1').value = "0";
			break;
			
		case "email":
			document.getElementById('vld_email').className = "valid no";
			document.getElementById('vld_email').innerHTML = "invalid";
			break;
			
		case "zip":
			document.getElementById('vld_city').innerHTML = "";
			document.getElementById('vld_state').innerHTML = "";
			document.getElementById('dyn_location').className = 'hidden';
			document.getElementById('val_zip').value = "0";
			break;
			
		case "zipToCityState":
			document.getElementById(str_zipToCityState_addressElem).innerHTML = "";
			break;
			
	}
}

var str_zipToCityState_addressElem;
function ajax_zipToCityState(zip, addressElem){
	str_zipToCityState_addressElem = addressElem;
	if (zip.length == 5) {
		val_string = "";
		val_string += "plan=12|~|";
		val_string += "checkfor=zip|~|";
		val_string += "v=" + zip + "|~|";
		doAjax('/ws/dataValidations.asp', val_string, "POST", true, "zipToCityState");
	} else document.getElementById(addressElem).innerHTML = "";
}



//============================================================================================================
//============================================================================================================
//============================================================================================================
//=========  COOKIES  ===========================================
//============================================================================================================
//============================================================================================================
//============================================================================================================
function setCookie(c_name, value, expiredays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name+ "=" +escape(value)+
	";path=/" +
	((expiredays == null) ? "" : ";expires="+exdate.toGMTString());
}
	
function getCookie(c_name){
	if (document.cookie.length > 0){
		c_start = document.cookie.indexOf(c_name + "=");
	 	if (c_start!=-1){
	    	c_start=c_start + c_name.length+1;
	    	c_end=document.cookie.indexOf(";",c_start);
	    	if (c_end==-1) c_end=document.cookie.length;
	    	return unescape(document.cookie.substring(c_start,c_end));
	    }
	}
	return "";
}
