$(function () {
	var iOS = navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/);
	window.setTimeout('poll()', 5000);
	if (iOS) $('#video1').show(); 
	if ($('#drawers').size()) $('#drawers').accordion({ header: 'h3' });
});
var now = new Date();
var pollTimestamp = now.format('ddHHMMss');

function poll() {
	$.getJSON('/watch/status/', function (data) {
		processData(data);
	});
}

function changeRes(res) {
	/* this function is in dev and may be unncessary 
	if (res == 'low') so.file = lowres;
	else if (res == 'high') alert(so['file']); */
}

function processData(data) {
	if (data['page_action']['command'] == 'force_restart') {
		//alert(parseInt(data['page_action']['timestamp'])+' > '+pollTimestamp+' = '+(parseInt(data['page_action']['timestamp']) > pollTimestamp));
		var timestamp = parseInt(data['page_action']['timestamp']);
		if ((pollTimestamp - timestamp) <= 2) reloadPage(); // allow 2 seconds to maximize effectiveness
	}
	if (data['status_message'] != '') showMessage(data['status_message']);
	else hideMessage();
	if (data['active_segment']) activateSegment(data['active_segment']);
	pollTimestamp = data['timestamp'];
	var hour = pollTimestamp.slice(2,4);
	var minutes = pollTimestamp.slice(4,6);
	if (hour < 12) {
		var time = hour+':'+minutes+' am';
	} else {
		var time = (hour == 12 ? 12 : hour - 12)+':'+minutes+' pm';
	}
	$('#time').html(time);
	window.setTimeout('poll()', parseInt(data['refresh_rate']) * 1000);
}
function activateSegment(id) {
	if (!$('#segment'+id).hasClass('active')) {
		$('#segments li').removeClass('active');
		$('#segment'+id).removeClass('inactive').addClass('active');
		deactivePrevious($('#segment'+id), 1);	
	}
}

function deactivePrevious(elem, i) {
	var p = elem.prev();
	if (p.size()) {
		if (i <= 5) p.addClass('inactive');
		else p.addClass('hidden');
		deactivePrevious(p, i+1);
	}
}

function showMessage(text) {
	$('#ad:visible').fadeOut('slow', function () {		
		$('#message').append('<p>'+text+'</p>');
	});
}
function hideMessage() {
	$('#message p:visible').fadeOut('slow', function () {
		$('#message p').remove();
		window.setTimeout('showAd()', 5000);
	});
}
function showAd() {
	$('#ad:hidden').fadeIn('medium');
}

function reloadPage() {
	window.location.reload();
}
