/*
 / Javascript AJAX Form Framework 1.09.1238
 / 3.4.2010
 / Written by Matthew Ewers
 / matt@cg-project.com
*/

// STYLE FOR OPACITY SCREEN
///////////////////////////////////////////////////////////

// #opacity_screen { position: absolute; top: 0; left: 0; background: #fff; opacity: .8; filter: alpha(opacity=80); visibility: hidden; text-align: center; }

// PRIMARY FUNCTIONS
///////////////////////////////////////////////////////////

var xmlHttp;

function $(i) {
	return document.getElementById(i);
}

function $$(i) {
	return document.getElementsByTagName(i);
}

function getAjaxObj() {
	var xmlHttp = null;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

// GLOBAL VARIABLES
///////////////////////////////////////////////////////////

var idStr = '';
var errStr = '';
var errTripped = false;
var use_opacity = false;
var loadingImg = '';
var errArr = new Array();
	errArr[0] = 'Please complete all required [highlighted] fields.';
	errArr[1] = 'The email you entered does not appear to be valid.';
	errArr[2] = 'The email you entered does not appear to be valid.';
	errArr[3] = 'The zip code you entered is not valid.';
	errArr[4] = 'The state you entered is not in an acceptable format.';
	errArr[5] = 'The name you entered is invalid, please do not use any special characters.';
	errArr[6] = 'The date field is not in the proper format.';
	errArr[7] = 'The two comparison values you entered did not match.';
	errArr[8] = 'The the number field may not contain letters or special characters.';

// PSEUDO FORM FUNCTIONS
///////////////////////////////////////////////////////////

function apnd() {
	if (idStr != '') idStr += '|';
	if (errStr != '' && errStr.substr(errStr.length - 1) != '|') errStr += '|';
}

function markTrbl() {
	if (idStr != '') {
		errTripped = true;
		var ta = idStr.split('|');
		for (i = 0; i < ta.length; i++) {
			var x = $(ta[i]).className;
			if (x != '') x += ' ';
			x += 'err';
			$(ta[i]).className = x;
		}
		idStr = '';
		announce();
		errStr = '';
	}
}

function announce() {
	msg ='';
	x = errStr.split('|');
	for (i = 0; i < x.length; i++) {
		if (msg != '') msg += '\n';
		if (x[i] != '' && x[i] != null) msg += errArr[x[i]];
	}
	alert(msg);
}

function clrTrbl() {
	errTripped = false;
	var y = Array('input','select','textarea');
	for (i = 0; i < y.length; i++) {
		var x = $$(y[i]);
		for (a = 0; a < x.length; a++) {
			var n = x[a].className;
			var id = x[a].id;
			if (id == undefined || id == null || id == '') x[a].id = y[i] + a;
			n = n.replace(/err/g, '');
			n = n.replace(/  /g, '');
			x[a].className = n;
		}
	}
}

function getForm(f,d,r,os,ef) {
	clrTrbl();
	var cArr, cont;
	if (os == undefined) os = use_opacity;
	var q = '';
	var iArr = new Array('input','select','textarea');
	for (a = 0; a < iArr.length; a++) {
		cArr = $(f).getElementsByTagName(iArr[a]);
		for (b = 0; b < cArr.length; b++) {
			var field = new getFieldObj(cArr[b]);
			if (field.name != undefined && field.name != '') {
				cont = true;
				validate(cArr[b]);
				if (field.isRadio() || field.isBox()) {
					if (!field.isChecked()) cont = false;
				}
				if (cont) {
					if (q != '') q += '&';
					q += field.name + '=' + noAmp(field.value);
				}
			}
			field = null;
		}
	}
	if (errStr != '') {
		//a problem was detected so we will mark up the form fields and alert the user.
		markTrbl();
		return false;
	} else {
		//good to go - process and send to destination file
		if (os) {
			createScreen();
			if (loadingImg != '') $('opacity_screen').innerHTML = '<img src="'+loadingImg+'" style="margin-top: 150px;" />';
			$('opacity_screen').style.visibility = 'visible';
		}
		
		q = encodeURI(q + '&req=' + Math.random());
		if (d != undefined) {
			var objAjax = new getAjaxObj();
			objAjax.onreadystatechange = function() {
				if (objAjax.readyState == 4) {
					r = (r != undefined ? r : f);
					$(r).innerHTML = objAjax.responseText;
					if (os) $('opacity_screen').style.visibility = 'hidden';
					if (ef != undefined) window[ef]();
				}
			}	
			objAjax.open('POST', d, true);
			objAjax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			objAjax.setRequestHeader('Content-length', q.length);
			objAjax.setRequestHeader('Connection', 'close');
			objAjax.send(q);
		} else {
			if (os) $('opacity_screen').style.visibility = 'hidden';
			return q;
		}
	}
}

function ecode(e) {
	if (e && e.which) {
		e = e;
		return e.which;
	} else {
		e = event;
		return e.keyCode;
	}
}

function ckEnter(e) {
	var c = ecode(e);
	var b = (c == 13) ? true : false;
	return b;
}

function noAmp(i) {
	return i.replace(/&/g, '^^');
}

function getFieldObj(x) {
	this.hasClass = function(c) {
		var cArr = x.className.split(' ');
		for (inc = 0; inc < cArr.length; inc++) {
			if (cArr[inc] == c)
				return true;
		}
	}
	
	this.addListener = function(ev,fn,bit) {
		if (x.addEventListener)
			x.addEventListener(ev,fn,bit);
	}
	
	this.isRadio = function() {
		return (x.type == 'radio') ? true : false;
	}
	
	this.isBox = function() {
		return (x.type == 'checkbox') ? true : false;
	}
	
	this.isChecked = function() {
		return (x.checked) ? true : false;
	}
	
	this.id = x.id;
	this.value = x.value;
	this.name = x.name;

}

function validate(x) {
	if (x.className != '') {
		var field = new getFieldObj(x);
		
		//Check for required field
		if (field.hasClass('req')) {
			var prob = false;
			if (field.isRadio() || field.isBox()) {
				if (!field.isChecked()) prob = true;
			}
			if (field.value == '') prob = true;
			if (prob) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(0) == -1)
					errStr += 0;
			}
		}
		//Regex for Email
		if (field.hasClass('vemail')) {
			var Regex =/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(1) == -1)
					errStr += 1;
			}
		}
		//Regex for Phone
		if (field.hasClass('vphone')) {
			var Regex = /^\(?[2-9]\d{2}[ \-\)] ?\d{3}[\- ]?\d{4}$/;
			var Regex2 = /^[2-9]\d{9}$/;
			if ((!Regex.test(field.value))&&(!Regex2.text(field.value))) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(2) == -1)
					errStr += 2;
			}
		}
		//Check for U.S. 5 digit zip code
		if (field.hasClass('vzip')) {
			var Regex = /^\d{5}$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(3) == -1)
					errStr += 3;
			}
		}
		//Check for state
		if (field.hasClass('vstate')) {
			var Regex = /^[a-zA-Z]{2}$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(4) == -1)
					errStr += 4;
			}
		}
		//Check for name	
		if (field.hasClass('vname')) {
			var Regex = /^[a-zA-Z\ ']*$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(5) == -1)
					errStr += 5;
			}
		}
		//Check for date
		if (field.hasClass('vdate')) {
			var Regex = /^([\d]|1[0,1,2]|0[1-9])(\-|\/|\.)([0-9]|[0,1,2][0-9]|3[0,1])(\-|\/|\.)\d{4}$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(6) == -1)
					errStr += 6;
			}
		}
		//Check for a field match
		if (field.hasClass('vmatch')) {
			if (field.value != $('match'+field.id).value) {
				apnd();
				idStr += field.id + '|match' + field.id;
				if (errStr.indexOf(7) == -1)
					errStr += 7;
			}
		}
		//Check for only an integer value - no length limit
		if (field.hasClass('vint')) {
			var Regex = /^\d$/;
			if (!Regex.test(field.value)) {
				apnd();
				idStr += field.id;
				if (errStr.indexOf(8) == -1)
					errStr += 8;
			}
		}
		
		field = null;

	}
}

