/* *******************************
JavaScript Functions
Author: Marcelo C. Melo
****************************** */


/************ GLOBAL VARIABLES ************/
var win = null;
var myForm = null;
var gSafeOnload = new Array();// Body onload utility (supports multiple onload functions)
var ie=document.all&&navigator.userAgent.indexOf("Opera")==-1;

/************ FUNCTIONS ************/

function isValidDate(dateStr){

	// I'm changing the very end so that it only accepts 4 digits years.
	//var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{2}|\d{4})$/;
	var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;
	
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			return false;
	   	}
	}
	return true;  // date is valid
}

function dateCompare(date1, date2){
var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{2}|\d{4})$/;

var matchArray1 = date1.match(datePat); 
var matchArray2 = date2.match(datePat);
if (matchArray1 == null || matchArray2 == null) {
	return false;
}

// parse date into variables
month1 = matchArray1[1]; 
if (month1.length == 1)
	month1 = '0' + month1;
day1 = matchArray1[3];
if (day1.length == 1)
	day1 = '0' + day1;
year1 = matchArray1[4];
if (year1.length == 2)
	year1 = '20' + year1;
month2 = matchArray2[1];
if (month2.length == 1)
	month2 = '0' + month2
day2 = matchArray2[3];
if (day2.length == 1)
	day2 = '0' + day2;
year2 = matchArray2[4];
if (year2.length == 2)
	year2 = '20' + year2;


if (year1 < year2)
	return -1;
if (year1 > year2)
	return 1;

//the years were equal!
if (month1 < month2)
	return -1;
if (month1 > month2)
	return 1;
	
//the months were equal too!
if (day1 < day2)
	return -1;
if (day1 > day2)
	return 1;
	
//the dates are equivalent
return 0;
}

function showHelp(url){
  settings = 'width=300,height=530,top=0,left=0,scrollbars=yes';
  if(win != null) win.close();
  win = window.open(url,'help',settings,false);
}

function showNewHelp(url){
  settings = 'width=' + screen.width + ',height=' + screen.height + ',top=0,left=0,scrollbars=yes,resizable=yes,maximize=yes';
  if(win != null) win.close();
  win = window.open(url,'help',settings,false);
  //alwaysLowered = false;  
}

function printMessage(){
  if(isCheckBoxSelected2(parent.frames['mainFrame'].document)){
    openWindow('/app/message/message.do?m=printMessage','report','600','700','no','resizable')
  }
  else
    alert("Please select a Message.");
}

function printClientMessage(){
  if(isCheckBoxSelected2(parent.frames['mainFrame'].document)){
    openWindow('/app/cmessage/message.do?m=printMessage','report','600','700','no','resizable')
  }
  else
    alert("Please select a Message.");
}

function refresh(){
  document.location.reload();
}

function checkStatus(form,field){
  alert("Deprecated functionality needs removed!");
}

function loadPreviewFrame(url){
  parent.frames['previewFrame'].document.location = url;
}

function confirmDivisionRemoval(){
  return confirm('Are you sure?\nClicking the OK button removes this division and moves all it\'s positions, clients and Service Locations to the parent division.')
}

function confirmCategoryRemoval(){
	return confirm('Are you sure?\nClicking the OK button removes this category.')
}

function confirmPositionAssignmentRemoval(){
  return confirm('Are you sure?\nClicking the OK button will remove this position.')
}

function confirmServiceLocationAssignmentRemoval(){
  return confirm('Are you sure?\nClicking the OK button removes this service location of the current division.\nIf you just want to change the service location assignment, click the Cancel button and then click the Edit link.')
}

function viewMessage(id){
  parent.frames['previewFrame'].document.location = '../message.do?m=viewMessage&messageID='+id;
}

function validateSearch(field){
  if(field.value == '' || field.value == ' Search By Text'){
    alert('Please enter search text.');
    return false;
  }
  else
    return true;
}

function submitSearchForm(form){
  var error = false;
  try {
    form.submit();
  } catch (err) {//main things thrown and caught are "navigate away cancels"
    error = true;
    //alert(err.description);
  }
  if (!error) parent.frames['mainFrame'].startProgressBar();
}

function submitMainFrameForm(action){
  if (isCheckBoxSelected(parent.frames['mainFrame'].document.forms[0])){
    parent.frames['mainFrame'].document.forms[0].m.value = action;
    parent.frames['mainFrame'].document.forms[0].submit();
  }
  else
    alert("Please select a Message.");
}

