
var okToSubmit = 1;

//preload new conf code gif
if (document.location.protocol != 'https:'){
	preload_image = new Image(120,40); 
	preload_image.src="http://top10workfromhomejobs.com/newConf.gif";	
};

//dollar function - returns getElementById()!
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

//using AjaxCon
/*
//initialize AjaxCon (if AjaxCon isn't created successfully, 
//the client doesnt' support Ajax)
var ajaxConn = new AjaxCon();

//post to mypage.php with args foo and bar
ajaxConn.connect("mypage.php", "POST", "foo=bar&bar=qux",fnWhenDone);

//when the server responds, javascript 
//will trigger this callback function
fnWhenDone(XML){
  alert(XML.responseText);
}
*/
function AjaxCon(){
	var xmlhttp, bComplete = false;
	try { 
  		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  	} catch (e) { 
		try {  
  			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
  		} catch (e) { 
  			try { 
  				xmlhttp = new XMLHttpRequest(); 
  			} catch (e) { 
  				xmlhttp = false;
  			}
  		}
	}
	
	if (!xmlhttp) return null;
	this.connect = function(sURL, sMethod, sVars, fnDone){
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();
		try {
  			if (sMethod == "GET") {
				xmlhttp.open(sMethod, sURL+"?"+sVars, true);
				sVars = "";
  			} else {
				xmlhttp.open(sMethod, sURL, true);
				xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
				xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  			}
  			//xmlhttp.onerror = function(){alert ('yow')};
  			xmlhttp.onreadystatechange = function(){
  			    //if status is not 200 there was some sort of error
  			    try {
  			        
					if(xmlhttp.readyState == 4 && (xmlhttp.status != 200)){
					    //let them try again.
					    if ($('ajaxErr')){
					        $('ajaxErr').value = xmlhttp.status;
					    }
					    xmlhttp.abort();
					    
					    msg = "There was a network error... please wait a minute and try again.";
					    failed (msg);
					}
				} catch (err){
				    //nothing to do!
				    
				}
				//if all is good, call the function to handle response
    			if (xmlhttp.readyState == 4 && !bComplete){
    	  			bComplete = true;
    	  			fnDone(xmlhttp);
    			}
      		};
  		xmlhttp.send(sVars);
	}
	catch(z) { 
		return false; 
	}
	return true;
	};
	return this;
}


function validateAddress2(iVal){
    var allValid=1;
    var urlstring = '';
	
	//see if we are passing dummy data
    postVars = 'iVal=' + iVal;
    postVars += '&step=' + step;
	try{
	    postVars += '&cSource=' + document.captureForm.cSource.value;
	}catch(ex){
	    //dosen't exist lets track it down
	    try{
	        postVars += '&cSource=ID-' + document.captureForm.SourceID.value;
	    }catch(ex){
	        postVars += '&cSource=NotAvailable';
	    }
	}
	if ($('captcha_input') && step == totalStep){
	    //get variables from captcha fields
        postVars += '&captcha_a=' + $('captcha_a').value;
        postVars += '&captcha_b=' + $('captcha_b').value;
        postVars += '&captcha_input=' + $('captcha_input').value;
	}
	for (x=0; x<document.captureForm.elements.length; x++){
		try {
		    var ElementName =  document.captureForm.elements[x].name;
		    var ElementValue = document.captureForm.elements[x].value;
		    if(postVars.indexOf(ElementName) == -1 && ElementName.indexOf("captcha") == -1){
		    	if(checkSend(document.captureForm.elements[x])){
		    		postVars += '&' + ElementName + "=" + ElementValue;
                }
            }
		} catch(ex) {
			//alert(ex);
		}
    }
	
	
    
    ajaxValidate = new AjaxCon();
    
    ajaxValidate.connect("/plugins/validateData/validateAddress.php", "POST", postVars, validateAddressReturn);
        

    
}

