//**************************************************************************************************
//	QUERYSTRING RETRIEVAL & STORAGE
//
//		Creates an array of all querystrings passed
//		to the page for easy access by any script.
//
//		**  This should probably stay at the top, **
//		**   as other functions may access this   **
//**************************************************
var pgParams = new Array();	//IMPORTANT! This is where the params are stored

// no 'Ready' function since it doesn't need to wait for the DOM
var qString = window.location.search.substring(1);
var qParams = qString.split('&');
for (var i = 0; i < qParams.length; i++) {
	var eq = qParams[i].indexOf('=');
	if (eq > 0) {
		var key = qParams[i].substring(0,eq);
		var val = qParams[i].substring(eq+1);
		pgParams[key] = val;	//this is where the keys are assembled into the array
	}
}

//**************************************************************************************************
//	QUICK HTML-ENCODING
//
//		performs basic HTML encoding for text passed into XML docs
//*************************************************
function ampEncode(txt){
	var reAmp = new RegExp("&","gi");
	return txt.replace(reAmp, "&amp;");
}

//**************************************************************************************************
//	AUTO PRINT
//
//		Will automatically print page if URL parameter
//		'print=auto' is passed.
//*************************************************
function readyAutoPrint(){
	if (pgParams['print'] == 'auto') {
		window.print();
	}
}

//**************************************************************************************************
//	POPOVER WINDOW FUNCTIONS
//
//		Opens a "popover" window and loads a remote
//		page into it. These tend to be complex.
//*************************************************

//	fixed-size popover READY function
function readyPopWin(){
	$("a[rel='pop']").click(function (e){
		e.preventDefault();
		$.modal(this.href + " #content > *", {
			containerId: 'popWin',
			onOpen: modalOpenPop,
			onClose: modalClosePop,
			append: 'div#content'
		});
		$("#modalOverlay").click(function() {
			$.modal.close();
		});
	});
}

//	auto-sized popover READY function
function readyPopWinAuto(){
	$("a[rel='popAuto']").click(function (e){
		e.preventDefault();
		$.modal(this.href + " #content > *", {
			containerId: 'popWinAuto',
			onOpen: modalOpenPop,
			onClose: modalClosePop,
			append: 'div#content'
		});
		$("#modalOverlay").click(function() {
			$.modal.close();
		});
	});
}


// survey pop up function
function surveyPop(){
		$.modal("/content/modals/survey.asp" + " #content > *", {
			containerId: 'popWinAuto',
			onOpen: modalOpenPop,
			onClose: modalClosePop,
			append: 'div#content'
		});
		$("#modalOverlay").click(function() {
			$.modal.close();
		});
}

//	Access Your Accounts window
function readyAccess () {
	$("a[rel='access']").click(function (e){
		e.preventDefault();
		$.modal(this.href + " #content > *", {
			containerId: 'accessModal',
			onOpen: modalOpenPop,
			onClose: modalClosePop,
			append: 'div#content'
		});
		$("#modalOverlay").click(function() {
			$.modal.close();
		});
	});
}

//	Offsite Links Window
function readyOffsite () {
	$("a[rel='offsite']").click(function (e){
		e.preventDefault();
		var safeRef = encodeURIComponent(this.href);	//this must be done to ensure special characters
														//are passed safely through the querystring
		$.modal("/content/modals/offsite/?offsite=" + safeRef, {
			containerId: 'exitModal',
			onOpen: modalOpenPop,
			onClose: modalClosePop,
			append: 'div#content'
		});
		$("#modalOverlay").click(function() {
			$.modal.close();
		});
	});
}