//Dumb fire fox fix
function submitMainFrameForm2(action){
  if (isCheckBoxSelected2(parent.frames['mainFrame'].document)){
    parent.frames['mainFrame'].document.forms[0].m.value = action;
    parent.frames['mainFrame'].document.forms[0].submit();
  }
  else
    alert("Please select a Message.");
}


function submitForm(){
  formName = arguments[0];
  methodName = arguments[1];
  formAction = arguments[2];  
  myForm = document.forms[formName];
  if(methodName != null)
    myForm.m.value = methodName;
  if(formAction != null)
    myForm.action = formAction;
  var error = false;
  try {
    myForm.submit();
  } catch (err) {//main things thrown and caught are "navigate away cancels"
    error = true;
    //alert(err.description);
  }
  if (!error) startProgressBar();
}

function gotoURL(url){
  var error = false;
  try {
    document.location = url;
  } catch (err) {//main things thrown and caught are "navigate away cancels"
    error = true;
    //alert(err.description);
  }
  if (!error) startProgressBar();
}

function topGotoURL(url){
  var error = false;
  try {
    top.document.location = url;
  } catch (err) {//main things thrown and caught are "navigate away cancels"
    error = true;
    //alert(err.description);
  }
  if (!error) startProgressBar();
}



   //START CLOCK FUNCTIONALITY 
   // There must be a hour, minute and second
   //hidden field populated from the server for this 
   //to work as well as a span with an id of 'clock'
   // JSacks 5.30.05
	function updateclock(){ 
		var hrs = parseInt(document.getElementById("hour").value,10);
		var min = parseInt(document.getElementById("minute").value,10);
		var sec = parseInt(document.getElementById("second").value,10);
		var col = ":";
		var spc = " ";
		var apm;
		sec++;

		if(isNaN(hrs) || isNaN(min) || isNaN(sec))
		{
			document.getElementById("clock").innerHTML = "Time not specified";
			return;
		}
		
		if(sec > 59)
		{
			sec-= 60;
			min++;
		}
		if(min> 59)
		{
			min-= 60;
			hrs++;
			document.getElementById("hour").value = hrs;
		}
		if (hrs> 11) { 
			if(hrs > 23)
			{
				apm="AM";
				hrs -= 24;
				document.getElementById("hour").value -= 24;
			}
			else
			{
				apm="PM";
				hrs -=12;
			}
		}
		else {
			apm="AM";
		}
		var dmin = min + "";
		var dsec = sec + "";
		if (hrs== 0) hrs=12;
		if (min<=9)	 dmin="0"+min;
		if (sec<=9) dsec="0"+sec;
	
		document.getElementById("clock").innerHTML = hrs+col+dmin+col+dsec+spc+apm;
		document.getElementById("minute").value = min;
		document.getElementById("second").value = sec;		
		
	} 


function writeDate(){
  var d = new Date();
  //var pm
  var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var dayname = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  document.write(dayname[d.getDay()] + ",&nbsp;");
  document.write(monthname[d.getMonth()] + "&nbsp;");
  document.write(d.getDate() + ",&nbsp;");
  document.write(d.getFullYear() + "&nbsp;");
/*  var hours = d.getHours() + ":"
  var minutes = d.getMinutes() + ":"
  var seconds = d.getSeconds()
  if(d.getHours() > 12){
	  hours = d.getHours() - 12 + ":";
	  pm = "pm"
  }
  if(d.getMinutes() < 10){
	  minutes = "0" + d.getMinutes() + ":";
  }
  if(d.getSeconds() < 10){
      seconds = "0" + d.getSeconds();
  }
  document.write(hours + minutes + seconds + "&nbsp;" + pm);*/
}

function writeShortDate(){
  var d = new Date();
  document.write(((d.getMonth())+1) + "/");
  document.write(d.getDate() + "/");
  document.write(d.getFullYear() + "");
}

function openLink(mypage){
  win = window.open(mypage);
}

function openWindow(mypage,myname,w,h,scroll,resizable){
  //resizable should equal 'resizable' string to turn it on
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable='+resizable;
	win = window.open(mypage,myname,settings,false);
}

//write option tags
function writeOptions(selectOptions){
	for (var i=0; i < selectOptions.length; i++ )
		document.write('<option value="' + selectOptions[i].value + '">' + selectOptions[i].text + '\n');
}

