ValidationA = 
{
	Start: function()
	{
		var elements = new Array("amountRequested", "firstName", "lastName", "emailAddress", "homeZip");
		
		for (var element = 0; element < elements.length; ++element)
		{
			$X(''+ elements[element] +'').onblur = function () { ValidationA.Definitions(this, "true"); };
		}
	},
	
	Define: function()
	{
		var possArr = new Array();
		possArr['amountRequested'] = new Array("isEmpty();isNumber();");
		possArr['firstName'] = new Array("isEmpty();isMin(2);");
		possArr['lastName'] = new Array("isEmpty();isMin(2);");
		possArr['emailAddress'] = new Array("isEmpty();isEmail();");
		possArr['homeZip'] = new Array("isEmpty();isNumber();isMin(5);isMax(5);");
		
		return possArr;
	},
	
	Definitions: function(pTarget, sqlStatus)
	{
		var possArr = ValidationA.Define();
		
		if (sqlStatus == "true")
		{
			GlobalVal.Validate(pTarget.name, pTarget.value, possArr[pTarget.name][0], true);
		}
		else
		{
			GlobalVal.Validate(pTarget.name, pTarget.value, possArr[pTarget.name][0], false);
		}
	},
	
	CallBack: function()
	{
		var possArr = ValidationA.Define();
		var elements = new Array("amountRequested", "firstName", "lastName", "emailAddress", "homeZip");
		var stop = '';
		
		for (var element = 0; element < elements.length; ++element)
		{
			if (GlobalVal.Validate(''+ elements[element] +'', $X(''+ elements[element] +'').value, possArr[''+ elements[element] +''][0], false) == "true")
			{
				//OK == Validation Passed
			}
			else
			{
				stop = true;
			}
		}
		
		if (stop == true)
		{
			alert('Please complete fields highlighted in RED');
			return false;
		}
		else
		{
			setConfirm();
			$('.btn-submit').attr("disabled", true);          
 	                         
			return true;
		}
	}
}

