//
// Constants for isCharsInBag
//
var NUMBERS = "0123456789";
var NUMBERS_ONLY = ".,0123456789";
var NUMBER_ONLY = ".,123456789";
var ALPHABETS_ONLY = "abcdefghijklmnopqrstuvwxyz";
var ALPHANUMERIC = NUMBERS_ONLY + ALPHABETS_ONLY;
var COMMON_SPECIAL = "& ,/-._'";
var COMMON_NUMBERS = NUMBERS_ONLY + COMMON_SPECIAL;
var ALPHA_COMMON = ALPHABETS_ONLY + COMMON_SPECIAL;
var NAME = ALPHA_COMMON;
var ALPHANUMERIC_COMMON =  ALPHANUMERIC + COMMON_SPECIAL + "#";
var COMMON_AMP =  " &,/-._'";
var EMP =  ALPHANUMERIC + COMMON_AMP +"@";
var EMAIL =  ALPHANUMERIC + COMMON_AMP +"@";

//
// Other constants - for specific types of fields
//

var LOGINID = ALPHANUMERIC +"_.-@";
var PHONE = NUMBERS_ONLY+"()[]+"+COMMON_SPECIAL;
var PHONE_DF = NUMBERS+" -().";
var ADDRESS = ALPHANUMERIC+"&@#()[]!"+COMMON_SPECIAL;
var CREDITCARDNUMBER = "0123456789";

//
// Error message constants for English
//

var INVALID_DAY_MESSAGE="Please enter a two-digit numeric day (01-31)";
var INVALID_YEAR_MESSAGE="Please enter a four-digit year later than 1800";

var INVALID_DATE_MESSAGE="The date you have entered is later than the current date. The field can only accept dates before the current date.";

var FILL_ALL_FIELDS_MESSAGE="Please complete all the fields in a row.\nIf you do not wish to enter information in this row, please clear the information you have entered.";

var FILL_ALL_BEFORE_ADDMORE_MESSAGE="Please complete all the rows on this page before you choose to add more information.\nIf you are done entering information, click the Next button below to proceed";

var INVALID_SSN_MESSAGE="The Social Security Number you have entered appears to be incorrect. Please review it to make sure it is entered properly.";
var MANDATORY_FIELD_MESSAGE="Please review the information you have entered and fill the following fields:\n";
var MANDATORY_TEXT_FIELD_MESSAGE="Please review the information you have entered and fill the textarea:\n";
var MANDATORY_FIELD_POSTFIX = "\n\nFor your convenience, we have marked all the fields that must be filled with a *\n\nPlease complete all the fields marked with a * before you proceed.\n";
var SELECT_LIST_MESSAGE_PREFIX="Please select the ";
var SELECT_CHECKBOX_MESSAGE_PREFIX="Please select one of the options in the ";
var SELECT_CHECKBOX_MESSAGE_POSTFIX=" field.";
var SELECT_CHECKBOX_DISCLAIMER_MESSAGE_PREFIX="Please click on OK to ALL the terms listed and then click ";
var SELECT_CHECKBOX_DISCLAIMER_MESSAGE_POSTFI="to proceed. Click Ok to close this box";

//
// Constants from validateRow  - distinguish between a fulfilled row
// an empty row and a partly filled row
//

var ROW_FULLY_FILLED = 0;
var ROW_PARTLY_FILLED = 1;
var ROW_NOT_FILLED = 2;

//
// Global debug flag, which determines if the browser will print 
// script error messages
//

var DEBUG=true;

//
// Set the runtime error handler to our own, which effectively disables
// runtime errors if DEBUG is set to false
//

window.onerror = handleRuntimeError;

//
// All pages define this function as a runtime error handler, which 
// suppresses the standard error message
//

function handleRuntimeError()
{
  // 
  // Returning true here causes the error not to be printed. 
  // This is !DEBUG, so we just return that.
  //

  return !DEBUG;
}

//
// Check if a phone number field has certain length
//

function isOfSize (s, size)	
{  
	// Search through string's characters one by one.

	for (var i = 0; i < s.length; i++)
    	{   
		alert("Ph"+ s.charAt(i));
   		// Check that current character isn't whitespace.
        	//var c = s.charAt(i);
	        //if (bag.indexOf(c) == -1) 
		//return false;
    	}

    	//return true;
}


//
// Check if a field contains only a given set of characters
//

