
function getAddress(name) {
	return document.inputForm.elements[name];
}

function markInvalid(field) {
    if(field.type && field.type.search(/select/i) < 0){
        field.style.border = "solid #b52e24 2px";
        field.style.backgroundColor = "#f9f4d3";
    }else{
        markInvalidSelect(field);
    }
}

function markValid(field) {
	if (field)
	{
	    if(field.type && field.type.search(/select/i) < 0){
		field.style.border = "1px solid #CCCCCC";
		field.style.backgroundColor = "#ffffff";
	    }else{
	        markValidSelect(field);
	    }
	}
}

function markInvalidSelect(field) {
    var spanField = document.getElementById(field.name+".div");
    if(spanField){
        spanField.style.border = "solid #b52e24 2px";
    }else{
        field.style.border = "solid #b52e24 2px";
    }
    field.style.backgroundColor = "#f9f4d3";
}

function markValidSelect(field) {
    if (field)
    {
        var spanField = document.getElementById(field.name+".div");
        if(spanField){
            spanField.style.border = "0px solid #CCCCCC";
        }else{
            field.style.border = "1px solid #CCCCCC";
        }
        field.style.backgroundColor = "#ffffff";
    }
}

function showMessage(id) {
	if(document.getElementById(id) != null)
		document.getElementById(id).style.display = "block";
}

function hideMessage(id) {
	if(document.getElementById(id) != null)
		document.getElementById(id).style.display = "none";
}

function toggleMessage(id) {
	if(document.getElementById(id) != null) {
		if(document.getElementById(id).style.display == "block") {
			document.getElementById(id).style.display = "none";
		}
		else {
			document.getElementById(id).style.display = "block";
		}
	}
}

function checkLogin()
{
	var allOk = true;
	hideMessage('fieldsMissing');
	
	var checkFields = new Array('orderData.lastName', 'orderData.zipCode', 'orderData.orderId');
	return markFieldsAsMissing(checkFields, true);
	
}

