function focusAndSelect(object)
{
	object.focus();
    object.select();
    return true;
}//focusAndSelect

function ValidateDate(varDateToCheck, varType) {
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	
	/* is the format ik? */
	var matchArray = varDateToCheck.match(datePat); 
	
	if (matchArray == null) 
	{
		alert( varType + " date is not in a valid format. Please use the MM/DD/YYYY format.");
		return false;
	}	
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	
	/* check month range */
	if (month < 1 || month > 12) 
	{
		alert(varType + " month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) 
	{
		alert(varType + " day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		alert(varType + " month "+month+" doesn't have 31 days!");
		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)) 
		{
			alert("February " + year + " doesn't have " + day + " days!");
			return false;
		}
	}
	return true;		
}//ValidateDate  
//
// We needed a new date validation routine that would simply pass the error 
// message back intead of presenting it directly.
//
function ValidateDateNew(varDateToCheck, varType) 
{
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var strMessage = "";
		
	/* is the format ik? */
	var matchArray = varDateToCheck.match(datePat); 
	
	if (matchArray == null) 
	{
		strMessage =  varType + " date is not in a valid format. Please use the MM/DD/YYYY format.";
		return strMessage;
	}	
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	
	/* check month range */
	if (month < 1 || month > 12) 
	{
		strMessage = varType + " month must be between 1 and 12.";
		return strMessage;
	}
	if (day < 1 || day > 31) 
	{
		strMessage = varType + " day must be between 1 and 31.";
		return strMessage;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		strMessage = varType + " month "+month+" doesn't have 31 days!";
		return strMessage;
	}
	if (month == 2) 
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) 
		{
			strMessage = "February " + year + " doesn't have " + day + " days!";
			return strMessage;
		}
	}
	return strMessage;		
}//ValidateDateNew 
//
// We needed a new time validation routine that would simply pass the error 
// message back intead of presenting it directly.
//
function ValidateTimeNew(varTimeToCheck, varType) 
{
	//	
	// Checks if time is in HH:MM:SS AM/PM format.
	//
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	var strMessage = "";

	var matchArray = varTimeToCheck.match(timePat);
	if (matchArray == null) 
	{
		strMessage =  varType + " time is not in a valid format.";
		return strMessage;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") 
	{ 
		second = null; 
	}
	if (ampm=="") 
	{ 
		ampm = null 
	}
	if (hour < 0  || hour > 12) 
	{
		strMessage =  varType + " hour must be between 1 and 12. ";
		return strMessage;
	}
	if (hour <= 12 && ampm == null) 
	{
		strMessage =  "You must specify AM or PM.";
		return strMessage;
	}
	if (minute<0 || minute > 59) 
	{
		strMessage =  "Minute must be between 0 and 59.";
		return strMessage;
	}
	if (second != null && (second < 0 || second > 59)) 
	{
		strMessage =  "Second must be between 0 and 59.";
		return strMessage;
	}
	return false;
}ValidateDateNew
//
// This function returns the difference between two dates for the interval (wrapper function).
//
function DateDiff(dtiStartDate, dtiEndDate, interval, rounding ) 
{
	switch (interval.charAt(0))
    {
		case 'y': case 'Y': 
           return DateDiffYears(dtiStartDate, dtiEndDate); 
           break;
        case 'j': case 'J': 
           return DateDiffMonths(dtiStartDate, dtiEndDate); 
           break;   
        default:
			return DateDiffOther(dtiStartDate, dtiEndDate, interval, rounding );
    }
}//DateDiff
//
// This function returns the difference between two dates for the interval (not for years).
//
function DateDiffOther(dtiStartDate, dtiEndDate, interval, rounding ) 
{
    var iOut = 0;
    var start = new Date(Date.parse(dtiStartDate));
    var end = new Date(Date.parse(dtiEndDate));
    //
    // Create 2 error messages, 1 for each argument. 
    //
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse(start) ;
    var bufferB = Date.parse(end) ;
    //	
    // check that the start parameter is a valid Date. 
    //
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	//
    // check that an interval parameter was not numeric. 
    //
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
		case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}//DateDiffOther
//
// Function for date difference in months.
//
function DateDiffMonths(birthDate, calcDate){
   birthday = new Date(birthDate);
   today = new Date(calcDate);
   months = (today.getFullYear() - birthday.getFullYear()) * 12;
   addmonths = today.getMonth() - birthday.getMonth();
   // The previous calculation could result in a negative number.
   months = months + addmonths;

   // Adjust month total if the birthday hasn't occurred yet this month.
   if(today.getDate() < birthday.getDate())
   {
      months--;
   }
   return months;
}//DateDiffMonths
//
// Function for date difference in years.
//
function DateDiffYears(birthDate, calcDate) 
{
	var i = birthDate.indexOf("/");
	var j = birthDate.lastIndexOf("/");
	var iBirthMonth = parseInt(birthDate.substring(0, i), 10);
	var iBirthDay = parseInt(birthDate.substring(i + 1, j), 10);
	var iBirthYear = parseInt(birthDate.substring(j + 1, birthDate.length), 10);

	if (iBirthDay < 1 || iBirthDay > daysInMonth(iBirthMonth - 1))
	{
		return("Invalid birth date");
    }
      
	i = calcDate.indexOf("/");
	j = calcDate.lastIndexOf("/");
  
	// Get the info for todays date
	var iCalcMonth = parseInt(calcDate.substring(0, i), 10);
	var iCalcDay = parseInt(calcDate.substring(i + 1, j), 10);
	var iCalcYear = parseInt(calcDate.substring(j + 1, calcDate.length), 10);

	if (iCalcDay < 1 || iCalcDay > daysInMonth(iCalcMonth - 1))
	{	
		return("Invalid calculation date");
	}
	
	var iYears = iCalcYear - iBirthYear;
  
	if (iCalcMonth < iBirthMonth)
	{
		iYears -= 1;
	}	
	else
	{
		if (iCalcMonth == iBirthMonth && iCalcDay < iBirthDay)
		{
			iYears -= 1;
		}		
	}
	return iYears;
}//DateDiffYears
//
// How many days in the month.
//
function daysInMonth(iMonth, iYear) 
{
	if (iMonth < 0 || iMonth > 11)
	{
		return 0;
	}
	if (iMonth == 1)
	{	
		return (28 + isLeapYear(iYear));
	}
	else
	{
		if (iMonth == 3 || iMonth == 5 || iMonth == 8 || iMonth == 10)
		{
			return (30);
		}	
		else
		{
			return (31);
		}
	}	
}//daysInMonth
//
// Is this a leap year.
//
function isLeapYear(iYear) 
{
  return (iYear % 4 ? 0 : iYear % 100 ? 1 : iYear % 400 ? iYear == 200 ? 1 : 0 : 1);
}//isLeapYear

function thisDate() 
{
  var dt = new Date()

  return (dt.getMonth()+1 + "/" + dt.getDate() + "/" + dt.getFullYear());
}//thisDate 
//
// Date add function.
//
function DateAdd(dtiStartDate, numDays, numMonths, numYears)
{
	//
	// Convert the string representation of the date to a date.
	//
	var startDate = new Date(dtiStartDate);
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	//
	// Return a string representation of the date.
	//
	return (returnDate.getMonth()+1) + "/" + returnDate.getDate() + "/" + returnDate.getFullYear();
}//DateAdd
//
// Function to check if an argument is numeric.
//
function isNumeric(value) 
{
    if (value == "")  { return false }
    if (value.charAt(0) == "-")
      start = 1;
    else
      start = 0;
    for (i=start; i<value.length; i++)
    {
      if (value.charAt(i) < "0" && value.charAt(i) != ".") { return false; }
      if (value.charAt(i) > "9" && value.charAt(i) != ".") { return false; }
    }
    return true;
}
//
// Trim space from a string.
//
function trim(inputString) 
{
   // Removes leading and trailing spaces from the passed string. Also
   // removes consecutive spaces and replaces it with one space.
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
}//trim 
//
// Function to test if a number is in currency format (Do not allow negatives).
//
function isCurrency(value) 
{
	// stript commas before validation.
	value = StripCommas(value);
	// strip dollar sign before validation.
	value = StripDollarSign(value);
    if (value == "")  { return false }
    if (value.charAt(0) == "$")
      start = 1;
    else
      start = 0;
    for (i=start; i<value.length; i++)
    {
      if (value.charAt(i) < "0" && value.charAt(i) != ".") { return false; }
      if (value.charAt(i) > "9" && value.charAt(i) != ".") { return false; }
    }
    return true;
}//isCurrency
//
// Remove commas from a number before attempting validation.
//
function StripCommas(strValue) 
{
  var objRegExp = /,/g; 
 
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}//StripCommas
//
// Remove commas from a number before attempting validation.
//
function StripDollarSign(strValue) 
{
	filteredValues = "$";     // Characters to be stripped
	var i;
	var returnString = "";
	// Search through string and append to unfiltered values to returnString.
	for (i = 0; i < strValue.length; i++) 
	{  
		var c = strValue.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}//StripDollarSign
//
// Check to see if a positive amount is entered (zero and fractional cents not allowed.
//
function isPositive(value)
{
    return (value >= 0.01);
} 

function isInRange(value, min, max)
{
    return ((value >= min) && (value <= max));
} 

function StringCompare(x,y)
{
	/* check to see if the first part of the strings are the same */
	for (var i=0; i < y.length; i++)
	{
		if (x.charAt(i) != y.charAt(i))
		{
			return false;
		}
	}
	return true;	
}//StringCompare
//
// Look for the string at the end of another string.
//
function StringEndCompare(x,y)
{
	/* check to see if the first part of the strings are the same */
	for (var i=0; i < y.length; i++)
	{
		if (x.charAt(x.length-y.length+i) != y.charAt(i))
		{
			return false;
		}
	}
	return true;	
}//StringEndCompare
//
//  Validate an integer
//
function isInteger(value) 
{
    if (value == "")  { return false }
    start = 0;
    for (i=start; i<value.length; i++)
    {
      if (value.charAt(i) < "0") { return false; }
      if (value.charAt(i) > "9") { return false; }
    }
    return true;
}//IsInteger
//
// Function to format a number as currency.
//
function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	{
		num = "0";
	}	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	{
		cents = "0" + cents;
	}	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	{
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	}	
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}//formatCurrency

function ElementEval(x,y)
{
	var SubString="";
	/* check to see if the first part of the strings are the same */
	for (var i=y.length; i < x.length; i++)
	{
		SubString = SubString + x.charAt(i);
	}
	return SubString;	
}//StringCompare
//
// Return the the left most part of string of length lngNumberCharacters.
//
function left(strString,lngNumberCharacters)
{
	var lngLength=0;
	var SubString="";
	// Make sure the number of characters is not greater than the string length
	if (strString.length < lngNumberCharacters)
	{
		lngLength = strString.length;
	}
	else
	{
		lngLength = lngNumberCharacters;	
	}	
	/* check to see if the first part of the strings are the same */
	for (var i=0; i < lngLength; i++)
	{
		SubString = SubString + strString.charAt(i);
	}
	return SubString;	
}//left
//
// Return the the characters after a particular position.
//
function mid(strString,lngStart)
{
	var lngStart2=0;
	var SubString="";
	// Make sure the start is not beyond the string length
	if (strString.length < lngStart)
	{
		lngStart2 = strString.length;
	}
	else
	{
		lngStart2 = lngStart;	
	}	
	/* check to see if the first part of the strings are the same */
	for (var i=lngStart; i < strString.length; i++)
	{
		SubString = SubString + strString.charAt(i);
	}
	return SubString;	
}//mid
//
// Return lngLen number of characters after a particular position.
//
function mid0(strString,lngStart,lngLen)
{
	var lngStart2=0;
	var lngEnd2 = 0;
	var SubString="";
	// Make sure the start is not beyond the string length
	if (strString.length < lngStart)
	{
		lngStart2 = strString.length;
	}
	else
	{
		lngStart2 = lngStart;	
	}	
	lngEnd2 = lngStart2 + lngLen;
	// Make sure length does not go beyond length of string
	if (lngEnd2 > strString.length)
	{
		lngEnd2 = strString.length
	}	
	/* check to see if the first part of the strings are the same */
	for (var i=lngStart; i < lngEnd2; i++)
	{
		SubString = SubString + strString.charAt(i);
	}
	return SubString;	
}//mid
//
// Find the first instance of the search character within a string
//
function instr(strString,strSearchCriteria)
{
	var lngLength=0;
	var SubString="";
	/* check to see if the first part of the strings are the same */
	for (var i=0; i < strString.length; i++)
	{
		if (strString.charAt(i) == strSearchCriteria.charAt(0))
		{
			return parseInt(i+1);
		}	
	}
	return 0
}//instr
//
// Find the first instance of the search character within a string starting at character intStart
//
function instr0(intStart,strString,strSearchCriteria)
{
	var lngLength=0;
	var SubString="";
	/* check to see if the first part of the strings are the same */
	for (var i=intStart; i < strString.length; i++)
	{
		if (strString.charAt(i) == strSearchCriteria.charAt(0))
		{
			return parseInt(i);
		}	
	}
	return 0
}//instr
//
// Find the first instance of the search string within a string
//
function instrNEW(strString,strSearchCriteria)
{
	var lngLength=0;
	var SubString="";
	var intLength=0;
	// Get the length of the search expression.
	intLength = strSearchCriteria.length;
	/* check to see if the first part of the strings are the same */
	for (var i=0; i < strString.length; i++)
	{
		if (strString.substr(i,intLength) == strSearchCriteria)
		{
			return parseInt(i+1);
		}	
	}
	return 0
}//instrNEW
//
// Display any errors issued by the update data routine.
//
function DisplayErrors(strError)
{
	if (strError != "")
	{
		alert(strError);
	}	
}//DisplayErrors	

// This is a cross browser routine for modal windows. 
var winModalWindow
 
function IgnoreEvents(e)
{
  return false
}
 
function ShowWindow(strPageName,strWidth, strHeight, strArgs)
{
  var strArg;
  var strRetValue;
  if (window.showModalDialog)
  {
	strArg="dialogWidth=" + strWidth + "px;dialogHeight=" + strHeight+ "px;scroll=no;status=no";
    strRetValue=window.showModalDialog(strPageName,strArgs,strArg)
  }
  else
  {
	strArg="dependent=yes,width=" + strWidth + ",height=" + strHeight
    window.top.captureEvents (Event.CLICK|Event.FOCUS)
    window.top.onclick=IgnoreEvents
    window.top.onfocus=HandleFocus 
    winModalWindow = 
    window.open (strPageName,"ModalChild",strArg)
    winModalWindow.focus()
  }
  return strRetValue;
}

function ShowScrollableWindow(strPageName,strWidth, strHeight, strArgs)
{
  var strArg;
  var strRetValue;
  if (window.showModalDialog)
  {
	strArg="dialogWidth=" + strWidth + "px;dialogHeight=" + strHeight+ "px;status=no";
    strRetValue=window.showModalDialog(strPageName,strArgs,strArg)
  }
  else
  {
	strArg="dependent=yes,width=" + strWidth + ",height=" + strHeight
    window.top.captureEvents (Event.CLICK|Event.FOCUS)
    window.top.onclick=IgnoreEvents
    window.top.onfocus=HandleFocus 
    winModalWindow = 
    window.open (strPageName,"ModalChild",strArg)
    winModalWindow.focus()
  }
  return strRetValue;
}
 
function HandleFocus()
{
  if (winModalWindow)
  {
    if (!winModalWindow.closed)
    {
      winModalWindow.focus()
    }
    else
    {
      window.top.releaseEvents (Event.CLICK|Event.FOCUS)
    }
  }
  return false
}
//
// If the user does not input slashes in the date, then attempt to auto format the result.
// Note:  For this to work the user must enter the data as 06/03/1970, not 6/3/1970.
//
function MaskDate(objDate)
{
	var intPos1=1;
	var intPos3=1;
	
	if(document.all)
	{
		//
		// Do not allow any key when the shift key is pressed.
		//
		if (event.shiftKey)
		{
			return false;
		}	
		else
		{
			// Allow the tab key to continue to work.
			if(event.keyCode==9) return true;
			// Reset content if the backspace key is pressed.
			if(event.keyCode==8) return true;	
			// Reset content if the delete key is pressed.
			if(event.keyCode==46) return true;
			// Allow numbers 0 to 9 on the normal keyboard and the "/" character to pass.
			// Also allow numbers 0 to 9 on the numeric keypad.
			if((event.keyCode>47 && event.keyCode<58) || event.keyCode==191 || (event.keyCode>95 && event.keyCode<106))
			{
				// If the user manually inserts a "/" then exit auto format.
				if (event.keyCode == 191)
				{
					return true;			
				}
				// If the position of the first slash is not at 2, then do not attempt auto format.
				intPos1 = instr0(1,objDate.value,"/")
				if(intPos1 != 2 && intPos1 != 0)
				{
					return true;
				}	
				// If the 2nd slash is not at position 5 do not attemp auto format.
				intPos3 = instr0(4,objDate.value,"/")
				//alert(intPos3);
				if(intPos3 != 5 && intPos3 != 0)
				{
					return true;
				}
				// Auto format the data when appropriate.
				if((objDate.value.length==2 || objDate.value.length==5) && event.keyCode!=8)
			    {
					objDate.value = objDate.value + "/";
				}
				return true;
			}
			else
			{
				return false;
			}	
		}	
	}
	else
	{
		var pattern = /^\d*$/;
		var text = objDate.value;
		if(text.search(pattern)<0 && text.length>0)
		{
			objDate = text.substr(0,text.length-2);
			return false;
		}
	return true;
	}
}//MaskDate
		
