
function select_choices(nm, val)
{
	// This function translates the values from the select box stored in the database back into
	// the number that corresponds to the array position for it.		
	var retVal = parseInt(val);
	if (retVal == -1) retVal = 0;  // Generally, this is all that is usually needed.
	
/*	if (nm=="dept_cat"  || nm=="dept_cat1" || nm=="dept_cat2" || nm=="dept_cat3" ) 
	{
		for (j=0; j < deptcat.length; j++) 
		{ 
			var deptcatno = parseInt(deptcat[j]);
			if (val==deptcatno) retVal=j;
		}
	}
	if (nm=="directory_ram") { if (retVal==9) retVal=0; }
*/
	return retVal;
}

function LoadThis()
{	
	if (pull_data=="Yes")
	{				
		for( var i=0; i < document.frm.length; i++ )           // Provided that name of form is 'frm'.
		{                                                                                  
			var e = document.frm.elements[i];
			if ( e.type!="submit" && e.type!="reset" && e.type!="button"  )
			{
				// Loop through the database fields / values.
				for ( j=0; j < db_values.length; j++ )
				{
					fn = db_names[j];
					fval = db_values[j];										
			 		if (fn==e.name) 
					{ 
						if (e.type!="select-one") 
						{
							if (e.type!="radio")
							{
								if (fval=='-999' || fval=='null') fval='-999';
								e.value = fval;
							}
							if (e.type=="radio")
							{
								if (fval!='-999')
								{
									fval2 = parseInt(fval) - 1;    // To get back into correct array position.
								}
								if (fval!='null')    // If DB is empty, do not do code below.
								{
									eval("document.frm."+fn+"['" + fval2 + "'].checked=true;");
								}
							}
						}
						if (e.type=="select-one")
						{	
							if ( (fval=='-999' || fval=='null') ) fval='0';						
							eval("document.frm."+fn+".selectedIndex='"+ select_choices(fn,fval)+"'");
							
							//if ( flag==true ){ 
							//  eval("document.frm."+fn+".selectedIndex='"+ 0 +"'"); }
						}
					}						
				}
			}
		}
	}
}

// **************************************************************************************************//

