// Array that contains information of the field names and the corresponding type of validation.
// Include those fields that require validation here.
// Note: String "validate" is appended to the validation type provided here in order to execute the appropriate function.
// For e.g., for "alpha", the function name would be "validate_alpha".
var fields_to_validate = [
			["promo_code","alpha"],
			["first_name","alpha"],
			["last_name","alpha"],
			["title","notempty"],
			["company","alpha"],
			["street","notempty"],
			["city","notempty"],
			["state","notempty"],
			["zip","alpha"],
			["country","notempty"],
			["phone","notempty"],
			["email","email"],
			["emailcheck","emailcheck","email"]
		];
// Global error messages
var err_messages = new Array();
err_messages["promo_code"] = '<li>You did not enter your <a href="#promo_code">Promo Code</a></li>';
err_messages["first_name"] = '<li>You did not enter your <a href="#first_name">First Name</a></li>';
err_messages["last_name"] = '<li>You did not enter your <a href="#last_name">Last Name</a></li>';
err_messages["title"] = '<li>You did not enter your <a href="#title">Title</a></li>';
err_messages["company"] = '<li>You did not enter your <a href="#company">Company</a></li>';
err_messages["street"] = '<li>You did not enter your <a href="#street">Address 1</a></li>';
err_messages["city"] = '<li>You did not enter your <a href="#city">City</a></li>';
err_messages["state"] = '<li>You did not enter your <a href="#state">State</a></li>';
err_messages["zip"] = '<li>You did not enter your <a href="#zip">Zip/Postal Code</a></li>';
err_messages["country"] = '<li>You did not enter your <a href="#country">Country</a></li>';
err_messages["phone"] = '<li>You did not enter your <a href="#phone">Phone</a></li>';
err_messages["email"] = '<li>You did not enter your <a href="#email">E-mail</a>; example: name@domain.com</li>';
err_messages["emailcheck"] = '<li>You did not verify your <a href="#emailcheck">E-mail</a></li>';
err_messages["00N30000000w1FI"] = '<li>You did not tell us if you have deployed <a href="#00N30000000w1FI">Active Directory</a></li>';
err_messages["00N40000001MepM"] = '<li>You did not tell us how many <a href="#00N40000001MepM">Linux and/or UNIX servers</a> you have in your organizations</li>';
err_messages["00N40000001MepR"] = '<li>You did not tell us the <a href="#00N40000001MepR">operating systems</a> you are running on your Linux and/or UNIX servers</li>';
err_messages["00N40000001MepW"] = '<li>You did not tell us the <a href="#00N40000001MepW">applications</a> you are running on your Linux and/or UNIX servers</li>';
err_messages["00N40000001Mepb"] = '<li>You did not tell us your <a href="#00N40000001Mepb">level of interest</a> in Active Directory integration for your Linux and/or UNIX systems and applications</li>';

// Main function to validate the entire form.
// This function first validates the main contact form before proceeding to the additional form.
// Thus if validation of the main contact form fails, appropriate error is shown and the validation process stops here.
// The additional form is validated only after the main form errors are corrected.
function validate_form() {
	var frm_obj = document.forms[0];
	var err_mainform = validate_mainform(frm_obj);
	var err_cnt = err_mainform.length;
	// Reset the style for all the form elements
	for(var i=0;i<frm_obj.elements.length;i++) {
		var frm_elem = frm_obj.elements[i];
		var frm_elem_obj = (frm_elem.name) ? document.getElementById(frm_elem.name) : null;
		// Skip if the dom object does not exist or the classname is not highlight.
		if(!frm_elem_obj || frm_elem_obj.className != "highlight") continue;
		frm_elem_obj.className = "";
	}
	if(err_cnt > 0) { // Error occured in main form
		var err_msg = "";
		for(var i=0; i<err_cnt; i++) {
			document.getElementById(err_mainform[i]).className = "highlight";
			err_msg += err_messages[err_mainform[i]]; // Display appropriate error messages
		}
		display_errormsg(err_cnt,err_msg);
		return false;
	}
	else { // No Errors in main form
		var err_addnlform = validate_additionalform(frm_obj);
		var err_addnlform_cnt = err_addnlform.length;
		if(err_addnlform_cnt > 0) { // Error occured in additional form
			var err_msg = "";
			for(var i=0; i<err_addnlform_cnt; i++) {
				err_msg += err_messages[err_addnlform[i]]; // Display appropriate error messages
			}
			display_errormsg(err_addnlform_cnt,err_msg);
			return false;
		}
		else { // No errors in additional form as well, i.e. no errors in the overall form
			hide_errormsg();
			// If a value is entered in to the Address 2 field, Address 1 = Address 1 + Address 2 
			if(frm_obj.street && frm_obj.street2 && frm_obj.street2.value != "")
				frm_obj.street.value = frm_obj.street.value + " " + frm_obj.street2.value;
			// Set "Likewise" cookie before submitting
			set_cookie("Likewise","FormFilled");
			// Validate the datasource of promotional code only if the form element 'promo_code' exists
			if(document.forms[0].promo_code)
				return validate_promocode(document.forms[0].promo_code.value);
			return true;
		}
	}
}

