if(jQuery) {
	jQuery.noConflict();
}

/* Ensure Array's indexOf function is defined in all browsers */
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
	if (fromIndex == null) {
		fromIndex = 0;
	} else if (fromIndex < 0) {
		fromIndex = Math.max(0, this.length + fromIndex);
	}
	for (var i = fromIndex, j = this.length; i < j; i++) {
		if (this[i] === obj)
			return i;
	}
	return -1;
  };
}


var url = window.location.href;
var protocol = url.substring(0, url.indexOf("/", 6) + 1);
var domain = url.substring(protocol.length, url.indexOf("/", 7));
var subdomain = domain.substring(0, domain.indexOf(".", 0));
var domainName = domain.substring(subdomain.length + 1, 999);

/* --------------------
 * Widget Use
 * --------------------*/
var widgetUse = widgetUse || [];
function widgetUsed(action, label) {
	var key = action + "|" + label;
	if(widgetUse.indexOf(key) == -1) {
		try {
			_gaq.push(['_trackEvent', 'Widget-Use', action, label]);
			widgetUse.push(key);
		} catch(err) {}
	}
}



jQuery(document).ready(function() {


	/* -----------------------------------------
	 * Whichever tab is active on document ready
	 * becomes the current site and UI elements
	 * are colored accordingly
	 * -----------------------------------------*/
	
	var currentSite = jQuery("#nav>ul>li.over");
	var currentSiteStyle = "corporate";
	currentSite.addClass("current");
	currentSiteSubNav = currentSite.children(".subnav");
	
	if(currentSiteSubNav.children("ul").children(".stones").length == 0) {
		var corporate = protocol + subdomain + '.guidestone.org/';
		currentSiteSubNav.children("ul").children("li").eq(0).before('<li class="stones"><a href="' + corporate + '"><img src="/~/media/8D1EE47B9D134F58A9AA1B315CC4A64D.ashx" width="39" height="20" hspace="7" vspace="3" alt="GuideStone Home" /></a></li>');
	}
	
	
	var navFloat = jQuery("#navFloat");
	
	
	// Set current site style based on the active tab.
	// If none is active, use corporate as the default.
	if(currentSite.length != 0) {
		var currentSiteName = currentSite.children("a:first-child").html().toLowerCase();
		if(currentSiteName.search("retirement") != -1) {
			currentSiteStyle = "retirement";
		} else if(currentSiteName.search("insurance") != -1) {
			currentSiteStyle = "insurance";
		} else if(currentSiteName.search("funds") != -1) {
			currentSiteStyle = "funds";
		} else if(currentSiteName.search("capital management") != -1) {
			currentSiteStyle = "capital-mgmt";
		} else if(currentSiteName.search("property") != -1) {
			currentSiteStyle = "property-casualty";
		} else if(currentSiteName.search("corporate") != -1) {
			currentSiteStyle = "corporate";
		} else {
			currentSiteStyle = "corporate";
		}
	}
	

	/* --------------------
	 * Site Navigation
	 * --------------------*/
	 
	var nav_delay = 800;
	var nav_delay_timer_L1;
	var nav_delay_timer_L2;
	var attached = true;
	 
	/* Top Level Navigation */
	jQuery("#nav").hover(
		function () {
			jQuery(this).addClass("over");
		},
		function () {
			clearTimeout(nav_delay_timer_L1);
			nav_delay_timer_L1 = setTimeout(function() {
				jQuery("#nav").removeClass("over");
			}, nav_delay);
		}
	);
	
	/* Hover over a L1 nav item -> Immediately show L2 nav menu + hide other L2 nav menus
	 * Hover out of a L1 nav item -> After delay, hide L2 nav menu + show L2 nav menus of current site */
	jQuery("#nav>ul>li").hover(
		function () {
			clearTimeout(nav_delay_timer_L2);
			jQuery("#nav>ul>li").removeClass("over");
			jQuery(this).addClass("over");
		},
		function () {
			/* Hide current subnav, set it to off state and show default nav after x milliseconds*/
			clearTimeout(nav_delay_timer_L2);
			var currentL1Nav = jQuery(this);
			var rollOff = function () {
				jQuery(currentL1Nav).removeClass("over");
				currentSite.addClass("over");
			}
			nav_delay_timer_L2 = setTimeout(rollOff, nav_delay);
			
		}
	);
	
	jQuery("#nav li li li").click(function () {
		var link = jQuery(this).children("a").attr("href");
		window.location.href = link;
	});
	
	navFloat.html(currentSiteSubNav.html());
	
	/* Hover over a L2 nav item -> Show L3 nav menu immediately
	 * Hover out of a L2 nav item -> Hide L3 nav menu immediately */
	jQuery(".subnav>ul>li").hover(
		function () {
			jQuery(this).children("ul").show();
		},
		function () {
			jQuery(this).children("ul").hide();
		}
	);
	
	/* Fix for L2 nav items that have no L3 items decrease the 
	 * padding-bottom from 10px to 6px so it doesn't hang over
	 * into the banner or ribbon. */
	jQuery("#nav .subnav>ul>li, #navFloat.subnav>ul>li").each(function () {
		var item = jQuery(this);
		var children = item.children('ul');
		var label = item.children('div');
		if(children.length == 0) {
			label.css('padding-bottom', '4px');
		}
	});
	
	/* Search box: Show "Search GuideStone" until search box is interacted with */
	jQuery('.gsSearchBox').focusin(function () {
		var search = jQuery(this);
		if(search.val() == "Search GuideStone") {
			search.val("");
			search.css("color", "#000");
		}
	});
	
	jQuery('.gsSearchBox').focusout(function () {
		var search = jQuery(this);
		if(search.val() == "") {
			search.val("Search GuideStone");
			search.css("color", "#999");
		}
	});
	
	/* Trap the enter key */
	jQuery('.gsSearchBox').keypress(function(e) {
		var search = jQuery(this);
		var code = (e.keyCode) ? e.keyCode : ((e.which) ? e.which : null);
        if(code == 13) {
			e.preventDefault();	
			search.blur();
			jQuery('.gsSearchBtnLink').focus().click();
			return false;
		} else {
			var character = String.fromCharCode(code);
			var query = escape(search.val() + character);
			var url = "/aboutus/search.aspx?cx=017280725682041736050%3Ac-97-i7i6dm&cof=FORID%3A11&ie=UTF-8&q=" + query;
			jQuery('.gsSearchBtnLink').attr('href', url);
		}
	});
	
	
	/* Search Button Click */
	jQuery('.gsSearchBtnLink').click(function(e) {
        var query = escape(jQuery(".gsSearchBox").val());
		e.preventDefault();
		if(query != null && query != "" && query != "Search%20GuideStone") {
			var url = "/aboutus/search.aspx?cx=017280725682041736050%3Ac-97-i7i6dm&cof=FORID%3A11&ie=UTF-8&q=" + query;
			window.location.href = url;
		} else {
			jQuery('.gsSearchBtnLink').attr('href', "#");
		}
		return false;
	});

	
	
	/* ---------------------------
	 * Expanding/Collapsing Footer
	 * ---------------------------
	 * Wait until footer is requested
	 * to load contents via ajax.
	 * ---------------------------*/
	
	var footerIsExpanded = false;
	
	jQuery("#footer .controls").show();
	
	jQuery("#footer .controls").click(function() {
		var footerContent = jQuery("#footer .content");
		var footerControls = jQuery("#footer .controls");
		var footerInner = jQuery("#footer .inner");
		if(footerIsExpanded) {
		
			footerContent.slideUp();
			footerControls.addClass("collapsed");
			footerControls.text("Open Links");
			
			jQuery("#footer .content").slideUp(400, checkScroll);
			jQuery("#footer .controls").addClass("collapsed");
			jQuery("#footer .controls").text("Open Links");
			footerIsExpanded = false;
			widgetUsed("Footer-Collapsed", window.location.href);
		} else {
			
			if(footerContent.length == 0) {
				jQuery("#footer .controls").after('<div class="tempContent"></div>');
				footerTemp = jQuery("#footer .tempContent");
				footerControls.html('<div class="ajaxLoad"><img src="/images/ajax_loader.gif" height="16" width="16" alt="Loading..." /></div>');
				footerTemp.hide();
				footerTemp.load('/largefooter.aspx', '', function(responseText, textStatus, XMLHttpRequest) {
					var temp = jQuery(footerTemp.html());
					temp.appendTo(footerInner);
					footerTemp.remove();
					footerContent = jQuery("#footer .content");
					
					footerContent.slideDown();
					footerControls.removeClass("collapsed");
					footerControls.html("Close Links");
					/*
					*/
				});
			} else {
				footerContent.slideDown();
				footerControls.removeClass("collapsed");
				footerControls.text("Close Links");
			}
			
			footerIsExpanded = true;
			widgetUsed("Footer-Expanded", window.location.href);
		}
	});
	
	/* -------------------------
	 * Moving L2 nav with scroll
	 * -------------------------*/
	function scrollYPosition() {
		var scrollTop = document.body.scrollTop;
		if (scrollTop == 0)
		{
			if (window.pageYOffset)
				scrollTop = window.pageYOffset;
			else
				scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
		return scrollTop;
	}
	
	
	function detachNav() {
		// Nothing at this time
	}
	
	/* When scrolling down below the L2 navigation, It attaches to the top of the screen*/
	function checkScroll() {
		var scrollY = jQuery(window).scrollTop()
		//This feature will not work with Safari browsers older than Safari 5
		if(jQuery.browser.webkit) {
			// Safari 5 uses webkit version 533 or higher
			if(getMajorBrowserVersion() < 533) {
				return;
			}
		}
		if(scrollYPosition() > 129 && currentSite.length > 0) {
			// Fix the navigation to the top of the screen while scrolling
			if(!currentSiteSubNav.hasClass("detached")) {
				// Align the menu items horazontally within the main layout
				jQuery(window).resize();
				navFloat.addClass("active");
				jQuery("#nav>ul>li").removeClass("over");
			}
		} else {
			navFloat.removeClass("active");
			jQuery("#nav .current").addClass("over");
		}
	}

	jQuery(window).scroll(function() {
		checkScroll();
	});
	
	/* Ensure the floating L2 nav is centered. */
	jQuery(window).resize(function() {
		var winWidth = jQuery(window).width();
		var left = 10;
		if(winWidth > 990) {
			left = (winWidth - 990)/2 + 10;
		}
		currentSiteSubNav.children("ul").css("left", left + "px");
	});
	
	function getMajorBrowserVersion() {
		var ver = jQuery.browser.version
		return parseInt(ver.substring(0, ver.indexOf(".", 0)));
	}
	
	/* -------------------------
	 * Style gsCarousel
	 * -------------------------*/
	
	jQuery('.gsCarousel').each(function () {
		var carousel = jQuery(this);
		carousel.addClass("jcarousel-skin-gsCarousel");
		carousel.jcarousel({scroll:3});
	});
	
	jQuery('.gsBooksCarousel').each(function () {
		var carousel = jQuery(this);
		carousel.addClass("jcarousel-skin-gsBooksCarousel");
		carousel.jcarousel({scroll:3});
	});


	
	/* -------------------------
	 * Style gsDrawer
	 * -------------------------*/
	jQuery('.gsDrawer').each(function () {
		setupDrawer(jQuery(this), currentSiteStyle);
	});
	
	/* -------------------------
	 * Style gsBuckets
	 * -------------------------*/
	jQuery('.gsBuckets').each(function () {
		setupBuckets(jQuery(this), currentSiteStyle);
	});
	
	/* -------------------------
	 * Style gsTabs
	 * -------------------------*/
	
	jQuery(".gsTabs").each(function() {
		setupTabs(jQuery(this), currentSiteStyle);
	});
	
	/* -------------------------
	 * Style gsTables
	 * -------------------------*/
	
	jQuery("table.gsTable").each(function() {
		styleTable(this, currentSiteStyle);
	});
	
	/* -------------------------
	 * Style Buttons
	 * -------------------------*/
	
	jQuery(".button").each(function() {
		jQuery(this).addClass(currentSiteStyle);
	});
	
	/* -------------------------
	 * Style Banner
	 * -------------------------*/
	
	jQuery("#layout-inner > #banner").addClass(currentSiteStyle);
	
	
	/* -------------------------
	 * Style Footer
	 * -------------------------*/
	
	jQuery("#footer").addClass(currentSiteStyle);
	
	/* -------------------------
	 * Style Call-To-Action box
	 * -------------------------*/
	
	jQuery(".call-to-action").addClass(currentSiteStyle);
	
	
	/* -------------------------
	 * Setup funds dropdown list
	 * -------------------------*/
	jQuery('.funds-dropdown-list').each(function() {
		var list = jQuery(this);
		list.change(function () {
			window.location.href = list.val();
		});
		list.find('option').each(function () {
			var option = jQuery(this);
			if(option.text() == '') {
				option.text(option.attr('label'));
			}
		});
	});
	
	
	
});

jQuery(document).ready(function() {
	
	// match css class named "modalSize[Width]x[Height]" where [Width] is the integer width and [Height] is the integer height of the modal window
	// ex: modalSize500x200. Negative width or height signify default width or height.
	function getModalSizeFromClasses(classes) {
		if(classes != null && classes.length >= 11) {
			var matches = classes.match(/modalSize[-]?[0-9]+x[-]?[0-9]+/i);
			
			if(matches != null && matches.length > 0) {
				var size = (matches[matches.length - 1].slice(("modalSize").length)).split("x");
				size[0] = parseInt(size[0]);
				size[1] = parseInt(size[1]);
				return size;
			}
		}
		return null;
	}
	
	function getModalSize(element) {
		return getModalSizeFromClasses(jQuery(element).attr('class'));
	}
	
	jQuery(".iFrame").each(function () {
		var size = getModalSize(this);
		var url = jQuery(this).attr('href');
		if(size == null || size.length < 2) {
			size = new Array(640, 480);

		}
		var iframe = jQuery("<iframe frameborder=\"0\" src=\"" + url + "\" />");
		iframe.css('border-width', '0px');
		iframe.css('width', size[0] + "px");
		if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 9) {
			iframe.css('height', Math.round(size[1] - (size[1]*.027)) + "px");
		} else {
			iframe.css('height', size[1] + "px");
		}
		jQuery(this).replaceWith(iframe);
	});

	/* Only displays modal on load if the user does not have a cookie with the same name as the value of the link's "name" attribute
	 * The number of days the cookie lasts (when the modal does not display) goes between the <a> and </a> tags. 
	 * Example: <a href="modalUrl" name="modal" class="modalSize500x200" id="modalOnLoad">14</a>
	 */
	jQuery("#modalOnLoad").each(function () {
		var link = jQuery(this);
		link.hide();
		if(cookieSupport()) {
			var name = link.attr('name');
			var ie6 = link.hasClass('ie6');
			if(!ie6 || (jQuery.browser.msie && jQuery.browser.version.substr(0,1) == "6")) {
				
				if(getCookie(name) == null) {
					var expires = new Date();
					var duration = parseInt(link.html()) * 86400000; // Milliseconds in a day
					expires.setTime(expires.getTime() + duration);
					var size = getModalSize(link);
					if(size == null || size.length < 2) {
						link.fancybox();
					} else {
						var params = {};
						params['hideOnContentClick'] = false;
						params['showCloseButton'] = true;
						if(link.attr('href').charAt(0) != '#') {
							params['type'] = 'iframe';
						}
						if(size[0] > 0) {
							params['width'] = size[0];
						}
						if(size[1] > 0) {
							params['height'] = size[1];
						}
						link.fancybox(params);
					}
					setCookie(name, 'DoNotDisplay', expires, null, null, null);
				}
			link.click();
			}
		}
	});
	
	jQuery("#paczip").each(function () {
		if(!cookieSupport()) {
			// No cookies, no modal
			return;
		}
		
		var link = jQuery(this);
		var href = link.attr('href');
		if(!href || href == "") {
			// No url, no modal
			return;
		}
		
		var name = link.attr('name');
		var size = getModalSize(link);
		var width = link.data('modalWidth');
		var height = link.data('modalHeight');
		
		var zip;
		var params = {};
		link.hide();
		
		// if cookie is present use that value
		zip = getCookie(name)
		if(zip != null && zipCheck(zip)) {
			return zipEntered(zip, this);
		}
		
		if(href.charAt(0) != '#') {
			params['type'] = 'iframe';
		}
		
		if(width) {
			params['width'] = width;
		}
		
		if(height) {
			params['height'] = height;
		}
		
		params['hideOnContentClick'] = false;
		params['showCloseButton'] = true;
		link.fancybox(params);
		link.click();
	});
	
	jQuery(".modal").each(function(i) {
		var size = getModalSize(this);
		if(size == null || size.length < 2) {
			jQuery(this).fancybox({
				'hideOnContentClick'	: 'none',
				'showCloseButton'		: 'none',
				'width'					: 700
			});
		} else {
			var params = {};
			params['hideOnContentClick'] = false;
			params['showCloseButton'] = true;
			if(size[0] > 0) {
				params['width'] = size[0];
			}
			if(size[1] > 0) {
				params['height'] = size[1];
			}
			jQuery(this).fancybox(params);
		}
	});
	

	jQuery(".modalImage").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'image'
	});

	jQuery(".modalFlash").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'swf'
	});

	jQuery(".modalFrame").each(function () {
		var size = getModalSize(this);
		if(size == null || size.length < 2) {
			jQuery(this).fancybox({
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe',
				width				: 1020,
				height				: 500
			});
		} else {
			var params = {};
			params['hideOnContentClick'] = false;
			params['showCloseButton'] = true;
			params['type'] = 'iframe';
			params['transitionIn'] = 'none';
			params['transitionOut'] = 'none';
			if(size[0] > 0) {
				params['width'] = size[0];
			}
			if(size[1] > 0) {
				params['height'] = size[1];
			}
			jQuery(this).fancybox(params);
		}
	});
	
	jQuery('.youtube').each(function () {
			var container = jQuery(this);
			var vidId = container.attr('id');
			var thumbnail = 'http://img.youtube.com/vi/' + vidId + '/0.jpg';
			
			if(container.children('a').children('img').size() > 0) {
				thumbnail = container.children('a').children('img').eq(0).attr('src');
			}
			
			var h = parseInt(container.attr('height'));
			var w = parseInt(container.attr('width')) - 2;
			var btnPlay =     '/~/media/3A8BC216940C48A1994A4AD21481F375.ashx';
			var btnPlayOver = '/~/media/FE6EB0B4F81E4B639C463665CC713384.ashx';
			
			var narrowPlayerWidth = 427;
			var widescreenPlayerWidth = 560;
			var aspectRatio = w/h;
			var narrowAspectRatio = 4/3;
			var wideAspectRatio = 16/9;
			var playerWidth = narrowPlayerWidth;
			var playerHeight = 340;
			
			var averageAspectRatio = (narrowAspectRatio + wideAspectRatio)/2;
			
			if(aspectRatio > averageAspectRatio) {
				playerWidth = widescreenPlayerWidth;
			}
			
			container.find('a').hide();
			
			// Set Video Width and Height
			container.css('width', w + 'px');
			container.css('height', h + 'px');
			// Get video thumbnail
			container.append('<img src="' + thumbnail + '" height="' + h + '" width="' + w + '" />');
			// Create Play Button
			container.append('<div class="playBtn"><img src="' + btnPlay + '" height="' + h + '" /></div>');
			// Play Button Click
			container.find('.playBtn').click(function () {
				container.fancybox({
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'href'				: ('http://www.youtube.com/v/' + vidId + '?fs=1&hl=en_US&autoplay=1'),
					'type'				: 'swf',
					'width'				: playerWidth,
					'height'			: playerHeight
				});
			});
			
			// Play Button Hover
			container.find('.playBtn').hover(
			function () {
				container.find('.playBtn img').attr('src', btnPlayOver);
			},
			function () {
				container.find('.playBtn img').attr('src', btnPlay);
			});
			
			container.css('border-left', '1px solid #000');
			container.css('border-right', '1px solid #000');
		});
		
		
	/*
	 * Use swfObject and jQuery to replace all html elements that have the "flash" class with a flash element:
	 * 
	 * Simple Example:
	 * ---------------
	 * <div class="flash" width="970" height="250" data-url="flash-media-url">Alternate Content (Mobile device or no flash plugin installed)</div>
	 *
	 * Complex Example:
	 * ----------------
	 * <div 
	 *	class="flash" 
	 *	id="optional-element-id" 
	 *	width="970" 
	 *	height="250" 
	 *	data-url="/flash/media/url/" 
	 *	data-version="optional.flash.version" 
	 *	data-flashvars="optional=flashvars&format=querystring">
	 *		Alternate Content (Mobile device or no flash plugin installed)
	 * </div>
	 *
	 * Required attributes:
	 * --------------------
	 * class	Ensure that "flash" is one of this elements classes to trigger this code
	 * height	The height of the flash movie/object
	 * width	The width of the flash movie/object
	 * data-url	The url or path to the flash movie/object
	 *
	 * Optional attributes:
	 * --------------------
	 * id				You can optionally specify an id attribute, but if omitted, one will be generated
	 * data-flashvars	Variables that can be passed into the flash movie/object. The value should be formatted and url-escaped the same way as a url querystring
	 * data-version		The minimum version of the flash plugin required to play the video (defaults to "9.0.0" if omitted)
	 */
	jQuery('.flash').each(function() {
		if(!swfobject) {
			return;
		}
		var element = jQuery(this);
		loadFlash(element, element)
	});
	
	jQuery('.flashother').each(function() {
		if(!swfobject) {
			return;
		}
		var element = jQuery(this);
		var targetId = element.data('target');
		if(!targetId || targetId == "") {
			return;
		}
		var target = jQuery('#' + targetId);
		loadFlash(element, target)
	});

});


