// This function trms off space, \t \r \n character of the word.
function trim(oldstr) 
{
  newstr="";
  badchars=" \t\r\n";
  
  /* uncoment for hex values be very carefull
	 because if you strip it out length property of
	 the string will not count it.
  re = /\x0D\x0A/g;
  oldstr = oldstr.replace(re, "");*/

  for(i=0;i < oldstr.length; i++) {
    curchar = oldstr.charAt(i);
    if( badchars.indexOf(curchar) == -1 ) {
      newstr = oldstr.substring(i,oldstr.length);
      break;
    }     
  }
  for(i=newstr.length-1;i>0; i-- ) {
    curchar = newstr.charAt(i);
    if( badchars.indexOf(curchar) == -1 ) {
      newstr = newstr.substring(0,i+1);
      break;
    }     
  }
  return(newstr);
}


// This function checks if field contains letters or commas
function checkAlphaComma(formField, fieldLabel)
{
	var errorStr = "";
	var sString = trim(formField.value);
	
	if (sString.length < 1)
		return errorStr;

	for (var i=0; i < sString.length; i++)
	{
		var cTest = parseInt(sString.charAt(i));
		if ((!isNaN(cTest) || 
			 sString.charAt(i).toLowerCase() < "a" || 
			 sString.charAt(i).toLowerCase() > "z") && 
			(sString.charAt(i) != "," &&
			 sString.charAt(i) != "-" &&
			 sString.charAt(i) != "." &&
			 sString.charAt(i) != "'" &&
			 sString.charAt(i) != " "))
		{
			errorStr += " + " + fieldLabel + " can only contain letters, a comma, \n" + 
				"dash, hyphen, period, apostrophe or space.\n";
			return errorStr;
		}
	}

	return errorStr;
}

// This function checks if field contains letters or periods
function checkAlphaPeriod(formField, fieldLabel)
{
	var errorStr = "";
	var sString = trim(formField.value);
	
	if (sString.length < 1)
		return errorStr;

	for (var i=0; i < sString.length; i++)
	{
		var cTest = parseInt(sString.charAt(i));
		if ((!isNaN(cTest) || 
			 sString.charAt(i).toLowerCase() < "a" || 
			 sString.charAt(i).toLowerCase() > "z") && 
			(sString.charAt(i) != "-" &&
			 sString.charAt(i) != "." &&
			 sString.charAt(i) != "'" &&
			 sString.charAt(i) != " "))
		{
			errorStr += " + " + fieldLabel + " can only contain letters, \n" + 
				"a dash, hyphen, period, apostrophe or space.\n";
			return errorStr;
		}
	}

	return errorStr;
}

// This function checks if field contains letters or blanks
function checkAlphaBlank(formField, fieldLabel)
{
	var errorStr = "";
	var sString = trim(formField.value);
	
	if (sString.length < 1)
		return errorStr;

	for (var i=0; i < sString.length; i++)
	{
		var cTest = parseInt(sString.charAt(i));
		if ((!isNaN(cTest) || sString.charAt(i).toLowerCase() < 'a' 
			|| sString.charAt(i).toLowerCase() > 'z') && sString.charAt(i) != ' ')
		{
			errorStr += " + " + fieldLabel + " can only contain letters and blanks.\n";
			return errorStr;
		}
	}

	return errorStr;
}


// This function checks if field contains only letters
/*function checkAlpha(formField, fieldLabel)
{
	var errorStr = "";
	var sString = trim(formField.value);
	
	if (sString.length < 1)
		return errorStr;

	for (var i=0; i < sString.length; i++)
	{
		if (sString.charAt(i).toLowerCase() < 'a' 
			|| sString.charAt(i).toLowerCase() > 'z')
		{
			errorStr += " + " + fieldLabel + " must be all letters.\n";
			return errorStr;
		}
	}

	return errorStr;
}
*/

// This function checks if field contains alpha-numeric values
/*
function checkAlphaNum(formField, fieldLabel)
{
	var errorStr = "";
	var sString = trim(formField.value);

	if (sString.length < 1)
		return errorStr;

	for (var i=0; i < sString.length; i++)
	{
		if (!((sString.charAt(i).toLowerCase() >= 'a' && sString.charAt(i).toLowerCase() <= 'z') || 
			(sString.charAt(i) >= '0' && sString.charAt(i) <= '9')))
		{
			errorStr += " + " + fieldLabel + " must be alpha-numeric.\n";
			return errorStr;
		}
	}

	return errorStr;
}
*/
// This function checks if field is blank
function checkBlank(formField, fieldLabel) {
	// check for blank field
    var errorStr = "";
    formField.value = trim(formField.value);
    if (formField.value.length == 0)
        errorStr = " + " + fieldLabel + " cannot be blank.\n";

	if(errorStr.length > 0){
		formField.focus();
		formField.select();
	}
    return errorStr;
}

