// Author: Shuns (www.netgrow.com.au/files), Version: 1.1
var dump3=function(object, showTypes){var dump='';var st=typeof showTypes=='undefined' ? true : showTypes;var winName='dumpWin';var browser=_dumpIdentifyBrowser();var w=760;var h=500;var leftPos=screen.width ?(screen.width-w)/ 2 : 0;var topPos=screen.height ?(screen.height-h)/ 2 : 0;var settings='height='+h+',width='+w+',top='+topPos+',left='+leftPos+',scrollbars=yes,menubar=yes,status=yes,resizable=yes';var title='Dump';var script='function tRow(s){t=s.parentNode.lastChild;tTarget(t, tSource(s));}function tTable(s){var switchToState=tSource(s);var table=s.parentNode.parentNode;for(var i=1;i < table.childNodes.length;i++){t=table.childNodes[i];if(t.style){tTarget(t, switchToState);}}}function tSource(s){if(s.style.fontStyle=="italic"||s.style.fontStyle==null){s.style.fontStyle="normal";s.title="click to collapse";return "open";}else{s.style.fontStyle="italic";s.title="click to expand";return "closed";}}function tTarget(t, switchToState){if(switchToState=="open"){t.style.display="";}else{t.style.display="none";}}';dump+=(/string|number|undefined|boolean/.test(typeof(object))||object==null)? object : recurse(object, typeof object);winName=window.open('', winName, settings);if(browser.indexOf('ie')!=-1||browser=='opera'||browser=='ie5mac'||browser=='safari'){winName.document.write('<html><head><title> '+title+' </title><script type="text/javascript">'+script+'</script><head>');winName.document.write('<body>'+dump+'</body></html>');}else{winName.document.body.innerHTML=dump;winName.document.title=title;var ffs=winName.document.createElement('script');ffs.setAttribute('type', 'text/javascript');ffs.appendChild(document.createTextNode(script));winName.document.getElementsByTagName('head')[0].appendChild(ffs);}winName.focus();function recurse(o, type){var i;var j=0;var r='';type=_dumpType(o);switch(type){case 'regexp':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>RegExp: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'date':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Date: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'function':var t=type;var a=o.toString().match(/^.*function.*?\((.*?)\)/im);var args=(a==null||typeof a[1]=='undefined'||a[1]=='')? 'none' : a[1];r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Arguments: </i></td><td'+_dumpStyles(type,'td-value')+'>'+args+'</td></tr><tr><td'+_dumpStyles('arguments','td-key')+'><i>Function: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'domelement':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Name: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeName.toLowerCase()+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Type: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeType+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Value: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeValue+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>innerHTML: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.innerHTML+'</td></tr>';j++;break;}if(/object|array/.test(type)){for(i in o){var t=_dumpType(o[i]);if(j < 1){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+'</th></tr>';j++;}if(typeof o[i]=='object' && o[i]!=null){r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else if(typeof o[i]=='function'){r+='<tr><td'+_dumpStyles(type ,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else{r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? ' ['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+o[i]+'</td></tr>';}}}if(j==0){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+' [empty]</th></tr>';}r+='</table>';return r;};};_dumpStyles=function(type, use){var r='';var table='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;cell-spacing:2px;';var th='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;text-align:left;color: white;padding: 5px;vertical-align :top;cursor:hand;cursor:pointer;';var td='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;vertical-align:top;padding:3px;';var thScript='onClick="tTable(this);" title="click to collapse"';var tdScript='onClick="tRow(this);" title="click to collapse"';switch(type){case 'string':case 'number':case 'boolean':case 'undefined':case 'object':switch(use){case 'table':r=' style="'+table+'background-color:#0000cc;"';break;case 'th':r=' style="'+th+'background-color:#4444cc;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccddff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'array':switch(use){case 'table':r=' style="'+table+'background-color:#006600;"';break;case 'th':r=' style="'+th+'background-color:#009900;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccffcc;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'function':switch(use){case 'table':r=' style="'+table+'background-color:#aa4400;"';break;case 'th':r=' style="'+th+'background-color:#cc6600;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#fff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'arguments':switch(use){case 'table':r=' style="'+table+'background-color:#dddddd;cell-spacing:3;"';break;case 'td-key':r=' style="'+th+'background-color:#eeeeee;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;}break;case 'regexp':switch(use){case 'table':r=' style="'+table+'background-color:#CC0000;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FF0000;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FF5757;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'date':switch(use){case 'table':r=' style="'+table+'background-color:#663399;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#9966CC;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#B266FF;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'domelement':switch(use){case 'table':r=' style="'+table+'background-color:#FFCC33;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FFD966;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FFF2CC;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;}return r;};_dumpIdentifyBrowser=function(){var agent=navigator.userAgent.toLowerCase();if (typeof window.opera != 'undefined'){return 'opera';} else if (typeof document.all != 'undefined'){if (typeof document.getElementById != 'undefined'){var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, '$1').replace(/ /, '');if(typeof document.uniqueID != 'undefined') {if (browser.indexOf('5.5') != -1){return browser.replace(/(.*5\.5).*/, '$1');}else{return browser.replace(/(.*)\..*/, '$1');}}else{return 'ie5mac';}}}else if(typeof document.getElementById != 'undefined'){if (navigator.vendor.indexOf('Apple Computer, Inc.')!=-1) {return 'safari';}else if(agent.indexOf('gecko')!=-1) {return 'mozilla';}}return false;};_dumpType=function(obj){var t=typeof(obj);if(t=='function'){var f=obj.toString();if((/^\/.*\/[gi]??[gi]??$/).test(f)){return 'regexp';}else if((/^\[object.*\]$/i).test(f)){t='object'}}if(t !='object'){return t;}switch(obj){case null:return 'null';case window:return 'window';case document:return document;case window.event:return 'event';}if(window.event &&(event.type==obj.type)){return 'event';}var c=obj.constructor;if(c !=null){switch(c){case Array:t='array';break;case Date:return 'date';case RegExp:return 'regexp';case Object:t='object';break;case ReferenceError:return 'error';default:var sc=c.toString();var m=sc.match(/\s*function(.*)\(/);if(m !=null){return 'object';}}}var nt=obj.nodeType;if(nt !=null){switch(nt){case 1:if(obj.item==null){return 'domelement';}break;case 3:return 'string';}}if(obj.toString !=null){var ex=obj.toString();var am=ex.match(/^\[object(.*)\]$/i);if(am !=null){var am=am[1];switch(am.toLowerCase()){case 'event':return 'event';case 'nodelist':case 'htmlcollection':case 'elementarray':return 'array';case 'htmldocument':return 'htmldocument';}}}return t;};

// ---------------------------------------------------------------------------------------------------------------------
// [rel="external"] also becomes [target="_blank"] (opens external links in new windows)
// ---------------------------------------------------------------------------------------------------------------------
function externalLinks()
{ 
	if (!document.getElementsByTagName)
	{
		return; 
	}
	var anchors = document.getElementsByTagName("a"); 
	for (var i = 0; i < anchors.length; i++)
	{ 
		var anchor = anchors[i];
		 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel")) 
		{
			var rels = anchor.getAttribute("rel").split(/\s+/);
			for (var j = 0; j < rels.length; j++)
			{
				if (rels[j].toLowerCase() == "external")
				{
					anchor.setAttribute("target", "_blank");
				}
				break;
			} 
		}
	} 
}

Event.observe(window, "load", externalLinks);

// ---------------------------------------------------------------------------------------------------------------------
// IE6 PNG fix
// ---------------------------------------------------------------------------------------------------------------------
var IEPNGFix=window.IEPNGFix||{};IEPNGFix.tileBG=function(elm,pngSrc,ready){var data=this.data[elm.uniqueID],elmW=Math.max(elm.clientWidth,elm.scrollWidth),elmH=Math.max(elm.clientHeight,elm.scrollHeight),bgX=elm.currentStyle.backgroundPositionX,bgY=elm.currentStyle.backgroundPositionY,bgR=elm.currentStyle.backgroundRepeat;if(!data.tiles){data.tiles={elm:elm,src:'',cache:[],img:new Image(),old:{}};}var tiles=data.tiles,pngW=tiles.img.width,pngH=tiles.img.height;if(pngSrc){if(!ready&&pngSrc!=tiles.src){tiles.img.onload=function(){this.onload=null;IEPNGFix.tileBG(elm,pngSrc,1);};return tiles.img.src=pngSrc;}}else{if(tiles.src)ready=1;pngW=pngH=0;}tiles.src=pngSrc;if(!ready&&elmW==tiles.old.w&&elmH==tiles.old.h&&bgX==tiles.old.x&&bgY==tiles.old.y&&bgR==tiles.old.r){return;}var pos={top:'0%',left:'0%',center:'50%',bottom:'100%',right:'100%'},x,y,pc;x=pos[bgX]||bgX;y=pos[bgY]||bgY;if(pc=x.match(/(\d+)%/)){x=Math.round((elmW-pngW)*(parseInt(pc[1])/100));}if(pc=y.match(/(\d+)%/)){y=Math.round((elmH-pngH)*(parseInt(pc[1])/100));}x=parseInt(x);y=parseInt(y);var repeatX={'repeat':1,'repeat-x':1}[bgR],repeatY={'repeat':1,'repeat-y':1}[bgR];if(repeatX){x%=pngW;if(x>0)x-=pngW;}if(repeatY){y%=pngH;if(y>0)y-=pngH;}this.hook.enabled=0;if(!({relative:1,absolute:1}[elm.currentStyle.position])){elm.style.position='relative';}var count=0,xPos,maxX=repeatX?elmW:x+0.1,yPos,maxY=repeatY?elmH:y+0.1,d,s,isNew;if(pngW&&pngH){for(xPos=x;xPos<maxX;xPos+=pngW){for(yPos=y;yPos<maxY;yPos+=pngH){isNew=0;if(!tiles.cache[count]){tiles.cache[count]=document.createElement('div');isNew=1;}var clipR=(xPos+pngW>elmW?elmW-xPos:pngW),clipB=(yPos+pngH>elmH?elmH-yPos:pngH);d=tiles.cache[count];s=d.style;s.behavior='none';s.left=xPos+'px';s.top=yPos+'px';s.width=clipR+'px';s.height=clipB+'px';s.clip='rect('+(yPos<0?0-yPos:0)+'px,'+clipR+'px,'+clipB+'px,'+(xPos<0?0-xPos:0)+'px)';s.display='block';if(isNew){s.position='absolute';s.zIndex=-999;if(elm.firstChild){elm.insertBefore(d,elm.firstChild);}else{elm.appendChild(d);}}this.fix(d,pngSrc,0);count++;}}}while(count<tiles.cache.length){this.fix(tiles.cache[count],'',0);tiles.cache[count++].style.display='none';}this.hook.enabled=1;tiles.old={w:elmW,h:elmH,x:bgX,y:bgY,r:bgR};};IEPNGFix.update=function(){for(var i in IEPNGFix.data){var t=IEPNGFix.data[i].tiles;if(t&&t.elm&&t.src){IEPNGFix.tileBG(t.elm,t.src);}}};IEPNGFix.update.timer=0;if(window.attachEvent&&!window.opera){window.attachEvent('onresize',function(){clearTimeout(IEPNGFix.update.timer);IEPNGFix.update.timer=setTimeout(IEPNGFix.update,100);});}

var applyPngFixToRules = ["ul#footer", "div#header h1", "div#header ul li a", "div#copy div.box h2", "p#article-media-browser-image-previous", "p#article-media-browser-image-next"];

// only IE7 has native XHR support; IE6 and below has attachEvent and no native XHR
if (window.attachEvent && !window.XMLHttpRequest)
{
	document.observe(
		"dom:loaded",
		function()
		{
			// array of CSS rules that will get the PNG fix
			$$(applyPngFixToRules.join(", ")).each(
				function(elem)
				{
					elem.setStyle(
						{
							behavior: "url(/htc/ie6png.htc)"
						}
					);
				}
			);
		}
	);
}

// ---------------------------------------------------------------------------------------------------------------------
// Suckerfish
// ---------------------------------------------------------------------------------------------------------------------
function bindSuckerfish(target)
{
	target.attachEvent("onmouseover", function()
	{
		target.className += " sfhover";
	});
	
	target.attachEvent("onmouseout", function()
	{
		target.className = target.className.replace(new RegExp(" sfhover\\b"), "");
	});
}

// only IE7 has native XHR support; IE6 and below has attachEvent and no native XHR
if (window.attachEvent && !window.XMLHttpRequest)
{
	window.attachEvent("onload", function()
	{
		var lis = document.getElementsByTagName("li");
		for (var i = 0; i < lis.length; i++)
		{
			bindSuckerfish(lis[i]);
		}
	});
}

// ---------------------------------------------------------------------------------------------------------------------
// Header map animation
// ---------------------------------------------------------------------------------------------------------------------
function animateHeaderMap()
{
	new Effect.Tween(
		"header",
		0,
		999,
		{
			duration: 45,
			transition: Effect.Transitions.linear,
			afterFinish: animateHeaderMap
		},
		animateHeaderMapTween
	);
}

function animateHeaderMapTween(value)
{
	$("header").setStyle(
		{
			backgroundPosition: Math.floor(value) + "px 60px"
		}
	);
}

if (!window.attachEvent || window.XMLHttpRequest)
{
	document.observe("dom:loaded", animateHeaderMap);
}

// ---------------------------------------------------------------------------------------------------------------------
// Poll Ajax
// ---------------------------------------------------------------------------------------------------------------------
function submitPoll(origin, resultsOnly)
{
	var form = Element.extend(origin).up("form");

	// get the selected radio
	var inputs = form.getInputs("radio", "data[Poll][response]");
	var isResponse1 = null;

	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs[i].checked)
		{
			isResponse1 = (inputs[i].value == 1);
			break;
		}
	}

	if (isResponse1 === null && !resultsOnly)
	{
		alert("Please select a response for the poll.");
	}
	else
	{
		// get the height of the box first before clearing its contents
		var box = form.down("div.poll-vote");
		var height = box.getHeight();
		box.setStyle(
			{
				height: height + "px"
			}
		);

		// clear its content
		box.childElements().each(
			function(elem)
			{
				elem.remove();
			}
		);

		// give it a trobber
		box.addClassName("loading");

		// animate it up and do the Ajax
		new Effect.Tween(
			box,
			height,
			20,
			{
				duration: 0.4,
				afterFinish: function()
				{
					new Ajax.Request(
						(!resultsOnly ? "/poll/vote/" + (isResponse1 ? 1 : 0) : "/poll/results"),
						{
							onSuccess: function(response)
							{
								box.removeClassName("loading");

								// animate it down
								box.setStyle(
									{
										height: "",
										display: "none"
									}
								);
									
								box.innerHTML = response.responseText;

								var newHeight = box.getHeight();

								new Effect.Tween(
									box,
									20,
									newHeight,
									{
										duration: 0.4,
										afterSetup: function()
										{
											box.setStyle(
												{
													display: ""
												}
											);
										},
										afterFinish: function()
										{
											box.setStyle(
												{
													height: ""
												}
											);
										}
									},
									function(value)
									{
										box.setStyle(
											{
												height: value + "px"
											}
										);
									}
								);
							},
							onFailure: function(response)
							{
								box.removeClassName("loading");

								alert("Ajax request error: server returned HTTP " + response.status + " " + response.statusText);
							}
						}
					);
				}
			},
			function(value)
			{
				box.setStyle(
					{
						height: value + "px"
					}
				);
			}
		);
	}
}

// ---------------------------------------------------------------------------------------------------------------------
// Top News rotation
// ---------------------------------------------------------------------------------------------------------------------
var currentArticleIndex = 0;
var articleRotationTimeout = null;

function rotateTopNews()
{
	if (articleRotationTimeout !== null)
	{
		var nextIndex = currentArticleIndex + 1;
		if (nextIndex >= articles.length)
		{
			nextIndex = 0;
		}
		switchTopNews(nextIndex);
	}

	articleRotationTimeout = window.setTimeout(rotateTopNews, 6500);
}

function switchTopNews(articleIndex)
{
	var totalDuration = 0.6;
	
	var topThumb = $("top-news-thumbnails");
	var topNews = $("top-news");
	if (!topNews.hasClassName("animating") && currentArticleIndex != articleIndex  && topThumb != null)
	{
		window.clearTimeout(articleRotationTimeout);

		topNews.addClassName("animating");
		
		// cross-fade the two thumbnails while other stuff is happening

		var fromThumbnail = $("top-news-thumbnails").childElements()[currentArticleIndex];
		var toThumbnail = $("top-news-thumbnails").childElements()[articleIndex];
		
		new Effect.Opacity(
			fromThumbnail,
			{
				from: 1,
				to: 0.5,
				duration: totalDuration
			}
		);
		
		new Effect.Opacity(
			toThumbnail,
			{
				from: 0.5,
				to: 1,
				duration: totalDuration
			}
		);
		
		//var rotatedImage = $$("#top-news p.image");

		//if ( rotatedImage == null ) {
		//	topNews.removeClassName("animating");
		//	return;
		//}

		var elems =
		[
			topNews.down("p.image"),
			topNews.down("h3"),
			topNews.down("p.teaser")
		];

		var stackSize = elems.length;
		Effect.multiple(
			elems,
			Effect.Opacity,
			{
				speed: 0,
				duration: totalDuration / 2,
				from: 1,
				to: 0,
				afterFinish: function()
				{
					stackSize--;

					if (stackSize <= 0)
					{
						// change the current article to the new one
						topNews.down("p.image a").href = articles[articleIndex].url;
						topNews.down("p.image a img").src = articles[articleIndex].image;
						topNews.down("h3 a").href = articles[articleIndex].url;
						topNews.down("h3 a").update(articles[articleIndex].headline);
						topNews.down("p.teaser").update(articles[articleIndex].teaser);
						
						stackSize = elems.length;
						
						// fade in the new one (well, DOM-wise the same one)
						Effect.multiple(
							elems,
							Effect.Opacity,
							{
								from: 0,
								to: 1,
								speed: 0,
								duration: totalDuration /2,
								afterFinish: function()
								{
									stackSize--;
									
									if (stackSize <= 0)
									{
										currentArticleIndex = articleIndex;
										topNews.removeClassName("animating");
									}
								}
							}
						);
					}
				}
			}
		);
	}
}

function fixBorkedPositioning(elem)
{
	if (window.attachEvent && !window.XMLHttpRequest)
	{
		var border = elem.getStyle("border");
		if (!border)
		{
			border = "none";
		}

		$("footer").setStyle(
			{
				border: "1px solid transparent"
			}
		);
		
		$("footer").setStyle(
			{
				border: border
			}
		);
	}
}

function fixFooterPosition()
{
	fixBorkedPositioning($("footer"));
}

document.observe(
	"dom:loaded",
	function()
	{
		if (typeof articles !== "undefined")
		{
			var total = 2 * articles.length;
			var stackSize = total;

			var p = $$("div#top-news p.loading")[0];

			var images = new Array();
			for (var i = 0; i < articles.length; i++)
			{
				images[i * 2] = new Image();
				images[i * 2 + 1] = new Image();

				images[i * 2].onload = images[i * 2 + 1].onload = images[i * 2].onerror = images[i * 2 + 1].onerror = function()
				{
					stackSize--;

					var percent = Math.floor(100 - ((stackSize / total) * 100));
					p.down("span").innerHTML = percent + "%";
					p.setStyle(
						{
							width: 360 * (percent / 100) + "px"
						}
					);

					if (stackSize <= 0)
					{
						// build the articles current main feature DOM
						var currentTopNews = new Element(
							"div",
							{
								id: "current-top-news"
							}
						).insert(
							new Element(
							"p",
							{
								"class": "image"
							}
						).insert(new Element(
							"a",
							{
								href: articles[0].url
							}
						).insert(new Element(
							"img",
							{
								src: articles[0].image,
								alt: ""
							}
						))));

						currentTopNews.insert(
							new Element("h3").insert(
								new Element(
									"a",
									{
										href: articles[0].url
									}
								).update(articles[0].headline)));

						currentTopNews.insert(
							new Element(
								"p",
								{
									"class": "teaser"
								}).update(articles[0].teaser));

						// ...and the top news thumbnails
						var topNewsThumbnails = new Element(
							"ul",
							{
								id: "top-news-thumbnails"
							}
						);

						for (var i = 0; i < articles.length; i++)
						{
							var img = new Element(
								"img",
								{
									src: articles[i].thumbnail,
									alt: ""
								}
							);

							img.observe(
								"click",
								function(event)
								{
									switchTopNews(event.element().up("li").previousSiblings().length);
								}
							);
							
							var li = new Element("li");
							
							topNewsThumbnails.insert(
								li.insert(
									new Element(
										"a",
										{
											href: "javascript:void(0)"
										}
									).insert(img)));
									
							if (i != 0)
							{
								li.setStyle(
									{
										opacity: 0.5
									}
								);
							}
						}

						// zomg animate it!
						var div = p.up("div");
						p.remove();

						currentTopNews.setStyle(
							{
								display: "none"
							}
						);
						
						topNewsThumbnails.setStyle(
							{
								display: "none"
							}
						);
						
						div.insert(currentTopNews);
						div.insert(topNewsThumbnails);

						var targetHeight = currentTopNews.getHeight() + topNewsThumbnails.getHeight();

						new Effect.Tween(
							div,
							0,
							targetHeight,
							{
								afterSetup: function()
								{
									currentTopNews.setStyle(
										{
											display: ""
										}
									);
									
									topNewsThumbnails.setStyle(
										{
											display: ""
										}
									);
								},
								afterUpdate: fixFooterPosition,
								afterFinish: function()
								{
									div.setStyle(
										{
											height: ""
										}
									);
								}
							},
							function(value)
							{
								div.setStyle(
									{
										height: Math.ceil(value) + "px"
									}
								);
							}
						);
					}
				};

				images[i * 2].src = articles[i].image;
				images[i * 2 + 1].src = articles[i].thumbnail;
			}

			rotateTopNews();
		}
	}
);

// ---------------------------------------------------------------------------------------------------------------------
// Featured article limits
// ---------------------------------------------------------------------------------------------------------------------
function limitFeatured(elemId, count)
{
	var ul = $(elemId);

	if (typeof ul.currentCount === "undefined")
	{
		ul.currentCount = 5;
	}

	if (!ul.hasClassName("animating") && count != ul.currentCount)
	{
		var elems = $$("div#"+elemId+" ul#"+elemId+"-list li");

		if (elems.length < count)
		{
			// there aren't this many to show in the first place; just show all of them
			count = null;
		}
		
		if (count === null)
		{
			count = elems.length;
		}

		// going to fewer elements?
		if (count < ul.currentCount)
		{
			// will need to hide extras
			var effect = Effect.BlindUp;
			var effectElems = elems.slice(count);
		}
		// then more elements
		else
		{
			var effect = Effect.BlindDown;
			var effectElems = elems.slice(ul.currentCount, count);
		}

		var stackSize = effectElems.length;

		if (stackSize > 0)
		{
			ul.addClassName("animating");

			Effect.multiple(
				effectElems,
				effect,
				{
					speed: 0,
					duration: 0.5,
					afterFinish: function()
					{
						stackSize--;

						if (stackSize <= 0)
						{
							ul.currentCount = count;
							ul.removeClassName("animating");
						}

						fixFooterPosition();
					}
				}
			);
		}
	}
}

// ---------------------------------------------------------------------------------------------------------------------
// Add even/odd classes to .evenoddify
// ---------------------------------------------------------------------------------------------------------------------
document.observe(
	"dom:loaded",
	function()
	{
		$$(".evenoddify").each(
			function(elem)
			{
				var children = elem.childElements();
				for (var i = 0; i < children.length; i++)
				{
					children[i].addClassName(i % 2 == 0 ? "odd" : "even");
				}
			}
		);
	}
);

// ---------------------------------------------------------------------------------------------------------------------
// Country scroller thing
// ---------------------------------------------------------------------------------------------------------------------
var countryListTimeout = null;

if (!window.attachEvent || window.XMLHttpRequest)
{
	document.observe(
		"dom:loaded",
		function()
		{
			$$("div#country-list ul li").each(
				function(li)
				{
					var title = li.down("a").childNodes[0].nodeValue.strip();
					var country = title.toLowerCase().replace(/the_/, "").replace(/ /, "_").replace(/__/, "_");

					li.setStyle(
						{
							backgroundImage: "url(/img/flags/" + country + ".png)"
						}
					);

					li.setAttribute("title", title);
				}
			);
		}
	);
}

function scrollCountryList(delta)
{
	if (countryListTimeout === null)
	{
		shiftCountryList(delta);
	}
}

function cancelScrollCountryList()
{
	window.clearTimeout(countryListTimeout);
	countryListTimeout = null;
}

function shiftCountryList(delta)
{
	var movement = calculateCountryListMovement(delta);
	var ul = $$("div#country-list ul")[0];

	var min = 707 - ul.getWidth();
	var max = 25;

	var marginLeft = parseInt(ul.getStyle("marginLeft").replace(/px/, "")) + delta;

	var cancel = false;
	if (marginLeft < min)
	{
		marginLeft = min;
		cancel = true;
	}
	else if (marginLeft > max)
	{
		marginLeft = max;
		cancel = true;
	}

	ul.setStyle(
		{
			marginLeft: marginLeft + "px"
		}
	);
		
	if (!movement.hitsStop)
	{
		countryListTimeout = window.setTimeout(
			function()
			{
				shiftCountryList(delta)
			},
			30
		);
	}
}

function calculateCountryListMovement(delta)
{
	var retval =
	{
		ul: $$("div#country-list ul")[0]
	};

	var min = 707 - retval.ul.getWidth();
	var max = 25;

	var marginLeft = parseInt(retval.ul.getStyle("marginLeft").replace(/px/, "")) + delta;

	if (marginLeft < min)
	{
		retval.marginLeft = min;
		retval.hitsStop = true;
	}
	else if (marginLeft > max)
	{
		retval.marginLeft = max;
		retval.hitsStop = true;
	}
	else
	{
		retval.marginLeft = marginLeft;
		retval.hitsStop = false;
	}

	return retval;
}
	
if (!window.attachEvent || window.XMLHttpRequest)
{
	document.observe(
		"dom:loaded",
		function()
		{
			var elems = $$("div#country-list ul");
			if (elems.length == 1)
			{
				var ul = elems[0];

				if (ul.getElementsByTagName("li").length >= 7)
				{
					// make the UL just wide enough to accomodate everything without wrapping
					ul.setStyle(
						{
							width: ((ul.down("li").getWidth() + 20) * ul.childElements().length) + "px"
						}
					);

					// bind the arrows
					var left = $$("p#country-list-left a")[0];
					var right = $$("p#country-list-right a")[0];

					left.observe(
						"mouseover",
						function()
						{
							scrollCountryList(10);
						}
					);

					left.observe("mouseout", cancelScrollCountryList);

					right.observe(
						"mouseover",
						function()
						{
							scrollCountryList(-10);
						}
					);

					right.observe("mouseout", cancelScrollCountryList);
				}
			}
		}
	);
}

// ---------------------------------------------------------------------------------------------------------------------
// Make the Flash MP3 player not stupid
// ---------------------------------------------------------------------------------------------------------------------
function ap_stopAll()
{
}

// ---------------------------------------------------------------------------------------------------------------------
// Article media switcher zomgness
// ---------------------------------------------------------------------------------------------------------------------
function switchMediaBrowser(origin, mediaType)
{
	var origin = Element.extend(origin);

	if (!origin.up("li").hasClassName("current"))
	{
		$("article-media-browser").childElements().each(
			function(elem)
			{
				elem.removeClassName("current");
			}
		);

		origin.up("li").addClassName("current");

		$("article-media-browser-contents").childElements().each(
			function(elem)
			{
				elem.removeClassName("current");
			}
		);

		$("article-media-browser-" + mediaType).addClassName("current");
	}
}

var currentArticleImageIndex = 0;

function previousArticleImage()
{
	if (!$("current-image").hasClassName("animating"))
	{
		switchArticleImage(-1);
	}
}

function nextArticleImage()
{
	if (!$("current-image").hasClassName("animating"))
	{
		switchArticleImage(1);
	}
}

function switchArticleImage(delta)
{
	var currentImage = $("current-image");
	currentImage.cleanWhitespace();
	
	currentImage.addClassName("animating");
	new Effect.Tween(
		currentImage,
		0,
		(delta > 0 ? -currentImage.getWidth() : currentImage.getWidth()),
		{
			duration: 0.5,
			afterFinish: function()
			{
				currentArticleImageIndex += delta;
				
				var src = "/img/media/thumbnails/" + articleImages[currentArticleImageIndex].id + "-388x230.jpg";

				var image = new Image();
				image.onload = function()
				{
					currentImage.down("img").src = src;

					if (currentArticleImageIndex == 0)
					{
						$("article-media-browser-image-previous").addClassName("disabled");
					}
					else
					{
						$("article-media-browser-image-previous").removeClassName("disabled");
					}
					
					if (currentArticleImageIndex == articleImages.length - 1)
					{
						$("article-media-browser-image-next").addClassName("disabled");
					}
					else
					{
						$("article-media-browser-image-next").removeClassName("disabled");
					}

					for (var i = 0; i < currentImage.childNodes.length; i++)
					{
						var node = currentImage.childNodes[i];

						if (typeof node.nodeName !== "undefined")
						{
							node.nodeValue = articleImages[currentArticleImageIndex].description;
						}
					}

					new Effect.Tween(
						currentImage,
						(delta > 0 ? currentImage.getWidth() : -currentImage.getWidth()),
						0,
						{
							duration: 0.5,
							afterFinish: function()
							{
								currentImage.removeClassName("animating");
							}
						},
						function(value)
						{
							currentImage.setStyle(
								{
									left: Math.floor(value) + "px"
								}
							);
						}
					);
				};

				image.onerror = function()
				{
					alert("Error loading image.");
				};

				image.src = src;
			}
		},
		function(value)
		{
			currentImage.setStyle(
				{
					left: Math.floor(value) + "px"
				}
			);
		}
	);
}

function popupVideo(mediaId)
{
	var fadeout = $("page-fadeout");
	fadeout.setStyle(
		{
			opacity: 0.4,
			display: "block"
		}
	);

	$("video-player-" + mediaId).setStyle(
		{
			display: "block"
		}
	);
}

function closeVideo(mediaId)
{
	var fadeout = $("page-fadeout");
	fadeout.setStyle(
		{
			display: "none"
		}
	);

	$("video-player-" + mediaId).setStyle(
		{
			display: "none"
		}
	);
}

