//
// Declare global variables that we need.
//
var mf, hasQuicktime = false;
var playlistList, albumList, messageList, currentMessage;


//
// Initial startup stuff.
//
function onLoad()
{
	setTimeout('onTimedLoad()', 500);
}


//
// This function is called a short while after the page is ready,
// by this time everything else should be initialized.
//
function onTimedLoad()
{
	//
	// We don't want lightbox to hide our stuff.
	//
	Lightbox.options.hideElements = false;

	//
	// Force the MooFlow to be visible from the start.
	//
	mf.MooFlow.style.height = (mf.MooFlow.getSize().x * mf.options.heightRatio) + 'px';
	mf.MooFlow.style.visibility = 'visible';

	//
	// Load up the playlists.
	//
	loadPlaylists();
}


//
// Initial MooFlow setup.
//
var myMooFlowPage = {
        start: function(){
                mf = new MooFlow($('MooFlow'), {
                        stylePath: 'libs/mooflow/MooFlow.css',
                        useSlider: true,
                        useAutoPlay: false,
                        useCaption: true,
                        useResize: false,
                        useWindowResize: true,
                        useMouseWheel: true,
                        useKeyInput: true,
			factor: 85,
			topFactor: 0.19,
                        heightRatio: 0.267
                });

		//
		// Setup the flowComplete handler.
		//
		mf.flowStart = function() {
			loadAlbum(mf.index);
		}
        }

};


//
// Setup the playlists.
//
function loadPlaylists()
{
	var url = '/mediacenter/mediacenter.json';

	new Request.JSON({
		onComplete: function(data){
			playlistList = data;
			buildPlaylists();
		}.bind(this),
		onFailure: function(){
			alert('failed');
		}.bind(this)
	}, this).get(url);
}


//
// Build the list of playlists.
//
function buildPlaylists()
{
	var tabs = $('groupTabs');
	var img, link, div, tab;


	//
	// Remove all existing tabs.
	//
	while (tabs.childNodes.length)
		tabs.removeChild(tabs.childNodes[0]);

	//
	// Add in the spacer tab.
	//
	div = document.createElement('DIV');
	div.className = 'tab';
	div.style.width = '20px';
	div.appendChild(document.createTextNode('\u00a0'));
	tabs.appendChild(div);

	//
	// Add in all the new tabs.
	//
	for (var i = 0; i < playlistList.length; i++) {
		//
		// Create the new tab element.
		//
		tab = document.createElement('DIV');
		tab.className = 'tab';

		//
		// Create the left part of the tab.
		//
		div = document.createElement('DIV');
		div.className = 'tabLeft';
		div.appendChild(document.createTextNode('\u00a0'));
		tab.appendChild(div);

		//
		// Create the middle part of the tab and the title/link.
		//
		div = document.createElement('DIV');
		div.className = 'tabMiddle';
		link = document.createElement('A');
		link.href = 'javascript:loadPlaylist(' + i + ');';
		link.onmouseover = function() { highlightTab(this.parentNode.parentNode, 1); };
		link.onmouseout = function() { highlightTab(this.parentNode.parentNode, 0); };
		link.appendChild(document.createTextNode(playlistList[i]['title']));
		div.appendChild(link);
		tab.appendChild(div);

		//
		// Create the right part of the tab.
		//
		div = document.createElement('DIV');
		div.className = 'tabRight';
		div.appendChild(document.createTextNode('\u00a0'));
		tab.appendChild(div);

		tabs.appendChild(tab);
	}

	//
	// By default start with the first playlist active.
	//
	loadPlaylist(0);
}


//
// Load up the given playlist index.
//
function loadPlaylist(index)
{
	var content = playlistList[index]['content'];

	//
	// If we don't have any content loaded yet, then load
	// it up.
	//
	if ($type(content) !== 'object') {
		var url = playlistList[index]['target'];

		new Request.JSON({
			onComplete: function(data){
				if ($chk(data)) {
					playlistList[index]['content'] = data;
					buildPlaylist(data);
				}
			}.bind(this),
			onFailure: function(){
				alert('failed');
			}.bind(this)
		}, this).get(url);
	}
	else {
		buildPlaylist(content);
	}
}


//
// Build the playlist with the given content.
//
function buildPlaylist(content)
{
	albumList = content['images'];
	mf.master = content;
	mf.index = 0;
	mf.clearMain();
}


//
// Load the messages for the given album.
//
function loadAlbum(index)
{
	var content = albumList[index]['content'];

	//
	// If we don't have any content loaded yet, then load
	// it up.
	//
	if ($type(content) !== 'array') {
		var url = albumList[index]['target'];

		new Request.JSON({
			onComplete: function(data){
				albumList[index]['content'] = data;
				buildAlbum(data);
			}.bind(this),
			onFailure: function(){
				alert('failed');
			}.bind(this)
		}, this).get(url);
	}
	else {
		buildAlbum(content);
	}
}


