// JavaScript Document

/*****************************************************************************\
+-----------------------------------------------------------------------------+
| Project        : GoLocal247.com			                                  |
| FileName       : formvalidation.js        	                              |
| Version        : 1.0                                                        |
| Developer      : Pinal Sakarvadia                                           |
| Created On     : 16-03-2008                                                 |
| Modified On    :                                                            |
| Modified By    :                                                            |
| Authorised By  : Pinal Sakarvadia                                           |
| Comments       : This file will conatain basic form validaion regular exp.  |
| Email          : pinalsakarvadia@greymatterindia.com                        |
+-----------------------------------------------------------------------------+
\*****************************************************************************/

function isHTML(str)
{
	var re = new RegExp("\<[a-zA-Z]|\</[a-zA-Z]|\< [a-zA-Z]|\<[a-zA-Z0-9 ]*\>");
	
	if(str.match(re))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isurl(obj,stmnt)
{
	var objRegExp  =  /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
	//var objRegExp=/^(ht|f)tp(s?)\:\/\/((www\.)*)+(([a-zA-Z_0-9-])+)+\.(com|net|org|edu|gov|mil|int|arpa|aero|biz|coop|info|museum|name|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cf|cd|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|fx|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zr|zw)$/ ;
	var test = objRegExp.test(dotrim(obj.value));
	
	if(test == false)
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
	return true;	
}




function isprice(obj,stmnt)
{
	var objRegExp  =  /^\d+\.\d{2}$/;
	var test = objRegExp.test(dotrim(obj.value));
	
	if(test == false)
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
	return true;	
}

function dotrim(strComp)
{
	/*ltrim = /^\s+/
	rtrim = /\s+$/
	strComp = strComp.replace(ltrim,'');
	strComp = strComp.replace(rtrim,'');
	*/
	strTrimString = strComp.replace(/^\s+|\s+$/g, '') ;
	
	return strTrimString;
}
			
function ischecked(obj,stmnt,i)
{
	flag = false;

	for(j=0;j<=i;j++)
		if(obj[j].checked == true)
			flag = true;

	if(flag == false)
	{
		alert(stmnt);
		obj[0].focus();
		return false;			
	}
	return true;
}

function ischeckedbox(obj,stmnt,i)
{
	flag = false;	

	if(obj.checked == true)
		flag = true;

	if(flag == false)
	{
		alert(stmnt);
		obj.focus();
		return false;			
	}
	return true;
}

function isselected(obj,stmnt)
{
	
	if(obj.options[obj.selectedIndex].value == "")
	{
		alert(stmnt);
		obj.focus();
		return false;		
	}
	return true;
}

function isblank(obj,stmnt)
{
	if(dotrim(obj.value) == "")
	{
		if(stmnt != '') 
		{
			alert(stmnt);
		}
		obj.focus();
		return false;
	}
	return true;
}

function isnumber(obj,stmnt)
{ 
	var objRegExp  =  /(^-?\d\s\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	var test = objRegExp.test(obj.value);
	if(test == false)
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
	return true;
}

function isnotnumber(obj,stmnt)
{ 
	var objRegExp  =  /(^-?\d\s\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	var test = objRegExp.test(dotrim(obj.value));
	if(test == true)
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
	return true;
}

function isemail(obj,stmnt)
{ 
	var objRegExp  = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;	

	//if(obj.value.indexOf(",")!="-1")	
	if(obj.value.indexOf(",")>=0)
	{
		var emailarr = new Array();
		emailarr = obj.value.split(",");
		for(i=0;i<emailarr.length;i++)
		{
			var t = dotrim(emailarr[i]);
			if(t!="")
			{
				t = objRegExp.test(t);
				if(t == false)
				{
					alert(stmnt);
					obj.focus();
					return false;
				}
			}
			else
			{
				alert(stmnt);
				obj.focus();
				return false;
			}
		}//end of for loop
	}
	else
	{
		var test = objRegExp.test(dotrim(obj.value));
		if(test == false)
		{
			alert(stmnt);
			obj.focus();
			return false;
		}
	}
	 /*** Added By Alok Jain **/
	var regExPattern= /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
	if(! obj.value.match(regExPattern) )
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
	
	return true;
}

function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

function isCheckedOrNot(obj,  stmt)
{
	var flag = false
	for (var i=0; i < obj.length; i++)
	{
		if (obj[i].checked)
		{
			flag = true;
		}
	}
	if (flag == false)
	{
		if(stmt != '')
		alert(stmt);
	}
	
	return flag;
	
}

/* Kalyani- for checking the length of the checkboxes with the minumum count */
function isCheckedCount(obj, minCount, stmt)
{
	var flag = false;
	currentLength = 0;
	
	for (var i=0; i < obj.length; i++)
	{
		if (obj[i].checked)
		{
			currentLength = currentLength +1;
		}
	}
	
	if(currentLength < minCount)
		alert(stmt);
	else
		flag = true;
	
	return flag;
	
}

function deleteAlert(url,messgae)
{
	if(confirm(messgae))
	{
		window.location.href=url;
	}
}

function UnArchiveAlert(url,messgae)
{
	if(confirm(messgae))
	{
		window.location.href=url;
	}
}

function spCharChk(obj)
{
	var objRegExp  =  /^[a-zA-Z0-9-_ ]+$/;
	var test = objRegExp.test(dotrim(obj.value));
	if(test == false)
	{
		obj.focus();
		return false;
	}
	return true;	
}
/* Ganesh Kadam - check valid phone number*/
function isValidPhoneNumber(obj,stmnt)
{ 
	//(233) 232-3242
	var digits = "0123456789";
	var phoneNumberDelimiters = "()- ";
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	var minDigitsInIPhoneNumber = 3;
	//++ -- -+ +-
	var strPhone = dotrim(obj.value);
	var f1= strPhone.indexOf("++");
	if(f1 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f2= strPhone.indexOf("--");
	if(f2 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f3= strPhone.indexOf("+-");
	if(f3 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f4= strPhone.indexOf("-+");
	if(f4 >= 0) 
	{
		alert(stmnt);
		return false;
	}

	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	if(isInteger(s) && s.length >= minDigitsInIPhoneNumber)
	//if(isInteger(s) && parseInt(s) > 0)
		return true;
	else
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
}
function isValidPhoneNumbers(obj,stmnt)
{ 
	//(233) 232-3242
	var digits = "0123456789";
	var phoneNumberDelimiters = "()- +";
	//var validWorldPhoneChars = phoneNumberDelimiters + "+";
	
	//var minDigitsInIPhoneNumber = 10;
	//++ -- -+ +-
	var strPhone = dotrim(obj.value);
	var f1= strPhone.indexOf("++");
	if(f1 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f2= strPhone.indexOf("--");
	if(f2 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f3= strPhone.indexOf("+-");
	if(f3 >= 0) 
	{
		alert(stmnt);
		return false;
	}
	var f4= strPhone.indexOf("-+");
	if(f4 >= 0) 
	{
		alert(stmnt);
		return false;
	}

	s=stripCharsInBag(strPhone,phoneNumberDelimiters);
	if(isInteger(s) && s.length > 0)
	//if(isInteger(s) && parseInt(s) > 0)
		return true;
	else
	{
		alert(stmnt);
		obj.focus();
		return false;
	}
}
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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function spCharChkwithAnd(obj)
{
	var objRegExp  =  /^[a-zA-Z0-9-  ,_& \-\' \s ]+$/;
	var test = objRegExp.test(dotrim(obj.value));
	if(test == false)
	{
		obj.focus();
		return false;
	}
	return true;	
}


function chkNumDescr(obj)
{
    num=dotrim(obj.value);
    var reNum=/^[0-9 \s]+$/
    if(reNum.test(num))
    	return true;
    else
    	return false;
}
function IsValidDate(Day,Mn,Yr)
{
    var DateVal = Mn + "/" + Day + "/" + Yr;
    var dt = new Date(DateVal);

    if(dt.getDate()!=Day){
       // alert('Invalid Date');
        return(false);
        }
    else if(dt.getMonth()!=Mn-1){
    //this is for the purpose JavaScript starts the month from 0

        //alert('Invalid Date');
        return(false);
        }
    else if(dt.getFullYear()!=Yr){
        //alert('Invalid Date');
        return(false);
        }
        
    return(true);
 }
// var imagetype_array = new Array();
//imagetype_array[0]='gif';
//imagetype_array[1]='jpg';
//imagetype_array[2]='jpeg';
	
function is_imagetype(fileObj) 
{
    imagefile_value=dotrim(fileObj.value);
    var checkimg = imagefile_value.toLowerCase();

        if(!checkimg.match(/(\.jpg|\.jpeg|\.gif|\.png|\.pjpeg)$/))
        {
            return false;
        }
        else	
        {
        	return true;
        }
         	
     
//	for(var i = 0; i < imagetype_array.length ; i++) {
//		//alert(v_array[i]);
//		if(imagetype_array[i] == p_val) {
//			return true;
//		}
//	}
	//return false;
}
function dateDifference(dateObj1,dateObj2)
{
	
    var arr1=dateObj1.split('-');
    var arr2=dateObj2.split('-');
    
    var startDate=new Date(arr1[0],arr1[1], arr1[2]); 
    var endDate=new Date(arr2[0],arr2[1], arr2[2]); 
    
    var one_day=1000*60*60*24;
    var dateDiff=Math.ceil((endDate.getTime()-startDate.getTime())/(one_day));
    
    if(dateDiff >= 0)
    return true;
    else
    return false;
}   


/*************************************************************************
*      To check the emal address it is validate or not.					 *
*	   Add By :- Jagdish Gade                                            *
*      Date:- 9-April-2009          									 *
**************************************************************************/

// Email validate function
function emailCheck (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)\.(\d)\.(\d)\.(\d)\]$/
         /* 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("Entered Email address is not valid. (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("The Email doesn't seem to be valid.");
             alert("Entered Email address is not 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) {
                         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.")
                 alert("Entered Email address is not 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) {
            // the address must end in a two letter or three letter word.
            alert("The 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 address is missing a hostname!"
            alert(errStr)
            return false
         }

         // If we've gotten this far, everything's valid!
         return true;
         }
function checkHtmTag(str){
	 if(str.match(/([\<])([^\>]{1,})*([\>])/i)!=null) {
       return false;
		}
	    else{
        	return true;
	    }

	
}
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

function validPhone(str){
	str = dotrim(str);
	if(str == '0')	
	 return false;
	if(str == '00')	
	  return false;
	if(str == '000')	
		return false;
	if(str == '0000')	
		return false;
	
	return true;
}

//Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars ="+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	var bracket=3
	strPhone=trim(strPhone)
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	var brchr=strPhone.indexOf("(")
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
	}

function isZip(s) 
{

     // Check for correct zip code
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
     if (!reZip.test(s)) {          
    	 return false;
     }

return true;
}

function checkChar(s){
	var noalpha = /^[a-zA-Z]*$/;
	if (!noalpha.test(s)) {          
        return false;
   }

return true;

}
function checkAlphaNumeric(string)	
{
  var an_string = string.replace(/[^a-zA-Z 0-9]+/g,'');
  if (an_string == string) {
      return true;
   } else {
      return false;
    }
}    

function checkInputLength(obj,objlength, type, stmt)
{
	if(type =='min'){
		if(dotrim(obj.value).length < objlength)
		{
			alert(stmt)
			obj.focus();
			return false;
		}
	}else if(type =='max'){
		if(dotrim(obj.value).length > objlength)
		{
			alert(stmt)
			obj.focus();
			return false;
		}
	}
	return true;
}

