/* The following functions to create, read, and delete cookies
 is courtesy Peter-Paul Koch, http://www.quirksmode.org/js/cookies.html */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/*********************************/

function rightHandAccordion(e)
{
	if(!this.up().hasClassName('active'))
	{
		var effects = [];
		
		var ul = this.next('ul');
		if(ul)
		{ 
			ul.immediateDescendants().each(function(li)
			{
				effects.push(new Effect.SlideDown(li));
			});
		}
		
		$$('#spotlights li.active ul li').each(function(li)
		{
			effects.push(new Effect.SlideUp(li));
		});
		
		new Effect.Parallel(effects, { duration: 0.5 });
		
		$$('#right_sidebar #spotlights li.active').invoke('removeClassName', 'active');
		this.up().addClassName('active');
	}
}

var tab_delay = "0.3";

function tabNav(e)
{
	// Stop the click on the hyperlink from going anywhere
	Event.stop(e);
	
	if (this.className == "tablink") {
		thisLink = $$('div#tabnav a[href="'+this.href.substring(this.href.search(/#/))+'"]')[0];
	}
	else
		thisLink = this;
	
	// Use the href of the clicked link for id of tab to show
	var href = thisLink.href;
	var contentToShowId = href.substring(href.search(/#/) + 1);
	
	// Find the current tab and remove the current flag
	$$('#tabs #tabnav li a.current').invoke('removeClassName', 'current');
	
	// Add the current flag to the list item which is the parent of the clicked link
	$(thisLink).addClassName('current')
	
	var currentContent = $$('#tabs div.current:not(.tab-subcat)').invoke('removeClassName', 'current');

	/*@cc_on
	/*@if (@_jscript_version < 5.7)
		$(currentContent[0].id).hide();
		$(contentToShowId).show();
	@else @*/
		new Effect.Fade(currentContent[0].id, {duration: tab_delay});
		new Effect.Appear(contentToShowId, {queue: 'end', duration: tab_delay});
	/*@end
	@*/

	$(contentToShowId).addClassName('current');
	
	if (thisLink.parentNode.className == 'no-subcat')
		$$("#tabnav div")[0].className = 'no-subnav';
	else
		$$("#tabnav div")[0].className = '';
}

function setFontSize(size, oldSize)
{
	createCookie('fontSize', size, 365);
	var bod = $(document.body);
	var wrap = $('wrap');
	if(size === 'small')
	{
		bod.setStyle({ fontSize: '70%' });
		$('small').replace('<span id="small">A</span>');
	}
	else if(size === 'medium')
	{
		bod.setStyle({ fontSize: '86%' });
		$('medium').replace('<span id="medium">A</span>');
	}
	else if(size === 'large')
	{
		bod.setStyle({ fontSize: '110%' });
		$('large').replace('<span id="large">A</span>');
	}
	
	if(oldSize)
	{
		$(oldSize).replace('<a href="#" id="' + oldSize + '" title="' + oldSize.capitalize() + ' Font Size">A</a>');
		$(oldSize).observe('click', fontSizeChange);
	}
	
	resizeTabs();
	resizeColumns();
	var shareThis = $("shareThis")
	if (shareThis && shareThis.className != "shareThis_off") {
		var shareContain = $$("#shareContain")[0];
		positionMenu(shareContain, shareThis.getDimensions().height,  shareThis.offsetLeft)
	}
	if($("home_box")) $("home_box").setStyle({height: "auto"}).setStyle({height: $("home_box").offsetHeight+"px"});
}

function fontSizeChange(e)
{
	Event.stop(e);
	var oldSize = readCookie('fontSize');
	var fontSize = Event.element(e).id;
	setFontSize(fontSize, oldSize);
}

function resizeTabs()
{
	var tabs = $('tab_container');
	if(tabs)
	{
		var maxHeight = $$('#tabs .tab_body').invoke('show').invoke('getHeight').max();
		$$('#tabs .tab_body:not(.current)').invoke('hide');
		tabs.setStyle(
		{
			height: maxHeight + 'px'
		});
	}
}

function resizeColumns()
{
	// If this isn't the first time, there may be a height already set for fade_left
	$('fade_left').setStyle({ height: 'auto' });
	
	// We really only care about the height of our three main content columns
	var maxHeight;
	if($('navigation'))
	{if($('right_sidebar'))
	{
		maxHeight = $('navigation', 'right_sidebar', 'main').invoke('getHeight').max();
	}
	else
	{
		maxHeight = $('navigation', 'main').invoke('getHeight').max();
	}}

	// As long as the main column's height is greatest, then we're fine
	if($('main').getHeight() < maxHeight)
	{
		// One of the other columns is taller, so increase the height of fade_left
		$('fade_left').setStyle({ height: maxHeight + 'px' });
	}
}

function clearTextField()
{
	// if already cleared, do nothing
	if(this._cleared) return;
	this.clear();
	var bodyFontColor = $(document.body).getStyle('color');
	this.setStyle({ color: bodyFontColor});
	this._cleared = true;
}

// BEGIN SHARE COMPONENT

var bookmarkLinks = [{text: "MySpace", className: "myspace", href: "http://www.myspace.com/Modules/PostTo/Pages/?u=[URL]&t=[TITLE]&c=%20"},
					 {text: "Facebook", className: "facebook", href: "http://www.facebook.com/sharer.php?u=[URL]&t=[TITLE]"},
					 {text: "StumbleUpon", className: "stumbleupon", href: "http://www.stumbleupon.com/submit?url=[URL]&title=[TITLE]"},
					 {text: "Technorati", className: "technorati", href: "http://technorati.com/faves?sub=addfavbtn&add=[URL]"},
					 {text: "Reddit", className: "reddit", href: "http://reddit.com/submit?url=[URL]&title=[TITLE]"},
					 {text: "Digg", className: "digg", href: "http://digg.com/submit?url=[URL]&title=[TITLE]&media=News&topic=health&thumbnails=0"},
					 {text: "Del.icio.us", className: "delicious", href: "http://del.icio.us/post?v=4&noui&jump=close&url=[URL]&title=[TITLE]"},
					 {text: "Email to Friend", className: "email", href: "http://www.feedburner.com/fb/a/emailFlare?itemTitle=[TITLE]&uri=[URL]"}];

function createNode(type, attributeList, text) {
	var node = document.createElement(type);
	
	if ((type) && (typeof type == "string")) {
	
		if ((attributeList) && (typeof attributeList == "object")) {
			var keys = Object.keys(attributeList);
			var values = Object.values(attributeList);
			for (i = 0; i < keys.length; i++) {
				if (keys[i] == "className") 
					node.className = values[i];
				else
					node.setAttribute(keys[i],values[i]);
			}
		}
		
		if ((text) && (typeof text == "string")) {
			var txt = document.createTextNode(text);
			node.appendChild(txt);
		}
	}
	
	return node;
}

var pageHREF = encodeURIComponent(window.location.href);
var pageTitle = encodeURIComponent(document.title);

function createListItem(bookmark, bookmarkList) {
	var URL = bookmark.href;
	URL = URL.replace("[URL]",pageHREF);
	URL = URL.replace("[TITLE]",pageTitle);
	var listItem = createNode("li");
	var bookmarkLink = createNode("a", {href: URL, className: bookmark.className}, bookmark.text);
	Event.observe($(bookmarkLink), "click", function(e) { pageTracker._trackPageview("/share_this_page/"+this.className+"/page.html?url="+pageHREF); }); 
	listItem.appendChild(bookmarkLink);
	bookmarkList.appendChild(listItem);
}

function sharePage() {
	// generate main ul
	var shareList = createNode("ul", {id: "share_page"});
	
	bookmarkLinks.each( function(bookmark) { createListItem(bookmark, shareList) } );
	
	// create what's this link
	var whatsThis = createNode("li", {className: "whatsThis"}, "What's This?");
	shareList.appendChild(whatsThis);
	
	Event.observe($(whatsThis), "click", function(e) { pageTracker._trackPageview("/share_this_page/whats_this.html"); toggleWhatsThis("show"); }); 

	// div that encompasses then entire menu
	var shareContain = createNode("div", {id: "shareContain", className: "hidden"})
	shareContain.appendChild(shareList);
	
	// dropshadow
	var dropShadow = createNode("div", {id: "dropShadow", className: "hidden"}," ");
	
	$$('#tab_container.addPrint')[0].appendChild(shareContain);
	$$('#tab_container.addPrint')[0].appendChild(dropShadow);
	
	positionMenu(shareContain, shareContain.offsetTop,  shareContain.offsetLeft)

	// attach mouseout and over events for delayed hide of menu
	Event.observe($$("#shareContain")[0], "mouseout", function(e) { Event.stop(e); toggleDelay=setTimeout(toggleMenu,1000); });
	Event.observe($$("#shareContain")[0], "mouseover", function(e) { Event.stop(e); clearTimeout(toggleDelay); });
	
	Event.observe($$("#shareThis")[0], "mouseout", function(e) { Event.stop(e); if (this.className.indexOf("shareThis_on") >= 0) toggleDelay=setTimeout(toggleMenu,750); });
	Event.observe($$("#shareThis")[0], "mouseover", function(e) { Event.stop(e); clearTimeout(toggleDelay); });
	
	Event.observe($$(".whatsThis")[0], "mouseout", function(e) { $(this).toggleClassName("hover"); });
	Event.observe($$(".whatsThis")[0], "mouseover", function(e) { $(this).toggleClassName("hover"); });
}

function toggleWhatsThis(display) {
	var width=400;
	var height=250;
	var borderWidth=6
	
	var top=((document.viewport.getHeight()/2) - (height/2)) + document.viewport.getScrollOffsets().top;
	var left=(document.viewport.getWidth()/2) - (width/2);
	
	if (this.transBorder == undefined) {
	
		this.transBorder = createNode("div",{id: "transBorder"});
		this.whatsThisContain = createNode("div",{id: "whatsThisContain"});
		this.closeWhatsThis = createNode("span",{id: "closeWhatsThis"}, "Close");

		$(this.transBorder).setStyle({ width: (width+borderWidth*2)+"px",
									   height: (height+borderWidth*2)+"px",
									   top: (top - borderWidth)+"px",
									   left: (left - borderWidth)+"px"
									 });
		$(this.transBorder).hide();
		
		$(this.whatsThisContain).setStyle({ width: width+"px",
										  	height: height+"px",
											top: top+"px",
											left: left+"px"
										  });
		$(this.whatsThisContain).hide();
		
		$$("body")[0].insert({top: transBorder});
		$$("body")[0].insert({top: whatsThisContain});
		$$("div#whatsThisContain")[0].innerHTML='<iframe height="'+ (height-20) +'" frameborder="0" width="'+ width +'" scrolling="auto" id="whatsThisFrame" src="/whatsthis.html" border="0"/>';
		$$("div#whatsThisContain")[0].insert({top: this.closeWhatsThis});
		
		$$("iframe#whatsThisFrame")[0].setAttribute("border","0");
		$$("iframe#whatsThisFrame")[0].setAttribute("frameborder","0");
		
		Event.observe($("closeWhatsThis"), "click", function(e) { toggleWhatsThis("hide")  });
	}
	
	if (display == "show") {
		$("transBorder").show();
		$("whatsThisContain").show();
		
		Event.observe($(window), "scroll", function(e) { toggleWhatsThis("reposition")  });
		Event.observe($(window), "resize", function(e) { toggleWhatsThis("reposition")  });
		Event.observe($(document), "mousedown", function(e) { toggleWhatsThis("hide")  });
	}
	else if (display == "hide") {
		$("transBorder").hide();
		$("whatsThisContain").hide();
		
		Event.stopObserving($(window), "scroll", function(e) { toggleWhatsThis("reposition")  });
		Event.stopObserving($(window), "resize", function(e) { toggleWhatsThis("reposition")  });
		Event.stopObserving($(document), "click", function(e) { toggleWhatsThis("hide")  });
	}
	else {
		$(this.transBorder).setStyle({top: (top - borderWidth)+"px",
								  left: (left - borderWidth)+"px"
								});
		$(this.whatsThisContain).setStyle({ top: top+"px",
								  left: left+"px"
								});
	}
}

function switchClass(obj,class1,class2) {
	if (obj.className == class1) obj.className = class2
	else obj.className = class1
}

var toggleDelay;
function toggleMenu() {
	var shareThis = $$("#shareThis")[0];
	var linkDim = shareThis.getDimensions();
	
	var shareContain = $$("#shareContain")[0];
	var dropShadow = $$("#dropShadow")[0];
	positionMenu(shareContain,linkDim.height,shareThis.offsetLeft);

	shareContain.toggleClassName("hidden");
	dropShadow.toggleClassName("hidden");

	$(shareThis).toggleClassName("shareThis_on");
}

function positionMenu(shareContain, y, x) {
	var dropShadow = $$("#dropShadow")[0];
	$(shareContain).setStyle({
							top: y+'px',
							left: x+'px',
							visibility: "hidden",
							display: "block"
							});
	
	var width, height, top, left;
	width = shareContain.offsetWidth - 6;
	height = shareContain.offsetHeight - 6;
	
	top = y + 5;
	left = x + 7;
	
	dropShadow.setStyle({
							top: top+'px',
							left: left+'px',
							width: width+'px',
							height: height+'px'
							});
	$(shareContain).setStyle({
							visibility: "visible",
							display: ""
							});

}
// END BOOKMARK COMPONENET

var currentQuote = 0;
var quoteTimeout;
function cycleQuote() {
	// $$(".#home_content div.awareness")[0].setStyle({border: "1px solid #FF0"});
	// alert($$(".#home_content div.awareness")[1].id);
	new Effect.Fade($$("#home_content div.awareness")[currentQuote].id, {duration: .5});
	new Effect.Appear($$("#home_content div.awareness")[currentQuote=(currentQuote+1)%($$("#home_content div.awareness").length)].id, {queue:'end', duration: .5});
	// $($$(".#home_content div.awareness")[currentQuote]).fade({duration: 1})
	// $($$(".#home_content div.awareness")[currentQuote=(currentQuote+1)%($$("#home_content div.awareness").length)]).appear({duration: 1})
																										
	quoteTimeout=setTimeout(cycleQuote, 10000);
}

document.observe("dom:loaded", function()
{
	if ($$("#home_content div.awareness").length > 1) {quoteTimeout=setTimeout(cycleQuote, 1000);}
	
	// Read our font size cookie to see if there is a preference
	// only if there is a fontsize widget on the page
	if($('font_adjust'))
	{
		$('font_adjust').innerHTML = $('font_adjust').innerHTML.replace("Change text size:","<span>Change text size:</span>");
		
		var storedSize = readCookie('fontSize');
		if(storedSize)
		{
			// if so, make sure the page knows
			setFontSize(storedSize);
		}
		else
		{
			// set default
			setFontSize('small');
		}
		
		// Add an event listener to each of the font size widget links
		$$('#font_adjust a').invoke('observe', 'click', fontSizeChange);
	}
	
	// A 'print page' link may be added by adding the class 'addPrint' to any #tab_container. Currently, this code only
	// accepts the first such element
	var printable = $$('#tab_container.addPrint')[0];
	if(printable)
	{
		// After checking to see if a print page button should be added, make it so
		// inserts a span element as the first child element of the element selected above
		new Insertion.Top(printable, '<span id="print"><a href="#" title="Print contents of all tabbed sections on this page">Print Page</a></span>');
		// Add the event listener to the link inside the span
		$$('#print a').invoke('observe', 'click', function(e)
		{
			Event.stop(e);
			// Open a new window to display the print preview
			// See printpreview.js for more
			var printWindow = window.open('../../prettyprint.html?page=' + self.location.pathname, 'name', 'height=400,width=600,resizable=yes,scrollbars=yes,location=yes,toolbar=yes');
			if (window.focus) { printWindow.focus(); }
		});
		
		// dynamically creates dropdowns for emailing page to friend and bookmarking page
		var shareThisLink = createNode("a", {id: "shareThis", className: "shareThis_off", href: "#"}, "Share This Page");
		new Insertion.Top(printable, shareThisLink);
		$$("a#shareThis").invoke('observe', 'click', function(e)
		{
			Event.stop(e);
			
			toggleMenu();
			clearTimeout(toggleDelay);
		});
		
		sharePage();
		
	}
	
	// Righthand Side Accordion
	if($('right_sidebar'))
	{
		// For every 'folder' title...
		$$('#right_sidebar #spotlights li span.title').each(function(o)
		{
			// which isn't the active tab...
			if(!o.up().hasClassName('active'))
				// hide it's child list items
				o.next('ul').immediateDescendants().invoke('hide');
			// and add an event listener to switch tabs
			Event.observe(o, 'click', rightHandAccordion);
		});
		
		// Add extra right side 'folder'
		new Insertion.Bottom('spotlights', '<li class="last"></li>');
	}

	// Form fields
	$$("form input[type='text']").each(function(tf)
	{
		// Add a method which will clear the text field on first focus
		tf.observe('focus', clearTextField.bindAsEventListener(tf));
	});
	

	// Lower middle tab navigation
	if($('tabs'))
	{
		// Add extra elements for styles
		$$('#tabnav ul li a').each(function(a)
		{
			var wrapper = document.createElement('span');
			$(wrapper).update(a.innerHTML);
			a.replaceChild(wrapper, a.firstChild);
		});
		new Insertion.Bottom('tabnav', '<div><div></div></div>');
		
		// Setup event handlers
		$$('#tabs #tabnav li a').each(function(o)
		{
			Event.observe(o, 'click', tabNav.bindAsEventListener(o))
		});
			
		if (!$('podcast-index')) {
			// Hide all but current tab body
			$$('#tabs div.tab_body:not(.current)').invoke('hide');
		}
	}

	// Evil, evil layout height fix
	resizeColumns();
	
	// Add element to markup in IE6 to enable em-based min/max width emulation
	/*@cc_on
	/*@if (@_jscript_version < 5.7)
		var emtester = document.createElement('div');
		emtester.setAttribute('id', 'em');
		emtester.style.width = "1.0em";
		document.body.appendChild(emtester);
		document.getElementById('wrap').style.setExpression("width", "setWidth()", "JavaScript");
	/*@end
	@*/
	
		$$("div#test_site form").invoke('observe', 'submit', function(e)
		{
			if ((window.location.href == "http://www.aids.gov/") || (window.location.href == "http://www.aids.gov/index.html"))
				pageTracker._trackPageview("/find_hivtest_site/home.html");
			else
				pageTracker._trackPageview("/find_hivtest_site/internal.html");
		});
		
});

function setWidth()
{
	var docElem = (document.compatMode && (document.compatMode == 'CSS1Compat')) ? document.documentElement : document.body;
	
	if (docElem.clientWidth > document.getElementById('em').style.pixelWidth * 85)
	{
		return '85em';
	}
	else if(docElem.clientWidth < 962)
	{
		return '960px';
	}
	else 
	{
		return '99%';
	}
}