/*
 * Loads flash into the given "target" element using the given "data" element to specify width, height, 
 * flash url and  ather relevant information.
 *
 * The width of the flash element will be the width of the target element unless the data element specifies a data-width attribute. * The data element's data-width attribute will override the target's width attribute
 *
 * Any flashvars loaded into the flash element are specified in querystring format in the data element's data-flashvars attribute. 
 * The data element and the target element can be the same
 */
function loadFlash(data, target) {
	if(!swfobject) {
		return;
	}
	var url = data.data('url');
	var id = target.attr('id');
	// The "data-width" attribute overrides the "width" attribute if set, otherwise flash width is the width attribute of the data element.
	var width = (!!data.data('width'))? data.data('width') : target.attr('width');
	var height = (!!data.data('height'))? data.data('height') : target.attr('height');
	var version = data.data('version');
	var flashvars = data.data('flashvars');
	flashvars += "&width="+width;
	flashvars += "&height="+height;
	var params = {'flashvars': flashvars, 'wmode':'transparent'};
	version = (!!version)? version : "9.0.0";
	var zeroOutFontSize = (data.data('zeroOutFontSize') == true);
	if(!width || width == "" || !height || height == "" || !url || url == "") {
		return;
	}
	
	if(!id || id == "") {
		id = "obj" + newDate().getTime();
		target.attr("id", id);
	}
	
	if(zeroOutFontSize) {
		target.parent().css('font-size', '0');
	}
	swfobject.embedSWF(url, id, width, height, version, false, false, params);
}