//*************************************************
//	popover OPEN function
function modalOpenPop(dialog){
	var getURL = dialog.data.text();		//get the url to load out of the dialog object
	dialog.data.empty();					//clear the data div
	dialog.container.prepend("<h1 id='modalTitle'>Loading...</h1>");	//generate temporary title
	
	dialog.overlay.fadeIn(200, function () {
		dialog.container.show("puff", { percent: 120 }, 300, function () {
			
			//*************************************************
				//LOAD the destination page
			dialog.data.load(getURL, {"sslOver": 1}, function(){
				
				dialog.data.find("#disclosure").siblings().replaceWith("");		//find if it's a disclosure, and trim surrounding content
				dialog.data.find("#popContent").siblings().replaceWith("");		//find if it's a disclosure, and trim surrounding content
				
				var $title = dialog.container.find("#modalTitle");		//find the temporary title h1, jQuery object
				var $heading = dialog.data.find("h1:first");			//find the first h1 in the loaded content, jQuery object
				var headText;	//hold the new title text
				
				//*************************************************
					//Get the title for the modal window
				if ($heading.is("h1")) {			//if an h1 was found,
					headText = $heading.html();		//set headText to its contents
					
					if ($heading.parent().is("div.modalData")) {	//if the found h1 was a direct child of the loaded content,
						$heading.replaceWith("");					//remove it from the content to avoid redundancy
					}
				} else {
					headText = "&nbsp;";	//if no h1 found, title will be blank
				}
				
				//*************************************************
					//Add close events to content
				dialog.data.find(".modalClose").click(function (e) {
					e.preventDefault();
					modalClosePop(dialog);
				});
				
				//*************************************************
					//Browser-specific content functions
				if ($.browser.msie) {
					//*************************************************
						//INTERNET EXPLORER
					
					$title.html(headText);		//swap titles, no animation because IE hates that
					dialog.container.find("a.modalCloseImg").hover(function(){		//this covers the old "hover" problem that IE has
						$(this).addClass("modalCloseHover");
					}, function(){
						$(this).removeClass("modalCloseHover");
					});
					dialog.data.slideDown({		//much more complicated data reveal
						duration: 500,
						easing: "easeInOutQuad",
						complete: function(){
							if (this.scrollHeight > this.offsetHeight) {	//if the content is larger than the container,
								$(this).animate({							//adjust the container to properly fit scrollbars
									paddingRight: "+=10px",					//(all other browsers do this automatically)
									width: "-=10px"
								}, 100);
							}
						}
					});
				} else {				
					//*************************************************
						//EVERYONE ELSE
					
					$title.animate({ opacity: 0 }, 100, function(){		//fade out the 'Loading' heading,
						$(this).html(headText).animate({ opacity: 100 }, 100);	//update it and fade it back in
					});
					dialog.data.slideDown(500, "easeInOutQuad");	//reveal data container
				}
			});
		});
	});
}

//*************************************************
//	popover CLOSE function
function modalClosePop(dialog){
	dialog.data.animate({
		height: 0,
		paddingTop: 0,
		paddingBottom: 0
	}, 300, "easeInOutQuad", function(){
		dialog.data.hide();//empty();
		dialog.container.hide("puff", { percent: 120 }, 200, function () {
			dialog.overlay.fadeOut(200, function () {
				$.modal.close();
			});
		});
	});
}

//**************************************************************************************************
//	Table Striping & Row Hovering
function readyTableStripe () {
	$("#content table.compare:not(.lefty)").each(function () {
		var $tr = $(this).find("tr:not(.topHeader, .tableFooter)");
		if ($tr.length > 2) {
			$tr.filter(":even").addClass("row-even");
			$tr.filter(":odd").addClass("row-odd");
		}
		
	});
	$(".tableHover").each(function() {
		var $td = $(this).find("td");							  
		$td.hover(function () {
			$(this).addClass("row-hover");
		},function () {
			$(this).removeClass("row-hover");
		});
	});
}


//**************************************************************************************************
//	Top Navigation dropdowns
function readyDropDowns () {
	//$("#nav-one").empty().load("/content/dropdowns.asp #nav-one > li", function () {
		$("#nav-one > li").hover(
			function () {
				$(this).addClass("sfHover");
				$("ul", this).bgiframe();
			}, 
			function () {
				$(this).removeClass("sfHover");
			} 
		);
	//});
}

//**************************************************************************************************
//	Tabs
function readyTabs () {
	var hashTab = window.location.hash;
	var $tabBox = $("#tabBox");
	
	if ((hashTab.length > 0) && ($("#tabBox").find("a[href=" + hashTab + "]").length > 0)) {
		//alert(hashTab);
		$tabBox.show().children("ul").tabs().tabs("select", hashTab);
	} else {
		$tabBox.show().children("ul").tabs();
	}
}


//**************************************************************************************************
//	clueTips
function readyClueTip () {
	$("span.tip").attr("title", function(){
		return (this.innerHTML + "|" + this.title);
	}).css({borderBottom: '1px dotted #666'}).cluetip({
		splitTitle: '|',
		positionBy: 'mouse',
		width: 300,
		leftOffset: 30,
		cluetipClass: 'jtip'
	});
	$("span.qtip").attr("title", function(){	/* developer comment tooltips */
		return ("Developer Question/Comment:|" + this.title);
	}).css({borderBottom: '1px dotted #666', backgroundColor: '#FF0000'}).cluetip({
		splitTitle: '|',
		positionBy: 'mouse',
		width: 400,
		leftOffset: 30,
		cluetipClass: 'jtip'
	});
}

