/**********************************************************
*  PA Global JavaScript Document                         *
*  Web       :  #js         *
*  E-mail    :  chad@secureindia.com                  *
*  Modified  :  13-Jul-2006                              *
**********************************************************/


/* Opens a New Window with file, name, sizes, scrolling
************************************************/
function customNewWin(file, name, h, w, scroll){
	var properties = '';
	properties += 'height=' + h + ',' + 'width=' + w + ',' + 'scrollbars=' + scroll + ',' + 'toolbar=no,resizable=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=100,top=100,screenX=100,screenY=100';
	properties = properties.substring(0,properties.length-1);
	//alert(properties);
	window.open(file, name, properties);
}

/* Opens a New Window class="external"
************************************************/
addEvent(window, 'load', externalLinks);


function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if(anchor.className.indexOf('external') != -1)
		//if (anchor.getAttribute("href") &&
		//    anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
		//alert(anchor.title + " " + anchor.target);
	}
}

/* Gets Labels by input ID.
************************************************/
function  getLabelForId(id) {
	var label, labels = document.getElementsByTagName('label');
	for (var i = 0; (label = labels[i]); i++) {
		if (label.htmlFor == id) {
			return label;
		}
	}
	return false;
}

/* START Validation Functions
************************************************/
function checkEmail(id) {
	var email;
	if(email = document.getElementById(id)) {
		var label = getLabelForId(id);
		//if (email.value.indexOf('@') == -1 || email.value.length < 5 ) { // Naive check for non empty string with @ sign
		if(!email.value.match(/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/)) {
			email.style.backgroundColor='#FFFFBF';
			label.className += ' problem';
			return false;
		} else {
			email.style.backgroundColor='white';
			label.className = label.className.replace(/problem/,'');
			return true;
		}
	} else {
		return true;
	}
}

function checkPhone(id) {
	var phone;
	if(phone = document.getElementById(id)) {
		var label = getLabelForId(id);
		var digits = phone.value.replace(/[^0-9]/ig, '');
		if (!digits) {
			phone.style.backgroundColor='#FFFFBF';
			label.className += ' problem';
			phone.value = '';
			return false;
		}
		if (digits.length == 10) {
			phone.value = '(' + digits.substring(0, 3) + ') ' +
			digits.substring(3, 6) + '-' +
			digits.substring(6, 10);
			label.className = label.className.replace(/problem/g, '');
			phone.style.backgroundColor='white';
			return true;
		} else {
			phone.style.backgroundColor='#FFFFBF';
			label.className += ' problem';
			phone.value = digits;
			return false;
		}
	} else {
		return true;
	}
}

function checkPhoneNotRequired(id) {
	var phone;
	if(phone = document.getElementById(id)) {
		var label = getLabelForId(id);
		var digits = phone.value.replace(/[^0-9]/ig,'');
		if(digits) {
			if(digits.length == 10) {
				phone.value = '(' + digits.substring(0, 3) + ') ' +
				digits.substring(3, 6) + '-' +
				digits.substring(6, 10);
				label.className = label.className.replace(/problem/g, '');
				phone.style.backgroundColor='white';
				return true;
			} else {
				phone.style.backgroundColor='#FFFFBF';
				label.className += ' problem';
				phone.value = digits;
				return false;
			}
		} else {
			phone.value = '';
		}
	} else {
		return true;
	}
}

function checkRequired(id) {
	var formfield;
	if(formfield = document.getElementById(id)){
		var label = getLabelForId(id);
		if(formfield) {
			if ((formfield.value.length == 0) || (formfield.selectedIndex == 0)) {
				formfield.style.backgroundColor='#FFFFBF';
				label.className += ' problem';
				return false;
			} else {
				formfield.style.backgroundColor='white';
				label.className = label.className.replace(/problem/, '');
				return true;
			}
		}
	} else {
		return true;
	}
}

function checkCheckBoxes(id) {
	var formfield = document.getElementById(id);
	var label = getLabelForId(id);
	if (formfield.checked == false) {
		formfield.style.backgroundColor='pink';
		label.className = 'problem';
		return false;
	} else {
		formfield.style.backgroundColor='white';
		label.className = '';
		return true;
	}
}

