
// Decide which way to render this layer...
var viaNSLayers = (document.layers) ? true : false;
var viaIE = (document.all) ? true : false;
var viaDOM = (document.getElementById) ? true : false;

errorTimeouts = new Array();

function MarkError(fField, fStyle) {
	var originalStyle = fStyle;
	if (typeof(fStyle) == "undefined") {
		originalStyle = "";
	}
	
	Errorize(fField);
	if (viaIE)
		errorTimeouts[(errorTimeouts.length + 1)] = window.setTimeout("UnErrorize(document." + fField.form.name + ".elements['" + fField.name + "'], '" + originalStyle + "')", 2000);
	else if (viaDOM)
		errorTimeouts[(errorTimeouts.length + 1)] = window.setTimeout("UnErrorize(document." + fField.form.name + "." + fField.name + ", '" + originalStyle + "')", 2000);

	fField.focus();
}

function Errorize(fField) {
	if (navigator.appName.indexOf("Microsoft") > -1 || parseInt(navigator.appVersion) >= 5) {
		fField.style.border = "2px solid #657889";
		fField.style.background = "#E0E6EB";
	}
}

function UnErrorize(fField, fStyle) {
	if (navigator.appName.indexOf("Microsoft") > -1 || parseInt(navigator.appVersion) >= 5) {
		fField.removeAttribute("style", 0);
		fField.style.background = "#FFFFFF";
	}
}

function checkRadio(qDesc, fForm, fFieldName, fOtherField, fOtherName, fRE) {
	
	var fOK = false; // :O Profanity in variables! 
	var fIsLast = false;
	var fOtherOK = true;
	var fField = document[fForm].elements[fFieldName];
	var fSubField;
	
	if (typeof(fField.length) == "undefined") {
			fField.checked = true;
			fIsLast = true;
			fOK = true;
	} else {
		//Check that a thingie is selected
		for (var i = 0; i < fField.length; ++i) { //Loop through the items in this radio group to find the victim...
			fSubField = document[fForm].elements[fFieldName][i];

			if (fSubField.checked) {
				fOK = true;
				if (i == (fField.length - 1))
					fIsLast = true;
				break;
			}
		}
	}

	if (fOtherField) { //If the last one in the sequence is selected, then ensure that there is a value in the OTHER field
		var fOtherField = document[fForm].elements[fOtherField];
		if (typeof(fRE) == "undefined") {
			if (fIsLast && fOtherField.value.length < 1) {
				fOtherOK = false;
			}
		} else {
			if (fIsLast && !checkTextField(fOtherField, "Error", 1, fRE, true)) {
				fOtherOK = false;
			}
		}	
	}
	
	if (!fOtherOK) {
		fOK = false;
		MarkError(fOtherField);
		window.alert("Please provide a valid value for " + fOtherName + ".");
	} else if (!fOK) {
		window.alert("Please select " + qDesc + ".");
	}
	
	return fOK;
}
	
function checkCheckBox(qDesc, fForm, fFieldName, fOtherIdx, fOtherFieldName, fOtherName) {
	//When they're named the same, is all hosed?
	var CheckBoxes;
	var fField = document[fForm].elements[fFieldName]
	var i = 0;
	
	//Check that a thingie is selected
	//If the last one in the sequence is selected, then ensure that there is a value in the OTHER field
	var fOK = false; // :O Profanity in variables! 
	var fOtherOK = true;

	for (i = 0; i < fField.length; ++i) { //Loop through the items in this radio group to find the victim...
		if (fField[i].checked) {
			fOK = true;
			fOtherField = document[fForm].elements[fFieldName + "I" + fField[i].value + "T"]; 
			if (document[fForm].elements[fFieldName + "I" + fField[i].value + "T"]) {
				if (fOtherField.value.length < 1) {
					fOK = false;
					fOtherOK = false;
					MarkError(document.Survey[fFieldName + "I" + fField[i].value + "T"]);
					break;
				}
			}
		}
	}

	if (!fOtherOK)
		window.alert("Please provide a value for '" + fOtherName + "'.");
	else if (!fOK)
		window.alert("Please select at least one " + qDesc + ".");
	
	return fOK;
}

function checkTextField(fField, fErr, fType, fConstraint, fNoWarn) {
	var fOK = true;
	var fWarn = true;
	
	if (typeof(fNoWarn) == "undefined")
		fWarn = true;
	else
		fWarn = !fNoWarn;

	if (fType == 1) { //Type 1 are regular expression validations...
		var ctfRE = new RegExp(fConstraint);
		
		if (!ctfRE.test(fField.value)) {
			fOK = false;
		}
	} else { //Otherwise just validate this thing for a certain length...
		if (fField.value.length < fConstraint) {
			fOK = false;
		}
	}
	
	if (!fOK && fWarn) {
		window.alert(fErr);
		MarkError(fField);
	}
	
	return fOK;
}

