/*
* 		Client side validations Java Script library
*		Version 1.0
*		Creation date 29/11/2005
*		Developer: Yoonas Khan
*
*
*		Description:
*		This library contains client side Java script validation functions
*		used to validate user input before the form is submitted, 
*		most of these function rely on Regular Expressions when performing 
*		their respective validations, these Regular Expressions can be over ridden
*		to provide tailored functionality.
*		see each function's description for further info on each function and its usage.
*
	
*/	
// This functions allow only the character which declared here for the text boxes 
var INTEGER_ALLOWED_CHARS =  /^((-[1-9])?[0-9]*|[-]|[+])$/;
var NUMBERS_ALLOWED_CHARS =  /^((-[1-9])?[0-9]*)$/;

function checkNumbers(fieldRef){
//alert("checkNumbers")
	var fieldValue = String.fromCharCode(event.keyCode);
		//alert(String.fromCharCode(event.keyCode))
	if (INTEGER_ALLOWED_CHARS.test(fieldValue) ) {
		return true;
	}else{
		return false;
	}
}

function checkBlank(fieldRef){
//alert("checkNumbers")
	var fieldValue = String.fromCharCode(event.keyCode);
//		alert(String.fromCharCode(event.keyCode))
	if (fieldValue !=' ') {
		return true;
	}else{
		return false;
	}
}


function checkInteger(fieldRef){
//alert("checkNumbers")
	var fieldValue = String.fromCharCode(event.keyCode);
		//alert(INTEGER_ALLOWED_CHARS.test(fieldValue))
	if (NUMBERS_ALLOWED_CHARS.test(fieldValue) ) {
		return true;
	}else{
		return false;
	}
}

function trim(str)
{
	//alert('str ' +str);
	var x;
	var ch;
	
	for(x=0;x<str.length;x++)
	{
		ch=str.substr(x,1);
		if(ch==' ' || ch=='\t')
		{
			str=str.substr(x+1,str.length-1);
		}
		else
			break;
	}
	
	for(x=str.length-1;x>=0;x=x-1)
	{
		ch=str.substr(x,1);
		if(ch==' ' || ch=='\t')
		{
			str=str.substr(0,str.length-1);
		}
		else
			break;
	}
	
	return str;
}



	//this function accepts the object as a parameter and display the appropriate error messages if the text box is empty
function checkempty(objname1,objname2,objname3,objname4,objname5,objname6,errmsg)
{
if((objname1.value=="")&&(objname2.value=="")&&(objname3.value=="")&&(objname4.value=="")&&(trim(objname5[objname5.selectedIndex].value)=="")&&(trim(objname6[objname6.selectedIndex].value)==""))

		{
			alert(errmsg);
			objname1.focus();
			return false;
		}
		return true;
}
// this is for pharmacy having 5 objects
function checkemptyphar(objname1,objname2,objname3,objname4,objname5,errmsg)
{
if((objname1.value=="")&&(objname2.value=="")&&(objname3.value=="")&&(objname4.value=="")&&(trim(objname5[objname5.selectedIndex].value)==""))

		{
			alert(errmsg);
			objname1.focus();
			return false;
		}
		return true;
}
function checkemptyinst(objname1,objname2,objname3,errmsg)
{
if((trim(objname1[objname1.selectedIndex].value)=="")&&(trim(objname2[objname2.selectedIndex].value)=="")&&(trim(objname3[objname3.selectedIndex].value)==""))

		{
			alert(errmsg);
			objname1.focus();
			return false;
		}
		return true;
}

//this function will validate the check boxes is checked or not in a form
function checkChecked(objname1,objname2,objname3,objname4,errmsg)
	{
		if (objname1.checked==false && objname2.checked==false && objname3.checked==false && objname4.checked==false)
		{
			alert(errmsg);
			
			return false;
		}
		return true;
	}
	

	//this function accepts the object as a parameter and display the appropriate error messages if the text box is empty
	//similar to the above function only that it checks for combo box
	function checkcomboempty(objname,errmsg)
	{
		if (trim(objname[objname.selectedIndex].value)=="")
		{
			alert(errmsg);
			objname.focus();
			return false;
		}
		return true;
	}
	
	