//called upon recieval of ajax call
function validateAddressReturn(XML){
    
    //alert (XML.responseText);
    
    //get the response XML and parse out nodes
    try {
        //certain browsers
        var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
        xmldoc.loadXML(XML.responseText);
    } catch(ex) {
        //every other browser on the planet
        var xmldoc = (new DOMParser()).parseFromString(XML.responseText, "text/xml");
    }
    
    //lets make sure personal validation is good
    
    //if there is an <error> node, then we are validating address, etc.
    if (xmldoc.getElementsByTagName('error')[0]){
        var error = xmldoc.getElementsByTagName('error')[0].firstChild.nodeValue;
        
        if (error > 0){
            //there was an error, alert the user and dont go forward
            message = xmldoc.getElementsByTagName('message')[0].firstChild.nodeValue;
            okToSubmit = 0;
            failed (message, error);
            
        } else {
            if(step < totalStep){
            	//we're on a multistep page, and not at the end so lets move forward
                //hide the loading graphic
                step++;
                if($('loadingGraphic')){
                    $('loadingGraphic').style.display = "none";
                }
    
                toggle('form'+step,1);
                if(step == totalStep){
                    toggle('submitButton',1);
                }else{
                    toggle('submit'+step,1);
                }
                toggle('form'+(parseInt(step)-1) ,0);
                toggle('submit'+(parseInt(step)-1),0);
            }
            okToSubmit = 1;
        }
    } else {
        //we didnt get an <error>, lets assume that it is ok.
        okToSubmit = 1;
    }
    
    //alert ("okToSubmit? "+okToSubmit);
    
    //if there is an <okcaptcha> node, then we are validating the captcha.
    if (xmldoc.getElementsByTagName('okcaptcha')[0]){
        
        var okcaptcha = xmldoc.getElementsByTagName('okcaptcha')[0].firstChild.nodeValue;
        
        if (okcaptcha == 1 && okToSubmit == 1){
            //conf code matches
            okToSubmit = 1;
        } else if (okcaptcha == 1 && okToSubmit == 0){
            //the captcha is fine, but there was a different error.
            //dont get a new captcha.
            okToSubmit = 0;
        } else if (okcaptcha == 0){    
            //bad captcha - get new conf code!
            var captcha_salt = xmldoc.getElementsByTagName('captcha_salt')[0].firstChild.nodeValue;
            var captcha_b = xmldoc.getElementsByTagName('captcha_b')[0].firstChild.nodeValue;
            
            $('captchaImage').src = "http://top10workfromhomejobs.com/newConf.gif";
            $('captchaImage').src = "http://www.bethebossnetwork.com/logic/captcha_image.php?captcha_a="+captcha_salt+"&captcha_b="+captcha_b+"";
            
            failed ("Your Confirmation Code did not match the text displayed on the page!  Please try again.");
            
            $('captcha_a').value = captcha_salt;
            $('captcha_b').value = captcha_b;
            
            $('captcha_input').value = "";
            try{
                $('captcha_input').focus(); 
            } catch(err){
                //
            }
            okToSubmit = 0;
            
            try{
                if (fnWhenDone){
                    fnWhenDone();
                }
            }catch(ex){
                
            }
        }
    } else if (step >= totalStep && okToSubmit == 1 && !$('captcha_input')){
        //we are on a page w/o a captcha, ok to submit!
        okToSubmit = 1;
    } else {
        //we are on a step of a multi-step page.  dont submit yet
        okToSubmit = 0;
    }
    
    //alert ('okToSubmit? '+okToSubmit+"\n step: "+step+"\n TotalStep: "+totalStep);
     
    //if there is a prev_cap value, put that back into the hidden value.
    if (xmldoc.getElementsByTagName('prev_cap')[0]){
        var prev_cap = xmldoc.getElementsByTagName('prev_cap')[0].firstChild.nodeValue;
        document.captureForm.prev_cap.value = prev_cap;
    }
    //if xml returned fail = 1 we need to set the iFailedValidation form variable to 1 so the lead will not sell
    if (xmldoc.getElementsByTagName('fail')[0]){
        var fail = xmldoc.getElementsByTagName('fail')[0].firstChild.nodeValue;
        document.captureForm.iFailedValidation.value = fail;
        //alert("failed");
    }
    if (okToSubmit == 1){
        try{
            if(ajaxSubmit == 1){
                doAjaxSubmit();
            }else{
                document.captureForm.submit();
            }
        }catch(ex){
            document.captureForm.submit();
        }
    }
}

function doAjaxSubmit(){
    var requestString = '';
    for (x=0; x<document.captureForm.elements.length; x++){

	    var ElementName =  document.captureForm.elements[x].name;
		var ElementVal = document.captureForm.elements[x].value;

		requestString = requestString + ElementName + "=" + ElementVal + "&";	
	}
    ajaxSubmit = new AjaxCon();
    ajaxSubmit.connect("process.php", "POST", requestString, ajaxSubmitCleanup);
}

function ajaxSubmitCleanup(RESULT){
    alert(RESULT);
}

