
// CORE SUBROUTINES : A lightweight js library (subroutines.js subset) essential to <iframe> child pages


// ============================================================================================================

// D.N.B. Pedergnana * Kansas State University * dnp@ksu.edu * (785) 532-3125

// Created at the K-State Educational Communications Center

// ============================================================================================================

	// Global variables

var popWin;			// Handle for a resizable popup window (when opening another site, etc.)
var popup;			// Handle for pop-up documents
var videoPopup;


	// Global events

			// Create an event listener that renews the session cookie (if any)

if( window.addEventListener ) {
	window.addEventListener('keyup', top.renewSession, false);
	window.addEventListener('mouseup', top.renewSession, false);
	window.addEventListener('onscroll', top.renewSession, false);

} else if( document.addEventListener ) {
	document.addEventListener('keyup', top.renewSession, false);
	document.addEventListener('mouseup', top.renewSession, false);
	document.addEventListener('onscroll', top.renewSession, false);

} else if( window.attachEvent ) {
	window.attachEvent('onkeyup', top.renewSession);
	window.attachEvent('onclick', top.renewSession);
	window.attachEvent('onscroll', top.renewSession);

} else if( document.attachEvent ) {
	document.attachEvent('onkeyup', top.renewSession);
	document.attachEvent('onclick', top.renewSession);
	document.attachEvent('onscroll', top.renewSession);
}



	// Core Functions

function getThisID(name) {				//  Get a DOM object's ID tag for easy referencing

	if (document.getElementById) {				// Firefox and Safari
		return document.getElementById(name);
	} else if (document.all) {				// IE
		return document.all[name]; 
	} else if (document.layers) {
		return document.layers[name];
	} else {
		return document.getElementById(name);		// Default for unknown browsers
	}
}

function getObjectByID(id) {				// Get a DOM object's ID tag for easy referencing

	var obj = getThisID(id);
	
//	if (obj == null) {
//		obj = top.getThisID('sidebarFrame').contentWindow.getThisID(id);
//		
//		if (obj == null) {
//			obj = top.getThisID('mainFrame').contentWindow.getThisID(id);
//		
//			if (obj == null) {
//				obj = top.getObjectByID(id);
//			}
//		}
//	}
//	
//	if (obj == null) {
//		obj = '';
//	}
	
	return obj;
}

function parseURL(param, queryURL) {	// Parses a URL queryString into components and returns the requested parameter

									// queryURL: If specified, parses the given parameterList; otherwise parses location.href
	var result = null;
	var paremeterList;

	if (queryURL) {
		parameterList = queryURL.split("?");		// GET Parameters
	} else {
		parameterList = location.href.split("?");		// GET Parameters
	}

	if (parameterList.length > 1) {

				// Split list into name.value pairs

		var parameterPairs = parameterList[1].split("&");
		var nameAndValue = new Array();
		var paramValue;
		var paramKey;

		for (p=0; p < parameterPairs.length; p++) {	// Cycle through name/value pairs & store values

			nameAndValue = parameterPairs[p].split("=");
			paramKey = nameAndValue[0];
			paramValue = nameAndValue[1];

			if (paramKey == param) {		// Is this the target key?
				result = paramValue;
				break;
			}
		}
	}
	return result;
}

function parseURLdata(frameRef, param) {	// Reads a frame's URL and splits it into its components
						// scope: parent.bodyFrame, top, etc.

	var paramResult = null;

	if (frameRef) {
		var parameterList = frameRef.location.href.split("?");	// GET Parameters when frameRef is named
	} else {
		var parameterList = location.href.split("?");		// GET Parameters when frameRef isn't specified
	}
	var result = 0;

	if (parameterList.length == 1) {			// No parameters; set defaults for home page:

		result = 0;

	} else {						// Split list into name.value pairs

		var parameterPairs = parameterList[1].split("&");
		var nameAndValue = new Array();
		var paramValue = new Array();
		var paramKey = new Array();

		for (p=0; p < parameterPairs.length; p++) {	// Cycle through name/value pairs & store values

			nameAndValue = parameterPairs[p].split("=");
			paramKey[p] = nameAndValue[0];
			paramValue[p] = nameAndValue[1];

			if (paramKey[p] == param) {		// Is this the target key?
				paramResult = paramValue[p];
			}
		}
	}

	// Remove anchors from selected:

	if (paramValue) {

		var last = (paramValue.length) - 1;

		if (paramValue[last].search('#') > 0) {

			var segment = selected.split("#");
			paramValue[last] = segment[0];
		}
	}

	if (param) {
		return paramResult;
	} else {						// No target param specified; return a list of values
		return paramValue;
	}
}