function checkSSN(id) {
	var ssn;
	if(ssn = document.getElementById(id)) {
		var label = getLabelForId(id);
		var digits = ssn.value.replace(/[^0-9]/ig, '');
		if (!digits) {
			ssn.style.backgroundColor='#FFFFBF';
			label.className = 'problem';
			ssn.value = '';
			return false;
		}
		if (digits.length == 9) {
			ssn.value = digits.substring(0, 3) + '-' +
			digits.substring(3, 5) + '-' +
			digits.substring(5, 9);
			label.className = '';
			ssn.style.backgroundColor='white';
			return true;
		} else {
			ssn.style.backgroundColor='#FFFFBF';
			label.className = 'problem';
			ssn.value = digits;
			return false;
		}
	} else {
		return true;
	}
}

/* END Validation Functions
************************************************/

//  Blur and Focus Colors.
addEvent(window, 'load', function() {
	var input;
	var inputs = document.getElementsByTagName('input');
	for (var i = 0; (input = inputs[i]); i++) {
		if(input.type!="checkbox" && input.type!="radio") {
			addEvent(input, 'focus', oninputfocus);
			addEvent(input, 'blur', oninputblur);
		}
	}
	var textareas = document.getElementsByTagName('textarea');
	for (var i = 0; (textarea = textareas[i]); i++) {
		addEvent(textarea, 'focus', oninputfocus);
		addEvent(textarea, 'blur', oninputblur);
	}
});

function oninputfocus(e) {
	/* Cookie-cutter code to find the source of the event */
	if (typeof e == 'undefined') {
		var e = window.event;
	}
	var source;
	if (typeof e.target != 'undefined') {
		source = e.target;
	} else if (typeof e.srcElement != 'undefined') {
		source = e.srcElement;
	} else {
		return;
	}
	/* End cookie-cutter code */
	source.style.border ='1px solid #000';
}
function oninputblur(e) {
	/* Cookie-cutter code to find the source of the event */
	if (typeof e == 'undefined') {
		var e = window.event;
	}
	var source;
	if (typeof e.target != 'undefined') {
		source = e.target;
	} else if (typeof e.srcElement != 'undefined') {
		source = e.srcElement;
	} else {
		return;
	}
	/* End cookie-cutter code */
	source.style.border ='1px solid #999';
}
function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

$(document).ready(hookInputsForEnter);

function hookInputsForEnter() {
	try {
		$("form").each(function(x) {
			var form = this;
			//alert("found form "+form.action);
			$("div",this).each(function(y) {
				//if(this.className.indexOf("button_")>=0) alert("found div with classname of "+this.className+" indexof test: "+this.className.indexOf("button_"));
				if(this.className.indexOf("button_")>=0) {
					var anchor = $("a",this).get(0);
					if(anchor && anchor.href) {
						//alert('hooking '+this.id+' to action '+anchor.href);
						$("input",form).each(function(z) {
							this.action = anchor.href;
							$(this).keypress(function(key) {
								if((key.which == 13) || key.keyCode == 13) {
									eval(this.action);
								}
							});
						});
					}
				}
			});
		});
	} catch(e) {
		//
	}
}

function log(msg, bold) {
	if(ele = document.getElementById('test')) {
		if(bold) {
			msg = "<B>" + msg + "</B>";
		}
		ele.innerHTML += "<PRE>"+msg+"</PRE>";
	}
}

//Creates the indexOf prototype function for the Array object if it doesn't exist (mainly for use in IE, ff supports array.indexOf)
if(!Array.indexOf) {
	Array.prototype.indexOf = function(v) {
		for(var i = 0; i < this.length; ++i) {
			if(this[i] && this[i] == v) return i;
			return -1;
		}
	};
}

