/*
File:		scripts_msi.js
Function:	Common javascript routines for all sites
Version:	Version 1.1
Modified:	2006.07.25, Thom Howard
Copyright:	2006, Moonstone Interactive (www.msinteractive.com)
*/

/*====================================================================
Form Validation Code
====================================================================*/
// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verifyForm(f)
{
	var msg;
	var empty_fields = "";
	var errors = "";

	//Loop through elements making sure a field label is set
	for (var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		if ((e.fieldlabel == null) || (e.fieldlabel == "")) {
			e.fieldlabel = e.name;
		}
	}

	// Loop through the elements of the form, looking for all
	// text and textarea elements that don't have an "optional" property
	// defined. Then, check for fields that are empty and make a list of them.
	// Also, if any of these elements have a "min" or a "max" property defined,
	// then verify that they are numbers and that they are in the right range.
	// Put together error messages for fields that are wrong.
	for(var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		//alert(e.fieldlabel + " type=" + e.type + ", value=" + e.value);
		if (((e.type == "text") || (e.type == "textarea") || (e.type == "password") || (e.type == "select") || (e.type == "select-one"))  && !e.optional) {
			
			// first check if the field is empty
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
				empty_fields += "\n		  " + e.fieldlabel;
				continue;
			}

			// Now check for fields that are supposed to be numeric.
			if (e.numeric || (e.min != null) || (e.max != null)) {
				var v = parseFloat(e.value);
				if (isNaN(v) ||
					((e.min != null) && (v < e.min)) ||
					((e.max != null) && (v > e.max))) {
					errors +=   e.fieldlabel + " must be a number";
					if (e.min != null)
						errors += " that is greater than " + e.min;
					if (e.max != null && e.min != null)
						errors += " and less than " + e.max;
					else if (e.max != null)
						errors += " that is less than " + e.max;
					errors += ".\n";
				}
			}

			//Check for special formats
			if ((e.format != null) && (e.format != "")) {
				switch (e.format) {
					case "email":
						if (!checkEmail(e.value)) {
							errors += e.fieldlabel + " must be a valid email address.\n";
						}
						break;
					case "creditcard":
						if (!verifyCCNumber(e)) {
							errors += "You must enter a valid credit card number"
							if (e.accept != null ) {
								errors += " (we accept " + e.accept + ")";
							}
							errors +=".\n";
						}
						break;
					case "phone":
						if (!checkPhone(e)) {
							errors += e.fieldlabel + " is not a valid phone number.\n";
						}
						break;
					case "zip":
						if (!checkZip(e)) {
							errors += e.fieldlabel + " is not a valid Zip Code.\n";
						}
						break;
				}
			}

			//Check for sameness with other fields
			if ((e.mustequal != null) && (e.value != e.mustequal.value )) {
					errors += e.fieldlabel + " must be the same as " + e.mustequal.fieldlabel + ".\n";
			}

		}
	}

	// Now, if there were any errors, display the messages, and
	// return false to prevent the form from being submitted.
	// Otherwise return true.
	if (!empty_fields && !errors) {
		return true;
	}

	msg  = "______________________________________________________\n\n"
	msg += "The form was not submitted because of the following error(s).\n";
	msg += "Please correct these error(s) and re-submit.\n";
	msg += "______________________________________________________\n\n"

	if (empty_fields) {
		msg += "- The following required field(s) are empty:"
				+ empty_fields + "\n";
		if (errors) msg += "\n";
	}
	msg += errors;
	alert(msg);
	return false;
}

//Check phone number - simple version, just get 10 good digits, reformat text in field 
function checkPhone(e) {
	var s = e.value;
	var r = false;
	var c = getNumbers(s);
	if (c.length == 10) {
		r = true;
		e.value = "(" + c.substr(0,3) + ") " + c.substr(3,3) + "-" + c.substr(6,4);
	}
	return r;
}

//Check zip - simple version, just check for either 5 or 9 digits, reformat for +plus format
function checkZip(e) {
	var s = getNumbers(e.value);
	var r = false;
	if (s.length == 9) {
		e.value = s.substr(0,5) + "-" + s.substr(5,4);
		r = true;
	}
	else if (s.length == 5) {
		r = true;
	}
	return r;
}