//
// Build the list of messages in this album.
//
function buildAlbum(content)
{
	var html = '';
	var table = $('playlistContentTable');
	var tbody;
	var tr;
	var td;


	//
	// Save the message list for later use.
	//
	messageList = content;

	//
	// Empty out the message list.
	//
	while (table.childNodes.length)
		table.removeChild(table.childNodes[0]);

	for (var i = 0; i < messageList.length; i++) {
		tr = table.insertRow(-1);
		tr.className = (i & 1 ? 'secondary' : 'primary');

		td = document.createElement('TD');
		td.className = 'titleColumn';
		link = document.createElement('A');
		link.href = 'javascript:showMessage(' + i + ');';
		link.appendChild(document.createTextNode(dehtmlize(messageList[i]['title'])));
		td.appendChild(link);
		tr.appendChild(td);

		td = document.createElement('TD');
		td.className = 'artistColumn';
		link = document.createElement('A');
		link.href = 'javascript:showMessage(' + i + ');';
		link.appendChild(document.createTextNode(messageList[i]['artist']));
		td.appendChild(link);
		tr.appendChild(td);

		td = document.createElement('TD');
		link = document.createElement('A');
		link.href = 'javascript:showMessage(' + i + ');';
		link.appendChild(document.createTextNode(messageList[i]['date']));
		td.appendChild(link);
		tr.appendChild(td);
	}

	$('playlistContentView').scrollTop = 0;

	//
	// IE7 is retarted. If I don't set this manually each time
	// I reload the content it will not display the scroll bar.
	//
	$('playlistContentView').style.overflowy = 'auto';
}


//
// Show the notes for the current message.
//
function showNotes()
{
	var url = currentMessage['src'], pages = Array(), i;


	for (i = 1; i <= currentMessage['notes']; i++) {
		pages.push([url + '-' + i + '.png', '']);
	}

	Lightbox.open(pages, 0);
}


//
// Show the audio player for the current message.
//
function showAudioPlayer()
{
	var mydiv = $('mediaPlayer'), url = currentMessage['src'] + '.mp3';

	mydiv.innerHTML = '<embed' +
		'	width="320"' +
		'        height="256"' +
		'        src="libs/player2/player8.swf"' +
		'        pluginspage="http://www.macromedia.com/go/getflashplayer"' +
		'        align="right"' +
		'        FlashVars="audio=' + url + '&image=/images/hdcbug.png&autoplay=on&autoload=on&volume=70&fgcolor=#ff0000"' +
		'        type="application/x-shockwave-flash">' +
		'</embed>';
}


//
// Show the flash player for the current message.
//
function showFlashPlayer()
{
	var mydiv = $('mediaPlayer'), url = currentMessage['src'] + '.flv';

	mydiv.innerHTML = '<embed' +
		'	width="320"' +
		'        height="256"' +
		'        src="libs/player2/player8.swf"' +
		'        pluginspage="http://www.macromedia.com/go/getflashplayer"' +
		'        align="right"' +
		'        FlashVars="movie=' + url + '&autoplay=on&autoload=on&volume=70&fgcolor=#ff0000"' +
		'        type="application/x-shockwave-flash">' +
		'</embed>';
}


//
// Show the quicktime player for the current message.
//
function showQuicktimePlayer()
{
	var mydiv = $('mediaPlayer'), url = currentMessage['src'] + '.mov';

	mydiv.innerHTML = '<embed src="' + url + '" ' +
			'width="320" height="256" autoplay="true" ' +
			'controller="true" loop="false" scale="aspect" ' +
			'align="right" ' +
			'pluginspage="http://www.apple.com/quicktime/"></div>';
}


//
// Show the quicktime player for the current message in full screen (well, as close
// as we can get).
//
function showFullscreenPlayer()
{
	var url = currentMessage['src'] + '-hq.mov';


	//
	// Stop the current player.
	//
	clearPlayer();

	window.open(url, 'HiResPlayer', 'resizable=no,width=640,height=496,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no');
}


//
// Clear out the player area.
//
function clearPlayer()
{
	var mydiv = $('mediaPlayer');

	mydiv.innerHTML = '';
}