function printButtonClick() {
	widgetUsed("Print-Button-Click", window.location.href);
	window.print();
}

/* Takes a table of the following form:
 * <table>
 *    <tbody>
 *       <tr>
 *			<td>...</td>
 *			<td>...</td>
 *			...
 * 		 </tr>
 *		 ...
 *	  </tbody>
 * </table>
 * Adds rounded corners, bottom row and accent row. Alternates colors between even and odd rows.
 * Must have at least 2 TD elements in the first row for rounded corners and last row.
 */
function styleTable(tableObj, tableClass) {
	// Get table info
	
	var table = jQuery(tableObj);
	var numCells = 0;
	var numSpan = 0;
	
	
	
	// Get the number of cells in a row
	table.find("tr:first-child td").each(function () {
		var colspan = parseInt(jQuery(this).attr("colspan"));
		numSpan += (colspan > 0)? colspan : 1;
		numCells += 1;
	});
	
	if(numCells == 1) {
		table.find('tr').each(function() {
			jQuery(this).append("<td class=\"added\"></td>");
		});
		numCells++;
		numSpan++;
	}
	
	
	//Only add the last row if it has not already been added
	if(table.find("tr.lastRow").length == 0) {
		table.find("tr:last-child").after("<tr class=\"lastRow nodata\"><td colspan=\"" + (numSpan - 1) +"\"> </td> <td> </td></tr>");
	}
	
	// set the silo based on the page footer
	if(tableClass != null && tableClass != "") {
		table.addClass(tableClass);
		table.find('tr.subhead').addClass(tableClass);
	}
	
	
	if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 9) {
		// Set even and odd rows for all rows except first row, last row and accent rows
		table.find("tr").each(function(i) {
			var row = jQuery(this);
			if(i != 0 && !row.hasClass("accentRow") && !row.hasClass("lastRow") && !row.hasClass("subhead"))  {
				if(i%2 == 0) {
					row.addClass("evenRow");
				} else {
					row.addClass("oddRow");
				}
			}
		});

		//Add Accent Rows if not already there
		if(table.find("tr.accentRow").length == 0) {
			table.find("tr:first-child").after("<tr class=\"accentRow nodata\"><td colspan=\"" + numSpan +"\"></td></tr>");
		}
		
		
		
		// Only round the corners if the table is > 1 cell wide
		if(numCells > 1 && table.find("tr:first-child td").length > 1) {
			
			// Round the top Corners
			table.find("tr:first-child td:first-child").addClass("cornerTopLeft");
			table.find("tr:first-child td:last-child").addClass("cornerTopRight");
			// Round the bottom corners
			table.find("tr:last-child td:first-child").addClass("cornerBottomLeft");
			table.find("tr:last-child td:last-child").addClass("cornerBottomRight");
			
		}
		table.find("tr:first-child").addClass("firstRow");
	}
}

