
/*
For all instances where you need to display a message in a pop-up window,
use the AlertWindow function.
There is only 1 argument. It is the string you wish to display.
*/


 
// Functions for data validation
// Include optional header and message string, and boolean false to NOT show errors.

// formverify(form [, strHeader [, strMessage [, bShowErrors]]])

function formverify(form){	

	var errors = "";
	var msg = "";
	var sAlertTitle = "";
	var bGetTitle, bGetMessage, bGetBody, bShowErrors;
	bGetTitle = bGetMessage = bGetBody = false;
	bShowErrors = true;

	//Loop through the fields in the form
	for (var I = 0; I < form.length; I ++){
		var fieldname = form.elements[I];
		
		if ( (fieldname.type != "hidden") || (fieldname.type == "hidden") && (fieldname.checkhidden !=null) ) {

			//check for blank required fields
			if (isblank(fieldname.value) &&  (fieldname.required) && fieldname.type != "select-one"){
				errors += "\n" + fieldname.msgname + " can not be blank.";
			}

			//check for min len
			if(fieldname.minlen !=null && fieldname.value.length < fieldname.minlen && !isblank(fieldname.value)){
				errors += "\n" + fieldname.msgname + " is too short.";
			}
	
			//check for selected from list boxes
			//alert(fieldname.type)
			if (fieldname.type == "select-one" && fieldname.required){
				if(fieldname.selectedIndex <= 0){
					errors += "\n" + "Please select  " + fieldname.msgname;
				}
			}
	
			//check for numeric
			if ((fieldname.numeric && !isblank(fieldname.value)) && (isNaN(fieldname.value))){
				errors += "\n" + fieldname.msgname + " needs to be numeric.";
			}

			//check email
			if ((fieldname.name =="Email") && (fieldname.required))
			{

				var emailReg = "[\\w]+[\-]*[\\w]*[\.]*[\\w]*[\-]*[\\w]*\@+[\\w]*\.+[\.]+[\\w]+$";
				var email = fieldname.value;
				if (!(email.match(emailReg)))
				{
					errors += "\n" + "A valid email address is required.";
				}
			}

			//check for positive value
			if ((fieldname.positive && !isblank(fieldname.value)) && (fieldname.value < 0)){
				errors += "\n" + "Please enter positive numbers only.";
			}
			
			if (fieldname.luhnValidity && !(luhnCheck(fieldname.value))) {
					errors += "\n" + "Please enter a valid " + fieldname.msgname + ".";
			}
			
			//*******new security validation*******
			
		
			var RegExVal = new RegExp("[a-zA-Z\-\s']","g");
			if ((fieldname.name =="UserName") && (fieldname.required))
			
			{	
				
			var emailReg = "[\\w]+[\-]*[\\w]*[\.]*[\\w]*[\-]*[\\w]*\@+[\\w]*\.+[\.]+[\\w]+$";
				var email = fieldname.value;
				if (!(email.match(emailReg)))
				{	
					var RegExVal = new RegExp("[^a-zA-Z0-9]","g")
					//alert (RegExVal.test(fieldname.value))
					if (!(RegExVal.test(fieldname.value)))
					{
					
					//alert("valid")
					}
				
					else
 					{
					errors += "\n" + "User Name contains invalid characters.";
					}	
				}
			}
			
			if ((fieldname.name =="FirstName") && (fieldname.required))
			{
				var RegExVal = new RegExp("[^a-zA-Z\-]","g")
					//alert (RegExVal.test(fieldname.value))
					if ((RegExVal.test(fieldname.value)))
				{					
				errors += "\n" + "First Name contains invalid characters.";
				}
			}
			
			if ((fieldname.name =="LastName") && (fieldname.required))
			{
				var RegExVal = new RegExp("[^a-zA-Z\-]","g")
					//alert (RegExVal.test(fieldname.value))
					if ((RegExVal.test(fieldname.value)))
				{
					errors += "\n" + "Last Name contains invalid characters.";
				}
			}	
			if ((fieldname.name =="City") && (fieldname.required))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\-]");
					//alert (RegExVal.test(fieldname.value))
					if ((RegExVal.test(fieldname.value)))
				{
					errors += "\n" + "City contains invalid characters.";
				}
			}
			
			if ((fieldname.name =="ServiceAddress1"))
			{			
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\-]");
					
					if (RegExVal.test(fieldname.value))
				{
					errors += "\n" + "Service Address 1 contains invalid characters.";
				}
			}
			if ((fieldname.name =="ServiceAddress2"))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\-]");
					
					if (RegExVal.test(fieldname.value))
				{
					errors += "\n" + "Service Address 2 contains invalid characters.";
				}
			}	

			if ((fieldname.name =="Address1") && (fieldname.required))
			{
				RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\=]");
					
					if (RegExVal.test(fieldname.value))
				{
				
					errors += "\n" + "Address contains invalid characters.";
				}
			}
			if ((fieldname.name =="Address2"))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\-]");
					
					if (RegExVal.test(fieldname.value))
				{
				
					errors += "\n" + "Address contains invalid characters.";
				}
			}
			if ((fieldname.name =="AccountNumber")&& (fieldname.required))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)]");
					
					if (RegExVal.test(fieldname.value))
				{
				
					errors += "\n" + "Account Number contains invalid characters.";
				}
			}
			if ((fieldname.name =="meternumber")&& (fieldname.required))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)]");
					
					if (RegExVal.test(fieldname.value))
				{
				
					errors += "\n" + "Meter Number contains invalid characters.";
				}
			}
			if ((fieldname.name =="ServiceState"))
			{
				var RegExVal = new RegExp("[!\@\#\$\%\^\&\*\(\)\=]");
					
					if (RegExVal.test(fieldname.value))
				{
				
					errors += "\n" + "Service State contains invalid characters.";
				}
			}
			
			if ((fieldname.name =="PassWord") && (fieldname.required))
			{
				RegExVal.compile("[^a-zA-Z0-9]","g")
				
				if (RegExVal.test(fieldname.name) == true)
				{
					errors += "\n" + "Password contains invalid characters.";
				}

			}	

		}// end if not hidden
	}// end for loop

	//error message
	if (!errors) return true;
	
	// Check the various optional arguments
	if ( arguments.length > 1 ) { // if there's a title argument
		if( arguments[1].length > 0 ){
			bGetTitle = true; // and it's not blank
		} // end if
	} // end if
	if ( arguments.length > 2 ) { // if there's a message argument
		if( arguments[2].length > 0 ) {
			bGetMessage = true; // and it's not blank
		} // end if
	} // end if
	if ( arguments.length > 3 ) { // if there's a body argument
		if( arguments[3].length > 0 ) {
			bGetBody = true; // and it's not blank
		} // end if
	} // end if
	if( arguments.length > 4 ){ // if there's a show errors argument
		bShowErrors = arguments[4]
	} // end if

	// Alter the message text based on optional args
	if ( bGetTitle ) {
		sAlertTitle = arguments[1];
	} else {
		sAlertTitle = "Form Errors";
	} // end if
	if ( bGetMessage ) {
		//msg = "<strong>" + arguments[2] + "</strong>\n";
		msg = arguments[2] + "\n";
	}else{
		//msg = "<strong>There were some errors on the form.\n";
		//msg += "Please correct them and re-submit.</strong>";
		msg = "Please complete the the following \n";
		msg += "and re-submit.";
	} // end if
	if ( bGetBody ) {
		msg += "\n" + arguments[3] + "\n";
	} // end if
	if ( bShowErrors ) {
		msg += "\n" + errors;
	} // end if

	AlertWindow(sAlertTitle, msg);

	return false;

}// end form verify function