function isCheckBoxSelected(formObj)
{
   for (var i=0;i < formObj.length;i++)
   {
      fldObj = formObj.elements[i];
      if (fldObj.type == 'checkbox')
      {
         if(fldObj.checked == true)
           return true;
       }
   }
   return false;
}

//Dumb fireFox/Chrome fix since they can't handle Ajax.  If they ever get out of the stone age we can swap back.
function isCheckBoxSelected2(documentObj)
{
 var fields = documentObj.getElementsByTagName("input");
 if (fields != null){
  if (fields.length){
   for (var i=0;i < fields.length;i++)
    if (innerIsCheckBoxSelected2(fields[i])) return true;
  } else {
    if (innerIsCheckBoxSelected2(fields)) return true;
  }
 }
 return false;
}

function innerIsCheckBoxSelected2(fldObj){
 if (fldObj.type == 'checkbox')
 {
  return fldObj.checked;
 }
 return false;
}

function selectRow(field)
{
   setRowColor(field);
   formObj = field.form;
   for (var i=0;i < formObj.length;i++)
   {
      fldObj = formObj.elements[i];
      if (fldObj.type == 'checkbox')
      {
         if(fldObj.value != field.value){
           fldObj.checked = false;
           dL(fldObj);
        }
       }
   }
}

function selectRow2(formObj,itemValue)
{
   for (var i=0;i < formObj.length;i++)
   {
      fldObj = formObj.elements[i];
      if (fldObj.type == 'checkbox')
      {
         if(fldObj.value == itemValue){
           fldObj.checked = true;
           hL(fldObj);
         }
         else{
           fldObj.checked = false;
           dL(fldObj);
        }
       }
   }
}

function selectRow3(fieldName,itemValue)
{
 var fields = document.getElementsByTagName("input");
 if (fields != null){
  if (fields.length){
   for (var i=0;i < fields.length;i++)
    innerSelectRow3(fields[i],fieldName,itemValue);
  } else {
    innerSelectRow3(fields,fieldName,itemValue);
  }
 }
}

function innerSelectRow3(fldObj, fldName, itemValue){
 if (fldObj.id == fldName && fldObj.type == 'checkbox')
 {
  if(fldObj.value == itemValue){
   fldObj.checked = true;
   hL(fldObj);
  } else {
   fldObj.checked = false;
   dL(fldObj);
  }
 }
}

// Select a message by clicking on subject link
function selectMessage(messageID) {
	// Go through each check-box
	var checkBoxes = getCheckBoxesByName("messageID");
	for (var i = 0; i < checkBoxes.length; i++) {
		var checkBox = checkBoxes[i];
		// If the check-box corresponds with the selected message
		if (checkBox.value == messageID) {
			// Check the check-box, highlight the row
			checkBox.checked = true;
			hL(checkBox);
		} else {
			// Un-check the check-box, un-highlight the row
			checkBox.checked = false;
			dL(checkBox);
		}
	}
	
	toggleActionDropDownAndMessageView();
}

// Check/un-check a message
function checkMessage(messageCheckBox) {
	// Highlight/un-highlight the row
	if (messageCheckBox.checked) {
		hL(messageCheckBox);
	} else {
		dL(messageCheckBox);
	}
	
	toggleActionDropDownAndMessageView();
}

// Select this page of filtered messages
function selectMessagesAll() {
	// Check all check-boxes, highlight all rows
	checkUncheckAllMessages(true);
	
	toggleActionDropDownAndMessageView();
}

// Select no messages
function selectMessagesNone() {
	// Un-check all check-boxes, un-highlight all rows
	checkUncheckAllMessages(false);
	
	toggleActionDropDownAndMessageView();
}

// Get all check-boxes in the current document that have the specified name
function getCheckBoxesByName(name) {
	var checkBoxes = new Array();
	
	var inputElements = document.getElementsByTagName("input");
	for (var i = 0; i < inputElements.length; i++) {
		if (inputElements[i].type == "checkbox" && inputElements[i].name == name) {
			checkBoxes.push(inputElements[i]);
		}
	}
	
	return checkBoxes;
}

//var actionOptions = null;

