function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// initialize all the functions
addLoadEvent(initButtonRollovers);
addLoadEvent(initNewsletterPage);
/*addLoadEvent(initDefeasanceCalc);*/
addLoadEvent(function() {
  /* more code to run on page load */ 
	sfHover('nav');
	sfClick('faqs');
	closeAnswer('faqs');
	stripe('faqs');
	stripeTable('ppl',1,2);
});

function isIE()
{
	return (document.all && !window.opera);
}

function getIEVersion()
{
	var versionText = parseFloat(navigator.appVersion.split("MSIE")[1]);
	return parseFloat(versionText);
}

function isIE7()
{
	if (isIE())
	{
		return getIEVersion() >= 7;
	}
	return false;
}

function isIE6()
{
	if (isIE())
	{
		return getIEVersion() < 7;
	}
	return false;
}

// hide the span that has the warning that JS is disabled
function hideJSDisabledWarning()
{
    var JSDisabledWarning = document.getElementById('JSDisabledWarning');
    if(JSDisabledWarning)
    {
        JSDisabledWarning.style.visibility = 'hidden';
    }
}

// show the dropdown navigation
function sfHover(id,elem) {
	// find the nav
	if (!document.getElementById(id)) return;
	if (!elem) var elem = 'li';
	// get all the LIs
	var sfEls = document.getElementById(id).getElementsByTagName(elem);
	if (sfEls.length == 0) return;

	// go through all the LIs in the nav and set events
	for (var i=0; i<sfEls.length; i++)
	{
		// set onmouseover event
		sfEls[i].onmouseover=function() {
			// set class
			this.className+=' sfhover';

			// because (IE is lame) the menu gets hidden behind select elements we have to hide them temporarily
			if (isIE7())
			{
				var subMenu;
				for (var i=0; i<this.childNodes.length; i++)
				{
					if(this.childNodes[i].nodeType == 1 && this.childNodes[i].className.indexOf('SecondaryMenu') > -1) {
						hideCollidedSelectBoxes(this.childNodes[i]);
					}
				}
			}
		}
		// set onmouseout event
		sfEls[i].onmouseout=function() {
			// remove class
			this.className = this.className.replace(' sfhover','');	
			showSelectBoxes();
		}
	}
}


// alternate display of the FAQ answers
function sfClick(id) {
	if (!document.getElementById(id)) return;
	var el = document.getElementById(id).getElementsByTagName('p');
	if (el.length == 0) return;

	for (i = 0; i < el.length; i++)
	{
		var ebar = el[i];
		if (ebar && ebar.className == 'q')
		{
			// set the onclick event
			ebar.onclick=function()
			{
				// if the class already exists, remove it
				if (this.parentNode.className.indexOf(''+'sfopen'+'') > -1)
				{
					this.parentNode.className=this.parentNode.className.substr(0, this.parentNode.className.indexOf(' sfopen'));
				} else { // otherwise add the class
					this.parentNode.className+=' sfopen';
				}
			}
		}
	}
}

function sfOpen(id)
{
	var qPar = document.getElementById(id);
	qPar.className += ' sfopen';
}


// for the close answer link in the FAQs
function closeAnswer(id) {
	if (!document.getElementById(id)) return;
	var el = document.getElementById(id).getElementsByTagName('a');
	if (el.length == 0) return;

	for (i = 0; i < el.length; i++)
	{
		var closer = el[i];
		if (closer && closer.className == 'closeAnswer')
		{	
			// set the click event
			closer.onclick=function()
			{
				var p = this.parentNode;
			
				while (p.className.indexOf('sfopen') == -1)
				{
					p = p.parentNode;
				}
				p.className=p.className.substr(0, p.className.indexOf(' sfopen'));
				return false;
			}
		}
	}
}


// open the relevant FAQ answer
function openAnswer(id) {
	if (!document.getElementById(id)) return;
	var el = document.getElementById(id);
	if (el.length == 0) return;

	// if the class already exists, move on
	if (el.className.indexOf(''+'sfopen'+'') > -1)
	{
		return;
	} else { // otherwise add the class
		el.className+=' sfopen';
	}
}


// add background color to every other item in a list
function stripe(id) {
	var list = document.getElementById(id);
	if (!list) return;
	var lis = [];

	//get all the LIs
	for (var i=0; i < list.childNodes.length; i++)
	{
		if (list.childNodes[i].nodeType == 1 && list.childNodes[i].nodeName.toLowerCase() == 'li')
		{
			lis[lis.length] = list.childNodes[i];
		}
	}
	// set class on every other item
	for (var i=0; i < lis.length; i += 2)
	{
		lis[i].className += ' odd';
	}
}

