/*
Checking function :
isEmail 			--		invalid email
C					-- 		Please choose one of the XXX checkbox
R 					-- 		cannot be empty
S					--		Please choose one of the XXX
isAccessNumber		-- 		XXX format is not valid.
isTel				--		XXX is not valid
isNotOnlyNum		--		XXX	must not be a numbers only
isNumLen			--		XXX must be 1 -- 9 digits.
isMaxLen			--		XXX is maximum 8 characters.
isLen				--		XXX must be 6 characters.
!=R					--		XXX must be a number.
inRange				--		must contain a number between 1 and 9.
isMatch                 --          compare with 3rd input parameter
*/

function trim(s) {
    if (s == null) {
      s = '';
    } else {

      while (s.substring(0,1) == ' ')
          s = s.substring(1, s.length);

      while (s.substring(s.length-1,s.length) == ' ')
          s = s.substring(0, s.length-1);
    }
    return s;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;
  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all)
    x=d.all[n];
  for (i=0;!x&&i<d.forms.length;i++)
    x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
    x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById)
    x=document.getElementById(n);

  return x;
}

function MM_validateForm() { //v4.0

  var i,p,q,nm,test,destName,comp,num,min,max,errors='',args=MM_validateForm.arguments;
  var extraparm,destval;

  for (i=0; i<(args.length-3); i+=4) {
    test=args[i+3];
    testName = args[i];
    Rval=MM_findObj(args[i+2]);
    destval=args[i+2];

    val=MM_findObj(testName);
    nm=args[i+1];

    if (val) {
      if (test.charAt(0) == 'C') {
        // Check if value is checked for checkbox
        var ifChecked = false;
        var j = 0;

        while (j < val.length && !ifChecked) {
          if (val[j].checked)
            ifChecked = true;
          j++;
        }

        if (!ifChecked)
          errors += '- Please choose one of the ' + nm + '.\n';

      } else if (test.charAt(0) == 'S') {
        // Check if value is selected for select box

      		if (!isObjSelected(val))
          	errors += '- Please choose one of the ' + nm + '.\n';

      } else if (test.indexOf('isVcePin')!=-1) {
		// Check if value is checked for checkbox

		var ifChecked = false;
		var j = 0;

		while (j < val.length && !ifChecked) {
			if (val[j].checked)
			ifChecked = true;
			j++;
		}
			var value = Rval.value;
			if (ifChecked)
			{
				if (value.length < 1 || value=='')
					errors += '- '+nm+' cannot be empty.\n';
				else if (!isAllDigits(value))
					errors += '- ' + nm + ' must be in numeric.\n';
				else if (value.length < 4)
					errors += '- ' + nm + ' is minimum 4 digits.\n';

			} // if

      } else if ((val=trim(val.value))!="") {

        if (test.indexOf('isCharOrSp')!=-1) {
          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!isLetter(c) && c != ' ')
            {
              errors += '- ' + nm + ' can only contain letters.\n';
              found = true;
            }
          }

        } else if (test.indexOf('isNoSpChar')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!isLetter(c))
            {
              errors += '- ' + nm + ' can only contain letters (no space).\n';
              found = true;
            }
          }

        } else if (test.indexOf('isCharOrDgtSp')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!(isLetter(c)||isDigit(c)||c==' '))
            {
              errors += '- ' + nm + ' can only contain letters/digits.\n';
              found = true;
            }
          }

        } else if (test.indexOf('isCharOrDgt')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!(isLetter(c)||isDigit(c)))
            {
              errors += '- ' + nm + ' can only contain letters/digits(no space).\n';
              found = true;
            }
          }

        } else if (test.indexOf('isValidWithAmpStroke')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!isValidCharWithAmpStroke(c) && c != ' ')
            {
              errors += '- ' + nm + ' contain invalid character(s).\n';
              found = true;
            }
          }

        } else if (test.indexOf('isValidWithAmp')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!isValidCharWithAmp(c) && c != ' ')
            {
              errors += '- ' + nm + ' contain invalid character(s).\n';
              found = true;
            }
          }

        } else if (test.indexOf('isValid')!=-1) {

          var found = false;
          var k = 0;
          for (k = 0; k < val.length && !found; k++)
          {
            var c = val.charAt(k);
            if (!isValidChar(c) && c != ' ')
            {
              errors += '- ' + nm + ' contain invalid character(s).\n';
              found = true;
            }
          }

        } else if (test.indexOf('isEmail')!=-1) {
		// BUG-UP-0057
		var found = false;
/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

		var checkTLD=1;
/* The following is the list of known TLDs that an e-mail address must end with. */
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

            // BUG-UP-0005-001
            // Email address only support alphanumeric, period, @ symbol, underscore, and hyphen
            validstr = /[^A-Za-z0-9\[\].@_-]/g;

            if ( validstr.test(val) ) {
                errors += '- ' + nm + ' format is incorrect.\n';
			continue;
            }
            // BUG-UP-0005-001 end

            var emailPat=/^(.+)@(.+)$/;
            var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
            var validChars="\[^\\s" + specialChars + "\]";
            var quotedUser="(\"[^\"]*\")";
            var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
            var atom=validChars + '+';
            var word="(" + atom + "|" + quotedUser + ")";
            var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
            var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

            var matchArray=val.match(emailPat);
            if (matchArray==null) {
                // Email address seems incorrect (check @ and .'s)
                errors += '- ' + nm + ' format is incorrect.\n';
                continue;
            }
            var user=matchArray[1];
            var domain=matchArray[2];
		for (var k=0; k<user.length; k++) {
			if (user.charCodeAt(k)>127) {
				errors += '- ' + nm + ': The username contains invalid characters.\n';
				found = true;
 				break;
			}
		}
		if ( found )
			continue;

		for (k=0; k<domain.length; k++) {
			if (domain.charCodeAt(k)>127) {
				errors += '- ' + nm + ': The domain contains invalid characters.\n';
				found = true;
 				break;
			}
		}
		if ( found )
			continue;

            if (user.match(userPat)==null) {
                // user is not valid;
                errors += '- ' + nm + ' format is incorrect.\n';
                continue;
            }

            var IPArray=domain.match(ipDomainPat);
            if (IPArray!=null) {
                // this is an IP address;
                      for (var k=1; k<=4;k++) {
                        if (IPArray[k]>255) {
					// Destination IP address is invalid
					errors += '- ' + nm + ': Destination IP address is invalid.\n';
					break;
                        }
			    }
			continue;
            }

		// BUG-UP-0057
if ( checkTLD == 0 ) {
            // Domain is symbolic name;
            var domainArray=domain.match(domainPat);
            if (domainArray==null) {
                // The domain name doesn't seem to be valid
                errors += '- ' + nm + ' format is incorrect.\n';
                continue;
            }

            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 three-letter domain, or two letter country
			errors += '- ' + nm + ' format is incorrect.\n';
			continue;
            }
} else if ( checkTLD == 1 ) {
		// Domain is symbolic name.  Check if it's valid.
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (k=0;k<len;k++) {
			if (domArr[k].search(atomPat)==-1) {
				errors += '- ' + nm + ': The domain name does not seem to be valid.\n';
				found = true;
				break;
			}
		}
		if ( found )
			continue;

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

		if (checkTLD && domArr[domArr.length-1].length!=2 && 
			domArr[domArr.length-1].search(knownDomsPat)==-1) {
			errors += '- ' + nm + ': The address must end in a well-known domain or two letters country.\n';
			continue;
		}
} // if checkTLD

            if (len<2) {
               // This address is missing a hostname
               errors += '- ' + nm + ' format is incorrect.\n';
               continue;
            }

        } else if (test.indexOf('isAccessNumber')!=-1) {

          if (!isAccNumber(val))
		// NEW-F008-001-029 add supporting hyphen
            errors += '- ' + nm + ' can only contain digit, * or # only.\n';
		// NEW-F008-001-029 end
            
	// NEW-F009-001-019 start
        } else if (test.indexOf('isCoadminTel')!=-1) {
		validstr = /[^0-9-+() ]/g;
	      if ( validstr.test(val) )
			errors += '- ' + nm + ' can only contain 0-9, -, +, (, ) or space.\n';
	// NEW-F009-001-019 end

        } else if (test.indexOf('isTel')!=-1) {

          if (!isPhone(val))
            errors += '- ' + nm + ' is not valid.\n';

        } else if (test.indexOf('isMobile')!=-1) {

		  if (!isPhone(val))
            errors += '- ' + nm + ' is not valid.\n';

          if (!startMobileDigit(val.charAt(0)))
          	errors += '- Not a valid Hong Kong mobile phone number.\n';

        } else if (test.indexOf('isNotOnlyNum') != -1) {

          if (isAllDigits(val))
            errors += '- ' + nm + ' must not be a number only.\n';

        } else if (test.indexOf('isDigits') != -1) {

          if (!isAllDigits(val))
            errors += '- ' + nm + ' must be digits.\n';
	// NEW-F008-001-029 start
        } else if (test.indexOf('isNumLenRange') != -1) {
			s=test.indexOf('isNumLenRange');
	            p=test.indexOf(':');
	            min=test.substring(s+13,p);
	            max=test.substring(p+1);
	            if (val.length<min || max<val.length || !isAllDigits(val))
	              errors+='- '+nm+' must be '+min+' - '+max+' digits.\n';
	// NEW-F008-001-029 end

        } else if (test.indexOf('isNumLen') != -1) {
          if (!isAllDigits(val) || val.length != test.substring(test.indexOf('isNumLen')+8))
            errors += '- ' + nm + ' must be '+test.substring(9)+' digits.\n';

        } else if (test.indexOf('isMinLen') != -1) {
          if (val.length < test.substring(test.indexOf('isMinLen')+8))
            errors += '- ' + nm + ' is minimum '+test.substring(test.indexOf('isMinLen')+8)+' characters.\n';

        } else if (test.indexOf('isMaxLen') != -1) {
          if (val.length > test.substring(test.indexOf('isMaxLen')+8))
            errors += '- ' + nm + ' is maximum '+test.substring(test.indexOf('isMaxLen')+8)+' characters.\n';

        } else if (test.indexOf('isLen') != -1) {
          if (val.length != test.substring(test.indexOf('isLen')+5))
            errors += '- ' + nm + ' must be '+test.substring(test.indexOf('isLen')+5)+' characters.\n';

        } else if (test.indexOf('notMatch')!=-1) {
          if (isObjMatched(val, Rval)){
            errors += '- '+nm+' must not be the same.\n';
          }

       } else if (test.indexOf('Match')!=-1) {
	      	if (!isObjMatched(val, Rval)){
        		errors += '- '+nm+' must be matched.\n';
        	}
	 } else if (test.indexOf('isLoginName') != -1) {
		// NEW-F008-001-029 add supporting hyphen
		validstr = /[^A-Za-z0-9-_.,]/g;
	      if ( validstr.test(val) )
			// NEW-F008-001-029 add supporting hyphen
			errors += '- ' + nm + ' can only contain alphanumeric, hyphen, underscore, comma and full-stop .\n';
         } else if (test.indexOf('isWebPin') != -1) {
                // NEW-F008-001-029 add supporting hyphen
                validstr = /[^A-Za-z0-9-_.,]/g;
              if ( validstr.test(val) )
                        // NEW-F008-001-029 add supporting hyphen
                        errors += '- ' + nm + ' can only contain alphanumeric, hyphen, underscore, comma and full-stop .\n';

	    } else if (test.indexOf('isNumericHyphen') != -1) {
		validstr = /[^0-9-]/g;
	      if ( validstr.test(val) )
			errors += '- ' + nm + ' can only contain numbers and hyphen.\n';
	    } else if (test.indexOf('isNumericStroke') != -1) {
		validstr = /[^0-9\/]/g;
	      if ( validstr.test(val) )
			errors += '- ' + nm + ' can only contain numbers and stroke.\n';

     } else if (test!='R') {
	          if (isNaN(val)) {
	            errors+='- '+nm+' must be a number.\n';
	          } else {
	            if (Math.abs(val) - parseInt(Math.abs(val)) != 0) {
	              errors+='- '+nm+' must be an integer number.\n';
	            }
	          }

	          if (test.indexOf('inRange') != -1) {
	            p=test.indexOf(':');
	            min=test.substring(8,p);
	            max=test.substring(p+1);

	            if (val<min || max<val)
	              errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
	          } // end if (test.indexOf('inRange') != -1
        } // end if (test.indexOf('isEmail')!=-1)
      } else if (test.charAt(0) == 'R') {
        errors += '- '+nm+' cannot be empty.\n';
      }

    } // end if (val)
  } // end for

  if (errors)
    alert('The following error(s) occurred:\n---------------------------------------------\n'+errors);

  //return (errors == '');
  document.MM_returnValue = (errors == '');
}

