//This function is used to trim any string value using javascript.
function trimString (str) {

    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

//This function is used for email validation
function isValid(str) {
	var emailFilter=/^.+@.+\..{2,3}$/;
	if (!(str.match(emailFilter))) { 
        return false;
	}
	else {
		return true;
	}

}

//This function checks for illegal characters in the email
function isEmailUnwantedChars(emailId){
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]\']/
	if (emailId.match(illegalChars)) {
		return true;
	}else{
		return false;
	}
}


//This function is used for Numeric values
function isNumeric(str) {
	var numFilter=/^[0-9][0-9]*$/;
	if (!(str.match(numFilter))) { 
        return false;
	}
	else {
		return true;
	}
}

//This function is used for decimal values
function isDecimal(str) {
	var numFilter=/^[0-9.]*$/;
	if (!(str.match(numFilter))) { 
        return false;
	}
	else {
		return true;
	}
}

// This function check for the alphanumeric value
function isAlphanumeric(fieldVal){
	
	var strValidChars =/^[0-9a-zA-Z]+$/;
	if (!(fieldVal.match(strValidChars))) { 
        return false;
	}
	else {
		return true;
	}
}



	//This function is used for alphabets
function isAlphabet(str) {
   
	var numFilter= /^[a-zA-Z]+$/;
	if (!(str.match(numFilter))) { 
        return false;
	}
	else {
		return true;
	}
}

function hasSpecialCharaters(fieldValue)
{
	  var iChars = "’!@#$%^&*()+=[]\\\';,/{}|\":<>";
	  var flag = false;
	  for (var i = 0; i < fieldValue.length; i++) {
	  	if (iChars.indexOf(fieldValue.charAt(i)) != -1) {
	  		flag = true;
	  		break;
	  	}
	  }
	  if(flag){
	  	return true;
	  }else{
	  	return false;
	  }
}


//Check For White Space
function hasWhiteSpace(fieldValue)
{
	  var iChars = "\t\n\r ";
	  var flag = false;
	  for (var i = 0; i < fieldValue.length; i++) {
	  	if (iChars.indexOf(fieldValue.charAt(i)) != -1) {
	  		flag = true;
	  		break;
	  	}
	  }
	  if(flag){
	  	return true;
	  }else{
	  	return false;
	  }
}


// This function check for the valid phone number
function isPhone(fieldVal){

	var strValidChars = "0123456789- ()";
	var blnResult = true;
	
	 for (i = 0; i < fieldVal.length; i++)
		{
			strChar = fieldVal.charAt(i);
			if (strValidChars.indexOf(strChar) == -1)
			 {
				 blnResult = false;
			 }
		}
	  if (blnResult == false)
	  {
			return false;
	  }else{
			return true;
	  }
}

// This function check for the valid zip code
function isZipCode(fieldVal){

	var strValidChars = "0123456789";
	var blnResult = true;
	var fldLength=fieldVal.length;
	if (fldLength == 5)
	 {
	 for (i = 0; i < fldLength; i++)
		{
			strChar = fieldVal.charAt(i);
			if (strValidChars.indexOf(strChar) == -1)
			 {
				 blnResult = false;
			 }
		}
	 }
	 else {
	 	
	 	blnResult = false;
	 	
	 }
	 
	  if (blnResult == false)
	  {
			return false;
	  }else{
			return true;
	  }
}




// This function is used to open a pop up window. User need to pass only two parameters
// 1) pageURL like: "userDetails.php?id=2"
// 2) windowName: Name of the pop up window
function ShowDetails(pageURL,windowName)
{
	var nLeft, nTop, nWidth, nHeight;
	nWidth  = 700;
	nHeight = 600;
	nLeft = screen.width - nWidth - 50;
	nTop  = screen.height - nHeight - 100;

	Window1 = window.open(pageURL, windowName,"dependent=yes,height=" + nHeight + ",width=" + nWidth + ",left=" + nLeft + ",top=" + nTop + ",location=no,menubar=no,resizable=yes,scrollbars=yes"); 
	Window1.focus(); 
}


// This function is used to check and uncheck all check box in the listing page

// check_all: Name of the button on whose click checkAll() function is called
// check_delete[]: Name of the check box against each row
function checkAll(){

	var check_all = document.getElementById('check_all').checked;
	var getCheckBox = document.getElementsByName('check_delete[]');
	// If Check box is checked, then check all checkbox to delete record
	if(check_all){
	
		for(var i=0; i<getCheckBox.length; i++){
		
			getCheckBox[i].checked = true;
		}

	}else{
	// If Check box is unchecked, then uncheck all checkbox to delete record
	
		for(var i=0; i<getCheckBox.length; i++){
		
			getCheckBox[i].checked = false;
		}
		
	}
	
}


