/////////////////////////////////////////////
// This file contains generic
// javascript functions for
// form processesing and validation
//
// Author: JVS
// Date  : 09/20/01
//
/////////////////////////////////////////////

///////////////////////////////////////////////
//Reset the Form
///////////////////////////////////////////////
function resetForm(myForm)
{
  myForm.reset();
}//end resetForm

///////////////////////////////////////////////
// Returns the value selected in a select object
///////////////////////////////////////////////
function getSelectValue(selectObject)
{
    //BCOMPAT
    //ie runtime errors if you access a options array slot
    //smaller then the array, so if nothing is selected
    //just return false now, netscape returns false in that case
    if(selectObject.selectedIndex < 0){
        return false;
    }//end if
    return selectObject.options[selectObject.selectedIndex].value;
}// end getSelectValue

///////////////////////////////////////////////
// Returns delimited string of values in multipe
// selected in a select object
///////////////////////////////////////////////
function getMultipleSelectValue(selectObject,delimiter)
{
    var results = "";
    for (var j=selectObject.length -1;j>=0;j--){

        if (selectObject.options[j].selected == true)
        {
            results += selectObject.options[j].value + delimiter;
        }//end if
    }//end for select obj
    if (results.length > 0)
    {
        return results.substring(0,results.length-1);
    }
    else
    {
        return false;
    }
}// end getMultipleSelectValue


///////////////////////////////////////////////
// Sets the value selected in a select object
///////////////////////////////////////////////
function setSelectValue(selectObject,value)
{
    var j;
    for(j=0;j<selectObject.length;j++)
    {
        if (selectObject.options[j].value == value)
        {
            //selectObject.options[j].selected = true;
            selectObject.selectedIndex = j;
            return true;
        }//end if
    }// end for
    return false;
}// end setSelectValue

///////////////////////////////////////////////
// Set the value seleted in a radio object
///////////////////////////////////////////////
function setRadioValue(radioObject,value)
{
    for ( var i =0; i < radioObject.length; i++)
    {
        if (radioObject[i].value == value)
        {
            radioObject[i].checked=1;
            break;
        }//end if
    }//end for

return true;
}//end setRadioValue

///////////////////////////////////////////////
// Returns the value seleted in a radio object
///////////////////////////////////////////////
function getRadioValue(radioObject)
{
    var value = null;

    for ( var i =0; i < radioObject.length; i++)
    {
        if (radioObject[i].checked)
        {
            value = radioObject[i].value;
            break;
        }//end if
    }//end for

return value;
}//end getRadioValue


///////////////////////////////////////////////
// Returns index of selected radio
///////////////////////////////////////////////
function getRadioIndex(radioObject)
{
    var value = null;

    for ( var i =0; i < radioObject.length; i++)
    {
        if (radioObject[i].checked)
        {
            break;
        }//end if
    }//end for

return i;
}//end for getRadioIndex

///////////////////////////////////////
// Check if all values in the argument
// are numeric.
//////////////////////////////////////
function IsAllDigits(number) {

        if(number.length == 0) {
                return false;
        }
        for (var i=0; i<number.length; i++) {
                var ch = number.charAt(i);
                if( ch < "0" || ch > "9") {
                        if( ch != "." && ch != "-")
                                return false;
                }//end if
        } //end for
        return true;
}//end IsAllDigits

///////////////////////////////////////
// clears all non number chars
// in the string
//////////////////////////////////////
function makeAllDigits(string) {
    var notDigits = /\D/gi;//not any number of digits
    var newString = string.replace(notDigits,"")
    return newString;
}//end IsAllDigits

///////////////////////////////////////
// setDaysInMonth
// expects month day and year select objects
// the month and year selects should call
// this on change
// it controls the number of days in the day
// select so that invalid dates cannot be selected
//
//pass in true to blankFlag if the first option in
//the selects is blank, or says (please select) or something
//////////////////////////////////////
function setDaysInMonth(month,day,year,blankFlag)
{
    var lastDayOfMonth = daysInMonth(getSelectValue(month), getSelectValue(day), getSelectValue(year));
    var j;

    for (j=1;j<=31;j++)
    {
        if (j > lastDayOfMonth)
        {
            if (! blankFlag)
            {
                day.options [j-1].text="--";
                day.options [j-1].value="";
            }
            else
            {
                day.options [j].text="--";
                day.options [j].value="";
            }
        }
        else
        {
            if (! blankFlag)
            {
                day.options [j-1].text=j;
                day.options [j-1].value=j;
            }
            else
            {
                day.options [j].text=j;
                day.options [j].value=j;
            }
        }
    }//end for
}//end setDaysInMonth