function setupTabs(tabGroup, style) {
	tabGroup.addClass(style);
	
	tabGroup.find("ul").each(function () {
		var list = jQuery(this);
		var listItems = list.find("li");
		if(listItems.length % 2 != 0) {
		list.append("<li></li>");
		}
		// style odd numbered items manually in IE
		if(jQuery.browser.msie) {
			listItems = list.find("li");
			listItems.each(function (i) {
				if((i+1)%2 == 1) {
					jQuery(this).addClass("odd");
				}
			});
		}
	});
	
	var tabs = tabGroup.children('div');
	var numTabs = tabs.size();
	
	tabs.each(function(i) {
		jQuery(this).addClass("tab");
		if(numTabs > 4) {
			jQuery(this).addClass("small");
			if (i == 0) {
				jQuery(this).css('width', '112px');
			}
		}
		
		if(i == 0) {
			// Set up a container for displaying content
			var contentSection = jQuery('<div class=\"tabContents\"></div>');
			tabGroup.append(contentSection);
			
			// Set first tab as selected by default
			selectTab(jQuery(this));
		}
		
		jQuery(this).click(function () {
			deselectTab();
			selectTab(jQuery(this));
			var label = jQuery(this).children('h3').html();
			widgetUsed("Tab-Switch", label);
		});
		
		// Convert an unordered list to a 2-column table. 
		//List items become table cells. 
		//Content's DOM properties are preserved.
		function convertToTable(ul) {
			var items = ul.children('li');
			var table = jQuery('<table></table>');
			var tbody = jQuery('<tbody></tbody>');
			tbody.appendTo(table);
			var row;
			for(i = 0; i < items.length; i++) {
				var cell = jQuery('<td></td>');
				items.eq(i).contents().appendTo(cell);
				
				if(i%2 == 0) {
					row = jQuery('<tr></tr>');
					row.appendTo(tbody);
				}
				cell.appendTo(row);
			}
			return table;
		}
		
		// Convert a table to an unordered list. 
		// Table cells become list items.
		// Content's DOM properties are preserved.
		function convertToUL(table) {
			var ul = jQuery('<ul></ul>');
			table.children('tbody').children('tr').children('td').each(function() {
				var li = jQuery('<li></li>');
				jQuery(this).contents().appendTo(li);
				li.appendTo(ul);
			});
			return ul;
		}
		
		function deselectTab() {
			var selected =  tabGroup.children('.selected');
			if(selected.length == 1) {
				// Put away old content
				var contentSection = tabGroup.children('.tabContents');
				var contentTable  =  contentSection.children("table");
				var content = convertToUL(contentTable);
				selected.append(content);
				contentTable.remove();
				selected.removeClass('selected');
			}
		}
		
		function selectTab(tab) {
			tab.addClass("selected");
			var selected =  tabGroup.children('.selected');
			var contentSection = tabGroup.children('.tabContents');
			var contentUL  =  selected.children("ul");
			var content  =  convertToTable(contentUL);
			contentSection.append(content);
			contentUL.remove();
		}
		
	});
}

