dojo.addOnLoad(init);

function init() {
	//if($("admin_opt") && !$("main")) $("main_content").style.padding = '0 10px';
	//else if($("admin_opt")) $("admin_opt").style.margin = '-20px 10px 10px 10px';
}

//shorthand DOM select

function $(val) {
	return dojo.byId(val);
}

//shorthand DIJIT select

function $$(val) {
	return dijit.byId(val);
}

//Trigger an event programatically, necessary if updating a DOM node w/js

function triggerEvent(targ,type) {
	var node = (typeof targ == "string") ? dojo.byId(targ) : targ;
	var ie_evt = (!type.match(/^on/)) ? 'on' + type : type;
	var ff_evt = (type.match(/^on/)) ? type.replace(/on/,'') : type;
	//For IE
	if(node.fireEvent) node.fireEvent(ie_evt);
	//For Gecko
	if(document.createEvent) {
		var evt = document.createEvent('HTMLEvents');
		if(evt.initEvent) evt.initEvent(ff_evt, true, true);
		if(node.dispatchEvent) node.dispatchEvent(evt);
	}
}

//get the window height in various browsers

function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

//Whitespace functions from Mozilla (http://developer.mozilla.org/en/docs/Whitespace_in_the_DOM)

function is_all_ws( nod )
{
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.data));
}

function is_ignorable( nod )
{
  return ( nod.nodeType == 8) || // A comment node
         ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
}