//Add more fields dynamically.
function addField(area,field,limit) {
	
	 if(!document.getElementById) return; //Prvent older browsers from getting any further.
	 
	 var field_area = document.getElementById(area);
	 
	 var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
	
	 //Find the count of the last element of the list. It will be in the format '<field><number>'. If the 
	 //  field given in the argument is 'friend_' the last id will be 'friend_4'.
	 var last_item = all_inputs.length - 1;
	 var last = all_inputs[last_item].id;
	
	 var count = Number(last.split("_")[1]) + 1;
	
	 //If the maximum number of elements have been reached, exit the function.
	 //  If the given limit is lower than 0, infinite number of fields can be created.
	 if(count > limit && limit > 0) return;
	  field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' size='26' class='txtFont'/></li>";
	/* if(document.createElement) { //W3C Dom method.
	  var li = document.createElement("li");
	  var input = document.createElement("input");
	  input.id = field+count;
	  input.name = field+count;
	  input.size = "25";
	  input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
	
	  li.appendChild(input);
	  field_area.appendChild(li);
        
	 } else { //Older Method
	  field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' size='26' class='txtFont'/>eytetry</li>";
	 }*/
}

function confirmOnDelete(){
	if(confirm("Do you really want to delete record")){
		return true;
	}else{
		return false;
	}
	
}