/* Takes a jQuery object of a <div class="gsBuckets">...</div>*/
function setupBuckets(bucketGroup, style) {
	bucketGroup.children("div").each(function(i) {
		var bucket = jQuery(this);
		var nextBucket = jQuery(this).next();
		bucket.addClass('bucket');
		bucket.children('h3').addClass('set');
		bucket.addClass(style);
		if(i%2 == 0) {
			
			bucket.addClass('firstCol');
			if(nextBucket != null) {
				// Ensure adjacent buckets have the same height
				ensureAdjacentBucketsHaveEvenHeight(bucket.children('ul'), nextBucket.children('ul'));
			}
		}
	});
	
	function ensureAdjacentBucketsHaveEvenHeight(bucket0, bucket1) {
		var h0 = bucket0.css('height');
		var h1 = bucket1.css('height');
		if(parseInt(h0) <  parseInt(h1)) {
			bucket0.css('height', h1);
		} else if(parseInt(h0) >  parseInt(h1)) {
			bucket1.css('height', h0);
		}					
	}
}

function setupDrawer(drawer, style) {
	drawer.addClass(style);
	
	var drawerItems = drawer.children('ul').children('li');
	var drawerLabel = drawer.children('h3');
	var hasSubDrawers = (drawerItems.find('h3+ul').size() > 0);
	var control = '<div class="controls">Open</div>';
	
	if(!hasSubDrawers) {
		addControls(drawer);
		drawer.addClass('single-level');
	} else {
		drawerItems.each(function () {
			var drawerItem = jQuery(this);
			drawerItem.addClass('drawer');
			addControls(drawerItem);
			drawerItem.children('h3').addClass('set');
		});
		drawer.children('h3').addClass('set');
	}
	
	function addControls(drawerItem) {
		var drawerLabel = drawerItem.children('h3');
		if(drawerItem.children('.controls').size() == 0) {
			drawerItem.prepend('<div title="Click to expand" class="controls">Open</div>');
			drawerItem.children('.controls').click(function() {
				drawerItem.children('ul').slideToggle();
				drawerItem.toggleClass('closed');
				if(drawerItem.hasClass('closed')) {
					drawerItem.children('.controls').attr('title', 'Click to expand');
					widgetUsed("Drawer-Closed", drawerLabel.html());
				} else {
					drawerItem.children('.controls').attr('title', 'Click to close');
					widgetUsed("Drawer-Opened", drawerLabel.html());
				}
			});
			drawerItem.children('ul').hide();
			drawerItem.addClass('closed');
		}
		drawerItem.children('.controls').html('&nbsp;');
	}
}

