function trimstr(textstr){
  while (textstr.charAt(0) == ' ') {
    textstr = textstr.substring(1,textstr.length);
  };
  while (textstr.charAt(textstr.length - 1) == ' ') {
    textstr = textstr.substring(0, (textstr.length - 1));
  };
  return textstr;
};

function validateEmail(emailStr) {
  /* The following pattern is used to check if the entered e-mail address
     fits the user@domain format.  It also is used to separate the username
     from the domain. */
  var emailPat=/^(.+)@(.+)$/
  /* The following string represents the pattern for matching all special
     characters.  We don't want to allow special characters in the address.
     These characters include ( ) < > @ , ; : \ " . [ ]    */
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
  /* The following string represents the range of characters allowed in a
     username or domainname.  It really states which chars aren't allowed. */
  var validChars="\[^\\s" + specialChars + "\]"
  /* The following pattern applies if the "user" is a quoted string (in
     which case, there are no rules about which characters are allowed
     and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
     is a legal e-mail address. */
  var quotedUser="(\"[^\"]*\")"
  /* The following pattern applies for domains that are IP addresses,
     rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
     e-mail address. NOTE: The square brackets are required. */
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
  /* The following string represents an atom (basically a series of
     non-special characters.) */
  var atom=validChars + '+'
  /* The following string represents one word in the typical username.
     For example, in john.doe@somewhere.com, john and doe are words.
     Basically, a word is either an atom or quoted string. */
  var word="(" + atom + "|" + quotedUser + ")"
  // The following pattern describes the structure of the user
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
  /* The following pattern describes the structure of a normal symbolic
     domain, as opposed to ipDomainPat, shown above. */
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

  var validDomainParts=new RegExp("[a-zA-Z0-9\-]")

  /* Finally, let's start trying to figure out if the supplied address is
     valid. */

  /* Begin with the coarse pattern to simply break up user@domain into
     different pieces that are easy to analyze. */
  var matchArray=emailStr.match(emailPat)
  if (matchArray==null) {
    /* Too many/few @'s or something; basically, this address doesn't
       even fit the general mould of a valid e-mail address. */
    return false
  }
  var user=matchArray[1]
  var domain=matchArray[2]

  // See if "user" is valid
  if (user.match(userPat)==null) {
    // user is not valid
    return false
  }

  /* if the e-mail address is at an IP address (as opposed to a symbolic
     host name) make sure the IP address is valid. */
  var IPArray=domain.match(ipDomainPat)
  if (IPArray!=null) {
    // this is an IP address
    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
        return false
      }
    }
    return true
  }

  // Domain is symbolic name
  var domainArray=domain.match(domainPat)
  if (domainArray==null) {
    return false
  }

  /* Now we need to break up the domain to get a count of how many atoms
     it consists of. */
  var atomPat=new RegExp(atom,"g")
  var domArr=domain.match(atomPat)
  var len=domArr.length
  // Make sure there's a host name preceding the domain.
  // Leo: check len first
  if (len<2) {
    var errStr="This address is missing a hostname!"
    return false
  }

  /* domain name seems valid, but now make sure that it ends in a
     three-letter word (like com, edu, gov) or a two-letter word,
     representing country (uk, nl), and that there's a hostname preceding
     the domain or country. Leo: Four-letter word added. (info, name)*/
  if (domArr[domArr.length-1].length<2 ||
      domArr[domArr.length-1].length>4) {
     // the address must end in a two letter or three letter word.
   return false;
  }

  // Leo: check a-z A-Z 0-9 and "-" for every part of domain
  for (var i=0;i<len;i++) {
      if (!domArr[i].match(validDomainParts)) {
          return false;
      }
  }


  // If we've gotten this far, everything's valid!
  return true;
}