function checkSelectBox(fField, fErr, fOtherIdx, fNoWarn) {
	var fWarn = true;

	if (typeof(fNoWarn) == "undefined")
		fWarn = true;
	else
		fWarn = !fNoWarn;

	if (!fField.selectedIndex) {
		if (fWarn) {
			window.alert(fErr);
			MarkError(fField);
		}
		return false;
	}
	
	return true;
}

function checkDateField(oDate, fWarn) {
	var dString = oDate.value;
	var pdRE = new RegExp("//+", "gi");
	dString = dString.replace(pdRE, "/");
	
	if (typeof(fWarn) == "undefined") fWarn = true;
	
	oDate.value = dString;
	var dArray = dString.split("/");
	
	if (dArray.length > 2) { /* In like Flynn */
		var dM = parseInt(dArray[0], 10);
		var dD = parseInt(dArray[1], 10);
		var dY = parseInt(dArray[2], 10);
		

		if (!isNaN(dY)) { //Clean up the year
			if (dY < 0 || (dY >= 100 && dY <= 1900) || dY > 2050) {
				if (fWarn) window.alert(String(dY) + " is an invalid year.");				
				return false;
			} else if (dY < 10) {
				dY += 2000;
			}
		} else {
			window.alert("Invalid year");
			return false;
		}
		
		if (!isNaN(dM)) { //Must be from 1-12
			if (dM < 1 || dM > 12) {
				if (fWarn) window.alert(String(dM) + " is an invalid month.");
				return false;
			}
			dM -= 1; //JavaScript months go from 0 to 11
			//Month OK
			var dYM = new Date(dY, dM, 1);
		} else {
			if (fWarn) window.alert("Invalid month.");
			return false;
		}
		
		if (!isNaN(dD)) {
			dMD = parseInt(DaysInMonth(dYM), 10);
			
			if (dD < 1 || dD > dMD) {
				if (fWarn) window.alert(String(dD) + " is an invalid day.  This month only has " + String(dMD) + " days.");
				return false;
			}
			
			//window.alert(DaysInMonth(dYM));
		} else {
			if (fWarn) window.alert("Invalid day.");
			return false;
		}
		
		var YMD = new Date(dY, dM, dD);
		
		oDate.value = (YMD.getMonth() + 1) + "/" + YMD.getDate() + "/" + YMD.getFullYear();
		
		
	} else {
		if (fWarn) window.alert("Please provide a valid date in the form mm/dd/yy or mm/dd/yyyy.");
		return false;
	}
	
	return true;
}

function realTimeValidate(statusField, status, type) {
	var statusSrc = "";	
	var statusImage = statusField + "_simg";
	var newStatus = 1 + type;
	
	//Types
	//0 Required
	//1 Optional
	//2 Required with blanking
	//3 Optional with blanking
	
	if (status)	newStatus = 0;
	
	if (type > 1) { //Allow for blanking out...
		if (status)
			newStatus = 3;
		else
			newStatus = type - 1;
	}
		
	switch (newStatus) {
		case 0:
			statusSrc = "/images/8/field_ok.gif";
			break;
		case 1:
			statusSrc = "/images/8/field_required.gif";
			break;
		case 2:
			statusSrc = "/images/8/field_optional.gif";
			break;
		case 3:
			statusSrc = "/images/8/field_blank.gif";
			break;
	}

	if (document.images) {
		document.images[statusImage].src = statusSrc;
	} else if (document.all) { 
		document.all[statusImage].src = statusSrc;
	} else {
		document.getElementById(statusImage).src = statusSrc;
	}
	
	return status;
}


function PhoneEntry(phCur, phTgt, phLen) {
	var re = new RegExp("[0-9]{" + phLen + "}");

	if (re.test(phCur.value)) {
		phTgt.focus();
	}
}

