// Tab group helper script {{{

var untab_msg = "Open all sub-pages";

function tg_anchor(obj, anchor)
{
	if (anchor)
		obj.attr('href', anchor);
	else
		obj.removeAttr('href');
}
function tg_setuntabmsg(msg)
{
	untab_msg = msg;
}

$(document).ready(function() {
	$('.tabgroup').each(function() {
		var group = $(this);
		var list = group.find('ul:first');
		var links = list.find('li.tg_tablink');
		var cnt = links.length;
		list.show();
		// Set up listeners
		links.each(function(i) {
			if (i != 0) $(this).css({borderTop: 'none'});
			$(this).css({cursor: 'pointer'});
			$(this).find('a').click(function(e) {
				var a = $(this);
				e.stopPropagation();
				list.find('li').removeClass('tg_currenttab');
				a.parent().addClass('tg_currenttab');
				group.find('.tg_tab').hide();
				group.find('.tg_tab').eq(i).show();
				group.data('index', i);
				if (!group.hasClass('tg_addquicknav')) return;
				var qn = group.find('.tg_quicknav a');
				window.setTimeout(function() {
					tg_anchor(qn.eq(0), a.parent().prev().find('a').attr('href'));
					tg_anchor(qn.eq(1), a.parent().next().find('a').attr('href'));
				}, 200);
			});
		});
		// Listener for tab remover
		if (group.hasClass('tg_adduntab')) {
			list.append('<li class="tg_untablink">'+ untab_msg);
			list.find('.tg_untablink').click(function() {
				list.next().removeClass('tg_body');
				group.find('.tg_tab').show();
				group.find('.tg_quicknav').hide();
				list.hide();
			});
		}
		// Decorate body and add quicknav
		if (group.hasClass('tg_addquicknav')) {
			group.append('<div class="tg_quicknav"><a href="#">Previous</a> | <a href="#">Next</a></div>');
			group.find('div:last a:nth-child(1)').click(function(e) {
				e.stopPropagation();
				list.find('li.tg_tablink > a').eq(group.data('index')-1).click();
			});
			group.find('div:last a:nth-child(2)').click(function(e) {
				e.stopPropagation();
				list.find('li.tg_tablink > a').eq(group.data('index')+1).click();
			});
		}
		// Set up initial view
		list.next().addClass('tg_body');
		group.find('.tg_tab').hide();
		list.find('li:first > a').click();
	});
	if (location.hash.match(/^#(.+)$/)) {
		var anchor = $("a[name='"+RegExp.$1+"']");
		if (!anchor) return;
		var tab = anchor.parent().eq(0);
		if (!tab.hasClass('tg_tab')) return;
		var body = tab.parent().eq(0);
		if (!body.hasClass('tg_body')) return;
		var idx = body.children().index(tab);
		var group = body.parent().eq(0);
		if (!group.hasClass('tabgroup')) return;
		group.find('ul:first a').eq(idx).click();
	}
});

// }}}

// MP3 player {{{
var mp3_listener = new Object();
mp3_listener.onInit = function()
{
	this.position = 0;
	this.bar = $('<div id="playstatus">Now playing: <strong id="playtitle"></strong> (<span id="playtime"></span> of <span id="playlength"></span>, loaded <span id="playloaded"></span>%)</div>');
	this.current = null;
	this.paused = false;
	this.playlist = false;
	this.eatmore = false;
};
mp3_listener.onUpdate = function()
{
	// Song ended or stopped
	if (this.isPlaying != "true" && !this.eatmore) {
		this.eatmore = true;
		if (this.paused) return;
		if (this.playlist) {
			window.setTimeout(function() { play(getNext()); }, 50);
			return;
		}
		// Clean up buttons etc.
		stop();
		$('#playstatus').remove();
		if ($('#playlistmode:checked').length) this.playlist = true;
		this.current = null;
		return;
	}
	$('#playtime').text(calcTime(this.position));
	$('#playlength').text(calcTime(this.duration));
	$('#playloaded').text(this.bytesPercent);
};

function calcTime(msecs)
{
	var mins = Math.floor(msecs / 60000);
	var secs = Math.floor(msecs % 60000 / 1000);
	if (secs < 10) secs = "0"+ secs;
	return mins +":"+ secs;
}
function getCurrent()
{
	if (mp3_listener.current == null) return null;
	return $('a[href='+ mp3_listener.current +']').prev();
}
function getNext()
{
	var obj = getCurrent();
	if (!obj) return null;
	var href = obj.next().attr('href');
	var i = $.inArray(href, mp3_listener.songs)+1;
	if ($('#loopmode:checked').length && i >= mp3_listener.songs.length) i = 0;
	if (i >= mp3_listener.songs.length) return null;
	return $('a[href='+mp3_listener.songs[i]+']').prev();
}
function isPlaying(obj)
{
	return obj.attr('src') == BASE_URI+'/resources/play.png';
}

function $f(key, val) { document.getElementById('player').SetVariable(key, val); }
function play(obj)
{
	if (obj.parent().parent().get(0).nodeName.toLowerCase() == 'td')
		var title = obj.parent().parent().find('a:first').text();
	else
		var title = obj.next().text();
	var link = obj.next();
	var href = link.attr('href');
	var bar = mp3_listener.bar;
	if (href != mp3_listener.current) {
		if (mp3_listener.current != null) pause();
		else $('body').append(bar);
		$('#playtitle').text(title);
		$('#playtime').text('?:??');
		$('#playlength').text('?:??');
		$('#playloaded').text('??');
		mp3_listener.current = href;
		$f('method:setUrl', href);
		$f('enabled', 'true');
		$('#playtime').click(function() { $f('method:setPosition', Number(mp3_listener.position)+10000); });
		$('#playtoggle,#playnext,#playkill').remove();
		bar.append('<a id="playtoggle" href="#">(pause playing)</a>');
		$('#playtoggle').click(function() { if (isPlaying(obj)) play(obj); else pause(); return false; });
		bar.append('<a id="playkill" href="#">kill player</a>');
		$('#playkill').click(function() { stop(); return false; });
		if (getNext()) {
			bar.append('<a id="playnext" href="#">play next</a>');
			$('#playnext').click(function() { play(getNext()); return false; });
		}
	}
	mp3_listener.eatmore = false;
	mp3_listener.paused = false;
	$f('method:play', '');
	obj.attr('src', BASE_URI+'/resources/pause.png');
	$('#playtoggle').text('(pause playing)');
}
function pause()
{
	var obj = getCurrent();
	mp3_listener.paused = true;
	$f('method:pause', '');
	obj.attr('src', BASE_URI+'/resources/play.png');
	var bar = mp3_listener.bar;
	$('#playtoggle').text('(resume playing)');
}
function stop()
{
	var obj = getCurrent();
	if (!obj) return;
	mp3_listener.playlist = false;
	$f('method:stop', '');
	obj.attr('src', BASE_URI+'/resources/play.png');
}
function setupPlayer()
{
	$(document).ready(function() {
		$('body').append('<object id="player" type="application/x-shockwave-flash" data="'+BASE_URI+'/resources/player.swf" width="1" height="1"><param name="movie" value="'+BASE_URI+'/resources/player.swf"><param name="AllowScriptAccess" value="always"><param name="FlashVars" value="listener=mp3_listener&amp;interval=500"></object>');
		var t = $('table.songs');
		if (t) {
			var playall = $('<p class="small"><input type="checkbox" id="playlistmode"> <label for="playlistmode">'+ T_playlist +'</label><br><input type="checkbox" id="loopmode"> <label for="loopmode">'+ T_loop +'</label>');
			t.before(playall);
			$('#playlistmode').change(function() { mp3_listener.playlist = !!$('#playlistmode:checked').length; });
		}
	});
}

$(document).ready(function() {
	var songs = new Array();
	var btn = $('<img class="playbutton" src="'+BASE_URI+'/resources/play.png">');
	$('a[href$=.mp3]').each(function() { songs.push($(this).attr('href')); }).before(btn);
	mp3_listener.songs = songs;
	$('.playbutton').click(function() { var a = $(this); if (isPlaying(a)) play(a); else pause(); });
});

// }}}

/* Rating editor {{{ */

$(document).ready(function() {
	var star1 = BASE_URI+'/resources/star.png';
	var star0 = BASE_URI+'/resources/star_empty.png';
	var elems = $('.ratingedit').html(function() {
		var id = $(this).attr('id');
		var star = '<img src="'+star0+'">';
		return star+star+star+star+star+ ' <a href="#">(clear)</a><input type="hidden" name="'+id+'" value="">';
	});
	if (elems.length == 0) return;
	elems.children('img').click(function() {
		var e = $(this);
		var stars = 1 + e.prevAll('img').length;
		e.nextAll('img').attr('src', star0);
		e.prevAll('img').attr('src', star1);
		e.attr('src', star1);
		e.nextAll('input').val(String(stars));
	});
	elems.children('a').click(function(ev) {
		var e = $(this);
		e.prevAll('img').attr('src', star0);
		e.nextAll('input').val('0');
		return false;
	});
});

/* }}} */

/* Odds and ends {{{ */

$(document).ready(function(){$('a.backlink').click(function(){history.back();return false})});
$(document).ready(function(){$('<a href="http://twitter.com/musicjk"><img src="http://twitter-badges.s3.amazonaws.com/t_mini-a.png" alt="Twitter feed"></a>').css({float:'right'}).appendTo('#menu')})
/* }}} */