function isObjSelected(obj)
{
  return (obj.options[obj.selectedIndex].value != '');
}


function isObjChecked(obj)
{
  return (obj[obj.selectedIndex].checked);
}



function isObjMatched(obj, obj2)
{
	if (obj!=obj2.value){
		return false;
	}
  	return true;
}

function isAllDigits (s)
{
  var i;
  for (i = 0; i < s.length; i++)
  {
	  var c = s.charAt(i);
	  if (!isDigit(c))
	  {
		  return false;
	  }
  }
  return true;
}

function isPhone (s)
{
  var i;
  for (i = 0; i < s.length; i++)
  {
	  var c = s.charAt(i);
	  if (!isPhoneDigit(c))
	  {
		  return false;
	  }
  }
  return true;
}

function startMobileDigit(c)
{
	return ((c == "6") || (c == "9"))
}

function isPhoneDigit (c)
{   return ((c >= "0") && (c <= "9") || (c == "-") || (c == " ") || (c == "(") || (c == ")"))
}


function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isAccNumber (s)
{   
  var i;
  for (i = 0; i < s.length; i++)
  {
	  var c = s.charAt(i);
	  if ( isDigit(c) || isAccess(c) )
	  {
	  } else {
	  	return false;
	  } // if 
  }
  return true;
} 

function isAccess (c) 
{	return ( (c == '#') || (c == '*') )
}

function isValidChar (c)
{
    return ((c!="?")&&(c!=";")&&(c!="%")&&(c!="&")&&(c!="\\")&&(c!="/")&&(c!="!")&&(c!="<")&&(c!=">"))
}

function isValidCharWithAmp (c)
{
    return ((c!="?")&&(c!=";")&&(c!="%")&&(c!="\\")&&(c!="/")&&(c!="!")&&(c!="<")&&(c!=">"))
}

function isValidCharWithAmpStroke (c)
{
    return ((c!="?")&&(c!=";")&&(c!="%")&&(c!="\\")&&(c!="!")&&(c!="<")&&(c!=">"))
}