function FormatPhone(fField, fFormat, fStrict, fAlpha) {
	var ph = fField.value;
	var phSuffixRE = new RegExp("( ex[tension]*\.? ?[0-9]+$)|( x\.? ?[0-9]+$)|( [0-9]+)", "gi");
	var phBreak = -1;
	var phMain = "";
	var phSuffix = "";
	var phfParenthesis = 0;
	var phfDashes = 1;
	var phfDots = 2;
	var phFormat = parseInt(fFormat);
	var phStrict = fStrict;
	var phAlpha = fAlpha;
	
	if (typeof(fFormat) == "undefined") 
		phFormat = 0;
		
	if (typeof(fStrict) == "undefined") 
		phStrict = true;
		
	if (typeof(fAlpha) == "undefined")
		phAlpha = false;
	
	if (ph.length) {
		phBreak = ph.search(phSuffixRE); //Look for a phone extension, 'cause people have things like that...
		if (phBreak > 7) {
			phMain = ph.slice(0, phBreak);
			phSuffix = " x" + ph.slice(phBreak, ph.length).replace(/[^0-9]/ig, "");
		} else {
			phMain = ph;
		}
		
		//Replace all weird characters, so that our own weird characters a.k.a. formatting can be added...
		if (phAlpha) {
			phMain = phMain.replace(/[^0-9A-Z]/ig, ""); 
			//This is gratuitous...
			phMain = phMain.replace(/[ABC]/ig, "2");
			phMain = phMain.replace(/[DEF]/ig, "3");
			phMain = phMain.replace(/[GHI]/ig, "4");
			phMain = phMain.replace(/[JKL]/ig, "5");
			phMain = phMain.replace(/[MNO]/ig, "6");
			phMain = phMain.replace(/[PQRS]/ig, "7");
			phMain = phMain.replace(/[TUV]/ig, "8");
			phMain = phMain.replace(/[WXYZ]/ig, "9");
		} else {
			phMain = phMain.replace(/[^0-9]/ig, ""); 
		}
		
		//If the phone starts with a "1", remove it because it is useless...
		if (phMain.slice(0, 1) == "1")
			phMain = phMain.slice(1, phMain.length);
		
		
		ph = "";
			
		if (phMain.length > 9 || (!phStrict && phMain.length > 0)) {
			switch (phFormat) {
				case 1:
					ph += phMain.slice(0, 3);
					if (phMain.length > 2) ph += "-" + phMain.slice(3, 6);
					if (phMain.length > 5) ph += "-" + phMain.slice(6, 10);
				break;
				case 2:
					ph += phMain.slice(0, 3);
					if (phMain.length > 2) ph += "." + phMain.slice(3, 6);
					if (phMain.length > 5) ph += "." + phMain.slice(6, 10);
				break;
				case 3: //SSN
					if (phMain.length < 5) {
						ph += phMain;
					} else {
						ph += phMain.slice(0, 3);
						if (phMain.length > 2) ph += "-" + phMain.slice(3, 5);
						if (phMain.length > 4) ph += "-" + phMain.slice(5, 9);
					}
				break;
				default:
					ph += "(" + phMain.slice(0, 3);
					if (phMain.length > 2) ph += ")" + phMain.slice(3, 6);
					if (phMain.length > 5) ph += "-" + phMain.slice(6, 10);
			}
			ph += phSuffix;
		}
		fField.value = ph;
		
		if (ph.length) {
			return true;
		} else {
			return false;
		}
	}
}

function DaysInMonth(tgtDate) {
	var wMonth;
	var wYear;
	
	if (tgtDate.getMonth() == 11) {
		wMonth = 0;
		wYear = tgtDate.getFullYear() + 1;
	} else {
		wMonth = tgtDate.getMonth() + 1;
		wYear = tgtDate.getFullYear();
	}
	
	var workDate = new Date(wYear, wMonth, 1, 12); //Set this to the first of the month
	workDate.setTime( workDate.getTime() - (24 * 60 * 60 * 1000) ) //Hours * Minutes * Seconds * 1000 is one day in milliseconds
	return workDate.getDate();
}

function FillMonths(fField) {
	var fForm = fField.form;
	var fName = fField.name;

	var fMonth = fForm[fName + "_month"];
	var fDay = fForm[fName + "_day"];
	var fYear = fForm[fName + "_year"];

	var iMonth = parseInt(fMonth.options[fMonth.selectedIndex].value, 10);
	var iYear = parseInt(fYear.options[fYear.selectedIndex].value, 10);

	if (!iMonth || !iYear) {
		//window.alert("Not attempting to recalculate days");
		return;
	}
	
	--iMonth;
	
	var curDay = fDay.selectedIndex;
	var curMonth = new Date(iYear, iMonth, 1);

	var oldDays = fDay.options.length - 1;
	var newDays = DaysInMonth(curMonth);
	//window.alert(newDays);
	if (oldDays != newDays) {
		for (i = 0; i < oldDays; ++i)  {
			fDay.options[i] = null;
		}
		
		fDay.options[0] = new Option(" ", "0");
		for (i = 1; i < (newDays + 1); ++i)  {
			fDay.options[i] = new Option(i, i);
		}
		
		if (curDay < newDays - 1) {
			fDay.selectedIndex = curDay;
		} else {
			fDay.selectedIndex = newDays;
		}
	}
}

