//UTILITY FUNCTIONS
// returns zero padded two digit integer
function LZ(x) {return(x<0||x>9?"":"0")+x}

// Remove all instances of chr from a string
function removeChars(string, chr) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != chr) newString += string.charAt(i);
	}
	return newString;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}

// months Array - index = month number
var monthsArray = new Array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")


// dateObj constructor
// 
function dateObj(strDate) {
	this.strDate = strDate;
	this.msDate = '';
	this.errormsg = '';
}

// pass in the strDate (mm/dd/yyyy) and return date formatted string
// 
// will take 1 or 2 digits for month or day
// and 2 or 4 digits for year (adds 2000 to 2 digit year)
// or if no year entered assumes current year
// valid delimiters include: dash(-) space( ) backslash(/) period( . )
//
// if no delimiter - can accept mmddyyyy
//
// returns formatted string
//
function ParseDate(myDateObj) {
	var strDate, strDateArray;
	var strMonth, strDay, strYear;
	var intDay, intMonth, intYear;
	var i;
	var isDelimitedDate = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	
	strDate = myDateObj.strDate;
	
	// parse string
	for (i = 0; i < strSeparatorArray.length; i++) {
		if (strDate.indexOf(strSeparatorArray[i]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[i]);
			if (strDateArray.length != 3) {
			// there aren't 3 elements in the string - possible bad format
				if (strDateArray.length == 2) {
				// string has 2 elements, assume the missing element is the current year
					thisYear = new Date();
					strDateArray[2] = thisYear.getYear();
				} else {
					myDateObj.errormsg += "\n - invalid format"
					return false;
				}
			}
			strMonth = strDateArray[0];
			strDay = strDateArray[1];
			strYear = strDateArray[2];
			isDelimitedDate = true;
			break;
	  }
	}
	// allow for the possibility of a date with no delimiters (requires: mmddyyyy)
	if (isDelimitedDate == false) {
		if (strDate.length > 5) {
			strMonth = strDate.substr(0, 2);
			strDay = strDate.substr(2, 2);
			strYear = strDate.substr(4);
	  } else {
			myDateObj.errormsg += "\n - invalid format"
			return false;
		}
	}
	
	intDay = parseInt(strDay, 10);
	intMonth = parseInt(strMonth, 10);
	intYear = parseInt(strYear, 10);

	if (strYear.length == 2) {
		// year is 2 digits - set correct century
		if (intYear > 35)
			intYear = intYear + 1900;
		else
			intYear = intYear + 2000;
	}
	
	if (isNaN(intDay) || isNaN(intMonth) || isNaN(intYear)) {
		// there is a non-numeric character in one of the component values
		myDateObj.errormsg += "\n - non-numeric character"
		return false;
	}

// we don't need to test here for > 31 days since we do below
//	if ( (intDay < 1) || (intDay > 31) ) {
	if ( intDay < 1 ) {
		// invalid day
		myDateObj.errormsg += "\n - invalid day"
	}

	if ( (intMonth < 1) || (intMonth > 12) ) {
		// invalid month
		myDateObj.errormsg += "\n - invalid month"
	}

	if ( (intYear < 1000) || (intYear > 9999) ) {
		// invalid year
		myDateObj.errormsg += "\n - invalid year"
	}
	
	if ( (intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) 
				&& (intDay > 30) ) {
		// 30 days has september, april, june and november
		myDateObj.errormsg += "\n - " + monthsArray[intMonth] + " has only 30 days."
	}
	else if (intMonth == 2) {
		if (IsLeapYear(intYear)) {
			if (intDay > 29) 
				myDateObj.errormsg += "\n - February of " + intYear + " has only 29 days."
		} 
		else {
			if (intDay > 28) 
				myDateObj.errormsg += "\n - February of " + intYear + " has only 28 days."
		}
	}
	else if (intDay > 31) {
		myDateObj.errormsg += "\n - " + monthsArray[intMonth] + " has only 31 days."
	}
	
	myDateObj.strDate = LZ(intMonth) +"/"+ LZ(intDay) +"/"+ intYear;
	
	// remember to subtract 1 from the month in the calculation
	var IETFDateObj = new Date(intYear, (intMonth-1), intDay, 23, 59, 59);
	myDateObj.msDate = Date.parse(IETFDateObj);
	
	if (myDateObj.errormsg)
		return false;
	else
		return true;
}