//Return only numbers from string
function getNumbers(s) {
	var i;
	var c = "";
	for (i=0;i<s.length;i++) {
		if (isNaN(parseInt(s.charAt(i)))) {}
		else { c += s.charAt(i); }
	}
	return c;
}

//Verify email
function checkEmail(c)
	{
	var strEmail, strError, countAtRate, countDot, i;
	var checkAtRate, checkDot;
	var ValidChars,CountValidChars;
	ValidChars="abcdefghijklmnopqrstuvwxyz012345678-9_.@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	strEmail = c;
	countAtRate=0;
	countDot=0;
	CountValidChars=0;
	if (strEmail.length >= 7)
		{
		for(i=0;i<strEmail.length;i++)
			{
			if(strEmail.charAt(i)=="@")
				countAtRate++;
			if(strEmail.charAt(i)==".")
				countDot++;
			CountValidChars=0;
			for(j=0;j<ValidChars.length;j++)
				{
				if(strEmail.charAt(i)==ValidChars.charAt(j))
					{
					CountValidChars++;
					}
				}
			if(CountValidChars==0)
				{
				strError=0;
				break;
				}
			}
		}
	checkAtRate=strEmail.indexOf("@",1);
	checkDot=strEmail.indexOf(".",1);
	for(i=1;i<countDot;i++)
		checkDot=strEmail.indexOf(".",checkDot+1);
	if(countAtRate==1 && countDot > 0 && strEmail.length >=7 && strError != 0)
		strError=1;
	else
		strError=0;
	if(checkDot>=strEmail.length-2)
		strError=0;
	if(strEmail.charAt(0)=="@" || strEmail.charAt(strEmail.length-1)=="@")
		strError=0;
	if(strEmail.charAt(0)=="." || strEmail.charAt(strEmail.length-1)==".")
		strError=0;
	if(checkDot < checkAtRate)
		strError=0;

	return strError;
}

//Verify credit card number,setting cc type along the way
function verifyCCNumber(e)
{
	var s,i,fDoubleIt,iTemp,iModValue,fMod10,sCCType,sCCNumber,aCardTypes,ai,c,iDigits,fCCTypeOk;
	s = e.value;
	fDoubleIt = false;
	iTemp = 0;
	iModValue = 0;
	fMod10 = false;
	sCCType = "";
	sCCNumber = "";
	ai = new Array();
	c="";
	iDigits=0;
	fCCTypeOk=false;

	//array of card types specifying name, starting digits, length
	aCardTypes = new Array("MasterCard,51,16",
					"MasterCard,52,16",
					"MasterCard,53,16",
					"MasterCard,54,16",
					"MasterCard,55,16",
					"Visa,4,16",
					"Visa,4,13",
					"American Express,34,15",
					"American Express,37,15",
					"Diners Club/CarteBlanche,300,14",
					"Diners Club/CarteBlanche,301,14",
					"Diners Club/CarteBlanche,302,14",
					"Diners Club/CarteBlanche,303,14",
					"Diners Club/CarteBlanche,304,14",
					"Diners Club/CarteBlanche,305,14",
					"Diners Club/CarteBlanche,36,14",
					"Diners Club/CarteBlanche,38,14",
					"enRoute,2014,15",
					"enRoute,2149,15",
					"Discover,6011,16",
					"JCB,3,16",
					"JCB,2131,15",
					"JCB,1800,15");

	//Move string into numeric array
	for (i=0 ; i < s.length; i++ ) {
		c = s.charAt(i);

		//Ignore non-numbers
		if (!isNaN(c) && c != ' ') {
			iDigits++;
			ai.length=iDigits;
			ai[iDigits-1]=parseInt(c);
		}
	}

	//Reassemble string without non-numeric characters, write value back to field
	for (i = 0; i < ai.length; i++){
		sCCNumber = sCCNumber + String(ai[i]);
	}
	e.value = sCCNumber;

	//Calculate Mod-10 value
	for (i = ai.length-1; i >= 0; i--){

		if (fDoubleIt) {
			iTemp = ai[i]*2;
			if (iTemp < 10) {
				iModValue = iModValue + iTemp;
			}
			else {
				iModValue = iModValue + parseInt(String(iTemp).substr(0,1));
				iModValue = iModValue + parseInt(String(iTemp).substr(1,1));
			}
			fDoubleIt = false;
		}
		else {
			iModValue = iModValue + ai[i];
			fDoubleIt=true;
		}
	}
	fMod10 = ((iModValue % 10 == 0) && (iModValue > 0));


	//Determine Card Type and write to field property
	for (i=0 ; i < aCardTypes.length ; i++) {
		aTmp = aCardTypes[i].split(",");
		if (ai.length == parseInt(aTmp[2]) && sCCNumber.substr(0,aTmp[1].length) == aTmp[1]) {
			sCCType=aTmp[0];
			break;
		}
	}
	e.cctype = sCCType;

	//Check for credit cards accepted
	if (e.accept != null && e.accept != "") {
		fCCTypeOk = (e.accept.indexOf(sCCType) >= 0);
	}
	else {
		fCCTypeOk = (sCCType.length > 1);
	}

	//Return true ONLY if it's a known card that passed mod10
	return (fMod10 && fCCTypeOk);

}