function SetDate(fField) {
	var today = new Date();
	var fForm = fField.form;
	var fName = fField.name;

	var fMonth =  fForm[fName + "_month"];
	var fDay =  fForm[fName + "_day"];
	var fYear =  fForm[fName + "_year"];
	
	var iMonth = fMonth.options[fMonth.selectedIndex].value;
	var iDay = fDay.options[fDay.selectedIndex].value;
	var iYear = fYear.options[fYear.selectedIndex].value;
	
	if (parseInt(iMonth) && parseInt(iDay) && parseInt(iYear)) {
		fField.value = iMonth + "/" + iDay + "/" + iYear;
		//window.alert("Setting date to " + fField.value);
	} else {
		//window.alert("Not setting date because it is not valid.");
		fField.value = "";
		return;
		//fField.value = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
	}
	//window.alert(DateForm[MainField].value);
}

function PopUpCenter(width, height) { //Courtesy of Ross Snyder @ NewGrounds.com!
	var xposition = 0, yposition = 0, text;
	
	if((parseInt(navigator.appVersion) >= 4))
	{
		xposition = (screen.width - width) / 2;
		yposition = (screen.height - height) / 2;
	}
	
	text = "width=" + width + ",height=" + height + ",screenx=" + xposition + ",screeny=" + yposition + ",left=" + xposition + ",top=" + yposition;
	return(text);
}

function Calendar(dValue, fField, advanced) {
	window.open("/utilities/calendar.asp?Date=" + document.getElementById(fField).value + "&FormField=" + fField + "&advanced=" + advanced, "CalendarWin", PopUpCenter(190, 190) + ",location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,hotkeys=0");
}

function DisableField(fName, fieldRawRE, fieldAction) {
	var fForm = document[fName];
	var fieldRE = new RegExp(fieldRawRE);

	for (var i = 0; i < fForm.elements.length; ++i) {
		if (fieldRE.test(fForm.elements[i].name)) {
			//window.alert(fForm.elements[i].type);
			if (fieldAction) {
				if (fForm.elements[i].type == "text")
					fForm.elements[i].value = "";
				else if (fForm.elements[i].type == "select-one")
					fForm.elements[i].selectedIndex = 0;
			}
	
			fForm.elements[i].disabled = fieldAction;
		}
	}	
}

function checkCC(s) {
  var i, n, c;
  var r = "";
	var t;

  s = s.replace(/[^0-9]/gi, ""); // First, reverse the string and remove any non-numeric characters.

  if(s.length < 13) return false;  // Check for a bad string. Is the string too short to be any kind of CC?
  for (i = 0; i < s.length; i++) r = s.charAt(i) + r;

  // Now run through each single digit to create a new string. Even digits
  // are multiplied by two, odd digits are left alone.
  t = "";
  for (i = 0; i < r.length; i++) {
	c = parseInt(r.charAt(i), 10);
	if (i % 2 != 0)
	  c *= 2;
	t = t + c;
  }

  // Finally, add up all the single digits in this string.
  n = 0;
  for (i = 0; i < t.length; i++) {
	c = parseInt(t.charAt(i), 10);
	n = n + c;
  }

  // If the resulting sum is an even multiple of ten (but not zero), the
  // card number is good.
  if (n != 0 && n % 10 == 0)
	return true;
  else
	return false;
}

function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages() {
	if (document.images && (preloadFlag == true)) {
		//window.alert(changeImages.arguments[0] + ' ' + changeImages.arguments[1]);
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document.images[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}

var preloadFlag = false;
var preLoadImageSource = new Array();
var preLoadImages = new Array();

function preloadImages() {
	for (i = 0; i < preLoadImages.length; ++i) {
		preLoadImages[i] = newImage(preLoadImages[i]);
	}
	preloadFlag = true;
}

function layerRef(lyrname) {
	if (viaNSLayers) { //Netscape 4 support...
		return document.layers[lyrname];
	} else if (viaIE) { //IE doesn't care for layers, but respects document.all
		return document.all[lyrname];
	} else if (viaDOM) { //DOM compliant
		return document.getElementById(lyrname);  
	}
}