function emailCheck (emailStr) {

/* 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)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

//error_msg += "Email address seems incorrect (check @ and .'s)";

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//error_msg += "Ths username contains invalid characters.";
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
//error_msg += "Ths domain name contains invalid characters.";
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

//error_msg += "The username doesn't seem to be valid.";
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
//error_msg += "Destination IP address is invalid!";
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
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) {
//error_msg += "The domain name does not seem to be valid.";
return false;
   }
}

/* 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) {
//error_msg += "The address must end in a well-known domain or two letter " + "country.";
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
//error_msg += "This address is missing a hostname!";
return false;
}

// If we've gotten this far, everything's valid!
return true;
}







function isURL(urlStr) {

var checkTLD=1;	
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

if (urlStr.indexOf(" ") != -1) {
//alert("Spaces are not allowed in a URL");
return false;
}

if (urlStr == "" || urlStr == null) {
return true;
}

urlStr=urlStr.toLowerCase();

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var atom=validChars + '+';
var urlPat=/^(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
var matchArray=urlStr.match(urlPat);

if (matchArray==null) {
//alert("The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s");
return false;
}

var user=matchArray[2];
var domain=matchArray[3];

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//alert("This domain contains invalid characters.");
return false;
}
}

for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i) > 127) {
//alert("This domain name contains invalid characters.");
return false;
}
}

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 does not seem to be valid.");
return false;
}
}
if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
//error_msg += "The address must end in a well-known domain or two letter " + "country.";
//alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}

return true;
} 

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    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 CardType() {
var n;
var argv = CardType.arguments;
var argc = CardType.arguments.length;

this.objname = "object CardType";

var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";
var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";
var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";

this.setCardNumber = setCardNumber;  // set CardNumber method.
this.setCardType = setCardType;  // setCardType method.
this.setLen = setLen;  // setLen method.
this.setRules = setRules;  // setRules method.
this.setExpiryDate = setExpiryDate;  // setExpiryDate method.

this.setCardType(tmpcardtype);
this.setLen(tmplen);
this.setRules(tmprules);
if (argc > 4)
this.setExpiryDate(argv[3], argv[4]);

this.checkCardNumber = checkCardNumber;  // checkCardNumber method.
this.getExpiryDate = getExpiryDate;  // getExpiryDate method.
this.getCardType = getCardType;  // getCardType method.
this.isCardNumber = isCardNumber;  // isCardNumber method.
this.isExpiryDate = isExpiryDate;  // isExpiryDate method.
this.luhnCheck = luhnCheck;// luhnCheck method.
return this;
}

/*************************************************************************\
boolean checkCardNumber([String cardnumber, int year, int month])
return true if cardnumber pass the luhncheck and the expiry date is
valid, else return false.
\*************************************************************************/
function checkCardNumber() {
var argv = checkCardNumber.arguments;
var argc = checkCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
var year = (argc > 1) ? argv[1] : this.year;
var month = (argc > 2) ? argv[2] : this.month;

this.setCardNumber(cardnumber);
this.setExpiryDate(year, month);

if (!this.isCardNumber())
return false;
if (!this.isExpiryDate())
return false;

return true;
}
/*************************************************************************\
String getCardType()
return the cardtype.
\*************************************************************************/
function getCardType() {
return this.cardtype;
}
/*************************************************************************\
String getExpiryDate()
return the expiry date.
\*************************************************************************/
function getExpiryDate() {
return this.month + "/" + this.year;
}
/*************************************************************************\
boolean isCardNumber([String cardnumber])
return true if cardnumber pass the luhncheck and the rules, else return
false.
\*************************************************************************/
function isCardNumber() {
var argv = isCardNumber.arguments;
var argc = isCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
if (!this.luhnCheck())
return false;

for (var n = 0; n < this.len.size; n++)
if (cardnumber.toString().length == this.len[n]) {
for (var m = 0; m < this.rules.size; m++) {
var headdigit = cardnumber.substring(0, this.rules[m].toString().length);
if (headdigit == this.rules[m])
return true;
}
return false;
}
return false;
}

/*************************************************************************\
boolean isExpiryDate([int year, int month])
return true if the date is a valid expiry date,
else return false.
\*************************************************************************/
function isExpiryDate() {
var argv = isExpiryDate.arguments;
var argc = isExpiryDate.arguments.length;

year = argc > 0 ? argv[0] : this.year;
month = argc > 1 ? argv[1] : this.month;

if (!isNum(year+""))
return false;
if (!isNum(month+""))
return false;
today = new Date();
expiry = new Date(year, month);
if (today.getTime() > expiry.getTime())
return false;
else
return true;
}

/*************************************************************************\
boolean isNum(String argvalue)
return true if argvalue contains only numeric characters,
else return false.
\*************************************************************************/
function isNum(argvalue) {
argvalue = argvalue.toString();

if (argvalue.length == 0)
return false;

for (var n = 0; n < argvalue.length; n++)
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;

return true;
}

/*************************************************************************\
boolean luhnCheck([String CardNumber])
return true if CardNumber pass the luhn check else return false.
Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
\*************************************************************************/
function luhnCheck() {
var argv = luhnCheck.arguments;
var argc = luhnCheck.arguments.length;

var CardNumber = argc > 0 ? argv[0] : this.cardnumber;

if (! isNum(CardNumber)) {
return false;
  }

var no_digit = CardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;

for (var count = 0; count < no_digit; count++) {
var digit = parseInt(CardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}

/*************************************************************************\
ArrayObject makeArray(int size)
return the array object in the size specified.
\*************************************************************************/
function makeArray(size) {
this.size = size;
return this;
}

/*************************************************************************\
CardType setCardNumber(cardnumber)
return the CardType object.
\*************************************************************************/
function setCardNumber(cardnumber) {
this.cardnumber = cardnumber;
return this;
}

/*************************************************************************\
CardType setCardType(cardtype)
return the CardType object.
\*************************************************************************/
function setCardType(cardtype) {
this.cardtype = cardtype;
return this;
}

/*************************************************************************\
CardType setExpiryDate(year, month)
return the CardType object.
\*************************************************************************/
function setExpiryDate(year, month) {
this.year = year;
this.month = month;
return this;
}

/*************************************************************************\
CardType setLen(len)
return the CardType object.
\*************************************************************************/
function setLen(len) {
// Create the len array.
if (len.length == 0 || len == null)
len = "13,14,15,16,19";

var tmplen = len;
n = 1;
while (tmplen.indexOf(",") != -1) {
tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);
n++;
}
this.len = new makeArray(n);
n = 0;
while (len.indexOf(",") != -1) {
var tmpstr = len.substring(0, len.indexOf(","));
this.len[n] = tmpstr;
len = len.substring(len.indexOf(",") + 1, len.length);
n++;
}
this.len[n] = len;
return this;
}

/*************************************************************************\
CardType setRules()
return the CardType object.
\*************************************************************************/
function setRules(rules) {
// Create the rules array.
if (rules.length == 0 || rules == null)
rules = "0,1,2,3,4,5,6,7,8,9";
  
var tmprules = rules;
n = 1;
while (tmprules.indexOf(",") != -1) {
tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);
n++;
}
this.rules = new makeArray(n);
n = 0;
while (rules.indexOf(",") != -1) {
var tmpstr = rules.substring(0, rules.indexOf(","));
this.rules[n] = tmpstr;
rules = rules.substring(rules.indexOf(",") + 1, rules.length);
n++;
}
this.rules[n] = rules;
return this;
}
//  End -->