var ERM =
{
	modalPromptCallback: null,
	modalWindowCallback: null,

	// trim() function for javascript.
	trim: function(str)
	{
		if (!str)
			return "";

		return str.replace(/^\s+|\s+$/, '');
	}, // Comma is important to seperate JSON functions

	setTitle: function (title)
	{
		if (!title || !title.length)
			return;

		var n = document.getElementById('ermpage-title');
		if (n) n.innerHTML = title;

		if (typeof(document.title) != 'undefined')
			document.title = title;
	},

	setFavicon: function(src)
	{
		// Thanks http://softwareas.com/dynamic-favicons
		var head = document.getElementsByTagName('HEAD')[0];
		if (!head)
			return;

		// Remove the current favicon. Don't just update the href!
		var links = head.getElementsByTagName('LINK');
		for (var i=0; i < links.length; i++)
		{
			var link = links[i];
			if (link.rel=="shortcut icon")
			{
				head.removeChild(link);
				break;
			}
		}

		// Make a new link node
		var link = document.createElement('LINK');
		link.rel = "shortcut icon";
		link.type = "image/vnd.microsoft.icon";
		link.href = src;

		// Append it to the head
		head.appendChild(link);
	},

	showWaitCursor: function()
	{
		if (document.body)
			document.body.className = 'showwaitcursor';
	},

	hideWaitCursor: function()
	{
		if (document.body)
		{
			var className = document.body.className;
			className = className.replace(/showwaitcursor/, '');
			document.body.className = className;
		}
	},

	// Useful method for attaching events to DOM nodes on the fly
	attachEvent: function(domElement, sEvent, pFunction)
	{
		// Remove 'on' from the beginning of the string if it's there
		sEvent = sEvent.toLowerCase();
		sEvent = sEvent.replace(/^on/, '');

		// Try to attach event in W3C/Firefox style first, then IE's way, then fall back to traditional way
		if ( typeof domElement.addEventListener != "undefined" ) // W3C, Firefox
			domElement.addEventListener( sEvent, pFunction, false );
		else if ( typeof domElement.attachEvent != "undefined" ) // IE
		{
			//domElement.attachEvent( "on" + sEvent, pFunction);

			// Use this instead, to make sure all events are handled properly
			domElement['e'+sEvent+pFunction] = pFunction;
			domElement[sEvent+pFunction] = function() { domElement["e"+sEvent+pFunction]( self.event ); }
			domElement.attachEvent("on"+sEvent, domElement[sEvent+pFunction]);
		}
		else
		{
			eval("var pdomElement = domElement.on" + sEvent + ";");
			if ( pdomElement != null )
			{
				eval("var oldEvent = domElement.on" + sEvent + "; domElement.on" + sEvent + " = function(e) { oldEvent(e); pFunction(); };");
			}
			else
			{
				eval("domElement.on" + sEvent + " = pFunction;");
			}
		}
	},

	removeEvent: function(domElement, sEvent, pFunction, bForce)
	{
		// Remove 'on' from the beginning of the string if it's there
		sEvent = sEvent.toLowerCase();
		sEvent = sEvent.replace(/^on/, '');

		// Try to attach event in W3C/Firefox style first, then IE's way, then fall back to traditional way
		if ( typeof domElement.removeEventListener != "undefined" ) // W3C, Firefox
			domElement.removeEventListener( sEvent, pFunction, false );
		else if ( typeof domElement.detachEvent != "undefined" ) // IE
			domElement.detachEvent( "on" + sEvent, pFunction);
		else
		{
			// We really can't seperate old-style events once they're joined, so just set it to null if forced.
			if (bForce)
			{
				eval("domElement.on" + sEvent + " = null;");
			}
		}
	},

	// Get target node - http://www.quirksmode.org/js/events_properties.html	<3 QuirksMode
	getTargetForEvent: function(e)
	{
		if (!e) var e = window.event;

		var targ;
		if (e.target)
			targ = e.target;
		else if (e.srcElement)
			targ = e.srcElement;

		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;

		return targ;
	},

	preventDefaultAction: function(e)
	{
		if(e.preventDefault)
			e.preventDefault();

		try
		{
			e.returnValue = false;
		}
		catch (ex)
		{
			// do nothing
		}
	},

	loader: function(pFunction)
	{
		ERM.attachEvent(window, 'load', pFunction);
	},

	// Initialization function for each ERM page (onload event)
	init: function()
	{
		// Load sidebar content from temporary div at bottom of page into main td
		var sidebar = document.getElementById("ermpage-sidebar");
		var content = document.getElementById("ermpage-sidebar-temp");

		if (content && sidebar)
		{
			sidebar.innerHTML = content.innerHTML;
			sidebar.style.display = '';

			// Clear the temp junk
			content.parentNode.removeChild(content);
		}

		// Show "Loading... Please Wait" if necessary
		var loading = document.getElementById("loadingpleasewait");
		if (loading)
			loading.style.display = "none";
	},

/*	// NavTab More-izer - Adds a "More" button to the NavTabs (if needed)
	navTabHider: function()
	{
		// Temporarily remove the resize event so it doesn't fire multiple times in IE
		ERM.removeEvent(window, 'resize', ERM.navTabHider);

		// If we're on a BlackBerry or iPhone, don't hide any tabs. (Other mobile browsers will probably fail anyway.)
		if (navigator && navigator.userAgent)
		{
			if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)
			 || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Opera Mini/i))
			{
				var navtabwrapper = document.getElementById('ermpage-navtabs');
				if (navtabwrapper)
				{
					var navtabul = navtabwrapper.getElementsByTagName('UL')[0];
					if (navtabul)
						navtabul.className = 'nomore';
				}

				return;
			}
		}

		// If we have a 'More' tab already, remove it
		var oMoreTab = document.getElementById('ermpage-navtabs-more');
		if (oMoreTab)
			oMoreTab.parentNode.removeChild(oMoreTab);

		if (typeof(ERMDropdown) != 'undefined')
			ERMDropdown.hide();

		// First get our menu pointers
		var navtabwrapper = document.getElementById('ermpage-navtabs');
		if (!navtabwrapper)
			return;

		var navtabul = navtabwrapper.getElementsByTagName('UL')[0];
		if (!navtabul)
			return;

		var navtabs = navtabul.getElementsByTagName('LI');
		if (!navtabs)
			return;

		// First, show all the hidden tabs
		for(var i = 0; i < navtabs.length; i++)
			navtabs[i].style.display = '';

		// Before we do anything else, let's make sure we actually need the More tab in the first place
		if (navtabs[navtabs.length - 1].firstChild.offsetTop < 10)
		{
			ERM.attachEvent(window, 'resize', ERM.navTabHider);	// Re-attach event
			return;
		}


		// Go ahead and add the More tab - we'll delete it later if needed
		oMoreTab = document.createElement('LI');
		oMoreTab.setAttribute('id', 'ermpage-navtabs-more'); // Need to set twice for IE
		oMoreTab.id = 'ermpage-navtabs-more';
		oMoreTab.innerHTML = '<a href="javascript:void({})" title="Click to see more menu choices" '
									+ 'onclick="if (typeof(ERMDropdown) != \'undefined\') ERMDropdown.show(\'edm_NavTabs\', this, event)"'
									+ '><span>More</span></a>';

		navtabul.appendChild(oMoreTab);

		// Now find out if we should keep it or not
		var aHiddenTabs = new Array();
		var iHiddenCount = 0;

		for(var i = navtabs.length - 1; i > 0; i--)
		{
			var tab = navtabs[i];

			// Don't count our "More" tab
			if (tab == oMoreTab || tab.className == 'activenavtab')
				continue;


			// See if the 'More' tab is still on the second row
			if (oMoreTab.firstChild.offsetTop > 9)
			//if (i > 9)
			{
				var o = new Object();

				var a = tab.firstChild;

				o.href = a.href;
				//o.onclick = a.onclick;
				o.title = a.firstChild.innerHTML;

				if (o.title == 'Help')
					continue;

				aHiddenTabs[iHiddenCount++] = o;
				tab.style.display = 'none';
			}
		}

		if (iHiddenCount)
		{
			// We need to make a menu out of our hidden choices
			var edmroot = document.getElementById('edm_NavTabs');
			if (!edmroot)
				return;

			var html = '';
			for(var i = iHiddenCount - 1; i >= 0; i--)
				html += '<a href="' + aHiddenTabs[i].href + '">' + aHiddenTabs[i].title + '</a>';

			var edm = edmroot.lastChild.lastChild;
			edm.innerHTML = html;
		}
		else
			navtabul.removeChild(oMoreTab);

		ERM.attachEvent(window, 'resize', ERM.navTabHider);	// Re-attach event
	},
*/

	evtGenericAjaxError: function(response)
	{
		alert('An unexpected error has occurred:\n\n'
				+ response.status + "\n" + response.responseText
				+ '\n\nPlease contact support@eratemanager.com for further assistance');
	},

	showShadow: function()
	{
		var shadow = document.getElementById('ermpage-shadow');
		shadow.style.display = '';
	},

	hideShadow: function()
	{
		var shadow = document.getElementById('ermpage-shadow');
		shadow.style.display = 'none';
	},

	setModalWindowCallback: function(f)
	{
		if (f)
			ERM.modalWindowCallback = f;
		else
			ERM.modalWindowCallback = null;
	},

	showModalWindow: function(content, width, height, title)
	{
		ERM.showShadow();

		var w = document.getElementById('ermpage-modalwindow');

		// Generate title HTML, if needed
		var titlecontent = '';
		if (title)
		{
			titlecontent = '<h1 class="windowtitle"><a class="iconlink" href="javascript:void({})" onclick="ERM.hideModalWindow()">'
								+ '<img src="/images/maps/close.gif" /></a>' + title + '</h1>';
		}

		// Update the width, height, and position of this window
		w.style.width = width + 'px';
		w.style.height = height + 'px';
		w.style.marginLeft = -(width / 2) + 'px';
		w.style.marginTop = -(height / 2) + 'px';

		w.style.display = '';
		if (typeof content == 'string')
			w.innerHTML = titlecontent + content;
		else
		{
			w.innerHTML = titlecontent;
			w.appendChild(content.cloneNode(true));

			// Hack for IE: Traverse BOTH source and destination looking for <SELECT> boxes. Copy the selectedIndex
			var sourceindexes = content.getElementsByTagName('SELECT');
			var destindexes = w.getElementsByTagName('SELECT');
			var sourcecount = sourceindexes.length;
			if (sourcecount > 0 && sourcecount == destindexes.length) // Sanity check: Make sure the number of elements are the same!
				for(var i = 0; i < sourcecount; i++)
					destindexes[i].selectedIndex = sourceindexes[i].selectedIndex;
		}

		// If our window is off the screen, move it so at least the top is visible
		if (w.offsetLeft < 0)
			w.style.marginLeft = (-w.offsetLeft + -(width / 2)) + 'px';
		if (w.offsetTop < 0)
			w.style.marginTop = (-w.offsetTop + -(height / 2)) + 'px';

		if (ERM.modalWindowCallback)
			ERM.modalWindowCallback();
	},

	showModalWindowAjax: function(url, width, height, title)
	{
		ERM.showShadow();

		var w = document.getElementById('ermpage-modalwindow');

		// Generate title HTML, if needed
		var titlecontent = '';
		if (title)
		{
			titlecontent = '<h1 class="windowtitle"><a class="iconlink" href="javascript:void({})" onclick="ERM.hideModalWindow()">'
								+ '<img src="/images/maps/close.gif" /></a>' + title + '</h1>';
		}

		// Update the width, height, and position of this window
		w.style.width = width + 'px';
		w.style.height = height + 'px';
		w.style.marginLeft = -(width / 2) + 'px';
		w.style.marginTop = -(height / 2) + 'px';

		// Make sure our AJAX library (prototype.js) is loaded
		if (typeof Ajax != 'undefined' && typeof Ajax.Request != 'undefined')
		{
			// Make an AJAX call with the url
			new Ajax.Request(url, { onFailure: ERM.evtModalFail, onSuccess: ERM.evtModalSuccess } );

			// Finally, show the window
			w.style.display = '';
			w.innerHTML = titlecontent + '<span>Loading...</span>';

			// If our window is off the screen, move it so at least the top is visible
			if (w.offsetLeft < 0)
				w.style.marginLeft = (-w.offsetLeft + -(width / 2)) + 'px';
			if (w.offsetTop < 0)
				w.style.marginTop = (-w.offsetTop + -(height / 2)) + 'px';
		}
		else
		{
			alert('ERROR: Cannot show window. Please contact support@eratemanager.com');

			ERM.hideModalWindow();
		}
	},

	hideModalWindow: function()
	{
		ERM.hideShadow();

		var w = document.getElementById('ermpage-modalwindow');
		w.style.display = 'none';
		w.innerHTML = '';
	},

	// "Private" events for Modal Window AJAX
	evtModalSuccess: function(response)
	{
		var w = document.getElementById('ermpage-modalwindow');

		w.removeChild(w.lastChild);
		w.innerHTML += response.responseText;

		if (ERM.modalWindowCallback)
			ERM.modalWindowCallback(response);
	},

	evtModalFail: function(response)
	{
		ERM.evtGenericAjaxError(response);
		ERM.hideModalWindow();
	},

	// A replacement for the built-in JavaScript prompt() function, which IE now blocks. Thanks IE!
	prompt: function(callback, prompt, title)
	{
		ERM.modalWindowCallback = null;
		ERM.modalPromptCallback = callback;

		// Replace all \n with <br />
		prompt = prompt.replace(/\n/gi, '<br />');

		var html = '<form class="ERMModalPrompt" onsubmit="ERM.evtPromptResponse(true); return false;">'
					+ '<p>' + prompt + '</p>'
					+ '<input type="text" id="ERMModalPromptTextbox" />'
					+ '<input type="submit" value="OK" />'
					+ '<input type="button" value="Cancel" onclick="ERM.evtPromptResponse(false);" />'
					+ '</form';

		ERM.showModalWindow(html, 600, 150, title);

		// Set focus to our new text box
		var t = document.getElementById('ERMModalPromptTextbox');
		if (t)
			t.focus();
	},

	evtPromptResponse: function(didSubmit)
	{
		var text = null;
		if (didSubmit)
		{
			var input = document.getElementById('ERMModalPromptTextbox');
			text = input.value;
		}

		ERM.hideModalWindow();

		if (ERM.modalPromptCallback)
			ERM.modalPromptCallback(text);
		else
			alert('ERROR: Cannot complete prompt action! Please contact support@eratemanager.com');

		ERM.modalPromptCallback = null;
	},

/*	// Note to self: DO NOT USE! openModalWindow doesn't get window.opener variable scope in IE, meaning you can't call parent window
	//               javascript functions!
	openModalWindow: function(url, name, width, height)
	{
		if (width == null)
			width = 720;
		if (height == null)
			height = 500;

		if (window.showModalDialog) // Open modal dialog in IE. It's slightly nicer than regular window.open()
		{
			var options = "dialogWidth:" + width + "px;dialogHeight:" + height + "px;center:yes;scroll:yes;status:no;help:no;resizable=yes";
			window.showModalDialog(url, name, options);
		}
		else
		{
			var x = (screen.width/2 - width/2); if (x < 0) x = 0;
			var y = (screen.height/2 - height/2); if (y < 0) y = 0;

			var options = "width=" + width + ",height=" + height + ",screenx=" + x + ",left=" + x + ",screeny=" + y + ",top=" + y ;
			options += ",location=no,scrollbars=yes,menubar=no,toolbar=no,statusbar=no,resizable=yes,modal=yes,";
			window.open(url, name, options);
		}
	},
*/
	openWindow: function(url, name, width, height)
	{
		if (width == null)
			width = 720;
		if (height == null)
			height = 500;

		var x = (screen.width/2 - width/2); if (x < 0) x = 0;
		var y = (screen.height/2 - height/2); if (y < 0) y = 0;

		var options = "width=" + width + ",height=" + height + ",screenx=" + x + ",left=" + x + ",screeny=" + y + ",top=" + y ;
		options += ",location=no,scrollbars=yes,menubar=no,toolbar=no,statusbar=no,resizable=yes,modal=yes,";

		var win = window.open(url, name, options);
		win.focus();

		return win;
	},

	getWindowWidth: function()
	{
		if (window.self && self.innerWidth)
			return self.innerWidth;

		if (document.documentElement && document.documentElement.clientWidth)
			return document.documentElement.clientWidth;

		return 0;
	},

	getWindowHeight: function()
	{
		if (window.self && self.innerHeight)
			return self.innerHeight;

		if (document.documentElement && document.documentElement.clientHeight)
			return document.documentElement.clientHeight;

		return 0;
	},

	getWindowScrollX: function()
	{
		if (window.self && self.pageXOffset)
			return self.pageXOffset;

		if (document.documentElement && document.documentElement.scrollLeft)
			return document.documentElement.scrollLeft;

		return 0;
	},

	getWindowScrollY: function()
	{
		if (window.self && self.pageYOffset)
			return self.pageYOffset;

		if (document.documentElement && document.documentElement.scrollTop)
			return document.documentElement.scrollTop;

		return 0;
	},

	// Detects whether the user pressed the 'Enter' key. Use with onkeydown/onkeyup events only! (Not onkeypress)
	pressedEnter: function(evt)
	{
		if (!evt) var evt = window.event;

		var key;
		if(evt && evt.which)
			key = evt.which;
		else
			key = evt.keyCode;

		if (key == 13 || key == 3) // Numpad Enter is ascii 3 on Mac (maybe just Safari)
			return true;

		return false;
	},

	createCookie: function(name,value,days)
	{
		if (days)
		{
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else
			var expires = "";

		document.cookie = name+"="+value+expires+"; path=/";
	},

	readCookie: function(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null;
	},

	eraseCookie: function(name)
	{
		ERM.createCookie(name,"",-1);
	},

	boldSidebar: function(section, title, dontunboldothers, unbolditem)
	{
		if (!dontunboldothers)
			dontunboldothers = false;
		if (!unbolditem) // 'hidden' 4th parameter, do we really want to unbold instead?
			unbolditem = false;

		if (!section || (!title && dontunboldothers))
			return;

		var ermsidebar = document.getElementById('ermpage-sidebar');
		if (!ermsidebar)
			return;

		var elements = ermsidebar.childNodes;
		var elemlen = elements.length;
		var bFoundHeader = false;
		var bFoundSection = false;

		for(var i = 0; i < elemlen; i++)
		{
			var elem = elements[i];
			var tagname = elem.tagName;
			var classname = elem.className;

			if (!tagname)
				continue;
			else if (tagname == 'DIV' && classname == 't') // After the redesign, the sidebar no longer has classnames that make sense.
			{
				if (bFoundHeader) // If we're back on another header, it means we didn't find our item to bold. So just go ahead and return...
					return;

				// Drill down past the junk divs to get the title
				var t = elem.lastChild.lastChild.lastChild.lastChild.lastChild.innerHTML;
				if (t == section)
					bFoundHeader = true;
			}
			else if (bFoundHeader && tagname == 'DIV' && classname == 'b2')
			{
				// Get all the UL's inside this node
				var uls = elem.getElementsByTagName('UL');
				var ulcount = uls.length;

				for(var k = 0; k < ulcount; k++)
				{
					var li = uls[k].childNodes;
					var lilen = li.length;

					for(var j = 0; j < lilen; j++)
					{
						var elem2 = li[j];
						var tagname2 = elem2.tagName;

						if (tagname2 && tagname2 == 'LI')
						{
							var a = elem2.childNodes[0];
							if (!a)
								continue;

							if (!dontunboldothers)
								a.className = '';

							// Trim the »&nbsp; off the beginning of the string
							var text = a.innerHTML.substring(7);
							if (text == title)
							{
								a.className = (unbolditem ? '' : 'activeSidebarLink');

								if (dontunboldothers)
									return;
							}
						}
					}
				}
			}
		}

		return;
	},

	unboldSidebar: function(section, title)
	{
		ERM.boldSidebar(section, title, (title ? true : false), true);
	},

	// IE8 is stupid and doesn't allow you to drag links where the href is HTTPS.
	// http://support.microsoft.com/kb/887614
	// Since these links are javascript:void({}), we need to change them behind the scenes for IE8.
	fixIE8DragDropLinks: function(obj)
	{
		// Conditional Compliation ensures this stupid stupid thing only works in IE8. Stupid IE8.
		/*@cc_on

		// Only IE8 needs to run this. IE9 works
		if (navigator.appVersion.indexOf('MSIE 8.0') < 0)
			return;

		if (!obj || !obj.childNodes || !obj.childNodes.length)
			return;

		var links = obj.getElementsByTagName('A');
		var linklen = links.length;

		for(var i = 0; i < linklen; i++)
		{
			var link = links[i];
			if (link.href == 'javascript:void({})')
				link.href = 'http://www.eratemanager.com';

			ERM.attachEvent(link, 'click', function(e) { ERM.preventDefaultAction(e); } );
		}
		@*/
	},

	menuSlider:
	{
		parentDiv: '',
		sliderType: '', // can be either 'FFL' or 'ERM'
		pointWhichWay: '', // can be either 'LEFT' or 'RIGHT'
		imageNode: '',
		set: function (sParentDiv, sPointWhichWay, sSliderType, fOnClick)
		{
			this.parentDiv = document.getElementById(sParentDiv);
			this.pointWhichWay = sPointWhichWay;
			this.sliderType = sSliderType;
/*
			// create an image node, then put it in the parent node that was specified
			// (make sure that it is the only node in the parent)
			this.imageNode = document.createElement('IMG');
			this.imageNode.src = '/images/fflmenubuttons.png';
			this.imageNode.style.position = 'relative';
*/
//			this.parentDiv.innerHTML = ''; // easy way to erase all child nodes
//			this.parentDiv.onmouseover = function () { ERM.menuSlider.pushIn(); };
//			this.parentDiv.onmouseout = function () { ERM.menuSlider.popOut(); }
			this.parentDiv.onclick = fOnClick;
//			this.popOut();
		}
/*	These aren't needed anymore. We're doing it through CSS instead!
		pushIn: function ()
		{
			if (this.sliderType == 'FFL' && this.pointWhichWay == 'LEFT')
			{
				// this.imageNode.style.top = '-20px';
				this.parentDiv.style.backgroundPosition = "0px -20px";
			}
			else if (this.sliderType == 'FFL' && this.pointWhichWay == 'RIGHT')
			{
				// this.imageNode.style.top = '-60px';
				this.parentDiv.style.backgroundPosition = "0px -60px";
			}
			else if (this.sliderType == 'ERM' && this.pointWhichWay == 'LEFT')
			{
				// this.imageNode.style.top = '-140px';
				this.parentDiv.style.backgroundPosition = "0px -140px";
			}
			else if (this.sliderType == 'ERM' && this.pointWhichWay == 'RIGHT')
			{
				// this.imageNode.style.top = '-100px';
				this.parentDiv.style.backgroundPosition = "0px -100px";
			}
		},
		popOut: function ()
		{
			if (this.sliderType == 'FFL' && this.pointWhichWay == 'LEFT')
			{
				// this.imageNode.style.top = '0px';
				this.parentDiv.style.backgroundPosition = "0px 0px";
			}
			else if (this.sliderType == 'FFL' && this.pointWhichWay == 'RIGHT')
			{
				// this.imageNode.style.top = '-40px';
				this.parentDiv.style.backgroundPosition = "0px -40px";
			}
			else if (this.sliderType == 'ERM' && this.pointWhichWay == 'LEFT')
			{
				// this.imageNode.style.top = '-120px';
				this.parentDiv.style.backgroundPosition = "0px -120px";
			}
			else if (this.sliderType == 'ERM' && this.pointWhichWay == 'RIGHT')
			{
				// this.imageNode.style.top = '-80px';
				this.parentDiv.style.backgroundPosition = "0px -80px";
			}
		}
*/
	}, // end property menuSlider

	// Leave empty husks for these three debugging-only functions
	debug: function(sMsg) {},
	print_r: function(v, showfunctions, level) {},
	alert_r: function(v, showfunctions) {},
	explainSQL: function(o) {}
}
ERM.loader(ERM.init);
//ERM.loader(ERM.navTabHider);
