 
//* =============================================================
//To apply this validatation and confirmation , document must have two things;
//1. The form tag must have onsubmit event to point the function
//	for example : <FORM Method=post name=frmValidate id=frmValidate action=index.htm onSubmit="return CheckDataAction()">
//	
//2. The document must have two extra functions in javacript; 
//	- checkRequiredField()
//		use for checking wheather the mandatory fields are filled, return true if all
//		mandatory fields are filled.
//	-validateData()
//		use for checking wheather the field is in the correct data type or format
//	these two function will written by programmers. They can leave blank although they are required.
//	for example to leave blank: function checkRequiredField() {return true}
// =============================================================

var varDataAction;

function checkRequiredTextBox(obj) {
	// only for text box
	
	if (obj.type=="text") {
		if (isNull(obj.value ) || isBlank(obj.value)) {
				alert("This information is required (*) and must not be blank.");
				obj.focus();
				return false;
			}
	}
	return true
	
}

// function the return
function checkIsNumberTextBox(txt) {
	if (!isNumber(txt.value)) {
		alert("Please enter number only.")
		txt.focus();
		txt.select();
		return false
	}
	return true
	
}

function isDate(idate){
	var Tmp;
	var indate = idate;
	return true
   if (indate.indexOf("-")!=-1)   {
       var sdate = indate.split("-");
   }
   else {
       var sdate = indate.split("/") ;       
   }
   sdate.reverse();
  alert(DefaultDateFormat.value)
  if (!(sdate[0].length == 2 || sdate[0].length == 4)){
		alert("Invalid year, it should be either 2 digits or 4 digits!");
		return false;	
   }

    if (DefaultDateFormat.value == "UK") {
		tmp = sdate[0] + "/" + sdate[1] + "/" + sdate[2];
	} else {
		// this for US date format only (mm/dd/yyyy)
		tmp = sdate[2] + "/" + sdate[1] + "/" + sdate[0];
	}
  var chkDate=new Date(Date.parse(tmp));
   if(sdate[0].length==4){
		
		var cmpDate=(chkDate.getDate())+"/"+(chkDate.getMonth()+1)+"/"+(chkDate.getFullYear());
		
		 if (DefaultDateFormat.value == "UK") {
		var indate2=(Math.abs(sdate[2]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[0])) ;
			} else {
		//this for US date format only
		var indate2=(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))+"/"+(Math.abs(sdate[0])) ;}
		}
   else{
		var cmpDate=(chkDate.getDate())+"/"+(chkDate.getMonth()+1)+"/"+(chkDate.getYear());
		
		if (DefaultDateFormat.value == "UK") {
			var indate2=(Math.abs(sdate[2]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[0])) ;
		} else {
		//THis for US date format only
		var indate2=(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))+"/"+(Math.abs(sdate[0])) ;  
		}
	}
		

   if (indate2!=cmpDate){
        alert("You've entered an invalid date or date format. Please use the DD/MM/YYYY format.");
        return false;
	}
	for(tmp=0;tmp<3;tmp++){
	if (!isInt(sdate[tmp])){
		alert("You've entered an invalid date or date format. Please use the DD/MM/YYYY format.");
        return false;
	}}
	alert(cmpDate)
	 return true	
}

// age is above 16, for DOB of the employee in particular only
// return true if above 16
function isAboveAge16(vDate) {

	var strDate = vDate;
	var arrDate = strDate.split("/");
	var today = new Date();
	try 
	{
		if (DefaultDateFormat.value == "UK") {
			var date = new Date(arrDate[2],arrDate[1],arrDate[0]);
		} else {
			var date = new Date(arrDate[2],arrDate[0],arrDate[1]);
		}
	
	} catch (e) {
		alert("Invalid date type!");
		return false;
	}
	

	if ((today.getFullYear() - date.getFullYear()) >= 16)
		return true
	else
		return false
}
function strtodate(tmp){
	var indate = tmp;
	var sdate = indate.split("/") ;
	
	sdate.reverse();
	if (sdate[0] < 50) {
		sdate[0] = parseInt(sdate[0]) + 2000;
	
	}
	if (DefaultDateFormat.value == "UK") {
		stmp = sdate[0] + "/" + sdate[1] + "/" + sdate[2];
	} else {
		//this for US date format only
		stmp = sdate[0] + "/" + sdate[2] + "/" + sdate[1];
	}
	return stmp;
}

function isInt(str) {
	var i
	mychar = str.charAt(0)
	if ((mychar < "0" || mychar > "9") && mychar != "-")
		return false
	
	for (i = 1; i < str.length; i++) {
		mychar = str.charAt(i);
		if (mychar < "0" || mychar > "9")
			return false
	}
	return true
}

