// create a single global namespace "com"
var com;
if (!com) com = {};
else if (typeof com != "object")
	throw new Error("global symbol com already exists and is not an object.");

// add our namespace oneamerica onto com	
if (com.oneamerica && typeof com.oneamerica != "object")
	throw new Error("global symbol com.oneamerica already exists and is not an object.");

com.oneamerica = {
	fractionalDigits: 2,
	window_width: 800,
	window_height: 600,
	_console: null,
	debug: (window.location.search.indexOf("js.debug") > 0),
	resizeTimer: null,
	
	popup: function (url, name)
	{
		
		this.popupSized(url, name, this.window_width, this.window_height);
		return false;	
	},
	
	popupSized: function (url, name, width, height)
	{
		this.log("popupSized: " + name + " " + width + "x" + height + " to " + url);
		window.open(url,name,'width='+width+',height='+height+',resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,status=yes,location=yes,directories=yes');
		return false;	
	},
	
	hookPopupLinks: function() {
		var openInPopup = function () {
			return com.oneamerica.popup(this.href, this.target);
		};
		var tags = document.getElementsByTagName('a');
		for (var i=0;i<tags.length;i++) {
			if (tags[i].target == "_blank" && ! tags[i].onclick)
			{
				this.log("hookPopupLinks: " + tags[i].href);
				tags[i].onclick = openInPopup;
			}
		}
	},
	
	hookWordmark: function() {
		var wordmark = document.getElementById('wordmark');
		var family = (wordmark) ? wordmark.getElementsByTagName('div')[0] : null;
		var hoverTimer = null;
		var showFamily = function () {
			com.oneamerica.log("timeout fired");
			if (hoverTimer) clearTimeout(hoverTimer);
			hoverTimer = null;
			family.style.visibility='visible';			
		};
		var startTimer = function () {
			if ('visible' != family.style.visibility && ! hoverTimer) {
				com.oneamerica.log("setting timeout " + family.style.visibility);
				hoverTimer = setTimeout(showFamily,750);
			}
		};
		var hideFamily = function (e) {
			if (!e) var e = window.event;
			/* reltg is the element we just moved into */
			var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
			/* Go through all the ancestors of reltg looking for wordmark. */
			while (reltg && reltg != wordmark && reltg.parentNode)
			{
				reltg = reltg.parentNode;
			}
			/* If we found workmark then that means the mouse is still inside of the wordmark or family div. */
			if (reltg != wordmark) {
				/* Otherwise if we didn't find wordmark then that means the mouse moved outside of the family and wordmark. */
				family.style.visibility='hidden';			
				if (hoverTimer) clearTimeout(hoverTimer);
				com.oneamerica.log("moused out timer cleared");
				hoverTimer = null;
			}
		};
		if (family)
		{
			this.addEvent(wordmark, "mouseover", startTimer,false);
			this.addEvent(wordmark, "mouseout", hideFamily,false);
		}
	},
	
	ieFix: function() {
		/* The menu bar is the first UL that is a desecendent of primarynav. */
		var firstUL = true;
		var primarynav = document.getElementById("primarynav");
		var menus = (primarynav) ? primarynav.getElementsByTagName("UL") : [];
		for (var i=0; i<menus.length; i++) {
			if (firstUL)
			{
				/* This will add :hover functionality to LI's of the menu bar and all sub menus. */
				this.ieHoverFix(menus[i]);
				firstUL = false;
			} else {
				/* Now provide an IFRAME shim for each sub-menu to fix painting problems with select tags. */
				this.ieZOrderFix(menus[i]);
			}
		}
		var wordmark = document.getElementById('wordmark');
		var family = (wordmark) ? wordmark.getElementsByTagName('div')[0] : null;
		if (family) this.ieZOrderFix(family);
	},
		
	ieZOrderFix: function(element) {
		// Make sure the element has already been layed out (e.g. has a width & height). This won't
		// be the case if the element or an ancestor element is display:none.
		if (element.offsetWidth && element.offsetHeight)
		{
			// IE script to cover <select> elements with <iframe>s
			// adapted from http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/select-tag-overlap-in-ie-part-iii
			this.log("ieZOrderFix " + this.elementPath(element));
			var shim=document.createElement('iframe');
			// per comment on blog this src should be OK for http and https
			shim.src="javascript:'<html></html>';";
			shim.scrolling="no";
			shim.frameBorder="0";
			with (shim.style) {
				position="absolute";
				/* We have to subtract the width of the primary nav borders, otherwise the iframe obscures them. */
				/* This may be a problem if you have something with varrying border sizes. */
				width=(element.offsetWidth - 2)+"px";
				height=element.offsetHeight+"px";
				// We'll be inserted into an element that's already absolutely or relatively positioned. Which
				// makes that element our container, 0,0 will correspont to the upper left corner of that element.
				top="0";
				left="0";
				// Go below the BODY element's layer, this still protects the select but we don't see the IFRAME.
				zIndex="-1";
				// Set the IFRAME to transparent or it blocks the background.
				filter="alpha(style=0,opacity=0)";
			}
			// Insert the IFRAME *into* the element (e.g. inside the DIV or UL)
			element.insertBefore(shim, element.childNodes[0]);
		}
	},
	
	ieHoverFix: function(element) {
		// IE script to change class on mouseover
		var menuItems = element.getElementsByTagName("LI");
		for (var i=0; i<menuItems.length; i++) {
			// Add a sfhover class to the li.
			menuItems[i].onmouseover=function() {
				if(!/sfhover\b/.test(this.className))
					this.className+="sfhover";
				com.oneamerica.log("hovering [" + this.className + "] " + com.oneamerica.elementPath(this));
			}
			menuItems[i].onmouseout=function() {
				if(!this.contains(event.toElement))
					this.className=this.className.replace('sfhover', '');
				com.oneamerica.log("hiding [" + this.className + "] " +  com.oneamerica.elementPath(this));
			}
		}
	},
	
	totalDatagrid: function (hookFields) {
		var tables = document.getElementsByTagName("TABLE");
		for (var i = 0; i < tables.length; i++)
		{
			// we're looking for a table with class=datagrid
			if (/datagrid\b/.test(tables[i].className))
			{
				// we expect to find a single input in the table's footer
				var tfoot = tables[i].getElementsByTagName("TFOOT")[0];
				if (! tfoot)
					continue;
				com.oneamerica.log(com.oneamerica.elementPath(tfoot));			
				var totalField = tfoot.getElementsByTagName("INPUT")[0];
				if (! totalField)
					continue;
					
				var tbody = tables[i].getElementsByTagName("TBODY")[0];
				var total = 0.0;
				
				// then we add up all the inputs in the table's body
				var fields = tbody.getElementsByTagName("INPUT");
				
				for (var j = 0; j < fields.length; j++)
				{
					if (!hookFields)
					{
						com.oneamerica.log("hooking input field " + com.oneamerica.elementPath(fields[j]));							
						fields[j].onblur = com.oneamerica.totalDatagrid;
					}
					var fieldValue = Number(fields[j].value);
					if (!isNaN(fieldValue))
					{
				    	total += Number(fields[j].value);
			    	}
				}
				
				// and set the total as the new value of the footer's input
				totalField.value = new Number(total).toFixed(com.oneamerica.fractionalDigits);
			}
		}
	},
	
	addEvent: function(elm, evType, fn, useCapture) {
		// cross-browser event handling for IE5+, NS6 and Mozilla
		// By Scott Andrew
		this.log("addEvent: on " + evType + " to " + elm);
		if (elm.addEventListener){
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent){
			var r = elm.attachEvent("on"+evType, fn);
			return r;
		} else {
			elm['on'+evType] = fn;
		}
	},
	
	findPos: function (element) {
		// see www.quircksmode.org for an explination of this...
		var curleft = curtop = 0;
		if (element.offsetParent) {
			curleft = element.offsetLeft
			curtop = element.offsetTop
			while (element = element.offsetParent) {
				curleft += element.offsetLeft
				curtop += element.offsetTop
			}
		}
		return [curleft,curtop];
	},

	getElementsByLevel: function (element, tagName, level) {
		// get the Nth level descendant tags of element
		var elementsByLevel = new Array();
		var allElements = (element) ? element.getElementsByTagName(tagName) : [];
		for (var i=0; i<allElements.length; i++) {
			var parentNode = allElements[i].parentNode;
			for (var l=1; l<level && parentNode.parentNode; l++)
				parentNode = parentNode.parentNode;
				
			if (parentNode == element)
				elementsByLevel.push(allElements[i]);
		}
		return elementsByLevel;
	},
		
	changeMenuDirection: function () {
		// This method can be called from the document onLoad event or a timer.
		// If resizeTimer is not null we assume the timer called us and clear it.
		if (this.resizeTimer) {
			clearTimeout(this.resizeTimer);
			this.resizeTimer = null;
			this.log("handling resize timer");
		}
		
		var primarynav = document.getElementById("primarynav");
		// We take the width of the primary nav (a.k.a. banner) as our "desired" width.
		var bannerWidth = this.findPos(primarynav)[0] + primarynav.offsetWidth;
		this.log("banner width=" + bannerWidth);
		
		// The first UL descendant of the primary nav div is our "horizontal" menu.
		var primarymenu = (primarynav) ? primarynav.getElementsByTagName("UL")[0] : null;
		// Secondary menus are "drop down" menus
		var secondaryMenus = this.getElementsByLevel(primarymenu, "UL", 2);
		var right = 0;
		for (var i=0; i<secondaryMenus.length; i++) {
			// If the right edge of the secondary menu is already outside our desired width
			// then left justify it and don't mess with at any of its children.
			right = this.findPos(secondaryMenus[i])[0] + secondaryMenus[i].offsetWidth;
			this.log(right + " " + this.elementPath(secondaryMenus[i]));
			if (right > bannerWidth)
			{
				secondaryMenus[i].className += " left";
				this.log("flipped " + this.elementPath(secondaryMenus[i]));
			} else {
				// sub menus are the tertiary or quanternary "fly out" menus
				// if any of these are outside our desired width then the whole
				// secondary menu and all its children are left justified.
				var subMenus = secondaryMenus[i].getElementsByTagName("UL");
				for (j=0; j<subMenus.length; j++) {
					right = this.findPos(subMenus[j])[0] + subMenus[j].offsetWidth;
					this.log(right + " " + this.elementPath(subMenus[j]));
					if (right > bannerWidth)
					{
						secondaryMenus[i].className += " left";
						this.log("flipped " + this.elementPath(secondaryMenus[i]));
						// as soon as we find a sub menu then quit looking at the rest
						break;
					}
				}
			}
		}
	},

	resetMenuDirection: function () {
		// IE continiously generates resize events as the window is dyamically resized.
		// So we start a timer to do the complicated stuff later, after the window has
		// presumably stopped resizing.
		//
		// If the timer is already running, that means this call is a "new" resize event
		// so clear the timer becuase we no longer care about the old window size.
		//
		// We also need this "two step" process of reset then readjust for browsers like
		// firefox that don't reflow their layout until the current JavaScript function
		// exits.
		if (this.resizeTimer) clearTimeout(this.resizeTimer);
		this.resizeTimer = null;
		var primarynav = document.getElementById("primarynav");
		var primarymenu = (primarynav) ? primarynav.getElementsByTagName("UL")[0] : null;
		var secondaryMenus = this.getElementsByLevel(primarymenu, "UL", 2);
		for (var i=0; i<secondaryMenus.length; i++) {
			// reset any menus there were previously left aligned
			// when the timer fires it will adjust all the menus
			this.log(secondaryMenus[i].className + " " + this.elementPath(secondaryMenus[i]));
			if (/\bleft\b/.test(secondaryMenus[i].className)) {
				secondaryMenus[i].className=secondaryMenus[i].className.replace('left', '');
				this.log("removed left class " + secondaryMenus[i].className);
			}
		}
		this.resizeTimer = setTimeout(function () {com.oneamerica.changeMenuDirection();},500);
	},

	detectCapslock:	function (msgElementId, e) 
	{
		if(!e) {return;}
		var keyPressed = e.keyCode;
		if(e.charCode) {keyPressed = e.charCode} // Gecko - Firefox
		
		// if upper case and shift is not pressed
		// or if lower case and shift is pressed
		if((keyPressed > 64 && keyPressed < 91 && !e.shiftKey)
		   || (keyPressed > 96 && keyPressed < 123 && e.shiftKey))
		{
			document.getElementById(msgElementId).style.visibility = 'visible';
		}
		else
		{
			document.getElementById(msgElementId).style.visibility = 'hidden';
		}
	},
	
	log: function (msg)
	{
		if (! this.debug) return;
		if (this._console == null || this._console.closed)
		{
			this._console = window.open("","console","width=600,height=300,resizable=yes,scrollbars=yes");
			this._console.document.open("text/plain");
			this._console.document.writeln("appName=" + window.navigator.appName);
			this._console.document.writeln("appVersion=" + window.navigator.appVersion);
			this._console.document.writeln("userAgent=" + window.navigator.userAgent);
		}
		this._console.document.writeln(msg);
		this._console.scrollTo(0,this._console.document.body.offsetHeight);
	},
	
	elementPath: function (element)
	{
		var path = "";
		while (element != null && element.tagName != "HTML")
		{
			path += element.tagName;
			if (element.id)
				path+= "#" + element.id;
			if (element.className)
				path += "." + element.className;
			path += ">";
			element = element.parentNode;
		}
		return path;
	}
};