function GetFieldVal(theForm, theFieldname, returnEmptyForNull, getNthField)
{
    if (theFieldname == null) return null;
    if (theForm == null) return null;

    var allValues= new Array(); var valueCount=0;
    var fieldFound=0;
    for (var i = 0; i < theForm.elements.length; i++) {
        fld = theForm.elements[i];
        if (fld.name == theFieldname) {
            fieldFound++;
            var fldValue = extractValueFromField(fld);
            //For Nav4, if (fldValue instanceof Array)
            if (!getNthField || getNthField==fieldFound) {
                if (fldValue!=null) {
                    if (isInstanceOf(fldValue, Array))
                        {valueCount+=fldValue.length; allValues=allValues.concat(fldValue);}
                    else
                        {allValues[valueCount]=fldValue; valueCount++;}
                } else if (returnEmptyForNull==true)
                    {allValues[valueCount]=""; valueCount++;}
            }
        }
    }
    if (valueCount==0)
      {if (returnEmptyForNull==true) {return "";} else {return null;}}
    else
    if (valueCount==1)
        return allValues[0];
    else
        return allValues;
//    return (valueCount==0?null:allValues);
/*
    var theField = eval("document." + theForm.name + "." + theFieldname);

    if (theField instanceof Array) { // Array
        alert('Array');
        var allValues= new Array(); var valueCount=0;
        for (var i=0;i<theField.length;i++) {
            var fieldValue = extractValueFromField(theField[i]);
            if (fieldValue instanceof Array) {valueCount+=fieldValue.length; allValues = allValues.concat(fieldValue);}
            else {valueCount++; allValues[allValues.length]=fieldValue;}
        }
        return allValues;
    } else if (theField) {
        return extractValueFromField(theField);
    } else {
        return null;
    }
*/
/*
    for (var i = 0; i < theForm.elements.length; i++) {
        fld = theForm.elements[i];

        if (fld.name == theFieldname) {
            if (fld.type != null) {
                if ((fld.type == "text") || (fld.type == "textarea") ||
                    (fld.type == "hidden") || (fld.type == "password") ||
                    (fld.type == "file"))
                    {return fld.value;}
                else if ((fld.type == "checkbox" || fld.type == "radio") && (fld.checked == true))
                    {return fld.value;}
                else if (fld.type == "select-one") {
                    if (fld.options.length > 0) {
                        idx = fld.selectedIndex;
                        if (idx >= 0) return fld.options[idx].value;
                    }
                }
                else if (fld.type == "select-multiple") {
                    var selectetion = new Array();
                    var selectCount = 0;

                    for(var j=0; j < fld.options.length; j++) {
                        if (fld.options[j].selected == true) {
                            selectetion[selectCount] = fld.options[j].value;
                            selectCount++;
                        }
                    }
                    if (selectCount > 0) {
                        return selectetion;
                    }
                }
            }
        }
    }
    return null;
*/
}

function extractValueFromField(fld) {
    if (fld.type != null) {
        if ((fld.type == "text") || (fld.type == "textarea") || (fld.type == "hidden") || (fld.type == "password") || (fld.type == "file"))
            { if (fld.value==null) return ""; else return fld.value;}
        else if ((fld.type == "checkbox" || fld.type == "radio") && (fld.checked == true))
            {return fld.value;}
        else if (fld.type == "select-one")
            {if (fld.options.length > 0) { idx = fld.selectedIndex; if (idx >= 0) {return fld.options[idx].value;}}}
        else if (fld.type == "select-multiple") {
            var selectetion = new Array();
            var selectCount = 0;

            for(var j=0; j < fld.options.length; j++) {
                if (fld.options[j].selected == true) {
                    selectetion[selectCount] = fld.options[j].value;
                    selectCount++;
                }
            }
            if (selectCount > 0) {
                return selectetion;
            }
        }
    }
    return null;
}

// Raymond, check if fields have duplicated value
function checkFieldsDuplicatedValue(theForm, theFieldname, promptIfFound, focusIfFound, fieldsLabel)
{
  var fldValues=null; //var firstFieldname;
  var theFieldValueCount = new Array();
  // Construct value array
  //if (theFieldname instanceof Array) {
  if (isInstanceOf(theFieldname, Array)) {
    fldValues = new Array(); var valueCount=0; //firstFieldname=theFieldname[0];
    for (var i=0;i<theFieldname.length;i++) {
      var oneFieldValue = GetFieldVal(theForm, theFieldname[i]);
      //if (oneFieldValue instanceof Array)
      if (isInstanceOf(oneFieldValue, Array))
        {valueCount+=oneFieldValue.length; fldValues=fldValues.concat(oneFieldValue); theFieldValueCount[i]=oneFieldValue.length;}
      else if (oneFieldValue)
        {fldValues[valueCount]=oneFieldValue; valueCount++; theFieldValueCount[i]=1;}
      else
        theFieldValueCount[i]=0;
    }
  } else {
    var firstFieldname = theFieldname;
    theFieldname = new Array(firstFieldname);
    fldValues = GetFieldVal(theForm, theFieldname);
    if (isInstanceOf(fldValues, Array)) {theFieldValueCount[0]=fldValues.length;}
  }

  if (fieldsLabel==null) fieldsLabel = "";

  //if (fldValues instanceof Array) {
  if (isInstanceOf(fldValues, Array)) {
    // Loop to check for duplicate value
    for (var j=0, fldIdx=0, currFldIdx=1;j+1<fldValues.length;j++, currFldIdx++) {
      // Skip empty
      while (theFieldValueCount[fldIdx]==0) {++fldIdx;}
      // If field change, reset current file index to 1 as restart
      if (theFieldValueCount[fldIdx]<currFldIdx) {currFldIdx = 1; ++fldIdx;}

      for (var k=j+1;k<fldValues.length;k++) {
        if (fldValues[j]==fldValues[k]) {
          var fieldsLabelStr = (isInstanceOf(fieldsLabel, Array)) ? fieldsLabel.join("\n\t") : fieldsLabel;
          if (promptIfFound) alert("Duplicate Value is found.\n\t" + fieldsLabelStr);
          if (focusIfFound) {
            // Locate first duiplcated field
            //setFocusToField(theForm, firstFieldname, j+1);
            setFocusToField(theForm, theFieldname[fldIdx], currFldIdx);
          }
          return false;
        }
      }
    }
  }
  return true;

}