//**************************************************************************************************
//	FAQs

	////////////////////////////////////////////////////////////
	//	eliminates child margins for an element to be animated
	$.fn.safeMargins = function() {
		
		//grab first and last child
		var $firstChild = $(this).children(":first-child");
		var $lastChild = $(this).children(":last-child");
		
		//get their heights
		firstChildHeight = $firstChild.height();
		lastChildHeight = $lastChild.height();
		
		//kill their margins and explicitly set heights
		$firstChild.css({
			marginTop: 0,
			height: firstChildHeight
		});
		
		$lastChild.css({
			marginBottom: 0,
			paddingBottom: 12,
			height: lastChildHeight
		});
	
		return this;
	};

	////////////////////////////////////////////////////////////
	//	THE FAQ READY FUNCTION
	function readyFaq() {
		$("dl.faq").each(function(){
			$(this).children("dt")
				.css({cursor: "pointer"})
				.each(function(){
					$(this)
						.click(function(){
							var $ddAnswer = $(this).next("dd");
							//var $bulletSpan = $(this).find("span.faqBullet");
							
							if ($ddAnswer.is(":hidden")) {
								$(this).addClass("expanded");
								//$bulletSpan.html("&ndash;&nbsp;");
								$ddAnswer.slideDown({
									duration: 500,
									method: "easeInOutQuad"
								});
							} else {
								$(this).removeClass("expanded");
								//$bulletSpan.html("+&nbsp;")
								$ddAnswer.slideUp({
									duration: 500,
									method: "easeInOutQuad"
								});
							}
						})
						//.prepend("<span class='faqBullet'>+&nbsp;</span>")	//write in a span for text bullets
						.hover(function(){		//apply the hover behavior
								$(this).addClass("faqHover");
							}, function(){
								$(this).removeClass("faqHover");	
						});
				});
		
			$("<a class='btn1small faqExpand' href='#'>Expand All</a>")	//write the "expand all/collapse all" button
				.toggle(function(){
						///////////	EXPAND ALL	///////////
						$(this).next("dl.faq")
							.find("dt")
								.addClass("expanded")
								.end()
							.find("dd")				//expand all answers
								.slideDown({
									duration: 500,
									method: "easeInOutQuad"
								});
						$(this).text("Collapse All");	//change text for next click
					},function(){
					////////////	COLLAPSE ALL	///////////
						$(this).next("dl.faq")
							.find("dt")
								.removeClass("expanded")
								.end()
							.find("dd")				//collapse all answers
								.slideUp({
									duration: 500,
									method: "easeInOutQuad"
								});
						$(this).text("Expand All");		//change text for next click
				})
				.insertBefore(this);	//insert the button before the faq
		
			$(this).children("dd")
				.each(function(){
					$(this)
						.safeMargins()	//fix margins for non-ie6 browsers for smooth animation
						.hide();	//hide the answers
				});
		});
	}

/*	OLD FAQ FUNCTION, PROBABLY NOT USED ANYWHERE
function readyFaq(){
	$("#content ul.faq li:has(:header)").each(function(){
		var $kids = $(this).children(":not(:header:first)").wrapAll("<div style='padding-left:12px'></div>").parent();	//wrap child elements in a div for better animation
		var $head = $(this).children(":header:first");
		
		$kids.hide();	//hide child elements
		$head.css({cursor: "pointer", textDecoration: "underline"})		//make images look like links
			.toggle(function(){				//add hide/reveal effect to child elements
				$kids.slideDown(200);
			}, function(){
				$kids.slideUp(200);
			})
			.hover(function(){			//add hover effect for 'pseudo-link' heading
				$(this).css({textDecoration: "none"});
			}, function(){
				$(this).css({textDecoration: "underline"});
		});
	});
}
*/


//**************************************************************************************************
//	CONTENT DIV FIX
//		adds an empty content div to any page that doesn't have one, necessary for modal windows and the PDF script
function readyContentFix(){
	if ($("div#content").size() < 1) {
			$("#centerCol").append("<div id='content'></div>");
	}
}