////////////////////////////////////
//returns number of days in month
///////////////////////////////////
function daysInMonth(month, day, year)
//returns number of days on month
{

    month = Number(month);
    year = Number(year);
    day = Number(day);

    if (month==2)
    {
        //February
        if (year == Math.round(year / 4) * 4)
        //leap year
        {
            return 29;
        }
        else
        {
            //non-leap year
            return 28;
        }//end if
    }
    else if (month==4)
    {
        //April
        return 30;
    }
    else if (month==6)
    {
        //June
        return 30;
    }
    else if (month==9)
    {
        //September
        return 30;
    }
    else if (month==11)
    {
        //November
        return 30;
    }
    else
    {
        return 31;
    }//end if

}// end daysInMonth

////////////////////////////////////
//these two are realted to the date active flag issue...
///////////////////////////////////
//sets dateActive to true onChange date element
function activateDate(form)
{
    form.dateActive.value = "true";
}//end activateDate

//sets dateActive to false on form reset
function resetDate(form)
{
    form.dateActive.value = "false";
}//end resetDate

////////////////////////////////////
//function allHaveValues
//accepts any number of form objects and
//returns true if they ALL have values
//accepts text, checkbox, select, select multiple,
//textarea, password and hidden objs
///////////////////////////////////
function allHaveValues(){
    var j;

    for(j=0;j<arguments.length;j++)
    {

        //if element has no value, return false
        //first the one we tell by value length
        if ((arguments[j].type == "text") ||
            (arguments[j].type == "textarea") ||
            (arguments[j].type == "password") ||
            (arguments[j].type == "hidden"))
        {
            if (trim(arguments[j].value).length < 1)
            {
                return false;
            }
        }
        //next checkbox
        if (arguments[j].type == "checkbox")
        {
            if (arguments[j].checked == false)
            {
                return false;
            }
        }
        //and then radio
        if ((arguments[j][0]) && (arguments[j][0].type == "radio"))
        {
            if (getRadioValue(arguments[j]) == null)
            {
                return false;
            }
        }
        //and select
        if ((arguments[j].type == "select-one") ||
            (arguments[j].type == "select-multiple"))
        {
            if (! getSelectValue(arguments[j]))
            {
                return false;
            }
        }

        //else keep going
    }
    return true;
}//end allHaveValues

////////////////////////////////////
//function anyHaveValues
//accepts any number of form objects and
//returns true any have values
//accepts text, checkbox, select, select multiple,
//textarea, password and hidden objs
///////////////////////////////////
function anyHaveValues(){
    var j;

    for(j=0;j<arguments.length;j++)
    {

        //if element has no value, return false
        //first the one we tell by value length
        if ((arguments[j].type == "text") ||
            (arguments[j].type == "textarea") ||
            (arguments[j].type == "password") ||
            (arguments[j].type == "hidden"))
        {
            if (trim(arguments[j].value).length >= 1)
            {
                return true;
            }
        }
        //next checkbox
        if (arguments[j].type == "checkbox")
        {
            if (arguments[j].checked == true)
            {
                return true;
            }
        }
        //and then radio
        if ((arguments[j][0]) && (arguments[j][0].type == "radio"))
        {
            if (getRadioValue(arguments[j]) != null)
            {
                return true;
            }
        }

        //and select
        if ((arguments[j].type == "select-one") ||
            (arguments[j].type == "select-multiple"))
        {
            if ((getSelectValue(arguments[j]).length > 0) && (getSelectValue(arguments[j]) != "false"))
            {
                return true;
            }
        }

        //else keep going
    }
    return false;
}//end anyHaveValues


////////////////////////////////////
//function clearValues
//accepts any number of
//form objects and emptys them out
//accepts text, checkbox, select, select multiple,
//textarea, password and hidden objs
///////////////////////////////////
function clearValues(){
    var j;

    for(j=0;j<arguments.length;j++)
    {

        //if element has no value, return false
        //first the one we tell by value length
        if ((arguments[j].type == "text") ||
            (arguments[j].type == "textarea") ||
            (arguments[j].type == "password") ||
            (arguments[j].type == "hidden"))
        {
            arguments[j].value="";
        }
        //next checkbox
        if (arguments[j].type == "checkbox")
        {
            arguments[j].checked = false;
        }

        //and selects
        if (arguments[j].type == "select-one")
        {
            setSelectValue(arguments[j],"");
        }
        //and selects
        if (arguments[j].type == "select-multiple")
        {
            arguments[j].selectedIndex = -1;
        }
        //else keep going
    }
}//end clear values