function siloChange(i) {
	var silos = new Array('insurance', 'retirement', 'investments', 'capital-mgmt', 'property-casualty', 'corporate');
	for(var k = 0; k < silos.length && i < silos.length; ++k) {
		var start = silos[k];
		var end = silos[i];
		jQuery("."+start).each(function() {
			if(start != end) {
				jQuery(this).removeClass(start);
				jQuery(this).addClass(end);
			 }
		});
	}
}

/** --------------------------------------------------
 * Cookie Management:
 ** --------------------------------------------------
 * - Check for cookie support
 * - Set a cookie
 * - Get a cookie
 * - Delete a cookie
 ** -------------------------------------------------*/
 
 /* True if cookie support is enabled in this browser
    Sets a test cookie and tries to read its value*/
function cookieSupport() {
	var cookieEnabled = false;
	var testCookieName = "GStestCookie";
	var testCookieValue = "TestCookie";
	var expired = new Date();
	expired.setTime(expired.getTime() + 1800000); // 1800000 milliseconds is 30 minutes
	setCookie(testCookieName, testCookieValue, expired, null, null, null);
	cookieEnabled = (document.cookie.indexOf(testCookieName) != -1)? true : false; //Able to create?
	expired = new Date();  // Create expired date object to delete cookie.
	expired.setTime(expired.getTime() - 1800000);
	setCookie(testCookieName, "deleted", expired, null, null, null);
	return cookieEnabled;
}

