/*
 * Ajx validation and submit
 *
 * when you deploy this file to prod, change the Ajax URL
 * url: "http://localhost/post-quotes"
 *
 * Date: 2010-04-06
 * Revision: 1.0
 */

var characters = 'abcdefghijklm\' nopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';
var combined = 'abcdefghijklmnopqrstuvw xyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var combined2 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ';
var comb_street = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#-,. ';
var result = '';

var countries = new Array();

	countries['PRFN'] = 'First Name';
	countries['PRLN'] = 'Last Name';
	countries['HASTREET'] = 'Street Address';
	countries['HACT'] = 'City';
	countries['HAST'] = 'State';
	countries['HAPC'] = 'Zip Code';	
	countries['PHHA'] = 'Phone';
	countries['PRE'] = 'Email';	

var good_all;


//Define indexOf function in case it's not defined. indexOf, still doesn't exist in IE
if (!Array.indexOf) {
	Array.prototype.indexOf = function(obj) {
		for (var i=0; i<this.length; i++) {
			if (this[i] == obj) {
				return i;
			}
		}
		return -1;
	}
}

//Return TRUE if inwhat contains what. The difference between indexOf and this
//is that, it checks out char by char in what string
function contains(what, inwhat) {
	for (var i=0; i<what.length; i++) {
		if (inwhat.indexOf(what.charAt(i)) == -1) return false;
	}
	return true;
}

//Return true if the string is in defined range, 
//Min and Max values must be passed
function check_range(str, min, max) {
	if (str.length < min) return false;
	if (str.length > max) return false;
	return true;
}

//Checks for valid e-mail with RegExp
function validateEmail(elementValue){  
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
	return emailPattern.test(elementValue);  
} 

//Function  which checks if passed string contains equal numbers(eg 111 222 or 333), also if it's increasing (eg: 123, 234 or 456)
function checkPhone(num1, num2, num3) {
	var good = false;
	var temp = num1.charAt(0);
	var str = num1 + num2 + num3;
	
	//get only first 3 characters of num3 for comparison.
	if (num3.length > 3) { 
		num3 = num3.substring(0,3);
	}
	
	//Check if all three fields are equal
	//if ( (num1 == num2) || (num1 == num3) || (num2 == num3) ) return false;
	if ( (num1 == num2) || (num2 == num3) ) return false;
	
	//Check if all the numbers are the same
	/*for (var i = 0; i < str.length; i++) {
		if (temp != str.charAt(i) ) {
			good = true;
			break;
		}
	}
	if (good == false) return false;*/
	
	//Check for sequence in numbers
	if (sequence(num1) && sequence(num2) && sequence(num3)) return false;
	
	return true;
}

function sequence(num) {
	var temp = num[0];
		for (var i = 1; i < num.length; i++) {
			temp++;
			if (temp > 9) temp = 0;	//FIXed
			if (num[i] != temp) return false;
		}
		return true;	//It's sequence
}