////////////////////////////////////
//function isDefaultValue
//accepts a form element
//returns true if the value is not changed,
//or if it is a hidden field
//false if it is changed
//accepts text, checkbox, select, select multiple,
//textarea, password and hidden objs
///////////////////////////////////
function isDefaultValue(element){

	if (element.type == "hidden")
	{
		return true;
	}

	//text types
	else if ((element.type == "text") ||
		(element.type == "textarea") ||
		(element.type == "password"))
	{
		if (element.value == element.defaultValue)
		{
			return true;
		}
	}

	//checkbox
	else if (element.type == "checkbox")
	{
		if (element.defaultChecked == element.checked)
		{
			return true;
		}
	}

	//radio
	else if (element.type == "radio")
	{
		if (element.defaultChecked == element.checked)
		{
			return true;
		}
	}

	//select
	else if ((element.type == "select-one") || (element.type == "select-multiple"))
	{
		var counter = 0;
		for (var k =0; k < element.length; k++)
		{
			//how many are default selected
			//if they have no value, and are
			//selected but not default selected,
			//then they are the first, blank element
			if (element.options[k].value == ""
				&& (element.options[k].selected != element.options[k].defaultSelected))
			{
				counter++;
			}
			else if (element.options[k].selected == element.options[k].defaultSelected)
			{
				counter++;
			}//end if
		}//end for select obj

		if (counter == element.length)
		{
			return true;
		}
	}

	return false;
}//end isDefaultValue

//////////////////////////////////////////
//the following functions are small validations
//the were being repeated in alot of searches
//////////////////////////////////////////

//latAndLong
//check for coord values
function latAndLong(latDeg,latMin,lonDeg,lonMin)
{
    if (! allHaveValues(latDeg,
                latMin,
                lonDeg,
                lonMin))
    {
        return ("Please enter Latitude and Longitude Degrees and Minutes when searching by Coordinates\n");
    }//end if
    //return true;
}//end latAndLong

//latAndLongAndSec
//check for coord values
function latAndLongAndSec(latDeg,latMin,latSec,lonDeg,lonMin,lonSec)
{
    if (! allHaveValues(latDeg,
                latMin,
                latSec,
                lonDeg,
                lonMin,
                lonSec))
    {
        return ("Please enter Latitude and Longitude Degrees Minutes and Seconds when searching by Coordinates\n");
    }//end if
    //return true;
}//end latAndLongAndSec

//radiusAndSeconds
//if radius then lat and long seconds
function radiusAndSeconds(radius,latSec,longSec)
{
    //radius, then must have lat and long seconds
    if ((allHaveValues(radius)) &&
        (! allHaveValues(latSec,
                 longSec)))
    {
        return ("Latitude and Longitude Seconds must be provided when searching by Radius\n");
    }//end if
    //return true;
}//end radiusAndSeconds

//frequencyExact
function frequencyExact(freq)
{
    if (! allHaveValues(freq))
    {
        return ("Please enter a frequency when searching by exact frequency\n");
    }//end if
    //return true;

}//end frequencyExact

//frequencyRange in between
function frequencyRange(low,high)
{
    if (! allHaveValues(low,
                high))
    {
        return ("Please enter a both a lower and upper frequency when searching by frequency range\n");
    }//end if
    if (Number(low.value) >=
        Number(high.value))
    {
        return ("Please make sure upper frequency is greater then lower frequency\n");
    }//end if
    //return true;
}//end frequencyRange

//heightExact
// check for a valid height
function heightExact(height)
{
    if (! allHaveValues(height))
    {
        return ("Please enter a exact height when searching by exact height\n");
    }//end if
    //return true;
}//end heightExact

//heightRange
//then check for two valid heights
function heightRange(low,high)
{
    if (! allHaveValues(low,
                high))
    {
        return ("Please enter a both a lower and upper height when searching by height range\n");
    }//end if
    if (Number(low.value) >=
        Number(high.value))
    {
        return ("Please make sure upper height is greater then lower height\n");
    }//end if
    //return true;
}//end heightRange

//frnValidateSearch
function frnValidateSearch(frn)
{
    //only numbers in frn
    if (isNaN(frn))
    {
   		return ("FRN must be numeric\n");//
    }//end if

    //less then 10 digits
    if (frn.length > 10)
    {
   		return ("FRN cannot be more than 10 digits\n");
    }//end if
}//end frnValidateSearch

//frnValidate
function frnValidate(frn)
{
    //only numbers in frn
    if (isNaN(frn))
    {
   		return ("FRN must be numeric\n");//
    }//end if

    //10 digits
    if (frn.length < 10)
    {
   		return ("10-digit FRN is required\n");
    }//end if
	return true;
}//end frnValidate

//cityState
//must have state selected
//or have entered a city
function cityState(city,state)
{
    if (! anyHaveValues(city,
                state))
    {
        return ("Please select one or more states, or enter a city, when searching by City/State\n");
    }//end if
    //return true;
}//end cityState

//ownerTinAndZip
//if owner tin, then zip code
function ownerTinAndZip(tinValue,tin,zip){
    var tinBox = getSelectValue(tin);
    if ((tinBox.indexOf(tinValue) != -1) &&
        (! allHaveValues(zip)))
    {
        return ("ZIP Code is required when searching by Owner TIN\n");
    }//end if
}//end ownerTinAndZip