function failed(msg, errcode){
    //alert the failure message
    alert (msg);
    //show the submit button
    if (step < totalStep){
        $('submit'+step).style.display = "block";
    } else {
        if ($('submitButton')){
            $('submitButton').style.display = "block";
        }
    }
    //hide the loader
    if ($('loadingGraphic')){
        $('loadingGraphic').style.display = "none";
    }
    
    //if we are on a three step, we may need to go back to step 1
    if (step == 2 && totalStep == 3 && (errcode & 2048 || errcode & 65536 || errcode & 32768)){
        step = 1;
        $('form1').style.display="block";
        $('submit1').style.display = "block";
        
        $('form2').style.display = "none";
        $('submit2').style.display = "none";
    }
    return null;
}

// Pop-under funtionality
var bSubmitted = false;


//Initialize our Ajax
if (window.XMLHttpRequest){
    //mozilla/safari
	xmlHttpRequestObject=new XMLHttpRequest();
} else {
    //other less compliant browsers
	xmlHttpRequestObject=new ActiveXObject("Microsoft.XMLHTTP");
}

// onUnload Exit Pop Functionality to Display Additional Offers
function onul(cURL,iType,iExit) {
	if(!bSubmitted && iType!=3 && iType!=4 && iExit!=1) {
		window.open(cURL);
		self.focus();
	}
}

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function oneOrMore(elementStart){
	var okay = 0;
	for (x=elementStart; x<document.captureForm.elements.length; x++){
		//alert(document.captureForm.elements[x].checked + " " + document.captureForm.elements[x].id)
		if(document.captureForm.elements[x].checked && (document.captureForm.elements[x].id == "checkThis" || document.captureForm.elements[x].id == "checkStart" || document.captureForm.elements[x].id == "checkEnd")){
			okay = 1;
		}
		if(okay == 0 && document.captureForm.elements[x].id == "checkEnd"){
			return false;
			break
		}else if(okay != 0 && document.captureForm.elements[x].id == "checkEnd"){
			return true;
			break
		}
	}
}

function checkCC(ccNum, ccExp){
	//Credit card validator for AMEX, VISA, MasterCard only. Allows spaces, dashes, or no separator between digit groups according to the layout (4-6-5 for AMEX, 4-4-4-4 for Visa and Mastercard)
	var ccRegExp = new RegExp(/\d{16}|\d{15}/);
	//Validates MM/YY for rough checking credit card expiration dates.
	var ccExpRegExp = new RegExp(/^((0[1-9])|(1[0-2]))\/(\d{4})$/);
	//alert(ccNum + ":" + ccRegExp.test(ccNum) + ", " + ccExp + ccExpRegExp.test(ccExp))
	if(ccRegExp.test(ccNum) && ccExpRegExp.test(ccExp)){
		return true;
	}else{
		return false;
	}
}

function checkExtraElements(){
	var returnVal = true
	for (x=0; x<document.captureForm.elements.length; x++){

		try{
			var AlertElement = document.captureForm.elements[x].name + "Text";
			var AlertText = $(AlertElement).value;
		}catch(ex){
			//alert(AlertElement)
			var AlertText = "";
		}

		if(document.captureForm.elements[x].id == "textReq"){
			if (document.captureForm.elements[x].value == ""){
				if(AlertText != ""){
					failed(AlertText);
				}else{
					failed("Please enter a value for this field.");
				}
				document.captureForm.elements[x].focus();
				returnVal = false;
				break
			}
		}
		if(document.captureForm.elements[x].id == "selectReq"){
			varSelect = new RegExp("Select");
			if (document.captureForm.elements[x].value.match(varSelect) || document.captureForm.elements[x].value == ""){
				if(AlertText != ""){
					failed(AlertText);
				}else{
					failed("Please select an option for this field.");
				}
				document.captureForm.elements[x].focus();
				returnVal = false;
				break
			}
		}
		if(document.captureForm.elements[x].id == "YN1"){
			var xx = x++;
			if (document.captureForm.elements[x].checked == false && document.captureForm.elements[xx].checked == false){
				if(AlertText != ""){
					failed(AlertText);
				}else{
					failed("Please answer all of the Yes/No questions.");
				}
				document.captureForm.elements[x].focus();
				returnVal = false;
				break
			}
		}
		if(document.captureForm.elements[x].id == "checkReq"){
			if (document.captureForm.elements[x].checked == false){
				if(AlertText != ""){
					failed(AlertText);
				}else{
					failed("Please answer all of the Yes/No questions.");
				}
				document.captureForm.elements[x].focus();
				returnVal = false;
				break
			}
		}
	}
	return returnVal;
}