// add background color to every other row in a table
function stripeTable(id,s,m) {
	var table = document.getElementById(id);
	if (!table) return;
    var trs = table.getElementsByTagName('tr');

	// set class on every other item
	for (var i=s; i < trs.length; i += m)
	{
		trs[i].className += ' even';
	}
}

// reset the form back to its default values
function reset_form() {
	// confirm reset
	if (confirm('Are you sure that you want to reset this form?')) {
		return true;
	}
	return false;
}

// set and preload the button 'on' state images
function initButtonRollovers() {
	if (!document.getElementsByTagName) return;
	
	var oPreLoad = new Array();
	var oTempSrc;
	var oInput = document.getElementsByTagName('input');
	var oAnchor = document.getElementsByTagName('a');
	

	for (var i = 0; i < oInput.length; i++) {
		// only look for INPUTs with class of 'rollover'
		if (oInput[i].className == 'rollover') 
		{
            setControlRolloverImage(oInput[i], oPreLoad);
		}
	}
	// Now look for anchors with images
	for (var j = 0; j < oAnchor.length; j++)
	{
	    if (oAnchor[j].className == 'rollover' && oAnchor[j].childNodes)
	    {
	        for (var k = 0; k < oAnchor[j].childNodes.length; k++)
	        {
	            if (oAnchor[j].childNodes[k].tagName != null && oAnchor[j].childNodes[k].tagName.toLowerCase() == 'img')
	            {
	                setControlRolloverImage(oAnchor[j].childNodes[k], oPreLoad);
	            }
	        }
	    }
	}
}

function setControlRolloverImage(oCntrl, oPreLoad)
{
    // get the image source
    var src = oCntrl.getAttribute('src');
    // get the over state by replacing 'off' with 'on'
    var osrc = src.replace(/-off(\.[a-z0-9]+)$/i,'-on$1');

    oCntrl.setAttribute('osrc', osrc);

    // preload 'on' state images
    var preloadLen = oPreLoad.length;
    oPreLoad[preloadLen] = new Image();
    oPreLoad[preloadLen].src = osrc;

    // set the on state
    oCntrl.onmouseover = function() 
    {
	    oTempSrc = this.getAttribute('src');
	    this.setAttribute('src', this.getAttribute('osrc'));
    }	

    // set back to off state
    oCntrl.onmouseout = function() 
    {
	    if (!oTempSrc) oTempSrc = this.getAttribute('src').replace(/-on(\.[a-z0-9]+)$/i,'-off$1');;
	    this.setAttribute('src', oTempSrc);
	}
}

// SML functions based on detectCollision.js
function hideCollidedSelectBoxes(o)
{
	if (isIE6())
	{
		var selectArray = document.getElementsByTagName('select');
		
		for (var i=0; i<selectArray.length; i++)
		{
			if (detectCollision(o, selectArray[i]))
			{
				selectArray[i].style.visibility = 'hidden';
			}
		}
	}
}

function showSelectBoxes(o)
{
	if (isIE6())
	{
		var selectArray = document.getElementsByTagName('select');
		for (var i=0; i<selectArray.length; i++)
		{
			selectArray[i].style.visibility = (selectArray[i].style.visibility == 'hidden') ? 'visible': '';
		}
	}
}


// author: slee@iconnicholson.com
// version: 1.0
// date: 2005-08-11
//
// collision detection theory
// for each pair of object, if one of their axis does not collide, then they do not collide
// implementation: loop through each axis and return false if they do not collide
// 
// method: detectCollision(a:Object, b:Object):Boolean
// a: document element object
// b: document element Object
// return: Boolean

function detectCollision(a,b)
{

	// x-axis
	var xA = getAbsoluteLeft(a);
	var xB = getAbsoluteLeft(b);
	var wA = a.offsetWidth;
	var wB = b.offsetWidth;
	if (Math.max(xA+wA, xB+wB)-Math.min(xA, xB) > (wA+wB))
		return false;
		
	// y-axis
	var yA = getAbsoluteTop(a);
	var yB = getAbsoluteTop(b);
	var hA = a.offsetHeight;
	var hB = b.offsetHeight;
	if (Math.max(yA+hA, yB+hB)-Math.min(yA, yB) > (hA+hB))
		return false;

	return true;
	
}


// getAbsolutePosition.js (part of the SML vocabulary)
function getAbsoluteLeft(o)
{
	var result = o.offsetLeft;
	var p = o.offsetParent;
	while (p != null)
	{
		result += p.offsetLeft;
		p = p.offsetParent;
	}
	return result;
}

