//VARIOUS JAVASCRIPT FUNCTIONS
//AUTHOR: RAMON VAZQUEZ
//TO BE DOCUMENTED IN THE FUTURE

function selectOption(selObj, optVal){
	for (var i=0; i<selObj.options.length; i++){
		if (selObj.options[i].value == optVal){
			selObj.options[i].selected = true;
			break;
		}
	}
}


function validEmail(str) {
//Function downloaded from http://www.webreference.com/js/tips/000310.html
  var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
  if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid
    return true;
  }
  return false;
}

function validUrl(str) {
  var reg1 = /(http:\/\/[0-9A-Za-z._:#&?=%\/~-]+)/; // valid
  var reg2 = /(https:\/\/[0-9A-Za-z._:#&?=%\/~-]+)/; // valid
  if (reg1.test(str) || reg2.test(str)) { // if syntax is valid
    return true;
  }
  return false;
}


//Counts how many items are checked in a radio or checkbox
function countChecked(field){
	count = 0;
	for (var i=0; i<field.length; i++){
		if (field[i].checked) count++;
	}
	return count;
}

//Counts how many items are selected in multiple-select field
function countSelected(field){
	count = 0;
	for (var i=0; i<field.length; i++){
		if (field[i].selected) count++;
	}
	return count;
}


function validateForm(theFormObj, requiredFields){
	errMsg = "";
	focusField = "";

	for(var i=0; i<requiredFields.length; i++){
		validateField(requiredFields[i]);
	}

	 if(errMsg == ""){
	 	//Everything OK submit form
	 	return true;
	 } else {
	 	errMsg = "We found some errors while processing your information:\n\n" + errMsg;
	 	errMsg += "\nPlease verify this to continue with your submission.";
	 	alert(errMsg);
	 	//alert(theFormObj.elements[focusField].focus);

	 	if(focusField != ""){
	 		try{
	 			eval("theFormObj." + focusField + ".focus();");
	 	    } catch(e) {
	 	    }
	 	}
		return false;
	 }
	return false;
  

}

function validateField(field){
//Validate a field according to its type
///// FOR RADIO BUTTONS, NOTHING DEFINED YET... IF NEEDED, TRY TO MAKE AN OPTION CHECKED BY DEFAULT, THIS ENSURES
///// THAT AT LEAST ONE VALUE IS SELECTED WHEN SUBMITTING THE FORM

	for(i=0; i<field.fInvalidConds.length; i++){
		////// TEXT FIELDS
		if (field.fType == "text" || field.fType == "hiddentext"){
			invalidVal = eval("field.fObj.value" + field.fInvalidConds[i]); //return true if the field has an invalid value
		}

		/////// SELECT FIELDS
		if (field.fType == "select"){
			invalidVal = eval("field.fObj.options[field.fObj.selectedIndex].value" + field.fInvalidConds[i]); //return true if the field has an invalid value
		}

		/////// OTHER FIELDS
		if (field.fType == "other"){
			invalidVal = eval(field.fInvalidConds[i]); //return true if the field has an invalid value
		}

		/////// EMAIL FIELDS 
		if (field.fType == "email"){
			invalidVal = eval("!validEmail(field.fObj.value)"); //return true if the field has an invalid value
		}

		/////// URLS FIELDS 
		if (field.fType == "url"){
			invalidVal = eval("!validUrl(field.fObj.value)"); //return true if the field has an invalid value
		}

		
		/// ADD ERROR MESSAGE AND SELECT A FIELD TO SET THE FOCUS
		if (invalidVal){
			errMsg += "- " + field.fErrMsgs[i] + "\n";

			//Focus for radio and checkboxes
			if (field.fObj.length > 1 && field.fType == "other"){
				focusField = (focusField == "") ? field.fObj[0].name + "[0]" : focusField;
			}
			focusField = (focusField == "" && field.fType!="hiddentext") ? field.fObj.name : focusField;
			return;
		}

	}	
}

//This is a definition of an object to contain required fields.. used for form validation
function ReqField(fObj, fType, fErrMsgs, fInvalidConds){
	this.fObj = fObj;
	this.fType = fType;
	this.fErrMsgs = fErrMsgs; //An array of error messages to each invalid condition
	this.fInvalidConds = fInvalidConds; //An array of invalid conditions for the field
}



//This is a definition of an object to contain files submitted for a resource.. used in Resource database
function SubmitFile(sysFilename, origFilename, fileTitle){
	this.sysFilename = sysFilename;
	this.origFilename = origFilename;
	this.fileTitle = fileTitle;
}

function getRadioAndCheckValues(theField){
	strValue = "";
	for(var i=0; i<theField.length; i++){
		if (theField[i].checked){
			strValue += (strValue == "") ? "" : ",";
			strValue += theField[i].value;
		}
	}
	return strValue;
}

/*
Change Cell Backgrounds -
© Shivaji Basu (www.shivbasu.com)
To add more shock to your site, visit www.DHTML Shock.com
Modified by Ramon Vazquez to preserve background color (useful for reports with mixed colors backgrounds)
*/

var currBg;
function cOn(td){
 if(document.getElementById||(document.all && !(document.getElementById))){
  currBg= td.style.backgroundColor;
  td.style.backgroundColor="#FFE89F";
 }
}

function cOut(td){
if(document.getElementById||(document.all && !(document.getElementById))){
  td.style.backgroundColor=currBg;
 }
}

function cOnRV(td, newColor){
 if(document.getElementById||(document.all && !(document.getElementById))){
  currBg= td.style.backgroundColor;
  td.style.backgroundColor=newColor;
 }
}


/*  END OF SHIVAJUS CODE */


function showPageJS(page){
	theForm = document.forms["showPage"];
	if (theForm == null){
		alert(">>> Form does not exist");
	} else {
		theForm.page.value = page;
		theForm.target="_self";
		theForm.submit();
	}

	
}
function showPage2(page){
	theForm = document.forms["showPage"];
	thewindow = window.open("", "open", "width=720,height=600,scrollbars=1,location=0,toolbar=0,status=0,resizable=1");
	if (theForm == null){
		alert(">>> Form does not exist");
	} else {
		theForm.page.value = page;
		theForm.target="open";
		theForm.submit();
	}

	
}
function showPrintPage(url){
	thewindow = window.open(url, "open", "width=720,height=600,scrollbars=1,location=0,toolbar=1,status=0,resizable=1");
	
}
function showHelpPage(url){
	thewindow = window.open(url, "open", "width=500,height=300,scrollbars=1,location=0,toolbar=0,status=0,resizable=1");
	
}

/**
  * Applies styleName to the trelem (TR) object and all the TD objects
  * that are part of trelem
  */
function ApplyStyleTRAndAllTD(trelem, styleName){
    trelem.style.background = styleName;
    var allChildren = trelem.childNodes;
    for (i=0; i < allChildren.length; i++){
	if ("TDTH".indexOf(allChildren[i].tagName) > -1)
	    allChildren[i].style.background = styleName;
    }
}


/*** Gets the target object from an event ***/
function sGetTarget(event){
    if (typeof event == "undefined") 
		return window.event.srcElement;    //IE
    else
		return event.target;	    	   //Mozilla et al
}


function sGetFormFieldObj(theForm, objName, idx){
    if (sIsInArray(theForm, objName))
	return theForm.elements[objName][idx];
    else
	return theForm.elements[objName];

}
function sIsInArray(theForm, objName){
    return (typeof theForm.elements[objName][0] != 'undefined');
}


/*******************
THE NEXT SET OF FUNCTION WERE DOWNLOADED FROM:
http://www.apriori-it.co.uk/Trim.asp
And modified by RV to consider whitespace and &nbsp;
******************/
function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
} //End Function

function RTrim(VALUE){
	VALUE = VALUE.replace(/\s| /g, " ");
	var w_space = String.fromCharCode(32);
	var w_spaceArr = new Array(w_space, "&nbsp;");
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
		return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1){
		for (var i=0; i<w_spaceArr.length; i++){
			w_space = w_spaceArr[i];
			if(VALUE.charAt(iTemp) == w_space){
			}
			else{
				strTemp = VALUE.substring(0,iTemp +1);
				break;
			}
		}
		iTemp = iTemp-1;
	} //End While
	return strTemp;

} //End Function

function LTrim(VALUE){
	VALUE = VALUE.replace(/\s| /g, " ");
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 1){
		return "";
	}

	var iTemp = 0;
	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
		}else{
			VALUE = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	
	return VALUE;
} //End Function
/********************	END OF TRIM FUNCTIONS **********************/


//****************   JS COOKIE FUNCTIONS ******************************************************/
/********** DOWNLOADED FROM: http://webreference.com/js/tips/000217.html  *********************/

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}
//****************   END js COOKIE FUNCTIONS ************************/


/*******  MISC ALERT FOR ALL APPS THAT USE THIS LIBRARY *****/
//alert("Server is being updated. Some services won't work.");