//------------------------------------------------------------------------------
// util_func.js
//
//	This file consists of some general purpose JS code used througout the
//	site.
//
//	@author		Aman. Patel <aman.patel@stjude.org>
//	@co-author		Martin Norland <martin.norland@stjude.org>
//	
//------------------------------------------------------------------------------

// JS GLOBALs

// this is an array that contains all onLoad
var onload_functions = new Array();

// Standard Detection Variables (GLOBALS):
DOM = (document.getElementById) ? true : false;
NS4 = (document.layers) ? true : false;
IE = (document.all) ? true : false;
IE4 = IE && !DOM;
isIE = ((document.all) || (IE4 && navigator.appVersion.indexOf("5.")!=-1));

// State of form values stored in this global
var frm_state = new Array;


//
// Register an onload function to be called upon BODY.onLoad()
//
// Returns void.
// Accepts a Function Object (  i.e. func_obj = new Function("alert('this is the body of this function');");   )
//
// takes an optional parameter to determine 'when' it is onloaded, 0 going first and higher being later
// defaults to (0) if not specified
// TODO - prefer to have it default to 10 (so things that are specified have a chance to go before it)
// TODO - so use our condense_array function across the array in the onload

function registerOnLoadFunction( func_obj , onload_position) {
	// append the func_obj to onloads global array.
	if ( onload_position == null) { onload_position = 0; }
	if (onload_functions[onload_position] == null) { onload_functions[onload_position] = new Array(); }
	if ( func_obj != null ) {
		onload_functions[onload_position][onload_functions[onload_position].length] = func_obj;
	}

}


//
// Navigate to a url
//
// This function is used mostly in <input type="button">'s onClick events to
// transfer the user to a particular URL.
//
//	p_URL	The url where to transfer to.
//

function navigate( p_URL ) {
	window.parent.location.href=p_URL;
}

//
// Opens a popup window
//
// All parameters are optional.
//
//	p_Width		width of the popped window (default 560)
//	p_Height	height of the window (default 400)
//	p_Name		name of the window (can be used to later refer back to
//			the particular window.
//	p_MenuBar	yes/no, on whether to include the menu bar
//	p_ToolBar	yes/no, on whether to include the tool bar
//
function popup_window(p_Where, p_Width, p_Height, p_Name, p_MenuBar, p_ToolBar) {
	if (p_Width == '') {p_Width = 560}
	if (p_Height == '') {p_Height = 400}
	if (p_Name == '') {p_Name = 'fetch_pop'}
	if (p_MenuBar == '') {p_MenuBar = 'yes'}
	if (p_ToolBar == '') {p_ToolBar = 'no'}
	var win=open(p_Where, p_Name,
		'menubar='+p_MenuBar
		+',toolbar='+p_ToolBar
		+',width=' + p_Width
		+',height=' + p_Height
		+',resizable=1,'
		+'scrollbars=1');
	win.moveTo(0,0);
	win.focus();
	return win;
}

//
// Checks email address to see if it complies with the normal
// 	user@site.name
// format.
//
// returns true/false depending upon the validation result.
//
function email_validation(e) {
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(i=0; i < e.length ;i++)
		if(ok.indexOf(e.charAt(i))<0)	return (false);

	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two))	return (-1);		
	}
}


/**
 * This function taken from functions.js of phpMyAdmin codebase. (thank you!)
 *
 * Provided with a element id (the value of id="") it returns the corresponding
 * object.
 *
 * getElement
 *
 */
function getElement(e,f){
    if(document.layers){
        f=(f)?f:self;
        if(f.document.layers[e]) {
            return f.document.layers[e];
        }
        for(W=0;i<f.document.layers.length;W++) {
            return(getElement(e,fdocument.layers[W]));
        }
    }
    if(document.all) {
        return document.all[e];
    }
    return document.getElementById(e);
}

