// --- START GLOBAL CONFIG PARAMS ---

var hoverDelayShow	= 300;				// in milliseconds, the top menu disappear delay
var hoverDelayHide	= 700;				// in milliseconds, the submenu disappear delay
var siteFeaturesDelay = 5000;			// in milliseconds, the Site Features appear delay
var tabAttentionWaitCount = 8;			// the number of times a tab would highlight to wait before actually doing the highlights
var snAttentionWaitCount = 5;			// the number of times a tab would highlight to wait before actually doing the highlights
var tabAttentionDelay = 400;			// in milliseconds, the time between the attention-grabbing attempt of each javascript Tab
var logoPopupDelay = 500;				// in milliseconds, the time for the logo info box to stay before fading away

// --- END GLOBAL CONFIG PARAMS ---

// --- LIBRARY CODE ---
function findPos(obj) {
	var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function slugify(text) {
	return text.replace(/[ |\/]/g, '-').replace(/[\(|\)|\?]/g, '').toLowerCase();
}

function OpenEmailCMS() {
	emailWind=window.open("/home/email.asp?URLemail="+escape(window.location)+"&Title="+escape(document.title),"Email","status=no,toolbar=no,resizable=yes,location=no,width=320,height=350");
	emailWind.focus();
}

function OpenPrintCMS(fromLegacy) {
	var url = window.location.href;
	url += (url.indexOf('?') > -1 || !fromLegacy) ? '&vPrint=1' : '?vPrint=1'; //non-legacy pages always use &; for legacy pages, if query string parm exists then append, otherwise create (AiG:JG 10-10-07)
	//alert(url);
	printWind=window.open(url,"PrintFriendly","status=0,toolbar=0,menubar=1,resizable=1,location=0,scrollbars=1,width=800,height=600");
	printWind.focus();
}

// --- START NAV CODE ---
function hideSupNavDropdown() {
	$('#moreSites > ul').slideUp('normal');
	$(this).removeClass('active');
}
$(document).ready(function() {
	// supernav dropdown
	var sntimeout;
	$('li#moreSites > a').click(function() {
		if ($('#moreSites > ul:visible').length > 0) {
			hideSupNavDropdown();
		} else {
			$('#moreSites > ul').slideDown('normal');
			$(this).addClass('active');
			clearTimeout(sntimeout);
			sntimeout = setTimeout('hideSupNavDropdown()', 7000);
		}
		return false;
	});
	
	// main nav dropdown
	var navTimeout;
	$('#topNav > ul.nav > li').hover(function() {
		if ($(this).find('div.subNav:visible').length == 0) { // if subnav is not already visible
			hideSubNav();
			if ($(this).find('li').length > 0) { // if has subnav items
				$(this).find('div.subNav').slideDown('normal');
			}
		}
		clearTimeout(navTimeout);
		$('#topNav > ul.nav > li.active').removeClass('active');
		$(this).addClass('active');
	}, function() {
		navTimeout = setTimeout('hideSubNav();', 1000);
	});
});

function hideSubNav() {
	$('#topNav li').removeClass('active');
	$('#topNav ul div.subNav:visible').slideUp('fast');
}

// --- START COUNTRY SELECT CODE ---
function setupCountryMenu(theTimeout, menuIDname, delay, showing) {
	clearTimeout(theTimeout);
	return setTimeout(function() {
		if (showing)	$('#' + menuIDname).slideDown('fast');
		else			$('#' + menuIDname).slideUp();
	}, delay);
}

$(document).ready(function() {
	var countryTimeout = null;
	$("#countryActuator")
		.hover(function() {
			countryTimeout = setupCountryMenu(countryTimeout, 'countryMenu', hoverDelayShow, true);
		}, function() {
			countryTimeout = setupCountryMenu(countryTimeout, 'countryMenu', hoverDelayHide, false);
		})
	;
	$("#countryMenu")
		.hover(function() {
			clearTimeout(countryTimeout);
		}, function() {
			countryTimeout = setupCountryMenu(countryTimeout, 'countryMenu', hoverDelayHide, false);
		})
	;
});

// -- START ACCORDION CODE ---
function createAccordion(parent) {
	var timeout = 500;
	var accordTimeout = null;
	$('.accordion', parent).accordion({ 
	    active: false, 
	    header: '.head', 
	    event: 'mouseover',
	    autoheight: true,
	    alwaysOpen: false
	});
	$('.accordion', parent).hover(
		function() { clearTimeout(accordTimeout) },
		function() { accordTimeout = setTimeout( function() { 
			$('.accordion').activate(-1);
			$('.accordion li').removeClass("selected"); },
		timeout)
	});
	
	// clickable accordion
	$('.accordionClick', parent).accordion({
	    active: ".active", 
		alwaysOpen: false,
		autoHeight: false,
		header: ".head"
	});
	$('.accordionClick').each(function() {
		if ($(this).hasClass("startOpen")) $(this).accordion("activate", 0);
	});
}

$(document).ready(function() {
	// ROUNDED CORNERS
	$('.btn').addClass('genCornerAll');
	$('#bigBanner, #medBanner').each(function() {
		$(this).addClass('genRoundedBorder').prepend('<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');
	});
	$('.genCornerAll').addClass('genRounded').prepend('<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');
	$('.genCornerTop, #ft').addClass('genRounded').prepend('<span class="tl"></span><span class="tr"></span>');
	$('.genCornerBot').addClass('genRounded').prepend('<span class="bl"></span><span class="br"></span>');

	// --- START NEWSLETTER SIGNUP CODE ---
	var val = 'Email newsletter signup';
	$('p.emailSignup input').focus(function() {
		if ($(this).val() == val) $(this).val('');
		$('.signupOptions').slideDown('normal');
	}).blur(function() {
		if ($(this).val() == '') $(this).val(val);
	});
	$('#cancelEmail').click(function() {
		$('.signupOptions').slideUp('normal');
		return false;
	});

	// --- START SEARCH CODE ---
	$("input.search").each(function() {
		//var searchText = this.value;
		var searchText = "Search";
		$(this)
			.focus(function() {
				//if (this.value == searchText) this.value = '';
				if (this.value.indexOf(searchText) >= 0) this.value = '';
			})
			.blur(function() {
				if (this.value == '') this.value = searchText;
			})
		;
	});
	
	var url = window.location.href;
	if (url.indexOf('vPrint=1') > -1) {
		$("link[media='screen']").remove();
		$("link[media='print']").attr("media", "all").each(function() {
			$(this).attr("href", $(this).attr("href") + '?');
		});
	}
	
	// --- START BANNER ROTATOR CODE ---
	/*$('.bannerRotator').each(function() {
		if ($(this).find('li').length > 1)
			$(this).tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 5000);
	});*/
	$('.bnrSelectors, .bnrArrows, .bnrTabs').each(function() {
		if ($(this).find('li').length > 1)
			$(this).tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 5000);
	});
	//$('.bnrSelectors, .bnrArrows, .bnrTabs').tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 5000);
	
	// --- START TAB CODE ---
	var cancelTimeout = false;
	$("div.tabContainer").each(function() {
		var tabContainer = this;
		if (this.className.indexOf('tabHover') != -1) {		// added by JL 6.28.07 -- only set height for hover tabs
			var maxHeight = 0;
			$("div.tab-ct", tabContainer).each(function() {
				if (this.scrollHeight > maxHeight) maxHeight = this.scrollHeight;
			});
			$("div.tab-ct", tabContainer).height(maxHeight + 'px');
		}
		
		$("div.tab-ct:gt(0)", this).hide();
		$($(tabContainer).find("h3.tab").addClass('tabTitle').hover(function() {
			if (this.className.indexOf('active') != -1) return;
			if (tabContainer.className.indexOf('tabHover') == -1) return;
			cancelTimeout = true;
			$("h3.tab", tabContainer).removeClass("active");
			$(this).addClass("active");
			$("div.tab-ct", tabContainer).hide();
			$($("div.tab-ct", tabContainer).get($("h3.tab", tabContainer).index(this))).show();
		}, function() {}).click(function() {
			if (this.className.indexOf('active') != -1) return;
			cancelTimeout = true;
			$("h3.tab", tabContainer).removeClass("active");
			$(this).addClass("active");
			$("div.tab-ct", tabContainer).hide();
			$($("div.tab-ct", tabContainer).get($("h3.tab", tabContainer).index(this))).show();
			return false;
		}).get(0)).addClass('active').after( $("h3.tab:gt(0)", tabContainer).get() );
		$(tabContainer).find("h3.tab:first").addClass('first');		// added by JL 6.28.07 -- need first & last classes on h3's
		$(tabContainer).find("h3.tab:last").addClass('last');
	});

	// -- START EXPANDABLE CODE ---
	$(".expandable").click(function() {
		if ($(this).hasClass("active")) $(this).next().slideUp("fast");
		else $(this).next().slideDown("normal");
		$(this).toggleClass("active").next();
	}).next().hide().addClass("expandable-ct");
	
	// --- START AUTOHIDE CODE ---
	$(".hideonclick").click(function() { $(this).hide(); }).focus(function() {
		$(this).hide();
		$('#newsletterFrame').each(function() {
			$(window.frames.newsletterFrame).focus();
			window.frames.newsletterFrame.focusOnEmail();
		});
	});
	
	// -- START ARTICLE TABLE FORMAT CODE --- JNL 3.23.07
	$("div.article table tr:odd").addClass("odd");
	$("td.sidenote").parent().parent().parent().addClass("sidenote");
	
	// -- ARTICLE SHOW-HIDE ONCLICK CODE --- JNL 5.17.07
	$(".hide-until-click").hide();
	$("a.click-to-show").each( function(i) {
		$(this).click( function() {
			$(".hide-until-click").eq(i).show("normal");
			$(this).hide();
			return false;
		});
	});
	
	// -- START BROWSER SPECIFIC CODE --- JNL 12.5.07 - JQUERY BUG FOR SAFARI 2.0.4
	/*$("div.browserSpecific").hide();
	if ($.browser.safari) $("div.safari").show();
	else if ($.browser.mozilla) $("div.mozilla").show();
	else if ($.browser.opera) $("div.opera").show();
	else if ($.browser.msie) $("div.msie").show();
	else $("div.unknownBrowser").show();*/
	
	// -- START AIG WEB 2 FORMAT CODE --- JNL 5.25.07
	$(".pageTitle").prepend("<span class='tl'>&nbsp;</span><span class='tr'>&nbsp;</span>");
	$(".col-left h2").each(function() {
		if ($("span", this).get().length == 0) {
			$(this).get(0).innerHTML = '<span>' + $(this).get(0).innerHTML + '</span>';
		}
	});
	
	var logoPopupFadeTimer = null;
	$("h1.headerHidden a").hover(function() {
		clearTimeout(logoPopupFadeTimer);
		if ($("div.logoPop").css("display") == "none") $("div.logoPop").fadeIn();
	}, function() {
		logoPopupFadeTimer = setTimeout(function () { $("div.logoPop").fadeOut(); }, logoPopupDelay);
	});
	$("div.logoPop").hover(function() {
		clearTimeout(logoPopupFadeTimer);
		if ($("div.logoPop").css("display") == "none") $("div.logoPop").fadeIn();
	}, function() {
		logoPopupFadeTimer = setTimeout(function () { $("div.logoPop").fadeOut(); }, logoPopupDelay);
	});
});