// This function checks if given date is valid date
function checkDate(DateFld, fieldLabel, noBlank) 
{
	var date = DateFld.value.replace(/\D/g,"");
	var month = date.substring(0, 2);
	var day = date.substring(2, 4);
	var year = date.substring(4, 8);

	if(date.length != 8 && DateFld.value.length > 0)
		return " + " + fieldLabel + " must be in MM/DD/YYYY format.\n";

	// validate Date field
    var errorStr = "";
    // noBlank set, and Date is blank
    if (month.length == 0 && day.length == 0 && year.length == 0 && noBlank)
        return " + " + fieldLabel + " cannot be blank\n";

    // Date is at least partially filled in
    if (month.length != 0 || day.length != 0 || year.length != 0) {
        errorStr += checkDateNumeric(month, fieldLabel + " month", 1, 12, 2, true);
        // if day is blank, set to 1
        if (trim(day).length == 0)
            day = "01";
        else
            errorStr += checkDateNumeric(day, fieldLabel + " day", 1, 31, 2, true);
        errorStr += checkDateNumeric(year, fieldLabel + " year", 1950, 3000, 4, true);
        if (errorStr.indexOf("characters long") > 0)
            return " + " + fieldLabel + " must be in MM/DD/YYYY format.\n";
        if (errorStr != "")
            return errorStr;
    
        // if format okay, check for bogus date
        if (errorStr == "") {
            var theDate = new Date(year, month - 1, day);
            // year 2000 goofiness
            if (theDate.getYear() > 1999)
                var year2compare = year;
            else
                var year2compare = year - 1900;
            if (theDate.getMonth() != month - 1 || theDate.getDate() != day || theDate.getYear() != year2compare)
                errorStr += " + " + month + "/" + day + "/" + year + " is not a valid date.\n";
        }
        return errorStr;
    }
    return errorStr;
}

function checkDecimal(formField, fieldLabel, min, max, noBlank) 
{
	// currency check
	var errorStr = "";
	var nNum = 0;
	var foundDec = 0;

	// no blanks
	if (formField.value.length == 0 && noBlank == true) {
		errorStr = " + " + fieldLabel + " cannot be blank.\n";
		return errorStr;
	}

	if (formField.value == ".")
	{
		errorStr = " + " + fieldLabel + " must be numeric.\n";
		return errorStr;
	}
		
	// numeric only + decimal
	for (var i = 0; i < formField.value.length; i++) {
		var ch = formField.value.substring(i, i + 1);
		if ((ch < "0" || ch > "9") && ch != ".") 
		{
			errorStr = " + " + fieldLabel + " must be numeric.\n";
			return errorStr;
		}else{
			if (foundDec == 1)
				nNum++;
		}
    
		if (ch == ".")
			foundDec++;
		
	}

	// too many decimals
	if (foundDec > 1) 
	{
		errorStr = " + " + fieldLabel + " format is invalid.\n";
		return errorStr;
	}

	// too many numbers to the right of the decimal
	if (nNum > 2) 
	{
		errorStr = " + " + fieldLabel + " format is invalid.\n";
		return errorStr;
	}

	// max/min
	var val = parseInt(formField.value, 10);
	if (min >= 0 && max >=0) {
		if ((val < min) || (val > max)) {
			errorStr = " + " + fieldLabel + " must be between " +  parseInt(min, 10) + " and " + parseInt(max, 10) + ".\n";
			return errorStr;
		}
	}
	return errorStr;
}

function checkDecimalNotZero(formField, fieldLabel)
{
	var errorStr = "";

	var nRate = parseFloat(formField.value);
	if (!isNaN(nRate))
	{
		if (nRate < 0.01)
			errorStr = " + " + fieldLabel + " must be greater than 0.\n";
	}	
	
	return errorStr;
}