// A utility function that returns true if a string contains only
// whitespace characters.
function isblank(s)
{
	for(var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

//Add States onto options
function addStates(e) {
	var i;
	if (e.type == "select" || e.type == "select-one") {
		i = e.length;
		e.options[i] = new Option('AB','AB');
		e.options[i+1] = new Option('AK','AK');
		e.options[i+2] = new Option('AR','AR');
		e.options[i+3] = new Option('AZ','AZ');
		e.options[i+4] = new Option('CA','CA');
		e.options[i+5] = new Option('CO','CO');
		e.options[i+6] = new Option('CT','CT');
		e.options[i+7] = new Option('DC','DC');
		e.options[i+8] = new Option('DE','DE');
		e.options[i+9] = new Option('FL','FL');
		e.options[i+10] = new Option('GA','GA');
		e.options[i+11] = new Option('HI','HI');
		e.options[i+12] = new Option('IA','IA');
		e.options[i+13] = new Option('ID','ID');
		e.options[i+14] = new Option('IL','IL');
		e.options[i+15] = new Option('IN','IN');
		e.options[i+16] = new Option('KS','KS');
		e.options[i+17] = new Option('KY','KY');
		e.options[i+18] = new Option('LA','LA');
		e.options[i+19] = new Option('MA','MA');
		e.options[i+20] = new Option('MD','MD');
		e.options[i+21] = new Option('ME','ME');
		e.options[i+22] = new Option('MI','MI');
		e.options[i+23] = new Option('MN','MN');
		e.options[i+24] = new Option('MO','MO');
		e.options[i+25] = new Option('MS','MS');
		e.options[i+26] = new Option('MT','MT');
		e.options[i+27] = new Option('NC','NC');
		e.options[i+28] = new Option('ND','ND');
		e.options[i+29] = new Option('NE','NE');
		e.options[i+30] = new Option('NH','NH');
		e.options[i+31] = new Option('NJ','NJ');
		e.options[i+32] = new Option('NM','NM');
		e.options[i+33] = new Option('NV','NV');
		e.options[i+34] = new Option('NY','NY');
		e.options[i+35] = new Option('OH','OH');
		e.options[i+36] = new Option('OK','OK');
		e.options[i+37] = new Option('OR','OR');
		e.options[i+38] = new Option('PA','PA');
		e.options[i+39] = new Option('PR','PR');
		e.options[i+40] = new Option('RI','RI');
		e.options[i+41] = new Option('SC','SC');
		e.options[i+42] = new Option('SD','SD');
		e.options[i+43] = new Option('TN','TN');
		e.options[i+44] = new Option('TX','TX');
		e.options[i+45] = new Option('UT','UT');
		e.options[i+46] = new Option('VA','VA');
		e.options[i+47] = new Option('VT','VT');
		e.options[i+48] = new Option('WA','WA');
		e.options[i+49] = new Option('WI','WI');
		e.options[i+50] = new Option('WV','WV');
		e.options[i+51] = new Option('WY','WY');
	}
	return true;
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
function pageWidth() {return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;}
function pageHeight() {return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}

//Minimum window size
function setMinimumWindowSize(x,y) {
	if (pageWidth() < x || pageHeight() < y) {
		window.resize(x,y);
	}
	return true;
}
