/*
 * Generic AJAX Form Submission, Validation, and Form Builder Routine
 * ------------------------------------------------------------------
 *                       SUBMISSION ROUTINE
 * ------------------------------------------------------------------
 */

var ajaxItem = null;
var handleResponse = null;
var submitCallback = null;
var thisFormId = null;
var default_x = null;
var default_y = null;
var debugOn = false;
var $errClass='dfiFormErrorField';

//Submits a form by posting to the 'submit.form' service
//formID is the id of the form to submit
//myCallback is the function to call when the roundtrip ajax call is finished
//myCallback should accept 1 parameter, which is the responseText of the XmlHttp object
function ajaxSubmit(formID, myCallback) {
	if(formValidated(formID)) {
		showPleaseWait(true);
		ajaxItem = GetXmlHttpObject();
		if (!ajaxItem) return;
		handleResponse = myCallback;
		thisFormId = formID;
		ajaxItem.onreadystatechange = stateChanged;
		//alert('POST: /submit.form?' + buildQuery(formID));
		ajaxItem.open("POST", '/submit.form?' + buildQuery(formID), true);
		ajaxItem.send(null);
		return true;
	}
	return false;
}

//handles cross-browser XmlHttp object generation
function GetXmlHttpObject() {
	if (window.XMLHttpRequest) return new XMLHttpRequest();
	if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	alert('Operation Aborted: Your browser does not support AJAX.');
	return null;
}

//searches the document for a form with the id specified,
//then builds a query based on INPUT and SELECT object in that form
function buildQuery(formID) {
	var myVars = '';
	var myForms = document.getElementsByTagName('form');
	for(i = 0; i < myForms.length; i++) {
		if(myForms[i].id == formID) {
			var myInputs = myForms[i].elements;
			for(j = 0; j < myInputs.length; j++) {
				myVars += parseInput(myInputs[j]);
			}
		}
	}

	return myVars.substring(1); //removes leading ampersand (&)
}

//parses the value from an INPUT or SELECT object
//returns a string that is either
//empty in the case that the object was filtered (for submit, reset, and button types),
//or an id/value pair which is
//selected from an option list (for select types),
//taken directly from the object value (for anything else).
//only picks up checkbox and radio values if the option is checked
function parseInput(inputField) {
	if(inputField.type != 'submit' && inputField.type != 'reset' && inputField.type != 'button' && inputField.id && inputField.value) {
		if(inputField.type == 'text' || inputField.type == 'textarea' || inputField.type == 'hidden' || inputField.type == 'password') {
			return '&' + inputField.id + '=' + encodeURIComponent(inputField.value);
		}
		else if((inputField.type == 'checkbox' || inputField.type == 'radio')&& inputField.checked) {
			return '&' + inputField.id + '=' + encodeURIComponent(inputField.value);
		}
		else if(inputField.type == 'select-one')  {
			return '&' + inputField.id + '=' + inputField.options[inputField.selectedIndex].value;
		}
		else if(inputField.type == 'select-multiple')  {
			var selectedOptions = '';
			for(i = 0; i < inputField.options.length; i ++) {
				if(inputField.options[i].selected) {
					selectedOptions += '&' + inputField.id + '=' + encodeURIComponent(inputField.options[i].value);
				}
			}
			return selectedOptions;
		}
	}
	return '';
}

//checks the readyState of the XmlHttp object when it is changed
//a readyState of 4 indicates that the post has made it round-trip
//and that a response awaits in the XmlHttp object's responseText attribute
function stateChanged() {
	if (ajaxItem.readyState == 4) {
		setTimeout('showPleaseWait(false)',500);
		defaultHandler(ajaxItem.responseText);
	}
}

