function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0)
			return true;
	}
	else {
		if ((intYear % 4) == 0)
			return true;
	}
	return false;
}

function validDay( intYear, intMonth, intDay ) {
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 ||
       	 intMonth == 7 || intMonth == 8 || intMonth == 10 ||
		 intMonth == 12) && (intDay > 31 || intDay < 1)) {
        return false;
    }

	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 ||
    	intMonth == 11) && (intDay > 30 || intDay < 1)) {
        return false;
    }

    if (intMonth == 2) {
    	if (intDay < 1) {
        	return false;
        }
        if (LeapYear(intYear) == true) {
        	if (intDay > 29) {
                return false;
            }
        }
        else {
        	if (intDay > 28) {
                return false;
            }
        }
    }

	return true;
}

/* return false only if the later day is not after the former day */
function dayAfterDay ( formerDay, laterDay, deLimiter ) {

	/* start day should be <= end day */
	if( formerDay.length > 0 && laterDay.length > 0 ) {
	strStartDate = formerDay.split(deLimiter);
	intStartDateYear = parseInt(strStartDate[0]);
	intStartDateMonth = parseInt(strStartDate[1])-1;
	intStartDateDay = parseInt(strStartDate[2]);
	startDate = new Date(intStartDateYear, intStartDateMonth, intStartDateDay);

	strExpiryDate = laterDay.split(deLimiter);
	intExpiryDateYear = parseInt(strExpiryDate[0]);
	intExpiryDateMonth = parseInt(strExpiryDate[1])-1;
	intExpiryDateDay = parseInt(strExpiryDate[2]);
	expiryDate = new Date(intExpiryDateYear, intExpiryDateMonth, intExpiryDateDay);

	if( isNaN(startDate) || isNaN(expiryDate) ){
		/* should use DateFormat to check more, true will be returned */
	} else if( expiryDate.getTime() - startDate.getTime() < 0 ) {
        return false;
    }
    }

	return true;
}

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;
}

/* get the value of the field from the field name,
   trim it at the same time */
function getFieldValue( theForm, fieldName ) {
    for( var i = 0; i < theForm.elements.length; i++ ) {
        if( theForm.elements[i].name == fieldName ) {
	        theForm.elements[i].value = trimstr(theForm.elements[i].value);
        	return theForm.elements[i].value;
		}
    }
    return null;
}

/* get the first field from the field name */
function getField( theForm, fieldName ) {
    for( var i = 0; i < theForm.elements.length; i++ ) {
        if( theForm.elements[i].name == fieldName ) {
        	return theForm.elements[i];
		}
    }
    return null;
}

/* get the array of field from the field name */
function getArrayField( theForm, fieldName ) {
	result = new Array();
    for( var i = 0; i < theForm.elements.length; i++ ) {
        if( theForm.elements[i].name == fieldName ) {
	        theForm.elements[i].value = trimstr(theForm.elements[i].value);
        	result.push(theForm.elements[i]);
		}
    }
    return result;
}

/* set the value of the field accroding from the field name,
   trim it at the same time */
function setFieldValue( theForm, fieldName, value ) {
    for( var i = 0; i < theForm.elements.length; i++ ) {
        if( theForm.elements[i].name == fieldName ) {
	        theForm.elements[i].value = trimstr(value);
		}
    }
    return null;
}

function validPhone( phoneNumber ) {
	var accept = "0123456789- ()";
   for( var i = 0; i < phoneNumber.length; i++ ) {
        if( accept.indexOf(phoneNumber.substring(i,i+1)) <0 )
        	return false;
	}
    return true;
}

function validUserId( userId ) {
	var accept = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
   for( var i = 0; i < userId.length; i++ ) {
        if( accept.indexOf(userId.substring(i,i+1)) <0 )
        	return false;
	}
    return true;
}

function validNickName( nickName ) {
	var notAccept = "`~!@#$%^&*()_+-=[]\\{}|;':\",./<>? ";
   for( var i = 0; i < notAccept.length; i++ ) {
        if( nickName.indexOf(notAccept.substring(i,i+1))>=0 )
        	return false;
	}
    return true;
}

/* Raymond 2006-06-19 */
function isDayAfterDay( aYear, aMonth, aDay, bYear, bMonth, bDay) {
    if( aYear < bYear) {
      return false;
    }
	else if( aYear == bYear ) {
		if( aMonth == bMonth ) {
            if( aDay <= bDay ) {
                return false;
			}
        }
        else if ( aMonth < bMonth ) {
            return false;
		}
	}
	return true;
}

