/*
	Who:    Lampo Web Team
	When: Feb 2003
	Why: All Javascript Functions common to this website
*/
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
var verNum;
var strUserAgent = navigator.userAgent.toLowerCase();
var isNS = isIE = isIE5 = isIE55 = isIE6 = isIE7 = 0;
var isNS4  = (navigator.appName == 'Netscape' && parseInt(navigator.appVersion) == 4)?1:0;
var isNS6  = (document.getElementById)?1:0;
var isIE4  = (document.all)?1:0;
var isMAC  = (strUserAgent.indexOf('mac') >= 0)?1:0;
var isSAF  = (strUserAgent.indexOf('safari') >= 0)?1:0;
var isKONQ = (strUserAgent.indexOf('konqueror') >= 0)?1:0;
var isKHT  = (isSAF || isKONQ)?1:0;
var isOPR  = (strUserAgent.indexOf('opera') >= 0)?1:0;
var isOPR7 = (isOPR && document.createTextNode)?1:0;

if(isOPR)
{
	isNS4 = isNS6 = 0;
	if(!isOPR7) isIE4 = 0;
}

var isIEMac = ((isIE4 && isMAC) && !(isKHT || isOPR))?1:0;

if(isIE4 && !isOPR)
{
	if((verNum = strUserAgent.match(/msie (\d\.\d+)\.*/i)) && (verNum = parseFloat(verNum[1])) >= 5.0)
	{
		isNS6=0;
		isIE4=0;
		if(verNum == 5.0)
			isIE5=1;
		if(verNum == 5.5)
			isIE55=1;
		else if(verNum == 6.0)
			isIE6=1;
		else if(verNum == 7.0)
			isIE7=1;
	}

	if(isNS6)
		isIE = isIE4 = isIE5 = isIE55 = isIE6 = isIE7 = 0;
}

isNS = (isNS4 || isNS6)?1:0;
isIE = (isIE4 || isIE5 || isIE55 || isIE6 || isIE7)?1:0;

