var dtCh= "/";
var minYear=2000;
var maxYear=2025;

function isEntryDate(dtStr){

	dtStr = Trim ( dtStr )
	if ( dtStr.length > 0 )
		{
		return isDate(dtStr)
		}
	return true
}


function IsEntryNumericOnly(varNumber, sName) {

    if (((varNumber / varNumber) != 1) && (varNumber != 0) && (varNumber.length > 0) ) {
    	alert('Please enter only a number into ' + sName);
    	return false;
    	}
    else {
	    return true;
    	}
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) 
            {
            alert('Enter only numbers')
            return false;
            }
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate2(dtStr){

	dtStr = Trim ( dtStr )
	if ( dtStr.length == 0 )
		{
		return true;
		}
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day in the month")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function IsEmpty(control) {
	var strVal = Trim ( control.value )
	if ((strVal.length==0) || (control.value==null)) {
		return true;
		}
	else { 
		return false;
		}
}

function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
		}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
		return "";
		}
	else{
		return TRIM_VALUE;
		}
	} //End Function

function RTrim(VALUE){

	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
		return"";
		}
	var iTemp = v_length -1;
	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
			}
		iTemp = iTemp-1;

	} //End While
return strTemp;

} //End Function

function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
		return"";
		}

	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;

	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
			}
		else{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
			}
		iTemp = iTemp + 1;
		} //End While
		return strTemp;
	} //End Function


function TestForDate(control){

	if ( !IsEmpty ( control ) ) 
		{
		if (isDate(control.value)==false){
			control.focus()
			return false
			}
		}
    return true
 }


  function showHideContent(id)
  {
    var elem = document.getElementById(id);
      if (elem == null)
      {
      }
      else
      {	
	      if (elem.style.visibility == 'hidden') 
	      {
	
	        elem.style.display = 'block';
	        elem.style.visibility = 'visible';
	      } 
	      else
	      {
		  
	        //elem.style.display = 'none';
	        //elem.style.visibility = 'hidden';
	        elem.style.display = 'block';
	        elem.style.visibility = 'visible';
	      }
      }
  }


function IsNumericOnly(varNumber) {

    if (((varNumber / varNumber) != 1) && (varNumber != 0) && (varNumber.length > 0) ) {
    	alert('Please enter only a number into this text box');
    	return false;
    	}
    else {
	    return true;
    	}
}