//Construct the message of incorrect fields
function bad(id) {
	if (result == '') {
		result += countries[id];
	} else {
		result += '<br/>'+countries[id];
	}
	
	if (countries[id] == 'Phone' ) {
		result += ' (Quote will be offered via phone)';
	}
	
	good_all = false;
}
//When DOM is loaded, build the array with countries in the drop-down list, for validation
$(document).ready(function() {
	$('#HAST option').each(function() {
		countries.push($(this).attr('value'));
	});

//Bind onkeyup event on phone fields

$('#PHHE').bind('keydown',function(eventData) {
	if (eventData.keyCode == 8) {
		if ($(this).val().length <= 0) $('#PHHA').focus();
	}
});

$('#PHHN').bind('keydown',function(eventData) {
	if (eventData.keyCode == 8) {
		if ($(this).val().length <= 0) $('#PHHE').focus();
	}
});


$('#PHHA').keyup(function() {
	if ($(this).val().length >= 3) $('#PHHE').focus();
});

$('#PHHE').keyup(function() {
	if ($(this).val().length >= 3) $('#PHHN').focus();
});



$('#submit1').click(function() {
	good_all = true;
	result = '';
	
	var PRFN = $.trim($("#PRFN").val());
	var PRLN = $.trim($("#PRLN").val());
	var HASTREET = $.trim($("#HASTREET").val());
	var HACT = $.trim($("#HACT").val());
	var HAST = $.trim($("#HAST").val());
	var HAPC = $.trim($("#HAPC").val());
	var PHHA = $.trim($("#PHHA").val());
	var PHHE = $.trim($("#PHHE").val());
	var PHHN = $.trim($("#PHHN").val());
	var PRE =  $.trim($("#PRE").val());
	var HAHT =  $.trim($("#HAHT").val());
	var credit_rating =  $.trim($("#credit_rating").val());
	
	//var sec_opt_in = (document.getElementById('sec_opt_in').checked)? "yes" : "no";
	var sec_opt_in = "no";

	var aff_subid = $("#aff_sub").val();
	var referer_page = $("#referer_page").val();
	var uniq_id = (new Date).getTime();
	var source = 'my-source-code';


    	var dataString = 'PRFN='+ PRFN + '&PRLN=' + PRLN + '&HASTREET=' + HASTREET + '&HACT=' + HACT +
    				'&HAST=' + HAST + '&HAPC=' + HAPC + '&PHHA=' + PHHA + '&PHHE=' + PHHE + '&PHHN='
    				+ PHHN + '&PRE=' + PRE  + '&aff_sub=' + aff_subid + '&affiliate_id=12&offer_id=PMIHW2'
    				+ '&transaction_id='+ uniq_id + '&referer_page=' + referer_page + '&opt_in=' + sec_opt_in
    				+ '&source='+ 'source' + '&HAHT='+ HAHT + '&credit_rating='+ credit_rating;

	//Fixed 2010.06.04 x6
	if (PRFN == 'First Name') bad('PRFN');
	if (PRLN == 'Last Name') bad('PRLN');
	if (HASTREET == 'Street Address') bad('HASTREET');
	//if (HACT == 'City') bad('HACT');
	
	
	//First Name
	if ( ( contains(PRFN,characters) ) && ( check_range(PRFN,2,26) ) ) {
	} else {
		bad('PRFN');
	}

	//Last Name. Allow chars only, min: 2, max: 26 the same as First Name
	if ( ( contains(PRLN,characters) ) && ( check_range(PRLN,2,26) ) ) {
	} else {
		bad('PRLN');
	}

	//Address. Allow combined symbols(a-zA-Z0-9), min: 5 max:40
	if ( ( contains(HASTREET,comb_street) ) && ( check_range(HASTREET,5,40) ) ) {
	} else {
		bad('HASTREET');
	}
	
	/*
	//City
	if ( ( contains(HACT,characters) ) && ( check_range(HACT,3,26) ) ) {
	} else {
		bad('HACT');
	}
	//State. Check if the value is in the countries array which is a dump of all "<option value="...."
	if ( contains(HAST,characters) && (countries.indexOf(HAST)) ) {
	} else {
		bad('HAST');
	}
	*/
	
	//ZIP code. Only digits and _must_ be 5 digits
	if ( ( contains(HAPC,numbers) ) && ( check_range(HAPC,5,5) ) ) {
	} else {
		bad('HAPC');
	}
	
	//Phone
	if ( (checkPhone(PHHA, PHHE, PHHN) ) && (contains(PHHA,numbers)) && (contains(PHHE, numbers)) && (contains(PHHN, numbers) && (check_range(PHHA, 3, 3)) && (check_range(PHHE, 3, 3)) && (check_range(PHHN, 4, 4)) ) ) {
	
	} else {
		bad('PHHA');
	}
	
	//Email
	if ( validateEmail(PRE) ) {	
	} else {
		bad('PRE');
	}

	if (good_all == true) {	//If good is not touched
		//alert("Now submitting" + dataString);
		$('.error').fadeOut(200).hide();
		$('.submit').hide();
		$('.hourglass').show();
		//$('#formelements').append('<div style="text-align: center"><img src="/wp-content/uploads/images/ajax-loader.gif" alt="Submitting your request" id="loading" /></div>');


		$.ajax({
		  type: "POST",
		  url: "/post-quotes",
		  data: dataString,
		  success: function(data_response){
		  //alert ('-->'+data_response+'<--');
		  if ( data_response.indexOf('ZIP_LOOKUP_FAILURE')>=0 ){
			$('.hourglass').hide();
			$('.error').html('Sorry, we could not determine State and City based on your Zip code. Please provide this information.');
			$('.error').show();
			$('#city-state').show();
			$('.submit').fadeIn(200).show();
		  }
		  else {
			window.location='/quote-req-submitted';
			/*$('#formelements').hide();
			$('.success').fadeIn(200).show();
			$('.hourglass').hide();*/
		     }
		  }
	    });
	}//else
	else {
		$('.error').html('Following fields contain invalid/insufficient data. Please review and resubmit: <br/>'+result);
		$('.error').show();
		$('.success').hide();
		$.ajax({
		  type: "POST",
		  url: "/post-quotes",
		  data: dataString + '&validation_failed=' + result,
		  success: function(data_response){
		  	//alert(data_response); 
		  }
	    });

	}
	
	return false;
	});
});




function showCityState() {

	var input_div = document.getElementById("citystate_inputs");
	input_div.style.display = "block";

	var text_div = document.getElementById("citystate_text");
	text_div.style.display = "none";

	return; //success
}

//validate 5 digit zip code
function valZipSubmitForm() {
	var zip = document.getElementById("zip").value;
	
	var zipCodePattern = /^\d{5}$/;
	if (zipCodePattern.test(zip)){
		return true;  //valid zip code
	}
	
	alert("Please enter a valid 5 digit zip code ...");
	return false;
}

