
var digits = "0123456789";

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


// whitespace characters
var whitespace = " \t\n\r";


// decimal point character differs by language and culture
var decimalPointDelimiter = ".";


// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";


// characters which are allowed in phone numbers
var validPhoneChars = digits + phoneNumberDelimiters;


// phone numbers have 10 digits.
var digitsInPhoneNumber = 10;

// mobile numbers have 10 digits.
var digitsInMobileNumber = 10;

// PIN codes have 6 digits.
var digitsInPinCode = 6;

var defaultEmptyOK = false;

var dtCh= "/";
var minYear=1900;
var maxYear=2999;


function isEmpty(s)
{   
	return ((s == null) || (s.length == 0))
}


function isWhitespace (s)
{   
	var i;

    	if (isEmpty(s)) return true;

    	for (i = 0; i < s.length; i++)
    	{   
        	var c = s.charAt(i);
        	if (whitespace.indexOf(c) == -1) return false;
    	}
    	return true;
}


function stripCharsInBag (s, bag)

{   
	var i;
    	var returnString = "";

    	for (i = 0; i < s.length; i++)
    	{   
        	var c = s.charAt(i);
        	if (bag.indexOf(c) == -1) returnString += c;
    	}
	return returnString;
}


function charInString (c, s)
{   
	var i;

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


function stripInitialWhitespace (s)
{   
	s = s + ""

	var i = 0;

    	while ((i < s.length) && charInString (s.charAt(i), whitespace))
       		i++;
    
    	return s.substring (i, s.length);
}


function stripLastWhitespace (s)
{   
	s = s + ""
	var i = s.length-1;

    	while ((i > -1) && charInString (s.charAt(i), whitespace))
       		i--;
    
    	return s.substring (0,++i);
}


function stripWhitespace (s)
{   
	return stripCharsInBag (s, whitespace)
}


function trim(s)
{
	var returnString;
	returnString = s;
	returnString=stripInitialWhitespace(returnString);
	returnString=stripLastWhitespace(returnString);

	return returnString;
}


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


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


function isLetterOrDigit (c)
{   
	return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{   
	var i;

    	if (isEmpty(s)) 
       		if (isInteger.arguments.length == 1) return defaultEmptyOK;
       		else return (isInteger.arguments[1] == true);
    	for (i = 0; i < s.length; i++)
    	{   
	        var c = s.charAt(i);
        	if (!isDigit(c)) return false;
    	}
    	return true;
}

function isReal (s)
{   
	var i, j;

    	if (isEmpty(s)) 
       		if (isInteger.arguments.length == 1) return defaultEmptyOK;
     		else return (isInteger.arguments[1] == true);
    	for (i = 0, j = 0; i < s.length; i++)
    	{   
	        var c = s.charAt(i);
        	if (!isDigit(c)) 
		{
			if(c=='.')
				j++;
			else
				return false;
		}
    	}

	if(j==1)
	{
		if(s.indexOf('.')==s.length-1) return false;
	}
	else if(j>1)
	{
	 	return false;
	}

    	return true;
}

function isAlphabetic (s)
{   
	var i;

    	if (isEmpty(s)) 
       		if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       		else return (isAlphabetic.arguments[1] == true);

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

function isAlphanumeric (s)
{   
	var i;

    	if (isEmpty(s)) 
       		if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       		else return (isAlphanumeric.arguments[1] == true);

    	for (i = 0; i < s.length; i++)
    	{   
        	var c = s.charAt(i);

        	if (! (isLetter(c) || isDigit(c) || whitespace.indexOf(c)!=-1 || ('?.-,!\'"').indexOf(c)!=-1) )
        		return false;
    	}
    	return true;
}


function isPinCode (s)
{  
	if (isEmpty(s)) 
       		if (isPinCode.arguments.length == 1) return defaultEmptyOK;
       		else return (isPinCode.arguments[1] == true);
	return (isInteger(s) && (s.length == digitsInPinCode))
}


function isPhoneNumber (s)
{   
	if (isEmpty(s)) 
       		if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
	       	else return (isPhoneNumber.arguments[1] == true);
	return (isInteger(s) && s.length == digitsInPhoneNumber)
}


function isMobileNumber (s)
{   
	if (isEmpty(s)) 
       		if (isMobileNumber.arguments.length == 1) return defaultEmptyOK;
	       	else return (isMobileNumber.arguments[1] == true);
	return (isInteger(s) && s.length == digitsInMobileNumber)
}


function isEmail(emailStr,fieldName) 
{
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	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=emailStr.match(emailPat);

	if (matchArray==null) 
	{
		alert(fieldName + " address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++) 
	{
		if (user.charCodeAt(i)>127) 
		{
			alert("Ths username in " + fieldName + " contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) 
	{
		if (domain.charCodeAt(i)>127) 
		{
			alert("Ths domain name in " + fieldName +  " contains invalid characters.");
			return false;
		}
	}

	if (user.match(userPat)==null) 
	{
		alert("The username in " + fieldName +  " doesn't seem to be valid.");
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) 
	{
		for (var i=1;i<=4;i++) 
		{
			if (IPArray[i]>255) 
			{
				alert("Destination IP address in " + fieldName + " is invalid!");
				return false;
   			}
		}
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) 
	{
		if (domArr[i].search(atomPat)==-1) 
		{
			alert("The domain name in " + fieldName + " does not seem to be valid.");
			return false;
   		}	
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) 
	{
		alert("The " + fieldName + " address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	if (len<2) 
	{
		alert(fieldName + " address is missing a hostname!");
		return false;
	}

	return true;
}


function isTime(str)
{
	var cnt,i,c;
	
	i=-1;
	cnt=0;
	if(str.length>5||str.length<3)
		return false;
	if(str.indexOf(':')<1)
		return false;
    	for (i = 0; i < str.length; i++)
	{   
        	c = str.charAt(i);
	        if (((c < "0") || (c > "9"))&&c!=":") 
        		return false;
	}
	while(str.indexOf(i+1,':')>0)
	{
		cnt = cnt+1;
		i = str.indexOf(i+1,':');
	}
	if(cnt>1)
		return false;
		
	i = str.indexOf(':');
	if(str.substring(0,i)>24 || str.substring(0,i)<0)
		return false;
	if(str.substring(i+1,str.length)>59 || str.substring(i+1,str.length)<0)
		return false;
	if(str.substring(0,i)==24 && str.substring(i+1,str.length)>0)
		return false;
	
	return true;
}


function daysInFebruary (year)
{
    	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}


function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) 
	{
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   	} 
   	return this
}


function isDate(dtStr,fieldName)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) 
		strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) 
		strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) 
	{
		if (strYr.charAt(0)=="0" && strYr.length>1) 
			strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1)
	{
		alert("The date format of " + fieldName + " should be : dd/mm/yyyy.")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12)
	{
		alert("Please enter a valid month for " + fieldName +".")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		alert("Please enter a valid day for " + fieldName +".")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear + " for " + fieldName +".")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		alert("Please enter a valid " + fieldName +".")
		return false
	}
	return true
}


function validateField(obj, minLen, maxLen, minVal, maxVal, dataType, fieldName)
{
	try
	{
		dataType = dataType.toLowerCase()
		fieldName = fieldName.toUpperCase();

		if (obj==null) return false;
	
		obj.value = trim(obj.value);

		var s = obj.value;

		if(minLen==0 && s.length==0) return true;

		if(s.length < minLen) 
		{
			if(s.length==0) alert("Please specify " + fieldName + "."); 
			else alert(fieldName + " must have minimum of " + minLen + " characters. It has only " + s.length + " characters."); 
			obj.focus();
			return false;
		}

		switch(dataType)
		{
			case "real":
				if(!isReal(s))
				{
					alert("Please specify numeric value for " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
			case "integer":
				if(!isInteger(s))
				{
					alert("Please specify integer value for " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
			case "alphabetic" :
				if(!isAlphabetic(s))
				{
					alert(fieldName + " allows only letters.");
					obj.focus();
					return false;
				}
				break;
			case "alphanumeric" :
				if(!isAlphanumeric(s))
				{
					alert(fieldName + " allows only letters and digits.");
					obj.focus();
					return false;
				}
				break;
			case "phone" :
				if(!isPhoneNumber(s))
				{  
					alert("Invalid " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
			case "mobile" :
				if(!isMobileNumber(s))
				{
					alert("Invalid " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
			case "pincode" :
				if(!isPincode(s))
				{
					alert("Invalid " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
			case "email" :
				if(!isEmail(s,fieldName))
				{
					obj.focus();
					return false;
				}
				break;
			case "date" :
				if(!isDate(s,fieldName))
				{
					obj.focus();
					return false;
				}
				break;
			case "time" :
				if(!isTime(s))
				{
					alert("Invalid " + fieldName + ".");
					obj.focus();
					return false;
				}
				break;
		}
	
		if(s.length > maxLen && maxLen>-1) 
		{
			alert(fieldName + " cannot have more than " + maxLen + " characters. It has " + s.length + " characters.");
			obj.focus();
			return false;
		}
	
		return true;
	}
	catch(e)
	{}
}


function areEqual(s1,s2)
{
	s1 = s1 + ""
	s2 = s2 + ""
	if(s1.toLowerCase()!=s2.toLowerCase())
		return false;
	return true
}

function DateDiff(start, end, interval, rounding ) 
{

    	var iOut = 0;
    
	var bufferA = Date.parse( start ) ;
    	var bufferB = Date.parse( end ) ;
    	
    	if ( interval.charAt == 'undefined' ) 
		return null ;
    
   	 var number = bufferB-bufferA ;
    
    	switch (interval.charAt(0))
    	{
        	case 'd': case 'D': 
            		iOut = parseInt(number / 86400000) ;
            		if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            		break ;
        	case 'h': case 'H':
            		iOut = parseInt(number / 3600000 ) ;
            		if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            		break ;
        	case 'm': case 'M':
            		iOut = parseInt(number / 60000 ) ;
            		if(rounding) iOut += parseInt((number % 60000)/30001) ;
            		break ;
        	case 's': case 'S':
            		iOut = parseInt(number / 1000 ) ;
            		if(rounding) iOut += parseInt((number % 1000)/501) ;
            		break ;
        	default:
        		return null ;
    	}
    
    	return iOut ;
}