// alert('isIE='+isIE+'\n' + 'isIE4='+isIE4+'\n' + 'isIE5='+isIE5+'\n' + 'isIE55='+isIE55+'\n' + 'isIE6='+isIE6+'\n' + 'isIE7='+isIE7+'\n');

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
if (!isIE)
{
	if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
	{
		HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode)
		{
			switch (where)
			{
			case 'beforeBegin':
				this.parentNode.insertBefore(parsedNode,this)
				break;
			case 'afterBegin':
				this.insertBefore(parsedNode,this.firstChild);
				break;
			case 'beforeEnd':
				this.appendChild(parsedNode);
				break;
			case 'afterEnd':
				if (this.nextSibling)
					this.parentNode.insertBefore(parsedNode,this.nextSibling);
				else
					this.parentNode.appendChild(parsedNode);
				break;
			}
		}

		HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
		{
			var r = this.ownerDocument.createRange();
			r.setStartBefore(this);
			var parsedHTML = r.createContextualFragment(htmlStr);
			this.insertAdjacentElement(where,parsedHTML)
		}

		HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
		{
			var parsedText = document.createTextNode(txtStr)
			this.insertAdjacentElement(where,parsedText)
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////


/***************************************************************
  	By: Leon Oosterwijk
	When: 2002
	Why: Find first form field that is a text field and
		 give focus to this element
****************************************************************/
function findFirstField()
{
	var intForm = -1;
	var intElement = -1;
	for (i = 0; i < document.forms.length && intForm == -1; i++)
	{
//		alert(document.forms[i].name);
//		alert(document.forms[i].name.indexOf('skip'));
//		if (document.forms[i].name.indexOf('skip') == -1)
//		{
			for (j = 0; j < document.forms[i].elements.length && intElement == -1; j++)
			{
				// we don't want to focus if the field is not a text field,
				// is hidden, disabled or a cold fusion debugging field...
				if (document.forms[i].elements[j].type == 'text' &&
					document.forms[i].elements[j].style.visibility != "hidden" &&
					document.forms[i].elements[j].disabled == false &&
					document.forms[i].elements[j].name.substring(0,3) != "cf_")
				{
					intForm = i;
					intElement = j;
				}
			}
//		}
	}

	if (intForm > -1 && intElement > -1)
	{
		document.forms[intForm].elements[intElement].focus();
	}
}

/***************************************************************/
/***************************************************************/
function MM_openBrWindow(theURL, winName, features)
{
	window.open(theURL, winName, features);
}
/***************************************************************/
/***************************************************************/
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
/***************************************************************/
/***************************************************************/
		function MM_findObj(n, d) { //v4.01
  			var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
   			d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  			if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  			for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  			if(!x && d.getElementById) x=d.getElementById(n); return x;
		}
/***************************************************************/
/***************************************************************/
	function MM_swapImage() { //v3.0
  			var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   			if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}	
/***************************************************************/
/***************************************************************/
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
/***************************************************************
	This function is a toggle for the display of objElement
	(usually a span or div id)
****************************************************************/
function ToggleDisplayByStatus(objElement,status)
{
	if (arguments[3] !== '')
		{styleType = 'display';}
	document.getElementById(objElement).style[styleType] = status;
}


/***************************************************************
	This function is a toggle for the display of objElement
	(usually a span or div id)
****************************************************************/
function ToggleDisplay(objElement)
{
	if (document.getElementById(objElement).style.display == 'none')
		document.getElementById(objElement).style.display = 'inline';
	else
		document.getElementById(objElement).style.display = 'none';
}

/***************************************************************
  	This function hides a submit button when it is clicked to
	help reduce duplicate leads and emails when forms are
	submitted. Usage: hideMeButton(this);
****************************************************************/
function hideMyButton(me)
{
	me.style.visibility="hidden";
}


/***************************************************************
	Name: getElementsByClassName
	Author: Jonathan Snook, http://www.snook.ca/jonathan
			Add-ons by Robert Nyman, http://www.robertnyman.com
	Date: April, 2006
	Description: Returns an array of HTML elements in a document
				 that are assigned a specific CSS class.
	Usage: --To get all a elements in the document with a "info-links" class
				getElementsByClassName(document, "a", "info-links");
		   --To get all div elements within the element named "container", with a "col" and a "left" class
				getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]);
****************************************************************/
function getElementsByClassName(oElm, strTagName, oClassNames)
{
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object")
	{
		for(var i=0; i<oClassNames.length; i++)
		{
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else
	{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++)
	{
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++)
		{
			if(!arrRegExpClassNames[k].test(oElement.className))
			{
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll)
		{
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

// Array support for the push method in IE 5
Array.prototype.push = ArrayPush;
function ArrayPush(value)
{
	this[this.length] = value;
}

/***************************************************************
	Name: TabIndexManager Object
	Author: Chris Simeone
	Date: April, 2006
	Description: TabIndexManager provides tabIndex data for
	dynamically setting HTML elements tabIndex property.
	Usage:	tim = new TabIndexManager();
			document.forms[fi].elements[ei].tabIndex = tim.getNextTabIndex();
 ***************************************************************/
function TabIndexManager()
{
	this.initTabIndex = 100;
	this.currTabIndex = 0;
	this.incTabIndex = 10;

	////////////////////////////////////////////
	////////////////////////////////////////////
	this.getNextTabIndex = function()
	{
		if(this.currTabIndex == 0)
			this.currTabIndex += this.initTabIndex;
		else
			this.currTabIndex += this.incTabIndex;

		return this.currTabIndex;
	}

	/////////////////////////////////////////////
	/////////////////////////////////////////////
	this.setInitialTabIndex = function(nTabIndex)
	{
		this.initTabIndex = nTabIndex;
	}
	/////////////////////////////////////////////
	this.getInitialTabIndex = function()
	{
		return this.initTabIndex;
	}

	/////////////////////////////////////////////
	////////////////////////////////////////////
	this.setTabIncrements = function(nTabIncr)
	{
		this.incTabIndex = nTabIncr;
	}
	////////////////////////////////////////////
	this.getTabIncrements = function()
	{
		return this.incTabIndex;
	}

	////////////////////////////////////////////
	////////////////////////////////////////////
	this.getCurrentTabIndex = function()
	{
		return this.currTabIndex;
	}
}

/***************************************************************
	Name: initTabIndexes()
	Author: Chris Simeone
	Date: April, 2006
	Description: Uses the TabIndexManager to dynamically set
	the tabIndex property of all HTML elements on a form and then
	sets the focus to the first HTML element on the form;
 ***************************************************************/
function initTabIndexes()
{
	var tim = new TabIndexManager();
	var fi = 0;
	var ei = 0;
	for (fi=0; fi<document.forms.length; fi++)
	{
		for (ei=0; ei<document.forms[fi].elements.length; ei++)
		{
			if (document.forms[fi].elements[ei].style.visibility != "hidden" &&
				document.forms[fi].elements[ei].disabled == false &&
				document.forms[fi].elements[ei].name.substring(0,3) != "cf_")
			{
				document.forms[fi].elements[ei].tabIndex = tim.getNextTabIndex();
			}
		}

		if(fi == 0)
		{
			findFirstField();
		}
	}
}
/***************************************************************
	Name: CharCounter(textfield,maxlength{,counterfield})
	Author: Internet - Michael Cole / Henry Rendleman III
	Date: July, 2007
	Description: Use to set the maxium number of characters that
	the user can enter in a input textarea box.
	Note: Is used with a counterfield to show user the character
	count down. Can be removed from view by using a hidden field.
	Example: <textarea name="comment" rows="3" cols="65" 
	onKeyDown="charCounter(this.form.comment,this.form.charlen,200);" 
	onKeyUp="charCounter(this.form.comment,this.form.charlen,200);">
	</textarea><br>Max. number of characters left: <input readonly type=text
	 name=charlen size=3 maxlength=3 value="200">
 ***************************************************************/
 function charCounter(textfield,maxlength,counterfield) 
 {
 	if (document.getElementById(textfield).value.length > maxlength) 
 	{
		document.getElementById(textfield).value = document.getElementById(textfield).value.substring(0, maxlength);
		alert('Your input has exceded the maximum allowed length!  It will be cut back!');
	}
	else
	{
		if(arguments.length >= 3)
			document.getElementById(counterfield).value = maxlength - document.getElementById(textfield).value.length;
	}
 }

/***************************************************************
	Name: Left(), Right()
	Author: Chris Simeone
	Date: April, 2006
	Description: Use to get the leftmost of right most substring.
	Note that Javascript does not provide Left() and Right()
	functions. Also note the first letter of these functions are
	uppercase.
	EDITED: by Troy to allow negative values to be passed in for
	length
 ***************************************************************/
 function Left(str, n)
{
	if (n <= 0) {
		var iLen = String(str).length;
		return String(str).substring(0, iLen + n);
	}
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0,n);
}

function Right(str, n)
{
	if (n <= 0) {
		var iLen = String(str).length;
		return String(str).substring(iLen - (iLen + n));
	}
	else if (n > String(str).length)
		return str;
	else {
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}

/*********************************************************************************************************
These functions make it possible to move things around in a list box and move from one list box to another
this function moves the item up or down in the box -true sends it up and false sends it down
usage move(this.form,true,'listBoxName')
**********************************************************************************************************/
function move(f,bDir,strCtrlSource) {
	var el = f.elements[strCtrlSource]
	var idx = el.selectedIndex
	if (idx==-1)
		alert("You must first select the item to reorder.")
	else {
		var nxidx = idx+( bDir? -1 : 1)
		if (nxidx<0) nxidx=el.length-1
		if (nxidx>=el.length) nxidx=0
		var oldVal = el[idx].value
		var oldText = el[idx].text
		el[idx].value = el[nxidx].value
		el[idx].text = el[nxidx].text
		el[nxidx].value = oldVal
		el[nxidx].text = oldText
		el.selectedIndex = nxidx
	}
}

//this function selects all the items in the list box so call it when the submit button is clicked if you want all items
//usage selectAllOptions('listBoxId')
function selectAllOptions(listBoxId) {
	var ref = document.getElementById(listBoxId);
	for(i=0; i<ref.options.length; i++)
	ref.options[i].selected = true;
}

//this function will display the text of an itemitem in another location, like a text box
//usage showItemInBox(this.form,'strCtrlSource','strCtrlTarget')
function showItemInBox(f,strCtrlSource,strCtrlTarget){
	var el = f.elements[strCtrlSource]
	var idx = el.selectedIndex
	document.getElementById(strCtrlTarget).value = el[idx].text
}

//this function will move and item from one list box to another
//usage showItemInBox(this.form,strCtrlSource,strCtrlTarget)
function MoveItem(ctrlSource, ctrlTarget) {

	var Source = document.getElementById(ctrlSource);
	var Target = document.getElementById(ctrlTarget);

	if ((Source != null) && (Target != null)) {
		while ( Source.options.selectedIndex >= 0 ) {
			var newOption = new Option(); // Create a new instance of ListItem
			newOption.text = Source.options[Source.options.selectedIndex].text;
			newOption.value = Source.options[Source.options.selectedIndex].value;
			newOption.id = Source.options[Source.options.selectedIndex].id;
			
			Target.options[Target.length] = newOption; //Append the item in Target
			Source.remove(Source.options.selectedIndex);  //Remove the item from Source
		}
	}
}

//this is the end of the listbox moving stuff
//*******************************************************************************************

/***************************************************************
	Name:		 IsNumeric(strString)
	Author:		 Scott Coldwell
	Date:		 June 2006
	Description: Determine if a string contains ONLY numeric
				 characters. Empty string is not considered
				 numeric.
 ***************************************************************/
function isNumeric(strString)
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

/***************************************************************
	Name: setBookmark( title, url)
	Author: Jon Wolski
	Date: July, 2006
	Description: Use to set a bookmark usually pending the
	user's confirmation.  Works in most browsers.
 ***************************************************************/

function setBookmark( title, url) {
	if (window.AddFavorite)
		window.AddFavorite(url, title);
	else if (window.external)
		window.external.AddFavorite(url, title);
	else if (window.sidebar && window.sidebar.addPanel)
		window.sidebar.addPanel( title, url, "" );
	else
		alert("Sorry, the script could not automatically create the bookmark.  Please do so manually (Ctrl+D in most browsers).");
}

/***************************************************************
	Name: fire_quickfinder( select_input )
	Author: unknown
	Date: Aug 2006
	Description: Fire event from a drop down box
 ***************************************************************/
function fire_quickfinder(z) {
	if(z.options[z.selectedIndex].value == "0")
	{
		alert("Please Make a Selection");
	}
	else if (z.options[z.selectedIndex].value != "0")
	{
		//window.location = document.quickfinder.qfselect;
		window.location = (z.options[z.selectedIndex].value);
	}
	else
	{
		z.form.submit();
	}
}
////******************************************
///This function reloads parent page and closes open page
////******************************************
function reloadParentNClose()
{
	opener.location.reload(true);
    self.close();
}

 /***************************************************************
	Name: selectAll( )
	Author: Dunno - Brian Brown put it in
	Date: Aug, 2006 
	Description: Checks all check boxes in a list.
	
	What the initial check box should look like.
	<form name="act_form" method="" action="">
	<input type="checkbox" title="select all the checkboxes" value="asel" onclick="if (this.value == 'asel'){selectAll();this.value='dsel';this.title='deselect all the checkboxes';}else{deselectAll();this.value='asel';this.title='select all the checkboxes';}">
	</form>
	example - admin catool dsp_dashboard.cfm
 ***************************************************************/
 function selectAll(formName) {
 d = document[formName];
 for (i = 0; i < d.elements.length; i++) {
   if (d.elements[i].type == "checkbox") {
     d.elements[i].checked = true;
   }
 }
}

function deselectAll(formName) {
 d = document[formName];
 for (i = 0; i < d.elements.length; i++) {
   if (d.elements[i].type == "checkbox") {
     d.elements[i].checked = false;
   }
 }
}

/***************************************************************
	Name: 			fadeElements()
	Author: 		Troy Stauffer
	Date: 			October 2, 2006
	Description: 	Used to replace image buttons (or images for 
					that matter) with a "faded" version of the 
					image, to be named the same as the original 
					image with the number 2 at the end. 
					Ex: /images/button.jpg would be changed to 
					/images/button2.jpg 
					Also, the onClick property will be cleared 
					and the cursor type will be changed to 
					default in case the image is not an input of 
					type image but rather just an image with 
					onclick properties to make it button-like.
	Usage:			fadeElements(['fademe','fademetoo','fademeaswell'])
 ***************************************************************/
function fadeElements(array)
{
	for ( var i=0, len=array.length; i<len; ++i ){
		document.getElementById(array[i]).onclick = '';
		document.getElementById(array[i]).src = Left(document.getElementById(array[i]).src,-4) + '2' + Right(document.getElementById(array[i]).src,4);
		document.getElementById(array[i]).style.cursor = 'default';
	}
}

/***************************************************************
	Name: 			submitForm()
	Author: 		Troy Stauffer
	Date: 			October 3, 2006
	Description: 	Used to submit a form via a js event. Takes
					the form id and the name of the processing 
					event.
	Usage:			submitForm('frmToSubmit','processEvent')
 ***************************************************************/
function submitForm(formName,eventName)
{
	document.getElementById(formName).action='?event=' + eventName;
	document.getElementById(formName).submit();
}
// Collapsable Menus
		function showHideTable(theTable) 
	{
		if (document.FormBudget.income_amount.value > 0)
			{
					
				if (document.getElementById(theTable).style.display == 'none') 
					{ 
						document.getElementById(theTable).style.display = 'block'; 
					} 
				else 
					{ 
						document.getElementById(theTable).style.display = 'none'; 
					}
			
			}
		else
			{
				window.alert("You must enter an income amount before proceeding.")
			}
	}
	
	
		function HouseholdIncome(theTable)
	{
		if (document.FormHouseholdIncome.income_amount.value > 0)
			{
				document.FormHouseholdIncome.submit();
			}
		else
			{
				window.alert("You must enter your household income before proceeding.")
			}
	}
	
// budget functions
	function findPercent(amount) 
		{
		// returns the amount in the .99 format
		    fltIncome = document.FormBudget.income_amount.value;
			
			newAmount = (Math.floor(amount*100))/fltIncome;
			newAmount = roundPercent(newAmount,1);
			if (newAmount == 0)
				{
					newAmount = "";
				}
			return newAmount;
		}
	function roundPercent(amount,numberofdecimals)
		{
			decimals = numberofdecimals;
			roundedAmount = Math.round(amount*Math.pow(10,decimals))/Math.pow(10,decimals);
			return roundedAmount;
		}
	function stripStringToFloat(str)
		{
			myString = str;
			
			myRegExpC = /[^0-9\.]/g;
			myRegExpD = /[^0-9]/g;
			
			myString = str;
			
			newString = myString.replace(myRegExpC, "");
			
			stringLength = newString.length;
			slicePoint = newString.lastIndexOf(".");
			
			rightString = newString.slice(slicePoint,stringLength);
			leftString = newString.slice(0,slicePoint);
			
			leftString = leftString.replace(myRegExpD, "");
			
			newString = leftString.concat(rightString);
			
			return newString;
		}
	function updateBudget(inputName)
		{
			document.FormBudget.income_amount.value = stripStringToFloat(document.FormBudget.income_amount.value);
			document.IncomeTotal.income_total.value = roundPercent(document.FormBudget.income_amount.value,2);
			document.IncomeTotal.income_remaining.value = document.IncomeTotal.income_total.value;
			
			//we don't want certain fields to affect the totals so create a few regular expressions to search for
			myRegExpA = /_pct/;
			myRegExpB = /actual/;
			
			//find out how many sections there are
			for(i=0; i < document.ZeroBasedBar.elements.length; i++)
				{
					document.ZeroBasedBar.elements[i].value = 0;
				}
			//loop through all of the input fields in the form and update the associated percentages
			for(i=0; i < document.FormBudget.elements.length; i++)
				{
					if (document.FormBudget.elements[i].name.search(myRegExpA) > 0)
						{
							document.FormBudget.elements[i-1].value = stripStringToFloat(document.FormBudget.elements[i-1].value);
							
							newValue = findPercent(document.FormBudget.elements[i-1].value);
							document.FormBudget.elements[i].value = newValue;
							
							if (document.FormBudget.elements[i].name.search(myRegExpB) < 0)
								{
									// update the rightbar percentages
									CurrentSectionId = document.FormBudget.elements[i-1].name;
									myLength = CurrentSectionId.length;
									myLastIndex = (CurrentSectionId.lastIndexOf("_")) + 1;
									myCurrentSectionId = CurrentSectionId.substring(myLastIndex,myLength);
									a = Number(document.ZeroBasedBar.elements[myCurrentSectionId-1].value);
									b = newValue;
									document.ZeroBasedBar.elements[myCurrentSectionId-1].value = roundPercent(a + b, 1);
									// update the rightbar totals
									a = Number(document.IncomeTotal.income_remaining.value);
									b = Number(document.FormBudget.elements[i-1].value);
									document.IncomeTotal.income_remaining.value = roundPercent(a - b, 2);
								}
						}
				}
			
			document.IncomeTotal.income_total.value = "$" + document.IncomeTotal.income_total.value.toString();
			document.IncomeTotal.income_remaining.value = "$" + document.IncomeTotal.income_remaining.value.toString();
			
			//submit the form (204)
			document.FormBudget.submit();
			
			//var strInput = DWRUtil.getValue(inputName);
			//strInputNameValue = inputName && "YY" && strInput;
			//DWREngine._execute(_cfscriptLocation, null, 'updateBudget', strInputNameValue);
		}

// --------------------------------------- //
// Flash Detection Functions By Macromedia //
// --------------------------------------- //

	// Detect Client Browser type
	var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
	var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
	var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
	jsVersion = 1.1;
	// JavaScript helper required to detect Flash Player PlugIn version information
	function JSGetSwfVer(i){
		// NS/Opera version >= 3 check for Flash plugin in plugin array
		if (navigator.plugins != null && navigator.plugins.length > 0) {
			if (navigator.plugins["Shockwave Flash"]) {
				var flashDescription = "";
				for (j=0; j < navigator.plugins.length; j++){
					if (navigator.plugins[j].name == "Shockwave Flash" && navigator.plugins[j].description > flashDescription){
						flashDescription = navigator.plugins[j].description;
					}
				}
				descArray = flashDescription.split(" ");
				tempArrayMajor = descArray[2].split(".");
				versionMajor = tempArrayMajor[0];
				versionMinor = tempArrayMajor[1];
				if ( descArray[3] != "" ) {
					tempArrayMinor = descArray[3].split("r");
				} else {
					tempArrayMinor = descArray[4].split("r");
				}
	      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
	            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
	      	} else {
				flashVer = -1;
			}
		}
		// MSN/WebTV 2.6 supports Flash 4
		else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
		// WebTV 2.5 supports Flash 3
		else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
		// older WebTV supports Flash 2
		else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
		// Can't detect in all other cases
		else {
			
			flashVer = -1;
		}
		return flashVer;
	} 
	// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
	function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) 
	{
	 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
	   	// loop backwards through the versions until we find the newest version	
		for (i=25;i>0;i--) {	
			if (isIE && isWin && !isOpera) {
				versionStr = VBGetSwfVer(i);
			} else {
				versionStr = JSGetSwfVer(i);		
			}
			if (versionStr == -1 ) { 
				return false;
			} else if (versionStr != 0) {
				if(isIE && isWin && !isOpera) {
					tempArray         = versionStr.split(" ");
					tempString        = tempArray[1];
					versionArray      = tempString .split(",");				
				} else {
					versionArray      = versionStr.split(".");
				}
				versionMajor      = versionArray[0];
				versionMinor      = versionArray[1];
				versionRevision   = versionArray[2];
				
				versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
				versionNum        = parseFloat(versionString);
	        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
				if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
					return true;
				} else {
					return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );	
				}
			}
		}	
	}

// --------------------------------------- //
//        Cookie Setting Functions         //
// --------------------------------------- //
	
	
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


function buildCookie(cookieString){
	var strCookie = getCookie("TourTracker") != null?getCookie("TourTracker"):"";
	var name = cookieString.substr(0, cookieString.indexOf("="));
	var value = cookieString.substr(cookieString.indexOf("=") + 1, cookieString.length );

	if (strCookie.length < 1) {
		strCookie = cookieString;
	} else {
		var location = strCookie.indexOf(name);
		if (location == -1){
			strCookie = strCookie + "," + cookieString;
		} else {
			strRegExp = name + "=[^,]*";
			replaceText = new RegExp(strRegExp);
			var currentString = strCookie.match(replaceText);
			currentString = currentString[0].substr(currentString[0].indexOf("=") + 1);
			currentString = currentString.substr(0,currentString.length);
			if (currentString != "finished"){
				strCookie = strCookie.replace(replaceText, cookieString);
			}
		}
	}
	setCookie("TourTracker", strCookie, "01 Jan 2050 00:00:00 GMT.");
}

function TourMain_DoFSCommand(command, args) {
  if (command == "setCookie") {
    buildCookie(args);
    getCookie("TourTracker");
  }
}

/* example: " 	asdf  ".trim() -> "asdf" */
String.prototype.trim = function() {
	return this.replace(/^\s*(\b.*\b|)\s*$/, '$1');
};

/* Cross-browser DOM (-emulated) */
function getElement (node, sID ) {
	return node.getElementById ? node.getElementById(sID) : node.all[sID];
}
function attachEventToDOMNode ( node, sEvent, fHandler ) {
	if (node.addEventListener) // DOM style
		node.addEventListener( sEvent, fHandler, false );
	else if (node.attachEvent) // IE style
		node.attachEvent( "on" + sEvent, fHandler );
}

/*******************************************************************************
* By: Jon Wolski <jon.wolski@daveramsey.com>                                   *
* Takes a URL to a stylesheet (can be relative or absolute).                   *
* If the stylesheet is not already linked, creates a link element in the head. *
* NOTE: This does not check for stylesheets imported in a style element.       *
*******************************************************************************/
function requireStyleSheet(sStyleSheetURL) {
	if (!isLinked(sStyleSheetURL))
		linkStyleSheet(sStyleSheetURL);
}

function isLinked(sStyleSheetURL) {
	var lstLinks = document.getElementsByTagName("link");
	for (i = lstLinks.length-1; i>0 ; i--) 
		if ( lstLinks.item(i).getAttribute("rel").trim().toLowerCase() == "stylesheet"
		  && resolveURL(lstLinks.item(i).getAttribute("href").trim()) == resolveURL(sStyleSheetURL))
			return true;
	return false;
}

function linkStyleSheet(sStyleSheetURL) {
	// create the element node
	var oLink = document.createElement("link");
	oLink.setAttribute("type", "text/css");
	oLink.setAttribute("rel",  "stylesheet");
	oLink.setAttribute("href", sStyleSheetURL);
	// attach the node to the document
	document.getElementsByTagName("head").item(0).appendChild(oLink);
}

/*********************************************************************
* By: Jon Wolski <jon.wolski@daveramsey.com>                         *
* Takes a relative URL or absolute URL                               *
* returns an absolute URL (including scheme, authority, path, etc. ) *
*********************************************************************/
function resolveURL(sURL) {
	/* use the browser's URL resolver */
	var anchor = document.createElement("a");
	anchor.setAttribute("href", sURL);
	return anchor.href;
}

function getXML(xmlNode)
{
  return xmlNode.innerHTML.replace(/"/g, "\%22")
}

/****************************************************************************
* By: Jon Wolski <jon.wolski@daveramsey.com>                                *
* Takes a String representation of a routing number                         *
* returns true if routingNumber is a valid routing number.  false otherwise *
****************************************************************************/
function isValidRoutingNumber(routingNumber) {
	var checkSum = 0;
	var checkSumFactors = [3,7,1,3,7,1,3,7,1];
	if (!routingNumber)
		return false;
	if (!/^[0-3][0-9]{8}$/.test(routingNumber))
		return false;
	// verify checksum
	// note: the coincidence of checkSumFactors.length === routingNumber.length is guaranteed by the regex check above.
	for (var i = 0; i < checkSumFactors.length; ++i)
		checkSum += checkSumFactors[i] * routingNumber.charAt(i);
	return checkSum % 10 === 0;
}