function checkAddressInformation(alsoCheckPassword) {
	var allOk = true;
	// remove all "errors"
	
	hideMessage('invalidName');
	hideMessage('invalidAddress');
	hideMessage('fieldsMissing');
	hideMessage('invalidEmail');
	hideMessage('passwordRules');
	hideMessage('emailNotEquals');
	hideMessage('invalidZip');
	hideMessage('passwordsNotEqual');
	hideMessage('invalidPhone');
	hideMessage('passwordNotConfirm');
	
	markValid(getAddress('ap1'));
	markValid(getAddress('ap2'));
	markValid(getAddress('ap3'));
	markValid(getAddress('profileData.email'));
	markValid(getAddress('profileData.loginName'));
	markValid(getAddress('profileData.loginName2'));

	var checkFields = new Array('profileData.loginName', 'profileData.password', 'profileData.password2',
			'profileData.firstName', 'profileData.lastName', 'pp1', 'pp2', 'pp3', 
			'email1_changeUserProfile', 'email2_changeUserProfile',
			'billingAddress.address_1', 'billingAddress.city', 'billingAddress.zipCode','billingAddress.state',
			'serviceAddress.address_1', 'serviceAddress.city', 'serviceAddress.zipCode', 'serviceAddress.state',
			'profileDate.firstName', 'profileData.lastName');
	allOk = markFieldsAsMissing(checkFields);
		
	if (alsoCheckPassword) 	{
		var pwf = getAddress('profileData.password');
		if (pwf) {
			firstName = getAddress("profileData.firstName");
			lastName = getAddress("profileData.lastName");
			loginName = getAddress("email");
			if (pwf.value != '') {
				if (checkPassword(pwf) == false) {
					markInvalid(pwf);
					showMessage('passwordRules');
					allOk = false;
				} else if (pwf.value == firstName.value && firstName.value.length != 0) {
					markInvalid(pwf);
					showMessage('passwordRules');
					allOk = false;
				} else if (pwf.value == lastName.value && lastName.value.length != 0) {
					markInvalid(pwf);
					showMessage('passwordRules');
					allOk = false;
				} else if (pwf.value == loginName.value && loginName.value.length != 0) {
					markInvalid(pwf);
					showMessage('passwordRules');
					allOk = false;
				} 
				
				if (pwf.value != getAddress('profileData.password2').value) {
					markInvalid(pwf);
					markInvalid(getAddress('profileData.password2'));
					showMessage('passwordsNotEqual');
					allOk = false;
				}
			}
		}
	}
	
	var emailFilter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	
	// now check for validity
	if (getAddress('profileData.email')) {
		if (getAddress('profileData.email').value != '') {
			if (! emailFilter.test(getAddress('profileData.email').value)) {
				markInvalid(getAddress('profileData.email'));
				showMessage('invalidEmail');
				allOk = false;
			} 
		}
	}
	
	if (getAddress('profileData.email2')) {
		if (getAddress('profileData.email').value !=
			getAddress('profileData.email2').value) {
			markInvalid(getAddress('profileData.email'));
			showMessage('emailNotEquals');
			allOk = false;
		}	
	}
	//check also Login Name
	if (getAddress('profileData.loginName')) {
		if (getAddress('profileData.loginName').value != '') {
			if (! emailFilter.test(getAddress('profileData.loginName').value)) {
				markInvalid(getAddress('profileData.loginName'));
				showMessage('invalidEmail');
				allOk = false;
			}
			else
			if (getAddress('profileData.loginName').value != 
				getAddress('profileData.loginName2').value) {
				markInvalid(getAddress('profileData.loginName'));
				markInvalid(getAddress('profileData.loginName2'));
				showMessage('emailNotEquals');
				allOk = false;
			}
		}
	}
	
	//check real name
	var nameFilter = /^[^0-9]+$/i;
	if (getAddress('profileData.firstName')) {
		if (getAddress('profileData.firstName').value != '') {
			if (! nameFilter.test(getAddress('profileData.firstName').value)) {
				markInvalid(getAddress('profileData.firstName'));
				showMessage('invalidName');
				allOk = false;
			}
		}
	}
	if (getAddress('profileData.lastName')) {
		if (getAddress('profileData.lastName').value != '') {
			if (! nameFilter.test(getAddress('profileData.lastName').value)) {
				markInvalid(getAddress('profileData.lastName'));
				showMessage('invalidName');
				allOk = false;
			}
		}
	}

	//check zip code
	var zipFilter = /^[0-9][0-9][0-9][0-9][0-9]$/i;
	if (! zipFilter.test(getAddress('billingAddress.zipCode').value)) {
		markInvalid(getAddress('billingAddress.zipCode'));
		if (getAddress('billingAddress.zipCode').value.length > 0)
			showMessage('invalidZip');
		allOk = false;
	}

	if (! zipFilter.test(getAddress('serviceAddress.zipCode').value)) {
		markInvalid(getAddress('serviceAddress.zipCode'));
		if (getAddress('serviceAddress.zipCode').value.length > 0)
			showMessage('invalidZip');
		allOk = false;
	}
	
	// check phone number
	var phoneFilter = /^[0-9]+$/i;
	if (! phoneFilter.test(getAddress('pp1').value) || ! phoneFilter.test(getAddress('pp2').value) || ! phoneFilter.test(getAddress('pp3').value) ||
		getAddress('pp1').value.length < 3 || getAddress('pp2').value.length < 3 || getAddress('pp3').value.length < 4 ||
		(getAddress('pp1').value == '000' && getAddress('pp2').value == '000' && getAddress('pp3').value == '0000') ||
		(getAddress('pp1').value == '999' && getAddress('pp2').value == '999' && getAddress('pp3').value == '9999')
	) {
		markInvalid(getAddress('pp1'));
		markInvalid(getAddress('pp2'));
		markInvalid(getAddress('pp3'));
		showMessage('invalidPhone');
		allOk = false;
	} 
	
	// no message for this - you would need an extra one for this optional field
	if (getAddress('ap1').value.length != 0 || getAddress('ap2').value.length != 0 || getAddress('ap3').value.length != 0)
	{
		if (! phoneFilter.test(getAddress('ap1').value) || ! phoneFilter.test(getAddress('ap2').value) || ! phoneFilter.test(getAddress('ap3').value) ||
			getAddress('ap1').value.length < 3 || getAddress('ap2').value.length < 3 || getAddress('ap3').value.length < 4 ||
			(getAddress('ap1').value == '000' && getAddress('ap2').value == '000' && getAddress('ap3').value == '0000') ||
			(getAddress('ap1').value == '999' && getAddress('ap2').value == '999' && getAddress('ap3').value == '9999') ) 
		{
			markInvalid(getAddress('ap1'));
			markInvalid(getAddress('ap2'));
			markInvalid(getAddress('ap3'));
			showMessage('invalidPhone');
			allOk = false;
		}
	}
	
	// Service address
	var tmp = getAddress('serviceAddress.address_1').value.toUpperCase();
	// remove space, . and dash
	tmp = tmp.replace(/[ .-]/g, '');
	
	if (tmp.indexOf('POBOX') != -1) {
		markInvalid(getAddress('serviceAddress.address_1'));
		showMessage('invalidAddress');
		allOk = false;
	}

	// Service address
	var tmp = getAddress('serviceAddress.address_2').value.toUpperCase();
	// remove space, . and dash
	tmp = tmp.replace(/[ .-]/g, '');
	
	if (tmp.indexOf('POBOX') != -1) {
		markInvalid(getAddress('serviceAddress.address_2'));
		showMessage('invalidAddress');
		allOk = false;
	}
            
            checkSetDuplicateAddress();
	// enable all fields to actually submit them
	if (allOk) {
		duplicateAddress(false);
	}	

	return allOk;
}