function isEmpty(theForm, fieldName, errorMsg) {
	if(getFieldValue( theForm, fieldName).length==0) {
		if (errorMsg!=null && errorMsg.length>0 ) {
			alert( errorMsg ); 
    		var focusOn = getField( theForm, fieldName );
    		// 2007-03-26, Raymond, avoid IE error
    		if (focusOn.type != "hidden") focusOn.focus();
		}
		return true;
	}
	return false;
}

function validPwd(theForm, fieldN, emptyMsg, minLen, minLenMsg) {
	var loginPwd = getFieldValue( theForm, fieldN);
	
    if( loginPwd.length == 0) {
		if (emptyMsg.length>0) alert( emptyMsg );
	    var focusOn = getField( theForm, fieldN);
		focusOn.focus();
		return false;
   	}
    if( loginPwd.length < minLen ) {
    	if (minLenMsg.length>0) alert( minLenMsg );
	    var focusOn = getField( theForm, fieldN);
		focusOn.focus();
       	return false;
	}
	return true;
}

function validPwdNRetype(theForm, fieldN, retypeF, emptyMsg, minLen, minLenMsg, unmatchMsg) {
	if (validPwd(theForm, fieldN, emptyMsg, minLen, minLenMsg)) {
		var loginPwd = getFieldValue( theForm, fieldN);
		var retypePwd = getFieldValue( theForm, retypeF);
       // password same as passwordretype
    	if( loginPwd != retypePwd ) {
			if (unmatchMsg.length>0) alert( unmatchMsg );
	    	var focusOn = getField( theForm, retypeF );
			focusOn.focus();
			return false;
		}
    } else {
    	return false;
    }
    return true;
}

function validLoginId(theForm, fieldN, emptyMsg, minLen, minLenMsg, maxLen, maxLenMsg, contentMsg) {
    var loginId = getFieldValue( theForm, fieldN );
    var focusOn = getField( theForm, fieldN );

    if( loginId.length == 0) {
        if (emptyMsg.length>0) alert( emptyMsg );
		focusOn.focus();
        return false;
    }

    if( loginId.length < minLen ) {
		if (minLenMsg.length>0) alert( minLenMsg );
		focusOn.focus();
       	return false;
	}

    if( loginId.length > maxLen ) {
		if (maxLenMsg.length>0) alert( maxLenMsg );
		focusOn.focus();
       	return false;
	}
	
    if( !validUserId(loginId) ) {
		if (contentMsg.length>0) alert( contentMsg );
		focusOn.focus();
       	return false;
    }
    
    return true;
}

function validName(theForm, fieldN, emptyMsg, minLen, minLenMsg, maxLen, maxLenMsg) {
    var fieldValue = getFieldValue( theForm, fieldN );
    var focusOn = getField( theForm, fieldN );

    if( fieldValue.length == 0) {
        if (emptyMsg.length>0) alert( emptyMsg );
		focusOn.focus();
        return false;
    }

    if( fieldValue.length < minLen ) {
		if (minLenMsg.length>0) alert( minLenMsg );
		focusOn.focus();
       	return false;
	}

    if( fieldValue.length > maxLen ) {
		if (maxLenMsg.length>0) alert( maxLenMsg );
		focusOn.focus();
       	return false;
	}
	
    return true;
}

function prefixF( prefixStr, fieldArray ) {
    for( var i = 0; i < fieldArray.length; i++ ) {
        //alert("fieldArray[i].name = " + fieldArray[i].name);
        fieldArray[i].name = prefixStr + fieldArray[i].name;
        //alert("fieldArray[i].name = " + fieldArray[i].name);
    }
}

//Check if year-month-day selection is valid and filled
function isDateSelectionValid(theForm, mandatory, mandatoryMsg, yearFn, monthFn, dayFn, invalidMsg, dateFn, seperator, timeFn) {
	var empty = false;
	if (dateFn.length>0) setFieldValue( theForm, dateFn, "");
	if (!mandatory) mandatoryMsg = "";
	if (isEmpty(theForm, yearFn, mandatoryMsg)) return !mandatory;
	if (isEmpty(theForm, monthFn, mandatoryMsg)) return !mandatory;
	if (isEmpty(theForm, dayFn, mandatoryMsg)) return !mandatory;
	
	var yearValue = parseInt(getFieldValue( theForm, yearFn ));
	var monthValue = parseInt(getFieldValue( theForm, monthFn ));
	var dayValue = parseInt(getFieldValue( theForm, dayFn ));
	if( !validDay( yearValue, monthValue, dayValue ) ) {
    	if (invalidMsg.length>0) alert( invalidMsg );
   	    var focusOn = getField( theForm, yearFn );
		focusOn.focus();
		return false;
	}
	if (dateFn.length>0) {
	    var dateValue = yearValue+seperator+monthValue+seperator+dayValue;
	    if (timeFn.length>0) {
	    	var timeValue = getFieldValue( theForm, timeFn );
		    if (timeValue.length>0) dateValue += " " + timeValue;
	    }
	    setFieldValue( theForm, dateFn, dateValue);
	}
	//alert(getFieldValue( theForm, dateFn ));
	return true
}