function previous_sibling( sib )
{
  while ((sib = sib.previousSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

function next_sibling( sib )
{
  while ((sib = sib.nextSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

function last_child( par )
{
  var res=par.lastChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}

function first_child( par )
{
  var res=par.firstChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}

function data_of( txt )
{
  var data = txt.data;
  // Use ECMA-262 Edition 3 String and RegExp features
  data = data.replace(/[\t\n\r ]+/g, " ");
  if (data.charAt(0) == " ")
    data = data.substring(1, data.length);
  if (data.charAt(data.length - 1) == " ")
    data = data.substring(0, data.length - 1);
  return data;
}

//Find element position on screen

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

//Create popup dialog window for forms

function dialog(e) {
	e.preventDefault();
	//create and style background div--clicking it will close the dialog
	var dim = document.createElement("div");
	dim.setAttribute("id","dim");
	//set width to cover whole document
	dim.style.width = document.body.offsetWidth + 'px';
	//get window height
	var winHeight = getWindowHeight();
	//if the window height is bigger than the document height, set width to window, otherwise, document
	dim.style.height = (winHeight > document.body.offsetHeight) ? winHeight + 'px' : document.body.offsetHeight + 'px';
	dojo.connect(dim,"onclick","closeDialog");
	document.body.appendChild(dim);
	//get callers name or id--this will match the name or id of the dialog content, if it exists
	//remove string _loop_{digits} in case several looping elements are referencing the one form
	var ref = e.target.getAttribute("id") ? e.target.getAttribute("id").replace(/_loop_\d+/,'') : e.target.getAttribute("name");
	//if it exists on page, mark its place and insert the content into the dialog
	if($(ref + "_dialog")) {
		var dialogContent = first_child($(ref + "_dialog"));
		var marker = document.createElement("div");
		marker.setAttribute("id","dialogMarker");
		dialogContent.parentNode.insertBefore(marker,dialogContent);
		bubble(dialogContent);
	}
	//if it doesn't exist, check for a filename by ref and load the contents
	else {
		dojo.xhrGet({
			url:	ref + "?nocache=" + new Date(),
			load:	bubble,
			timeout:30000
		});
	}
	//populate and display the dialog
	function bubble(obj) {
		//create dialog -- pulls styles from css, opacity must be 0 for fadeIn to work
		var bubble = document.createElement("div");
		bubble.setAttribute("id","dialog");
		var innerBubble = document.createElement("div");
		innerBubble.setAttribute("id","innerBubble");
		dialogContent ? innerBubble.appendChild(dialogContent) : innerBubble.innerHTML = obj;
		bubble.appendChild(innerBubble);
		//find reference elements position and position dialog accordingly
		var p = findPos(e.target);
		//necessary so screen doesn't jump when bubble is appended
		bubble.style.top = p[1] + 'px';
		document.body.appendChild(bubble);
		bubble.style.top = p[1] - (bubble.offsetHeight/1.5) + 'px';
		bubble.style.left = p[0] - (bubble.offsetWidth+22) + 'px';
		//create bubble nub
		var bubbleBorder = document.createElement("div");
		bubbleBorder.setAttribute("id","bubbleBorder");
		bubbleBorder.style.top = p[1] - 8 + 'px';
		bubbleBorder.style.left = p[0] - 23 + 'px';
		document.body.appendChild(bubbleBorder);
		//display dialog and focus/select first input element
		dojo.fx.combine([
			dojo.fadeIn({
				node: bubble,
				duration: 200,
				onEnd:function(){
					var node = dojo.query("input","dialog")[0];
					node.focus();
					if(node.value != '') node.select();
				}
			}),
			dojo.fadeIn({
				node: bubbleBorder,
				duration: 200
			})
		]).play();
	}
}

//Close dialog box and return contents to marker

function closeDialog() {
	//kill dim
	if($("dim")) $("dim").parentNode.removeChild($("dim"));
	//kill any remaining tooltips--dialog may be destroyed before field has a chance to lose focus and drop the tooltip
	dojo.query(".dijitTooltip").forEach("item.parentNode.removeChild(item)");
	//kill dialog and put contents back in the marker
	dojo.fx.combine([
		dojo.fadeOut({
			node: "dialog",
			duration: 200,
			onEnd: function() {
				if($("dialogMarker")) $("dialogMarker").parentNode.replaceChild(first_child(first_child($("dialog"))),$("dialogMarker"));
				if($("dialog")) $("dialog").parentNode.removeChild($("dialog"));
				if($("bubbleBorder")) $("bubbleBorder").parentNode.removeChild($("bubbleBorder"));
			}
		}),
		dojo.fadeOut({
			node: "bubbleBorder",
			duration: 200
		})
	]).play();
}

//Return current time

function currentTime() {
	var t = new Date();
	hours = t.getHours() < 13 ? t.getHours() : t.getHours() - 12;
	minutes = t.getMinutes() < 10 ? "0" + t.getMinutes() : t.getMinutes();
	ap = t.getHours() < 12 ? "am" : "pm";
	time = hours + ":" + minutes + ap;
	return time;
}

//Status messages

function addStatus(val,nodeId,bad) {
	if(!$(nodeId + "_status")) {
		var div = document.createElement("div");
			div.setAttribute("id",nodeId + "_status");
			div.className = 'status';
		var div2 = document.createElement("div");
			div2.className = "bd";
		var div3 = document.createElement("div");
			div3.className = "bg";
		div2.appendChild(div3);
		div.appendChild(div2);
		$(nodeId).appendChild(div);
		dojo.fadeIn({ node: $(nodeId + "_status"), duration: 600 }).play();
		var first = true;
	}
	var newTime = document.createElement("span");
		newTime.className = "timeDisplay";
		newTime.appendChild(document.createTextNode(currentTime()));
	var newMsg = document.createElement("span");
		newMsg.className = "errorDisplay";
		newMsg.appendChild(document.createTextNode(val));
	var newDiv = document.createElement("div");
		bad ? newDiv.className = "bgbad" : newDiv.className = "bg";
		newDiv.appendChild(newTime);
		newDiv.appendChild(newMsg);
	$(nodeId + "_status").firstChild.appendChild(newDiv);
	if(!first) {
		dojo.fx.combine([
			dojo.fx.slideTo({
				node: newDiv.previousSibling,
				left: "0",
				top: "-30",
				unit: "px",
				duration: 1000,
				onEnd: function(){
					newDiv.parentNode.removeChild(newDiv.parentNode.firstChild);
				}
			}),
			dojo.fx.slideTo({
				node: newDiv,
				left: "0",
				top: "0",
				unit: "px",
				duration: 1000
			})
		]).play();
	}
	else {
		newDiv.parentNode.removeChild(newDiv.parentNode.firstChild);
		newDiv.style.top = '0px';
	}
}