//dateRange
//make sure no "--" days (invalid)
//are selected, the "--" and blank values
//come from the setDaysInMonth function
//and the to date is larger then the from
//noSelectFlag is for raw values, not in select boxes
function dateRange(fromDay,fromMonth,fromYear,toDay,toMonth,toYear,noSelectFlag)
{
    var toDate;
    var fromDate;

    if (noSelectFlag == true)
    {
        if (toYear.value,toMonth.value,toDay.value)
        {
            toDate = new Date(toYear.value,(toMonth.value-1),toDay.value);
        }
        if (fromYear.value,fromMonth.value,fromDay.value)
        {
            fromDate = new Date(fromYear.value,(fromMonth.value-1),fromDay.value);
        }
    }
    else
    {
        if ((! getSelectValue(fromDay)) ||
            (! getSelectValue(toDay)))
        {
            return ("Please select a valid day, when searching by date range\n");
        }//end if
        toDate = new Date(getSelectValue(toYear),(getSelectValue(toMonth)-1),getSelectValue(toDay));
        fromDate = new Date(getSelectValue(fromYear),(getSelectValue(fromMonth)-1),getSelectValue(fromDay));
    }

    //BCOMPAT
    //ie returns "NaN", netscape "Invalid Date" of date was not build correctly
    //(not entered so undefined was returned from splitDates)
    if (fromDate == "NaN" || fromDate == "Invalid Date")
    {
           return ("Please enter a valid FROM date\n");
    }
    if (toDate == "NaN" || toDate == "Invalid Date")
    {
           return ("Please enter a valid TO date\n");
    }

    //at least a from date
    //if (! fromDate)
    //{
    //       return ("Please enter at least a FROM date\n");
    //}

    //from date and to date
    if (! fromDate || ! toDate)
    {
           return ("Please enter both FROM and TO dates\n");
    }

    //toDate and to greater then from
    //if(toDate && (fromDate >= toDate))
    if (fromDate > toDate)
    {
        return ("Please make sure TO date is greater than FROM date, when searching by date range\n");
    }
    //return true;
}//end dateRange


//splitDates
//splits date and inserts the values
//into hiddens in the form
function splitDates(date,monthHidden,dayHidden,yearHidden)
{
    var dateArray = date.value.split("/");
    var month = dateArray[0];
    var day = dateArray[1];
    var year = dateArray[2];

    if (month) {monthHidden.value = month;}else{monthHidden.value = ""}
    if (day) {dayHidden.value = day;}else{dayHidden.value = ""}
    if (year) {yearHidden.value = year;}else{yearHidden.value = ""}
}//end splitDates

//dateValidate
//validate dates...
//mm/dd/yyyy , m/dd/yyyy , mm/d/yyyy , /m/d/yyyy
//are the excepted formats
//also checks for days in the month, ect.
function dateValidate(date)
{
    //if date starts with
    // d/ then assume and add
    //the 0 to the month
    var leadingZero = /^\d\//;
    if (date.match(leadingZero))
    {
        date = "0" + date;
    }

    //if month starts with
    // d/ then assume and add
    //the 0 to the month
    var dayMatch1 = /^\d\/\d\//;
    var dayMatch2 = /^\d\d\/\d\//;
    if (date.match(dayMatch1) || date.match(dayMatch2))
    {
        var insertArray = date.split("/");
        date = insertArray[0] + "/0" + insertArray[1] + "/" + insertArray[2];
    }

    //check for date format
    var dateFormat = /^\d\d\/\d\d\/\d\d\d\d$/;
    if (! date.match(dateFormat))
    {
        return ("Please enter dates in the MM/DD/YYYY format\n");
    }//end if

    var dateArray = date.split("/");
    var month = dateArray[0];
    var day = dateArray[1];
    var year = dateArray[2];

    //are they numbers
    if (isNaN(month) || isNaN(day) || isNaN(year))
    {
        return ("Month, year and day can only be numbers\n");
    }//end if

    //day, month and year cannot be 0
    if (day == 0 || month == 0 || year == 0)
    {
    	return ("The entered date is not valid, day, month or year cannot be 0");
    }
    
    //month under 12, and a number
    if (month > 12)
    {
        return ("The entered date is not valid, month is greater than 12\n");
    }//end if

    //day a number  and <= days in month
    if (day > daysInMonth(month,day,year))
    {
        return ("The date is invalid, there are only " + daysInMonth(month,day,year) +" days in " + month + " " + year +"\n");
    }//end if
    return true;
}//end dateValidate