function isSignNumber(str) {
	var numdecs;
	var i = 0;
	mychar = str.charAt(0)
	if ((mychar < "0" || mychar > "9") && mychar != "-")
		return false

	for (i = 1; i < str.length; i++) {
		mychar = str.charAt(i)
		if ((mychar >= "0" && mychar <= "9") || mychar == ".") {
			if (mychar == ".")
				numdecs++
		}
		else 
			return false
	}
//	if (numdecs > 1)
//		return false	
return true
}


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function CheckDataAction(TheForm) { 
	//alert(varDataAction)
	if (varDataAction == "Cancel") return true
	
	if (varDataAction == "Delete")
		return confirm("Are you sure you want to delete this record?");
	try {
		if (!checkRequiredField())
			return false;
	} catch(e) {
		alert("Error on javaScript\n" + e.description)
		return false;
	}
		
	try {
		if (validateData()) {
			if (varDataAction == "Submit")
				return confirm("Are you sure you want to submit this form?");
			else if (varDataAction == "Update")
				return confirm("Are you sure you want to update this record?");
		}
		else
			return false;	
	} catch(e) {
		alert("Error on javaScript\n" + e.description)
		return false;
	}
	
}

function assignAction(){
	var srcElement;
	srcElement = window.event.srcElement;
	if (srcElement.name == "DataAction") {
		switch (srcElement.value) {
		case "Delete":
			varDataAction = "Delete";
			break;
		case "Save&Next":
			varDataAction = "Update";
			break;
		case "Save&Back":
			varDataAction = "Update";
			break;			
		case "Update":
			varDataAction = "Update";
			break;
		case "Submit":
			varDataAction = "Submit";
			break;
		case "Cancel":
			varDataAction = "Cancel";
			break;
		}
	}
	
}
document.onclick = assignAction;

//javacript for data validation
function isAlphabet(str) {
	var isvalid = true;
	str += "";
  	for (i = 0; i < str.length; i++) {
		if ( !( ((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
      			((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) ) ) 
			{
         		isvalid = false;
         		break;
      		}
   	} 
	return isvalid;
}  

//check if conatains only alphanumeric character
function isAlphanumeric(str) {
	str += "";
	for (i = 0; i < str.length; i++) {
	// Alphanumeric must be between "0"-"9", "A"-"Z", or "a"-"z"
		
     	if (!(((str.charAt(i) >= "0") && (str.charAt(i) <= "9")) || 
     			((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
     			((str.charAt(i) >= "A") && (str.charAt(i) <= "Z"))))
		{
		alert ("The string contains non-alphanumeric character(s)");
		return false
			}
	}
	return true
}

//check if it is empty
function isBlank( str ) {
	var isValid = true;
 	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) != " ") {
			isValid = false;
			}
	}
	return isValid;
}


function isNumber(str) {
	numdecs = 0
	for (i = 0; i < str.length; i++) {
		mychar = str.charAt(i)
		if ((mychar >= "0" && mychar <= "9") || mychar 
			== ".") {
			if (mychar == ".")
				numdecs++
		}
		else 
			return false
	}
	if (numdecs > 1)
		return false	
return true
}

function isInRange(str, num1, num2) {
	var i = parseInt(str)
	return((i >= num1) && (i <= num2))

}
function isNull(str) {
	if (str.length == 0 )
		return true
	else 
		return false
}

function notNull(str) {
	if (str.length == 0 )
		return false
	else 
		return true
}

function notBlank(str) {
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) != " ")
			return true
	}
	return false
}

function isSize(str, size) {
	if (str.length == size) 
		return true
	else
		return false
}

function isTime(itime){
	var Tmp;
	var intime = itime;
   if (intime.indexOf(":")!=-1)   {
		intime = intime + ":00"
       var stime = intime.split(":");
   }
   else {
		intime = intime + ".00"
       var stime = intime.split(".") ;       
   }
   

   if (stime.length < 3)  {
        alert("You've entered an invalid time format(24 hours). Please use the HH:MM format.");
		return false; 
   }
	
   
   if (!(isInt(stime[2]))){
        alert("You've entered an invalid time format(24 hours). Please use the HH:MM format.");
		return false; 
   }
	
   if (stime[0] > 24.1) return false
   if (stime[1] > 60) return false
   if (stime[2] > 60) return false 
   
   tmp = stime[0] + ":" + stime[1] + ":" + stime[2];
   var chkTime=new Date(0,0,0,stime[0],stime[1],stime[2]);
   var cmpTime=(chkTime.getHours())+":"+(chkTime.getMinutes())+":"+(chkTime.getSeconds());
   var intime2=(Math.abs(stime[0]))+":"+(Math.abs(stime[1]))+":"+(Math.abs(stime[2])) ;  
   if (intime2!=cmpTime){
        alert("You've entered an invalid time format(24 hours). Please use the HH:MM format.");
        return false;
	}
	 return true	
}  