function doCheckPWD() {
	var allOk = true;
	hideMessage('webServiceError');
	hideMessage('passwordsNotEqual');
	hideMessage('fieldsMissing');
	hideMessage('passwordRules');

	allOk = markFieldsAsMissing(new Array("oldPassword", "newPassword", "newPassword2"));
	
	var pwd = getAddress("newPassword");
	if (checkPassword(pwd) == false) {
		markInvalid(pwd);
		showMessage('passwordRules');
		allOk = false;
	}

	var pwd2 = getAddress("newPassword2");
	if (pwd.value != pwd2.value) {
		markInvalid(pwd);
		markInvalid(pwd2);
		showMessage('passwordsNotEqual');
		allOk = false;
	}
	
	return allOk;
}

/*
 * Marks empty fields as missing and non-empty fields as valid
 * @param chcekFields an arraylist of field name to check
 * @param doTrim if true, all field values are being trimmed before checking
 */
function markFieldsAsMissing(checkFields, doTrim) {
	var allOk = true;
	for (var i = 0; i < checkFields.length; i++) {
		var field = getAddress(checkFields[i]);
		if (! field)
			continue;
		if (doTrim)
			field.value = trim(field.value); 
		if (field.value.length == 0) {
			markInvalid(field);
			showMessage('fieldsMissing');
			allOk = false;
		} else {
			markValid(field);
		}
	}
	return allOk;
}

/*
 * Checks the password itself
 * 
 * Note: no comparision to other fields
 */
function checkPassword(pwd) {
	if (pwd.value.length < 8) {
		return false;
	} else if  (pwd.value.length > 16 ){
		return false;
	} else if (pwd.value == "password") {
		return false;
	} else if (pwd.value.match(" ") != null) {
		return false;
	} else {
		return true;
	}	
}

function priceOnly(element) {
	var val = element.value;
	var part = val.match('[0-9]{0,4}(\\.[0-9]{0,2})?');
	element.value = part[0];
}

function digitsOnly(element) {
	var val = element.value;
	var pattern = new RegExp('[^0-9]+', 'g');
	val = val.replace(pattern, '');
	element.value = val;
}

