
var Radio = {
	timeout: 15000, // milliseconds
	interval: null,
	initStreams: [2,1,53,6,5,12,3,29,13,7],
	viewEle: null,
	showAll: false,
	data: {},
	jsonURL: '/radiodata.json?',
	popup: null,
	streamPath: 'http://www.rr.com/radio/index.cfm?startstream=',
	loadChannel: function(event) {
		var ele = Event.element(event);
		var channelID = $(ele).findParent('audio').getAttribute('id');
		var url = Radio.streamPath + channelID;
		var name = 'RRRADIO';
		var args = 'width=320,height=425,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no';
		Radio.popup = window.open(url,name,args);
	},
	init: function() {
		if (!$('radioModule')) return;
		Radio.viewEle = $$('div#radioModule div.titleBar a.btn')[0];
		Radio.setupEvents();
		Radio.loadData();
		Radio.interval = setInterval(Radio.loadData,Radio.timeout);
	},
	loadData: function() {
		var time = new Date().getTime();
		new Ajax.Request(Radio.jsonURL+time, {
			method: 'get',
			onSuccess: function(tr) {
				Radio.data = tr.responseText.evalJSON();
				Radio.callback();
			}
		});
	},
	setupEvents: function() {
		$(Radio.viewEle).observe('click',Radio.viewAll);
		$($('radioModule').select('a.btn')[0]).observe('click',Radio.preventDefault);
	},
	preventDefault: function(ev) {
		ev.stop();
	},
	viewAll: function() {
		$(Radio.viewEle).stopObserving('click',Radio.viewAll);
		$(Radio.viewEle).observe('click',Radio.viewSome);
		$(Radio.viewEle).select('span')[0].update('Top '+ Radio.initStreams.length);
		
		Radio.showAll = true;
		Radio.loadData();
	},
	viewSome: function() {
		$(Radio.viewEle).stopObserving('click',Radio.viewSome);
		$(Radio.viewEle).observe('click',Radio.viewAll);
		$(Radio.viewEle).select('span')[0].update('View All');
		
		Radio.showAll = false;
		Radio.loadData();
	},
	callback: function() {
		Radio.clear();
		Radio.sorter();
		Radio.genresDisplay();
		Radio.streamsDisplay();
		Radio.hideGenres();
	},
	clear: function() {
		while($('radioChannels').childNodes.length>0) {
			$('radioChannels').removeChild($('radioChannels').childNodes[0]);
		}
	},
	genresDisplay: function() {
		var last = $H(Radio.data.genres).values().length;
		var genreDiv = new Element('div', { 'class': 'item' });
		var heading  = new Element('h6');
		var anchor   = new Element('a', { 'class': 'genre' } ).setStyle({ 'cursor': 'default' });
		
		$H(Radio.data.genres).each(function(genre,i) {
			var div = $('radioChannels').appendChild(genreDiv.cloneNode(true));
			$(div).setAttribute('id',genre[1].id);
			if (i==0) $(div).addClassName('first');
			var h6 = $(div).appendChild(heading.cloneNode(true));
			var a = $(h6).appendChild(anchor.cloneNode(true));
			$(a).update(genre[1].title);
		});
	},
	streamsDisplay: function() {
		var p     = new Element('p',{'class': 'audio'});
		var str   = new Element('strong');
		var a     = new Element('a');
		var mdash = document.createTextNode('\u00a0\u2013\u00a0');
		
		$H(Radio.data.streams).each(function(stream,i) {
			var streamID = parseInt(stream.key,10);
			var stream = stream.value;
			
			var genreID = Radio.data.genres[stream.genreID].id;
			var node = $(genreID).appendChild(p.cloneNode(true));
				node.setAttribute('id',stream.startID);
			var chan = node.appendChild(str.cloneNode(true));
			if (stream.explicit.toBool()) chan.addClassName('explicit');
			var chanlink = $(chan).appendChild(a.cloneNode(true));
			$(chanlink).observe('click',Radio.loadChannel);
			$(chanlink).update(stream.title);
			$(chan).appendChild(mdash.cloneNode(true));
			var song = $(node).appendChild(a.cloneNode(true));
			$(song).update(stream.song.artist +' | '+ stream.song.title);
			$(song).observe('click',Radio.loadChannel);
			
			if (Radio.showAll == true) return;
			if (Radio.initStreams.indexOf(streamID) == -1) $(node).hide();
		});
	},
	hideGenres: function() {
		$A($('radioChannels').select('div.item')).each(function(genre) {
			var paragraphs = $(genre).select('p');
			var count = 0;
			paragraphs.each(function(p) {
				if (! $(p).visible()) count++;
			});
			if (count == paragraphs.length) {
				$(genre).hide();
			}
		});
	},
	sorter: function() {
		// Genre Sort
		var temp = {};
		var gOrder = $H(Radio.data.genres).keys().sort(Radio.genreTitleSort);
		gOrder.each(function(key) {
			temp[key] = Radio.data.genres[key];
		});
		Radio.data.genres = temp;
		
		// Channel Sort
		var temp = {};
		var sOrder = $H(Radio.data.streams).keys().sort(Radio.streamTitleSort);
		sOrder.each(function(key) {
			temp[key] = Radio.data.streams[key];
		});
		Radio.data.streams = temp;
	},
	genreTitleSort: function(a,b) {
		var Atitle = Radio.data.genres[a].title;
		var Btitle = Radio.data.genres[b].title;
		return (Atitle<Btitle) ? -1 : (Btitle<Atitle) ? 1 : 0;
	},
	streamTitleSort: function(a,b) {
		var Atitle = Radio.data.streams[a].title;
		var Btitle = Radio.data.streams[b].title;
		return (Atitle<Btitle) ? -1 : (Btitle<Atitle) ? 1 : 0;
	}
};

document.observe('dom:loaded',Radio.init);