function isSelectedInMultiple(theForm, theFieldname, theFieldValue)
{
    var fld = null;
    if (theFieldname == null) return null;
    if (theForm == null) return null;
    if (theFieldValue == null) return null;

    for (var i = 0; i < theForm.elements.length; i++) {
        fld = theForm.elements[i];
        if (fld.name == theFieldname && fld.type == "select-multiple") {
            for (var j = 0; j < fld.options.length; j++) {
                if (fld.options[j].value == theFieldValue)
                    {return fld.options[j].selected;}
            }
        }
    }

    return null;
}

// CHECK STRING - ENSURE ALL CHARACTERS ARE LETTERS
function toAlpha(checkString)
{
    var newString = "";    // REVISED/CORRECTED STRING
    var count = 0;         // COUNTER FOR LOOPING THROUGH STRING

    // LOOP THROUGH STRING CHARACTER BY CHARACTER
    for (var i = 0; i < checkString.length; i++) {
        var ch = checkString.substring(i, i+1);

        // ENSURE CHARACTER IS AN ALPHA CHARACTER
        if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z" )) {
            newString += ch;
        }
    }

    return newString;
}

function isVaildDate(yr, mth, day)
{
    var vaild=true;

    //basic error checking
    if (mth<1 || mth>12) vaild = false
    if (day<1 || day>31) vaild = false
    if (yr<1000 || yr>2099) vaild = false

    //advanced error checking

    // months with 30 days
    if (mth==4 || mth==6 || mth==9 || mth==11){
	if (day==31) vaild = false
    }

    // february, leap year
    if (mth==2){
	// feb
	var g=parseInt(yr/4)
	if (isNaN(g)) {
	    vaild = false
	}
	if (day>29) vaild = false
	if (day==29 && ((yr/4)!=parseInt(yr/4))) vaild = false
    }

    return vaild;
}

function isVaildTime(aHour, aMinute, aSecond)
{
    var vaild=true;

    //basic error checking
    vaild = isVaildHour(aHour) && isVaildMinute(aMinute) && isVaildSecond(aSecond);

    return vaild;
}

function isVaildHour(aHour)
{
    var vaild=true;

    if (aHour<0 || aHour>23) vaild = false

    return vaild;
}

function isVaildMinute(aMinute)
{
    var vaild=true;

    if (aMinute<0 || aMinute>59) vaild = false

    return vaild;
}

function isVaildSecond(aSecond)
{
    var vaild=true;

    if (aSecond<0 || aSecond>59) vaild = false

    return vaild;
}


//function fillFirstReg(theForm)
//{
//    frmonth = GetFieldVal(theForm, theForm.ad_frmonth.name);
//    fryear = GetFieldVal(theForm, theForm.ad_fryear.name);
//
//    if ((fryear != "" ) && (frmonth != "" ))
//    {
//        theForm.FIRSTREG.value = fryear + '-' + frmonth + "-1";
//    }
//}

function SetFieldVal(theForm, fieldName, vals, setDefault, setNthField) {
     var valOffset=0; var fieldFound=0;
     if (theForm == null || fieldName == null || vals == null) return false;
     for (var i = 0; i < theForm.elements.length; i++) {
          if (theForm.elements[i].name == fieldName) {
               fieldFound++;
               var theField = theForm.elements[i];
               var type = eval("theField.type");
               var val = vals;
               if (!isInstanceOf(vals, String) && isInstanceOf(vals, Array)) val = vals[valOffset++];
               if (type != null && (!setNthField || fieldFound==setNthField)) {
                    if ((type == "text") || (type == "textarea") ||
                        (type == "hidden") || (type == "password") ||
                        (type == "file")) {
                         theField.value = val;
                         if (setDefault) theField.defaultValue = val;
                    } else if (type == "radio") {
                         if (theField.value == val) {
                             theField.checked = true;
                             if (setDefault) theField.defaultChecked = true;
                         } else
                             theField.checked = false;
                    } else if (type == "checkbox") {
                      // Check for Mulitple Checkbox
                      //alert(theForm.elements[fieldName].length);
                      if (theForm.elements[fieldName].length > 1) {
                         //alert(fieldName);
                         for (var j = 0; j < theForm.elements[fieldName].length; j++) {
                           theField = theForm.elements[fieldName][j];
                           //alert(theField.value);
                           if (val == theField.value) {
                             theField.checked = true;
                             if (setDefault) theField.defaultChecked = true;
                             break;
                           } else
                             theField.checked = false;
                         }
                      } else {
                         //alert(theField.name);
                         // theField.checked = (val != "")? true:false;
                           if (val == theField.value) {
                             theField.checked = true;
                             if (setDefault) theField.defaultChecked = true;
                           } else
                             theField.checked = false;
                      }
                    } else if ((type == "select-one") || (type == "select-multiple")) {
                         for(var j=0; j < theField.length; j++) {
                              if (theField.options[j].value == val) {
                                   theField.options[j].selected = true;
                                   if (setDefault) theField.options[j].defaultSelected = true;
                              }
                         }
                    }
               }
          }
     }
     return true;
}

