// ----------------------------Form validation script
if (typeof getId != 'function') {
	function getId(myObject) {
		return window.document.getElementById(myObject);
	}
}
function checkFields(form) {
	var required = form['required'];
	var proper_name = form['proper_name'];
	var email = form['email'];
	var email_proper = form['email_proper'];
	var phone = form['phone'];
	var phone_proper = form['phone_proper'];
	var error_message = '';
	for (i = 0; i < required.length; i++) {
		input = getId(required[i]);
		if (input != null) {
			// if field is empty
			if (input.value == "") {
				error_message += proper_name[i] + " is required.\r\n";
				input.setAttribute('style', 'background-color:pink;background-image:none');
			} else {
				input.removeAttribute('style');
			}
		}
	}
	// routine for checking non standard email fields
	if (phone != undefined) {
		for (i = 0; i < phone.length; i++) {
			var input = getId(phone[i]);
			input.removeAttribute('style');
			checkPhone(input);
		}
	}
	// routine for checking non standard email fields
	if (email != undefined) {
		for (i = 0; i < email.length; i++) {
			var input = getId(email[i]);
			input.removeAttribute('style');
			checkEmail(input);
		}
	}
	function checkPhone(input) {
		var phone = input.value;
		phone = phone.replace(/[^0-9]/g, '');
		input.value = phone;
		if (phone.length < 10) {
			error_message += phone_proper[i] + " is not valid.\r\n";
			input.setAttribute('style', 'background-color:pink;background-image:none');
		}
	}
	function checkEmail(input) {
		// check the email
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(input.value)) {
			error_message += email_proper[i] + " is not valid.\r\n";
			input.setAttribute('style', 'background-color:pink;background-image:none');
		}
	}
	if (error_message != '') {
		alert(error_message);
		return false;
	}
	return true;
}
function initFormValidation(form_id, input_id, input_name, email_id, email_name, phone_id, phone_name) {
	// displays all errors from the lead processor before starting to validate
	displayError();
	// insert input field so I can tell if javascript is enabled
	var input = document.createElement("input");
	input.setAttribute("type", "hidden");
	input.setAttribute("name", "js_on");
	//input.setAttribute("id","txt1");
	input.setAttribute("value", "1");
	document.getElementById(form_id).appendChild(input);
	// seting up default values for most of the forms
	// NO SPACES only commas between values!!!
	input_id = typeof(input_id) != 'undefined' ? input_id : 'course,first_name,last_name,format,address,city,state,zip,age,country,militarystatus';
	input_name = typeof(input_name) != 'undefined' ? input_name : 'Program,First Name,Last Name,Program Guide Format,Address,City,Province,Postal Code,Age,Country,Military Status';

	email_id = typeof(email_id) != 'undefined' ? email_id : 'email';
	email_name = typeof(email_name) != 'undefined' ? email_name : 'Email';
	phone_id = typeof(phone_id) != 'undefined' ? phone_id : 'phone';
	phone_name = typeof(phone_name) != 'undefined' ? phone_name : 'Phone number';
	// initializing form arrays
	var form = [];
	form['required'] = input_id.split(',');
	form['proper_name'] = input_name.split(',');
	form['email'] = email_id.split(',');
	form['email_proper'] = email_name.split(',');
	form['phone'] = phone_id.split(',');
	form['phone_proper'] = phone_name.split(',');
	// id of the form goes here
	var form_id = getId(form_id);
	form_id.onsubmit = function() {
		saveSelections(form_id);
		return checkFields(form)
	};
	// load selections
	loadSelections(form_id);
}
// ----------------------------Error handling
function $_GET() {
	var get = new Object();
	var parameters = window.location.toString().split("?").pop().split("&amp;");
	for (var i in parameters) {
		var parts = parameters[i].split("=");
		get[parts[0]] = String(parts[1]);
	}
	return get;
}
function displayError() {
	// get invalid field errors
	var get = $_GET('ife');
	var ife = get.ife
	// get duplicate flag
	var get = $_GET('dup');
	var dup = get.dup;
	// if there are input errors detected
	// the delay is in there so the page can have time to load before the alert can fire
	if (ife != undefined) {
		setTimeout('parseError("' + ife + '");', 2000);
	} else if (dup != undefined) {
		setTimeout('alert("We\'re Sorry. Our records indicate you have already requested this program with in the last 180 days. Feel free to select another program.");', 2000);
	}
}
function parseError(ife) {
	var message = "We\'re Sorry. The following are invalid:\n";
	var input_errors = new Array();
	// these map to the corresponding input id name so it can be highlighted 
	var input_id = new Array();
	input_errors['01'] = '- Salutation';
	input_errors['02'] = '- First Name';
	input_id['02'] = 'first_name';
	input_errors['03'] = '- Last Name';
	input_id['03'] = 'last_name';
	input_errors['04'] = '- Address';
	input_id['04'] = 'address';
	input_errors['05'] = '- Telephone';
	input_id['05'] = 'phone';
	input_errors['06'] = '- Email Address';
	input_id['06'] = 'email';
	input_errors['07'] = '- Age';
	input_id['07'] = 'age';
	input_errors['08'] = '- Date of Birth';
	input_errors['09'] = '- Gender';
	input_errors['10'] = '- Education Level';
	input_errors['11'] = '- OptInMail';
	input_errors['12'] = '- OptInEmail';
	input_errors['13'] = '- OptInPhone';
	input_errors['14'] = '- ProgramID';
	input_id['14'] = 'course';
	input_errors['15'] = '- PublicationCode';
	input_errors['16'] = '- Spot Code';
	input_errors['17'] = '- Affiliate ID';
	input_errors['18'] = '- IP Address';
	input_errors['19'] = '- IP Timestamp';
	input_errors['20'] = '- Referral URL';
	var ife_length = ife.length;
	for (i = 0; i < ife_length; i += 2) {
		var seg = ife.substr(i, 2);
		if (input_errors[seg] != undefined) {
			message += input_errors[seg] + '\n';
			if (input_id[seg] != undefined) {
				input = getId(input_id[seg]);
				input.setAttribute('style', 'background-color:pink;background-image:none');
			}
		}
	}
	message += " Please correct and then resubmit.";
	// wait a bit for everything to load
	alert(message);
}
function saveSelections(frm) {
	
	var setvalue;
	var fieldType;
	var index;
	var formname = frm.id;
	var today = new Date();// expire 1 day
	var exp = new Date(today.getTime() + 1 * 24 * 60 * 60 * 1000);
	var string = "formname=" + formname + "|";
	var cookieName = formname;
	var n = frm.length;
	for (i = 0; i < n; i++) {
		e = frm[i].name;
		fieldValue = frm[i].value;
		fieldType = frm[i].type;
		// saves  radio buttons
		if (fieldType == "radio") {
			for (x = 0; x < frm.elements[e].length; x++) {
				if (frm.elements[e][x].checked) {
					index = x
				}
			}
			string = string + index + "\|";
		}
		// saves input , textarea and selects
		if ((fieldType == "text") || (fieldType == "textarea") || (fieldType == "select-one")) {
				string = string + frm.elements[e].value + "\|";
		}
		// saves checkbox fields
		if (fieldType == "checkbox") {
			if (frm.elements[e].checked == true) {
				var setvalue = "1";
			}
			if (frm.elements[e].checked == false) {
				var setvalue = "0";
			}
			string = string + setvalue + "\|"; //alert("checkbox");
		} //
		// saves hidden field data
		/*
		if (fieldType == "hidden") {
			string = string + frm.elements[e].value + "\|"; //alert("text");
		}
		*/
	}
	setCookie(cookieName, string, exp);
}
function loadSelections(frm) {

	var e;
	var z;
	var x;
	var cookieName;
	var fieldArray;
	var fieldValues;
	var fieldValue;
	var formname = frm.id;
	cookieName = formname;
	fieldValues = getCookie(cookieName);
	if(fieldValues==null){
		return;
	}
	
	fieldArray = fieldValues.split("\|");
	var n = frm.length;
	var z = 1;
	for (i = 0; i < n; i++) {
		e = frm[i].name;

		var fieldType = frm[i].type;
		var fieldValue = fieldArray[z]; 
		// had to add this switch if there are any elements inside 
		// the form like a flash object it will mess up the loading order
		switch(fieldType){
			case 'text':
			case 'textarea':
			case 'select-one':
				if(e!='course' && e!='comments'){ // we dont want to load course selection or comments
					frm.elements[e].value = fieldValue; 
				}
				z++;			
			break;		
			case 'checkbox':
				fld_checkbox = fieldValue;
				if (fld_checkbox == "1") {
					frm.elements[e].checked = true;
				}
				z++;			
			break;		
			case 'radio':
				x = fieldValue; //alert(x);
				frm.elements[e][x].checked = true;
				z++;			
			break;	
			case 'hidden':
				//frm.elements[e].value = fieldValue;
				//z++;						
			break;
		}
		
		
	}
}
function setCookie(name, value, expires, path, domain, secure) {
	path = '/';
	cookie_string = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
	document.cookie = cookie_string;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}
// ---------------------------- END Form validation script

