var	bIsMSIE = (navigator.appName == "Microsoft Internet Explorer");

// var docroot = "/morgankeller/planroom/";
var docroot = "/planroom/";

/******************************************************************************
SetUserMsg (msg)
	Helper to set a message to the user.
******************************************************************************/

function SetUserMsg (msg)
{
	var UserMsg = document.getElementById ("UserMsg");
	SetElementText (UserMsg, msg);
}

/******************************************************************************
TrimR (szStr)
	Helper to trim blanks, etc. off the end of a string.
******************************************************************************/

function TrimR (szStr)
{
	while (szStr.length > 0 && szStr.charAt (szStr.length - 1) <= ' ')
		szStr = szStr.substring (0, szStr.length - 1);

	return szStr;
}

/******************************************************************************
TrimL (szStr)
	Helper to trim blanks, etc. off the front of a string.
******************************************************************************/

function TrimL (szStr)
{
	while (szStr.length > 0 && szStr.charAt (0) <= ' ')
		szStr = szStr.substring (1);

	return szStr;
}

/******************************************************************************
Trim (szStr)
	Helper to trim blanks, etc. off the front and end of a string.
******************************************************************************/

function Trim (szStr)
{
	return TrimL (TrimR (szStr));
}

/******************************************************************************
SetSelID (List, ID)
	Helper to set selected entry in a list.
******************************************************************************/

function SetSelID (List, ID)
{
	if (typeof (List) == "string")
		List = document.getElementById (List);

	var	nSelect = -1;

	for (var i = 0; nSelect < 0 && i < List.length; i++) {
		if (List.options [i].value == ID)
			nSelect = i;
	}

	List.selectedIndex = nSelect;

	if (nSelect >= 0 && nSelect < List.length)
		List.options [nSelect].selected = true;
}

/******************************************************************************
SetChecked (box, val)
	Helper to set (un)checked for a checkbox
******************************************************************************/

function SetChecked (box, val)
{
	var checkBox = document.forms['form1'].elements[box];
	if (val == 1)
		checkBox.checked = true;
	else
		checkBox.checked = false;
}

/******************************************************************************
addmsg (str, msg)
	Helper to append a message on a new line
******************************************************************************/

function addmsg (str, msg)
{
	if (str)
		str += "<br/>";

	str += msg;

	return str;
}

/******************************************************************************
ClearChildren (parent)
	Helper to delete all children of a node.
******************************************************************************/

function ClearChildren (parent)
{
	if (typeof (parent) == "string")
		parent = document.getElementById (parent);

	while (parent.firstChild)
		parent.removeChild (parent.firstChild);
}

/******************************************************************************
SendToDB (uri, xml, RespFunction, context, urisrcdir)
	Send or queue data to the database.
******************************************************************************/

	// Create a queue of updates waiting to be sent.

	var	bClientBusy = false;
	var	LastSentRespFunction = null;
	var	LastContext = null;
	var	SendQueue = new Array ();
	var srcdir = "";

function SendToDB (uri, xml, RespFunction, context, urisrcdir)
{
	if (!urisrcdir && srcdir)
		urisrcdir = srcdir;

	if (urisrcdir)
		uri = urisrcdir + uri;

	if (!xml)
		xml = '<a></a>';

	if (!bClientBusy)
		DoSendToDB (uri, xml, RespFunction, context);
	else {
		SendQueue.unshift ([uri, xml, RespFunction, context]);
		try {
			ShowAjaxQueueLength (SendQueue.length);
		} catch (ex) {
		}
	}
}

/******************************************************************************
DoSendToDB (uri, xml, RespFunction, context)
	Send data to the database.
******************************************************************************/

function DoSendToDB (uri, xml, RespFunction, context)
{
	bClientBusy =  true;
	client = new HttpClient ();
	client.isAsync = true;
	client.requestType = 'POST';
	client.callback = DBResponseRcvd;
	LastSentRespFunction = RespFunction;
	LastContext = context;
	client.makeRequest (uri, xml, 'text/xml');
}

/******************************************************************************
DBResponseRcvd (responseText)
	A response was received from the database.
******************************************************************************/