function isFieldsEmpty(frm, fieldName, returnNull)
{
  var valstr = GetFieldVal(frm, fieldName);
  if (valstr == null) {if (returnNull) return null; else return true;}

  //if (valstr instanceof Array) {
  if (isInstanceOf(valstr, Array)) {
      for (var i=0;i<valstr.length;i++) {if (trimstr(valstr[i])=="") return true;}
      return false;
  }

  if (typeof valstr == 'object') valstr = valstr.toString();
  valstr = trimstr(valstr);
  return (valstr == "");
}

function setFocusToField(theForm, theFieldname, nthField)
{
    var fld = null; var lastFound = null;
    if (theFieldname == null) return;
    if (theForm == null) return;
    if (nthField == null) nthField = 1;


    for (var i = 0, nthFound=0; i < theForm.elements.length; i++) {
        fld = theForm.elements[i];

        if (fld.name == theFieldname && fld.type != null) {
            nthFound++;
            lastFound=fld;
            if (nthFound==nthField) break;
        }
    }
    if (lastFound != null) lastFound.focus();
}

// Vary for different form validation requirement
// Raymond, add support for fields with same field name
function checkRequiredFields(input, requiredFields, fieldNames)
{
    var fieldCheck   = true;
    var fieldsNeeded = MID10201 + "\n\n\t";
    var Notpassed = -1;

    for(var fieldNum=0; fieldNum < requiredFields.length; fieldNum++) {
//        var valstr = GetFieldVal(input, input.elements[requiredFields[fieldNum]].name);
//        var valstr = GetFieldVal(input, requiredFields[fieldNum]);
//        if ((valstr == null) || (valstr == "") || (valstr == " ")) {
        var fempty = isFieldsEmpty(input, requiredFields[fieldNum]);
        if (fempty) {
            fieldsNeeded += fieldNames[fieldNum] + "\n\t";
            if (Notpassed < 0) Notpassed = fieldNum;
            fieldCheck = false;
        }
    }

    // ALL REQUIRED FIELDS HAVE BEEN ENTERED
    if (fieldCheck == true)
    {
        return true;
    }
    // SOME REQUIRED FIELDS ARE MISSING VALUES
    else
    {
        alert(fieldsNeeded);
//        input.elements[requiredFields[Notpassed]].focus();
        setFocusToField(input, requiredFields[Notpassed]);
        return false;
    }
}

// Check if no fields is filled
function isAnyFieldsFilled(input, checkFields, fieldNames)
{
    var filledCount  = 0;
    var fieldsNeeded = MID10202 + "\n\n\t";
    var Notpassed = 0;

    for(var fieldNum=0; filledCount == 0 && fieldNum < checkFields.length; fieldNum++) {
        var valstr = GetFieldVal(input, input.elements[checkFields[fieldNum]].name);
        if ((valstr == "") || (valstr == " ")) {
            fieldsNeeded += fieldNames[fieldNum] + "\n\t";
            if (Notpassed == 0) Notpassed = fieldNum;
        } else {
            filledCount ++;
        }
    }

    // SOME FIELDS HAVE BEEN ENTERED
    if (filledCount > 0)
    {
        return true;
    }
    // SOME REQUIRED FIELDS ARE MISSING VALUES
    else
    {
        alert(fieldsNeeded);
        input.elements[checkFields[Notpassed]].focus();
        return false;
    }
}


//function Validate(form, requiredFields, fieldNames){
//    if (checkRequiredFields(form, requiredFields, fieldNames))
//    {
//            form.submit();
//    }
//}


/* Requried Message ID
MID10001 = "Year must be a 4-digit number\n";
MID10005 = " is invalid\n";
MID10201 = "Please input for mandatory field - ";
MID10202 = "Please input value for at least one field - ";
MID10009 = " must be equal or later than ";
*/