function checkPresent(dateName){
	theMonth = dateName + "Month";
	theMonth = document.getElementsByName(theMonth)
	theYear = dateName + "Year";
	theYear = document.getElementsByName(theYear)
	if (theMonth[0].selectedIndex == 1)
		{
		theYear[0].className = "hide";
		theYear[0].selectedIndex == 0;
	} else
	 {
		theYear[0].className = "textinside";
		
	}
	
}
	

	function checknumeric(objname,errmsg)
	{
		if (isNaN(trim(objname.value)))
		{
			alert(errmsg);
			objname.focus();
			return false;
		}
		return true;
	}
//Email validation starts from here
	function checkemail(objname,errmsg)
	{
		vvalue=trim(objname.value);
		atPos = vvalue.indexOf('@');
		sppos = vvalue.indexOf(" ");
		dopos = vvalue.indexOf(".");
		if (atPos < 1 || atPos == (vvalue.length - 1) || (sppos != -1)|| (dopos == -1))
		{
			alert(errmsg);
			objname.focus();
			return false;
		}
		return true;
	}
//Email validation ends from here

//telno validation starts from here 
//it checks that the entered value does not contain anything except numeric characters and hyphen
	function checktelno(objname,errmsg)
	{
		var str = trim(objname.value);
		for(x=0;x<str.length;x++)
		{
			ch=str.substr(x,1);
			if ((ch < '0' || ch >'9')&&(ch!='-'))
			{
				//alert(errmsg);
				objname.focus();
				return false;
			}
		}
		return true;
	}
//telno validation ends over here

//maxlength validation starts over here
	function checkmaxlength(objname,maxlength,errmsg)
	{
		var str = objname.value;
		if (str.length>maxlength)
		{
			alert(errmsg);
			objname.focus();
			return false;
		}
		return true;
	}
//maxlength validation ends over here

//minlength validation starts over here
	function checkminlength(objname,minlength,errmsg)
	{
		var str = objname.value;
		if (str.length<minlength)
		{
			alert(errmsg);
			objname.focus();
			return false;
		}
		return true;
	}
//minlength validation ends over here
	function checkinteger(objname,errmsg)
	{
		var str = trim(objname.value);
		for(x=0;x<str.length;x++)
		{
			ch=str.substr(x,1);
			if ((ch < '0' || ch >'9'))
			{
				alert(errmsg);
				objname.focus();
				return false;
			}
		}
		return true;
	}

	
function checkFileds()
{
	var nMaxLength=Lookup.ID.value.length;

	if(isNaN(Lookup.ID.value)){ 
		alert("Invalid data format.\n\nOnly numbers are allowed."); 
		Lookup.ID.focus(); 
		return (false); 
	}
	if(nMaxLength!=11 && nMaxLength!=8 && nMaxLength!=7){
		alert("QID should be either 7/8/11 digits");
		Lookup.ID.focus(); 
		return (false); 
	}
	document.Lookup.QID.value=document.Lookup.ID.value;
	return true;
}


function valDrop(val)
{
if (val == '') return false;
else return true;
} 
	
//*******************************************************************************

// Copyright © 2001 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.

// email

function checkEmail (strng) {
var error="";
if (strng == "") {
   error = "You didn't enter an email address.\n";
}

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) { 
       error = "Please enter a valid email address.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters.\n";
       }
    }
return error;    
}


// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a phone number.\n";
}

var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";
  
    }
    if (!(stripped.length == 10)) {
	error = "The phone number is the wrong length. Make sure you included an area code.\n";
    } 
return error;
}


// password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}

    var illegalChars = /[\W_]/; // allow only letters and numbers
    
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    } 
    else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
    }  
return error;    
}    


// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (objnamestrng) {
var error = "";
//if (strng == "") {
 //  error = "You didn't enter a username.\n";
//}


    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((strng.length < 4) || (strng.length > 10)) {
       error = "The username is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    } 
return error;
}       


// non-empty textbox