/**
* 
* This function looks for the element named userChanged[] and sets it to
* 'y'.
* 
// added by a.patel:
//	This function will now check for original value of this element at the
//	load time, if the values are same, it set the change mark to 'n', see
//	the white paper.
	//if ( changed_name == '' ) {		// be backwards compatible, not
	//					// all setcChanged will pass
	//					// this param 
	//	changed_object = MM_findObj ( changed_name )
	//	// did this object was changed back to the original value?
	//	if ( changed_object.value == frm_state[changed_name] ) { 
	//		// it did, so mark as not changed.
	//		obj.value = 'n';	
	//	}
	//}
*
*/

function setChanged(n)
{
	objname = 'userChanged[' + n + ']';
	obj = MM_findObj(objname);
	obj.value = 'y';
	return true;
}


/**
 * Store the state of all form values and names.
 *
 */

function storeState(frm) {
	frm = MM_findObj( frm );
	for( i=0; i< frm.elements.length; i++ ) {
		n = frm.elements[i].name;
		frm_state[n] = frm.elements[i].value;
	}
}

/**
 * Calls all registered on load functions for this page.
 *
 * This function is not a user function. It is called by every
 * page's onLoad event.
 *
 * Returns nothing.
 * Accepts nothing.
 *
 */

function check_for_onload_function() {
	if (window.onloadfunc != undefined) {
		onloadfunc();
	}

	if (onload_functions != undefined) {
	//onload_functions = g_condense_array(onload_functions);
		for (var i =0; i < onload_functions.length; i++ ) {
			//alert("now i'm doing " + i + " with length " + onload_functions[i].length);
			if (onload_functions[i] != undefined) {
				for (var j = 0; j < onload_functions[i].length; j++ ) {
					//alert(i + " " + j + " " + onload_functions[i][j])
					onload_functions[i][j]();
				}
			}
		}
	}
}

function g_set_form_elements(form_obj, begins_with, value) {
	for ( var i=0; i <= form_obj.elements.length; i++ ) {
		if ( form_obj.elements[i] ) {
			name_str = new String(form_obj.elements[i].name); // because x.name is not a String() object
			if ( name_str.substr(0,begins_with.length) == begins_with ) {

				if (form_obj.elements[i].options) {
					g_set_dropdown(form_obj.elements[i],'');
				} else {
					form_obj.elements[i].value = '';
				}
			}
		}
	}

}

/**
 * Set a dropdown to a specific value
 * [works with multi's but won't unset w/o extra params/code.]
 *
 */

function g_set_dropdown(dropdownid, newvalue) {
	//pieces.options[i].selected
	dropdownid.selectedIndex = 0;	// safe default
	for (var i=0; i<dropdownid.options.length; i++) {
		if (dropdownid.options[i].value == newvalue) {
			dropdownid.options[i].selected = true;
		}
	}
}

/**
 * Translate a value from a dropdown. (eg. you pass male_female_dropdown, 'm'
 * and 'Male' is returned)
 *
 */

function g_translate_dropdown(dropdownid, key) {
	// searches through a dropdown for key == dropdownid.value, and returns the displayed key
	for (var i=0; i<dropdownid.options.length; i++) {
		if (dropdownid.options[i].value == key) {
			//alert(dropdownid.options[i].value + " = " + key);
			return dropdownid.options[i].innerHTML;
		}
	}
	return key;
}

/**
 * Set an items value to the passed value [convenience function, allows us to apply other functions to the data
 * if we wish
 *
 */

function g_set_value (inputid, newvalue) {
	inputid.value = newvalue;
}


/**
 * Takes a sparse array (eg. Arr[0]="foo", Arr[50]="bar") and condenses it into Arr[0]/Arr[1] - this is needed
 * because javascript implicitly defines the values inbetween, and it doesn't condense when you try to delete them.
 *
 * returns the array condensed - so you must use this function as:
 *   myarray = condense_array( myarray) ;
 * (does not just blindly set the array assuming it's global)
 */

