var resizeTimerID = null;
var resizeNum = 0; 
var resizeLastWidth = 0; 

/*** COOKIE FUNCTIONS ***************************************************************************/

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);
}

/*** PEN FUNCTIONS ******************************************************************************/

function setSearchQuery() {

	var searchDefaultValue = $("#search_query").val();

	$("#search_query").focus(function() {
		$(this).addClass("on");
		if($(this).val() == searchDefaultValue) $(this).val('');

	}).blur(function() {
		if(!$(this).val()) $(this).val(searchDefaultValue);
		if($(this).val() == searchDefaultValue) $(this).removeClass("on");
	});
}

function setImageCaptions() {

	if($("body").is(".ie6")) return;

	$("img.image_item[alt]").each(function() {

		var $t = $(this);
		var $a = $t.parent();
		var alt = $t.attr('alt');

		$t.wrap("<div>").parent()
			.css('float', $t.css('float'))
			.css('width', $t.width())
			.attr('class', $t.attr('class'))
			.addClass('image_caption')
			.append("<span>" + alt + "</span>");


		if($a.is("a")) {
			// if the image is linked, then move the link so its only applying to the image and not the new caption 
			var href = $a.attr('href'); 
			$a.replaceWith($a.children()); 
			$t.wrap('<a href="' + href + '"></a>');
		}

		$t.css('float', 'none');

	});
}

function setImageOriginals() {
	// if the image has an original (enlargement) then make it's link go through thickbox
	$("a > img.has_original").each(function() {
		$t = $(this); 
		var href = $t.parent().attr('href'); 
		if(href.indexOf('/process/assets/images/') == -1) return; // skip non-image links
		$t.parent().addClass('thickbox'); 
		$t.removeAttr('alt'); 
	}); 
}

function setColumnHeights() {

	if($("#sidebar").size() > 0) {

		var sidebarHeight = $("#sidebar").height();
		var bodycopyHeight = $("#bodycopy").height();

		if(sidebarHeight >= bodycopyHeight) {
			$("#bodycopy").height(sidebarHeight); 

		} else if($("#bodycopy").css("height") != "auto") {
			$("#bodycopy").css("height", "auto"); 
		}
	}

	if($("#body_home").size() == 0) {
		var h = $("#footer").offset().top - $("#section").offset().top; 
		$("#section").height(h); 
	}

}

function windowResizedHomepage() {

	// adjust number of news items show on homepage
	// wider window shows more news items

	var $news = $("#bodycopy ul.subpages").eq(0); 
	var $items = $news.children("li"); 
	var width = $("#bodycopy").width();
	var numItems = $items.size();
	var targetNum = 3; // minimum number of items shown

	if(width < resizeLastWidth) return; // don't reduce number of items on the page
	
	if(width > 650) targetNum++; 
	if(width > 800) targetNum++;
	if(width > 950) targetNum++; 

	$items.each(function(cnt) {
		if(cnt > (targetNum-1)) $(this).hide();
			else $(this).show();
	}); 
}

function windowResizedFunc() {

	// execute any functions that need to be called after a resize
	// this is called after a short delay to prevent multiple events getting thrown for one resize

	var isHomepage = $("#body_home").size() > 0; 
		
	if(isHomepage) windowResizedHomepage(); 
	//if($("body").is(".ie6")) alert('resize'); 

	setColumnHeights(); 
	resizeNum++; 
	resizeLastWidth = $("#bodycopy").width(); 
	clearTimeout(resizeTimerID);
	resizeTimerID = null; 
}


function windowResized() {

	// IE and Safari throw lots of resize events for each resize
	// so this function prevents us from using more than one of them

	//if(resizeTimerID != null) clearTimeout(resizeTimerID); 	
	//if($("#bodycopy").width() == resizeLastWidth) return; // IE6
	//if(resizeTimerID == null) resizeTimerID = setTimeout("windowResizedFunc()", 500); 
	if(!$("body").is(".ie6")) windowResizedFunc();
}


function setTopicIdentifiers() {
	$("span.parent_path:contains(news/)").addClass("topic_item").addClass("topic_news");
	$("span.parent_path:contains(events/)").addClass("topic_item").addClass("topic_events"); 
	$("span.parent_path:contains(publications/)").addClass("topic_item").addClass("topic_publications"); 
}

