/* nginx fancyindex improvments
 * 2014 ed <irc.rizon.net>
 * bsd licensed
 */

var song = -1;
var songs = [];
var playa = null;
var stopit = false;
var firstplay = true;
$(function()
{
	$('td a').each(function()
	{
		var o = $(this);
		var h = o.attr('href');
		if (/&gt;$/.test(o.html()))
		{
			o.html(decodeURIComponent(h));
		}
		if (/\.(mp3|ogg|mp4|m4a|aac)$/i.test(h))
		{
			var i = songs.length;
			songs.push(h);
			var pre = o.closest('tr').find('td').eq(0);
			pre.html('<a href="#trk'+i+'" class="play" id="mp'+i+'">play</a>');
			// $('<a href="#" class="play" data-id="'+i+'">play</a>').insertBefore(o);
		}
	});
	$('.play').click(onplay);
	bar();

	var v = location.hash;
	if (v && v.length > 4 && v.indexOf('#trk') === 0)
	{
		play(parseInt(v.substr(4)));
	}
});

function onplay(e)
{
	e.preventDefault();
	var id = $(this).attr('id').substr(2);
	play(parseInt(id));
}

function play(n)
{
	if (firstplay)
	{
		firstplay = false;
		$('<div id="mpta" />').appendTo('body');
		$('<div id="mptb" />').appendTo($('#mpta'));
		$('<div id="mptc" />').appendTo($('#mpta'));
		$('#mpta').click(seek);
		$('#mptb').click(seek);
		$('#mptc').click(seek);
	}
	while (n >= songs.length)
		n -= songs.length;

	song = n;
	if (parent.F == 'rci')
	{
		parent.tx(window.location.pathname + songs[n]);
		return true;
	}
	if (playa)
	{
		//playa.removeEventListener('suspend', playa_suspend, false);
		//playa.removeEventListener('progress', playa_progress, false);
		//playa.removeEventListener('error', playa_error, true);
		playa.pause();
		playa.src = '';
	}
	else
	{
		playa = new Audio();
		playa.addEventListener('progress', playa_progress, false);
		playa.addEventListener('error', playa_error, true);
	}

	playa.src = songs[song];

	var mp3ok = !!playa.canPlayType && playa.canPlayType('audio/mpeg') != '';
	var oggok = !!playa.canPlayType && playa.canPlayType('audio/ogg; codecs="vorbis"') != '';
	var aacok = !!playa.canPlayType && (
		playa.canPlayType('audio/mp4') != '' ||
		playa.canPlayType('audio/aac') != '');
	var ismp3 = /\.mp3$/i.test(songs[song]);
	var isogg = /\.ogg$/i.test(songs[song]);
	var isaac = /\.(mp4|m4a|aac)$/i.test(songs[song]);
	if (ismp3 == mp3ok || isogg == oggok || isaac == aacok)
	{
		try
		{
			playa.play();
			if (playa.paused)
				autoplay_blocked();

			location.hash = 'trk' + song;
		}
		catch (ex)
		{
			alert('what');
		}
		$('.play').removeClass('act');
		$('#mp'+song).addClass('act');
		return true;
	}
	badFile(song);
	return false;
}

function revmatch(x, y)
{
	if (y.length > x.length) return false;
	for (var n = 1; n <= y.length; n++)
		if (x[x.length - n] != y[y.length - n])
			return false;
	return true;
}

function badFile(n)
{
	$('#mp'+song).remove();
	if (n == song)
	{
		setTimeout('play(' + (song+1) + ');', 250);
	}
}




var buffered = 0;
function bar()
{
	if (stopit) return;
	if (!playa)
	{
		setTimeout(bar, 10);
		return;
	}
	var len = playa.duration;
	var pos = playa.currentTime;
	var act = !playa.paused;
	$('#mptb').css('width', (100*(buffered/len)) + '%');
	$('#mptc').css('width', (100*(pos/len)) + '%');
	if (pos > 0 && pos > len - 1 && !act)
	{
		play(song+1);
	}
	//document.getElementById('plist').innerHTML = 'len ' + len + ', pos ' + pos + ', act ' + act;
	setTimeout(bar, 10);
}
function seek(e)
{
	var width = $('#mpta').width();
	var click = e.clientX;
	var len = playa.duration;
	len *= (click*1.0 / width);
	playa.currentTime = len;
}





function playa_progress()
{
	var range = 0;
	for (var a = 0; a < playa.buffered.length; a++)
	{
		range +=
			playa.buffered.end(a) -
			playa.buffered.start(a);
	}
	buffered = range;
}

function playa_error(e)
{
	var err = '';
	var src = (e && e.target) || (window.event && window.event.srcElement);
	src = src.src;
	for (var a = 0; a < songs.length; a++)
	{
		if (revmatch(src, songs[a]))
		{
			badFile(a);
		}
	}
	switch (e.target.error.code)
	{
		case e.target.error.MEDIA_ERR_ABORTED:
			err = 'Playback was aborted';
			break;
		case e.target.error.MEDIA_ERR_NETWORK:
			err = 'Network error';
			break;
		case e.target.error.MEDIA_ERR_DECODE:
			err = 'Corrupted file';
			break;
		case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
			err = 'Unsupported codec';
			break;
		default:
			err = 'Unknown Errol';
			break;
	}
}

function autoplay_blocked()
{
	$('#blocked').remove();
	$('<div id="blocked"><div id="blk_play"><a><span id="blk_tx1"></span><span id="blk_tx2"></span></a></div><div id="blk_abrt"><a>Cancel<br /><br />(show file list)</a></div></div>').appendTo('body');
	var mp = $('#mp'+song);
	var lnk = mp.closest('tr').find('td').eq(1).find('a').eq(0);
	// nodeValue is r/w text of top node
	var text1 = lnk.contents().filter(function(){return this.nodeType==3})[0].nodeValue;
	var text2 = lnk.find('span').html();
	if (text2 != '')
		text2 = '<br /><br />' + text2;
	$('#blk_tx1').text('Play "' + text1 + '"');
	$('#blk_tx2').html(text2);
	$('#blk_play a').click(function()
	{
		playa.play();
		$('#blocked').remove();
	});
	$('#blk_abrt a').click(function()
	{
		$('#blocked').remove();
	});
}

//setTimeout(autoplay_blocked, 500);