function validEmail(emailForm, emailField, emptyMsg, invalidMsg) {

	var email = getFieldValue( emailForm, emailField );
    /* valid email*/
  	if( email.length == 0 ) {
		if (emptyMsg.length>0) alert( emptyMsg );
        var focusOn = getField( emailForm, emailField );
		focusOn.focus();
		return false;
   	} else {
    	if( validateEmail( email ) == false ) {
			if (invalidMsg.length>0) alert( invalidMsg );
        	var focusOn = getField( emailForm, emailField );
			focusOn.focus();
			return false;
		}
	}
	return true;
}

function isEmptyDate(theForm, yearF, monthF, dayF, errorMsg) {
    if (isEmpty(theForm, yearF, errorMsg))
		return true;
    if (isEmpty(theForm, monthF, errorMsg))
		return true;
    if (isEmpty(theForm, dayF, errorMsg))
		return true;
	return false;
}

function isValidDateFields(theForm, yearF, monthF, dayF, invalidMsg, checkEmpty) {
	if (checkEmpty==true) {
	    if (isEmpty(theForm, yearF, invalidMsg))
			return false;
	    if (isEmpty(theForm, monthF, invalidMsg))
			return false;
	    if (isEmpty(theForm, dayF, invalidMsg))
			return false;
	}
    var intYear = parseInt(getFieldValue( theForm, yearF ));
    var intMonth = parseInt(getFieldValue( theForm, monthF ));
    var intDay = parseInt(getFieldValue( theForm, dayF ));
    if( !validDay( intYear, intMonth, intDay ) ) {
        if (invalidMsg.length>0) alert( invalidMsg );
        var focusOn = getField( theForm, dayF );
        focusOn.focus();
        return false;
    }
    return true;
}

function setDateField(theForm, dateF, yearF, monthF, dayF, delimiter, timeF) {
	var year = getFieldValue( theForm, yearF );
	var month = getFieldValue( theForm, monthF );
	var day = getFieldValue( theForm, dayF );
	var value = year + delimiter + month + delimiter + day;
	if (timeF.length>0) {
		var timeValue = getFieldValue( theForm, timeF );
		if (timeValue.length>0) value += " " + timeValue;
	}
    setFieldValue( theForm, dateF, value);
}

function shiftFields( theForm, fieldNArray ) {
	var size = fieldNArray.length;
	var values = new Array();
    for( var i = 0; i < size; i++ ) {
    	var value = getFieldValue( theForm, fieldNArray[i]);
    	if (value.length>0) values.push(value);
    }

    for( var i = 0; i < size; i++ ) 
    	if (i < values.length )
    		setFieldValue( theForm, fieldNArray[i], values[i] );
    	else
    		setFieldValue( theForm, fieldNArray[i], "" );
}
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 setFieldVal(theForm, fieldName, val, setDefault) {
     if (theForm == null || fieldName == null || val == null) return false;
     for (var i = 0; i < theForm.elements.length; i++) {
          if (theForm.elements[i].name == fieldName) {
               var theField = theForm.elements[i];
               var type = eval("theField.type");
               if (type != null) {
                    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.selectedIndex=j;
                                   theField.options[j].selected = true;
                                   if (setDefault) theField.options[j].defaultSelected = true;
                              } else {
                                   theField.options[j].selected = false;
                                   if (setDefault) theField.options[j].defaultSelected = false;
                              }
                         }
                    }
               }
          }
     }
     return true;
}

function setYMDField(theForm, datetimeF, yearF, monthF, dayF, delimiter, setDefault) {
    	var datetimeVal = getFieldValue( theForm, datetimeF );
    	var values = (datetimeVal.split(" ")[0]).split(delimiter);
    	setFieldVal(theForm, yearF, values[0], setDefault); 
    	setFieldVal(theForm, monthF, values[1], setDefault);
    	setFieldVal(theForm, dayF, values[2], setDefault);
}