// Function to display the error message
function display_errormsg(cnt,msg) {
	var err_box = document.getElementById("error");
	var err_msg = '<p>We encountered <strong>' +cnt+ ' error(s)</strong> while trying to process this form:</p>';
	err_msg += '<ul class="normal_list">';
	err_msg += msg;
	err_msg += '</ul>';
	err_box.innerHTML = err_msg;
	err_box.className = "alert";
	// Link up to the error box whenever error occurs.
	window.location.hash = "#error";	
}

// Function to hide the error message
function hide_errormsg() {
	var err_box = document.getElementById("error");
	err_box.innerHTML = "";
	err_box.className = "hide";
}

// Validation code for the Main Contact Form.
function validate_mainform(frm_obj) {
	var err = new Array();
	// Execute the appropriate validation functions
	for(var i=0; i<fields_to_validate.length; i++){
		var field = eval("document.forms[0]."+fields_to_validate[i][0]);
		if(!field) continue; // Do not execute if the field is not present.
		var function_name = "";
		if(fields_to_validate[i][1] == "emailcheck") { // If EmailCheck, then check for the original email field before comparing the values.
			var field1 = eval("document.forms[0]."+fields_to_validate[i][2]);
			if(!field1) continue;
			function_name = "validate_"+fields_to_validate[i][1]+"(field.value,field1.value)";
		}
		else
			function_name = "validate_"+fields_to_validate[i][1]+"(field.value)";

		if(!eval(function_name)) // Actual function call happens here.
			err[err.length] = fields_to_validate[i][0];
	}  
	return err;
}

// Validation code for the Additional Questions Form.
function validate_additionalform(frm_obj) {
	var err = new Array();
	// Default value is NO - not answered.
	var ad_answer = "NO";
	var servers_answer = "NO";
	var os_answer = "NO";
	var apps_answer = "NO";
	var interest_answer = "NO";
	var obj = null;
	if(obj = frm_obj.elements["00N30000000w1FI"]) {	// Check for the element before validating
		for (i=0; i<obj.length; i++) {
			if (obj[i].checked) { // A radio option or checkbox is selected.
				ad_answer = "YES";
				break;
			}
		}
	} else // Indicate that the element is not present, i.e. NA - not applicable
		ad_answer = "NA";

	if(obj = frm_obj.elements["00N40000001MepM"]) { // Check for the element before validating
		for (i=0; i<obj.length; i++) {
			if (obj[i].checked) { // A radio option or checkbox is selected.
				servers_answer = "YES";
				break;
			}
		}
	} else // Indicate that the element is not present, i.e. NA - not applicable
		servers_answer = "NA";

	if(obj = frm_obj.elements["00N40000001MepR"]) { // Check for the element before validating
		for (i=0; i<obj.length; i++) {
			if (obj[i].checked) { // A radio option or checkbox is selected.
				os_answer = "YES";
				break;
			}
		}
	} else // Indicate that the element is not present, i.e. NA - not applicable
		os_answer = "NA";

	if(obj = frm_obj.elements["00N40000001MepW"]) { // Check for the element before validating
		for (i=0; i<obj.length; i++) {
			if (obj[i].checked) { // A radio option or checkbox is selected.
				apps_answer = "YES";
				break;
			}
		}
	} else // Indicate that the element is not present, i.e. NA - not applicable
		apps_answer = "NA";

	if(obj = frm_obj.elements["00N40000001Mepb"]) { // Check for the element before validating
		for (i=0; i<obj.length; i++) {
			if (obj[i].checked) { // A radio option or checkbox is selected.
				interest_answer = "YES";
				break;
			}
		}
	} else // Indicate that the element is not present, i.e. NA - not applicable
		interest_answer = "NA";

	// The additional questions are not answered.
	if(ad_answer == "NO")
		err[err.length] = "00N30000000w1FI";
	if(servers_answer == "NO")
		err[err.length] = "00N40000001MepM";
	if(os_answer == "NO")
		err[err.length] = "00N40000001MepR";
	if(apps_answer == "NO")
		err[err.length] = "00N40000001MepW";
	if(interest_answer == "NO")
		err[err.length] = "00N40000001Mepb";

	return err;
}