function getAbsoluteTop(o)
{
	var result = o.offsetTop;
	var p = o.offsetParent;
	while (p != null)
	{
		result += p.offsetTop;
		p = p.offsetParent;
	}
	return result;
}


function hideShowElement(elemId, show, tableRow)
{
	if (show)
	{
		showElement(elemId, tableRow);
	}
	else
	{
		hideElement(elemId);
	}
}

// Hide an element using it's ID with javascript
// param elemId - Id of the element to hide
function hideElement(elemId)
{
	hideElementObj(document.getElementById(elemId));
}

// Hide an element with javascript
// param elemId - Id of the element to hide
function hideElementObj(elem)
{
	if(elem == null)
	{
		return;
	}
	elem.style.display = "none";
}

// Display an element using it's ID with javascript
// Note that table rows need a different command in IE and other browsers
// param elemId - Id of the element to show
// param tableRow - true if we are showing a tablerow TR element due to browser differences
function showElement(elemId, tableRow)
{
	showElementObj(document.getElementById(elemId), tableRow);
}

// Display an element with javascript
// Note that table rows need a different command in IE and other browsers
// param elemId - element to show
// param tableRow - true if we are showing a tablerow TR element due to browser differences
function showElementObj(elem, tableRow)
{
	if (elem == null)
	{
		return;
	}
	if (tableRow == null || document.all || tableRow == false)
	{
	// IE
		elem.style.display = "block";
	}
	else
	{
	// OTHER
		elem.style.display = "table-row";
	}
}

function isElemVisible(elemId)
{
	var elem = document.getElementById(elemId);
	if (elem == null)
	{
		return false;
	}
	return elem.style.display != "none";
}

function toggleElement(elemId, tableRow)
{
	var elemObj = document.getElementById(elemId);
	if (elemObj == null)
	{
		return false;
	}
	if (isElemVisible(elemId))
	{
		hideElement(elemId);
	}
	else
	{
		showElement(elemId, tableRow);
	}
	return true;
}

// Toggles visibility for an array of elements
// param elemIdArray - array of element names
function toggleElements(elemIdArray, tableRowElements)
{
	var x = 0;
	for (x = 0; x < elemIdArray.length; x++)
	{
		toggleElement(elemIdArray[x], tableRowElements);
	}
}

//*********Begin Javascript Functions that handle carriage return submissions**************//
var ButtonToSubmit;
function initNewsletterPage()
{
	if(!document.getElementById||!document.getElementById('login'))return;
	var bodyTag = document.getElementById('login');
	if(bodyTag.tagName !='BODY')return;	
	var nlElementIds = new Array('RegistrationForm_TitleTextBox','RegistrationForm_FirstNameTextBox','RegistrationForm_LastNameTextBox','RegistrationForm_EmailTextBox','RegistrationForm_PhoneTextBox','RegistrationForm_CompanyTextBox','RegistrationForm_MailingAddressTextBox');
	var liElementIds = new Array('UserNameTextBox','PasswordTextBox');
	var newsLetterButton = document.getElementById('RegistrationForm_NewsletterSubmitButton');
	addOnFocusEventsToTextBoxes(nlElementIds, newsLetterButton);
	if(document.getElementById('LoginSubmitButton'))
	{	
		var loginButton  = document.getElementById('LoginSubmitButton');
		addOnFocusEventsToTextBoxes(liElementIds, loginButton);
	}
	ButtonToSubmit = newsLetterButton;
}

function addOnFocusEventsToTextBoxes(textBoxes,button)
{
	document.onkeypress = setButtonToClick;
	var i;
	var txtBox;
	for(i=0;i<textBoxes.length;i++)
	{
		txtBox = document.getElementById(textBoxes[i]);
		addOnFocusEvent(txtBox, button);
	}
}


function addOnFocusEvent(textBox, button) 
{  
	
  if (typeof textBox.onfocus != 'function') {
    textBox.onfocus = function() {
		setButtonToSubmit(button);
	}
  } else {
	var oldonfocus = textBox.onfocus;
    textBox.onfocus = function() {
      oldonfocus();
      setButtonToSubmit(button);
    }
  }
}


function setButtonToSubmit(button)
{
	ButtonToSubmit = button;	
}


function setButtonToClick(e)
{
	var ev = e;
	var IsIE = false;
	if(typeof(event)!='undefined')
	{
		ev = event;
		IsIE = true;
	}
	if(ev)
	{
		if(ev.keyCode == 13)
		{
			if(IsIE)
			{
				ButtonToSubmit.focus();
				return;
			}
			ButtonToSubmit.click();
		}		
	}
}
//*********End Javascript Functions that handle carriage return submitions**************//