//Check for the date format
function checkDate(theForm, theYearFieldName, theMonthFieldName, theDayFieldName, fieldLabel)
{
    var msg = "";
    var valid = true;
    if (theForm == null)
        return false;
    if (theYearFieldName == null)
        return false;
    if (theMonthFieldName == null)
        return false;
    if (theDayFieldName == null)
        return false;

    var yearValue = GetFieldVal(theForm, theYearFieldName);
    var monthValue = GetFieldVal(theForm, theMonthFieldName);
    var dayValue = GetFieldVal(theForm, theDayFieldName);

    //alert(yearValue + "-" + monthValue + "-" + dayValue);

    // Skip if all empty
    if (((yearValue == "") || (yearValue == " ")) && ((monthValue == "") || (monthValue == " ")) && ((dayValue == "") || (dayValue == " ")))
        return true;

    if (((yearValue == "") || (yearValue == " ")) || ((monthValue == "") || (monthValue == " ")) || ((dayValue == "") || (dayValue == " ")))
        valid = false;

    if (valid==true)
        valid = !isNaN(yearValue.toString());

    if (valid==true)
        valid = !isNaN(monthValue.toString());

    if (valid==true)
        valid = !isNaN(dayValue.toString());

    if (valid==true)
        valid = isVaildDate(yearValue, monthValue, dayValue);

    if (valid==false)
        alert(fieldLabel + MID10005);

    return valid;
}

//Check for the date format
function checkTime(theForm, theHourFieldName, theMinuteFieldName, theSecondFieldName, fieldLabel)
{
    var msg = "";
    var valid = true;
    if (theForm == null)
        return false;
    if (theHourFieldName == null)
        return false;
    if (theMinuteFieldName == null)
        return false;
    if (theSecondFieldName == null)
        return false;

    var hourValue = GetFieldVal(theForm, theHourFieldName);
    var minuteValue = GetFieldVal(theForm, theMinuteFieldName);
    var secondValue = GetFieldVal(theForm, theSecondFieldName);

    // Skip if all empty
    if (((hourValue == "") || (hourValue == " ")) && ((minuteValue == "") || (minuteValue == " ")) && ((secondValue == "") || (secondValue == " ")))
        return true;

    if (((hourValue == "") || (hourValue == " ")) || ((minuteValue == "") || (minuteValue == " ")) || ((secondValue == "") || (secondValue == " ")))
        valid = false;

    if (valid==true)
        valid = !isNaN(hourValue.toString());

    if (valid==true)
        valid = !isNaN(minuteValue.toString());

    if (valid==true)
        valid = !isNaN(secondValue.toString());

    if (valid==true)
        valid = isVaildTime(hourValue, minuteValue, secondValue);

    if (valid==false)
        alert(fieldLabel + MID10005);

    return valid;
}


//Check for the date range
function checkDateRange(theForm, theYearFromFieldName, theMonthFromFieldName, theDayFromFieldName,
                                 theYearToFieldName, theMonthToFieldName, theDayToFieldName,
                                 fromFieldLabel, toFieldLabel, allowOpenStart, allowOpenEnd)
{
    var valid = true;
    if (theForm == null)
        return false;
    if (theDayFromFieldName == null)
        return false;
    if (theMonthFromFieldName == null)
        return false;
    if (theYearFromFieldName == null)
        return false;
    if (theDayToFieldName == null)
        return false;
    if (theMonthToFieldName == null)
        return false;
    if (theYearToFieldName == null)
        return false;

    var theYearFromValue = GetFieldVal(theForm, theYearFromFieldName);
    var theMonthFromValue = GetFieldVal(theForm, theMonthFromFieldName);
    var theDayFromValue = GetFieldVal(theForm, theDayFromFieldName);

    var theYearToValue = GetFieldVal(theForm, theYearToFieldName);
    var theMonthToValue = GetFieldVal(theForm, theMonthToFieldName);
    var theDayToValue = GetFieldVal(theForm, theDayToFieldName);

    // Check for open start and end
    var isOpenStart = (((theYearFromValue == "") || (theYearFromValue == " ")) && ((theMonthFromValue == "") || (theMonthFromValue == " ")) && ((theDayFromValue == "") || (theDayFromValue == " ")));
    var isOpenEnd = (((theYearToValue == "") || (theYearToValue == " ")) && ((theMonthToValue == "") || (theMonthToValue == " ")) && ((theDayToValue == "") || (theDayToValue == " ")));
    if (isOpenStart == true && isOpenEnd == true)
        return true;

    if ((isOpenStart && allowOpenStart) || (isOpenEnd && allowOpenEnd))
        return true;

    if (isOpenStart == true || isOpenEnd == true)
        valid = false;


    // Assume date is valid
    if (valid == true) {
        if (theYearFromValue > theYearToValue )
            valid = false;

        if (theYearFromValue == theYearToValue) {
            if (theMonthFromValue > theMonthToValue) {
                valid = false;
            }
            if (theMonthFromValue == theMonthToValue) {
                if (theDayFromValue > theDayToValue)
                    valid = false;
            }
        }
    }

    if (valid == false)
	alert(toFieldLabel + MID10009 + fromFieldLabel);

    return valid;
}
// Leo add start
//Check for the date range
function checkDateRange(theForm, theDateFromFieldName, theDateToFieldName,
                                 fromFieldLabel, toFieldLabel, allowOpenStart, allowOpenEnd)
{
    var valid = true;

    if (theForm == null)
        return false;
    if (theDateFromFieldName == null)
        return false;
    if (theDateToFieldName == null)
        return false;
    if (theDateFromFieldName.value==null || trimstr(theDateFromFieldName.value)=="") {
        if (allowOpenStart==true)
          return true;
        else {
          alert(MID10201 + fromFieldLabel);
          return false;
        }
    }
    if (theDateToFieldName.value==null || trimstr(theDateToFieldName.value)=="") {
        if (allowOpenEnd==true)
          return true;
        else {
          alert(MID10201 + toFieldLabel);
          return false;
        }
    }

    // default format dd/MM/yyyy
    var theYearFromValue = theDateFromFieldName.value.substr(6);
    var theMonthFromValue = theDateFromFieldName.value.substr(3,2);
    var theDayFromValue = theDateFromFieldName.value.substr(0,2);

    var theYearToValue = theDateToFieldName.value.substr(6);
    var theMonthToValue = theDateToFieldName.value.substr(3,2);
    var theDayToValue = theDateToFieldName.value.substr(0,2);

    // Assume date is valid
    if (valid == true) {
        if (theYearFromValue > theYearToValue )
            valid = false;

        if (theYearFromValue == theYearToValue) {
            if (theMonthFromValue > theMonthToValue) {
                valid = false;
            }
            if (theMonthFromValue == theMonthToValue) {
                if (theDayFromValue > theDayToValue)
                    valid = false;
            }
        }
    }

    if (valid == false) {
	    alert(toFieldLabel + MID10009 + fromFieldLabel);
	  }

    return valid;
}
// Leo add end
function constructFormPostTimestamp(aYear, aMonth, aDay, aHour, aMinute, aSecond, aNano) {
    // Construct Timestamp in format : yyyy-mm-dd hh:mm:ss.fffffffff

    //if (aMonth < 10) {aMonth = "0" + aMonth; }
    //if (aDay < 10) { aDay = "0" + aDay; }
    //if (aHour < 10) { aHour = "0" + aHour; }
    //if (aMinute < 10) { aMinute = "0" + aMinute; }
    //if (aSecond < 10) { aSecond = "0" + aSecond; }

    return (aYear + "-" + aMonth + "-" + aDay + " " + aHour + ":" + aMinute + ":" + aSecond + "." + aNano);
}