function checkDateNumeric(formField, fieldLabel, min, max, len, noBlank) {
	// numeric field check
    var errorStr = "";
    // no blanks
    if (formField.length == 0 && noBlank == true) {
        errorStr = " + " + fieldLabel + " cannot be blank.\n";
        return errorStr;
    }
    // numeric only
    for (var i = 0; i < formField.length; i++) {
        var ch = formField.substring(i, i + 1);
        if (ch < "0" || ch > "9") {
           errorStr = " + " + fieldLabel + " must be numeric.\n";
           return errorStr;
        }
    }
    // max/min
    var val = parseInt(formField, 10);
    if (min >= 0 && max >=0) {
        if ((val < min) || (val > max)) {
            errorStr = " + " + fieldLabel + " must be between " + parseInt(min, 10) + " and " + parseInt(max, 10) + ".\n";
            return errorStr;
        }
    }
    // length
    if (len > 0 && formField.length != len && formField.length > 0) {
        errorStr = " + " + fieldLabel + " must be " + len + " characters long.\n";
    }

	return errorStr;
}
function checkNumeric(formField, fieldLabel, min, max, len, noBlank) {
	// numeric field check
    var errorStr = "";
    // no blanks
    if (formField.value.length == 0 && noBlank == true) {
        errorStr = " + " + fieldLabel + " cannot be blank.\n";
        return errorStr;
    }
    // numeric only
    for (var i = 0; i < formField.value.length; i++) {
        var ch = formField.value.substring(i, i + 1);
        if (ch < "0" || ch > "9") {
           errorStr = " + " + fieldLabel + " must be numeric.\n";
           return errorStr;
        }
    }
    // max/min
    var val = parseInt(formField, 10);
    if (min >= 0 && max >=0) {
        if ((val < min) || (val > max)) {
            errorStr = " + " + fieldLabel + " must be between " + parseInt(min, 10) + " and " + parseInt(max, 10) + ".\n";
            return errorStr;
        }
    }
    // length
    if (len > 0 && formField.value.length != len && formField.value.length > 0) {
        errorStr = " + " + fieldLabel + " must be " + len + " digits long.\n";
    }

	return errorStr;
}

function checkNameFormat(formField, fieldLabel, blnRequired) {
	// Aerotrak name format
    var errorStr = "";
    var fld_len = formField.value.length;
    var c;
    var c3;
	var sLast = "";
	var nDash = 0;
	var nComma = 0;
	var nSpace = 0;
	var nApost = 0;
	var nPeriod = 0;
	var bLastName = true;
	var nDashFirst = 0;

    var errMsg = " + " + fieldLabel + " must be in BD name format. \n" +
			"Ex: Francis,Robert T.\n" +
			"Gourdou-Chase Jr.,Rodney T.\n" +
			"St. John,James\n" +
			"O'Reilly,Jean-Pierre\n";

    if (formField.value == "")
        return errorStr;

	// Name must contain a comma.  Name cannot begin with a comma, dash, period, apostrophe, or space.
    if(	formField.value.indexOf(",") < 0 || 
		formField.value.charAt(0) == "," ||
		formField.value.charAt(0) == "-" ||
		formField.value.charAt(0) == "." || 
		formField.value.charAt(0) == "'" || 
		formField.value.charAt(0) == " " ||
		fld_len == 1) {
        errorStr = errMsg;
        return errorStr;
    }

    for (var i = 0; i < fld_len; i++) {
		

        c = formField.value.charAt(i) + formField.value.charAt(i+1);
		
		// Check for bad combinations:
		if (c == ", " || c == " ," || c == ",-" || c == "-,"  ||
			c == ",." || c == " ." || c == "-." || c == ".-" || c == ".." ||
			c == " -" || c == "- " || c == "  " || c == "' " || c == " '" || c == "--") 
		{
            errorStr = errMsg;
            return errorStr;
        }
		
		c3 = c.toLowerCase() + formField.value.charAt(i+2);
		if (c3 == "jr," || c3 == "sr," || c3 == "..." || c3 == "   ")
		{
            errorStr = errMsg;
            return errorStr;
        }
			
		// One comma allowed
		if (formField.value.charAt(i) == ",")
		{
			bLastName = false;
			nComma++;
			if (nComma > 1)
			{
				errorStr = errMsg;
				return errorStr;
			}
		}

		// One hyphen allowed
		if (formField.value.charAt(i) == "-")
		{
			nDash++;
			if (bLastName == false)
				nDashFirst++;
			
			// One dash in the last name.
			if ((bLastName == true) && (nDash > 1))
			{
				errorStr = errMsg;
				return errorStr;
			}
				
			// One dash in the first name.
			if ((bLastName == false) && (nDashFirst > 1))
			{
				errorStr = errMsg;
				return errorStr;
			}
			

			if (nDash > 2)
			{
				errorStr = errMsg;
				return errorStr;
			}

		}

		// One apostrophe allowed
		if (formField.value.charAt(i) == "'")
		{
			nApost++;
			// No apostrophes in the first name.
			if ((bLastName == false) && (nApost > 0))
			{
				errorStr = errMsg;
				return errorStr;
			}

			if (nApost > 1)
			{
				errorStr = errMsg;
				return errorStr;
			}

		}

		// Three spaces allowed
		if (formField.value.charAt(i) == " ")
		{
			nSpace++;
			if (nSpace > 3)
			{
				errorStr = errMsg;
				return errorStr;
			}

		}

		// Three periods allowed
		if (formField.value.charAt(i) == ".")
		{
			nPeriod++;
			if (bLastName &&
				(formField.value.charAt(i+1) != " " &&
				 formField.value.charAt(i-2).toLowerCase() != "j" &&
				 formField.value.charAt(i-2).toLowerCase() != "s"))
			{
				errorStr = errMsg;
				return errorStr;
			}	

		
			if (nPeriod > 3)
			{
				errorStr = errMsg;
				return errorStr;
			}

		}
				
    }

	// If last char is period, should also be a space (middle intitial)
    if (formField.value.charAt(fld_len-1) == "." && 
		formField.value.charAt(fld_len-3) != " ")
	{	
		errorStr = errMsg;
		return errorStr;
	}

	sLast = formField.value.charAt(fld_len-2).toLowerCase() + formField.value.charAt(fld_len-1).toLowerCase(); 
	// If last 2 chars are jr or sr, error.
    if (sLast == "jr" || 
		sLast == "sr")
	{
		errorStr = errMsg;
		return errorStr;
	}

	// Check last position:
    if (formField.value.charAt(fld_len - 1) == "," || 
		formField.value.charAt(fld_len - 1) == "'" ||
		formField.value.charAt(fld_len - 1) == "-") // no char after comma; invalid last char
        errorStr = errMsg;

    return errorStr;
}

