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 FAILCOLOR = '#FF3333';
var PASSCOLOR = "";

//Controls the color of selected and Deselected Table Rows
var SELECTEDROWBACKCOLOR = "#FFFEB7"; 


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( arrCtrlIDs, blnDisabled){
     //toggle the disabled attribut for an array of control IDs
	var x;
	var ctrl
	
	for (x = 0; x < arrCtrlIDs.length; x++){
		ctrl = document.getElementById(arrCtrlIDs[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.value == "" ) ) {
		ctrl.style.background=FAILCOLOR;
		return 1;
		}
	else {
		ctrl.style.background=PASSCOLOR;
		return 0;
	}
}

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

//------------------------------------------------------------------------------------------
function isValidNumber(ctrl, req) {
	ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
     //makes sure that value is numeric and in the following form: x0.00

     if ( req || ctrl.value.length > 0 ) { 

          if ( ctrl.value.match(/^\d+\.?\d*?$/) ){
               ctrl.style.background=PASSCOLOR;
               return 0;
          } else {
               ctrl.style.background=FAILCOLOR;
               return 1;
          }
     } else {





     }
}

//-----------------------------------------------------------------------------------------i
function isValidInteger(ctrl) {
	//makes sure that value is numeric and in the following form: x0.00
     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
     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

     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
	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
     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
	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 
     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
	var mailChecker = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i; 



	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){
	     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})?$/;
     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
     var DatePattern1 = /^\d{2}\/\d{2}\/\d{4}$/;
     var DatePattern2 = /^[a-zA-Z]{3} \d{1,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(DatePattern1)) && (ctrl.value!='')) {
		ctrl.style.background=PASSCOLOR;
		return 0; 
     } else if ((ctrl.value.match(DatePattern2)) && (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
	ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
	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})?$/;
     ctrl.value = trim( ctrl.value ); //clean leading and trailing spaces
     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 isValidTable( ctrl ) {
     //checks to make sure that there is at least one row selected on the table
     if (extractSelectedRows( ctrl ) ){
          ctrl.style.background=PASSCOLOR; 
          return 0; 
     } else {
          ctrl.style.background=FAILCOLOR;
          return 1;          
     }
}



//------------------------------------------------------------------------------------------
function hasInnerHTML( ctrl ) {
     // this simply tests for the presence of innerHTML in controls like DIVS that are populated dynamically.  
     // Like the pricingMacro editor.
     if ( ctrl.innerHTML.length == 0 ){
          ctrl.style.background=FAILCOLOR; 
          return 1; 
     } else {
          ctrl.style.background=PASSCOLOR;
          return 0;          
     }
}
//------------------------------------------------------------------------------------------

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, 1);
			break;
		case "OptNumber": 
			result = isValidNumber(ctrl, 0);
			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= 0; x < arrIDs.length; x++) {	// loop and push
                    
                    //preventing an obvious wrong/nmissing name error
				if (document.getElementById(arrIDs[x] ) ){
                         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], 1);
				break;
 			case "OptNumber": 
				result += isValidNumber(arrElements[x], 0);
				break; 

               case "ReqInteger": 
                    result += isValidInteger(arrElements[x]);
                    break;
               case "ReqTblRow": 
                    result += isValidTable(arrElements[x]); 
                    break;
               case "HasInnerHTML": 
                    result += hasInnerHTML(arrElements[x]); 
                    break; 
               default: 
			}
		}
		
		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 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].getAttribute( 'selected')  == "true"){
			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 ) {
	//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 = SELECTEDROWBACKCOLOR;
			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
	var 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(ctrlIDs) {
	//loops through argFieldList and clears the value and resets the background.  
	//call this feature before showing a dialog box.

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

			case "SELECT":
                    ctrl.selectedIndex = 0;
                
                    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;
} 


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


function getCurrentDate(argDate, argFormat) { 
	
	var theYear 	= argDate.getFullYear(); 
	var theMonth 	= argDate.getMonth() + 1; 
	var theDay	= argDate.getDate(); 
	var theHour	= argDate.getHours(); 
	var theMinute	= argDate.getMinutes(); 
	var unixTime	= argDate.getTime /1000; 
	var medMonth   = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; 
	var result 		= '';
	
	switch (argFormat) {
		case "YYYY-MM-DD": 
			if ( theMonth < 10 ) { theMonth = "0"+theMonth; }
			if ( theDay < 10 ) { theDay = "0"+theDay; }
			result = theYear+"-"+theMonth+"-"+theDay; 
			break; 		
		case "M/D/YYYY": 
			result = theYear+"-"+theMonth+"-"+theDay; 		
			break; 
          case "MMM DD, YYYY":
			if ( theDay < 10 ) { theDay = "0"+theDay; }
               result = medMonth[theMonth-1]+" "+theDay+", "+theYear;
               break; 

		default: 
			theYear = theYear -100; 
			if ( theYear < 10 ) { theYear = "0"+theYear; }
			result = theMonth+"/"+theDay+"/"+theYear; 
			break; 
	}
	return result; 

} 

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

function toDecimal( argTarget, argPlaces) {
     //this function uses Math to round to the given # of places
     var num = argTarget.value * 1;
     argTarget.value = num.toFixed(argPlaces); 


}

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

function trim(stringToTrim) {
     return stringToTrim.replace(/^\s+|\s+$/g,"");
}


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

function stopRKey(evt) {
     // this will prevenet the enter key from submitting forms

     var evt  = (evt) ? evt : ((event) ? event : null);
     var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
     if ((evt.keyCode == 13) && (node.type=="text")) { return false; }
}


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

function changeEnterToTab( event ){
     //suppressing the enter key in the textbox
     if(event.keyCode==13){
          return false; 
     }    
}

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

function getElementsByAttribute ( attrib, value, context_node, tag ) {
     // this function returns a list of all of the elements with in the context node of a particular tag kind  that have a 
     // specific Attribute with  specific value
     // for a document wide search: 
     //   context_node = document ( the document node)
     //   tag = '*' ( will search all tags or pass in a tag name to narrow te search) 

     var nodes = [];

     if ( context_node == null ){ 
          context_node = this;
     }

     if ( tag == null ) { 
          tag = '*';
     }

     var elems = context_node.getElementsByTagName(tag);
     for ( var i = 0; i < elems.length; i += 1 ) {
          if ( value ) {
               if ( elems[i].hasAttribute(attrib) && elems[i].getAttribute(attrib) == value ){ 
                    nodes.push(elems[i]);
               }
          } else {
               if ( elems[i].hasAttribute(attrib) ){ 
                    nodes.push(elems[i]);
               }

          }
     }
     return nodes;
}

function loadEditor() {


     tinyMCE.init({
             mode : "textareas",
             theme : "advanced",
             plugins : "emotions,spellchecker,advhr,insertdatetime,preview", 
             width : "600px", 
             height : "400px",
                     
             // Theme options - button# indicated the row# only
             theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect",
             theme_advanced_buttons2 : "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,|,code,|,forecolor,backcolor",
             theme_advanced_buttons3 : "insertdate,inserttime,|,spellchecker,advhr,,removeformat,|,sub,sup,|,charmap",      
             theme_advanced_toolbar_location : "top",
             theme_advanced_toolbar_align : "left",
             theme_advanced_statusbar_location : "bottom",
             theme_advanced_resizing : true
     });

}