function constructFormPostDate(aYear, aMonth, aDay) {
    return (aYear + "-" + aMonth + "-" + aDay);
}

function isValidNumeric(aForm, aFieldName) {
    return isValidNumeric(aForm, aFieldName, null, null);
}

//-write by kikin-
//A funtion to check whether the numeric input is valid.
//The parameter aValidDigits is the valid digits numbers after decimal point.
//Not test yet!

function isValidNumeric(aForm, aFieldName, aAccuDigits) {

//    var aNumeric = GetFieldVal(aForm, aFieldName);
//    var valid = true;
//    var dotPosition = -1;
//    var AccuDigitsNum = 0;
//
//    for (var i = 0; i < aNumeric.length; i++) {
//        var ch = aNumeric.substring(i, i+1);
//
//        if (!(ch >= "0" && ch <= "9") || (ch =="." )) {
//            valid = false;
//            return valid;
//        }
//        if(ch == "." ) {
//            if (dotPosition > -1){
//                valid = false;
//                return valid;
//	    }
//            dotPosition = i;
//        }
//    }
//
//    AccuDigitsNum = aNumeric.length - dotPosition
//    if( AccuDigitsNum != aAccuDigits) {
//         valid = false;
//    }
//    return valid;

    return isValidNumeric(aForm, aFieldName, null, aAccuDigits);
}

// check if the amount in the field is valie
// maximum integer length = 11, maximum field length = 4
function isValidAmount(aForm, aFieldName){
    return isValidNumeric(aForm, aFieldName, 11, 4);
}

//maxIntLen - maximum len of the integer potion
//maxFractionLen - maximum len of the fraction portion
function isValidNumeric(aForm, aFieldName, maxIntLen, maxFractionLen) {
    var aNumeric = GetFieldVal(aForm, aFieldName);
    var dotPosition = -1; // no period
    var AccuFractionNum = 0;
    var AccuIntNum = 0;

    for (var i = 0; i < aNumeric.length; i++) {
        var ch = aNumeric.substring(i, i+1);

        if (!((ch >= '0' && ch <= '9') || (ch =='.' ))) {
            return false;
        }
        if(ch == "." ) {
            if (dotPosition > -1){
                return false; // more than 1 digit found
	    }
            dotPosition = i;
        }
    }
	if (maxFractionLen ==0 && dotPosition >-1) {
        return false;
	}
    // check fraction length
    if (maxFractionLen != null && dotPosition > -1){
	    AccuFractionNum = aNumeric.length - dotPosition - 1
	    if( AccuFractionNum > maxFractionLen) {
        	 return false;
	    }
    }
    else if(maxFractionLen == null && dotPosition > -1)
            return false;


    // check integer length
    if (dotPosition == -1)
        AccuIntNum = aNumeric.length;
    else
        AccuIntNum = dotPosition;
    if (maxIntLen != null && AccuIntNum > maxIntLen){
        return false;
    }

    return true;
}