// returns whether intYear is a leap year
function IsLeapYear(intYear) {
if ( (intYear % 4) != 0)
    return false;
else if ( (intYear % 400) == 0)
    return true;
else if ( (intYear % 100) == 0)
    return false;
else
    return true;
}


// Author: Matt Kruse <matt@mattkruse.com>
// Modified: Kevin Goldberg <keving@imagistic.com>
// WWW: http://www.mattkruse.com/
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var W=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,W,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=monthsArray[M];
	value["W"]=DAY_NAMES[W];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
}

// real email address - check for:
// 1 character + @ + 1 character + . + 1 character
//
// returns errormsg or false
//
function IsEmailError(emailStr) {

	var errormsg = "";

	var atLoc = emailStr.indexOf("@")
	var periodLoc = emailStr.lastIndexOf(".")

	var nameStr = emailStr.substring(0, atLoc)
	var domainStr = emailStr.substring(atLoc+1, periodLoc)
	var extensionStr = emailStr.substring(periodLoc+1, emailStr.length)
	
	if ( (atLoc > periodLoc) ||
				(atLoc == -1) ||
				(periodLoc == -1) ||
				(nameStr.length == 0) ||
				(domainStr.length == 0) ||
				(extensionStr.length == 0) ) {
			errormsg = errormsg + ('\n enter a valid E-mail address')
	}
	
	return errormsg;
	
}

// Check that a US zip code is valid
function IsValidZipCode(zipcode) {
	if ( zipcode.length == 5 && isNumeric(zipcode) ) return true;
	zipcode = removeChars(zipcode, ' ');
	zipcode = removeChars(zipcode, '-');
	if ( zipcode.length != 9 || (!isNumeric(zipcode)) ) return false;
   return true;
}


// Check that a Canadian postal code is valid
function IsValidPostalCode(postalcode) {
	if (postalcode.search) {
		postalcode = removeChars(postalcode, ' ');
		if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) return true;
		else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]-\d[a-zA-Z]\d$/) != -1) return true;
		else return false;
	}
	return true;
}

// pass in password
// 
// checks for strong encryption
// 7 characters, upper case, lower case, number, special character
//
// returns errormsg or false
//
function IsPasswordError(passwordStr) {

	var errormsg = "";

	var has7Chars = false
	var hasUpperCase = false
	var hasLowerCase = false
	var hasNumber = false
	var hasSpecial = false
	
	var passwordLen = passwordStr.length
	
	if (passwordLen >= 7) has7Chars = true

	for (i=0; i<passwordLen; i++) {
		passwordChr = passwordStr.substring(i,i+1)
		passwordAscii = passwordChr.charCodeAt()
		if (passwordAscii >= 65 && passwordAscii <= 90) hasUpperCase = true
			else if (passwordAscii >= 97 && passwordAscii <= 122) hasLowerCase = true
				else if (passwordAscii >= 48 && passwordAscii <= 57) hasNumber = true
					else if ( (passwordAscii >= 33 && passwordAscii <= 47) ||
										(passwordAscii >= 58 && passwordAscii <= 64) ||
										(passwordAscii >= 91 && passwordAscii <= 96) ||
										(passwordAscii >= 123 && passwordAscii <= 126) ) hasSpecial = true
	}

	if (!has7Chars) {
		errormsg = errormsg + ('\n   enter more than 7 characters')
	}
	if (!hasUpperCase) {
		errormsg = errormsg + ('\n   include at least one Upper Case character')
	}
	if (!hasLowerCase) {
		errormsg = errormsg + ('\n   include at least one Lower Case character')
	}
	if (!hasNumber) {
		errormsg = errormsg + ('\n   include at least one Number')
	}
	if (!hasSpecial) {
		errormsg = errormsg + ('\n   include at least one Special character')
	}
	
	return errormsg;

}

// pass in a form field
//
// returns if any instances of checkbox or radiobutton are checked
//
function ValidateCheckRadio(a){
	for (var counter=0; counter < a.length; counter++) 
		if (a[counter].checked)
			return true;
	return false;
}

// pass in a form field and the specific value to test for
//
// returns if the specific value has been checked
//
function IsFieldChecked(a,b){
	for (var counter=0; counter < a.length; counter++) 
		if (a[counter].checked)
			if (a[counter].value == b)
				return true;
	return false;
}