ValidationB = 
{
	Start: function()
	{
		var elements = new Array(
				"homeAddress", 
				"homeCity", 
				"homeState",
				"homeLength02", 
				"homeLength03",
				"bestCallTime", 
				"homePhone01", 
				"homePhone02", 
				"homePhone03", 
				"stateID", 
				"birthDate01",
				"birthDate02", 
				"birthDate03", 
				"ssnPart01", 
				"ssnPart02",
				"ssnPart03", 
				"bankName", 
				"bankPhone01",
				"bankPhone02", 
				"bankPhone03",
				"bankABA", 
				"bankAccount",
				"bankLength02",
				"bankLength03",
				"refName01",
				"refPhoneOne01",
				"refPhoneOne02", 
				"refPhoneOne03", 
				"refName02", 
				"refPhoneTwo01", 
				"refPhoneTwo02", 
				"refPhoneTwo03", 
				"employmentStatus", 
				"employerName",
				"jobTitle", 
				"employerCity",
				"employerState",
				"employerZip", 
				"workPhone01", 
				"workPhone02", 
				"workPhone03", "monthlyIncome", "payFrequency", "dateHired02", "dateHired03", "directDeposit", "nextPayday01", "nextPayday02", "nextPayday03", "secondPayday01", "secondPayday02", "secondPayday03")
		
		for (var element = 0; element < elements.length; ++element)
		{
				$X(''+ elements[element] +'').onblur = function () { ValidationB.Definitions(this, "true"); };
		}
		
		$("#homePhone01, #homePhone02, #homePhone03").numeric();
		$("#cellPhone01, #cellPhone02, #cellPhone03").numeric();
		$("#homePhone01, #homePhone02, #homePhone03").numeric();
		$("#ssnPart01, #ssnPart02, #ssnPart03").numeric();
		$("#bankPhone01, #bankPhone02, #bankPhone03").numeric();
		$("#refPhoneOne01, #refPhoneOne02, #refPhoneOne03").numeric();
		$("#refPhoneTwo01, #refPhoneTwo02, #refPhoneTwo03").numeric();
		$("#workPhone01, #workPhone02, #workPhone03").numeric();
		
		autoTab('homePhone01', 'homePhone02', 3);
		autoTab('homePhone02', 'homePhone03', 3);
		autoTab('cellPhone01', 'cellPhone02', 3);
		autoTab('cellPhone02', 'cellPhone03', 3);
		autoTab('ssnPart01', 'ssnPart02', 3);
		autoTab('ssnPart02', 'ssnPart03', 2);
		autoTab('bankPhone01', 'bankPhone02', 3);
		autoTab('bankPhone02', 'bankPhone03', 3);
		autoTab('refPhoneOne01', 'refPhoneOne02', 3);
		autoTab('refPhoneOne02', 'refPhoneOne03', 3);
		autoTab('refPhoneTwo01', 'refPhoneTwo02', 3);
		autoTab('refPhoneTwo02', 'refPhoneTwo03', 3);
		autoTab('workPhone01', 'workPhone02', 3);
		autoTab('workPhone02', 'workPhone03', 3);
	},
	
	Define: function()
	{
		var possArr = new Array();
		possArr['homeAddress'] = new Array("isEmpty();");
		possArr['homeCity'] = new Array("isEmpty();");
		possArr['homeState'] = new Array("isEmpty();");
		possArr['homeLength02'] = new Array("isEmpty();isNumber();");
		possArr['homeLength03'] = new Array("isEmpty();isNumber();");
		possArr['bestCallTime'] = new Array("isEmpty();");
		possArr['homePhone01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['homePhone02'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['homePhone03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['stateID'] = new Array("isEmpty();");
		possArr['birthDate01'] = new Array("isEmpty();isNumber();");
		possArr['birthDate02'] = new Array("isEmpty();isNumber();");
		possArr['birthDate03'] = new Array("isEmpty();isNumber();");
		possArr['ssnPart01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['ssnPart02'] = new Array("isEmpty();isNumber();isMin(2);isMax(2);");
		possArr['ssnPart03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['amountRequested'] = new Array("isEmpty();isNumber();");
		possArr['bankName'] = new Array("isEmpty();");
		possArr['bankPhone01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['bankPhone02'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['bankPhone03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['bankABA'] = new Array("isEmpty();isNumber();isMin(9);isMax(9);");
		possArr['bankAccount'] = new Array("isEmpty();isNumber();");
		possArr['bankLength02'] = new Array("isEmpty();isNumber();");
		possArr['bankLength03'] = new Array("isEmpty();isNumber();");
		possArr['refName01'] = new Array("isEmpty();isMin(2);");
		possArr['refPhoneOne01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['refPhoneOne02'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['refPhoneOne03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['refName02'] = new Array("isEmpty();isMin(2);");
		possArr['refPhoneTwo01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['refPhoneTwo02'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['refPhoneTwo03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['employmentStatus'] = new Array("isEmpty();");
		possArr['employerName'] = new Array("isEmpty();isMin(2);");
		possArr['jobTitle'] = new Array("isEmpty();isMin(2);");
		possArr['employerCity'] = new Array("isEmpty();");
		possArr['employerState'] = new Array("isEmpty();");
		possArr['employerZip'] = new Array("isEmpty();isMin(5);isMax(5);");
		possArr['workPhone01'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['workPhone02'] = new Array("isEmpty();isNumber();isMin(3);isMax(3);");
		possArr['workPhone03'] = new Array("isEmpty();isNumber();isMin(4);isMax(4);");
		possArr['monthlyIncome'] = new Array("isEmpty();");
		possArr['payFrequency'] = new Array("isEmpty();");
		possArr['dateHired02'] = new Array("isEmpty();isNumber();");
		possArr['dateHired03'] = new Array("isEmpty();isNumber();");
		possArr['directDeposit'] = new Array("isEmpty();");
		possArr['nextPayday01'] = new Array("isEmpty();isNumber();");
		possArr['nextPayday02'] = new Array("isEmpty();isNumber();");
		possArr['nextPayday03'] = new Array("isEmpty();isNumber();");
		possArr['secondPayday01'] = new Array("isEmpty();isNumber();");
		possArr['secondPayday02'] = new Array("isEmpty();isNumber();");
		possArr['secondPayday03'] = new Array("isEmpty();isNumber();");
		
		return possArr;
	},
	
	Definitions: function(pTarget, sqlStatus)
	{
		var possArr = ValidationB.Define();
		
		if (sqlStatus == "true")
		{
			GlobalVal.Validate(pTarget.name, pTarget.value, possArr[pTarget.name][0], true);
		}
		else
		{
			GlobalVal.Validate(pTarget.name, pTarget.value, possArr[pTarget.name][0], false);
		}
	},
	
	CallBack: function()
	{
		var possArr = ValidationB.Define();
		var elements = new Array("homeAddress", "homeCity", "homeState", "homeLength02", "homeLength03", "bestCallTime", "homePhone01", "homePhone02", "homePhone03", "stateID", "birthDate01", "birthDate02", "birthDate03", "ssnPart01", "ssnPart02", "ssnPart03", "bankName", "bankPhone01", "bankPhone02", "bankPhone03", "bankABA", "bankAccount", "bankLength02", "bankLength03", "refName01", "refPhoneOne01", "refPhoneOne02", "refPhoneOne03", "refName02", "refPhoneTwo01", "refPhoneTwo02", "refPhoneTwo03", "employmentStatus", "employerName", "jobTitle", "employerCity", "employerState", "employerZip", "workPhone01", "workPhone02", "workPhone03", "monthlyIncome", "payFrequency", "dateHired02", "dateHired03", "directDeposit", "nextPayday01", "nextPayday02", "nextPayday03", "secondPayday01", "secondPayday02", "secondPayday03")
		var stop = '';
		
		for (var element = 0; element < elements.length; ++element)
		{
			if (GlobalVal.Validate(''+ elements[element] +'', $X(''+ elements[element] +'').value, possArr[''+ elements[element] +''][0], false) == "true")
			{
				//OK == Validation Passed
			}
			else
			{
				stop = true;
			}
		}
		
		if (stop == true)
		{
			alert('Please complete fields highlighted in RED');
			return false;
		}
		else
		{
			setConfirm();
			//$X('getcash').disabled = true;
			return true;
		}
	}
}

GlobalVal =
{
	Validate: function(id, value, validations, mysql)
	{
		var valArr = validations.split(";");
		var newID = (strstr(id, 'ref')) ? (strstr(id, 'Phone')) ? id.replace(/[0-9]+/, '') : id : id.replace(/[0-9]+/, '');
		var stop = '';
		
		for (var element = 0; element < valArr.length; ++element)
		{
			if (valArr[element] != '')
			{
				if (GlobalVal.Process(id, value, valArr[element]) == true)
				{
					//Update Passed
					if (element == (valArr.length - 2))
					{
						if (mysql == true)
						{
							//GlobalVal.Mysql(id, value);
						}
					}
				}
				else
				{
					
					//$X("V"+newID).src = 'images/cross.png';
					$X(id).style.backgroundColor = '#DF8685';
					
					stop = 1;
					break;
				}
			}
		}
		
		if (stop != 1)
		{
			//$X("V"+newID).src = 'images/tick.png';
			$X(id).style.backgroundColor = '';
			return "true";
		}
	},
	
	Process: function(id, value, validation)
	{	
		switch (validation)
		{
			case strstr(validation, 'isEmpty'):
				if (value == '')
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
			
			case strstr(validation, 'isNumber'):
				if (!IsNumeric(value) * 1)
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
			
			case strstr(validation, 'isMin'):
				var newNum = validation.match(/isMin\((.*)\)/);
				
				if (value.length < newNum[1])
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
			
			case strstr(validation, 'isMax'):
				var newNum = validation.match(/isMax\((.*)\)/);
				
				if (value.length > newNum[1])
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
			
			case strstr(validation, 'isEmail'):
				var emailRegex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				
				if (emailRegex.test(value) == false)
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
			
			case strstr(validation, 'isDate'):
				var dateRegex = /^([0-9]{2})+\/([0-9]{2})+\/([0-9]{4})$/;
				
				if (dateRegex.test(value) == false)
				{
					return false;
				}
				else
				{
					return true;
				}
			break;
		}
	},
	
	Mysql: function(name, value)
	{
		var xmlHttp;
		var id = $X('uid').value;
		
		if (this.id != '')
		{
			try
			{
				xmlHttp=new XMLHttpRequest();
			}
			catch (e)
			{
				try
				{
					xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e)
				{
					try
					{
						xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (e)
					{
						//Ajax is not supported
						return false;
					}
				}
			}
			
			xmlHttp.onreadystatechange = function()
			{
				if (xmlHttp.readyState == 4)
				{
					if (xmlHttp.status == 200)
					{
						var response = xmlHttp.responseText.split('|');
						if (response[0] == "OK")
						{
							//Pass
						}
						else
						{
							//Fail
						}
					}
				}
			}
			
			xmlHttp.open("GET", 'update?uid='+ id +'&rowKey='+ name +'&rowValue=' + value +'', true);
			xmlHttp.send(null);
		}
		else
		{
			return false;
		}
	}
}

function strstr( haystack, needle, bool )
{
    var pos = 0;
	
    haystack += '';
    pos = haystack.indexOf( needle );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

var noConfirm = false;

function setConfirm()
{
	noConfirm = true;
}

function resetConfirm()
{
	noConfirm = false;
}

function $X(element)
{
	element = document.getElementById(element);
	return element;
}

function checkStatus(id, approvedURL)
{
	$.ajax({
		method: 'get',
		url : '/status?uid='+ id +'&str=true&time='+ Math.round(new Date().getTime() / 1000) +'',
		type: "GET",
		dataType : 'text',
		success: function (text) { if (text == 'COMPLETE') { clearTimeout(statusCheck); window.location.href = approvedURL; } else { $('#statusUpdate').text(text); } }
	});
}

countDown = {
	sec: 00,
	min: 05,
	
	Start: function()
	{
		countDown.sec--;
		if (countDown.sec == -01)
		{
			countDown.sec = 59;
			countDown.min = countDown.min - 1;
		}
		else {
			countDown.min = countDown.min;
		}
		if (countDown.sec<=9)
		{ 
			countDown.sec = "0" + countDown.sec;
		}
		
		time = (countDown.min<=9 ? "" + countDown.min : countDown.min) + " minutes and " + countDown.sec + " seconds";
		
		if (document.getElementById)
		{
			if ($X('theTime'))
			{
				$X('theTime').innerHTML = time;
			}
			else
			{
				window.clearTimeout(SD);
			}
		}
		
		SD=window.setTimeout("countDown.Start();", 1000);
		
		if (countDown.min == '00' && countDown.sec == '00')
		{
			countDown.sec = "00"; window.clearTimeout(SD);
		}
	}
}

function autoTab(CurrentElementID, NextElementID, FieldLength) {
    var CurrentElement = $('#' + CurrentElementID);
    var NextElement = $('#' + NextElementID);
 
    CurrentElement.keyup(function(e) {
        var KeyID = (window.event) ? event.keyCode : e.keyCode;
		
        if (CurrentElement.val().length >= FieldLength
            && ((KeyID >= 48 && KeyID <= 90) ||
            (KeyID >= 96 && KeyID <= 105)))
            NextElement.focus();
    });
}

function hasAccount()
{
	var pTarget = document.forms['cash_advance'].bank;
	
	if (radioValidate(pTarget) == "TRUE")
	{
		$X('bank_account_row').style.display = 'none';
	}
	else
	{
		$X('bank_account_row').style.display = '';
	}
}

function startTimer(pTarget, firstName, amountRequested)
{
	$("#progress").progressbar({ value: 0,   change: function(event, ui) { var newVal = $(this).progressbar('option', 'value'); $('.pblabel', this).text(newVal + '%'); } });
	
	/* We want 100% in 5000 ms or 5 seconds */
	var stopLoop = 0;
	var value = 0;
	
	var increment = 6000 / 100;
	var next = increment;
	
	$("#progress").progressbar({ value: 0 });
	do
	{
		//increment = Math.random() * 80;
		
		if (stopLoop == 0)
		{
			setTimeout("$('#progress').progressbar('option', 'value', '"+ value +"');", next);
			value = value + 1;
			next = next + increment;
		}
		
		if (value == 101)
		{
			stopLoop = 1;
		}
		
	} while (stopLoop < 1);
	
	setTimeout("showText('"+ pTarget +"', '"+ firstName +"', '"+ amountRequested +"')", 8000);
}

function showText(pTarget, homeCity, amountRequested)
{
	var pValue = '<h1>Congratulations! Loans are available for $'+ amountRequested +'!</h1><h2>To secure your loan, complete your application within<br /><span class="time" id="theTime">5 minutes 0 seconds</span>.</h2>';
	
	$("#"+ pTarget +"").html(pValue);
	countDown.Start();
}

function resetTermsBox(pTarget)
{
	if (pTarget.checked)
	{
		$X('legalText').style.color = '#000000';
		$X('legalText').style.fontWeight = '400';
	}
	else
	{
		$X('legalText').style.color = '#C00E0C';
		$X('legalText').style.fontWeight = '700';
	}
}

function loadpopunder()
{
	if (!noConfirm)
	{
		return "*************************************************\n\n>>> WAIT, DON'T LEAVE WITHOUT YOUR CASH!\n\n*************************************************\n\nYour application is almost complete, You're only 60 seconds away from getting the money you deserve.\n\nIf you close the tab, your application and pre-approval will be lost.\n\nCLICK THE CANCEL BUTTON NOW TO GET YOUR CASH.\n\n*************************************************";
	}
}

function skipPop()
{
	window.onbeforeunload = '';
}

function setPop()
{
	window.onbeforeunload = loadpopunder;
}

var hasFired = false;

function getBankName()
{
	var number = $("#bankABA").val();
	
	if ((number != '') && (hasFired == false))
	{
		$.ajax({
			type: "GET",
			url: "/images/getBankName.php",
			data: "aba="+ number +"",
			success: function(msg)
			{
				var msg = msg.split("--");
				
				switch (msg[0])
				{
					case "ERROR":
						$X("VbankABA").src = 'images/cross.png';
						
						$("#steptwo-form").block({ 
							message: '<br /><h1>Your ABA number does not appear to be valid.<br /><br />Please try entering your ABA again.</h1><br /><a href="#" id="unBlock" style=\"color: blue;\">CLICK HERE TO CLOSE</a></h1>', 
							css: { border: '3px solid #ff0000', width: '545px', height: '115px', cursor: null } 
						});
						
						$("#unBlock").click(function() {
							$("#steptwo-form").unblock();
							return false;
						});
						
						$("#checkImage").show("slow");
					break;
					
					case "TRUE":
						$("#bankName").val(msg[1]);
						$("#bankPhone01").val(msg[2]);
						$("#bankPhone02").val(msg[3]);
						$("#bankPhone03").val(msg[4]);
					break;
				}
			}
		});
		
		hasFired = true;
	}
}

function newWindow(url, name)
{
	window.open(url, ""+ name +"", "menubar=no,width=800,height=500,toolbar=no,location=no,resizable=no,scrollbars=yes");
}

function radioValidate(btn)
{
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--)
	{
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}

function checkDate(input)
{
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
	var returnval=false
	if (!validformat.test(input))
	return false;
	else{ //Detailed check for valid date ranges
	var monthfield=input.split("/")[0]
	var dayfield=input.split("/")[1]
	var yearfield=input.split("/")[2]
	var dayobj = new Date(yearfield, monthfield-1, dayfield)
	if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
	return faslse;
	else
	returnval=true
	}
	if (returnval==false) input.select()
	return returnval
}

function IsNumeric(strString)
{
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}



function submitForm() {
	if(ValidationA.CallBack()) {		
		urlString = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/payday/?";
		urlString += "amountRequested=" + $("#amountRequested").val() +
					 "&" + "firstName=" + $("#firstName").val() +
					 "&" + "lastName="  + $("#lastName").val() +
					 "&" + "emailAddress=" + $("#emailAddress").val() +
					 "&" + "homeZip=" + $("#homeZip").val();
		window.location = urlString;
		return false;
	} else {
		return false;
	}
}                      

$(document).ready( function() { 
	$('#whitelabel-form').submit(function() {  	
		if(!ValidationB.CallBack()) { return false; }	
		$.ajax({
		   type: "POST",
		   url: "/wp-content/plugins/whitelabel-offer/whitelabel-submit.php",
		   data: $(this).serialize(),
		   success: function(msg){		   	
		   	 if(msg.indexOf("Error") == 0) {		   	 	
		   	 	$('#loader').hide();
		   	 	$('#submit-button').show();
		   	 	$('#error-message').html(msg);
		   	 	return false;
		   	 } 
		   	 response = jQuery.parseJSON(msg);
		   	 window.location = response.redirectURL;	     
		   }
		 });  		
		 return false;
	});
	$("#loader").ajaxStart(function(){
	   $(this).show();
	   $('#submit-button').hide();
	 });	
})