/* An adaptation of Dorcht's function for setting a cookie. */
function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

/* Gets the value of a browser cookie by name */
function getCookie(name){
  var cookieName = name + "=";
  var dc = document.cookie;
  if (dc.length > 0) {
    begin = dc.indexOf(cookieName);
    if (begin != -1) {
      begin += cookieName.length;
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    }
  }
  return null;
}

/* An adaptation of Dorcht's function for deleting a cookie. */
function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


/** --------------------------------------------------
 * Embedded youtube video API management:
 ** --------------------------------------------------
 * - onReady function
 * - Add an event listener
 * - Translate player state
 * control YouTube videos embedded using SimpleFlashElementHeader
 * YouTube player API located at: http://code.google.com/apis/youtube/js_api_reference.html
 * ------------------------------------------------------------------------*/
 
// Once the player is ready, it will automatically call onYouTubePlayerReady
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById(playerId);
	if(ytplayer != null) {
		ytplayer.isReady = true;
	}
}

// create your own listener function to handle the player's onStateChange event
function addYoutubeListener(playerId, listenerFunction) {
	ytplayer = document.getElementById(playerId);
	if(ytplayer != null && ytplayer.isReady) {
		ytplayer.addEventListener("onStateChange", listenerFunction);
	}
}

/* Return the meaning of the youtube player's current state
 * use playerObj.getPlayerState() to get the players state number */