// selects the first non-hidden form element for focus
//
function nonHiddenFocus(){
	for (i=0; i<document.Form1.length; i++)
		if (document.Form1.elements[i].type != 'hidden' && document.Form1.elements[i].type != 'button') {
			document.Form1.elements[i].focus()
			return;
		}
}


// pass in a select field
//
// returns value of selected
// (used for compatability with Netscape)
//
function GetSelectedValue(a){
	var sIndex = a.selectedIndex;
	return a.options[sIndex].value;
}

// specialized function to check for required field of a checkbox array
//
function ValidateCheckbox( elementName ) {
	var fieldFound = false;
	var anyChecked = false;

	for ( i = 0; i < document.Form1.length; i++) {
		if ( document.Form1.elements[i].name == elementName ) {
			fieldFound = true;
		}
		else {
			if ( fieldFound )
				break;
		}

		if ( fieldFound ) {
			if ( document.Form1.elements[i].checked == true ) {
				anyChecked = true;
				break;
			}
		}
	}

	return ( anyChecked );
	
}

// sets given option attributes
function changeOptions(field, indx, value, text, selectedValue) {
	field.options[indx].value = value;
	field.options[indx].text = text;
	if (value != "" ) {
		testvalue = value + ", ";
		testvalue = testvalue.slice(0, testvalue.indexOf(","));
		if (testvalue == selectedValue) {
		 	field.options[indx].selected = true;
		 }
	}
}	

// clear all the values in a form
function clearForm( form ) {
	for ( i=0; i < document.Form1.elements.length; i++ ) {		
		if ( document.Form1.elements[i].type != 'hidden' ) {
			if ( ( document.Form1.elements[i].type == 'checkbox' ) || ( document.Form1.elements[i].type == 'radio' ) ) {
			document.Form1.elements[i].checked = false;
			}
			else if ( document.Form1.elements[i].type != 'button' ) {
				document.Form1.elements[i].value = "";
				document.Form1.elements[i].text = "";
			}
		} // !hidden
	} // for
}	// clearForm

// generates a popup window
function popupWindow(windowname, URL, wwidth, wheight, wtitle) {
	if (!wwidth) 
		wwidth = 400;
	if (!wheight) 
		wheight = 380;
	var newname = "popup_" + windowname;
	var characteristics = "width=" + wwidth + ",height=" + wheight + ",resizeable,scrollbars=auto";
	var popup = window.open(URL, newname ,characteristics);			
	popup.focus();
//	if (wtitle) {
//		popup.document.title = wtitle;
//	}
}

// generates a popup window
function removeFiles(filename, filecontrol, pagename, idfield, id) {
	
	ok = window.confirm('Confirm: Are you sure you want to delete this file from the server?');
	if (ok)
	{
		wwidth = 300;
		wheight = 120;
		var newname = "popup_remove";
		var characteristics = "width=" + wwidth + ",height=" + wheight + "";
		var popup = window.open("/Controls/RemoveFile.php?filename="+escape(filename), 'popup_remove' ,characteristics);			
		popup.focus();
		//popup.document.title ="Removing File...";
		
//		popup.close();
//		parent.location=pagename+"?"+idfield+"="+id+"&"+filecontrol+"deleted=true";
	}
}

function finishRemoveFiles()
{
		self.close();
		opener.location=pagename+"?"+idfield+"="+id+"&"+filecontrol+"deleted=true";
}

function handler(keypressed) {
// The Document Object Model event we need is only available in
// Javascript 1.2, MSIE4+ and NN4+
// This function is the onKeyPress event handler

	var key;
        
	// Test if MSIE DOM without all that parsing of the agent string
	// NN and MSIE use different DOMs
	if (document.all) {
		key=window.event.keyCode;
	}
	else {
		key=keypressed.which;
	};
		      
	// Check each key pressed for character code 13 (carriage return), AND
	// then SUBMIT the form for the user
	if (key==13) {
		submitThis();
	}
}



function IsPhonenumber(c,r) {
	theElement = document.getElementById(c);
	//alert(theElement.value);
    if (!theElement.value || theElement.value.search(/\(?\d{3}\)?[ \.-]?\d{3}[ \.-]\d{4}/)>-1) 
    {return 0;}
    else
    	{
    		alert("Please Enter a Valid Phone Number \nin the Folowing Format \n     (123) 123-4567");
		return 1;
	}
    }