// Popup Fuction
function findForm(formName) {
    var found = null;
    for (var i=0; i < document.forms.length && found == null; i++) {
    	if (document.forms[i].name == formName) {
            found = document.forms[i];
    	}
    }
    //alert(found.name);
    return found;
}
function openPopupWin(url, win_id, wid, hei){
    if (hei == null) {
        hei = getWorkspaceHeight();
    }
    if (wid == null) {
        wid = getWorkspaceWidth();
    }
    if (window.showModelessDialog) {
	// for IE5
    	var WinName = showModelessDialog(url, window, 'dialogHeight:' + hei + 'px;dialogWidth:' + wid + 'px');
    }
    else if (window.showModalDialog) {
	// for IE4
    	var WinName = showModalDialog(url, window, 'dialogHeight:' + hei + 'px;dialogWidth:' + wid + 'px');
    }
    else if (navigator.userAgent.substring(0,9) != "Mozilla/2") {
        //3.0 and above
	var WinName = window.open(url, win_id ,'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,copyhistory=0,width=' + wid + ' ,height=' +hei );
    }
    else if (window.name == "netobjects_main_power") {
        //2.0 re-entry position - main window already have name
	var WinName = window.open(url,'netobjects_nav','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,copyhistory=0,width=' + wid + ' ,height=' +hei );
    }
    else {
	var WinName = window.open(url, win_id,'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,copyhistory=0,width=' + wid + ' ,height=' +hei );
    }
}

// Popup Fuction for Popup
function IsIEPopup() {
    return (window.dialogArguments && window.dialogArguments.self);
}

function getPopupOpener() {
    if (window.opener) {
    	return window.opener;
    }
    else if (window.dialogArguments && window.dialogArguments.self) {
        //IE5/4 where opener is pass in as dialogArguments
        return window.dialogArguments;
    }

}

function returnFormToOpener(toOpenerFormName, fromFormName) {
    var fromForm = findForm(fromFormName);
    var fieldNames = new Array();
    var fieldValues = new Array();

    for (var i=0; i < fromForm.elements.length; i++) {
    	var formElement = fromForm.elements[i];
    	fieldNames[i] = formElement.name;
    	fieldValues[i] = GetFieldVal(fromForm, formElement.name);
    }
    returnFieldValuesToOpener(toOpenerFormName, fieldNames, fieldValues);
}

function returnFormFieldsToOpener(toOpenerFormName, fromFormName, fieldNames) {
    var fromForm = findForm(fromFormName);
    var fieldValues = new Array();

    for (var i=0; i < fieldNames.length; i++) {
    	fieldValues[i] = GetFieldVal(fromForm, fieldNames[i]);
    }
    returnFieldValuesToOpener(toOpenerFormName, fieldNames, fieldValues);
}

function returnFieldValuesToOpener(toOpenerFormName, fieldNames, fieldValues) {
    var popupOpener = getPopupOpener();

    if (popupOpener) {
        popupOpener.setFiledValuesByPopup(toOpenerFormName, fieldNames, fieldValues);
    }
    window.close();
}

function fillFormFieldsFromOpener(fromOpenerFormName, toFormName, fieldNames) {
    var popupOpener = getPopupOpener();
    var fieldValues = popupOpener.getFieldValuesForPopup(fromOpenerFormName, fieldNames);
    var setToForm = findForm(toFormName);
//    var debugmsg = "fillFormFieldsFromOpener from " + fromOpenerFormName + " to " + toFormName + " with field : ";

    for (var i=0; i < fieldNames.length; i++) {
//    	debugmsg += fieldNames[i] + " = " + fieldValues[i] + " ";
    	SetFieldVal(setToForm, fieldNames[i], fieldValues[i]);
    }
//    debugmsg += " Length = " + fieldNames.length;
//    alert(debugmsg);
}

function fillFormFromOpener(fromOpenerFormName, toFormName) {
    var setToForm = findForm(toFormName);
    var fieldNames = new Array();

    for (var i=0; i < setToForm.elements.length; i++) {
    	fieldNames[i] = fromForm.elements[i].name;
    }

    fillFormFieldsFromOpener(fromOpenerFormName, toFormName, fieldNames);
}

// Popup Fuction for Opener

function setFiledValuesByPopup(fieldNames, fieldValues) {
    setFiledValuesByPopup(document.forms[0].name, fieldNames, fieldValues);
}

function setFiledValuesByPopup(formName, fieldNames, fieldValues) {
    var setToForm = findForm(formName);

    for (var i=0; i < fieldNames.length; i++) {
    	SetFieldVal(setToForm, fieldNames[i], fieldValues[i]);
    }
}