function getPlayerStateMeaning(newState) {
	switch(newState) {
		case -1: return "video unstarted";
		case  0: return "video ended";
		case  1: return "video playing";
		case  2: return "video paused";
		case  3: return "video buffering";
		case  5: return "video cued";
		default: return "invalid state";
	}
}

/** -------------------------------------------------------
 * Gets the query string from the url and reads the params 
 * -------------------------------------------------------*/
var qsParm = new Array();
function qs() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
}


/** ------------------------------------------------------
 * Location
 * ------------------------------------------------------*/
function zipEntered(zip, link) {
	
	// Read the zip from the field if none is passed in
	if(zip == null) {
		var field = document.getElementById("zip");
		zip = field.value;
	}
	
	// Valid zip code entered
	if(!zipCheck(zip)) {
		field.style.borderColor = "red";
		field.style.borderStyle = "solid";
		return;
	}

	// Remember the zip code for next time
	var expires = new Date();
	var memory = jQuery(link).data('memory');
	memory = (!!memory)? parseInt(memory) : 14;
	var duration = memory * 86400000; // Number of days of memory * Milliseconds in a day
	expires.setTime(expires.getTime() + duration);
	setCookie("paczip", zip, expires, null, null, null);
	
	// Does zip code match the following states
	if(isTexas(zip)) {
		widgetUsed("TX zip entered", zip);
		top.location.href = link.getAttribute("data-texas");
	} else if(isAlabama(zip)) {
		widgetUsed("AL zip entered", zip);
		top.location.href = link.getAttribute("data-alabama");
	} else {
		// Zip is not recognized as one of the above states (close the modal window)
		widgetUsed("Other zip entered", zip);
		parent.jQuery.fancybox.close();
		field.value = "";
		return;
	}
} 

function zipCheck(zip) {
	var zipPattern = new RegExp("^[0-9]{5}$");
	if(!zipPattern.test(zip)) {
		return false;
	}
	return true;
}
 
// Returns true if the given zip code is in Texas
function isTexas(zip) {
	// Zip codes starting with these numbers are in TX
	var include = ["733", "75", "76", "77", "78", "79", "885"];
	// Except for zip codes starting with these numbers
	var exclude = [];
	return stateMatch(zip, include, exclude);
}

// Returns true if the given zip code is in Alabama
function isAlabama(zip) {
	// Zip codes starting with these numbers are in AL
	var include = ["35", "36"];
	// Except for zip codes starting with these numbers
	var exclude = [];
	return stateMatch(zip, include, exclude);
}

/* 
 * Look up the given zip code in the given include/exclude lists. 
 * If it matches an entry in the include list by starting with the 
 * same numbers, and it does not match an entry in the exclude list, 
 * then it is a match.
 */
function stateMatch(zip, include, exclude) {
	// If zip code starts with the same numbers as an entry in the exclude list, then it is not a match
	for(var i = 0; i < exclude.length; ++i) {
		excludePattern = new RegExp("^" + exclude[i]);
		if(excludePattern.test(zip)) {
			return false;
		}
	}
	
	// If zip code starts with the same numbers as an entry in the include list, then it is a match
	for(var i = 0; i < include.length; ++i) {
		var includePattern = new RegExp("^" + include[i]);
		if(includePattern.test(zip)) {
			return true;
		}
	}
	
	// if no matches were found yet, it is not a match
	return false;
}
/** -------------------------------------------------------------------------
 * Funds Risk/Reward Meter
 * Swap out Fund risk/reward meter images when hovering over a fund
 * --------------------------------------------------------------------------*/
jQuery(document).ready(function() {
  
	// Copy the current fund's risk meter image into the display box when its link is hovered over
	jQuery('#fundsListTable td>div').each(function() {
		var img = jQuery(this).find('img.fundRiskMeter');
		var meter = jQuery('.fundsListRiskRow td img');
		var temp = meter.attr('src');
		if(img.length > 0) {
			if(img.attr('src') != '') {
				jQuery(this).children('a').hover(
					function() {
						meter.attr('src', img.attr('src'));
					},
					function () {
						meter.attr('src', temp);
					}
				);
			}
		}
	});
});	