//function dobValidate
//for frc dob
//must be between 115 and 10
function dobValidate(date,today)
{
	//Set the two dates
	var dateArray = date.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var checkDate = new Date(year,month - 1,day); //Month is 0-11 in JavaScript

	//var dateArray = today.split("/");
	//var month = dateArray[0];
	//var day = dateArray[1];
	//var year = dateArray[2];
	//var checkToday = new Date(year,month - 1,day); //Month is 0-11 in JavaScript

	//Get 1 day in milliseconds
	var one_day=1000*60*60*24;

	var dateArray = today.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var oneHundredAndFifteenYearsAgo = new Date(year -115,month - 1,day); //Month is 0-11 in JavaScript

	var dateArray = today.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var tenYearsAgo = new Date(year -10,month - 1,day); //Month is 0-11 in JavaScript


	var dateArray = today.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var twentyOneYearsAgo = new Date(year -21,month - 1,day); //Month is 0-11 in JavaScript

	if (Math.ceil((checkDate.getTime()-oneHundredAndFifteenYearsAgo.getTime()) <= 0))
	{
	    return "150";
	}

	if (Math.ceil((checkDate.getTime()-tenYearsAgo.getTime()) >= 0))
	{
	    return "10";
	}

	if (Math.ceil((checkDate.getTime()-twentyOneYearsAgo.getTime()) > 0))
	{
	    return "21";
	}
    return true;


}//end dobValidate

//monthDayValidate
//a version of the above dateValidate that skips years
//mm/dd
//are the excepted formats
function monthDayValidate(date)
{
    //if date starts with
    // d/ then assume and add
    //the 0 to the month
    var leadingZero = /^\d\//;
    if (date.match(leadingZero))
    {
        date = "0" + date;
    }

    //if month starts with
    // d/ then assume and add
    //the 0 to the month
    var dayMatch1 = /^\d\/\d\//;
    var dayMatch2 = /^\d\d\/\d\//;
    if (date.match(dayMatch1) || date.match(dayMatch2))
    {
        var insertArray = date.split("/");
        date = insertArray[0] + "/0" + insertArray[1] + "/" + insertArray[2];
    }

    //check for date format
    var dateFormat = /^\d\d\/\d\d$/;
    if (! date.match(dateFormat))
    {
        return ("Please enter dates in the MM/DD format\n");
    }//end if

    var dateArray = date.split("/");
    var month = dateArray[0];
    var day = dateArray[1];

    //are they numbers
    if (isNaN(month) || isNaN(day))
    {
        return ("Month and day can only be numbers\n");
    }//end if

    //month under 12, and a number
    if (month > 12)
    {
        return ("The entered date is not valid, month is greater than 12\n");
    }//end if

    //day a number  and > 31
    //we have no year, so we cannot see if the date really exsits...
    if (day > 31)
    {
        return ("The date is invalid, date cannot be greater than 31\n");
    }//end if
    return true;
}//end monthDayValidate

//dateDefinedRange
//checks for a value in the defined date select range
function dateDefinedRange(rangeSelect)
{
    if (! getSelectValue(rangeSelect))
    {
        return ("Please Select a defined date range, when searching by defined date range\n");
    }//end if
}// end dateDefinedRange

//isdateActive
//Don't use this, use hasDateType.
//this is still here for ASR, at present
//we need to prevent users from setting dates or date stuff without
//selecting a date type, but we cannot check radios because one is always
//selected by default. so onChange of any date fields, we set dateActive
//flag to true, then if that is true, we make sure a dateType is selected
//on reset, we reset that value as well
function isdateActive(dateActive,dateType)
{
    if ((dateActive.value == "true") &&
       (getSelectValue(dateType)==""))
    {
        return ("Please select a Date Type when searching by date\n");
    }//end if
    //return true;
}//end isdateActive

//hasDateType
//this replaces the above function
//isDateActive.
function hasDateType(dateType)
{
    if (getSelectValue(dateType)=="")
    {
        return ("Please select a Date Type when searching by date\n");
    }//end if
}

//setValidatedFlagTrue
//sets the jsValidated flag to true
//so the backend will know form has been validated
//it is set to false by default in the page
//so if it's not true in the backend, javascript is off
//in the browser
function setValidatedFlagTrue(jsValidated)
{
    jsValidated.value="true";
    //return true;
}//end setValidatedFlagTrue

//function setAllFeetToMeters
//first arg is what to set select to,
//second is the select
//others are the value boxes
//else call convert to meters
function setAllFeetToMeters(setTo,selectObj)
{
    //if its not already what we want
    //then do the switch
    if (getSelectValue(selectObj) != setTo)
    {
        setSelectValue(selectObj,setTo);
        for(j=2;j<arguments.length;j++)
        {
            arguments[j].value = feetToMeter(arguments[j].value);
        }//end for
    }//end if
}//end setAllFeetToMeters