function DateCompare(Date1, Date2, fieldLabel1, fieldLabel2) {
	// compares 2 valid dates: d2 must be greater than d1
    var errorStr = "";
	date1 = Date1.value;
	date2 = Date2.value;

	var y1 = date1.substring(6, 10);
	var y2 = date2.substring(6, 10);
	var m1 = date1.substring(0, 3);
	var m2 = date2.substring(0, 3);
	var d1 = date1.substring(3, 6);
	var d2 = date2.substring(3, 6);

    if (parseInt(y1,10) > parseInt(y2,10) || (parseInt(y2,10) == parseInt(y1,10) && parseInt(m1,10) > parseInt(m2,10)) || (parseInt(y2,10) == parseInt(y1,10) && parseInt(m2,10) == parseInt(m1,10) && parseInt(d1,10) > parseInt(d2,10)))
        errorStr = " + " + fieldLabel1 + " cannot be greater than " + fieldLabel2 + ".\n";
    return errorStr;
}

function checkLength(theField, fieldLabel, max, noBlank) {
	// text field length
    var errorStr = "";
    // no blanks
    var tmpStr = trim(replaceHtmlTag(theField.value));

    if (tmpStr.length == 0 && noBlank == true) {
        errorStr = " + " + fieldLabel + " cannot be blank.\n";
        if(errorStr.length > 0){
			theField.focus();
			theField.select();
		}

		return errorStr;
    }
    // max length
    if (max > 0 && tmpStr.length > max) {
        errorStr = " + " + fieldLabel + " cannot be greater than " + max + " characters long.\n";
    }

    if(errorStr.length > 0){
		theField.focus();
		theField.select();
	}
	return errorStr;
}

function checkZip(oZip, nCountry)
{
        var errorStr = "";
        var sZip = oZip.value;
        var oZipNew = new Object();

        if (isNaN(parseInt(nCountry))) // because no state selected
        {
                return errorStr;
        }

        if (nCountry == 1) //USA
        {
                if (sZip.length == 5)
                {
                		oZipNew.value = sZip;
                	    errorStr += checkNumeric(oZipNew, "ZIP", 0 , 99999, 5, 1);
                 }
                else if (sZip.length == 10 && sZip.charAt(5) == '-')
                {
                        oZipNew.value = sZip.substring(0,5);
                        oZipNew.value += sZip.substring(6,10);
                        errorStr += checkNumeric(oZipNew, "ZIP", 0 , 999999999 , 9, 1);
                }
                else
                        errorStr += " + USA Zip code must be in \"99999\" OR \"99999-9999\" format.\n";

                return errorStr;
        }

        if (nCountry == 2) //Canada
        {
                if (sZip.length == 7 && sZip.charAt(3) == ' ')
                {
                        oZipNew.value = sZip.substring(0,3);
                        oZipNew.value += sZip.substring(4,7);
                        errorStr += checkAlphaNum(oZipNew, "Zip");
                }
                else
                        errorStr += " + Canada Zip code must be in \"XXX XXX\" format.\n";

                return errorStr;
        }

        //Shouldn't get here because we should have a countryid match
        errorStr += " + Select a state in order to validate the zip code.\n";
		
		if(errorStr.length > 0){
			oZip.focus();
			oZip.select();
		}
        return errorStr;
}