function autoTab(ele, next, e) {
	var val = ele.value;
	var pattern = new RegExp('[^0-9]+', 'g');
	val = val.replace(pattern, '');
	ele.value = val;
	if (ele.value.length == ele.getAttribute("maxlength") &&
	e.KeyCode != 8 && e.keyCode != 16 && e.keyCode != 9) {
		try {
			if (next != null)
				document.getElementById(next).focus();
		}
		catch (ex) {
		}
	}
}

function checkSetDuplicateAddress() {
	var checkFields = new Array(
	'address_1', 'address_2', 'city', 'state', 'zipCode');
	
	var isSame = true;
	for (i = 0; i < checkFields.length; i++) {
		if (getAddress("serviceAddress." + checkFields[i]).value != getAddress("billingAddress." + checkFields[i]).value) {
			isSame = false;
			break;
		}
	}
	
	if (isSame == true && getAddress("billingAddress.address_1").value != '') {
		document.getElementById("sameAddress").checked = true;
		duplicateAddress(true);
	}
}

var isDuplicateAddress = false;

function duplicateAddress(doDuplicate) {
	isDuplicateAddress = doDuplicate;
		
	// copy all billing fields -> service fields and enable/disable them
	var checkFields = new Array(
	'address_1', 'address_2', 'city', 'state', 'zipCode');
	var i;
	if (isDuplicateAddress == false) {
		for (i = 0; i < checkFields.length; i++) {
			var f = getAddress("serviceAddress." + checkFields[i]);
			f.disabled = false;
			f.style.background = "#fff";
		}
		return;
	}
	
	for (i = 0; i < checkFields.length; i++) {
		var f = getAddress("serviceAddress." + checkFields[i]);
		copyValue(getAddress("billingAddress." + checkFields[i]).value, "serviceAddress." + checkFields[i]);
		f.disabled = true;
		f.style.background = "#eeeeee";
	}
}

function copyValue(val, toField) {
	if (isDuplicateAddress)
	getAddress(toField).value = val;
}

/**
* checks a given string for a valid credit card
* @returns:
*  	-1	invalid
*	 	1	mastercard
*		2	visa
*		3	amex
*		4	diners club
*		5	discover
*		6	enRoute
*		7	jcb
*/
function checkCC(val) {
	String.prototype.startsWith = function (str) {
		return (this.match("^" + str) == str)
	}
	
	Array.prototype.has=function(v,i){
		for (var j=0;j<this.length;j++){
			if (this[j]==v) return (!i ? true : j);
		}
		return false;
	}
	
	// get rid of all non-numbers (space etc)
	val = val.replace(/[^0-9]/g, "");
	
	// now get digits
	var d = new Array();
	var a = 0;
	var len = 0;
	var cval = val;
	while (cval != 0) {
		d[a] = cval%10;
		cval -= d[a];
		cval /= 10;
		a++;
		len++;
	}
	
	if (len < 13)
		return -1;
	
	var cType = -1;
	
	// mastercard
	if (val.startsWith("5")) {
		if (len != 16)
			return -1;
		cType = 1;
	} else
	// visa
	if (val.startsWith("4")) {
		if (len != 16 && len != 13)
			return -1;
		cType = 2;
	} else
	// amex
	if (val.startsWith("34") || val.startsWith("37")) {
		if (len != 15)
			return -1;
		cType = 3;
	} else
	// diners
	if (val.startsWith("36") || val.startsWith("38") || val.startsWith("300") || val.startsWith("301") || val.startsWith("302") || val.startsWith("303") || val.startsWith("304") || val.startsWith("305")) {
		if (len != 14)
		return -1;
		cType = 4;
	} else
	// discover
	if (val.startsWith("6011")) {
		if (len != 15 && len != 16)
			return -1;
		cType = 5;
	} else
	// enRoute
	if (val.startsWith("2014") || val.startsWith("2149")) {
		if (len != 15 && len != 16)
			return -1;
		// any digit check
		return 6;
	} else
	// jcb
	if (val.startsWith("3")) {
		if (len != 16)
		return -1;
		cType = 7;
	} else
	// jcb
	if (val.startsWith("2131") || val.startsWith("1800")) {											

		if (len != 15)
		return -1;
		cType = 7;
	} else
	return - 1;
	// invalid cc company
	
	// ignore calculation for "test"-cc #
	if ([4455010000000000,4446661234567890,5233272716340010,5499974444444440,
		6011000993069240,6011031100333330,378282246311005].has(val))
		return cType;
	
	// lets do some calculation
	var sum = 0;
	var i;
	for (i = 1; i < len; i += 2) {
		var s = d[i] * 2;
		sum += s % 10;
		sum += (s - s%10) /10;
	}
	
	for (i = 0; i < len; i += 2)
		sum += d[i];
	
	// musst be %10
	if (sum%10 != 0)
		return - 1;
	
	return cType;
}