function DBResponseRcvd (responseText)
{
	// SetUserMsg ("Rcvd: '" + responseText + "'");

	// See if a reload has occurred. e.g., error.php

	try {

		var	xml = client.xmlhttp.responseXML;
		var	ReloadLocation = getxmltext (xml, 'reload');

		if (ReloadLocation)
			window.location = ReloadLocation;

	} catch (ex) {
	}

	if (LastSentRespFunction) {

		if (LastContext)
			LastSentRespFunction.call (LastContext, responseText);
		else
			LastSentRespFunction (responseText);

		LastSentRespFunction = null;
		LastContext = null;
	}

	if (SendQueue.length > 0) {
		var	queueinfo = SendQueue.pop ();
		try {
			ShowAjaxQueueLength (SendQueue.length);
		} catch (ex) {
		}
		DoSendToDB (queueinfo [0], queueinfo [1], queueinfo [2], queueinfo [3]);
	} else
		bClientBusy =  false;
}

/******************************************************************************
GetElementText (e)
	Helper to return text.
******************************************************************************/

function GetElementText (e)
{
	if (typeof (e) == "string")
		e = document.getElementById (e);

	var	szText = "";

	if (e.firstChild) {
		szText = e.firstChild.data;
	}

	return szText;
}

/******************************************************************************
GetElementTextLast (e)
	Helper to return text.
******************************************************************************/

function GetElementTextLast (e)
{
	if (typeof (e) == "string")
		e = document.getElementById (e);

	var	szText = "";

	if (e.lastChild) {
		szText = e.lastChild.data;
	}

	return szText;
}

/******************************************************************************
SetElementText (e, text)
	Helper to set text.
******************************************************************************/

function SetElementText (e, text)
{
	if (typeof (e) == "string")
		e = document.getElementById (e);

	e.innerHTML = "";
	
	var	textel;

	for (textel = e.firstChild; textel && textel.nodeType != 3; // 3 = Node.TEXT_NODE
			textel = textel.nextSibling);

	if (textel) {
		textel.data = text;
	} else {
		t = document.createTextNode (text);
		e.appendChild (t);
	}
}

/******************************************************************************
GetInputText (e)
	Helper to return text from an input element.
******************************************************************************/

function GetInputText (e)
{
	var	szText = "";

	if (typeof (e) == "string")
		e = document.getElementById (e);

	szText = e.value;

	return szText;
}

/******************************************************************************
SetInputText (e, text)
	Helper to set the text value of an input field.
******************************************************************************/

function SetInputText (e, text)
{
	if (typeof (e) == "string")
		e = document.getElementById (e);

	e.value = text;
}

/******************************************************************************
IsElementDisplayed (e)
	Helper to return true if the element is displayed.
******************************************************************************/

function IsElementDisplayed (e)
{
	var	bDisplayed = false;

	if (typeof (e) == "string")
		e = document.getElementById (e);

	if (e)
		bDisplayed = (e.style.display != "none");

	return bDisplayed;
}

/******************************************************************************
SetElementDisplayed (e, bDisplayed, ShowHow)
	Helper to set the display state of an element.
******************************************************************************/

function SetElementDisplayed (e, bDisplayed, ShowHow)
{
	if (typeof (e) == "string")
		e = document.getElementById (e);

	if (!ShowHow)
		ShowHow = "";

	if (e)
		e.style.display = bDisplayed ? ShowHow : "none";
}

/******************************************************************************
getxmlint (tree, tagName)
	Helper to return the value of an integer entry in XML.
******************************************************************************/

function getxmlint (tree, tagName)
{
	var	szText = getxmlitem (tree, tagName);
	var	nValue = parseInt (szText);
	return !isNaN (nValue) ? nValue : null;
}

/******************************************************************************
getxmlbool (tree, tagName)
	Helper to return the value of a bool entry in XML.
******************************************************************************/

function getxmlbool (tree, tagName)
{
	var	szText = getxmlitem (tree, tagName);
	var	nValue = parseInt (szText);
	return !isNaN (nValue) ? (nValue != 0) : false;
}

/******************************************************************************
getxmlitem (tree, tagName)
	Helper to return the value of an entry in XML.
******************************************************************************/

function getxmlitem (tree, tagName)
{
	var	szItem = "";

	try {
		var	n = tree.getElementsByTagName (tagName)[0];
		szItem = n.hasChildNodes () ? n.firstChild.nodeValue : "";
	} catch (e) {
//		SetUserMsg ("XML can't find " + tagName);
		return null;
	}

	return DoDecode (szItem);
}

/******************************************************************************
getxmltext (tree, tagName)
	Helper to return the value of a text entry in XML.
******************************************************************************/

function getxmltext (tree, tagName)
{
	var	szText = getxmlitemex (tree, tagName);
	return szText ? DoDecode (szText) : "";
}

/******************************************************************************
getxmlitemex (tree, tagName)
	Helper to return the value of a possibly extended item in XML.
******************************************************************************/