//function setAllRadiusToKilometers
//first arg is what to set select to,
//second is the select
//others are the value boxes
//else call convert to meters
function setAllRadiusToKilometers(setTo,selectObj)
{
    //if its not already what we want
    //then do the switch
    if (getSelectValue(selectObj) != setTo)
    {
        setSelectValue(selectObj,setTo);
        for(j=2;j<arguments.length;j++)
        {
            arguments[j].value = mileToKiloMeter(arguments[j].value);
        }//end for
    }//end if
}//end setAllRadiusToKilometers

//function setCurrentYear
//takes a select box and sets it to the current year
//select box values must be 4 digit years
function setCurrentYear(selObj)
{
    setSelectValue(selObj,String(new Date().getFullYear()));
}//end setCurrentYear

//function addToTextFromSelect
//adds the selected value from a select to a text box
function addToTextFromSelect(selObj,textObj,delimiter)
{
    //if box is empty, don't add delimiter
    if (textObj.value.length < 1)
    {
        textObj.value = textObj.value + getSelectValue(selObj);
    }
    else
    //else delimiter
    {
        textObj.value = textObj.value + delimiter + getSelectValue(selObj);
    }
    //end if delimiter
}//end addToTextFromSelect


//function repopSelectFromArray
//this rebuilds select based on the value passed in
//the matchCode value must match a value stored as
//value: in the array that is passed in...
//ie...'9:AA - Coast & Ground-Site-Based'
//all items in array that match 9:
//will be put into the to array
function repopSelectFromArray(matchCode,toSelectObject,array)
{

    var selectIndex = 0;

    //de-select
    toSelectObject.selectedIndex=-1;
    //get the length
    var selectLength = toSelectObject.length - 1;
    //erase them all
    for (j=selectLength;j >= 0;j--)
    {
        toSelectObject.options[j].value = "";
        toSelectObject.options[j].text = "";
        toSelectObject.options[j] = null;
    }//end for select obj


    //if we want to display them all
    //then loop thru and set them all
    if (matchCode == "ALL")
    {
        for(j=0;j < array.length;j++)
        {
            var tmp = array[j];
            tmpArray = new Array(2);
            tmpArray = tmp.split(":");
            if (tmpArray[0] && tmpArray[1])
            {
                //load it up
                toSelectObject.options[j] = new Option(tmpArray[1],tmpArray[0]);
            }//end if values
        }//end for array
    }
    else
    //else if not display all
    //then just do the smaller array
    {
        for(j=0;j < array.length;j++)
        {
            //if item in array starts with the match code we want, like 1:
            if (array[j].indexOf(matchCode + "|") == 0)
            {
                var tmp = array[j];
                tmpArray = new Array(2);
                tmpArray = tmp.split(":");
                //load it up
                toSelectObject.options[selectIndex] = new Option(tmpArray[1],tmpArray[0]);
                selectIndex++;
            }//end if groupId match
        }//end for array
    }//end if not display all
}//end repopSelectFromArray

//function addSelectedItems
//this takes the selected
//items from on select and
//moves them into the other
function addSelectedItems(fromSelect,toSelect)
{
	//loop thru from looking from selected
	for (var j=0;j < fromSelect.length;j++)
	{
		//if selected
		if (fromSelect.options[j].selected == true)
		{
			addFlag = true;
			//loop thru to select
			for (var k=0;k < toSelect.length;k++)
			{
				//if it's not in there, add it
				if (toSelect.options[k].value == fromSelect.options[j].value)
				{
					addFlag = false;
					break;
				}
			}

			if (addFlag == true)
			{
				toSelect.options[toSelect.length] = new Option(fromSelect[j].text,fromSelect[j].value);
			}
		}
	}
	//remove the null value
	if (toSelect.options[0].value == "")
	{
		toSelect.options[0] = null;
	}
}// end addSelectedItems

//function removeSelectedItems
//removes selected items
//from a select obj
function removeSelectedItems(selectObj)
{
	//loop thru from looking from selected
	for (var j=0;j < selectObj.length;j++)
	{
		//if selected
		if (selectObj.options[j].selected == true)
		{
			selectObj.options[j] = null;
			j--;
		}
	}
}//end removeSelectedItems

//function moveSelectedItems
//this function removes the selected items from one list and
//adds them into the other
//Need to make sure there are no item in common between these 2 lists
function moveSelectedItems(fromSelect,toSelect)
{
	//loop thru from looking fromSelected
	for (var j=0;j < fromSelect.length;j++)
	{
		//if selected
		if (fromSelect.options[j].selected == true)
		{
			toSelect.options[toSelect.length] = new Option(fromSelect[j].text,fromSelect[j].value);
			fromSelect.options[j] = null;
			j--;
		}
	}
	//remove the null value
	if (toSelect.options[0].value == "")
	{
		toSelect.options[0] = null;
	}
}// end addSelectedItems