function setNavTreeParents() {
	$("#section a.on").parents("li:eq(1)").children("a").addClass("on"); 
}

function setCalendarIcon() {
	var $ds = $("#sidebar p.datestamp"); 
	if($ds.size() < 1) return;

	var date = $ds.text(); 
	var day = $ds.text().substring(date.indexOf(' ')+1, date.indexOf(','));
	$ds.append('<em>' + day + '</em>'); 
}

function setTextResize() {

	function doTextResize(c) {
		$("body").removeClass("text_larger").removeClass("text_largest"); 
		$("body").addClass("text_" + c); 
		$("#text_resizer a").removeClass('on'); 
		$("#text_resize_" + c).addClass('on'); 
		createCookie("textsize", c, 30); 
		if(resizeNum > 0) setColumnHeights(); 
	}

	var p = '<li id="text_resizer">' + 
		'<a id="text_resize_normal" href="#" title="Recommended text size">A</a> ' + 
		'<a id="text_resize_larger" href="#" title="Larger text size">A</a> ' + 
		'<a id="text_resize_largest" href="#" title="Largest text size">A</a> ' + 
		'</li>'; 

	$("#tools li:last").before(p); 

	$("#text_resize_larger").click(function() { doTextResize('larger'); return false; }); 
	$("#text_resize_largest").click(function() { doTextResize('largest'); return false; }); 
	$("#text_resize_normal").click(function() { doTextResize('normal'); return false; }); 

	var c = readCookie('textsize'); 

	if(c) doTextResize(c); 
		
}

function setAvToggles() {

	var moveToSummary = function() {

		var $t = $(this); 
		var img = $t.css('backgroundImage');
		var href = $t.parent().children("a").eq(0).attr('href'); 

		img = img.substring(img.indexOf('(')+1, img.lastIndexOf(')')); 	
		if(img.indexOf('"') > -1) img = img.substring(1, img.length - 1); // IE adds quotes around this property, so remove them
		img = "<a href='" + href + "'><img src='" + img + "' /></a>"; 
		
		$t.hide().parent().children("span.summary").append("&nbsp;&nbsp;").append(img); 
	}

	$("#content ul.subpages li span.toggle_video").each(moveToSummary); 
	$("#content ul.subpages li span.toggle_audio").each(moveToSummary); 
}

function setIcons() {
	$("#content a.video").append("&nbsp;<img src='/process/templates/styles/images/icons/icon_video.gif' alt='video' />"); 
	$("#content a.audio").append("&nbsp;<img src='/process/templates/styles/images/icons/icon_audio.gif' alt='audio' />"); 
}


function setInternetExploder() {
	$("form fieldset legend").parent().addClass("has_legend"); 	
	if(parseInt(jQuery.browser.version) < 7) $("body").addClass("ie6"); 
		else $("body").addClass("ie7"); 
}

function setTools() {
	$("#tools .tools_print").click(function() { window.print(); }); 
}

/*
function setInventories() {
	$("#section ul li a:contains(Search)").prepend('<img src="/process/templates/styles/images/icons/16/icon_search.png" alt="search" style="display: inline;" /> '); 
}
*/

/***********************************************************************************************************************/

$(document).ready(function() {

	//if(navigator.platform.indexOf('Mac') > -1) $("body").addClass("mac"); 
	if($.browser.msie) setInternetExploder();

	setImageCaptions();
	setImageOriginals();


	if($("#topnav").css("display") != 'block') return; // print stylesheet, so abort 
	setSearchQuery(); 

	if($("body").attr("id") == 'body_topics') setTopicIdentifiers(); 

	setTextResize(); 
	setAvToggles(); 
	setIcons();
	$(window).resize(windowResized); 
	windowResizedFunc();
	setCalendarIcon();
	setTools();

	// if($("#body_inventories").size() > 0) setInventories(); 

	//setNavTreeParents();

	// if image is first thing in bodycopy, then move it above headlines (looks nicer)
	//$("#content #bodycopy > h1 + h2 + p > .image_right").insertBefore("#content #bodycopy > h1").addClass("image_top"); 


}); 