function chkDate(vDateFrom, vDateTo) {
	var strDateFrom = vDateFrom
	var strDateTo = vDateTo
	var arrDateFrom =strDateFrom.split("/");
	var arrDateTo = strDateTo.split("/");
	
	try 
	{
	
		if (DefaultDateFormat.value == "UK") {
			var dateFrom = new Date(arrDateFrom[2],arrDateFrom[1],arrDateFrom[0]);
			var dateTo = new Date(arrDateTo[2],arrDateTo[1],arrDateTo[0]);
		} else {
			// this for US Date format only
			var dateFrom = new Date(arrDateFrom[1],arrDateFrom[2],arrDateFrom[0]);
			var dateTo = new Date(arrDateTo[1],arrDateTo[2],arrDateTo[0]);
		}
	
	} catch (e) {
		alert("Invalid date type!");
		return false;
	}
	
	if (dateFrom > dateTo) {
		alert("Invalid 'from date' and 'to Date'! \n 'to date' must after 'from date'.");
		return false
		}
	return true;
}

function emailCheck (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 +")*$")


	/* 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. */
		alert("Invalid Email 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
	    alert("Invalid Email Address")
	    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) {
		        alert("Invalid Email Address")
			return false
		    }
	    }
	    return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Invalid Email Address")
	    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. */

	/* 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
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   alert("Invalid Email Address")
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="Invalid Email Address" 
	   alert(errStr)
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function isIC(iic){
	var i ;
	var inic = iic;
   if (inic.indexOf("-")!=-1) 
       var sic = inic.split("-");
   else {
		alert("You've entered an invalid ic format. Please use this format xxxxxx-xx-xxxx");
		return false;
   }
  for ( i=0; i<=2;i++)
		if (!isInt(sic[i])){
		 alert("Please key in integer"); 
		 return false; }
	if (!((sic[0].length == 6 && sic[1].length == 2) && sic[2].length == 4)){ 
		alert("You've entered an invalid ic format. Please use this format xxxxxx-xx-xxxx");
		return false;}
 
return true;
}

function quoteCheck(str){
	var mycode = new String(str);
	var SearchSpace = mycode.indexOf("'");
	if (SearchSpace > -1){
		alert("This symbol is not allowed in this field. ' ");
		return false ;
	}
		
	var SearchSpace = mycode.indexOf(" ");
	if (SearchSpace > -1){
		alert("No space is allow in this field.");
		return false ;
	}
	
	var SearchSpace = mycode.indexOf('"');
	if (SearchSpace > -1){
		alert("This symbol is not allowed in this field.  ");
		return false ;
	}	
	
	return true;

}

//Added by MH LEE (01 March 2004)
function isCurrency(p_objName, p_intDecimalPoint)
{

	var nNum = 0;			// Total numbers for currency value.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var txtLen;				// Length of string passed.
	var decPos;				// Assigned value of numbers or positions after decimal point.
	var i;					// For forloop indexing.
	var x;					// Assigned each indivual character in string.

	// Assign the length of the string to txtLen.
	txtLen = p_objName.value.length

	for(i = 0; i < txtLen; i++)
	{
		// Assign charater in substring to x.
		x = p_objName.value.substr(i, 1);
		if(x == ".")
			nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
		else if(parseInt(x) >= 0 || parseInt(x) <= 9)
			nNum = nNum + 1; // If the character is a number sum total times a number occurs.
		else{
			// Error occurs if any other character value is in the string
			// other then the valid characters.
			alert("ERROR: "+p_objName.name+"\n\nYou have entered an illegal value!\nPlease enter only: " +
				  "Decimal Points and numbers between 0...9!");
			return false;
		} // end else
	} // end for


	if(nDecimal > 1)
	{
		alert("ERROR: "+p_objName.name+"\n\nYou have entered more then one decimal point!\nPlease only enter one!");
		return false;
	} // end if

	if(nDecimal == 1)
	{
		// Get the number of numbers after the decimal point in
		// the string if there is a decimal point present
		decPos = (txtLen - 1) - p_objName.value.indexOf(".");
		// Floating point cannot be more then two.
		// Valid format after decimal point.
		if(decPos > parseInt(p_intDecimalPoint))
		{
			alert("ERROR: "+p_objName.name+"\n\nThe decimal point you entered is not in the correct position!\nOnly " +
				  ""+p_intDecimalPoint+" decimal point is allowed in this field.");
			return false;
		} // end if
	} // end if

	// Return true indicating that the value is a valid currency.
	return true;
}

function IsInteger(ObjName) {
	
	var checkOK = "0123456789";
	var allValid = true;
	var countCode = 0;
	var YourString = trimAll(ObjName.value);

	for (i = 0;  i < YourString.length;  i++){
		ch = YourString.charAt(i);
		for (j = 0;  j < checkOK.length;  j++){
			if (ch == checkOK.charAt(j)){
				countCode++;
				break;
			}
			
		}
	}
	
	if (countCode != YourString.length)
		return false;
	else	
		return true;
}

function leftTrim(sString) {
	while (sString.substring(0,1) == ' ')
	{
	sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString) {
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
	sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function trimAll(sString) {
	while (sString.substring(0,1) == ' ')
	{
	sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
	sString = sString.substring(0,sString.length-1);
	}
return sString;
}