function isCharsInBag (s, bag)	
{  
	// Search through string's characters one by one.

	for (var i = 0; i < s.length; i++)
    	{   
   		// Check that current character isn't whitespace.
        	var c = s.charAt(i);

	        if (bag.indexOf(c) == -1) 
		   return false;
    	}

    	return true;
}


//
// Check to see if a field is empty
//

function isEmpty(s)   			
{
	return ((s == null) || (s.length == 0));
}

//
// Check to see if a field is all whitespace
//

function isWhitespace(s)		
{
	var whitespace="\t\n\r";

	var i;   
 	
	// Is s empty?
  
	if (isEmpty(s))	       
    	    return true; 		       

	// Search through string's characters one by one
	// until we find a non-whitespace character.
	// When we do, return false; if we don't, 
	// return true.

       	for (i = 0; i < s.length; i++)
	{					    
          // Check that current character isn't whitespace.
   	  
         var c = s.charAt(i);
	
         if (whitespace.indexOf(c) == -1)
	     return false;
	}				  

        // All characters are whitespace.

	return true;	
}

//
// Append a string to another
//

function buildStr(s, s1)		
{
   if (s.length > 0) 
       s = " " + s;

    s = s + s1;
    return s;
}

//
// For "Next" actions; add a "mode=next" to the action URL
//

function next() {
        document.forms[0].elements[0].value = "next";
	validateCheck();
}


//
//  Get a form field, given its name
//
//

function getFormField(fieldName)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == fieldName)
    {
      formField = document.forms[0].elements[counter];
	return formField;

    }
  }
}


//
// Check all mandatory fields and display an appropriate error message
// if they're not filled
//

function mandatoryAlert(fieldValues, fieldNames)
{
  var fieldsNotFilled = "";

  for (var counter =0; counter < fieldValues.length; counter++)
  {
    if (isWhitespace((getFormField(fieldValues[counter])).value.toLowerCase()))
    {
      fieldsNotFilled = buildStr(fieldsNotFilled,"\n"+fieldNames[counter]);
     }
  }

  if ( fieldsNotFilled.length > 0 )
     {
       alert(MANDATORY_FIELD_MESSAGE + fieldsNotFilled + MANDATORY_FIELD_POSTFIX);
       return;
     }
}



//
// Check all mandatory textarea fields and display an appropriate error message
// if they're not filled
//

function mandatoryTextAlert(fieldValues, fieldNames)
{
  var fieldsNotFilled = "";

  for (var counter =0; counter < fieldValues.length; counter++)
  {
    if (isWhitespace((getFormField(fieldValues[counter])).value.toLowerCase()))
    {
      fieldsNotFilled = buildStr(fieldsNotFilled,"\n"+fieldNames[counter]);
     }
  }

  if ( fieldsNotFilled.length > 0 )
     {
       alert(MANDATORY_TEXT_FIELD_MESSAGE + MANDATORY_FIELD_POSTFIX);
       return;
     }
}


//
// Validate a field given a character bag (possibly one of the constants 
// defined above)
//

function validateField(field, fieldName, bag)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
    {
      formField = document.forms[0].elements[counter];
      break;
    }
  }

  if (!isCharsInBag(formField.value.toLowerCase(), bag))
  {
    alert("There appear to be characters in the "+fieldName+" field that should not be present.\nPlease review the information you have entered and correct any mistakes you may have made.");
    focusSelect(formField);
    return false;
  }
  return true;
}

// Validate the field if it has the value 0
//
//


function validateZero(field, fieldName)
{
  var formZeroField;
  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
	{
	formZeroField = document.forms[0].elements[counter].name[0];
	alert(formZeroField);
	}
}
	if(formZeroField)

	{
        alert("There appear to be characters in the "+fieldName+" field that should not be present.\nPlease review the information you have entered and correct any mistakes you may have made.");
    focusSelect(field);
     }
  
}
//
// Validate a list box to make sure that a valid option is selected
//

function validateList(field, fieldName)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
    {
      formField = document.forms[0].elements[counter];
      break;
    }
  }

 if (formField.selectedIndex == 0) 
  {
    alert(SELECT_LIST_MESSAGE_PREFIX+fieldName);
    focusSelect();
    return false;
  }
  return true;
}   

//
// Validate a set of radio buttons and make sure that one is always
// selected
//