// -- START AIG PAGINATION CODE --- JNL 8.1.07
$("#paginate").ready(function() {
	var curPage = 0;
	$("#paginate").append("<p class='button prev'><a href='#paginateTop'>Previous</a></p> <p class='button next'><a href='#paginateTop'>Next</a></p><div class='clearPages'>&nbsp;</div>")
				.before("<a name='paginateTop'></a>");
	updatePage(curPage);
	$("#paginate .prev a").click(function() { curPage--; updatePage(curPage); });
	$("#paginate .next a").click(function() { curPage++; updatePage(curPage); });
});

function updatePage(p) {
	$("div.page:visible").hide();
	$("div.page").eq(p).show();
	$("#paginate .next").show();
	$("#paginate .prev").show();
	if (p == 0) { $("#paginate .prev").hide(); }
	if (p == $("div.page").length - 1) { $("#paginate .next").hide(); }
}
/*
// -- START AJAX LINK CODE --- JNL 9.22.07
var curLink = 0;
$(document).ready(function() {
	ajaxActions(0);
	
	// Initialize history plugin.
	$.historyInit(ajaxClick);
});

var aigAjaxRequestFunctions = [];
var aigAjaxLoadedFunctions = [];
var curLink = 0;

function ajaxActions(container) {
	if (container == 0) container = $(document);
	
	$("a.ajaxTip", container).hover(function(){JT_show(this,this.name)}, function(){$('#JT').remove()});
	$("table tr:odd", container).addClass("odd");
	createAccordion(container);
	$("a.ajaxLink", container).each(function() {
		$(this).attr( "href", $(this).attr("href")
				 .replace("/get-answers/", "/get-answers#/")
				 .replace("/media/", "/media#/")
				 );
		
	}).click(function() {
		curLink = $(this); // this is to remember what link was clicked in "ajaxClick()"
		var url = $(this).attr("href").replace("http://www.answersingenesis.org","");
		var url_parts = url.split('#');
		if (window.location.pathname == url_parts[0]) {
			url = url_parts[1];
			$.historyLoad( url );
			return false;
		}
	});
	
	$("span.lockedContent").prepend("<a href='http://www.answersingenesis.org/store/catid/243/lockicon/lockedarticle/subscribe/answersmagazinesubscription' title='Subscribe to Answers magazine to access locked content.' class='jTip lockIcon'><img src='/assets/layout/am/icon_lock_sm.gif' /></a>");
	
	// call any ajax functions passed in from other scripts
	for (var i=0; i < aigAjaxLoadedFunctions.length; i++) {
		aigAjaxLoadedFunctions[i].call(this,container);
	}
}

// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function ajaxClick(hash) {
	if(hash) {
		if (hash.indexOf('/') == -1 && $('#'+hash).length > 0) return true;
		
		var anchorLink = $("a[href='#"+ hash +"']:first");
		if (anchorLink.length > 0 && !$(anchorLink).hasClass("ajaxLink")) {	// process generated tabs and accordion links
			var tabLink = $('ul.ui-tabs-nav a[href="#'+ hash +'"]');
			var accordHeader = $('.ui-accordion #'+hash+'.ui-accordion-header');
			if (tabLink.length) {
				$(tabLink).parent().parent().parent().tabs('select', '#'+hash);
			} else if (accordHeader.length) {
				var gParent = $(accordHeader).parent().parent();
				if (gParent.hasClass('ui-tabs-panel')) {
					$(accordHeader).parent().parent().parent().tabs('select', '#'+gParent.attr('id'));
				}
				$(accordHeader).parent().accordion('activate', '#'+hash);
			}
		} else {
			if (curLink == 0 || curLink.length == 0) curLink = $("a.ajaxLink[href*='"+ hash +"']:first");
			
			var url = window.location.pathname + hash;
			var containerMain = "#ajaxHolder";
			
			$('#JT').remove();
			$(curLink).parent().addClass("active");
			
			$("body").append("<div id='ajaxOverlay' style='background-color:#fff;height:100%;left:0;opacity:0.5;filter:alpha(opacity=50);-moz-opacity:0.5;position:fixed;top:0;width:100%;z-index:7000;'>&nbsp;</div>"+
							 "<div id='ajaxLoading' style='left:50%;position:fixed;text-align:left;top:50%;z-index:7002;padding: 10px 15px;background-color:#fff;border:solid 3px #ccc;margin-left:-104px;margin-top:-8px;'><img src='/assets/layout/home2/loadingAnimation.gif' /></div>");
			var oldAccordionIndex = accordionIndex();
			$.get(url.replace(/^(\/stage)?\//i,"$1/web/ajax/" ), {}, function(data) {
				$(containerMain).html( data );
				ajaxActions(containerMain);
				$("ul.accordionClick", containerMain).accordion("activate", oldAccordionIndex);
				
				$("#ajaxOverlay, #ajaxLoading").remove();
			});
	
			// call any ajax functions passed in from other scripts
			for (var i=0; i < aigAjaxRequestFunctions.length; i++) {
				aigAjaxRequestFunctions[i].call(this,hash,curLink);
			}
			return false;
		}
	}
}
*/
function accordionIndex() {
	var index = false;
	$("ul.accordionClick:first > li").each(function(i) {
		if ($(this).hasClass("selected")) index = i;
	});
	return index;
}