//parses the success code & passes to callback
 function defaultHandler(response) {
	var x = response.split("&");
	var success = null;
	var msg = null;
	var myForms = document.getElementsByTagName('form');
	
	for (i = 0; i < x.length; i++) {
		if(x[i].split("=")[0] == "success") {
			success = x[i].split("=")[1];
		}
		if(x[i].split("=")[0] == "msg") {
			msg = x[i].split("=")[1];
		}
	}
	if(debugOn) {
		alert(success);
		alert(msg);
	}
	if(handleResponse == defaultHandler) {//check if submit call indicated default handling. if not, handle with provided handler
		for(i = 0; i < myForms.length; i++) {
			if(myForms[i].id == thisFormId) {
				var formHeight = $("#"+thisFormId).height();
				myForms[i].innerHTML = (success=="0") ? ('<div style="height: '+formHeight+';text-align: center;width: ' + default_x + ';padding-top: ' + default_y + ';font-family:Arial, Helvetica, sans-serif;font-size:15px;font-weight:bold;color:#333333;">Thank you!</div>') : ('<div style="height: '+formHeight+';text-align: center;width: ' + default_x + ';padding-top: ' + default_y + ';font-family:Arial, Helvetica, sans-serif;font-size:15px;font-weight:bold;color:#333333;">Your request could not be completed.</div>');
			}
		}
	} else {
		handleResponse(success);
	}
	if(submitCallback != null)
		submitCallback();
 }
 
 function showPleaseWait(show) {
	if(show) {
		$("#screen").empty();
		$("#screen").append('' +
			'<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">' +
				'<tr>' +
					'<td valign="middle" align="center">' +
						'<div style="width:200px; height:110px;border: solid 1px #444444; background:white; text-align: center;">'+
							'<p style="background:#6666cc;text-align: left; padding: 3px; color: white;margin:0; font-weight:bold;">' +
								'DataFoundations.com'+
							'</p>'+
							'<p style="background:#ffffff;text-align: center;padding: 10px;margin:0;">' +
								'<img src="/images/page_loading_ani.gif" />'+
								'<br />'+
								'<span style="font-weight: bold; font-style: italics;font-family: Trebuchet MS; font-size: 16px; color: #1c4165;">Please Wait...</span>'+
							'</p>'+
						'</div>'+
					'</td>' +
				'</tr>' +
			'</table>' +
		'');
		$("#screen").width($(document).width());
		$("#screen").height($(document).height());
		$("#screen").fadeIn(250);
	}else{		
		$("#screen").fadeOut(250, function(){
			$("#screen").empty();
			$("#screen").css('display','none');
		});
	}
 }
 
 function showValidationAlert(show,msg) {
	if(show) {
		$("#screen").empty();
		$("#screen").append('' +
			'<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">' +
				'<tr>' +
					'<td valign="middle" align="center">' +
							'<table border="0" cellpadding="0" cellspacing="0" style="width:300px; border: solid 1px #444444; background:white; text-align: left;">'+
								'<tr>'+
									'<td style="background:#3333cc;text-align: left; padding: 3px; color: white;margin:0; font-weight:bold;">' +
										'Required Fields Missing!'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td style="background:#ffffff;text-align: left;padding: 10px;margin:0;">' +
										'<span style="font-weight: bold; font-family: Trebuchet MS; font-size: 12px; color: black;">'+
										msg+
										'</span>'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td style="background:#ffffff;text-align: right;padding: 10px;margin:0;">' +
										'&nbsp;' +
										'<div style="float:right;width: 50px; text-align:center;padding:3px; cursor:pointer; border: solid 1px #444444; background: #dddddd; color:black;" onclick="showValidationAlert(false,\'\')" onmouseover="this.style.background=\'#f5f5f5\'" onmouseout="this.style.background=\'#dddddd\'">OK</div>'+
									'</td>'+
								'</tr>'+
							'</table>'+
					'</td>' +
				'</tr>' +
			'</table>' +
		'');
		$("#screen").width($(document).width());
		$("#screen").height($(document).height());
		$("#screen").fadeIn(250);
	}else{		
		$("#screen").fadeOut(250, function(){
			$("#screen").empty();
			$("#screen").css('display','none');
			if (!$.browser.msie || ($.browser.msie && $.browser.version.substr(0,1)>=7)) {
				$("input."+$errClass+":first").focus();
			}
		});
	}
 
 }
 
//allows user to use default handling, which simply replaces the form content with a default response message.
//specifies x and y to determine width/height for response
function useDefault(x,y,customCallback) {
	default_x = x;
	default_y = y;
	if(customCallback !== null)
		submitCallback = customCallback;
	return defaultHandler;
}
 
/*
 * ------------------------------------------------------------------
 *                       DOM ONREADY ROUTINE
 * ------------------------------------------------------------------
 */
 
 $(document).ready( function(){
	var $abbr='<abbr title="This Field is Required">*</abbr>';
	$('fieldset form ol li input.nonblank').before($abbr);
	$('fieldset form ol li input.phone').before($abbr);
	$('fieldset form ol li input.email').before($abbr);
	if (!$.browser.msie || ($.browser.msie && $.browser.version.substr(0,1)>=7)) {
		$('fieldset form ol li input:first').focus();
	}
 });
 
/*
 * ------------------------------------------------------------------
 *                       VALIDATION ROUTINE
 * ------------------------------------------------------------------
 */
  
function formValidated(formID) {
	var errMsg = '';
	var myForms = document.getElementsByTagName('form');
	
	for(i = 0; i < myForms.length; i++) {
		if(myForms[i].id == formID) {
			var myInputs = myForms[i].elements;
			for(j = 0; j < myInputs.length; j++) {
				//if(errMsg == '') myInputs[j].focus(); // Causes errors in IE. Stops the submit during validation, and nothing makes it to POST.
				errMsg += checkValid(myInputs[j]);
			}
		}
	}
	if(errMsg == '') return true;
	showValidationAlert(true,'Please fill in or correct the following fields:<ul style="text-align:left;">' + errMsg + '</ul>');
	return false;
}

function checkValid(field) {
	var error = '';
	if(field.className) {
		var myClassNames = field.className.split(' ');
		for(i = 0; i < myClassNames.length; i++) {
			if(myClassNames[i] == 'phone') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass);
					//alert("Phone Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			} else if(myClassNames[i] == 'email') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass)
					//alert("Email Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else if(!validate_email(field.value)){
					$("#"+field.id).addClass($errClass)
					//alert("Email Validation 2: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			} else if(myClassNames[i] == 'nonblank') {
				if( field.value == ''){
					$("#"+field.id).addClass($errClass)
					//alert("Nonblank Validation 1: $(#"+field.id+").addClass("+$errClass+");");
					error = '<li>' + field.alt + '</li>';
				}else {
					$("#"+field.id).removeClass($errClass);
				}
			}
		}
	}
	return error;
}

function validate_email(value) {
	 apos=value.indexOf("@");
	 dotpos=value.lastIndexOf(".");
	 if (apos<1||dotpos-apos<2)
	 {
	   return false;
	 } else {
	   return true;
	 }

}