function checkDisClaimer(field, msg){
    
	if(!document.getElementById(field).checked) {
		if(document.getElementById(field+"Text")){
			failed (document.getElementById(field+"Text").value);
		}else{
			failed (msg);
		}
		document.getElementById(field).focus();
		return false;
	}else{
		return true;
	}
	
}
// Autotab functionality
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();
	}

	// <DIV> toggle functionality
	function toggle(obj,show) {
		var el = document.getElementById(obj);
		if (show != 0){
			el.style.display = 'block';
		} else {
			el.style.display = 'none';
		}
	}

	// Contains array data
	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;
}


/**************** End Radio Button Check ***********/
function CheckNull(boxName, Readable)	{
    
	if (boxName.value == ""){
		failed("Please enter your " + Readable + ".")
		try{
		    boxName.focus();
		} catch (err){
		    //
		}
		return false;
	} else {
		return true;
	}
}
function checkSend(boxName)	{
	varSelect = new RegExp("[S|s]elect");
	try{
		if(boxName.value.length > 0 && !boxName.value.match(varSelect) ){
			return true;
		}else{
			return false;
		}
	}catch(ex){
		return false;
	}
}
function validatePhone() {

	var re = /^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/;
// var re = new RegExp(/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/);

	if(!document.getElementById("area_code")){
		var theAreaCode = document.getElementById("phone").value.slice(0,3)
		var theExchange = document.getElementById("phone").value.slice(3,6)
		var theEnd = document.getElementById("phone").value.slice(4,10)
		var theNumber = document.getElementById("phone").value;
	}else{
		var theAreaCode = document.getElementById("area_code").value
		var theExchange =document.getElementById("phone1").value
		var theEnd = document.getElementById("phone2").value
		var theNumber = theAreaCode + theExchange + theEnd;
	}

	var OK = re.test(theNumber);

    if (!OK){
      failed ("Please enter a valid Phone Number.");
      return false;
    }

	/* Check for repeating digits in area code */
	if ((theAreaCode == "444")	|| (theAreaCode == "555")	|| (theAreaCode == "666") || (theAreaCode == "800") || (theAreaCode == "999") || (theAreaCode == "900")) {
		failed("Please enter a valid Area Code.");
		try{
			document.getElementById("area_code").focus();
		}catch(ex){
			document.getElementById("phone").focus();
		}
		return false;
	}
	/* Check exchange for 555 */
	if (theExchange == "555") {
		failed("Please enter a valid Phone Number.");
		try{
			document.getElementById("phone1").focus();
		}catch(ex){
			document.getElementById("phone").focus();
		}
		return false;
	}

	return true;

}