function popWin(url,width,height,scroll,status,resize) 
{
	if (!scroll) scroll = 1;
	if (!status) status = 1;
	if (!resize) resize = 1;

	window.open(url,'','width=' + width + ', height=' + height + ', location=0, toolbar=0, menubar=0, directories=0, scrollbars=' + scroll + ', status=' + status + ', resizable=' + resize + '');
}

// Function: stripComma - Strips commas and spaces off dollar amount
// param money - String representing dollar amt
// returns: string representing dollar amount reformatted
//			if input was null, then an empty string gets returned
function stripComma(money)
{
	var retVal = ""
	if( money != null )
	{
		retVal = money;
		if(retVal.indexOf(',') != -1) // strip the commas
		{
			var strip = retVal.split(',');
			retVal = "";

			for(var y=0;y< parseInt(strip.length);y++)
			{
				retVal += strip[y];
			}

		}
		if(retVal.indexOf(' ') != -1) // strip the spaces
		{
			var strip = retVal.split(' ');
			retVal = "";

			for(var y=0;y< parseInt(strip.length);y++)
			{
				retVal += strip[y];
			}

		}

	}
	return retVal;
}// end stripComma

function FormatAsMoney(txtbox) 
{
	nStr = stripComma(txtbox.value);
	if(!isNaN(nStr))
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = (typeof(x[1]) == 'undefined')?'00':x[1];
		x2 = (x2.length == 1)?x2+'0':x2;
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		txtbox.value = x1;
	}
}
function showCollidedSelects(obj)
{
	if (isIE6())
	{
		var selectArray = document.getElementsByTagName('select');
		for (var i=0; i<selectArray.length; i++)
		{
			var selectElt = selectArray[i];
			
			if(!areAllParentsVisible(selectElt))
			{
			    continue;
			}
			
			if (selectElt.style.previousVisibility 
				&& selectElt.style.previousVisibility.length>0
				&& selectElt.style.previousVisibilityObjId[selectElt.style.previousVisibilityObjId.length-1] == obj.id)
			{
			    selectElt.style.visibility = selectElt.style.previousVisibility.pop();   
                selectElt.style.previousVisibilityObjId.pop();
			}
		}
	}
}

function hideCollidedSelects(obj)
{
	if (isIE6())
	{
		var selectArray = document.getElementsByTagName('select');
		for (var i=0; i<selectArray.length; i++)
		{
			var selectElt = selectArray[i];
			
			if(!areAllParentsVisible(selectElt))
			{
			    continue;
			}
			
			if (detectCollision(obj, selectElt))
			{
			    if(!selectElt.style.previousVisibility)
			    {
				    selectElt.style.previousVisibility = new Array();
				    selectElt.style.previousVisibilityObjId = new Array();
				}
				selectElt.style.previousVisibility.push(selectElt.style.visibility);
				selectElt.style.previousVisibilityObjId.push(obj.id);
				selectElt.style.visibility = 'hidden';
			}
			else if (selectElt.style.previousVisibility 
				    && selectElt.style.previousVisibility.length>0
				    && selectElt.style.previousVisibilityObjId[selectElt.style.previousVisibilityObjId.length-1] == obj.id)
			{
		        selectElt.style.visibility = selectElt.style.previousVisibility.pop();
                selectElt.style.previousVisibilityObjId.pop();
			}
		}
    }
}


function areAllParentsVisible(obj)
{
    if(obj && obj.parentNode && obj.parentNode.nodeType != 9)
    {
        var parentNode = obj.parentNode;
        
        var objectCurrentStyle;
        
        if (isIE()) //IE
        {
			objectCurrentStyle = parentNode.currentStyle;
        }
        else // FF
        {
			objectCurrentStyle = window.getComputedStyle(parentNode, null);
        }
        
        if(objectCurrentStyle.visibility == 'hidden' || objectCurrentStyle.display == 'none')
        {
            return false;
        }
        else if(parentNode.parentNode)
        {
            return areAllParentsVisible(parentNode.parentNode);
        }
    }
    return true;
}

function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure)
{
	var cookie_string = name + "=" + escape (value);

	if (exp_y)
	{
		var expires = new Date (exp_y, exp_m, exp_d);
		cookie_string += "; expires=" + expires.toGMTString();
	}

	if (path)
	cookie_string += "; path=" + escape (path);

	if (domain)
	cookie_string += "; domain=" + escape (domain);

	if (secure)
	cookie_string += "; secure";

	document.cookie = cookie_string;
}

function get_cookie(cookie_name)
{
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if(results)
		return (unescape(results[2]));
	else
		return null;
}