/**
 * This file is jsp, but returns javascript file.
 * So, you may use this jsp like follows.
 *
 * <script language="javascript" src="/modules/Validity.js.jsp"></script>
 *
 * Then, server executes this jsp and returns javascript codes.
 * This is for front site.
 */

	var checking = false;
	var moneyLocale = "zh";

	function checkValidity(form)
	{
		checking = true;
		var eles = form.elements;
		for (i = 0; i < eles.length; i++) {
			if (eles[i].onblur) {
				if (!eles[i].onblur()) {
					checking = false;
					return false;
				}
			}
		}
		checking = false;
		return true;
	}


	function checkRequired(field, required)
	{
		if ((field.className == "inputs" || required == "true")
				&& field.value == "") {
			alert(m("msg.mandatory", field.alt));
			_focus(field);
			return false;
		}
		return true;
	}

	function checkLength(field, max)
	{
		if (field == null || field.value == "") return true;
		var len = getByteLength(field.value);
		if (len > max) {
			alert(m("msg.allow.charnum", field.alt, max));
			_focus(field)
			return false;
		}
		return true;
	}

	function checkIsNumber(field)
	{
		if (field == null || field.value == "") return true;
		if (!(new RegExp("^\\d{0,12}\\.?\\d{0,2}$")).test(field.value)) {
			alert(m("msg.in.num") + " : " + field.alt );
			_focus(field);
			return false;
		}
		return true;
	}

	function checkIsInteger(field)
	{
		if (field == null || field.value == "") return true;
		if (!(new RegExp("^\\d*$")).test(field.value)) {
			alert(m("msg.in.num") + " : " + field.alt);
			_focus(field);
			return false;
		}
		return true;
	}

	function checkNumberBoundary(field, min, max)
	{
		if (field == null || field.value == "") return true;
		if (field.value < min) {
			alert(m("msg.allow.great", field.alt, min));
			_focus(field);
			return false;
		}
		if (field.value > max) {
			alert(m("msg.allow.below", field.alt, max));
			_focus(field);
			return false;
		}
		return true;
	}

	function checkExactLength(field, len)
	{
		if (field == null || field.value == "") return true;
		if (getByteLength(field.value) != len) {
			alert(m("msg.allow.length", field.alt, len));
			_focus(field);
			return false;
		}
		return true;
	}

	function checkStringValidity(field, required, maxsize)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (maxsize != null && !checkLength(field, maxsize)) return false;
		return true;
	}

	function checkNumberValidity(field, required, min, max)
	{
		if (!checking)return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (min != null && max != null && !checkNumberBoundary(field, min, max)) return false;
		return true;
	}

	function checkIdentityNumberValidity(field, required, len)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsInteger(field)) return false;
		if (len != null && !checkExactLength(field, len)) return false;
		return true;
	}

	function checkPhoneNumberValidity(field, required, maxsize)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);
		if (!checkRequired(field, required)) return false;
		//if (!checkIsInteger(field)) return false;
		if (maxsize != null && !checkLength(field, maxsize)) return false;
		return true;
	}

	function checkYearValidity(field, required)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (!checkNumberBoundary(field, 1700, 2500)) return false;
		return true;
	}

	function checkMonthValidity(field, required)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (!checkNumberBoundary(field, 1, 12)) return false;
		if (getByteLength(field.value) == 1) field.value = "0" + field.value;
		return true;
	}

	function checkDateValidity(field, required)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (!checkNumberBoundary(field, 1, 31)) return false;
		if (getByteLength(field.value) == 1) field.value = "0" + field.value;
		return true;
	}

	function checkHourValidity(field, required)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (!checkNumberBoundary(field, 0, 24)) return false;
		if (getByteLength(field.value) == 1) field.value = "0" + field.value;
		return true;
	}

	function checkMinSecValidity(field, required)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (!checkNumberBoundary(field, 0, 60)) return false;
		if (getByteLength(field.value) == 1) field.value = "0" + field.value;
		return true;
	}

	function checkZipCodeValidity(field, required, len)
	{
		if (!checking) return true;
		field.value = trimmed(field.value);

		if (!checkRequired(field, required)) return false;
		if (!checkIsNumber(field)) return false;
		if (len != null && !checkExactLength(field, len)) return false;
		return true;
	}

	//
	//
	//

	function isLeap( year )
	{
		return (( year % 4 == 0 ) && ( year % 100  != 0 ) || ( year % 400 == 0 )) ? 1 : 0;
	}

    function isDay( yyyy, mm, value )
    {
    	var leap = new Array();
    	leap[0] = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		leap[1] = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

		var dd 		 = eval(value);
	    var maxMonth = leap[isLeap(yyyy)][eval(mm) - 1];

	    if ( (0 < dd) && (dd <= maxMonth) )
	    	return true;
	    else
	    	return false;
    }

    function isMon( value )
    {
	    return( (0 < eval(value)) && (eval(value) < 13) );
    }

    function isYear( value )
	{
    	return( (1700 < eval(value)) && (eval(value) < 2500) );
    }


    function trimmed(value)
    {
    	if (value == null) return "";
        value = value.replace(/^\s+/, "");  // remove leading white spaces
        return  value.replace(/\s+$/g, ""); // remove trailing while spaces
    }

    function _focus(field)
    {
        if (field != null && field.form != null &&
                field.type != "hidden" && !field.disabled && field.style.display != "none")
            field.focus();
    }

	// this is for UTF-8
	var lengthTable = new Array( new Array("\u0080", 1), new Array("\u07FF", 2), new Array("\uFFFF", 3) );

	// this is for EUC series
	//var lengthTable = new Array( new Array("\u0080", 1), new Array("\uFFFF", 2) );

	function getByteLength(val)
	{
		var len = 0;

		if ( val == null ) return 0

		for(var i = 0; i < val.length; i ++ ) {
			for (j = 0; j < lengthTable.length; j++) {
				if (val.charAt(i) < lengthTable[j][0]) {
					len += lengthTable[j][1];
					break;
				}
			}
		}
		return len;
	}

	/**
	 * shows error message alert
	 */
	var errMsgs = new Array();

	errMsgs["msg.mandatory"] = "Entry is Required";
	errMsgs["msg.allow.great"] = "Entry is too high";
	errMsgs["msg.allow.below"] = "Entry is too low";
	errMsgs["msg.allow.char"] = "Charaters not allowed";
	errMsgs["msg.allow.charnum"] = "{0}领域中只允许阿尔法等和数字。";
	errMsgs["msg.allow.decimalpoint"] = "{0}领域中只允许小数点以上{1}位，小数点以下{2}位的实数值。";
	errMsgs["msg.allow.alphanumeric"] = "Only Letters & Numbers are allowed";
	errMsgs["msg.in.num"] = "请输入数字。";
	errMsgs["msg.allow.length"] = "{0}领域中只允许{1}位。";
	errMsgs["msg.err.year.data"] = "Entry must be a 4 digit year.";
	errMsgs["msg.err.month.data"] = "Entry must be a valid 2 digit month";
	errMsgs["msg.err.date.data"] = "Entry muist be a valid day in the month";
	errMsgs["msg.great.0"] = "Entry Must be Greater than 0";
	errMsgs["msg.err.big.num"] = "数字太大。";
	errMsgs["msg.invalid.currency.format"] = "Entry must be a valid currency value.";
	errMsgs["msg.in.num.format"] = "Invalid Number Format";
	errMsgs["msg.allow.int"] = "Entry may only be digits (0-9).";
	errMsgs["msg.wrong.email.addr"] = "Entry must be a valid email address.";


	function m(key)
	{
    	var msg = errMsgs[key];
    	for (var i = 1; msg && i < arguments.length; i++) {
    		re = new RegExp("\\{" + (i - 1) + "\\}");
    		msg = msg.replace(re, arguments[i]);
    	}
    	return msg;
	}


	function checkIsMoney(val)
 	{
		if( moneyLocale == 'ko' )
		{
	 		if( /\./.test(val) )
 			{
 				alert(m("msg.invalid.currency.format"));
 				return false;
 			}
 		}
 		else if( moneyLocale == 'en' )
 		{
 			if ( !(new RegExp("^\\d{0,12}\\.?\\d{0,2}$")).test(val) )
 			{
 				alert(m("msg.invalid.currency.format"));
 				return false;
 			}
 		}
 		else
 		{
 			if ( !(new RegExp("^\\d{0,12}\\.?\\d{0,2}$")).test(val) )
 			{
 				alert(m("msg.invalid.currency.format"));
 				return false;
 			}
 		}

	 	return true;
 	}

	function checkNumberData(val)
	{
		if ( isNaN(val) )
		{
			alert(m("msg.in.num.format"));
			return false;
		}
		else if( val <= 0 )
		{
			alert(m("msg.great.0"));
			return false;
		}
		else if ( val >= 1000000000000 )
		{
			alert(m("msg.err.big.num"));
			return false;
		}

		return true;
	}


 	function checkPrice(field)
	{
		field.value = trimmed(field.value);

		var value = field.value;
		value = value.replace(/^\s+/, '');
		field.value = value;

		if (field == null || value == "") return true;

		if ( !checkNumberData(value) )
		{
			field.focus();
			return false;
		}

		if ( !checkIsMoney(field.value) )
		{
			field.focus();
			return false;
		}

		return true;
	}

	function checkNumber(field)
	{
		field.value = trimmed(field.value);

		var value = field.value;
		value = value.replace(/^\s+/, '');
		field.value = value;

		if (field == null || value == "") return true;

		if ( !checkNumberData(value) )
		{
			field.focus();
			return false;
		}

		return true;
	}


	function checkInteger(field)
	{
		field.value = trimmed(field.value);

		var value = field.value;
		value = value.replace(/^\s+/, '');
		field.value = value;

		if (field == null || value == "") return true;

		if ( !checkNumberData(value) )
		{
			field.focus();
			return false;
		}

		if( /\./.test(value) )
		{
			alert(m("msg.allow.int"));
			field.focus();
			return false;
		}

		return true;
	}

	function checkEmail(field)
	{
		field.value = trimmed(field.value);

		var value = field.value;
		value = value.replace(/^\s+/, '');
		field.value = value;

		if (field == null || value == "") return true;

		if ( !(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) )
	    {
	        alert(m("msg.wrong.email.addr"));
	        field.focus();
	        return false;
	    }

		return true;
	}
	
	function addDays(myDate,days) {
		return new Date(myDate.getTime() + days*24*60*60*1000);
	}