// media RR loader
function loadMediaRR(sku) {
	if (sku != undefined && sku.length > 0) {
		$("#mediaProduct").load("/scripts/productListVertical.asp?skus='" + sku + "'", function() {
			$("#mediaProduct .resourceImage img").attr("src", 
				$("#mediaProduct .resourceImage img").attr("src").replace("_sm", "_med")).load(function() {
					if ($(this).width() > 180) $(this).attr("width",180);
				});
		});
	}
}


// -- Automators for Table of Contents, Tabs and Accordion ---
jQuery.fn.reverse = Array.prototype.reverse;
function createToc(container) {
	var curLi = 0;
	var tocID = 'toc';
	$(container).prepend('<div id="'+ tocID +'" class="ui-corner-all"><b>Contents (<a href="#" id="hideContents">hide</a>)</b><ul></ul></div>')
		.children().each(function() {
			if (this.nodeName.match(/^H2$/)) {
				$('#'+tocID+' > ul').append( addHeader(this) );
				curLi = $('#'+tocID+' > ul > li:last');
				
			} else if (this.nodeName.match(/^H3$/)) {
				if ( $('ul', curLi).length == 0) $(curLi).append('<ul></ul>');
				$('ul', curLi).append( addHeader(this) );
			}
		});
	
	$('#hideContents').click(function() {
		$('#toc > ul').toggle();
		$(this).text( ($(this).text() == 'hide') ? 'show' : 'hide' );
		return false;
	});
}
function addHeader(item) {
	var text = $(item).text();
	var slug = slugify(text);
	$(item).attr('id', slug);
	return '<li><a href="#'+ slug +'" rel="history">'+ text +'</a></li>';
}