//
// Show the given message.
//
function showMessage(index)
{
	var html = '', url, artworkURL, hasWatch = false;


	//
	// Get the currently selected message and the base url.
	//
	currentMessage = messageList[index];
	url = currentMessage['src'];

	//
	// Show the album artwork.
	//
	artworkURL = albumList[mf.index]['src'];
	$('artworkView').innerHTML = '<img src="' + artworkURL + '" width="256" height="214" />';

	//
	// Show the notes links.
	//
	html = '';
	if (currentMessage['notes'] > 0) {
		html = '<div align="center" style="vertical-align: middle;">';
		html += '<table border="0" cellpadding="0" cellspacing="0"><tr>';
		html += '<td><a href="javascript:showNotes();"><img class="icon" src="mediacenter/images/notes.gif"></a></td>';
		html += '<td><a href="javascript:showNotes();">message notes</a></td>';
		html += '<td><a href="/download.php?file=' + url + '.pdf"><img class="icon" src="mediacenter/images/download.gif"></a></td>';
		html += '</tr></table></div>';
	}
	$('messageNotes').innerHTML = html;

	//
	// Build the message information.
	//
	html = currentMessage['title'] + '<br />' +
		'<small>' + currentMessage['artist'] + ' - ' +
		currentMessage['date'] + '</small>' +
		'<hr width="75%" />';
	$('mediaInformation').innerHTML = html;
	$('mediaInformation').style.visibility = 'visible';

	//
	// Build the links for watching and listening.
	//
	html = '<div class="mediaBlockContainer">';
	html += '<div class="mediaBlock">';
	html += '<table border="0" cellspacing="0" cellpadding="0"><tr>';
	html += '<td><img class="icon" src="mediacenter/images/watch.gif" /></td>';
	html += '<td><a class="mediaLink" href="javascript:showAudioPlayer();">audio</a>';
	html += ' | ';

	//
	// Disabled low quality quicktime for now, because we have
	// 1 hour video files the header information that needs
	// to be downloaded by the server is in the 2-3MB range and
	// causes a massive delay even on 768kb DSL.
	//
	if (0 && hasQuicktime == true && currentMessage['video'] & 2) {
		html += '<a class="mediaLink" href="javascript:showQuicktimePlayer();">low quality</a>';
		hasWatch = true;
	}
	if (hasWatch == false && currentMessage['video'] & 1) {
		html += '<a class="mediaLink" href="javascript:showFlashPlayer();">low quality</a>';
		hasWatch = true;
	}
	if (hasWatch == false)
		html += 'low quality';
	html += ' | ';

	if (currentMessage['video'] & 4 && hasQuicktime == true)
		html += '<a class="mediaLink" href="javascript:showFullscreenPlayer();">high quality</a>';
	else
		html += 'high quality';

	html += '</td></tr></table></div>';

	//
	// Build all the download links.
	//
	html += '<div class="mediaBlock">';
	html += '<table border="0" cellspacing="0" cellpadding="0"><tr>';
	html += '<td><img class="icon" src="mediacenter/images/download.gif" /></td>';

	html += '<td><a class="mediaLink" href="/download.php?file=' + url + '.mp3">audio</a>';
	html += ' | ';
	if (currentMessage['video'] & 2 && hasQuicktime == true)
		html += '<a class="mediaLink" href="/download.php?file=' + url + '.mov">low quality</a>';
	else
		html += 'low quality';
	html += ' | ';
	if (currentMessage['video'] & 4 && hasQuicktime == true)
		html += '<a class="mediaLink" href="/download.php?file=' + url + '-hq.mov">high quality</a>';
	else
		html += 'high quality';

	html += '</td></tr></table></div>';

	//
	// Put up the iTunes subscribe block.
	//
	html += '<div class="mediaBlock">';
	html += '<table border="0" cellspacing="0" cellpadding="0"><tr>';
	html += '<td><img class="icon" src="mediacenter/images/rss.gif" /></td>';
	html += '<td>';
	html += '<a class="mediaLink" target="_blank" href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=118806335">subscribe</a>';
	html += '</td></tr></table></div>';

	html += '</div>';

	//
	// Show the media links, we need to update this to dynamically build
	// what is shown.
	//
	$('mediaLinks').innerHTML = html;
	$('mediaLinks').style.visibility = 'visible';

	//
	// Show the default media player after a
	// 1/2 second delay.
	//
	setTimeout('showDefaultMediaPlayer()', 500);
}


//
// Called after delay to show the default media player.
//
function showDefaultMediaPlayer()
{
	var filled = false;


	//
	// If we have video, show the video. Disabled quicktime, see
	// above.
	//
	if (0 && currentMessage['video'] & 2 && hasQuicktime == true)
		showQuicktimePlayer();
	else if (currentMessage['video'] & 1)
		showFlashPlayer();
	else
		showAudioPlayer();
}


//
// De-html a string. Convert &amp; to &, etc.
//
function dehtmlize(str){
	str = str.replace(/\&apos\;/g,"'");
	str = str.replace(/\&quot\;/g,"\"");
	str = str.replace(/\&gt\;/g,">");
	str = str.replace(/\&lt\;/g,"<");
	str = str.replace(/\&amp\;/g,"&");

	return str;
}


//
// Highlight a tab (or unhighlight it). We have to use .gif files
// because IE6 does not recognize png transparency as a background.
//
function highlightTab(tab, highlight)
{
	for (i = 0; i < tab.childNodes.length; i++) {
		child = tab.childNodes[i];

		if (child.className == 'tabLeft') {
			if (highlight == true)
				child.style.backgroundImage = 'url(mediacenter/images/roundhighlight-left.gif)';
			else
				child.style.backgroundImage = '';
		}

		if (child.className == 'tabMiddle') {
			if (highlight == true)
				child.style.backgroundImage = 'url(mediacenter/images/roundhighlight-middle.gif)';
			else
				child.style.backgroundImage = '';
		}

		if (child.className == 'tabRight') {
			if (highlight == true)
				child.style.backgroundImage = 'url(mediacenter/images/roundhighlight-right.gif)';
			else
				child.style.backgroundImage = '';
		}
	}

	return true;
}


//
// On-load events.
//
window.addEvent('domready', myMooFlowPage.start);
window.addEvent('domready', onLoad);