// Enable/disable the action drop-down and show either the currently selected message or
// the multiple-messages-selected dialog, depending on the number of selected messages
function toggleActionDropDownAndMessageView() {
	var numberOfSelectedMessages = getNumberOfMessagesChecked();
	
	// If there is only one selected message
	if (numberOfSelectedMessages == 1) {
		showSelectedMessage();
	} else {
		//If more than one message is selected then send an option array to the showMultipleMessages function.
		//that function will use the option array to populate the dropdown list.
		var tempArray = null;
			
		if(numberOfSelectedMessages > 1) {
			tempArray = new Array();
			var tempOption1 = new Option("File/Close", "fileMultipleMessages");
		
			tempArray[0] = tempOption1;
		}
		
		showMultipleMessagesSelectedDialog(tempArray);
	}
}

// Get number of currently checked messages
function getNumberOfMessagesChecked() {
	var count = 0;
	var checkBoxes = getCheckBoxesByName("messageID");
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked) count++;
	}
	
	return count;
}

// Show the currently selected message in the preview frame
function showSelectedMessage() {
	var selectedMessageID = "";
	
	var checkBoxes = getCheckBoxesByName("messageID");
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked) {
			selectedMessageID = checkBoxes[i].value;
			break;
		}
	}
	
	if (selectedMessageID != "") viewMessage(selectedMessageID);
}

// Show the multiple-messages-selected dialog
function showMultipleMessagesSelectedDialog(optionsArray) {
	var selectedMessageIDs = "";
	
	var checkBoxes = getCheckBoxesByName("messageID");
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked) {
			if (selectedMessageIDs != "") selectedMessageIDs += ",";
			selectedMessageIDs += checkBoxes[i].value;
		}
	}
	
	var options = ""; 
	if(optionsArray != null) {
		options = "options=";
		for(var i = 0; i < optionsArray.length; i++) {
			if(i < optionsArray.length && i != 0) options += ",";
			options += optionsArray[i].text + ":" + optionsArray[i].value;
		}
	}
	
	parent.frames["previewFrame"].document.location = "../message.do?m=viewMessagesSelect&messageIDs=" + selectedMessageIDs + "&" + options;
}

// Check/un-check all messages
function checkUncheckAllMessages(checked) {
	// Check/un-check all check-boxes, highlight/un-highlight all rows
	var checkBoxes = getCheckBoxesByName("messageID");
	for (var i = 0; i < checkBoxes.length; i++) {
		var checkBox = checkBoxes[i];
		checkBox.checked = checked;
		if (checked) hL(checkBox); else dL(checkBox);
	}
}

function setSelectBoxes(formObj, selectedIndex, startAt, endAt)
{
  //startAt,endAt = index range of checkboxes in the form
  if( startAt == null)
    startAt = 0;
  if( endAt == null || endAt > formObj.length)
    endAt = formObj.length;
  fieldCount = 0;
  for (var i=startAt;i < endAt;i++){
    fldObj = formObj.elements[i];
    if (fldObj.type == 'select-one' && fieldCount <= endAt && fldObj.disabled == false){
      fldObj.selectedIndex = selectedIndex;
      fieldCount++;
    }
  }
}

function setAndEnableSelectBoxes(formObj, selectedIndex, startAt, endAt)
{
  //startAt,endAt = index range of checkboxes in the form
  if( startAt == null)
    startAt = 0;
  if( endAt == null || endAt > formObj.length)
    endAt = formObj.length;
  fieldCount = 0;
  for (var i=startAt;i < formObj.length;i++){
    fldObj = formObj.elements[i];
    if (fldObj.type == 'select-one' && fieldCount <= endAt){
      fldObj.selectedIndex = selectedIndex;
      fldObj.disabled = false;
      fieldCount++;
    }
  }
}

function setCheckBoxes(formObj, itemValue, startAt, endAt)
{
  //startAt,endAt = index range of checkboxes in the form
  if( startAt == null)
    startAt = 0;
  if( endAt == null || endAt > formObj.length)
    endAt = formObj.length;
  fieldCount = 0;
  for (var i=startAt;i < formObj.length;i++){
    fldObj = formObj.elements[i];
    if (fldObj.type == 'checkbox' && fieldCount <= endAt && fldObj.disabled == false){
      fldObj.checked = itemValue;
      fieldCount++;
    }
  }
}