function genTabs(container, tabs) {
	var tabContainerID = 'genTabs';
	var tabHeaders = $(tabs, container).reverse();
	$(tabHeaders).eq( $(tabHeaders).length-1 ).before('<div id="'+ tabContainerID +'"><ul id="tabList"></ul></div>');
	$(tabHeaders).each(function(i) {
		var tabID = $(this).attr('id');
		$('#'+tabContainerID+' > ul')
			.prepend('<li><a href="#'+ tabID +'">'+ $(this).text() +'</a></li>')
			.after('<div id="'+ tabID +'"></div>');
		$('#'+tabID).append( $(this).nextAll() );
		$(this).remove();
	});
	$('#'+tabContainerID).tabs();
	$('#'+tabContainerID+' > ul.ui-tabs-nav > li').each(function() {
		var prev = $(this).prev('li');
		var next = $(this).next('li');
		var href = $('a', this).attr('href');
		if (prev.length)
			$( href ).append('<a href="'+ $('a', prev).attr('href') +'" class="tabPrev ui-corner-all ui-state-default exclude" rel="history"><span class="ui-icon ui-icon-arrowthick-1-w" style="float:left;" />'+ $(prev).text() +'</a>');
		if (next.length)
			$( href ).append('<a href="'+ $('a', next).attr('href') +'" class="tabNext ui-corner-all ui-state-default exclude" rel="history"><span class="ui-icon ui-icon-arrowthick-1-e" style="float:right;" />'+ $(next).text() +'</a>');
	});
}

function genAccordion(container, header) {
	$(container).prepend('<div class="genAccordion"></div>');
	var accord = $('.genAccordion', container);
	var tabHeaders = $(header, container).reverse();
	$(tabHeaders).each(function(i) {
		$(this).wrapInner('<a href="#"></a>');
		$(accord).prepend('<div></div>');
		$('div:first', accord).append( $(this).nextAll('*:not(.exclude)') );
		$(accord).prepend(this);
	});
	$('.genAccordion', container).accordion({ autoHeight: false });
}
// -- end toc, tabs, accordion


// -- Search box formatting AiG:ARS 07/10/07
var lastSearchBoxValue = null;
function formatSearchString(searchBox) {
	if (searchBox.value == lastSearchBoxValue) return;

	lastSearchBoxValue = searchBox.value;
}
$(document).ready(function() {
	$(".search").keydown(function() { formatSearchString(this); }).keyup(function() { formatSearchString(this); }).change(function() { formatSearchString(this); });
});