// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model
// sufficiently well, so innerHTML option removed (redundant).
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;
  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};
// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;  
function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  if (emptyString.test(tfld)) {
    if (reqd) {
      msg (ifld, "error", "* Required");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}


// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", "");  
  return true;
};


// -----------------------------------------
//			   validateSelect
// Validate that something is selected for 
// dropdownlist.
// ensure that something has been selected
// other than index 0, which has no value.
// -----------------------------------------
function validateSelect(vfld, // element to be validated
						ifld) // id of element to receive info/error msg
{
	if (vfld.selectedIndex == 0)
	{
		msg(ifld, "error", "* Required");
		return false;
	}
	msg (ifld, "warn", ""); 
	return true;
}

function validateRadioGroup(vfld, // radio button group
							 ifld)  // id of element to receive info/error msg
{
	var radioLen = vfld.length;
	var check = false;
	
	for (var i = 0; i < radioLen; i++)
	{
		if (vfld[i].checked)
		{
			check = true;
			break;
		}
	}
	if (!check) 
	{
		msg(ifld, "error", "* Required");
		return false;
	}
	msg (ifld, "warn", ""); 
	return true;	
}

// -----------------------------------------
//            validateCheck
// Validate if something has been checked. For two option
// Returns true if so 
// -----------------------------------------

function validateCheck(vfld,   // element to be validated
                         ifld)  // id of element to receive info/error msg
{
	if(!(vfld[0].checked == true ||vfld[1].checked == true))
	{
		msg(ifld, "error", "* Please select an option");
		return false;
	}
  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//            validateCheck3
// Validate if something has been checked. For three option
// Returns true if so 
// -----------------------------------------

function validateCheck3(vfld,   // element to be validated
                         ifld)  // id of element to receive info/error msg
{
	if(!(vfld[0].checked == true ||vfld[1].checked == true||vfld[2].checked == true))
	{
		msg(ifld, "error", "Please select an option");
		return false;
	}
  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//            validatePaymentMode
// Validate if something has been checked for three option
// Returns true if so 
// -----------------------------------------

function validatePaymentMode(vfld,   // element to be validated
                         ifld)  // id of element to receive info/error msg
{
	if(!(vfld[0].checked == true ||vfld[1].checked == true||vfld[2].checked == true))
	{
		msg(ifld, "error", "Please select an payment mode");
		return false;
	}
  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//               validateName
// Validate if name
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateName  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var name = /^[A-Za-z]*( )[A-Za-z]*$/;
  var name2 = /^[A-Za-z]*$/;
  if ((!name.test(tfld)) && (!name2.test(tfld)))
  {
    msg (ifld, "error", "* Invalid Name");
    setfocus(vfld);
    return false;
  }

    msg (ifld, "warn", "");
  	return true;
};



// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "* Invalid E-mail Address");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "Unusual e-mail address - check if correct");
  else
    msg (ifld, "warn", "");
  return true;
};


// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "* Invalid telephone number. Enter only digits, space ()- or leading +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<8) {
    msg (ifld, "error", "* " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }
  else   if (numdigits>8)
  {
    msg (ifld, "error", "* " + numdigits + " digits - too long");
    setfocus(vfld);
	return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// -----------------------------------------

function validateAge    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "* Invalid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "* Invalid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "Bit young for this, aren't you?");
    else        msg (ifld, "warn", "");
  }
  return true;
};

// -----------------------------------------
//             Validate Date
// Validate Date
// Returns true if OK 
// -----------------------------------------
function validateDate  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
	if (!validformat.test(tfld))
	{
		msg(ifld, "error", "* Invalid Date Format");	
	    setfocus(vfld);
		return false;
	}
	else
	{ //Detailed check for valid date ranges
		var dayfield=tfld.split("/")[0];
		var monthfield=tfld.split("/")[1];
		var yearfield=tfld.split("/")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
		{
			msg(ifld, "error", "* Invalid Date detected");
			return false;
		}
	}
	msg (ifld, "warn", "");
  return true;
};