function setCheckBoxes(formObj, itemName, itemValue)
{
  for (var i=0;i < formObj.length;i++){
    fldObj = formObj.elements[i];
    if (fldObj.type == 'checkbox' && fldObj.name == itemName && fldObj.disabled == false){
      fldObj.checked = itemValue;
    }
  }
}


function setRadioBoxes(formObj, itemValue, startAt)
{
  //startAt,endAt = index range of checkboxes in the form
  if( startAt == null)
    startAt = 0;
  if( endAt == null || endAt > formObj.length)
    endAt = formObj.length;
  fieldCount = 0;
  for (var i=startAt;i < formObj.length;i++){
    fldObj = formObj.elements[i];
    if (fldObj.type == 'radio' && fieldCount <= endAt && fldObj.disabled == false){
      fldObj.checked = itemValue;
      fieldCount++;
    }
  }
}

function getRadioValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setRowColor(cb){
	if (cb.checked)
		hL(cb);
	else
		dL(cb);
}
function hL(element){
  if (ie){
    while (element.tagName!="TR"){
      element=element.parentElement;
    }
  }
  else{
    while (element.tagName!="TR"){
      element=element.parentNode;
    }
  }
  element.className = "selectedrow";
}

function dL(element){
  if (ie){
    while (element.tagName!="TR"){
      element=element.parentElement;
    }
  }
  else{
    while (element.tagName!="TR"){
      element=element.parentNode;
    }
  }
  element.className = "field";
}

// Currently, this function doesn't really work.  It has caused problems.  Here is a link to the origin of the code:
// http://www.griffininteractive.net/archives/scripting/000019.html
function SafeAddOnload(f)
{
	// Browser Detection
	isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
	NS4 = (document.layers) ? true : false;
	IEmac = ((document.all)&&(isMac)) ? true : false;
	IE4plus = (document.all) ? true : false;
	IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
	IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
	ver4 = (NS4 || IE4plus) ? true : false;
	NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;

	if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else if  (window.onload)
	{
		if (window.onload != SafeOnload)
		{
			gSafeOnload[gSafeOnload.length] = window.onload;
			window.onload = SafeOnload;
		}
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
		window.onload = f;
}

function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++)
		gSafeOnload[i]();
}


	
	

/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...
      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }
   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
{
   return RTrim(LTrim(str));
}

/*
=============================================================
formatDate(objFormField, nEvent) : Format phone on keyup event
=============================================================
*/
function formatDate(objFormField, nEvent){
  var keyCode = nEvent.keyCode ? nEvent.keyCode : nEvent.which ? nEvent.which : nEvent.charCode;
  var locs = new Array(2,5,6,7);
  var delims = new Array("/","/","2","0");
  mask(objFormField.value,objFormField,locs,delims,keyCode);
}

/*
=============================================================
formatPhone(objFormField, nEvent) : Format phone on keyup event
=============================================================
*/
function formatPhone(objFormField, nEvent){
  /*var keyCode = nEvent.keyCode ? nEvent.keyCode : nEvent.which ? nEvent.which : nEvent.charCode;
  var locs = new Array(0,4,5,9);
  var delims = new Array("(",")"," ","-");
  mask(objFormField.value,objFormField,locs,delims,keyCode);*/
  
  var numerals = "0123456789";
  var currentStr = objFormField.value;  
  var buildStr = "";
  for (var i = 0; i < currentStr.length; i++) {
    if (numerals.indexOf(currentStr.substring(i, i+1)) != -1) {
      buildStr += currentStr.substring(i, i+1);      
    }
  }  
  if (buildStr.length > 9) {
    objFormField.value = "(" + buildStr.substring(0,3) + ") " + buildStr.substring(3, 6) + "-" + buildStr.substring(6, 10);
  }
}