//checks for blanks spaces in input fields
function isblank(s) {
	if (s == null) return true;
	if (s == "") return true;
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

//Phone functions
function phone1_onkeyup() 
	{
		if (document.form.phone1.value.length >= 3) document.form.phone2.focus()
	}
	
function phone1_onblur()
	{
		document.form.phone.value = document.form.phone1.value.toString() + document.form.phone2.value.toString() + document.form.phone3.value.toString()
	}
	
function phone2_onkeyup() 
	{
		if (document.form.phone2.value.length >= 3) document.form.phone3.focus()
	}
	
function phone2_onblur()
	{
		document.form.phone.value = document.form.phone1.value.toString() + document.form.phone2.value.toString() + document.form.phone3.value.toString()
	}

function phone3_onblur() 
	{
		document.form.phone.value = document.form.phone1.value.toString() + document.form.phone2.value.toString() + document.form.phone3.value.toString()
	if(isNaN(document.form.phone.value))
		{
		alert("Please enter only numbers.")
		}
	}
	
	//if(isNaN(document.form.phone.value)
	//	{
	//		alert("Numbers only")
	//	}	
	
	//used in the signup page
	function workphone1_onkeyup(){
		if (document.form.workphone1.value.length >= 3) document.form.workphone2.focus();
	}
	function workphone1_onblur(){
		document.form.workphone.value = document.form.workphone1.value.toString() + document.form.workphone2.value.toString() + document.form.workphone3.value.toString();
	}
	function workphone2_onkeyup(){
		if (document.form.workphone2.value.length >= 3) document.form.workphone3.focus();
	}
	function workphone2_onblur(){
		document.form.workphone.value = document.form.workphone1.value.toString() + document.form.workphone2.value.toString() + document.form.workphone3.value.toString();
	}
	function workphone3_onblur(){
		document.form.workphone.value = document.form.workphone1.value.toString() + document.form.workphone2.value.toString() + document.form.workphone3.value.toString();
		if(isNaN(document.form.workphone.value)){
			alert("Please enter only numbers.");
		}
	}
	
/*******************************************************************
AutoAdvance(Condition, NextElement)
********************************************************************
Created 3/15/01 Peter Lanoie
Arguments: Boolean expression, and destination Form element
Purpose: Automatically advances the focus to the specified element
Return: None
Notes: Function must be called from element's onkeyup handler
	Only advances for a keypress that actually changes the value and
	causes condition to be true.
Example:
<form name="MyForm">
	<input type="hidden" name="Phone">
	<input type="Text" name="Phone1" onkeyup="MergeFields(this.form.Phone);">
	<input type="Text" name="Phone2" onblur="MergeFields(this.form.Phone);">
	<input type="Text" name="Phone3" onblur="MergeFields(this.form.Phone);">
</form>
*******************************************************************/
function AutoAdvance(objElement, bCondition, objNextElement){
	// this and next element must exist
	var undefined;
	if( (objNextElement!=undefined) && (objElement!=undefined) ){
		// there's a keypress, did the value change and is the 
		// condition met?
		// this takes care (mostly) of tab entry, and any other
		// keypress that doesn't actually modify data
		if(bCondition && (objElement.lastValue != objElement.value)){
			objNextElement.focus(); //yup, advance to next element
		} // end if
		objElement.lastValue = objElement.value; // reassign lastvalue
	}else{ //element doesn't exist
		alert("AutoAdvance Error: Requested element doesn't exist.");
	} // end if undefined
} // end AutoAdvance
/*******************************************************************
End of AutoAdvance()
*******************************************************************/



/*******************************************************************
MergeFields()
********************************************************************
Created 3/15/01 Peter Lanoie
Arguments: Form element that is the destination for a split field
Purpose: concatenates all elements of a split field, like phone
Return: None
Notes: Split fields MUST be named similar to destination and be a
	sequence of 1 to n. See Example.
Example:
<form name="MyForm">
	<input type="hidden" name="Phone">
	
	<input type="Text" name="Phone1" onblur="MergeFields(this.form.Phone);">
	<input type="Text" name="Phone2" onblur="MergeFields(this.form.Phone);">
	<input type="Text" name="Phone3" onblur="MergeFields(this.form.Phone);">
</form>
*******************************************************************/
function MergeFields(Element){
	// Make sure element exists
	//alert(Element)
	var undefined;
	if(Element != undefined){ // master element must exist
		var i = 1;							// looper
		var sElementName = Element.name;	//The requested form name
		var ParentForm = Element.form;		//The element's parent
		var sMergedValue = "";				//The concatenated string

		//look for all elements with the main element's name + i
		while(ParentForm[sElementName+i] != undefined){
			//concatenate the value
			sMergedValue += ParentForm[sElementName+i].value;
			i++; //increment i
		} // end do
		Element.value = sMergedValue; //write out file value
	}else{ //element doesn't exist
		alert("MergeFields Error: Requested element doesn't exist.");
	}// end if
}// end function
/*******************************************************************
End of MergeFields()
*******************************************************************/



/*******************************************************************
AlertWindow()
Created 3/13/2001 by Peter Lanoie
Arguments: Window Title, Message Text
Purpose: This creates a 'modal' dialog window that displays whatever 
	information is passed into it in the 1 argument.  It displays a 
	'pretty' window instead of the standard JavaScript alert dialog.
Return: None
Notes: None
*******************************************************************/
function AlertWindow(sTitle, sAlertText){
	var sWindowDetails; // These are the list of parms for window properties
	var sTextStyle = "style=\"font-size:12;font-family:Arial,Helvetica;\"";
	var nFocusDelay = 250;
	var nAutoDisappearDelay = 30000;
	var nLineBreakCount = 0;
	var sAlertRE = /\n/i; // find the FIRST \n

	var nPixelsPerLine = 16;
	var nWindowWidth, nWindowHeight, nWindowXPos, nWindowYPos;

	nWindowWidth = 300;

	var UserAgent = window.navigator.userAgent
	var aol = UserAgent.indexOf ("AOL")
	
	if (aol != -1)
	{
		alert(sAlertText);
	}
	else
	{
	
		// figure out how high the window should be
		while( sAlertText.search(sAlertRE) != -1 ){ //search until none found
			nLineBreakCount++; // increment count
			sAlertText = sAlertText.replace(sAlertRE, "<br>"); //replace the one found
		}// end while
		nWindowHeight = (nLineBreakCount * nPixelsPerLine) + (6 * nPixelsPerLine);

		//gets top and left positions based on user's resolution so window is centered.
		nWindowXPos = (window.screen.width/2) - (nWindowWidth/2 + 10); //half the screen width minus half the new window width (plus 5 pixel borders).
		nWindowYPos = (window.screen.height/2) - (nWindowHeight/2 + 25); //half the screen height minus half the new window height (plus title and status bars).

		sWindowDetails = "width=" + nWindowWidth + ",height=" + nWindowHeight + ",left=" + nWindowXPos + ",top=" + nWindowYPos + ",screenX=" + nWindowXPos + ",screenY=" + nWindowYPos + ",resizable=no,scrollbars=no,menubar=no,status=no,title=no,alwaysRaised=yes";
		var NewWindow = window.open("", "Errors", sWindowDetails); //create window

		with (NewWindow.document){ // write out all the HTML contents of the window
			open();
			write("<html>\n");
			write("<head>\n");
			write("<title>" + sTitle + "</title>\n");
			// Include a script that will automatically set the focus of the 
			// window so it appears 'modal'
			write("<scri" + "pt>\n");
			write("<!--\n");
			write("var myElem = self;\n");
			write("setTimeout('setmyfocus()'," + nFocusDelay + ");\n\n");
			write("setTimeout('self.close()'," + nAutoDisappearDelay + ");\n\n");
			write("function setmyfocus() { \n");
			write("\tmyElem.focus();\n");
			write("\tsetTimeout('setmyfocus()'," + nFocusDelay + ");\n}\n");
			write("//-->\n");
			write("</scri" + "pt>\n");
			write("</head>\n");
			write("<body bgcolor='lightyellow'>\n");
			write("<form><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td " + sTextStyle + ">\n");
			write(sAlertText + "\n");
			write("<br><br>\n");
			write("<center><input type='button' value='&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;' onfocus='myElem=this' onclick='self.close()'></center>\n");
			write("</td></tr></table></form>\n");
			write("</body>\n");
			write("</html>\n");
			close();
		}// end with
	}// end if
}// end function
/*******************************************************************
End of AlertWindow()
*******************************************************************/

/*************************************************************************\
  boolean luhnCheck([String Number])
  return true if Number passes the luhn check else return false.
\*************************************************************************/
function luhnCheck(sNumber) {

  if (isNaN(sNumber)) {
    return false;
  }

  var no_digit = sNumber.length;
  var oddoeven = no_digit & 1;
  var sum = 0;

  for (var count = 0; count < no_digit; count++) {
    var digit = parseInt(sNumber.charAt(count));
    if (!((count & 1) ^ oddoeven)) {
      digit *= 2;
      if (digit > 9)
	digit -= 9;
    }
    sum += digit;
  }
  if (sum % 10 == 0)
    return true;
  else
    return false;
}