function getxmlitemex (tree, tagName)
{
	var	szItem = "";

	try {
		var	n = tree.getElementsByTagName (tagName)[0];
		szItem = getNodeText (n);
	} catch (e) {
//		SetUserMsg ("XML can't find " + tagName);
		return null;
	}

	return DoDecode (szItem);
}

/******************************************************************************
gettagitems (xml, tagName)
	Helper to return the value(s) of an entry in an XML string.
	Returns a single string if only one match is found.
	Returns an array of matches or an empty string.
******************************************************************************/

function gettagitems (xml, tagName)
{
	var	pat = "<" + tagName + ">" + "(.*)" + "<\/" + tagName + ">";
	var	reg = new RegExp (pat, "g");
	var	result = reg.exec (xml);

	return result ? (result.length == 2 ? result [1] : result.slice (1)) : "";
}

/******************************************************************************
mkxmlitem (value, tagName)
	Helper to return an XML string for a value.
******************************************************************************/

function mkxmlitem (value, tagName)
{
	return "<" + tagName + ">" + value + "</" + tagName + ">";
}

/******************************************************************************
mkxmltext (text, tagName)
	Helper to return an XML string for a text value.
******************************************************************************/
function mkxmltext (text, tagName)
{
	return mkxmlitem (DoEncode (text), tagName);
}

/******************************************************************************
mkxmlTimeStamp ()
	Helper to return an XML string for the current time.
******************************************************************************/

function mkxmlTimeStamp ()
{
	var	time = new Date ();
	return mkxmlitem (time.getTime (), 'time');
}

/******************************************************************************
getNodeText (n)
	Helper to return the text from a tree.
******************************************************************************/

function getNodeText (n)
{
	var	szText = "";

	switch (n.nodeType) {
	case 1:					// Node.ELEMENT_NODE:
		for (var cn = n.firstChild; cn; cn = cn.nextSibling)
			szText += getNodeText (cn);

		break;
	case 3:					// Node.TEXT_NODE:
		szText = n.nodeValue;
		break;
	}

	return szText;
}

/******************************************************************************
DoEncode (v)
	Encode a value for transmission and storage.
******************************************************************************/

function DoEncode (v)
{
	var	szRes;

	try {
		szRes = encodeURIComponent (v);
	} catch (e) {
		szRes = escape (v);
	}

	return szRes;
}

/******************************************************************************
DoDecode (v)
	Decode a value received.
******************************************************************************/

function DoDecode (v)
{
	var	szRes;

	try {
		szRes = decodeURIComponent (v);
	} catch (e) {
		szRes = unescape (v);
	}

	return szRes;
}

/******************************************************************************
GetSelID (List)
	Helper to return the value of the selected entry in a list.
******************************************************************************/

function GetSelID (List)
{
	if (typeof (List) == "string")
		List = document.getElementById (List);

	var ID = -1;

	if (List.length > 0 && List.selectedIndex >= 0)
		ID = List.options [List.selectedIndex].value;

	return ID;
}

/******************************************************************************
******************************************************************************/

function handleClass(action, element, class1, class2)
{
	switch (action)
	{
		case 'swap':
			element.className =! handleClass('check', element, class1) ? element.className.replace(class2, class1): element.className.replace(class1, class2);
			break;
		case 'add':
			if (!handleClass('check',element,class1))
				element.className += element.className ? ' ' + class1 : class1;
			break;
		case 'remove':
			var rep = element.className.match(' ' + class1) ? ' ' + class1 : class1;
			element.className = element.className.replace(rep, '');
			break;
		case 'check':
			return new RegExp('\\b' + class1 + '\\b').test(element.className)
			break;
	}
}


function insertAfter (newElement, targetElement)
{
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement)
		parent.appendChild(newElement);
	else
		parent.insertBefore(newElement, targetElement.nextSibling);
}


function getURLParam(strParamName)
{
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 )
	{
		var strQueryString = strHref.substr(strHref.indexOf("?"));
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
		{
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 )
			{
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
}

function getElementsByClassName(oElm, strTagName, strClassName)
{
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++)
	{
		oElement = arrElements[i];      
		if(oRegExp.test(oElement.className))
			arrReturnElements.push(oElement);  
	}
	return (arrReturnElements);
}

/******************************************************************************
gotoPage - Go to passed HTML page
******************************************************************************/

function gotoPage (loc)
{
	document.location.href = docroot + loc + '.html';
}

/******************************************************************************
isset - from http://phpjs.org/
******************************************************************************/

function isset()
{
    var a=arguments; var l=a.length; var i=0;
    
    if (l==0) { 
        throw new Error('Empty isset'); 
    }
    
    while (i!=l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}