// Form helper functions
// REQUIRES: eventHelper.js

function IsCharacterFound(strVal,strChar)
{
	if (strVal.indexOf(strChar)>=0)
		return true;
	return false;
}

//check whether the title is empty or not
function checkProgram(cboAdmin)
{
	id = cboAdmin.id;
	blnValue = (cboAdmin.value == '-1');
	
	if (id == 'cboAdminPFS')
	{
		if(!document.frmManagePrograms.elements['chkProgramPFS'].disabled)
			document.frmManagePrograms.elements['chkProgramPFS'].checked = !blnValue;
	}	
}
function IsProgramAdminSelected(strAdmin)
{
	//var blnProgram = new Boolean(strProgram);
	return (strAdmin == '-1');
}
function checkTitle(sTitle, sOtherTitle)
{
	return ( (sTitle=="-1") || (compareStrings(sTitle,"13",true) && !checkString(sOtherTitle) ) );
}
// check if title select is other then it will enable the other title field
function checkTitleDisable(val,id)
{
	var txtTitleOther = document.getElementById(id);
	if(val == '13')
		txtTitleOther.disabled = false;
	else
		txtTitleOther.disabled = true;
}
// check if Food Contract dropdown is true or not
function checkFoodDropdownDisable(val,id)
{
	var cboFoodContract = document.getElementById(id);
	if(val == true)
		cboFoodContract.disabled = false;
	else
		cboFoodContract.disabled = true;
}

//check for valid user name - allowed characters a-z, A-Z, 0-9, and ( . - _ @ )
function IsValidUserName( s )
{
	s = TrimAll(s);

	for (i=0; i<s.length; i++)
	{
		ch = s.charAt(i);
		if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch=='.' || ch=='-' || ch=='_' || ch=='@' )
		{
		}
		else
		{ return false;	}
	}
	
	return true;
}
function IsValidTaxID( tax1, tax2 )
{
	if (tax1.length != 2 || tax2.length != 7)
		return false;
	if ( !IsNumericOnly(tax1) || !IsNumericOnly(tax2) )
		return false;
	return true;
}
//check for valid zip code against format "ddddd-dddd or ddddd"
function IsZipcode( sValue )
{
	if (sValue.length <= 4) return false;
	if (sValue.length == 5) return IsNumericOnly(sValue);
	if (sValue.length > 5 && sValue.length <=9) return false;
	if (sValue.length > 10) return false;
	
	if (sValue.length == 10)
	{
		for (var i=0; i < sValue.length; i++)
		{
			if (i==5 && sValue.charAt(5) != '-' ) return false;
			if (i!=5 )
			{
				if ( ! IsNumericOnly(sValue.charAt(i)) ) return false;
				if ( parseInt(sValue.charAt(i),10)<0 && parseInt(sValue.charAt(i),10)>9  )
					return false;
			}
		}
	}
	return true;
}

// check for valid password
function checkPassword(s)
{
	s = TrimAll(s);
	var rv = new Boolean();
	rv = true;
	for (i=0; i<s.length; i++)
	{
		ch = s.charAt(i);
		if ( !(ch >= 'a' && ch <= 'z') && !(ch >= 'A' && ch <= 'Z') && !(ch >= '0' && ch <= '9') )
		{
			rv = false;
			break;
		}
	}
	if (rv == true)
	{
		blnDigitFound = (s.search(/[0-9]/) == -1 ? false : true);
		blnLetterFound = (s.search(/[a-zA-Z]/) == -1 ? false : true);
		rv = (blnLetterFound && blnDigitFound);
	}
	return rv;
}
//  check for valid phone numbers against format "(phone1)phone2-phone3"
function checkPhone(phone1, phone2, phone3)
{
	if ( !checkString(phone1) || !checkString(phone2) || !checkString(phone3))
		return false;
	if (phone1.length != 3 || phone2.length != 3 || phone3.length != 4)	
		return false;
	if (!IsNumericOnly(phone1) || !IsNumericOnly(phone2) || !IsNumericOnly(phone3))
		return false;
	return true;
}
//  check for valid integer numeric strings	
function IsNumericOnly(strString)
{
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}
// Check for a valid e-mail address
function checkEmail(s) {
/*
	var emailReg = '^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$';
	var regex = new RegExp(emailReg);
	return regex.test(s);
*/
  var result = false;
  var theStr = new String(s);

	if (theStr.length == 0) return false;
	
  for (i=0; i<theStr.length; i++)
  {
	ch = theStr.charAt(i);
	if ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch=='_' || ch=='.' || ch=='-' || ch=='@')
	{ 
		//do nothing 
	}
	else
		return false;
  }
	
	var strInValidChars = new String("'\"`~!#$%^&*()+=|\\/:;, ");
	var strChar;
	//test strString consists of Invalid characters
	for (i = 0; i < theStr.length; i++)
	{
		strChar = theStr.charAt(i);
		if (strInValidChars.indexOf(strChar) >= 0)
		{
			strInValidChars.indexOf(strChar);
			return false;
		}
	}

	var index = theStr.indexOf("@");
	if (index > 0)
	{
		var pindex = theStr.indexOf(".",index);
		if ((pindex > index+1) && (theStr.length > pindex+1))
			result = true;
	}
	var Expr =  /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;      
	if (Expr.test(theStr) )
		result = true
	else
		result = false
		
	return result;

}