//**************************************************************************************************
//	Append PDF text links
function readyPDF(){
	var $pdfLinks = $("a[href$='.PDF'],a[href$='.pdf']");
	
	if ($pdfLinks.size() > 0) {
		
		/* PDF labels */
		$pdfLinks
			
			.attr("target","_blank").not(":has(img)")
				.append("<sup style='text-decoration:none;'>&nbsp;[PDF]</sup>");
		
		/*Reader Download Link*/
		$("#content")
				.append("<p id='acrobat'>To view or print a PDF file, you must have Adobe<sup>&reg;</sup> Reader<sup>&reg;</sup>. <a href='http://get.adobe.com/reader/' rel='offsite'>Download the latest version of Adobe<sup>&reg;</sup> Reader<sup>&reg;</sup></a></p>");
	}
	//$("a[href$='PDF'],a[href$='pdf']").not(":has(img)").append("<sup style='text-decoration:none;'>&nbsp;[PDF]</sup>");
}

//**************************************************************************************************
//	BREADCRUMB FIX
//
//		Trims spans from the breadcrumb trail if it wraps
//*************************************************
function readyCrumbTrim(){
	var safety = 0;	//to avoid infinite loops
	
	while (($("#breadCrumbs").height() > 40) && (safety < 10)) {
		$("#breadCrumbs span:nth-child(2)").remove();
		safety++;
	}
}

//**************************************************************************************************
//	Remove self-referential Services links
function readyServices(){
	var docPath = location.pathname;

	if (docPath.match("default.asp")) {		//remove "default.asp" if it appears
		var slicePoint = docPath.lastIndexOf("/");
		docPath = docPath.slice(0,slicePoint);
	}

	$("div.services li:has(a[@href$=" + docPath +"])").hide();
}

//**************************************************************************************************
//**************************************************************************************************
//	Execute ALL jQuery 'ready' functions
//**************************************************************************************************
//**************************************************************************************************
$(function () {
	readyContentFix();	//adds a content div to centerCol for any page that doesn't have one, critical for many other functions
	readyServices();
	readyDropDowns();
	readyCrumbTrim();
	readyTableStripe();
	readyClueTip();
	readyPDF();			//must come before readyOffsite, as this function will write an offsite link into the page
	readyAccess();
	readyOffsite();
	readyPopWin();
	readyPopWinAuto();
	readyFaq();
	readyTabs();		//this should be almost last, so anything within the tabs is formatted properly before being hidden
	readyAutoPrint();	//this should be last in the list, so the document is fully assembled before printing
});

//**************************************************************************************************
//	Link color-change test, runs off a URL parameter
$(function(){
	if (pgParams['change'] == 'green') {
		$("#content a")
		.filter(function(){
			var thisColor = $(this).css("color");
			var filterBool = true;
			var re = /rgb\(((255(,\s*)255(,\s*)255)|(51(,\s*)51(,\s*)51)|(102(,\s*)102(,\s*)102))\)/;
			
			return (!thisColor.match(re));
			
		})
		.css("color", "#006342");
	}
})

//**************************************************************************************************
//	Change disclaimer OL to image-based superscripts
$(function(){
	$("#disclaimers ol li").each(function(i){
		var shifter = (i * (-500));		//to calculate bg image offset - bg is 12px x 10,000px
		$(this).css("backgroundPosition", "0px " + shifter + "px");
	});
})

//**************************************************************************************************
//	Adds Numbers to any element with the class Numbered
var faqnum = 1;
$(function(){
	$(".numbered").each(function(i){	
		$(this).prepend(faqnum + ".) ")
		faqnum++
	});
})
//**************************************************************************************************
//	Add Print functionality to 'print this page' buttons
//					rewrite this later to write-in the link itself
$(function(){
	$("#printButton").click(function(e){
		e.preventDefault();
		window.print();
	});
})

//**************************************************************************************************
//	IMAGE ROTATOR
//		throw images in a div with class imgRotator, and this turns it into a fading rotation
//		req: jquery.innerfade.js
$(function(){
	$("div.imgRotator").each(function(){
		var heightMax = 0;	//used for finding the tallest image
		
		$(this)
			.show()	//show the hidden imgRotator div (hidden in CSS)
			.find("img")	//find images
				.each(function(){	//test all images against the current max, update max if necessry
					heightMax = Math.max(heightMax, this.height);
				})
				.end()	//end find images, return to original $(this) collection
			.innerfade({	//apply the fade
				timeout: 3000,
				speed: 1500,
				containerheight: heightMax
			});
	});
});


//	IE background-image flicker bug fix

try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


/*
 *
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Version 1.0
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 * $LastChangedDate$
 * $Rev$
 */
 
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(null, callback);
 *
 */