function setValue () {				// Sets the value property of specified field(s)

	var thisID;
	var thisObj;
	var thisVal;
	var lastObj = (setValue.arguments.length);

	for(var n=0; n<lastObj; n++) {
		thisID = setValue.arguments[n]
		thisObj = getThisID(thisID);

		if(!thisObj) {
			alert("* setValue Error: " + thisID + " doesn't exist (Called by " + arguments.caller + ")" );
			++n;
		} else {
			thisVal = setValue.arguments[++n];
			thisObj.value = thisVal;
		}
	}
}

function getValue (id) {			// Returns the value property of the specified object

	var obj = getThisID(id);

	if(!obj) {
		alert("getValue Error: " + id + " doesn't exist (Called by " + arguments.caller + ")" );
		return '';
	} else {
		return obj.value;
	}
}

function focusOn(targetID, msDelay) {		// Gives focus to the named field or form object
											// msDelay is how long to pause before giving focus

	if (msDelay) {
		var cmd = "getObjectByID('" + targetID + "').focus();" ;
		setTimeout(cmd, msDelay);
	} else {
		getObjectByID(targetID).focus();
	}
}

function openDefault(page) {		// Opens a document in a default window that includes the location bar and is resizable

	if (popWin) {		// Close any open windows before opening another
		popWin.close;
	}

	popWin = window.open(page, 'fullWin', 'scrollbars=yes, status=yes, menubar=yes, toolbar=yes, location=yes, resizable=yes, width=999, height=680');
}

function showObject() {				// Show a dynamic form field or menu
										// Iterates through argument list if an array is input
										
	var lastObj = showObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		thisObj = getObjectByID(showObject.arguments[n]);
		thisObj.style.display = "";
	}
}



function hideObject() {					// Show a dynamic form field or menu
											// Iterates through argument list if an array is input
	var lastObj = hideObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		
		thisObj = getObjectByID(hideObject.arguments[n]);
		thisObj.style.display = "none";
	}
}


function isShown(id) {

	if ( getObjectByID(id).style.display == 'none') {
		return 0;
	} else {
		return 1;
	}
}


function joinValues(fields, radioForm) {		// Accepts a string of comma-separated field names as input (with spaces) and returns a string of values
												// Delimiter = |
												// radioForm: The name of a form in which radio button values exist (required to call getRadio)
	var fieldList = fields.split(", ");
	var lastItem = fieldList.length;
	var v = '';
	var valList = new Array();
	
	for (n=0; n<lastItem; n++) {
		
		if (fieldList[n].search(/Radio/i) > -1) {		// Radio button: use getRadio (* Note radio field IDs must include the word 'Radio' to be recognized as such)
								
			v = getRadio( radioForm, fieldList[n] );	
		} else {						
			v = getValue( fieldList[n] );			// Input field: use getValue
		}
		valList.push(v);
	}
	
	return valList.join("|");
}


function setText() {					// Sets the innerHTML of specified objects to desired text.

	var lastObj = (setText.arguments.length);
	for(n=0; n<lastObj; n++) {
		thisID = setText.arguments[n]
		thisObj = getObjectByID(thisID);

		if(!thisObj) {
			alert("Error: " + thisID + " doesn't exist");
			++n;
		} else {
			thisText = setText.arguments[++n];
			thisObj.innerHTML = thisText;
		}
	}
}


function escapeRegex(inputString) {			// Prevents invalid quantifier errors when searching for special characters in Regex
	
	return inputString.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}


function updateCheckbox(type, id, field, refreshMode) {						// Simple Ajax call to update the database when a checkbox is checked via updateForm

	setValue('updateType', type);
	setValue('updateID', id);

	var checkedVal;
	
	if ( getObjectByID(field).checked ) {								// Get the value of this box if checked
		checkedVal = getValue(field);
	} else {
		checkedVal = '';
	}

	setValue('updateV', checkedVal);
	sendReq('updateForm', refreshMode); 
}


