var xmlns = 'http://www.w3.org/1999/xhtml';

/* Internet Explorer... */
if(!document.createElementNS)
{
	document.createElementNS = function(ns, el)
	{
		return document.createElement(el);
	};
}

if(!window.DOMInitialised)
{
	Event.onDOMReady(init);
}
else
{
	window.setTimeout(init, 1);
}

function init()
{
	document.getElementsByClassName('popup').each(function (obj) { Event.observe(obj, 'click', popup, false); });
	
	window.showboxRunner = window.setInterval(showboxTimer, 1000);
};

/**
 * Pop up a link in a new window.
 * @param evt Event
 */
function popup(evt)
{
	window.open(Event.element(evt).href, null);
	Event.stop(evt);
};

/**
 * Runs the showbox.
 */
function showboxTimer()
{
	if(window.showboxNextTime)
	{
		var nextTime = window.showboxNextTime;
	}
	else
	{
		return;
	}

	if($('showbox_time').getElementsByTagName('strong').length == 0)
	{
		return;
	}
	else
	{
		var timer = $('showbox_time').getElementsByTagName('strong')[0];
	}

	var currentTime = Math.round(new Date().getTime() * 0.001);

	// During the show (between the show start time and 4 hours from the start)
	if(currentTime >= nextTime && currentTime < nextTime + 14400)
	{
		var el = document.createElementNS(xmlns, 'span');
		el.id = 'showbox_time';

		var link = document.createElementNS(xmlns, 'a');
		link.href = 'http://www.etn.fm';
		Event.observe(link, 'click', popup, false);
		link.appendChild(document.createTextNode('On the air! Tune in now!'));
		el.appendChild(link);

		timer.parentNode.parentNode.replaceChild(el, timer.parentNode);
		window.clearInterval(window.showboxRunner);
		window.showboxRunner = window.setTimeout(resetShowboxTimer, nextTime + 14400 - currentTime);
	}
	// Before/after the show
	else
	{
		if(currentTime > nextTime)
		{
			nextTime += 604800;
		}
		
		var diff = nextTime - currentTime;
		var time = '';
		time = ((diff % 60).toString().length == 1 ? '0' : '') + (diff % 60);
		diff = Math.floor(diff / 60);
		time = ((diff % 60).toString().length == 1 ? '0' : '') + (diff % 60) + ':' + time;
		diff = Math.floor(diff / 60);
		time = (diff.toString().length == 1 ? '0' : '') + diff + ':' + time;

		timer.replaceChild(document.createTextNode(time), timer.childNodes[0]);
	}
};

/**
 * Resets the showbox to 168 hours.
 */
function resetShowboxTimer()
{
	var el = document.createElementNS(xmlns, 'span');
	el.id = 'showbox_time';
	
	var strong = document.createElementNS(xmlns, 'strong');
	strong.appendChild(document.createTextNode('168:00:00'));
	el.appendChild(strong);
	el.appendChild(document.createTextNode(' until next show!'));

	$('showbox_time').parentNode.replaceChild(el, $('showbox_time'));
	
	window.clearTimeout(window.showboxRunner);
	window.showboxRunner = window.setInterval(showboxTimer, 1000);
};