function stripZip(sZip)
{
	if (sZip == null)
		return "";

	var sNewZip = "";
	for (var i = 0; i < sZip.length; i++)
	{
		sNewZip += ((sZip[i] == '-' || sZip[i] == ' ') ? "" : sZip[i]);
	}
	return sNewZip;
}

function checkPhone(theField, fieldLabel, Required) {

	
	var Phone =  theField.value.replace(/\D/g,"");

	// validate phone number field
    var errorStr = "";
	
	if(theField.value.length != 0 && Phone.length < 10)
		errorStr += " + " + fieldLabel + " field must be a 10 digit U.S. phone number (like 415 555 1212).\n";

	// phone can be blank but is partly filled in, or cannot be blank
	else if (Phone.length == 0 && Required){
		errorStr += " + " + fieldLabel + " field cannot be blank.\n";
	}  
	// phone is required and characters less than 10
	else if(Phone.length < 10 && Required){
		errorStr += " + " + fieldLabel + " field must be a 10 digit U.S. phone number (like 415 555 1212).\n";
	}
	else if(Phone.length != 0 && Phone.length < 10 && !Required){
		errorStr += " + " + fieldLabel + " field must be a 10 digit U.S. phone number (like 415 555 1212).\n";
	}
	if(errorStr.length > 0){
		theField.focus();
		theField.select();
	}
    return errorStr;
}

function formatSSN (theField)
{   

    var ssn = theField.value.replace(/\D/g,"");
	if (ssn.length == 9)
		theField.value= ssn.substring(0,3) + "-" + ssn.substring(3,5) + "-" + ssn.substring(5,9);
}

function checkSSN(theField, fieldLabel, Required) {
	
	var errorStr = "";
	var ssn = theField.value.replace(/\D/g,"");
	
	if(ssn.length == 0 && Required)
		errorStr += " + " +fieldLabel + " field cannot be blank.\n";

	else if(ssn.length != 9 && ssn.length > 0)
		errorStr += " + " +fieldLabel + " field must be a 9 digit U.S. social security number (like 123 45 6789).\n";
	else if (theField.value.length != 0 && ssn.length == 0)
		errorStr += "+ " + fieldLabel + " field must be numeric.\n";
	if(errorStr.length > 0){
		theField.focus();
		theField.select();
	}
    return errorStr;
}

function formatDate(theField)
{
	var strDate = theField.value.replace(/\D/g,"");
	if(strDate.length != 8)
		return;
	theField.value = strDate.substring(0,2) + "/" + strDate.substring(2, 4) + "/" + strDate.substring(4, 8);
}

function formatPhone(theField)
{
	var Phone = theField.value.replace(/\D/g,"");
	if(Phone.length < 10)
		return;
	theField.value = "" + "(" + Phone.substring(0,3) + ")" + Phone.substring(3, 6) + "-" + Phone.substring(6, 10) + (Phone.length > 10 ? " Ext." + Phone.substring(10, Phone.length) : "");
}

function stripPhone(theField)
{
	return theField.value.replace(/\D/g,"");
}



function checkSelectBlank(theField, theFieldLabel)
{
	var errorStr = "";
	
	if(theField.options[theField.options.selectedIndex].value == "-1")
		errorStr += " + " + theFieldLabel + " cannot be blank.\n";
    
	if (errorStr.length > 0){
	  theField.focus();
	  theField.select();
    }

	return errorStr;
}
function checkOtherPhoneTypeUnique(theField1, theFieldLabel1, theField2, theFieldLabel2)
{
    var errorStr = "";
    var field1 = theField1.options[theField1.selectedIndex].value;
	var field2 = theField2.options[theField2.selectedIndex].value;

	if ((field1 == field2) && !(field1 == -1 && field2 == -1)) {
	  errorStr += " + " + theFieldLabel1 + " and " + theFieldLabel2 + " cannot be the same. \n";
	}

    if (errorStr.length > 0){
	  theField2.focus();
	  theField2.select();
    }

    return errorStr;
}
function checkOtherPhoneTypeBlank (theSelectField, theSelectFieldLabel, theField, theFieldLabel)
{
    var errorStr = "";
	var selectField = theSelectField.options[theSelectField.selectedIndex].value;
	var field1 = theField.value;

    if ((selectField != -1) && (field1== "")) {
	  errorStr += " + " + theFieldLabel + " cannot be blank when " + theSelectFieldLabel + " is selected. \n"; 
	}

	if ((selectField == -1) && (field1.length > 0)) {
	  errorStr += " + " + theSelectFieldLabel + " cannot be blank when " + theFieldLabel + " contains a phone number. \n";
	}

	if (errorStr.length > 0){
	  theSelectField.focus();
	  theSelectField.select();
    }
    
    return errorStr;
}