function TestForDateGT(control, sBase, sMsg, iDays, dtOrig)
	{
	if ( !IsEmpty ( control ) ) 
		{
		if (isDate(control.value)==false){
			control.focus()
			return false
			}
		else
			{
			var sTest = control.value
			sTest = Trim ( sTest )
			var bResult = true
			if ( sTest != '' ) {
				var dtTest = new Date(sTest);
				var dtBase = new Date()
				var dtBase = addDays(dtBase,iDays)
				var sMax = dtBase.getMonth() + 1 + '/' + dtBase.getDate() + '/' + dtBase.getFullYear() 
				var bResult = ( dtTest < dtBase );
				if ( ! bResult ) {
					alert ( ' Date needs to be on or after ' + sMsg + ' of ' + sBase + ' and no later than ' + sMax + '.' )
					control.value = dtOrig
					control.focus()
					}
				}
			return bResult;
			}
		}
	}


	function MustHaveDate(TestObj, dtOrigValue, sMsg)
		{
		if ((TestObj.value.length==0) || (TestObj.value==null))
			{
			alert ( sMsg + ' requires this date, it can not be deleted' )
			TestObj.value = dtOrigValue
			TestObj.focus()
			}
		else
			{
			if (!isDate(TestObj.value))
				{
					alert ( sMsg + ' requires this date, it can not be deleted' )
					TestObj.value = dtOrigValue
					TestObj.focus()
				}
			}
		return true
		}


	function Chr(CharCode)
	{
		return String.fromCharCode(CharCode);
	}
	
	function Left(str, n){
		if (n <= 0)
		    return "";
		else if (n > String(str).length)
		    return str;
		else
		    return String(str).substring(0,n);
	}
	
	function Right(str, n){
	    if (n <= 0)
	       return "";
	    else if (n > String(str).length)
	       return str;
	    else {
	       var iLen = String(str).length;
	       return String(str).substring(iLen, iLen - n);
	    }
	}


	function validateEmail(addr,man,db) {
	
	var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
	
	for (i=0; i<invalidChars.length; i++) {
	   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
	      if (db) alert('email address contains invalid characters');
	      return false;
	   }
	}
	
	for (i=0; i<addr.length; i++) {
	   if (addr.charCodeAt(i)>127) {
	      if (db) alert("email address contains non ascii characters.");
	      return false;
	   }
	}
	
	var atPos = addr.indexOf('@',0);
	if (atPos == -1) {
	   if (db) alert('email address must contain an @');
	   return false;
	}
	if (atPos == 0) {
	   if (db) alert('email address must not start with @');
	   return false;
	}
	if (addr.indexOf('@', atPos + 1) > - 1) {
	   if (db) alert('email address must contain only one @');
	   return false;
	}
	if (addr.indexOf('.', atPos) == -1) {
	   if (db) alert('email address must contain a period in the domain name');
	   return false;
	}
	if (addr.indexOf('@.',0) != -1) {
	   if (db) alert('period must not immediately follow @ in email address');
	   return false;
	}
	if (addr.indexOf('.@',0) != -1){
	   if (db) alert('period must not immediately precede @ in email address');
	   return false;
	}
	if (addr.indexOf('..',0) != -1) {
	   if (db) alert('two periods must not be adjacent in email address');
	   return false;
	}
	var suffix = addr.substring(addr.lastIndexOf('.')+1);
	if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
	   if (db) alert('invalid primary domain in email address');
	   return false;
	}
	return true;
	}


	function replaceSubstring(inputString, fromString, toString) {
	   // Goes through the inputString and replaces every occurrence of fromString with toString
	   var temp = inputString;
	   if (fromString == "") {
	      return inputString;
	   }
	   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
	      while (temp.indexOf(fromString) != -1) {
	         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
	         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
	         temp = toTheLeft + toString + toTheRight;
	      }
	   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
	      var midStrings = new Array("~", "`", "_", "^", "#");
	      var midStringLen = 1;
	      var midString = "";
	      // Find a string that doesn't exist in the inputString to be used
	      // as an "inbetween" string
	      while (midString == "") {
	         for (var i=0; i < midStrings.length; i++) {
	            var tempMidString = "";
	            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
	            if (fromString.indexOf(tempMidString) == -1) {
	               midString = tempMidString;
	               i = midStrings.length + 1;
	            }
	         }
	      } // Keep on going until we build an "inbetween" string that doesn't exist
	      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
	      while (temp.indexOf(fromString) != -1) {
	         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
	         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
	         temp = toTheLeft + midString + toTheRight;
	      }
	      // Next, replace the "inbetween" string with the "toString"
	      while (temp.indexOf(midString) != -1) {
	         var toTheLeft = temp.substring(0, temp.indexOf(midString));
	         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
	         temp = toTheLeft + toString + toTheRight;
	      }
	   } // Ends the check to see if the string being replaced is part of the replacement string or not
	   return temp; // Send the updated string back to the user
	}

	function validatePhoneNumber(sNumber, bMsg)
		{
		var regForDigits = /^[0-9]{10}/
		if ( !regForDigits.test(sNumber) )
			{
				if ( bMsg )
				{
				alert("You must supply a valid 10 digit US phone number."); 
				}
				return false; 
			}
		else
			{
			return true;
			}
		}