//function selectAll
//this selects all the
//items in a select
function selectAll(selectObj)
{
	for (var j=0;j < selectObj.length;j++)
	{
		selectObj.options[j].selected = true
	}
}//end selectAll

//leftClickTrap
//prevents left clicking on form submit buttons
//so ie users can't not follow the query download instructions
function leftClickTrap()
{
    if (navigator.appName == 'Microsoft Internet Explorer' && event.button == 1)
    {
        var alertString = "Internet Explorer users:\r";
            alertString += "Right-click on the Download button, move your cursor over";
            alertString += " the Download button and click your right mouse button.\r";
            alertString += "Select Save Target As.\r";
            alertString += "In the Save As window, choose the directory on your PC or";
            alertString += " network where you want to save the file. \r";
            alertString += "Then click Save.";
        alert(alertString);
        return false;
    }

}//end leftClickTrap

////////////////////////////////////////////////
// validatePhoneFormat
// allows (xxx)xxx-xxxx or (xxx) xxx-xxxx or xxx-xxx-xxxx or xxxxxxxxxx
// all numeric only
////////////////////////////////////////////////
function validatePhoneFormat(phoneNumber)
{

    var format1 = /^\(\d{3}\)\d{3}-\d{4}$/;
    var format2 = /^\(\d{3}\) \d{3}-\d{4}$/;
    var format3 = /^\d{3}-\d{3}-\d{4}$/;
    var format4 = /^\d{10}$/;
    //if ( (phoneNumber == null) || (phoneNumber.trim().length() == 0) ) {
    //    return true;
    //}
    if (! format1.test(phoneNumber) &&
        ! format2.test(phoneNumber) &&
        ! format3.test(phoneNumber) &&
        ! format4.test(phoneNumber))
    {
        return ("Phone or Fax Number Invalid, enter (xxx)xxx-xxxx or (xxx) xxx-xxxx or xxx-xxx-xxxx or xxxxxxxxxx, digits only");
    }//end if
    return true;
}// end for validatePhoneFormat

////////////////////////////////////////////////
// validatePrecent
// all numeric only
// between 0 and 100, or N/A
////////////////////////////////////////////////
function validatePercent(percent)
{
    //no move then 2 after the .
    //and others
    var format1 = /^\d{3}.\d{2}$/;
    var format2 = /^\d{2}.\d{2}$/;
    var format3 = /^\d{1}.\d{2}$/;
    //var format4 = /^\d{2}$/;

    if (! format1.test(percent) &&
        ! format2.test(percent) &&
        ! format3.test(percent))
    {
        return ("Percent Format Invalid, enter xx.xx or xxx.xx, digits only");
    }//end if

    if ((percent < 0) || (percent > 100))
    {
        return ("Percent must be between 0 and 100");
    }//end if
    return true;
}// end for validatePercent

////////////////////////////////////////////////
// validateEmail
////////////////////////////////////////////////
function validateEmail(email)
{
    //any chars, then an @, then any chars, then a . then 2 or 3 chars
    // var format1=/^.+@.+\..{2,3}$/
    // SCR 7929 validate for spaces
    //var format1=/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,3}$/
    //modified 7929 to include .-_
    //var format1=/^[\w\.\_\-]+@[a-zA-Z0-9\.\-]+\.[\w\.\_\-]{2,3}$/
    //modified 9281 (removed the number of characters expected after the last .)
    var format1=/^[\w\.\_\-]+@[a-zA-Z0-9\.\-]+\.[\w\.\_\-]{2,}$/
    if (! format1.test(email))
    {
        return ("Please enter a valid email address");
    }//end if

    return true;
}// end validateEmail


////////////////////////////////////////////////
// trim
// for some reason, this is not a standard
// javascript function
////////////////////////////////////////////////
function trim(value)
{
    // skip leading and trailing whitespace
    // and return everything in between
   return value.replace(/^\s*(\b.*\b|)\s*$/, "$1");
}

/////////////////////////////////////
// saveConfirm
// goes to page if no changes were made, or cancel
// else submits form
////////////////////////////////////

function saveConfirm(form,page,anyChanges)
{
    if (anyChanges == 'true')
    {
        if (confirm("Save data before leaving page?"))
        {
            if (validate(form))
            {
                form.submit();
            }
        }//else go to page
        else
        {
            document.location=page;
        }//end if confirm
    }//else if not any changes go to page
    else
    {
        document.location=page;
    }//end if any changes
}//end cancelAll



