var testObj;//used for fading in and out

var dragID = "";
var positionable = false   


//CONSTANTS
//These two constants control the backcolor of controls for the validation routines
var FAILCOLOR = "#FF0C1C";	
var PASSCOLOR = "White";

//Controls the color of selected and Deselected Table Rows
var SELECTEDROWBACKCOLOR = "lightgray";
var DESELECTEDROWBACKCOLOR = "White";


function initFadeIn(strID) {
	testObj = document.getElementById(strID);
	for (var i=0;i<11;i++)
		setTimeout('setOpacity('+i+')',30*i);
	return false;
}

//------------------------------------------------------------------------------------------

function initFadeOut(strID) {

	testObj = document.getElementById(strID);
		setOpacity( 0);
	return true;
}

//------------------------------------------------------------------------------------------

function setOpacity(value)	
{
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

//------------------------------------------------------------------------------------------

function disableControls(doc, strCtrlIDList, blnDisabled){
	var x;
	var arrCtrls = strCtrlIDList.split(",");
	var ctrl
	
	for (x = 0; x < arrCtrls.length; x++){
		ctrl = doc.getElementById(arrCtrls[x]);
		ctrl.disabled = blnDisabled;
	}
}

//------------------------------------------------------------------------------------------

function openWindow(argURL, argHeight, argWidth){
	/*this function accepts a url (relative) the length and width and displays it in a new window called 
	"my_window". */

	window.open(argURL,"my_new_window",	"toolbar=no,location=no, directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=" + argWidth + ",height=" + argHeight)
}

//------------------------------------------------------------------------------------------

function AllChecks(ckTarget, blnValue){
	//Takes the array check boxes (ckTarget) and sets their check value 
	//to the value of blnValue
	for (var x = 0; x < ckTarget.length; x++)
		ckTarget[x].checked = blnValue;
}

//------------------------------------------------------------------------------------------

function extractValuesFromCheckBoxArray(argArray){
	//Extracts the values from an array of check boxes where the checkbox.checked property = true
	var strResult = ""
	for (var x = 0; x < argArray.length; x++)
		if (argArray[x].checked)
			strResult += argArray[x].value + ", ";
	if (strResult != "") 
		strResult = strResult.slice(0, -2);
	return strResult;
}

//------------------------------------------------------------------------------------------

function extractFromQueryString(argName){
	//return the value part of the name value pair of a given the name
	var arrNameValuePair, arrNameValueDetail;
	var queryString
	//split the name value pairs out of the query string
	//Remove the "?" from the Query String
	queryString = document.location.search.slice(1)
	//Split into array of name value pairs
	arrNameValuePair = queryString.split("&")
	for (var x=0; x < arrNameValuePair.length;x++){
		//split out each name value pair
		arrNameValueDetail = arrNameValuePair[x].split("=");
		//if the name is found, return the value
		if (arrNameValueDetail[0]==argName)
			return arrNameValueDetail[1];
	}//else return nothing
	return "";
}

//------------------------------------------------------------------------------------------

function checksToText(arrCheckBoxes, argTextBox){
	//This function populates a textbox (argTextBox) with the value properties of an 
	//array of check boxes
	var strResults = "";	//to hold the check box values
	var x;			//counter
	
	for (x = 0; x < arrCheckBoxes.length; x ++ )
		if ((arrCheckBoxes[x].checked) && (arrCheckBoxes[x].value != ""))
			strResults += arrCheckBoxes[x].value + ", ";

	if (strResults!= "")
		strResults = strResults.slice(0, -2);	//clears the last ", "

	argTextBox.value = strResults;
}

//------------------------------------------------------------------------------------------

function textToChecks (argList, arrCheckBoxes){
	//This function accepts a textbox with a	comma separated list in string format and 
	//compares each value to the value property of the arrCheckBoxes elements
	//If a match is found, the element's checked property is set to true
	
	var strList = argList.value.split(", ");
	var x, y;
	// Loop through arrCheckBoxes
	for (x = 0; x < arrCheckBoxes.length; x++)
	{	//Loop through strList()
		for (y = 0; y < strList.length; y++)
		{	//Match Found
			if (arrCheckBoxes[x].value == strList[y])
				arrCheckBoxes[x].checked = true
		}
	}
}

//------------------------------------------------------------------------------------------

function extractOptionsFromSel(sel) {
	var x = 0;
	var Results = "";
	for (x = 0; x < sel.options.length ; x++ ){
		if (sel.options[x].selected == true){
			Results = Results +  sel.options[x].value + ", "
            }
	}
	alert(Results);
}

//------------------------------------------------------------------------------------------
 
function strCSOptionsFromSel(sel) {
	//This function accepts a select element and returns 
	//a comma separated list of Selected Values.  Originally built to compare the 
	//contents of a multi select <select> element with a single select <select>
	var x = 0;													
	var Results = "";	
	
	for (x = 0; x < sel.options.length ; x++ ){					
		if (sel.options[x].selected == true){					
			Results +=  sel.options[x].value + ", "				
		}
	}

	if (Results.length > 0)	{
		Results = Results.slice(0, Results.length - 2);			//Remove the last ", "
		}
		alert(Results);
	return Results;												
}



//------------------------------------------------------------------------------------------

//**************************************************VALIDATION
//Selection valudation value cannot = 0
function isValidSelection(ctrl){
//this proceedure compares the value of the control to 0 and markes the ctrl FAILCOLOR if it == 0
	if ((ctrl.value == "0") || (ctrl.value == "none")) {
		ctrl.style.background=FAILCOLOR;
		return 1;
		}
	else {
		ctrl.style.background=PASSCOLOR;
		return 0;
	}
}

//------------------------------------------------------------------------------------------
function isValidPrice(ctrl) {
	//makes sure that value is numeric and in the following form: x0.00
	if ( ctrl.value.match(/^\$?\d+.\d\d$/) ){
		ctrl.style.background=PASSCOLOR;
		return 0;
	} else {
		ctrl.style.background=FAILCOLOR;
		return 1;
	}
}

//------------------------------------------------------------------------------------------
function isValidNumber(ctrl) {
	//makes sure that value is numeric and in the following form: x0.00
	if ( ctrl.value.match(/^\d+\.?\d*?$/) ){
		ctrl.style.background=PASSCOLOR;
		return 0;
	} else {
		ctrl.style.background=FAILCOLOR;
		return 1;
	}
}

//------------------------------------------------------------------------------------------
function isValidInteger(ctrl) {
	//makes sure that value is numeric and in the following form: x0.00
	if ( ctrl.value.match(/^\d+$/) ){
		ctrl.style.background=PASSCOLOR;
		return 0;
	} else {
		ctrl.style.background=FAILCOLOR;
		return 1;
	}
}

//------------------------------------------------------------------------------------------
function isValidText(ctrl){
//this proceedure examines the value attribute of ctrl and makes sure that it contains a string 
// with a length > 0.  Uses the constants FAILCOLOR and PASSCOLOR

	if ( ctrl.value == "" ){
		ctrl.style.background=FAILCOLOR;
		return 1;
		}
	else{
		ctrl.style.background=PASSCOLOR;
		return 0;
	}
}

//------------------------------------------------------------------------------------------

function isValidReqMinLen(ctrl){
//this function examines the value attribute of ctrl and makes sure that it contains 
//a string of textLen characters

	var reqMinLength = ctrl.getAttribute("textLen");

	if ( ctrl.value.length <  reqMinLength){
		ctrl.style.background=FAILCOLOR;
		return 1;
		}
	else{
		ctrl.style.background=PASSCOLOR;
		return 0;
	}
}


//------------------------------------------------------------------------------------------

function isValidEmail(ctrl, req){
	//Uses a resgular expressions to test for valid email structure
	//any number of characters followed by the @ symbol followed by any number of characters followed by the . symbol
	//followed by any number of characters 

	var mailChecker = /.+@.+\..+/;

	if (req) { //if this is a required field
		//if the text is missing...return 1 get out
		if (isValidText(ctrl)){
			return 1;
		}
	} else if(ctrl.value == '') {
		ctrl.style.background=PASSCOLOR;
		return 0; //this is is not a required field	
	}

	//test the structure
	if (mailChecker.test(ctrl.value) == true){
		//make sure the address ends with an acceptable domain
		var okDomains = /(com|org|edu|net|bus|gov)$/;
		if (okDomains.test(ctrl.value)== true){
			ctrl.style.background=PASSCOLOR;
			return 0;	//pass
			
		}
	}

	ctrl.style.background=FAILCOLOR;
	return 1;	//fail
}

//------------------------------------------------------------------------------------------

function isMatchField(ctrl){

	//For Use in password validation
	var matchCtrl = document.getElementById(ctrl.getAttribute("MatchCtrl"));
	//used the + operator because \\ short circutes the second operation
	if(isValidText(ctrl) + isValidText(matchCtrl)){
		//If either control is blank this fails
		return 1;
	}
	//test to make sure that the values are identical
	if (ctrl.value == matchCtrl.value){
		ctrl.style.background=PASSCOLOR;
		matchCtrl.style.background=PASSCOLOR;
		return 0; 
	} else {
		ctrl.style.background=FAILCOLOR;
		matchCtrl.style.background=FAILCOLOR;
		return 1; 
	}
}

//------------------------------------------------------------------------------------------


//date validation using a regular expression
function isValidDate(ctrl) {

	//this validate date input based on a regular expression
    //var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var RegExPattern =/^\d{2}\/\d{2}\/\d{4}$/;
	//var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay mm/dd/yyyy.';
    var dtTemp
	if ((ctrl.value.match(RegExPattern)) && (ctrl.value!='')) {
		ctrl.style.background=PASSCOLOR;
		return 0; 
    } else {
        ctrl.style.background=FAILCOLOR;
		return 1;
    } 
}

//------------------------------------------------------------------------------------------


// zip code validation
function isValidZip(ctrl){
	//valudates to a 5 digit zip code	
	var regExPattern = /^\d{5}$/;
	if ( ctrl.value.match(regExPattern) ){
		ctrl.style.background=PASSCOLOR;
		return 0; 	
	} else {
		ctrl.style.background=FAILCOLOR;
		return 1; 
	}
	
}

//------------------------------------------------------------------------------------------

function isValidPhone(ctrl) {
	//this validate date input based on a regular expression
    //var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var RegExPattern =/^(\(?\d{3}?\)?)?[-| |.]?\d{3}[-| |.]?\d{4}$/;
	//var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay mm/dd/yyyy.';
 
	if (ctrl.value.match(RegExPattern))  {
		ctrl.style.background=PASSCOLOR;
		return 0; 
    } else {
        ctrl.style.background=FAILCOLOR;
		return 1;
    } 
}

//------------------------------------------------------------------------------------------

function ctrl_LostFocus(ctrl){
	//evaluates the dataType attribute for a control dataType, evaluates its value.
	//This should be used on with the onBlur event.
	//This proceedure does not return a value externally B/C it is not intended to stop 
	//the user, rather to illuminate the errors as the user fills out the form
	var result;
	//evaluate data type
	switch (ctrl.getAttribute("dataType")) {
		case "ID": //requires numeric value
			break;
		case "Price":
			result = isValidPrice(ctrl);
			break;
		case "Selection":
			result = isValidSelection(ctrl);
			break;
		case "Date":
			result = isValidDate(ctrl);
			break;
		case "ReqText":	//should be able to use for both input type text and Text area because they both use the value attribute
			result = isValidText(ctrl);
			break;
		case "ReqMinLen":
			result += isValidReqMinLen(ctrl);
			break;
		case "ReqEmail":	//required email
			result = isValidEmail(ctrl, 1);
			break;
		case "OptEmail": 	//optional email
			result = isValidEmail(ctrl, 0);
			break;
		case "MatchField":
			result = isMatchField(ctrl);
			break;
		case "ReqZip": 
			result = isValidZip(ctrl);
			break; 
		case "ReqPhone":
			result = isValidPhone(ctrl);
			break; 
		case "ReqNumber": 
			result = isValidNumber(ctrl);
			break;
          case "ReqInteger": 
               result = isValidInteger(ctrl);
               break;
	}
}

//------------------------------------------------------------------------------------------

function validateForm(argCtrls) {
	//accepts either a form or a list of ids and runs the validation routines;
	var result = 0;
	var arrElements = new Array();
	switch (typeof argCtrls ) {
		case 'string':	//this assumes that a cvs list of ids was passed in
			//create list based on ids
	
			arrIDs = argCtrls.split(',');
			for (x in arrIDs) {	// loop and push
				arrElements.push( document.getElementById( arrIDs[x] ) );
			}	
			break;
		case 'object':  //backward compatibility for accepting a form
			arrElements = argCtrls.elements;	
			break;
	}
	
	
	
	for (x = 0; x < arrElements.length; x++){
	
		switch (arrElements[x].getAttribute("dataType")) {
			case "ID": //requires numeric value is not a user controlled field
				break;
			case "Price":
				result += isValidPrice(arrElements[x]);
				break;
			case "Selection" :
				result += isValidSelection(arrElements[x]);
				break;
			case "Date":
				result += isValidDate(arrElements[x]);
				break;
			case "ReqText":
				result += isValidText(arrElements[x]);
				break
			case "ReqMinLen":
				result += isValidReqMinLen(arrElements[x]);
				break
			case "ReqEmail":	//Required email
				result += isValidEmail(arrElements[x], 1);
				break;
			case "optEmail":	//optional email
				result += isValidEmail(arrElements[x], 0);
				break;			
			case "MatchField":
				result += isMatchField(arrElements[x]);
				break;
			case "ReqZip":
				result += isValidZip(arrElements[x]);
				break; 
			case "ReqPhone":
				result += isValidPhone(arrElements[x]);
				break;
			case "ReqNumber": 
				result += isValidNumber(arrElements[x]);
				break; 
               case "ReqInteger": 
                    result = isValidInteger(arrElements[x]);
                    break;
			}
		}
		
		if(result > 0){
			alert("Highlighted fields contain invalid data");
			return false;
		}
		//will return the sum total of all the validation calls.  if the value of result = 0 then the form is valid
		return true;
	

}
//------------------------------------------------------------------------------------------


function selectSingleRow(argTable, argTRID){
//This function sets the background color of a single row in a specific table
// argTableID is the ID for the target table, argTRID stands for "Table Row ID".  It referrs 
// to the row that should be selected at the end of the function.  The function assumes that 
// all other rows will be deselected.

	var rows = argTable.getElementsByTagName("tr");

	//Loop through all rows and set background color white
	for (var x = 0;x < rows.length ;x++ ){
		if (rows[x].id == argTRID.id){	//Found the target
			rows[x].style.backgroundColor = SELECTEDROWBACKCOLOR;

			} else {

			rows[x].style.backgroundColor = DESELECTEDROWBACKCOLOR;
		}
	}
}

//------------------------------------------------------------------------------------------

function extractSelectedRows(argTable){
//Build a comma separated list that includes all selected rows of argTable
//If this table is a selectSingleRow Table then this function will only extract 
//one value which can be used witout further processing.  If no rows are selected 
//it will return  0. 
	var rows 

	try{	// this wil err if there is no table or no rows
		rows = argTable.getElementsByTagName("tr");
		}
	catch(err){
		return 0;
	}
	var result = "";				//holds the resulting string

	//build list of rows
	for(var x = 0; x < rows.length; x++){
		if (rows[x].style.backgroundColor == SELECTEDROWBACKCOLOR){
			result += rows[x].id + ",";
		}
	}

	//Test for length and remove last comma 
	if (result.length > 1){
		result = result.substr(0, (result.length - 1));
		} else {
		result = 0;
	}

	return result;
}

//------------------------------------------------------------------------
//javascript overlay code

function attachHandler_Inputs(){
	//This will attach the onBlur event to all text boxes in the document
	//test to make sure that the DOM methods exist
	if(!document.getElementsByTagName) return false;
	
	//Get the <input> elements and add 
	var ctrls = document.getElementsByTagName("input");
	//attach onBlurevents 
	for (var x=0; x < ctrls.length; x++ ){
		ctrls[x].onblur = function(){
			//this provides inline validation
			ctrl_LostFocus(this);
			return false;
		}
	}

	//Get the <select> elements and add 
	var ctrls = document.getElementsByTagName("select");

	for (var x=0; x < ctrls.length; x++ ){
	ctrls[x].onblur = function(){
		//this provides inline validation
		ctrl_LostFocus(this);
		return false;
		}
	}

	//Get the <select> elements and add 
	var ctrls = document.getElementsByTagName("textarea");

	for (var x=0; x < ctrls.length; x++ ){
	ctrls[x].onblur = function(){
		//this provides inline validation
		ctrl_LostFocus(this);
		return false;
		}
	}
}

//------------------------------------------------------------------------

function attachHandler_Submit(argSubmit, argForm){
	//Accepts a submit button and a form.  This calls validateForm on argForm which returns true
	//if the svalid otherwise it returns false. Returning false short circuits the form submission.

	argSubmit.onclick = function(){
		return validateForm(argForm);
	}
}


//------------------------------------------------------------------------	

function attachHandler_btnSave(argSubmit, argForm){
	//Accepts a submit button and a form

	argSubmit.onclick = function(){
		var validationResult = validateForm(argForm);
		
		if (validationResult){
			argForm.submit();
		}
		return validationResult;
		
	}
}

//------------------------------------------------------------------------

function clearForm( argForm ) {
	//clear out stored form values
	for (x = 0; x < argForm.elements.length; x++){
		if (argForm.elements[x].type == "text"){
			argForm.elements[x].value='';
			argForm.elements[x].style.background=PASSCOLOR;
		}
	}
}

//------------------------------------------------------------------------

function selectSingleRow( argTable, argID, argSelectBackColor, argSelectForeColor  ) {
	//This function itterates over the tr elements in a table if they have an id value
	//reset the background-color to '' unless its id matches argID then set it to 
	//specified color and set the 'selected' attribute to 'true' (string)

	
	var rows = document.getElementById(argTable).getElementsByTagName('tr');

	for (x = 0; x < rows.length; x++){
		if (rows[x].id == argID) {
			rows[x].style.backgroundColor = argSelectBackColor;
			rows[x].style.color=argSelectForeColor;
			rows[x].setAttribute('selected', 'true')
		} else {
			rows[x].style.backgroundColor = '';
			rows[x].style.color='';
			rows[x].setAttribute('selected', 'false')
		}
	}
}

//------------------------------------------------------------------------

function getSelectedRow (argTable) {
	//figure out which row was selected
	rows = document.getElementById(argTable).getElementsByTagName('tr');

	for (x = 0; x < rows.length; x++ ){
		if ( rows[x].getAttribute('selected') == 'true' ){

			return rows[x].id;
			break;
		}
	}
	return 0; //no rows were selected
}

//------------------------------------------------------------------------

function togglePosition(argDragID) {

	dragID = argDragID;
	positionable = !positionable;

}

//------------------------------------------------------------------------

function closeDialog(argDialog){
	//closes the calendar control by resetting the dispay attribute 
	//to the default from the css file
	//Used with showDialog
	document.getElementById(argDialog).style.display="";	
	togglePosition(argDialog);
}

//------------------------------------------------------------------------

function showDialog(argDialog) {
	//puts a "dialog box" (div) display proprty to "block
	//Used with closeDialog
	document.getElementById(argDialog).style.display="block";
}

//------------------------------------------------------------------------

function mouseMove(ev){
	ev = ev || window.event;
	var mousePos = mouseCoords(ev);
	var ctrl = document.getElementById(dragID);
	if (positionable == true){
		ctrl.style.left = (mousePos.x -10)+"px";
		ctrl.style.top = (mousePos.y-10)+"px";
	}
}

//------------------------------------------------------------------------

function mouseCoords(ev) {
	if (ev.pageX || ev.pageY) {
		 return {x:ev.pageX, y:ev.pageY};
	}
	return {
		 x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		 y:ev.clientY + document.body.scrollTop - document.body.clientTop
	};


}     

//------------------------------------------------------------------------

function clearFields(argFieldList) {
	//loops through argFieldList and clears the value and resets the background.  
	//call this feature before showing a dialog box.
	ctrlIDs = argFieldList.split(",");

	for (x=0; x < ctrlIDs.length; x++){
		ctrl = document.getElementById(ctrlIDs[x]);
		ctrl.style.backgroundColor = PASSCOLOR;
		switch (ctrl.tagName) {
			case "INPUT":
			case "TEXTAREA":
				ctrl.value = '';
				break;
			case "SPAN":
			case "SELECT":
				ctrl.innerHTML = '';
				break;
		}
	}
}	
//------------------------------------------------------------------------

function getXMLHTTPReqObject() {
     // this function attempts to generates the appropriate xml http requests object 
     // for the browser.  It will return false if it cannot generate the appropriate 
     //XMLHTTP Object
     var request = false; //default value

     try {
          request = new XMLHttpRequest(); // Good Browsers
     } catch(err1) {
          try {     //Some IE versions
               request = new ActiveXObject("Msml2.XMLHTTP");
          } catch(err2) {
               try {     //More IE versions
                    request = new ActiveXObject("Microsoft.XMLHTTP"); 

               } catch (err3) {
                    try {
                         request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
                    } catch (err4) {
                         request = false;
                    } 
               }
          }
     }
     return request;
} 