function isEmpty(strng) {
var error = "";
  if (strng.length == 0) {
     error = "The mandatory text area has not been filled in.\n"
  }
return error;	  
}

// was textbox altered

function isDifferent(strng) {
var error = ""; 
  if (strng != "Can\'t touch this!") {
     error = "You altered the inviolate text area.\n";
  }
return error;
}

// exactly one radio button is chosen

function checkRadio(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
    }
return error;
}


function checkRadioBut(field,errmsg) 
{
	if (!field[0].checked && !field[1].checked )	 
	
	{
		 alert(errmsg);
      field[0].focus();
		return false;

    }
return true;
}

//validating radio button for yes or no
function checkRadioButton(objname,errmsg)
 {
 
  if (objname.value=="")
    {
       alert(errmsg);
			objname.focus();
			return false;
    }
return true;
}


// valid selector from dropdown list

function confirmdropdown(objname,errmsg)
{
	if (objname.selectedIndex == 0)
	{
	alert(errmsg);
	objname.focus();
	return false;
	}
	return true;
}


function checkuser(objname,errmsg1,errmsg2) {
var error = "";
//if (strng == "") {
 //  error = "You didn't enter a username.\n";
//}


    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((objname.length < 4) || (objname.length > 10)) {
       //error = "The username is the wrong length.\n";
       alert(errmsg1);
    }
    else if (illegalChars.test(objname)) {
    //error = "The username contains illegal characters.\n";
    alert(errmsg2);
    } 
return error;
}       


// HISTORY
// ------------------------------------------------------------------
// May 17, 2003: Fixed bug in parseDate() for dates <1970
// March 11, 2003: Added parseDate() function
// March 11, 2003: Added "NNN" formatting option. Doesn't match up
//                 perfectly with SimpleDateFormat formats, but 
//                 backwards-compatability was required.

// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	var sysDate = new Date(); 

	if (d1 == d2) {
		errmsg = "Invalid Dates"
		return errmsg;
		}
	else if (d1 > d2) {
		errmsg = "Invalid Dates"
		return errmsg;
		}
	else if (d1 == sysDate){
		errmsg = "From date cannot be todays date"
		return errmsg;
	}
	return true;
	}

function checkToday(date1,dateformat1) {
	var d1=getDateFromFormat(date1,dateformat1);
	var sysDate = new Date(); 
	if (d1 == sysDate){
		errmsg = "From date cannot be todays date"
		return errmsg;
	}
	return true;

	}
// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
function validateAge(dob,errMsg)
{
	var date1 = new Date(dob.value);
	year1 = date1.getFullYear();
	var date2 =new Date();
	year2 = date2.getYear();
	//alert(date1+'||'+year1+'||'+date2+'||'+year2);
	var bAge = 16;
	var age = year2 - year1;
//	alert(year2+' - ' + year1 +' = '+age);
	if(bAge > age)
	{
		alert(errMsg);
		return false;
	} 
	return true;
}
function doDateCheck(from, to,errMsg) 
	{
		//alert(' i am here in doDateChecks');
	//	var x = from.value
	//	var dt1 = new Date(x).format('dd\mmmm\yyyy');
		//alert(dt1+' || '+ Date.parse(dt1));
		if (Date.parse(from.value) >= Date.parse(to.value)) 
		{
			alert(errMsg);
			return false;
		}
		return true;
	}
function isFuture(dt,errMsg) 
	{
		var now = new Date();
		
	//	alert(' i am here in isFuture');

		if (Date.parse(dt.value) > Date.parse(now)) 
		{
			
			alert(errMsg);
			return false;
		}
		return true;
	}

var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);

var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
Date.prototype.format = function(f)
{
    if (!this.valueOf())
        return '&nbsp;';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
            case 'yyyy': return d.getFullYear();
            case 'mmmm': return gsMonthNames[d.getMonth()];
            case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
            case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'dddd': return gsDayNames[d.getDay()];
            case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
            case 'dd':   return d.getDate().zf(2);
            case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case 'nn':   return d.getMinutes().zf(2);
            case 'ss':   return d.getSeconds().zf(2);
            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
}