/*
=============================================================
validatePhoneNumber(objFormField, phoneOrFax) : Check the phone/fax number for validity
=============================================================
*/
function validatePhoneNumber(objFormField, phoneOrFax) { //phoneOrFax = either "Phone" or "Fax"
  var MIN_PHONE_NUMBER_LENGTH = 10;
  var PHONE_DELIMITERS = "()+- "; //Accepted characters for a phone number
  var NUMERIC_DIGITS = "0123456789";

  var phoneNumber = objFormField.value;
  var replacementPhoneNumber = ""; //String to replace what is currently in the field (has invalid characters stripped out)
  var invalidCharacters = "";
  var alertMessage = "";
  var numDigits = 0;
  var valid = true;

  if (phoneNumber.length > 0) { //Only validate if something is written in the field
    for (var i = 0; i < phoneNumber.length; i++) {
      var c = phoneNumber.substr(i, 1);
      if (NUMERIC_DIGITS.indexOf(c) != -1) {
        replacementPhoneNumber += c;
        numDigits++;
      } else if (PHONE_DELIMITERS.indexOf(c) != -1) {
        replacementPhoneNumber += c;
      } else {
        invalidCharacters += c;
      }
    }

    if (invalidCharacters.length > 0) {
      valid = false;
      objFormField.value = replacementPhoneNumber;
      alertMessage += "Invalid character(s) in " + phoneOrFax + " Number: " + invalidCharacters;
    }

    if (numDigits < MIN_PHONE_NUMBER_LENGTH) {
      valid = false;
      if (alertMessage.length > 0) {
        alertMessage += "\n";
      }
      alertMessage += "Invalid " + phoneOrFax + " Number (must be at least " + MIN_PHONE_NUMBER_LENGTH + " digits).";
    }

    if (!valid) {
      alert(alertMessage);
      objFormField.focus();
    }
  }
  return valid;
}

/*
=============================================================
validateNumericField(objFormField, minValue, maxValue) : Check the given object for validity (must be a number within the given range)
=============================================================
*/
function validateNumericField(objFormField, minValue, maxValue) {
  var num = parseInt(objFormField.value);
  if (!isNaN(num)) objFormField.value = num;
  return (!isNaN(num) && num >= minValue && num <= maxValue);
}

/*
=============================================================
mask(str,textbox,loc,delim) : automatically enters a specified character at a certain point in a text box.
=============================================================
*/
function mask(str,textbox,locs,delims,keyCode){
 if (str != '' && keyCode != 8){ //skip empty string and backspace
   for (var i = 0; i <= locs.length; i++){
     for (var k = 0; k <= str.length; k++){
   	   if (k == locs[i]){
   	     if (str.substring(k, k+1) != delims[i]){
   	       str = str.substring(0,k) + delims[i] + str.substring(k,str.length);
   	     }
       }
     }
   }
   textbox.value = '';
 }
 textbox.value = str; 
}




function moveSelected(index,to) {
var list = document.form.list;
var total = list.options.length-1;
if (index == -1) return false;
if (to == +1 && index == total) return false;
if (to == -1 && index == 0) return false;
var items = new Array;
var values = new Array;
for (i = total; i >= 0; i--) {
items[i] = list.options[i].text;
values[i] = list.options[i].value;
}
for (i = total; i >= 0; i--) {
if (index == i) {
list.options[i + to] = new Option(items[i],values[i + to], 0, 1);
list.options[i] = new Option(items[i + to], values[i]);
i--;
}
else {
list.options[i] = new Option(items[i], values[i]);
   }
}
list.focus();
}

function indexOf(searchItem, array) {
	for (var i = 0; i < array.length; i++){
		if (array[i] == searchItem) {
			return i;
		}
	}
	return -1;
}

function IsNumeric(sText)
{
 var ValidChars = "0123456789";
 var IsNumber=true;
 var Char;
 
 for (i = 0; i < sText.length && IsNumber == true; i++){ 
  Char = sText.charAt(i); 
  if (ValidChars.indexOf(Char) == -1){
   IsNumber = false;
  }
 }
 return IsNumber;
}

function showHideElement(elementID) {
	var element = document.getElementById(elementID);
	if (element) {
		if (element.style.display == "none") {
			element.style.display = "block";
		} else {
			element.style.display = "none";
		}
	}
}

var _scrollProtect=new Object();
var _spSubmitted=false;

function addScrollProtectionAndSubmit(formObj, targetForm, targetM, extraCode){
  _scrollProtect[formObj]=false;
  formObj.onmousewheel=function(){_scrollProtect[formObj]=true;return true;};
  formObj.onblur=function(){if (_spSubmitted)return;eval(extraCode);document.forms[targetForm].m.value=targetM;_spSubmitted=true;submitForm(targetForm);};
  formObj.onchange=function(){if (_scrollProtect[formObj]||_spSubmitted)return;eval(extraCode);document.forms[targetForm].m.value=targetM;_spSubmitted=true;submitForm(targetForm);};
}

function isScrollProtectedSubmitted(){
  return _spSubmitted;
}