// Check for a valid string
function checkString(s) {
	s = TrimAll(s);
	return ((s != null) && (s.length > 0));
}

// Check for a valid boolean
function checkBoolean(b) {
	return (new Boolean(b)).valueOf();
}

// Compare the values of two strings
//   s1 - string one
//   s2 - string two
//   nocase - if set to true, does a case-insensitive compare
function compareStrings(s1, s2, nocase) {
	if (s1 == null && s2 == null) return true; // both null, compare is equal
	if (s1 == null || s2 == null) return false; // one null, but not both, compare is not equal
	if (nocase) { s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); }
	return (s1 == s2);
}

// Event handler to check for ENTER key press in forms
function checkEnterPressed(evt) {
	var keycode;
	if (evt) keycode = (window.event) ? evt.keyCode : evt.which;
	else return false;
	if (keycode == 13 || keycode == 10) return true;
	else return false;
}

// Add key-capturing events to all text fields of a given form
function formKeyCapture(id, fn)
{
	var frm = document.forms[id];
	var inputs = frm.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'text' || inputs[i].type == 'password') {
			//alert('Adding key event to: ' + inputs[i].getAttribute('id'));
			addKeyEvent(inputs[i], fn);
		}
	}
	var selects = frm.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++) {
		addKeyEvent(selects[i], fn);
	}
}
function IsNumeric(strString)
//  check for valid numeric strings	
{
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;
	
   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
			blnResult = false;
         }
      }
   return blnResult;
}

function checkDoubleQuotes(s)
{
	/*
	for (i=0; i<s.length; i++)
	{
		if ( !( (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') || (s.charAt(i) >= '0' && s.charAt(i) <= '9') ) )
		{ return false; }
	}
	*/
	if (s.indexOf('"')>=0)
		return false;
	return true;
}

function checkSpecialCharacter(s)
{
	if(s.indexOf('<') != -1 || s.indexOf('>')!= -1)
	{
		return false;
	}
	return true;
}

function LTrimAll(str)
{
	if (str==null){return str;}
	for (var i=0; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i++);
	return str.substring(i,str.length);
}

function RTrimAll(str)
{
	if (str==null){return str;}
	for (var i=str.length-1; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i--);
	return str.substring(0,i+1);
}

function TrimAll(str) 
{
	return LTrimAll(RTrimAll(str));
}

function ReadCookie(cookieName) 
{
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return "";
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length; 
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function SetCookie(cookieName,cookieValue,nDays) 
{
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString();
}

function TestCookie() 
{
	testValue=Math.floor(1000*Math.random());
	SetCookie('AreCookiesEnabled',testValue);
	return testValue==ReadCookie('AreCookiesEnabled')
}

function IsValidDate(day,month,year)
{
    if (isNaN(day))
        { return false; }
    
    if (isNaN(month))
        { return false; }
        
    if (isNaN(year))
        { return false; }
    
    if (month>12 || month<1)
        { return false; }
    
    if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
    && (day > 31 || day < 1))
        { return false; }
    
    if ((month == 4 || month == 6 || month == 9 || month == 11) && (day > 30 || day < 1))
        { return false; }
    
    if (month == 2)
    {
        if (day < 1)
            { return false; }
        
        if (LeapYear(year) == true)
        {
            if (day > 29)
                { return false; }
        }
        else
        {
            if (day > 28)
                { return false; }
        }
    }
    
    return true;
}

function LeapYear(intYear)
{
    if (intYear % 100 == 0)
    {
        if (intYear % 400 == 0)
            { return true; }
    }
    else
    {
        if ((intYear % 4) == 0)
            { return true; }
    }
    
    return false;
}