function validateCheckBox(field, fieldName)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
    {
      formField = document.forms[0].elements[counter];

      if (formField.checked == true)
          return true;	
    }
  }

  alert(SELECT_CHECKBOX_MESSAGE_PREFIX +fieldName+ SELECT_CHECKBOX_MESSAGE_POSTFIX);
  return;
}


//
// Validate a set of check boxes and make sure that all are
// selected before the user is sent to the next page. 
// The User should agree to all the conditions
//

function validateCheckDisclaimer(field, fieldName)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
    {
      formField = document.forms[0].elements[counter];

      if (formField.checked == true)
          return true;	
    }
  }

  alert(SELECT_CHECKBOX_DISCLAIMER_MESSAGE_PREFIX +fieldName+ SELECT_CHECKBOX_DISCLAIMER_MESSAGE_POSTFIX);
  return;
}

//
//
//

function validateRadio(field, fieldName)
{
  var formField;

  for (var counter = 0; counter < document.forms[0].elements.length; counter++)
  {
    if (document.forms[0].elements[counter].name == field)
    {
      formField = document.forms[0].elements[counter];
      
      if (formField.checked == true)
          return true;	
    }
  }
 
  alert(SELECT_CHECKBOX_MESSAGE_PREFIX +fieldName+ SELECT_CHECKBOX_MESSAGE_POSTFIX);
  return;
}

//
// Common code to focus(), select(), call net() and return
//

function focusSelect(field)
{
  field.focus();
  field.select();
  net();
  return;
}

//
// Vali date
//

function dateValidate(day, month, year, beforeToday)
{
        var monthList = "JanFebMarAprMayJunJulAugSepOctNovDec";

        var dayField = getFormField(day);
        var monthField = getFormField(month);
        var yearField = getFormField(year);

        var dayValue = dayField.value;
	var monthValue = monthField[monthField.selectedIndex].text;
	var yearValue = yearField.value;

        // Current date 

  	var present = new Date();	

	// The information the user entered in Date form

	var userDate;

	if (dayValue.length > 2 || dayValue.length == 0)
	{
	  alert(INVALID_DAY_MESSAGE);
	  focusSelect(dayField);
	  return false;
        }

	if (!isCharsInBag(dayValue, NUMBERS_ONLY))
	{
	  alert(INVALID_DAY_MESSAGE);	
	  focusSelect(dayField);
          return false;
	}
          
        if (dayValue <= 0 || dayValue > 31)
        {
          alert(INVALID_DAY_MESSAGE);
          focusSelect(dayField);
          return false;
        }

        if (yearValue.length != 4 || yearValue < 1800)
	{
	  alert(INVALID_YEAR_MESSAGE);
          focusSelect(yearField);
          return false;
        }
	
	if (!isCharsInBag(yearValue, NUMBERS_ONLY))
	{
	  alert(INVALID_YEAR_MESSAGE);	
	  focusSelect(yearField);
          return false;
	}

        var monthIndex = monthList.indexOf(monthValue)/3;
        var userDate = new Date(yearValue, monthIndex, dayValue);

	if (beforeToday == true)
        {
   	   if (userDate.getTime() > present.getTime())
               {
                 alert(INVALID_DATE_MESSAGE);
                 focusSelect(yearField);
                 return false;
               }
	}
      
       return true;
  }


//
// Validate the from and to dates
//

function dateDiff2(fday, fmonth, fyear, ffield, tday, tmonth, tyear, tfield)
{
        alert("FDAY "+fday+" FMONTH "+fmonth+" FYEAR "+fyear+" ffield "+ffield+" TDAY "+tday+" TMONTH "+tmonth+" TYEAR "+tyear+" TFIELD "+tfield);

	var mthList   = "JanFebMarAprMayJunJulAugSepOctNovDec";
        
        var fromday   = getFormField(fday).value;
	var frommonthField = getFormField(fmonth);
	var fmonth   = frommonthField[frommonthField.selectedIndex].text;

	var fromyear  = getFormField(fyear).value;
        var fmthIndex = mthList.indexOf(fmonth)/3;
        var fromDate  = new Date(fromyear, fmthIndex, fromday);

        var today     = getFormField(tday).value;
	var tomonthField  = getFormField(tmonth);
	var tmonth = tomonthField[tomonthField.selectedIndex].text;

	var toyear    = getFormField(tyear).value;
        var tmthIndex = mthList.indexOf(tmonth)/3;
        var toDate    = new Date(toyear, tmthIndex, today);

	if( fromDate.getTime() > toDate.getTime())
	{
	alert("The date " +ffield +" began is later than the date "+tfield +" ended.");
        focusSelect(tyear);
        return false;
      	}

        return true;
}