function formatName(first, last, middle, suffix)
{
   var sName = "";
   first = (first == "null" ? "" : first);
   last = (last == "null" ? "" : last);
   middle = (middle == "null" ? "" : middle);
   suffix = (suffix == "null" ? "" : suffix);

   sName += (last.length > 0 ? last : "");
   sName += (suffix.length > 0 ? " " + suffix + "." : "");
   sName += (first.length > 0 ? "," + first : "");
   sName += (middle.length > 0 ? " " + middle.substring(0,1) + "." : "");
   return sName;
}

function populateDropDown (keyField, dropDownField, anArray, defaultValue)
{
	var intSelectedIndex = 0;
	var keyValue = keyField.options[keyField.selectedIndex].value;	
	for (i = dropDownField.length - 1; i >= 0; i--)
		dropDownField.options[i] = null;
		
        if (keyValue.search("-1") != -1)
	{    	
	    for (var i=0; i < anArray[-1].length; i++)
	    {
		opt = new Option(anArray[-1][i][1], anArray[-1][i][0]);
		dropDownField.options[i] = opt;
		if ((defaultValue != null) && (defaultValue.length > 0))
			if (defaultValue == (anArray[-1][i][0]))
				intSelectedIndex = i;
		else
			if ((anArray[-1][i][0] == "-1") ||
				(anArray[-1][i][0].length == 0))				
					intSelectedIndex = i;
	    }
	}
	else
	{    	
	    for (var i=0; i < anArray[keyValue].length; i++)
	    {
		opt = new Option(anArray[keyValue][i][1], anArray[keyValue][i][0]);
		dropDownField.options[i] = opt;
		if ((defaultValue != null) && (defaultValue.length > 0))
			if (defaultValue == (anArray[keyValue][i][0]))
				intSelectedIndex = i;
		else
			if ((anArray[keyValue][i][0] == "-1") ||
				(anArray[keyValue][i][0].length == 0))				
					intSelectedIndex = i;
	    }
	}
	dropDownField.options[intSelectedIndex].selected = true;					
}
function replaceHtmlTag (textArea)
{	
	var ret = "";
	ret = textArea.replace(/>/g,"&gt;");
	ret = ret.replace(/</g,"&lt;");
	ret = ret.replace(/\'/g,"\'\'");
	ret = ret.replace(/\"/g,"&quot;");
	return ret;
}

function formatSearchString(formFieldVal, flag)
{
	var foundQuote = false;
	var newChar = "";
	var foundChar = false;

	for(j=0; j < formFieldVal.length; j++)
	{
		if(formFieldVal.charAt(j) == '\"')
		{
			if (foundQuote)
 			    foundQuote = false;	
			else		
			    foundQuote = true;
		}
		if (!foundQuote)
		{
			if(flag != null){
				if (formFieldVal.charAt(j)== '*'){
					newChar += '%';
					continue;
				}
			}
			else 
			{
				if (formFieldVal.charAt(j)== '%'){
					newChar += '*';
					continue;
				}
			}
				
			newChar += formFieldVal.charAt(j);
		}
		else
			newChar += formFieldVal.charAt(j);
	}
	return newChar;
}

function errQueryString(formFieldVal, fieldLabel) 
{
    var errorStr = "";
    var ch = "";
    var quotes = 0;
    var badspace = 0;
    var goodword = 0;

    // must contain equal number of quotes
    for (i = 0; i < formFieldVal.length; i++) 
	{
        ch = formFieldVal.charAt(i);
		if (ch == "\"")
           quotes++;
    }

	if (quotes > 0 && quotes % 2 != 0)
        errorStr += "+ " + fieldLabel + " contains an uneven number of quotes.\n";

	//regexp strps out reserved chars.
    var re  = /[\'\[\~\`\!\@\#\$\%\^\&\_\+\=\-\]\<\>\;\|\}\{\,\.]/; 	var foundQuote = false;
	var newChar = "";
	var foundChar = false;

	for(j=0; j < formFieldVal.length; j++)
	{
		if(formFieldVal.charAt(j) == '\"')
		{
			if (foundQuote)
 			    foundQuote = false;	
			else		
			    foundQuote = true;
		}
		if (!foundQuote)
		{
			if(re.test(formFieldVal.charAt(j)))
				return errorStr += "+ " + fieldLabel + " contains one of these reserved characters.\n [ ' ~ % ` ! @ # $ % ^ & _ + = - ] < > ; | } { , . ]\nYou can use reserved characters inside double quotes.";
		}
		if(!foundChar)
			newChar += formFieldVal.charAt(j);
	}
	// check string for logicals and quotes
    if (errorStr == "") 
	{
        quotes = 0;
        for (i = 0; i < formFieldVal.length; i++) 
		{
            ch = formFieldVal.charAt(i);
            if (ch == '\"') 
			{
                quotes ++;
                if (quotes % 2 != 0) 
				{  
                    quotes ++;
                    if ((i = formFieldVal.toUpperCase().indexOf(ch, i + 1)) == -1)
                        break;
                }
            }

			// check for logicals
			else if (ch == " ") 
			{
				// check what's after space
				if (goodword == 0) 
				{  
					if (formFieldVal.substring(i + 1, i + 5).toUpperCase() == "AND " && 
						formFieldVal.substring(i + 1, i + 9).toUpperCase() != "AND NOT " &&
						formFieldVal.substring(i + 1, i + 8).toUpperCase() != "AND OR " &&
						formFieldVal.substring(i + 1, i + 7).toUpperCase() != "AND *" &&
						formFieldVal.substring(i + 1, i + 7).toUpperCase() != "AND * ")
					{
						i += 4;
						goodword ++;
					}
					if(formFieldVal.substring(i + 1, i + 5).toUpperCase() == "NOT " &&
					   formFieldVal.substring(i + 1, i + 9).toUpperCase() != "NOT AND " &&
					   formFieldVal.substring(i + 1, i + 8).toUpperCase() != "NOT OR " &&
					   formFieldVal.substring(i + 1, i + 7).toUpperCase() != "NOT *" && 
					   formFieldVal.substring(i + 1, i + 7).toUpperCase() != "NOT *")
					{
						i += 4; 
						goodword ++;
					}
					if (formFieldVal.substring(i + 1, i + 4).toUpperCase() == "OR " &&
						formFieldVal.substring(i + 1, i + 8).toUpperCase() != "OR AND " &&
						formFieldVal.substring(i + 1, i + 8).toUpperCase() != "OR NOT " &&
						formFieldVal.substring(i + 1, i + 6).toUpperCase() != "OR *" &&
						formFieldVal.substring(i + 1, i + 6).toUpperCase() != "OR * ")
					{
						i += 3;
						goodword ++;
					}
				}
				if (goodword == 0)  //  still not a good one, must be bad
				{
					badspace = 1;
					break;
				}

				if (goodword == 1)  // space after good word
					goodword = 0;
			}
        }
		if (badspace == 1)
			errorStr += " + There is a problem with the format of your search criteria. See \' Search Tips \' for more examples.";
     }
	 return errorStr;
}

var lastCtrl = "";

function checkLastCtrl(ctrl)
{
  if (lastCtrl == "")
    lastCtrl = ctrl;
}

// This function checks if the ctrl contains alpha characters.  
// input:
//    ctrl => this is the control that is being evaluated
//    strCtrlLabel => this is the label for the control
//    blnRequired => optional boolean parameter that is used to determine
//      if this is a required field.  By default, if this parameter is
//      not passed in, it is set to false.
// output:
//    string => this is the resulting error string for this control.  If 
//      there are no errors, a null string is returned.
// note:
//    if this control contained invalid data, the control is passed to the
//    checkLastCtrl function to see if it is the first control to have bad
//    data.  This can be used to set focus to that control in the calling
//    function.
function checkAlpha(ctrl, strCtrlLabel, blnRequired)
{
  var strCtrl = trim(ctrl.value);

  if (checkAlpha.arguments.length == 2)
    blnRequired = false;
  
  // if required, make sure its not null
  if (blnRequired && strCtrl == "")
  {
    checkLastCtrl(ctrl);
    return " + " + strCtrlLabel + " cannot be blank.\n";
  }
  else if (strCtrl == "")
    return "";

  // otherwise, make sure that the string contains alpha characters
  for (var i=0; i < strCtrl.length; i++)
  {
    if (strCtrl.charAt(i).toLowerCase() < 'a' || strCtrl.charAt(i).toLowerCase() > 'z')
 	{
      checkLastCtrl(ctrl);
  	  return " + " + strCtrlLabel + " must be all letters.\n";
	}
  }

  return "";
}

// This function checks if field contains alpha-numeric values
function checkAlphaNum(ctrl, strCtrlLabel, blnRequired)
{
  var strCtrl = trim(ctrl.value);

  if (checkAlphaNum.arguments.length == 2)
	blnRequired = false;

  if (blnRequired && strCtrl == "")
  {
	checkLastCtrl(ctrl);
	return " + " + strCtrlLabel + " cannot be blank.\n";
  }
  else if (strCtrl == "")
	return "";

  // otherwise, make sure that the string contains alphanum characters
  for (var i=0; i < strCtrl.length; i++)
  {
	if (!((strCtrl.charAt(i).toLowerCase() >= 'a' && strCtrl.charAt(i).toLowerCase() <= 'z') || 
		(strCtrl.charAt(i) >= '0' && strCtrl.charAt(i) <= '9')))
	{
	  checkLastCtrl(ctrl);
	  return " + " + strCtrlLabel + " must be alpha-numeric.\n";
    }
  }

  return "";
}


function checkName(ctrl, strCtrlLabel, blnRequired)
{
  var strCtrl = trim(ctrl.value);

  if (checkName.arguments.length == 2)
    blnRequired = false;
  
  // if required, make sure its not null
  if (blnRequired && strCtrl == "")
  {
    checkLastCtrl(ctrl);
    return " + " + strCtrlLabel + " cannot be blank.\n";
  }
  else if (strCtrl == "")
    return "";

  // otherwise, make sure that the string contains alpha characters
  for (var i=0; i < strCtrl.length; i++)
  {
    if ((strCtrl.charAt(i).toLowerCase() < 'a' || 
		 	strCtrl.charAt(i).toLowerCase() > 'z') &&
		strCtrl.charAt(i) != "/" &&
		strCtrl.charAt(i) != "-" &&
		strCtrl.charAt(i) != "." &&
		strCtrl.charAt(i) != "'")
	{
      checkLastCtrl(ctrl);
  		return " + " + strCtrlLabel + " must contain letters, slashes, dashes, periods, or apostrophes.\n";
	}
  }

  return "";
}

function checkNotBlank(ctrl, strCtrlLabel)
{
  var strCtrl = trim(ctrl.value);

  if (strCtrl == "")
  {
    checkLastCtrl(ctrl);
    return " + " + strCtrlLabel + " cannot be blank.\n";
  }

  return "";
}

function checkAlphaWords(ctrl, strCtrlLabel, blnRequired)
{
  var strCtrl = trim(ctrl.value);

  if (checkAlphaWords.arguments.length == 2)
    blnRequired = false;
  
  // if required, make sure its not null
  if (blnRequired && strCtrl == "")
  {
    checkLastCtrl(ctrl);
    return " + " + strCtrlLabel + " cannot be blank.\n";
  }
  else if (strCtrl == "")
    return "";

  // otherwise, make sure that the string contains alpha characters
  for (var i=0; i < strCtrl.length; i++)
  {
    if ((strCtrl.charAt(i).toLowerCase() < 'a' || 
		 	strCtrl.charAt(i).toLowerCase() > 'z') &&
		strCtrl.charAt(i) != "-" &&
		strCtrl.charAt(i) != "." &&
		strCtrl.charAt(i) != "'" &&
		strCtrl.charAt(i) != " ")
	{
      checkLastCtrl(ctrl);
  		return " + " + strCtrlLabel + " cannot have '" + strCtrl.charAt(i) + "' characters in it.\n";
	}
  }

  return "";
}

function checkSelected(ctrl, field, blnZeroValid)
{
  if (checkSelected.arguments.length == 2)
    blnRequired = false;
    
  if (blnZeroValid && ctrl.selectedIndex >= 0)
    return "";

  else if (ctrl.selectedIndex > 0)
    return "";

  checkLastCtrl(ctrl);

  return " + " + field + " must have a value selected from the list.\n";
}

function checkEmail(theField, theFieldLabel, Required)
{ 	
	var errorStr = "";
	var email = theField.value;
	
    if (email.length == 0 && Required)
		errorStr +=  " + " + theFieldLabel + " cannot be blank.\n";
		
	else if (email.length > 0)
	{
		var atSymbol = 0;
		var period = 0;
		var space = 0;
		var fieldError = " + " + theFieldLabel + " is not a valid E-mail address. ";
		
		for (i=0; i < email.length; i++)
		{
			if (email.charAt(i) == "@") 
				atSymbol++;
			else if (email.charAt(i) == ".")
				period++;
			else if (email.charAt(i) == " ")
			    space++;
		}
	
		if (atSymbol > 1)
			errorStr += fieldError  + "Extra '@' sign is detected.\n";		
	    else if (atSymbol == 0)
			errorStr += fieldError  + "Missing '@' sign.\n";
		
		if (period == 0)
			errorStr += fieldError  + "Missing 'dot'.\n";
	
		if (space > 0)
			errorStr += fieldError  + "Can not contain a 'space'.\n";
	}
	
	if (errorStr != "")
		checkLastCtrl(theField);
		
	return errorStr;

}