function IsBlank(s)
{
    // A utility function that returns true if a string contains only whitespace characters.
	for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

function CharOnly(text) {            // A regular expression to check for non-numeric entries.
	var myRegExp = /[^a-z]/i;        // Check for entries that are NOT a-z nor A-Z.
	return !(myRegExp.test(text));
}

function AlphaNum(text) {            // A regular expression to check for alpha-numeric entries.
	var myRegExp = /[^a-z\d]/i;      // Check for entries that are NOT a-z, A-Z nor numeric.
	return !(myRegExp.test(text));
}

function AlphaNumSp(text) {            // A regular expression to check for alpha-numeric entries.
	var myRegExp = /[^a-z\d ]/i;       // Check for entries that are NOT a-z, A-Z, numeric, nor a space.
	return !(myRegExp.test(text));
}

function IsFloat(text) {               // A regular expression to check for floating point entries.
	var myRegExp = /[^.\d]/;           // Check for entries that are NOT numeric.
	return !(myRegExp.test(text));
}

function fix (fixNumber, decimalPlaces) {
	// Function to get number with fixed decimal places.
	var div = Math.pow (10, decimalPlaces);
	fixNumber =  Math.round(fixNumber * div) / div;  // Math.round...
	return fixNumber;
}

// Calculate percent of a / b, and set result to another field value.
function Calc_Pct (a, b, result)  {                                      // Note: Pass objects to this.
	    result.value =  Math.round((parseFloat(a.value)/parseFloat(b.value))*100 *100000) / 100000;
		return true;
}


function CheckDate(THISDATE) {
	// This function makes sure the date is in mm/dd/yyyy format.
	// Taken from the Ethos JavaScript code.
	var err=0;
	var returnVal = true;
	a=THISDATE.value;
	if (a.length > 0) 
	{
        if (a.length != 10) err=1
	        mon = a.substring(0, 2)       // month
	        c   = a.substring(2, 3)       // '/'
	        day = a.substring(3, 5)       // day
	        e   = a.substring(5, 6)       // '/'
	        yr  = a.substring(6, 10)      // year
	        if (mon<1 || mon>12) err = 1
	        if (day<1 || day>31) err = 1
	        if (yr<1900 || yr>3000) err = 1
	        if (mon==4 || mon==6 || mon==9 || mon==11)
			{
	        	if (day==31) err=1
	        }
	        if (mon==2)
			{
	            var g=parseInt(yr/4)
	            if (isNaN(g)) 
				{
	            	err=1
	            }
	            if (day>29) err=1
	            if (day==29 && ((yr/4)!=parseInt(yr/4))) err=1
	        }
	        if (err==1) 
			{
				returnVal=false;
	        	// alert(THISDATE.value + 
				//	" is not a valid date. Please re-enter in this format MM/DD/YYYY.");
	        	// THISDATE.value = ""
	        }
	} 
	else 
	{
		returnVal=false;
		// THISDATE.value = ""
	}
	return returnVal;		
}


function getDateToday() {
	var month = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
	// var month = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var nowDate = new Date();
	var dayNow = nowDate.getDate();
	var day = dayNow;
	if (dayNow > 0 && dayNow < 10) day="0" + dayNow;
	var date_str = new String (month[nowDate.getMonth()]+ "/" + day + "/" + nowDate.getFullYear());
	return date_str;
}

function getStrTime(flag)   {
	var nowDate = new Date();
	var nowHour = nowDate.getHours();
    var nowMinute = nowDate.getMinutes();
	var post_txt = "";
	var nowHour_new = 0;   
	if (nowMinute < 10) nowMinute = "0" + nowMinute;
	if (nowHour < 10)   nowHour = "0" + nowHour;
	if (nowHour <= 12) { 
		nowHour_new=nowHour;
		post_txt = "a.m.";	}
	else
		{nowHour_new = nowHour - 12;
		post_txt = "p.m."; 	
		} 
	if (nowHour==12) post_txt = "p.m.";
	var str_time = new String (nowHour_new+":"+nowMinute+" "+post_txt );
	var str_time_m = new String (nowHour + ":" + nowMinute);            // Military time for form field.
	if (flag==1) return str_time;
	if (flag==2) return str_time_m;
//	document.write(nowHour + ":" + nowMinute + " " + post_txt);
}



// ************************************************************************************************//

// THE CODE BELOW IS NOT USED ---

//var datevars = new Array("DATEADM","DOB","DATEINJ");        // Global array of date vars.
//var floatvars = new Array("AGE");                           // Global array of float vars.
//var req = new Array("ID","DATEADM","GENDER");               // Global array of required fields.


function Submit_Form_Stuffffffff(f) {                    // THIS FUNCTION NOT USED YET
	// var f = document.frm;                       // Not needed now.
	var returnVal=true;
	var msg;
	var empty_fields = "";
	var errors = "";
	var tot_err = 0;                               // total no. of incorrect fields.
	
	// Loop through all elements on the form.
	for (var i=0; i < f.length; i++) 
{
		var max = eval(f.length - 1);
		var e = f.elements[i];		
		var e_val = new String(e.value);
		if (e.name=="ID")
		{ 
			e.value = new String(e.value).toUpperCase(); 
		}
		if ( e.name=="DATEDX" ) 
		{
/*			var dt_today = new Date(f.DATETODAY.value);
			if ( CheckDate(e)==true )                         // Check if DATEDX is a date.
			{
				var dt_dx = new Date(e.value);
				var daysDiff = (dt_today.valueOf() - dt_dx.valueOf());				
				daysDiff = Math.floor((((daysDiff / 1000) / 60) / 60) / 24);
				f.DAYSDX_DIFF.value = daysDiff;
				if ( daysDiff < 0 )
				{
					errors += "\n          Date of Dx (DATEDX) is an incorrectly entered date.";
				}
			}
*/
		}		
		var date_yn = false;                       // datevar yes/no.
		var float_yn = false;                      // floating-point var yes/no.
		var req_yn = false;                        // required field yes/no.
		
		for (j=0; j < datevars.length; j++) { if (e.name==datevars[j])  date_yn=true; }
		for (j=0; j < floatvars.length; j++){ if (e.name==floatvars[j]) float_yn=true; }
		for (j=0; j < req.length; j++)      { if (e.name==req[j])       req_yn=true; }
	
	if (tot_err < 10)
	{
		if ( e.type=="text" || e.type=="textarea") // e.type=="hidden"    // Text Boxes - do not check hidden boxes (like DATETODAY).
		{
			// first check if the field is empty
            if ((e.value == null || e.value == "" || IsBlank(e.value)) && req_yn==true ) 
			{
               	empty_fields += "\n          " + e.name;
				tot_err++;
               	continue;
			}
			// check for errors in dates.
			if (date_yn==true && CheckDate(e)==false) {
					errors += "\n          " + e.name + " is an incorrectly entered date.";
					tot_err++;
					continue;
			}
			// check for errors in floating-point vars.
			if (float_yn==true && IsFloat(e.value)==false){
					errors += "\n          " + e.name + " is not a floating-point value.";
					tot_err++;
					continue;
			}
			// check for errors in other text vars.
/*
			if (date_yn==false && float_yn==false && AlphaNumSp(e.value)==false)
			{
					errors += "\n          " + e.name + " does not have valid text entry.";
					tot_err++;
					continue;
			}
*/
		}
		if ( e.type=="select-one")                                        // Select-one boxes.
		{
			if (e.value=="-1" && req_yn==true) {                          // Indicates empty select-one box.
				empty_fields += "\n          " + e.name;
				tot_err++;
               	continue;
			}
		}
	}
}                 // end of for.. loop.
		
  	if (empty_fields || errors) 
	{
		msg  = "______________________________________________________\n\n";
		msg += "The form was not submitted because of the following error(s).\n";
		msg += "Please correct these error(s) and re-submit.\n";
		msg += "______________________________________________________\n\n";
		
		if (empty_fields)
		{
      		msg += "- The following required field(s) are empty:" 
                		+ empty_fields + "\n";
		}
		
		if (errors)
		{
			msg += "\n";
			msg += "- The following required field(s) have errors:"
							+ errors + "\n";
		}
		alert(msg);
		returnVal=false;
    }
    return returnVal;
}

function LoadPageOne()  
{
	if (pull_data=="No")
	{
		document.frm.reset();
		var dt_today = getDateToday();                 // Get date of data entry into form field, date_today.
		document.frm.DATETODAY.value = dt_today;
		document.frm.DATEADM.value   = dt_today;
		document.frm.TIMETODAY.value = getStrTime(2);  // Time, military format.
	}
	LoadThis();
}

// ************************************************************************************************//






