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;
  alert(dispmessage);
/* Blocked by Nirma
  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  
  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "Required field");  
      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;
};

// -----------------------------------------
//               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
  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", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and 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<6) {
    msg (ifld, "error", "ERROR: " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
    else
      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", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR: not a valid 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;
};
function makeDaysOfMonth(){
  var i = 0;
  this[i++] = 0; // dummy
  this[i++] = 31;
  this[i++] = 29;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i  ] = 31;
  this.length = i;
}

function calcAge(dd, mm, yy)
{
  var t, mon, day, year, DD, MM, YY, age;
  var MTB = new makeDaysOfMonth();
  YY   = parseInt(yy);	// year of birth (4 digits)
  MM   = parseInt(mm);	// month of birth (1-12)
  DD   = parseInt(dd);	// date of birth (1-31)
  t    = new Date();	// get current date
  year = t.getFullYear();	// get year of current
  mon  = t.getMonth() + 1;	// get month of current
  day  = t.getDate();	// get date of current
  age = year - YY;
  if ((MM > mon) || (MM == mon && day < DD)) age --;
  return age;
}
function onKeyPressDates(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /^[\-\/0-9]/;
	if (key==8) return true; else return reg.test(keychar);
}
function onKeyPressNames(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /^[a-zA-Z .]/;
	if (key==8) return true; else return reg.test(keychar);
}
function onKeyPressNumbers(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /^[0-9]/;
	if (key==8) return true; else return reg.test(keychar);
}
function onKeyPressMarks(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /^[0-9.]/;
	if (key==8) return true; else return reg.test(keychar);
}
function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) IsNumber = false;
      }
   return IsNumber;
}
function IsText(sText)
{
   var ValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .";
   var IsText=true;
   var Char;
   for (i = 0; i < sText.length && IsText == true; i++) 
      { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) IsText = false;
      }
   return IsText;
}

function validtextfldR(obj,desc,ifld)
{
	if (obj.value=='') 
	{msg (ifld, "warn", "Enter "+ desc);}
	else 
	{
		if (!IsText(obj.value))  {msg (ifld, "warn", "Invalid "+ desc);} //obj.focus();}
		else {uCase(obj);}
	}
}
function validtextfld(obj,desc,ifld)
{
	if (obj.value!='') 
	{
		if (!IsText(obj.value))  {msg (ifld, "warn", "Invalid "+ desc); }//obj.focus();}
		else {uCase(obj);}
	}
	//else msg (ifld, "warn", "");
}
function validaddrfld(obj,desc,ifld)
{
	if (obj.value=='') {msg (ifld, "warn", "Enter "+ desc);}
	//else msg (ifld, "warn", "");
}
function validdatefld(obj,desc,ifld)
{
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = obj.value.match(datePat);
	if (obj.value=='') msg (ifld, "warn", "Enter "+ desc);
		//obj.focus();
	else 
	{
		if (!isDate(obj.value))  msg (ifld, "warn", "Invalid "+ desc);
			//obj.focus();
		else 
		{	

			day = matchArray[1]; 
			month = matchArray[3];
			year = matchArray[5];		
			age = calcAge (day,month,year);
			//alert(age);
			if (age<10){msg (ifld, "warn", "Age atleast 10 years");}
			//else msg (ifld, "warn", "Age : "+age+""); 
		}
	}
}
function validnumcodefld(obj,desc,ifld,min,max)
{
	if (obj.value!='')
	{
		if (IsNumeric(obj.value))
		{
			mval=parseFloat(obj.value,10);
			mval=mval-1
			if (mval<min || mval>max)
			{
				msg (ifld, "warn", "Incorrect "+ desc);
				obj.focus();
			}
		}
		else msg (ifld, "warn", "Invalid "+ desc);
	}
}
/*function checkYears(mmk,myear,mcompareyear,myobject,isnormal)
{
	try{
	mf=document.onlinefrm;
	mdt=new Date();
	mcYear=mdt.getFullYear();
	msg11="Invalid Year ";
	errmsgr='';
	//alert(mcompareyear+ " > "+ myear);
	if (isnormal==0)
	{
		alert("P2Val: ");
		if (myear<=mcompareyear || myear=>mcYear) { errmsgr = msg11+'\n';}
	}
	else
	{
		alert("P3Val: ");
		if (mmk>0) {if (myear<mcompareyear || myear>mcYear) errmsgr = msg11+'\n';}
	}
	return errmsgr;
	}
	catch (e) {alert(e);}
	year10=parseInt(mf.year_10.value); year12=parseInt(mf.year_12.value);
	yearGR1=parseInt(mf.year_GR1.value); yearGR2=parseInt(mf.year_GR2.value); yearGR3=parseInt(mf.year_GR3.value); yearGR4=parseInt(mf.year_GR4.value);
	yearPG1=parseInt(mf.year_PG1.value); yearPG2=parseInt(mf.year_PG2.value); yearPG3=parseInt(mf.year_PG3.value);
	yearBED=parseInt(mf.year_BED.value); yearDIP=parseInt(mf.year_DIP.value); yearGATE=parseInt(mf.year_GATE.value); 
	mf.mmk_GR3
	msg11="Invalid Year ";
	if (year10<1916 || year10>mcYear) {errmsg+=msg11+'Secondary\n';errnum+=1;}
	if (year12<=year10+1 || year12>mcYear) {errmsg+=msg11+'Senior Secondary\n';errnum+=1;}
	if (yearGR1<=year12 || yearGR1>mcYear) {errmsg+=msg11+'Graduation (I Year)\n';errnum+=1;}
	if (yearGR2<=yearGR1 || yearGR2>mcYear) {errmsg+=msg11+'Graduation (II Year)\n';errnum+=1;}
	if (yearGR3<=yearGR2 || yearGR3>mcYear) {errmsg+=msg11+'Graduation (III Year)\n';errnum+=1;}
	if  
	 if (yearGR2<=yearGR1 || yearGR2>mcYear) {errmsg+=msg11+'Graduation (II Year)\n';errnum+=1;}

}*/
function checkMarks(maxMarks,obtMarks,exYear,objname)
{
	var d = new Date();
	curr_year = d.getFullYear();
	err1=0;ermsg='';
	if (maxMarks>0) 
	{
		if (maxMarks<obtMarks) {err1+=1; ermsg+='Invalid Obtained Marks'+' ('+ objname +')\n';}
		if (obtMarks<=0) {err1+=1; ermsg+='Enter Obtained Marks'+' ('+ objname +')\n';}
		//if (grade=='') {err1+=1; ermsg+='Enter Division'+' ('+ objname +')\n';}
	}
	else 
	{
		if (obtMarks>0) {err1+=1; ermsg+='Invalid Obtained Marks'+' ('+ objname +')\n';}
		if (obtMarks<=0 && exYear!=curr_year) {err1+=1; ermsg+='Invalid Obtained Marks'+' ('+ objname +')\n';}
		//if (grade=='' && exYear!=2006) {err1+=1; ermsg+='Enter Division'+' ('+ objname +')\n';}
	}
	return ermsg;
}
function validmarks(obj,desc,ifld,mval1,mval2,mvalyear,isObt)
{
	var curdate = new Date();
	year1 = curdate.getFullYear();
	myyear=parseInt(mvalyear.value);
	mmax=parseInt(mval1.value); 
	if (isNaN(mmax) || mmax<=0) {mmax=0; mobt=0;}
	else {mobt=parseInt(mval2.value); if (isNaN(mobt) || mobt<=0) {mobt=0;}}
	if (mmax==0  &&  year1!=myyear) {msg(ifld, "warn", "Enter "+ desc+" Marks");}
	else if ((mmax>0 && mobt<=0) || mmax<mobt) 
	{if (isObt==1) msg (ifld, "warn", "Invalid "+ desc+" Obtained Marks");}
	//else {msg (ifld, "warn", "");}
	if (mobt<=0 || mmax<=0 || mmax<mobt) mperc=0; else mperc=(mobt/mmax)*100;	
	mperc=Math.round(mperc*100)/100;
	return mperc;
	//alert (mmax+ ' ' +mobt);	
}
/*			

	else if (mmax<mobt) {msg (ifld, "warn", "Invalid "+ desc+" Marks");}
	else {msg (ifld, "warn", "");}
	mperc=(mobt/mmax)*100;	
	return mperc;
}
*/
function validphotofld(obj,desc,ifld)
{
	if (obj.value=='') msg (ifld, "warn", "Enter "+ desc);
	obj.focus();
}

function isDate(dateStr)
{

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null)
	{
		//alert("Please enter date as either dd/mm/yyyy or dd-mm-yyyy.");
		return false;
	}

	day = matchArray[1]; // p@rse date into variables
	month = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12)  // check month range
	{
		//alert("Month must be between 1 and 12.");
		return false;
	}

	if (day < 1 || day > 31)
	{
		//alert("Day must be between 1 and 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31)
	{
		//alert("Month "+month+" doesn`t have 31 days!")
		return false;
	}

	if (month == 2) // check for february 29th
	{
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap))
		{
			alert("February " + year + " doesn`t have " + day + " days!");
			return false;
		}
	}
	return true; // date is valid
}
function LTrim( value ) 
{
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
function RTrim( value ) 
{	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
function alltrim( value ) 
{
	return LTrim(RTrim(value));
}
function uCase(obj) 
{
  var txt = obj.value;
  obj.value=txt.toUpperCase();
}
function textCounter(field, maxlimit) 
{
	if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);
}