/////////////////////////////////////
// isDatePast
// returns false is date is in the past
// checks by a whole day, to cover for time
// diffs between computers
// assumes dateValidate() is true
//
//we also pass in today from server date, not client date
////////////////////////////////////
function isDatePast(date,today)
{
	//Set the two dates
	var dateArray = date.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var checkDate = new Date(year,month - 1,day); //Month is 0-11 in JavaScript

	var dateArray = today.split("/");
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	var checkToday = new Date(year,month - 1,day); //Month is 0-11 in JavaScript

	//Get 1 day in milliseconds
	var one_day=1000*60*60*24;

	if (Math.ceil((checkToday.getTime()-checkDate.getTime())/(one_day) < 0))
	{
		//alert(Math.ceil((checkToday.getTime()-checkDate.getTime())/(one_day)));
	    return ("The date is invalid, it is in the future\n");
	}
    return true;
}

////////////////////////////////////////////////
// validatePoBoxFormat
////////////////////////////////////////////////
function validatePoBoxFormat(pobox)
{
	var format1 = /[^a-zA-Z0-9]/;

    if( format1.test(pobox) )
    {
        return ("Please enter valid P.O.Box (alphanumeric only)");
    }//end if

    return true;
}// end validatePoBoxFormat

////////////////////////////////////////////////
// validateAlphanumeric
////////////////////////////////////////////////
function validateAlphanumericFormat(value)
{
	var format1 = /[^a-zA-Z0-9\s]/;

    if( format1.test(value) )
    {
        return ("Please enter alphanumeric values only");
    }//end if

    return true;
}// end validateAlphanumeric

////////////////////////////////////////////////
// validateDigits
////////////////////////////////////////////////
function validateDigitsFormat(digits)
{
    if (! IsAllDigits(digits))
    {
        return ("Please enter numeric values only");
    }//end if

    return true;
}// end validateDigits


///////////////////////////////////////////////////
// Check if the argument is positive whole number
///////////////////////////////////////////////////
function IsPosWholeNumber(number) {

        if(number.length == 0) {
                return false;
        }
        for (var i=0; i<number.length; i++) {
                var ch = number.charAt(i);
                if( ch < "0" || ch > "9") return false;
        } //end for
        return true;
}//end IsPosWholeNumber


////////////////////////////////////////////////
// validatePosWholeNumber
////////////////////////////////////////////////
function validatePosWholeNumber(digits)
{
    if (! IsPosWholeNumber(digits))
    {
        return ("Please enter positive whole numbers only");
    }//end if

    return true;
}// end validatePosWholeNumber


////////////////////////////////////////////////
// validateScaleFormat
////////////////////////////////////////////////
function validateScaleFormat(value,before,after)
{
	var errorFlag = false;
	var beforeTest = before;

	//remove prefix 0's
	value = value.replace(/^0+(.*[^\^0+])/, "$1");

	//if there is a . , then removed suffix0's
	if (value.indexOf(".") > -1)
	{
		value = value.replace(/(^.*[^0+$])0+$/, "$1");
	}

	//if more then one .
	var pieces = value.split(".");
	if (pieces.length > 2)
	{
		errorFlag = true;
	}

	//numbers only
	if (pieces[0] && validateDigitsFormat(pieces[0]) != true)
	{
		errorFlag = true;
	}

	//numbers only
	if (pieces[1] && validateDigitsFormat(pieces[1]) != true)
	{
		errorFlag = true;
	}

	//if first char is -, then allow 1 more in length
	if (pieces[0] && pieces[0].charAt(0) == "-")
	{
		beforeTest+=1;
	}

	//if no more then dbLength chars after .
	if (pieces[0] && pieces[0].length > beforeTest)
	{
		errorFlag = true;
	}

	//if no more then dbScale chars after .
	if (pieces[1] && pieces[1].length > after)
	{
		errorFlag = true;
	}

    if(errorFlag == true)
    {
        //return ("Please enter numeric values with precision of " + dbPrecision + " and scale of " + dbScale);
        return ("Valid entry is " + before + " positions to the left of the decimal and " + after + " positions to the right of the decimal");
    }//end if

    return true;
}//end validatePosWholeDigits


function wildcardCharCHK(element, rtnAlertMsg)
{

	var alertString = "";
	//you can build up the invalid charactor here
	// use \ in front of the special punctuation , such as \%\?\*\\\/ you R looking for %,?,*,\,/
	var regExp = /[\%]/;
	var inputStr = element.value;
	if(inputStr.search(regExp) > -1){
		if(rtnAlertMsg =='Y'){
			return ("\"%\" is not valid search criteria\n");
		}else{
			alert("\"%\" is not valid search criteria\n");
			if (element.type != "hidden"){element.focus();}
			return false;
		}
	}

	regExp = /^\_/;
	if(inputStr.search(regExp) > -1){
		if(rtnAlertMsg =='Y'){
			return ("\"_\" is not valid search criteria\n");
		}else{
			alert("\"_\" is not valid search criteria\n");
			if (element.type != "hidden"){element.focus();}
			return false;
		}
	}

	if(rtnAlertMsg =='Y'){
		return "";
	}

	return true;
}