function doCheckCC() {
	var number = document.getElementById("cardNumber").value;
	var type = document.getElementById("cardType").value;
	var allOk = true;
	
	if (type == 'VISA') type = 2; 
	else if (type == 'MasterCard') type = 1; 
	else if (type == 'Discover') type = 5; 
	else if (type == 'AMEX') type = 3; 
	else {
		markInvalid(document.getElementById('cardNumber'));
		showMessage('invalidCC');
		allOk = false;
	}
	
	if (checkCC(number) != type) {
		markInvalid(document.getElementById('cardNumber'));
		showMessage('invalidCC');
		allOk = false;
	} else {
		markValid(document.getElementById('cardNumber'));
		hideMessage('invalidCC');
		document.getElementById("cardNumber").value = number.replace(/[^0-9]/g, "");
	}
	
	if (document.getElementById("cardName").value.length == 0) {
		markInvalid(document.getElementById("cardName"));
		showMessage('nameMissing');
		allOk = false;
	} else {
		markValid(document.getElementById("cardName"));
		hideMessage('nameMissing');
	}
	
	if (document.getElementById("cvnField") != null) {
		if (document.getElementById("cvnField").value.length == 0) {
			markInvalid(document.getElementById("cvnField"));
			showMessage('cvnMissing');
			allOk = false;
		} else {
			markValid(document.getElementById("cvnField"));
			hideMessage('cvnMissing');
		}
	}
	
	// check expiration date
	var cYear = new Date().getYear();
	if (cYear < 1900)
		cYear += 1900;
	if (document.getElementById("ccMonth").value < (new Date().getMonth() + 1) &&
	document.getElementById("ccYear").value <= cYear) {
		markInvalid(document.getElementById("ccMonth"));
		markInvalid(document.getElementById("ccYear"));
		showMessage('invalidExpiration');
		allOk = false;
	} else {
		markValid(document.getElementById("ccMonth"));
		markValid(document.getElementById("ccYear"));
		hideMessage('invalidExpiration');
	}
	
	return allOk;
}

function doCheckOptionalCC(){
    //clear
    markValid(document.getElementById('cardNumber'));
    hideMessage('invalidCC');
    markValid(document.getElementById("cardName"));
    hideMessage('nameMissing');
    markValid(document.getElementById("ccMonth"));
    markValid(document.getElementById("ccYear"));
    hideMessage('invalidExpiration');
 
    document.getElementById("expiration").value =  document.getElementById("ccYear").value+"-"+document.getElementById("ccMonth").value;
    if(document.getElementById("cardName").value.length != 0 || document.getElementById("cardNumber").value.length != 0){
       if (doCheckCC()) return true;
       checkSetDuplicateAddress();
       return false;
   }else{
        document.getElementById("cardType").disabled = true;
        document.getElementById("cardName").disabled = true;
        document.getElementById("cardNumber").disabled = true;
        document.getElementById("expiration").disabled = true;
        return true;
    }
}