function g_condense_array( myarray ) {
	var dense_array = new Array();
	var skipped = 0;
	for (var i=0; i < myarray.length; i++) {
	// TODO: check against '== undefined' here
		if (myarray[i] == "") { skipped++; }
		else { dense_array[i-skipped] = myarray[i]; }
	}
	//myarray = dense_array;
	//return myarray;
	return dense_array;
}

/**
 * takes a value and a description of which quotes to htmlent and does just that, replaces them.
 * used when writing to innerHTML, input values - so all data will be stored.
 *   eg. 'this " would break' => <input type="hidden" value="this " would break">
 *
 * when pulling back out of database, values must be stripslashes'd (through tpl())
 */

	function g_htmlent_string( value, which ) {
		// double, single, both [none - nah!]
		switch(which) {
			case 'double':
				value = g_htmlent_double(value);
				break;
			case 'single':
				value = g_htmlent_single(value);
				break;
			default: // all
				// handle & and/or ; *FIRST* if you ever do them
				value = g_htmlent_double(value);
				value = g_htmlent_single(value);
				break;
		}
		return value;
	}

/**
 * child function of g_htmlent_string - handles single quotes
 */
	function g_htmlent_single(string) {
		var re = new RegExp ("'", 'gi') ;
		return (string.replace(re,"&#39;")); // (&apos;) &#39;    [&apos works but isn't standard]
	}

/**
 * child function of g_htmlent_string - handles double quotes
 */
	function g_htmlent_double(string) {
		var re = new RegExp ('"', 'gi') ;
		return (string.replace(re,'&quot;')); // &quot; &#34;
	}

// which = which item.
// status : 
//	hidden	- hide but still occupy space
//	none	- hide but do not occupy space
//	block	- show
function g_set_display( which, status ) {

	which.style.display = status

}

// which = which item.
// what = what's the class name
function g_class_add(which, what) {
	which.className = what + " " + which.className;
}

// which = which item.
// what = what's the class name
function g_class_strip(which, what) {
	regex = new RegExp("(.*)"+what+"(.*)","");
	which.className = which.className.replace(regex, "$1$2");
}

//
// replace all <options> of a select box (target)
//

function g_set_options(target, values, names, blank) {
	if (blank == null) { blank = 1; } // default true, have blanks
	//if (values.length == 1 && values[0] == "") { return;show_noclassification(); }

	var newnum = values.length;
	var oldnum = target.options.length-blank; // one less [if blank] to account for blank option
	if (blank == 1) { target.options[0] = new Option("","") }
	for (var i=0; i < newnum; i++) {
		//var newoption = new Option(names[i], values[i]);
		var newoption = new Option(names[i], values[i]);
		target.options[i+blank] = newoption; // add 1 [if blank] to 'hop' the blank option at the front
	}
	// clear out extraneous options (if exist)
	if (newnum < oldnum) {
		for (var i=newnum; i < oldnum; i++) {
			target.options[newnum] = null; // nulling deletes it entirely, thus moving the index down
		}
	}
}

function g_print_dialog() {
	if (typeof(window.print) != 'undefined') {
	    window.print();
	}
}

function y2k(number){

	return (number < 1000) ? number + 1900 : number;

}

function get_computer_time() {

	var now = new Date();
	var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var date = ((now.getDate()<10) ? '0' : '')+ now.getDate();
	mod = ' '
	mod +=  months[now.getMonth()] + ', '
	mod += date  +  ' ' + (y2k(now.getYear()))  + ' ; ';
	var hrs = now.getHours() + ''; if (hrs.length == 1) { hrs = '0' + hrs; }
	var min = now.getMinutes() + ''; if (min.length == 1) { min = '0' + min; }
	mod += hrs + ' : ' + min;

	return mod;
}


function maximize_window( ) {
	if (window.screen) {
		self.moveTo(0,0);
		self.resizeTo(screen.availWidth,screen.availHeight);
	}
}