//
// Validate the from and to dates
//

function dateDiff(fromField, fromFieldName, toField, toFieldName)
{
	var mthList   = "JanFebMarAprMayJunJulAugSepOctNovDec";
        
        var fromday   = getFormField(fromField+".day").value;
	var frommonthField = getFormField(fromField+".month");
	var fmonth   = frommonthField[frommonthField.selectedIndex].text;

	var fromyear  = getFormField(fromField+".year").value;
        var fmthIndex = mthList.indexOf(fmonth)/3;
        var fromDate  = new Date(fromyear, fmthIndex, fromday);

        var today     = getFormField(toField+".day").value;
	var tomonthField  = getFormField(toField+".month");
	var tmonth = tomonthField[tomonthField.selectedIndex].text;

	var toyear    = getFormField(toField+".year").value;
        var tmthIndex = mthList.indexOf(tmonth)/3;
        var toDate    = new Date(toyear, tmthIndex, today);

	if( fromDate.getTime() > toDate.getTime())
	{
	alert("The date " +fromFieldName +" began is later than the date "+toFieldName +" ended.");
        focusSelect(toField+".year");
        return false;
      	}

        return true;
}


//
// Validate the fields in a tabular column, when all the rows in the fields
// need to be filled
//
        
function validateRow(numFields)
{
   var fieldsNotFilled = numFields;
      
   for (var index = 1; index <= numFields; index++)
     {
	//if (validateRow.arguments[index].type == "select-one" && validateRow.arguments[index].selectedIndex == 0)
        //{
	  //fieldsNotFilled--;
        //}

	if (validateRow.arguments[index].type == "text" && validateRow.arguments[index].value.length == 0)
        {
	  fieldsNotFilled--;
        }
     }       

     if (fieldsNotFilled == numFields)
	return ROW_FULLY_FILLED;
     else if (fieldsNotFilled == 0)
        return ROW_NOT_FILLED;
     else
       {
         alert(FILL_ALL_FIELDS_MESSAGE);
         return ROW_PARTLY_FILLED;
       }
}

//
// Make sure that all fields on the page are filled if Add More is clicked
// 

function addMoreCheck(form)
{
  for(var index =0; index < (form.elements.length - 1) ;index++)
  {
    if(form.elements[index].type == "text" && form.elements[index].value == "")
    {
      alert(FILL_ALL_BEFORE_ADDMORE_MESSAGE);
      return false;
    }
  }

  return true;
}

//
// Toggle the hidden field on a page for adding additional information - 
// by convention called "add"
//

function toggleAdd(falseBias)
{
  if (falseBias)
    {
      document.forms[0].add.value = "false";
      return;
     }

  if (document.forms[0].add.value == "true")
      document.forms[0].add.value = "false";
  else 
      document.forms[0].add.value = "true";
}


//
//Reset all Form Fields
//

function clearAll()
 {
  for(var i=0;i<document.regAccount.elements.length;i++)
   {
   	document.regAccount.elements[i].value="";
	}
  }



//
// MacroMedia DreamWeaver rollover functions
//

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//To check the Email Id is valid

//To check the Email Id is valid

function emailCheck(emailStr) 		
{
	var emailPat=/^(.+)@(.+)$/			
	/* Email Pattern*/ 
	
	var specialChars="\\(\\)<>@,;:`~!#$%^*\\\\\\\"\\.\\[\\]"
	/* The string represents the chars aren't allowed in a username or domainname. */
	
	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 +")*$")


	/*main()*/
	/* 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("The Email of the Referrer seems Invalid. Re-Enter")
	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 address 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)
	{
	// alert("The email Destination IP address is invalid!")
	return false
	}
	}
	return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null)
	{
	// alert("The email address 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, In), 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>4)
	{
	// the address must end in a two letter or three letter word.
	// alert("The email 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="The email address is missing a hostname!"
	// alert(errStr)
	return false
	}
	// If we've gotten this far, everything's valid!
	return true;
}

// 
// old functions
//

    function submitform(url)
     {
        document.forms[0].action = url ;
        document.forms[0].submit() ;
     }

    function cancelform(msg,url)
    {
        var yes ;

        yes = confirm(msg) ;

        if(yes)
        {
            document.forms[0].action = url ;
            document.forms[0].submit() ;
        }
    }