function getFieldValuesForPopup(fromFormName, fieldNames) {
    var fromForm = findForm(fromFormName);
    var fieldValues = new Array();
//    var debugmsg = "getFieldValuesForPopup from " + fromFormName + " with field : ";

    for (var i=0; i < fieldNames.length; i++) {
    	fieldValues[i] = GetFieldVal(fromForm, fieldNames[i]);
//    	debugmsg += fieldNames[i] + " = " + fieldValues[i] + " ";
    }
//    debugmsg += " Length = " + fieldNames.length;
//    alert(debugmsg);
    return fieldValues;
}

var scrollbarOffset = 10; // Scrollbar width/height for Nav to offset

function getWorkspaceHeight() {
  var lworkspaceHeight;

  if (window.innerHeight) {
    lworkspaceHeight = window.innerHeight;
    // detect scrollbar is shown and adjust for Nav
    if (document.width > window.innerWidth) {lworkspaceHeight -= scrollbarOffset;}
  } else {
    lworkspaceHeight = document.body.clientHeight;
  }
  return lworkspaceHeight;
}

function getWorkspaceWidth() {
  var lworkspaceWidth;

  if (window.innerWidth) {
    lworkspaceWidth= window.innerWidth;
    // detect scrollbar is shown and adjust for Nav
    if (document.height > window.innerHeight) {lworkspaceWidth -= scrollbarOffset;}
  } else {
    lworkspaceWidth = document.body.clientWidth;
  }
  return lworkspaceWidth;
}

// To use in Select tag : onChange="fillSelectFromArray(this.form.?, ((this.selectedIndex == -1) ? null : team[this.selectedIndex-1]));"
// itemArrary is Array of 2 element Array, first element is Option Text nad 2nd is Option Value
function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem, defaultItemValue) {
  var i, j;
  var prompt;
  // empty existing items
  //for (i = selectCtrl.options.length; i >= 0; i--) {
  //  selectCtrl.options[i] = null;
  //}
  selectCtrl.options.length = 0;

  prompt = (itemArray != null) ? goodPrompt : badPrompt;
  if (prompt == null) {
    j = 0;
  }
  else {
    selectCtrl.options[0] = new Option(prompt);
    j = 1;
  }

  // No default if not specified
  if (defaultItem == null) defaultItem = -1;

  if (itemArray != null) {
    // add new items
    for (i = 0; i < itemArray.length; i++) {
      selectCtrl.options[j] = new Option(itemArray[i][0], itemArray[i][1]);
      if (i==defaultItem || (defaultItemValue && itemArray[i][1]==defaultItemValue)) { selectCtrl.options[j].selected = true; selectCtrl.options[j].defaultSelected = true; }
//      selectCtrl.options[j] = new Option(itemArray[i][0]);
//      if (itemArray[i][1] != null) {
//        selectCtrl.options[j].value = itemArray[i][1];
//      }
      j++;
    }
  }
}

function isValidAlphaNumeric(val) {
	var i;
	var temp_char;
	for (i=0;i<val.length; i++) {
		temp_char = val.substr(i,1);
		if (!((temp_char >= "0" && temp_char <="9") || (temp_char >= "A" && temp_char <= "Z") || (temp_char >= "a" && temp_char <= "z"))) {
			return false;
		}
	}
	return true;
}

function checkWordLength(aForm, aField, start, end){
        var aValue = GetFieldVal(aForm, aField);

        if(start == null){
            if(aValue.length < end)
                  return false;
            else{
                  return noSpaceAllowed(aValue);
                  }

        }
        else {// start != null
            if(!(aValue.length >= start && aValue.length <= end))
                  {return false;}
            else{
                  return noSpaceAllowed(aValue);
                  }
        }
}

function noSpaceAllowed(aFieldValue){
    for (var i = 0; i < aFieldValue.length; i++) {
           var ch = aFieldValue.substring(i, i+1);

          if (ch == ' ')
            {return false;}

        }//end for
    return true;
}

function isInstanceOf(obj, proto) {
  if (document.all) return (eval("obj instanceof proto"));
  while (obj != null) {
    if (obj == proto.prototype)
      return true;
    else
      obj = obj.__proto__;
  }
  return false;
}

function GetField(theForm, theFieldname, getNthField)
{
    if (theFieldname == null) return null;
    if (theForm == null) return null;

    var allFlds= new Array(); var fldCount=0;
    var fieldFound=0;
    for (var i = 0; i < theForm.elements.length; i++) {
        fld = theForm.elements[i];
        if (fld.name == theFieldname) {
            fieldFound++;
            if (!getNthField || getNthField==fieldFound) {
                allFlds[fldCount]=fld; fldCount++;
                if (getNthField) break;
            }
        }
    }
    if (fldCount==0)
      return null;
    else
    if (fldCount==1)
        return allFlds[0];
    else
        return allFlds;
}