function del(type, id) {			// Ajax call to delete an item. Only valid types will be deleted by users of admin or partner status

	setValue('deleteType', type);
	setValue('deleteID', id);
	sendReq('deleteForm', 'js');
}


	// Responses to Keypresses

function getRadio(formName, radioGroupName) {		// Returns the value of the currently selected radio item from a specified group.

	var radioObj = document.forms[formName].elements[radioGroupName];
	
	if (!radioObj) {
		return "";
	} else {
		
		var radioLength = radioObj.length;
		
		if (radioLength == undefined) {
			if (radioObj.checked) {
				return radioObj.value;
			} else {
				return "";
			}
		}
			
		for (var i = 0; i < radioLength; i++) {
			if (radioObj[i].checked) {
				return radioObj[i].value;
			}
		}
		return "";
	}
}

function tabOutAction(e, tabAction, escAction) {		// Accepts a keypress event, tabAction, & escAction as input.
														//	Triggers default actions when the user types either [TAB] ot [ESC] from this field
	
		// Capture the keypress value and define the Esc and Tab key codes


 	var keynum  = (window.event) ? event.keyCode : e.keyCode;

    var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;	 // Capture keypress event for either MSIE : Firefox
	var Tab = (window.event) ? 9 : e.DOM_VK_TAB;
	
	
	if ( tabAction && (keynum == Tab || keynum == 13 || keynum == 3) ) {
		eval(tabAction);
	}
	
	if ( escAction && keynum == Esc ) {	
		eval(escAction);
	}
}

function returnAction(e, returnAction, escAction) {		// Accepts a keypress event, tabAction, & escAction as input.
														//	Triggers default actions when the user types either [TAB] ot [ESC] from this field
	
		// Capture the keypress value and define the Esc and Tab key codes


 	var keynum  = (window.event) ? event.keyCode : e.keyCode;

    var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;	 // Capture keypress event for either MSIE : Firefox
	
	
	if ( returnAction && (keynum == 13 || keynum == 3) ) {
		eval(returnAction);
	}
	
	if ( escAction && keynum == Esc ) {	
		eval(escAction);
	}
}

function fetch(type, id, dialog, focusOn, target) {		// Performs an Ajax call using the fetchForm to retrieve data
													// fetchDialog: optional dialog to show after populating the form fields
													// fetchFocus:  optional field to place cursor in after populating
													// target:      if set, checks to see that this ID exists before trying to fetch

	if (getValue('fetchType')) {	// Possible request conflict (simultaneous fetch attempts): delay this request
	
		var cmd = "fetch('" + type + "', " + id + ", '" + dialog + "', '" + focusOn + "', '" + target + "');" ;
		setTimeout(cmd, 150);
		alert('conflict');
	}
	
	if (target) {			// Confirm that ID exists before attempting fetch

		if (!getObjectByID(target) ) {
			var cmd = "fetch('" + type + "', " + id + ", '" + dialog + "', '" + focusOn + "', '" + target + "');" ;
			setTimeout(cmd, 150);
			alert(target + 'not exist');
			return;
		}
	}
	
	setValue('fetchType', type);
	setValue('fetchID', id);
	setValue('fetchDialog', dialog);
	setValue('fetchFocus', focusOn);
	
	if (target) {
		sendReq('fetchForm', target);
	} else {
		sendReq('fetchForm', 'js');
	}
	
	setValue('fetchType', '');			// Clear the fetch buffer signalling that more requests can be made
}

function openVideo(file, w, h) {		// Opens a QuickTime video of specified dimensions in a separate pop-up window

	if ( file.match(/assets-/) ) {				// Adjust START.html path names
		file = file.replace(/assets-/, "");
		queryString = 'assets/videoPlayer.html?video=' + file + '&w=' + w + '&h=' + h;
	} else {
		queryString = 'videoPlayer.html?video=' + file + '&w=' + w + '&h=' + h;
	}

	if(videoPopup) {
		videoPopup.close();
	}

		// Offset video window dimensions

	
	w = w + 36;
	h = h + 103;

	videoPopup = window.open(queryString, 'videoWindow', 'height=' +h+ ', width=' +w+ ', scrollbars=no, resizeable=no');
}