/*

Name: jsDate
Desc: VBScript native Date functions emulated for Javascript
Author: Rob Eberhardt, Slingshot Solutions - http://slingfive.com/
History:
	2005-08-04	v0.94		scrapped new dateDiff approach to better match VBScript's simplistic Y/M/Q
	2005-08-03	v0.93		fixed dateDiff/leapyear bug with yyyy/m/q intervals
	2004-11-26	v0.91		fixed datePart/ww bug, added weekdayName() & monthName()
	2004-08-30	v0.9		brand new
	
*/

// used by dateAdd, dateDiff, datePart, weekdayName, and monthName
// note: less strict than VBScript's isDate, since JS allows invalid dates to overflow (e.g. Jan 32 transparently becomes Feb 1)
function isDate(p_Expression){
    if ( p_Expression != '' )
        {
	    return !isNaN(new Date(p_Expression));		// <<--- this needs checking
	    }
	else
	    {
	    return true;
	    }
}


// REQUIRES: isDate()
function dateAdd(p_Interval, p_Number, p_Date){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}
	if(isNaN(p_Number)){return "invalid number: '" + p_Number + "'";}	

	p_Number = new Number(p_Number);
	var dt = new Date(p_Date);
	switch(p_Interval.toLowerCase()){
		case "yyyy": {// year
			dt.setFullYear(dt.getFullYear() + p_Number);
			break;
		}
		case "q": {		// quarter
			dt.setMonth(dt.getMonth() + (p_Number*3));
			break;
		}
		case "m": {		// month
			dt.setMonth(dt.getMonth() + p_Number);
			break;
		}
		case "y":		// day of year
		case "d":		// day
		case "w": {		// weekday
			dt.setDate(dt.getDate() + p_Number);
			break;
		}
		case "ww": {	// week of year
			dt.setDate(dt.getDate() + (p_Number*7));
			break;
		}
		case "h": {		// hour
			dt.setHours(dt.getHours() + p_Number);
			break;
		}
		case "n": {		// minute
			dt.setMinutes(dt.getMinutes() + p_Number);
			break;
		}
		case "s": {		// second
			dt.setSeconds(dt.getSeconds() + p_Number);
			break;
		}
		case "ms": {		// second
			dt.setMilliseconds(dt.getMilliseconds() + p_Number);
			break;
		}
		default: {
			return "invalid interval: '" + p_Interval + "'";
		}
	}
	return dt;
}



// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (defaults for both)
function dateDiff(p_Interval, p_Date1, p_Date2, p_firstdayofweek, p_firstweekofyear){
	if(!isDate(p_Date1)){return "invalid date: '" + p_Date1 + "'";}
	if(!isDate(p_Date2)){return "invalid date: '" + p_Date2 + "'";}
	var dt1 = new Date(p_Date1);
	var dt2 = new Date(p_Date2);

	// get ms between dates (UTC) and make into "difference" date
	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	// calc various diffs
	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
	var nQuarters = parseInt(nMonths/3);	//<<-- different than VBScript, which watches rollover not completion
	
	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS/1000);
	var nMinutes = parseInt(nSeconds/60);
	var nHours = parseInt(nMinutes/60);
	var nDays  = parseInt(nHours/24);
	var nWeeks = parseInt(nDays/7);


	// return requested difference
	var iDiff = 0;		
	switch(p_Interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": 		// day of year
		case "d": return nDays;
		case "w": return nDays;
		case "ww":return nWeeks;		// week of year	// <-- inaccurate, WW should count calendar weeks (# of sundays) between
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;	// millisecond	// <-- extension for JS, NOT available in VBScript
		default: return "invalid interval: '" + p_Interval + "'";
	}
}



// REQUIRES: isDate(), dateDiff()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (does system default for both)
function datePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}

	var dtPart = new Date(p_Date);
	switch(p_Interval.toLowerCase()){
		case "yyyy": return dtPart.getFullYear();
		case "q": return parseInt(dtPart.getMonth()/3)+1;
		case "m": return dtPart.getMonth()+1;
		case "y": return dateDiff("y", "1/1/" + dtPart.getFullYear(), dtPart);			// day of year
		case "d": return dtPart.getDate();
		case "w": return dtPart.getDay();	// weekday
		case "ww":return dateDiff("ww", "1/1/" + dtPart.getFullYear(), dtPart);		// week of year
		case "h": return dtPart.getHours();
		case "n": return dtPart.getMinutes();
		case "s": return dtPart.getSeconds();
		case "ms":return dtPart.getMilliseconds();	// millisecond	// <-- extension for JS, NOT available in VBScript
		default: return "invalid interval: '" + p_Interval + "'";
	}
}


// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek (does system default)
function weekdayName(p_Date, p_abbreviate){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}
	var dt = new Date(p_Date);
	var retVal = dt.toString().split(' ')[0];
	var retVal = Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')[dt.getDay()];
	if(p_abbreviate==true){retVal = retVal.substring(0, 3)}	// abbr to 1st 3 chars
	return retVal;
}
// REQUIRES: isDate()
function monthName(p_Date, p_abbreviate){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}
	var dt = new Date(p_Date);	
	var retVal = Array('January','February','March','April','May','June','July','August','September','October','November','December')[dt.getMonth()];
	if(p_abbreviate==true){retVal = retVal.substring(0, 3)}	// abbr to 1st 3 chars
	return retVal;
}



// ====================================

// bootstrap different capitalizations
function IsDate(p_Expression){
	return isDate(p_Expression);
}
function DateAdd(p_Interval, p_Number, p_Date){
	return dateAdd(p_Interval, p_Number, p_Date);
}
function DateDiff(p_interval, p_date1, p_date2, p_firstdayofweek, p_firstweekofyear){
	return dateDiff(p_interval, p_date1, p_date2, p_firstdayofweek, p_firstweekofyear);
}
function DatePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear){
	return datePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear);
}
function WeekdayName(p_Date){
	return weekdayName(p_Date);
}
function MonthName(p_Date){
	return monthName(p_Date);
}


//FormatDateTime(datetime, FormatType) : Returns an expression formatted
//                                       as a date or time
//========================================================================
/*
	 FomatType takes the following values
		1 - General Date = Friday, October 30, 1998
		2 - Typical Date = 10/30/98
		3 - Standard Time = 6:31 PM
		4 - Military Time = 18:31
*/