com.oneamerica.addEvent(window,"load",function () {com.oneamerica.hookPopupLinks();});
// 2/7/07 EPB - final legal decision not to have a popup in the footer
// com.oneamerica.addEvent(window,"load",function () {com.oneamerica.hookWordmark();});
com.oneamerica.addEvent(window,"load",function () {com.oneamerica.changeMenuDirection();});
com.oneamerica.addEvent(window,"resize",function () {com.oneamerica.resetMenuDirection();});

// submits a form when the enter key is pressed
function submitOnEnter(event, buttonName)
{
  	var keycode;
  	if (window.event)
  		keycode = window.event.keyCode;
  	else if (event)
  		keycode = event.which;
  	else
  		return true;

  	if (keycode == 13)
  	{
  		document.getElementById(buttonName).click();
  		return false;
  	}
  	else
  		return true;

}

// disables a button when clicked and returns true if the action should
// continue, or false if the button is disabled and should not continue
var disableButtonMap = new Object();

function disableButton(element)
{				
	if (disableButtonMap[element.id] == null)
	{
		disableButtonMap[element.id] = true;
		element.style.border = "1px solid";
		element.style.fontWeight = "bold";
		element.style.color = "#696969";
		return true;
	}
	else
	{
		return false;
	}
}




jQuery.fn.oaCenter = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.outerHeight() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft() + "px");
    return this;
}


$(function() {
	//1. Disable link if classed with singleClick
	$('a.singleClick').click(function() {
		this.onclick = function() {};
		$(this).addClass("disabled");
	});
	//2. Add coBrand class to content id if there is an id with coBrand				
	if ($('#coBrand').length > 0)
  	{
		$('#content').addClass('coBrand');
  	}
  	//3.  Center on load, round corners and then center again if the window is resized
  	$('.oaCenter').oaCenter();
  	$(window).resize(function() {
  		$('.oaCenter').oaCenter();
	});
});