// Email Validation: returns true if valid, otherwise false.
function validate_email(value) {
	var obj_reg_exp  = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
	return obj_reg_exp.test(value);
}

// Email Check: returns true if correct, otherwise false.
function validate_emailcheck(value1,value2) {
	if(!validate_email(value2)) return true;
	return (value1 == value2);
}

// US Phone Validation (999) 999-9999 or 999-999-9999 or 999 999 9999 or 999.999.9999 : returns true if valid, otherwise false.
function validate_phone(value) {
	var obj_reg_exp  = /^\(?[1-9]\d{2}\)?[\s\-\.]?\d{3}[\s\-\.]?\d{4}$/;
	return obj_reg_exp.test(value);
}

// US Zip Validation 99999 or 99999-9999 : returns true if valid, otherwise false.
function validate_zip(value) {
	var obj_reg_exp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	return obj_reg_exp.test(value);
}

// Alpha numeric Validation: returns true if valid, otherwise false.
function validate_alpha(value) {
	var obj_reg_exp  = /^[A-Za-z0-9]/;
	return obj_reg_exp.test(value);
}

// Checks for non-empty value: returns true if valid, otherwise false.
function validate_notempty(value) {
	var temp = value;
	temp = trim(temp);
	if(temp.length > 0){
		return true;
	}
	return false;
}

// Trims all leading and trailing spaces.
function trim(value) {
	var obj_reg_exp = /^(\s*)$/;
	if(obj_reg_exp.test(value)) {
		value = value.replace(obj_reg_exp, '');
		if( value.length == 0)
			return value;
	}
	obj_reg_exp = /^(\s*)([\W\w]*)(\b\s*$)/;
	if(obj_reg_exp.test(value)) {
		//remove leading and trailing whitespace characters
		value = value.replace(obj_reg_exp, '$2');
	}
	return value;
}

// Function to set the cookie value
function set_cookie(name,value) {
  var cookie_string = name + "=" + escape(value);
  cookie_string += "; expires=Thu, 31-Dec-2020 08:00:00 GMT";
  cookie_string += "; path=/";
  document.cookie = cookie_string;
}

// Function to read the cookie value
function getCookie(name) {
  var results = document.cookie.match( name + '=(.*?)(;|$)' );
  if(results)
    return (unescape(results[1]));
  else
    return null;
}

// Function that posts the promotional code to datasource validation(PHP) via XMLHttp
var http_obj = null;
function validate_promocode(code) {
	http_obj = create_request();
	http_obj.open('post', '/includes/datasource_validation.php'); // Post the data
	http_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http_obj.send('promocode='+code); // Send the query parameter
	http_obj.onreadystatechange = handle_response; // Call the function 'handle_response' when the ready state changes
	return false;
}

// Function to create the XMLHttp request object
function create_request(){
	var request_obj; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer") {
		// Create the object using MSIE's method
		request_obj = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		// Create the object using other browser's method
		request_obj = new XMLHttpRequest();
	}
	return request_obj; //return the object
}

// Function to handle the response from XMLHttp
function handle_response(){
	if(http_obj.readyState == 4){ //Finished loading the response
		var response = http_obj.responseText;
		switch(response){ // Display appropriate error messages
			case '0':
					display_errormsg(1,"<li>Server connection colud not be established</li>");
			break;
			case '1':
					display_errormsg(1,'<li>Database connection could not be estabished</li>');
			break;
			case '2':
					display_errormsg(1,'<li>The <a href="#promo_code">promotional code</a> you entered is invalid</li>');
			break;
			case '3':
					display_errormsg(1,'<li>The <a href="#promo_code">promotional code</a> you entered has already been submitted</li>');
			break;
			case '4':
					document.forms[0].submit();
			break;
			default:
					return false;
			break;
		}
	}
}

// The actual validation function call
window.onload = function(){document.forms[0].onsubmit=validate_form};
// E N D