// COMMON FUNCTIONS
///////////////////////////////////////////////////////////

function toggle(i) {
	var c = $(i).className;
	if (c.indexOf('hide') > -1) {
		c = c.replace(/hide/g, '');
		c = c.replace(/  /g, '');
	} else {
		if (c.length > 0)
			c += ' ';
		c += 'hide';
	}
	$(i).className = c;
}

function sel(x) {
	x.focus();
	x.select();
}

function toNext(e) {
	var x = e.target;
	var maxLen = x.getAttribute("maxlength");
	var cCode;
	var ccode = ecode(e);
	// ensure edits can be made by way of deletion
	if (x.value.length == maxLen && ccode != 8 && ccode != 46) {
		var b = $$('body')[0];
		var a = b.getElementsByTagName('input');
		for (i = 0; i < a.length; i++) {
			if (a[i].id == x.id) {
				sel(a[i+1]);
				break;
			}
		}
	}
}

// SCREEN OVERLAY / POPUP GENERATOR / AND LOADING GRAPHIC
///////////////////////////////////////////////////////////

function getPageSize() {	
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

function toTop() {
	window.scrollTo(0,0);
}

function getElementSize(i) {
	var eWidth = $(i).offsetWidth;
	var eHeight = $(i).offsetHeight;
	return [eWidth,eHeight];
}

function createScreen() {
	if (!$('opacity_screen')) {
		var oBody = $$('body')[0];
		var x = document.createElement('div');
		var dims = getPageSize();
		x.style.height = dims[1] + 'px';
		x.style.width = dims[0] + 'px';
		x.setAttribute('id','opacity_screen');
		oBody.appendChild(x);
	}
}

function createPopup() {
	if (!$('popup')) {
		var oBody = $$('body')[0];
		var x = document.createElement('div');
		var dims = getPageSize();
		x.setAttribute('style','position: absolute; top: 0; left: 0; display: none;');
		x.setAttribute('id','popup');
		oBody.appendChild(x);
	}
}

function killPopup() {
	$('popup').style.display = 'none';
	$('opacity_screen').style.display = 'none';
}

// ONLOAD HANDLER
///////////////////////////////////////////////////////////

function enableFunctions() {
	var b = $$('body')[0];
	var a = b.getElementsByTagName('input');
	for (i = 0; i < a.length; i++) {
		var field = new getFieldObj(a[i]);
		// toNext Function
		if (field.hasClass('toNext')) {
			if (field.id == null || field.id == undefined || field.id == '') a[i].id = 'next' + i;
			field.addListener('keyup',toNext,false);
			field.addListener('keydown',toNext,false);
		}
	}
}

var on_load = window.onload;
window.onload = function() {
	if (typeof(on_load) == 'function') on_load();
	// add new onload functions here
	enableFunctions();
}