function doCheckOrderNow() {
	var cvnField = document.getElementById("cvnField");
	var allOk = true;

	hideMessage('invalidTosBox');
	markValid(document.getElementById("tosBoxDiv"));
	hideMessage('invalidCvnField');
	markValid(cvnField);
	hideMessage('invalidVerifyBox');
	markValid(document.getElementById("verifyBoxDiv"));

	
	if(document.getElementById("tosBox").checked == false) {
		showMessage('invalidTosBox');
		markInvalid(document.getElementById("tosBoxDiv"));
		allOk = false;
	} 

	// check if verify exists
	if(document.getElementById("verifyBox") && document.getElementById("verifyBox").checked == false) {
		showMessage('invalidVerifyBox');
		markInvalid(document.getElementById("verifyBoxDiv"));
		allOk = false;
	} 
	
	// cvn is available
	if(cvnField && cvnField.value.length < 3 || cvnField.value.length > 4) {
		showMessage('invalidCvnField');
		markInvalid(cvnField);
		allOk = false;
	} 

	// Prevent Double order click
	if(allOk && document.getElementById('order_now_button')) {
		document.getElementById('order_now_button').disabled=true;
	}

	return allOk;
}

function selectAddresses() {	
	billingAddrElem = document.getElementById("billingAddressState");
	selectedBillingAddr = document.getElementById("selectedBillingAddressState");
	if(billingAddrElem != null && selectedBillingAddr != null) {
		for(i=0; i< billingAddrElem.length; i++) {
			if(billingAddrElem.options[i].value==selectedBillingAddr.innerHTML)
				billingAddrElem.selectedIndex=i;
		}
	}

	serviceAddrElem = document.getElementById("serviceAddressState");
	selectedServiceAddr = document.getElementById("selectedServiceAddressState");
	if(billingAddrElem != null && selectedServiceAddr != null) {
		for(i=0; i< serviceAddrElem.length; i++) {
			if(serviceAddrElem.options[i].value==selectedServiceAddr.innerHTML)
				serviceAddrElem.selectedIndex=i;
		}
	}
}

function checkLength(elementId, min, max, errorId, otherErrorId) {
	element = document.getElementById(elementId);
	markValid(element);
	hideMessage(errorId);
	eleLength = element.value.length;
	if(eleLength >= min && eleLength <= max) {
		return true;
	} 
	else {
		markInvalid(element);
		if(document.getElementById(otherErrorId) != null) {
			hideMessage(otherErrorId);
		}
		showMessage(errorId);
		return false;
	}
}

// Simulates PHP's date function from http://jacwright.com/projects/javascript/date_format
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replace.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replace.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replace.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replace.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function fixOrderField (name)
{
	document.inputFormOrderDataSearch.elements[name].value = trim(document.inputFormOrderDataSearch.elements[name].value); 
}
function fixOrderDataForm()
{
	fixOrderField ('phone');
	fixOrderField ('orderId');
	fixOrderField ('zipCode');
	fixOrderField ('lastName');
	return true;
}

//Timeout fuctions

//Global variables used in timeout functions
var errorTime = 3600000; //Time to redirect to error page
var warningTime = 3300000;  //Time to show warning message
var errorTimeout;  // Holds setTimeout() return value for error time
var warningTimeout;  // Holds setTimeout() return value for warning time

 function restartTimeout(){
    stopTimeout();
    startTimeout();
}

function startTimeout(){
    document.getElementById("overlayWarning").style.display = "none"
    document.getElementById("warning").style.display = "none"
    
    errorTimeout = setTimeout("showError()", errorTime);
    warningTimeout = setTimeout("showWarning()", warningTime);
}

function stopTimeout(){
    clearTimeout(errorTimeout);
    clearTimeout(warningTimeout);
}

function showError(){
    window.location.pathname = "html/custom/135/error";
}
			
function showWarning(){
    document.getElementById("overlayWarning").style.display = "block"
    document.getElementById("warning").style.display = "block"
}

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;
    }
} 

function getCookieValue(name){
    var allCookies = document.cookie.split( ';' );
    var cookie = '';
    var cookieVame = '';
    var cookieValue = '';

    for ( i = 0; i < allCookies.length; i++ ){
        cookie = allCookies[i].split( '=' );
        cookieName = cookie[0].replace(/^\s+|\s+$/g, '');
        if ( cookieName == name ){
            if ( cookie.length > 1 ){
                cookieValue = unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
                return cookieValue;
            }else{
                return '';
            }
        }
    }
    return '';
}