// -----------------------------------------
//            validatePostalCode
// Validate Postal Code
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validatePostalCode (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^[0-9]+$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "* Invalid Postal Code");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (ifld, "error", "* " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }
  else if (numdigits>6)
  {
    msg (ifld, "error", "* " + numdigits + " digits - too long");
    setfocus(vfld);
	return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//            validateNumber
// Validate Number
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateNumber (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  vfld.value = tfld;
  var num = /^[0-9]{1,10}$/
  if (!num.test(tfld)) {
    msg (ifld, "error", "* Invalid. Only numbers are allowed ");
    setfocus(vfld);
    return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//            validateNumber
// Validate Number
// Returns true OK
// -----------------------------------------

function validateNumOfYears (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  vfld.value = tfld;
  var num = /^\d(2)+(\.d(1))?$/
  if (!num.test(tfld)) {
    msg (ifld, "error", "* Invalid. Only numbers are allowed ");
    setfocus(vfld);
    return false;
  }

  msg (ifld, "warn", "");

  return true;
};


//Validate NRIC
//Return true if Ok
//
function validateNRIC(vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{


  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value.toUpperCase());  // value of field with whitespace trimmed off
  vfld.value = tfld;
  var NRIC = /^[S,F]\d{7}[A-Z]$/
  if (!NRIC.test(tfld)) {
    msg (ifld, "error", "* Invalid NRIC");
    setfocus(vfld);
    return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//            validateYearsOfWork
// Validate Years of Work
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateYearsOfWork (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^\d+(\.\d)?$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "* Invalid input for years");
    setfocus(vfld);
    return false;
  }

  if (tfld>=100) {
    msg (ifld, "error", "* Invalid Range");
    setfocus(vfld);
    return false;
  }
  
  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//             Validate Year
// Validate Year (YYYY format)
// Returns true if OK 
// -----------------------------------------
function validateYear (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var validformat=/^\d{4}$/ //Basic check for format validity
	if (!validformat.test(tfld))
	{
		msg(ifld, "error", "* Invalid Year");	
	    setfocus(vfld);
		return false;
	}
	else
	{ //Detailed check for valid date ranges
		var yearfield=tfld.split("/")[0];
		var dayobj = new Date();
		if (yearfield>dayobj.getFullYear()||yearfield<1900)
		{
			msg(ifld, "error", "* Invalid Year range detected");
			return false;
		}
	}
	msg (ifld, "warn", "");
  return true;
};

// -----------------------------------------
//            validateCCNum
// Validate Creadit Card Number
// Returns true if OK
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateCCNum  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "* not a valid Credit Card number. Characters permitted are digits, space and -");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<13) {
    msg (ifld, "error", "* " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }
  else if (numdigits>12&&numdigits<16)
  {
    msg (ifld, "warn", "" + numdigits + " digits - Check if correct");
    setfocus(vfld);
	return false;
  }
  else   if (numdigits>16)
  {
    msg (ifld, "error", "* " + numdigits + " digits - too long");
    setfocus(vfld);
	return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//             Validate Credit Card Date
// Validate Credit Card Date and check if it had expired
// Returns true if OK 
// -----------------------------------------
function validateCCDate  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var validformat=/^\d{2}\/\d{4}$/ //Basic check for format validity
	if (!validformat.test(tfld))
	{
		msg(ifld, "error", "* Invalid Date Format");	
	    setfocus(vfld);
		return false;
	}
	else
	{ //Detailed check for valid date ranges
	var dayfield = 1;
		var monthfield=tfld.split("/")[0];
		var yearfield=tfld.split("/")[1];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getFullYear()!=yearfield))
		{
			msg(ifld, "error", "* Invalid Date range detected");
			return false;
		}

		var systemDate = new Date();
		var userDate = new Date();
		userDate.setMonth(monthfield-1);
		userDate.setYear(yearfield);
		if (userDate.getFullYear()<systemDate.getFullYear())
		{
			msg(ifld, "error", "* Credit Card have expiry. Please use another card.");
			return false;
		}
		else if(userDate.getMonth()<systemDate.getMonth() && userDate .getFullYear()==systemDate.getFullYear())
		{
			msg(ifld, "error", "* Credit Card have expiry. Please use another card.");
			return false;
		}
	}
	msg (ifld, "warn", "");
  return true;
};

// -----------------------------------------
//            validate Score
// Validate Score for rating done at self assessment report
// Returns true if ok
// -----------------------------------------

function validateScore (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  vfld.value = tfld;
  var num = /^[0-9]*$/
  if (!num.test(tfld)) {
    msg (ifld, "error", "* not valid. Only numbers are allowed ");
    setfocus(vfld);
    return false;
  }
  if(tfld > 5 || tfld<1)
  {
  	msg (ifld, "error", "* Please select a rating");
    setfocus(vfld);
    return false;
  }

  msg (ifld, "warn", "");

  return true;
};

// -----------------------------------------
//             ValidateMMYYYY
// Validate Date (MM/YYYY format)
// Returns true if OK 
// -----------------------------------------
function validateMMYYYY  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var validformat=/^\d{2}\/\d{4}$/ //Basic check for format validity
	if (!validformat.test(tfld))
	{
		msg(ifld, "error", "* Invalid Date Format");	
	    setfocus(vfld);
		return false;
	}
	else
	{ //Detailed check for valid date ranges
	var dayfield = 1;
		var monthfield=tfld.split("/")[0];
		var yearfield=tfld.split("/")[1];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getFullYear()!=yearfield))
		{
			msg(ifld, "error", "* Invalid Date range detected");
			return false;
		}
	}

	msg (ifld, "warn", "");
  return true;
};

  function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

// -----------------------------------------
//            validateNoOfManYear
// Validate Number
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateNoOfManYear (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^\d+(\.\d)?$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "* Invalid input for years");
    setfocus(vfld);
    return false;
  }
  
  msg (ifld, "warn", "");

  return true;
};

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=800,height=300,left = 62,top = -16');");
};