//Creates the Array.foreach prototype, allowing you to iterate through each item in an array
if(!Array.foreach) {
	Array.prototype.foreach = function(func) {
		var len = this.length;
		for(var i = 0; i < len; i++) {
			var result;
			if((result = func(this[i],i)) !== undefined) return result;
		}
	}
}


function gID(s) {
	var e;
	return (e=document.getElementById(s))?e:false;
}

function autoScrollTo() {
	var query = getQueryHash();

	if(query.items['goto']) {

		var id = query.items['goto'];

		var item = document.getElementById(id);

		var x = y = 0;

		while(item != null) {
			x += item.offsetLeft;
			y += item.offsetTop;
			item = item.offsetParent;
		}

		this.scrollTo(x,y);

	}

}

function getQueryHash() {
	var query = document.location.search;
	query = query.substring(1,query.length);

	var opts = query.split("&");

	var hash = new Hash();

	for(var x=0;x < opts.length;x++) {
		var opt = opts[x].split("=");
		var key = opt[0];
		var val = opt[1];
		hash.setItem(key, val);
	}

	return hash;

}

function Hash() {
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}

	this.removeItem = function(in_key) {
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}

		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value) {
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}

		return in_value;
	}

	this.hasItem = function(in_key)	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function debugLog(msg) {
	if(!document.timeStamps) document.timeStamps = [];
	if(!document.timeStampts[msg]) startbench(msg);
}

function startbench( what ) {
	if( !document.timeStamps ) document.timeStamps = []
	if( !document.timeStamps[ what ] ) document.timeStamps[ what ] = [ 0, 0, 0, 0 ]
	document.timeStamps[ what ][ 0 ] -= (new Date()).valueOf()+0*(document.timeStamps[ what ][ 3 ]=1)
}

function stopbench( what ){
	return ( !document.timeStamps || 
			 !document.timeStamps[ what ]  || 
			 !document.timeStamps[ what ][3] )?
			 	-1
			 	:document.timeStamps[ what ][ 2 ] = Math.round( 100*(document.timeStamps[ what ][ 0 ] += (new Date()).valueOf() ) / ++document.timeStamps[ what ][ 1 ] )/100+(document.timeStamps[ what ][ 3 ]=0)
}

function get_form() {
	if(window.location.pathname && window.location.pathname.indexOf('agreement') > -1) {
		if(document.forms.oa_form) return document.forms.oa_form;
	} else {
		if(document.forms.oo_form) return document.forms.oo_form;
	}
	return false;
}

function focusfield(id) {
	$("#"+id).focus();
}

//create a ucwords method for string objects similar to PHPs ucwords function
if(!String.ucWords) {
	String.prototype.ucWords = function() {
		//take the string, explode it by spaces, then capitalize the first letter of each word
		var words = this.toLowerCase().split(" ");
		var word;
		for(var i = 0; i < words.length; i++) {
			word = words[i];
			//for each word, capitilize the first letter..
			words[i] = word.substring(0,1).toUpperCase() + word.substring(1,word.length);
		}
		return words.join(" ");
	}
}

if(!String.trim) {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/, '');
	}
}

if(!String.ltrim) {
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/, '');
	}
}

if(!String.rtrim) {
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/, '');
	}
}

function getMultipleSelect(sel) {
	var res = new Array();
	var reselect = new Array();
	
	while (sel.selectedIndex != -1) { 
		reselect.push(sel.selectedIndex);
		res.push(sel.options[sel.selectedIndex]);
		sel.options[sel.selectedIndex].selected = false; 
	}
	
	//the script has to deselect the selected items in order to traverse through the list, so now we reselect them
	for(var i = 0; i < reselect.length; i++) {
		sel.options[reselect[i]].selected = true;
	}
	
	return res;
}

var _JSPATH = "http://"+window.location.hostname+"/landing/";

function includeJS(js) {

	var head = document.getElementsByTagName("head")[0];
	var frag = document.createDocumentFragment();

	var scr = document.createElement("script");
	scr.setAttribute("type","text/javascript");
	scr.setAttribute("src",_JSPATH+"js/"+js);
	frag.appendChild(scr);

	head.appendChild(frag);

}