//This function is used to select and unselect all the check box of the given name.
//fmobj id	= 	the form oblect
//chekname	=	The checkbox name to be select and unselect.
function chk(frm)
{	
	var email_chk=/(^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$)/i;
	var msg='Please enter valid data for the following fields\n------------------------------------------------------'; 
	//Fields marked (*) are mandatory\n';
	var foc=-1;
	if(typeof fields != "undefined"){
		for(i=0; i<fields.length; i++){
			var field = eval('frm.'+fields[i]);
			var field_value = getFieldValue(field);
			if(empty(field_value)){
				if(!field.disabled) { 
					if(foc==-1)foc=fields[i];
					msg+='\n'+msgs[i];
				} 
			}
		}
	}
	if(typeof emails != "undefined"){
		for(j=0; j<emails.length; j++){
			var field_value = eval('frm.'+emails[j]+'.value');
			if(!email_chk.test(field_value) && !empty(field_value) ){
				if(foc==-1)foc=emails[j];
				msg+='\n'+email_msgs[j];
			}
		}
	}
	if(typeof nums != "undefined")
	{

		for(k=0; k<nums.length; k++)
		{
			var field_value = eval('frm.'+nums[k]+'.value');
			if (typeof num_zero!='undefined')
			{
					if ((num_zero==0))
					{
						if(!empty(field_value) && (isNaN(field_value) || (field_value <= 0))){
							if(foc==-1)foc=nums[k];
							msg+='\n'+nums_msgs[k];
						}
					}
					else
					{
						if(!empty(field_value) && (isNaN(field_value)))
						{
							if(foc==-1)foc=nums[k];
							msg+='\n'+nums_msgs[k];
						}
					}
			}
			else
			{
					if(!empty(field_value) && (isNaN(field_value) || (field_value <= 0))){
							if(foc==-1)foc=nums[k];
							msg+='\n'+nums_msgs[k];
						}

			}
		}
	}
	
	if(foc!=-1)
	{
		alert(msg);
		var fieldType = eval('frm.' + foc + '.type');
		if(fieldType && fieldType!='hidden' && fieldType!='radio' && fieldType!='checkbox')
		{
			eval('frm.'+foc+'.focus()')
		}		
		return(false);
	} else {
		return(true);
	}
}

function empty(str)
{
	var empty_chk=/(^[\ ]*$)/i;
	if(!empty_chk.test(str))return false;
	return(true);
}

function getFieldValue(field)
{
   switch(field.type)
   {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         return field.value;
      case "select-one" :
         var i = field.selectedIndex;
         if (i == -1)   return "";
         else   return field.options[i].value ;
		 /*return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;*/
      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < field.options.length; i++)
            if(field.options[i].selected)
               allChecked[allChecked.length] = (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
         return allChecked;
      case "button":
      case "reset":
      case "submit":
         return "";
      case "radio" :
	  case "checkbox" :
         if (field.checked) { return field.value; } else { return ""; }
      default :
         if(field[0].type == "radio")
         {
            for (i = 0; i < field.length; i++)
               if (field[i].checked)
                  return field[i].value;

            return "";
         }
         else if(field[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < field.length; i++)
               if(field[i].checked)
                  allChecked[allChecked.length] = field[i].value;
            return allChecked;
         }
         break;
   }
   
   return "";
}
//This function can be used with listing pages like category listing in admin side for Mass Update.
function CheckCheckAll(fmobj,chekname) {
	
var TotalBoxes = 0;
var TotalOn = 0;
for (var i=0;i<fmobj.elements.length;i++)
	{
	var e = fmobj.elements[i];
	if(fmobj.select_all.checked==true)
		{
			if(e.name==chekname)
			{e.checked=true;}
		}
	else
		{
				if(e.name==chekname)
				{e.checked=false;}
		}
	}
}
function isValidURL(urlStr) {
	if (urlStr.indexOf(" ") != -1) {
	return false;
	}

	if (urlStr == "" || urlStr == null) {
	return true;
	}

	urlStr=urlStr.toLowerCase();

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var urlPat=/^http:\/\/(\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;
	}
	}

return true;
}  
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 to display image of real size

function popUp(url) {
	//alert(url);
window.open(url, "name_of_window", "width=600,height=500,left=20,top=20,scrollbars=yes,menubar=no, resizable=no,location=no,toolbar=no");
}

function emailCheck(email)
{
	var email_chk=/(^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$)/i;
	if(email_chk.test(email))
	{
		return true;	
	}
	else
	{
		return false;
	}
}
function emailCheckingcc(str) {
  		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true
}
function emailChecking(emailStr) {
	/* 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. */
		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    alert("Email address seems incorrect")
	    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) {
		        alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("The Domain Name doesn't seem to be valid.")
	    return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length 
	if (domArr[domArr.length-1].length<2 || 
	    //domArr[domArr.length-1].length>3) {
		 domArr[domArr.length-1].length>4) {
	   // the address must end in a two letter or three letter word.
	   alert("The E-mail address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This E-mail address is missing a hostname!"
	   alert(errStr)
	   return false
	   }
	   // If we've gotten this far, everything's valid!
	return true	   
}
// end o
// A Domain check , which must start with http://www. or https://www.
// First argument will be the string to check
// Second argument will be the message to print out
function domainCheck(){
	var strDomain = "";	
	
	if(arguments.length == 0){
		return false;
	}else{
		strDomain = arguments[0];
		strTitle = arguments.length > 1 ? arguments[1] : "URL";
	}
	
	if(strDomain.indexOf("http://www.") == -1 && strDomain.indexOf("https://www.") == -1){
		alert(strTitle + " must start with 'http://www.' or 'https://www.' .");
		return false; 
	}else{
		var strUrl ="";
		if(strDomain.indexOf("http://www.") == -1)
			strUrl = strDomain.substr(12);
		else
			strUrl = strDomain.substr(11);
		
		var domPat = /^([^.]+\.)+[a-zA-Z]{2,3}(\/.*)?$/;
		arrMat = strUrl.match(domPat);
		if(arrMat == null){
			alert("Enter a valid " + strTitle +".");
			return false; 
		}
	}
	return true;
}
function lcaseCheck(e) {
	key = getKeyCodeVal(e);
	if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
		return true;
	else if ((key > 96 && key < 123) || (key > 47 && key < 58))
		return true;
	else
		return false;
}
function getKeyCodeVal(e) {
 if (window.event)
    return window.event.keyCode;
 else if (e)
    return e.which;
 else
    return null;
}

function imposeMaxLength(the){
	var mlength=250;
		if (the.value.length>mlength){
			the.value=the.value.substring(0,mlength);
			alert("Maximum 250 Characters are allowed");
			return false;
		}
}