function FormatDateTime(datetime, FormatType)
{
	var strDate = new String(datetime);

	if (strDate.toUpperCase() == "NOW") {
		var myDate = new Date();
		strDate = String(myDate);
	} else {
		var myDate = new Date(datetime);
		strDate = String(myDate);
	}

	// Get the date variable parts
	var Day = new String(strDate.substring(0,3));
	if (Day == "Sun") Day = "Sunday";
	if (Day == "Mon") Day = "Monday";
	if (Day == "Tue") Day = "Tuesday";
	if (Day == "Wed") Day = "Wednesday";
	if (Day == "Thu") Day = "Thursday";
	if (Day == "Fri") Day = "Friday";
	if (Day == "Sat") Day = "Saturday";	
	
	var Month = new String(strDate.substring(4,7)), MonthNumber = 0;
	if (Month == "Jan") { Month = "January"; MonthNumber = 1; }
	if (Month == "Feb") { Month = "February"; MonthNumber = 2; }
	if (Month == "Mar") { Month = "March"; MonthNumber = 3; }
	if (Month == "Apr") { Month = "April"; MonthNumber = 4; }
	if (Month == "May") { Month = "May"; MonthNumber = 5; }
	if (Month == "Jun") { Month = "June"; MonthNumber = 6; }
	if (Month == "Jul") { Month = "July"; MonthNumber = 7; }
	if (Month == "Aug") { Month = "August"; MonthNumber = 8; }
	if (Month == "Sep") { Month = "September"; MonthNumber = 9; }
	if (Month == "Oct") { Month = "October"; MonthNumber = 10; }
	if (Month == "Nov") { Month = "November"; MonthNumber = 11; }
	if (Month == "Dec") { Month = "December"; MonthNumber = 12; }
	
	var curPos = 11;
	var MonthDay = new String(strDate.substring(8,10));
	if (MonthDay.charAt(1) == " ") {
		MonthDay = "0" + MonthDay.charAt(0);
		curPos--;
	}	
	
	var MilitaryTime = new String(strDate.substring(curPos,curPos + 5));
	
	var Year = new String(strDate.substring(strDate.length - 4, strDate.length));	
	document.write(strDate + "");	

	// Format Type decision time!
	if (FormatType == 1)
		strDate = Day + ", " + Month + " " + MonthDay + ", " + Year;
	else if (FormatType == 2)
		strDate = MonthNumber + "/" + MonthDay + "/" + Year
		//.substring(2,4);
	else if (FormatType == 3) {
		var AMPM = MilitaryTime.substring(0,2) >= 12 && MilitaryTime.substring(0,2) != "24" ? " PM" : " AM";
		if (MilitaryTime.substring(0,2) > 12)
			strDate = (MilitaryTime.substring(0,2) - 12) + ":" + MilitaryTime.substring(3,MilitaryTime.length) + AMPM;
		else {
			if (MilitaryTime.substring(0,2) < 10)
				strDate = MilitaryTime.substring(1,MilitaryTime.length) + AMPM;
			else
				strDate = MilitaryTime + AMPM;
		}
	}	
	else if (FormatType == 4)
		strDate = MilitaryTime;

	return strDate;
}


function FormatDate(date) {

	var bDate = !isNaN(new Date(date))
	if ( bDate ) {
		var sResult = '' + ( date.getMonth() + 1 ) + '/' + date.getDate() + '/' + date.getFullYear() + ''
		return sResult
	}

}

IE4 = document.all;

function newAlert(title,mess,icon,mods) {
   (IE4) ? makeMsgBox(title,mess,icon,0,0,mods) : alert(mess);
}

function newConfirm(title,mess,icon,defbut,mods) {
   if (IE4) {
      icon = (icon==0) ? 0 : 2;
      defbut = (defbut==0) ? 0 : 1;
      retVal = makeMsgBox(title,mess,icon,4,defbut,mods);
      retVal = (retVal==6);
   }
   else {
      retVal = confirm(mess);
   }
   return retVal;
}

function newPrompt(title,mess,def) {
   retVal = (IE4) ? makeInputBox(title,mess,def) : prompt(mess,def);
   return retVal;
}

function IEBox(title,mess,icon,buts,defbut,mods) {
   retVal = (IE4) ? makeMsgBox(title,mess,icon,buts,defbut,mods) : null;
   return retVal;
}


function getWindowWidth(objWin) {

    winW = screen.width / 2
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape") {
            winW = objWin.innerWidth;
        }
        if (navigator.appName.indexOf("Microsoft")!=-1) {
            winW = objWin.document.body.offsetWidth;
        }
    }
    return winW
}

function getWindowHeight(objWin) {

    winH = screen.height / 2
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape") {
            winH = objWin.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft")!=-1) {
            winH = objWin.document.body.offsetHeight;
        }
    }
    return winH
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
    if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

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);
}