/**************** REGEX ***********/
// names: only alpha and .,-"'
function DoRegEx1(field,desc){
	var illegalChars = /[^A-Za-z\.\"\'\- ]+/
	var strng = eval("document."+field+".value");
	if (illegalChars.exec(strng)) {
		failed(desc+" is not valid!");
		return false;
	} else {
		return true;
	}

}
// email: no !#$%^&*(){}[],
function DoRegEx2(field,desc){
	DoRegEx3(field,desc);
	var illegalChars = /[ \$\!\#\%\&\*\^\(\)\{\}\[\]\,]+/
	var strng = eval("document."+field+".value;");
	if (illegalChars.exec(strng)) {
		failed(desc+" is not valid!");
		return false;
	} else {
		return true;
	}
}
// email: fix email .co
function DoRegEx3(field,desc){
	var strng = eval("document."+field+".value;");
	var lastchar = strng.lastIndexOf('.');
	var strnglength = strng.length;
	var strngdiff = parseFloat(strnglength-lastchar);
	var dmn = strng.substring(strnglength,lastchar);
	if (dmn == '.co'){
		var strng = strng.substring(0,lastchar) + ".com";
		eval("document."+field+".value='"+strng+"';");
	}
	return true;
}

// RegEx email validation: http://www.4guysfromrolla.com/webtech/052899-1.shtml
function validateEmail(src) {
	var emailReg = "";
	var regex = new RegExp('^[\\w-_\.][\\w-_\.][\\w-_\.]*[\@][\\w-][\\w--\.][\\w--\.][\\w-\.]*[\.][\\w-_\.]+[\\w]$');
	//alert(regex.test(src));
	//return regex.test(src);
	return true;
}

function validateInteger(strValue) {
	/************************************************
	DESCRIPTION: Validates that a string contains only
	valid integer number.

	PARAMETERS:
	strValue - String to be tested for validity

	RETURNS:
	True if valid, otherwise false.
	**************************************************/
	var objRegExp  = /(^-?\d\d*$)/;

	//check for integer characters
	return objRegExp.test(strValue);
}

function placeAd(xfile, xright, xtop, xwide, xhi){
	var x = "<div id=\"Layer1\" style=\"position: absolute; right: " + xright + "px; top: " + xtop + "px; width: " + xwide + "px; height: " + xhi + "px; z-index: 1\">";
	x = x + "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\"" + xwide + "\" height=\"" + xhi + "\">";
	x = x + "<param name=\"movie\" value=\"" + xfile + "\" />";
	x = x + "<param name=\"quality\" value=\"high\" />";
	x = x + "<param name=\"wmode\" value=\"transparent\" />";
	x = x + "<embed src=\"" + xfile + "\" width=\"" + xwide + "\" height=\"" + xhi + "\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" wmode=\"transparent\"></embed>";
	x = x + "</object></div>";
	document.write(x);
}

function toggle(obj,show) {
    
    if ($(obj)){
    	var el = $(obj);
    	
    	if (show != 0){
    	    el.style.display = 'block';
    	} else {
    	    el.style.display = 'none';
    	}
    }
}

function buildFlash(){
	objects = document.getElementsByTagName("object");
	for (var i = 0; i < objects.length; i++){
	    objects[i].outerHTML = objects[i].outerHTML;
	}
}

// Privacy Graphical Checkbox
function setPrivacy() {
    var f = document.captureForm;
    var iPrivacy = f.privacy.value;
    if (iPrivacy != '1') {
        f.privacy.value = '1';
        MM_swapImage('check-box','','images/checkbox-on.gif',0)
    } else {
        f.privacy.value = '0';
        MM_swapImage('check-box','','images/checkbox-off.gif',0)
    }
}

function openPrivacy(url) {
    window.open(url, 'PrivacyPolicy', 'width=760,height=490,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no');
}

//dollar function - returns getElementById!
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

function checkRepeat(field, desc) {
    
    var okay = false;
    
	var illegalChars = /([ -~])\1{2}/
	
	
	if ($(field) && $(field).value){
	    //if we can get this by id
	    strng = $(field).value;
	} else {
	    //get it by name
	    eval("strng = document.captureForm."+field+".value");
	}
	
    var illegalChars2 = /[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]{6}/
    var illegalChars3 = /[aeiouyAEIOUY]/
	if (illegalChars.exec(strng)) {
		okay = false;
	} else {
	    if(strng.length > 1){
	        if(strng.length == 2 && strng.substr(0,1) == strng.substr(1,1)){
	            okay = false;
	        }else{
	            if (strng.length > 2 && (illegalChars2.exec(strng) || !illegalChars3.test(strng))) {
		            okay = false;
		        }else{
	                okay = true;
	            }
	        }
	    }else{
		    okay = false;
		}
	}
	if(okay == false){
	    failed(desc+" is not valid!");
	}
	return okay;
}

function alphaRepeat(field, desc) {
    var okay = false
	var illegalChars = /([a-zA-Z])\1{2}/
	
	if ($(field) && $(field).value){
	    //if we can get this by id
	    strng = $(field).value;
	} else {
	    //get it by name
	    eval("strng = document.captureForm."+field+".value");
	}
    
    var illegalChars2 = /[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]{6}/
    var illegalChars3 = /[aeiouyAEIOUY]/
	if (illegalChars.exec(strng)) {
		okay = false;
	} else {
	    if(strng.length > 1){
	        if(strng.length == 2 && strng.substr(0,1) == strng.substr(1,1)){
	            okay = false;
	        }else{
	            if (strng.length > 2 && (illegalChars2.exec(strng) || !illegalChars3.test(strng))) {
		            okay = false;
		        }else{
	                okay = true;
	            }
	        }
	    }else{
		    okay = false;
		}
	}
    
    if(okay == false){
        failed(desc+" is not valid!");
    }
	
	return okay;
}

function processReqChange() {
    // only if req shows "loaded"
    if (xmlHttpRequestObject.readyState == 4) {
        // only if "OK"
        if (xmlHttpRequestObject.status == 200) {
            // ...processing statements go here...
            
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                xmlHttpRequestObject.statusText);
        }
    }else{
        //document.body.style.cursor='url("http://dev.mlmgo.com/intranet/images/circle-loader.gif"), wait';
    }
}

function timerLoop() {
	var postVars = "iTankID="+document.captureForm.iTankID.value;
	ajaxValidate = new AjaxCon();
    ajaxValidate.connect("/plugins/updateTimer.php", "POST", postVars, doUpdated);
}

function doUpdated(XML) {
	//update successful
}