$(function(){
	var ms = $('#mediaswitch');
	ms.css('display','inline');
	ms.click(function() {
		mediaplayer();
	});
});

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 && !act)
	{
		playSong(song+1);
	}
	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;
}

var song = -1;
var songs = null;
var playa = null;
var stopit = false;
function mediaplayer()
{
	$('<div id="mbox" />').appendTo('body');
	$('body').addClass('nobody');
	var mbox = $('#mbox');
	
	$('<a href="#" id="quit">X</a>').appendTo(mbox);
	$('<div id="mpta" />').appendTo(mbox);
	$('<div id="mptb" />').appendTo(mbox);
	$('<div id="mptc" />').appendTo(mbox);
	$('<div id="mpr" />').appendTo(mbox);
	$('<div id="mpl" />').appendTo(mbox);
	var mpr = $('#mpr');
	var mpl = $('#mpl');
	$('#mpta').click(seek);
	$('#mptb').click(seek);
	$('#mptc').click(seek);
	
	$('<img id="cover" />').appendTo(mpl);
	var img = $('#cover');

	$('<div id="caption" />').appendTo(mpl);
	var loc = $('#plist a:last-child').html();
	$('#caption').html(loc);

	song = -1;
	songs = [];
	var cover = '.ico/unknown.png';
	var reSong = /\.(mp3|ogg|mp4|m4a|aac)$/i;
	var reCover = /(^|\/)cover\.(png|gif|jpg)$/i;

	$('#flist a').each(function(i)
	{
		var href = $(this).attr('href');
		if (reSong.test(href))
		{
			songs.push(href);
		}
		if (reCover.test(href))
		{
			cover = href;
		}
	});
	img.attr('src', cover);

	var html = [];
	for (var a=0; a<songs.length; a++)
	{
		var title = songs[a].replace(/%20/g, ' ');
		title = title.substring(title.lastIndexOf('/') + 1);
		title = decodeURIComponent(title);
		html.push('<a data-id="' + a + '" href="#">' + title + '</a>');
	}
	mpr.html(html.join('\n'));
	$('#mpr a').click(play);

	$('#cover').click(quitplayer);
	$('#quit').click(quitplayer);
	stopit = false;
	bar();
}

function quitplayer()
{
	if (playa) playa.pause();
	$('body').removeClass('nobody');
	$('#mbox').remove();
	stopit = true;
}

function play(e)
{
	var o = $(this);
	var n = o.data('id');
	playSong(n);
}

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 playSong(n)
{
	if (n >= songs.length)
	{
		n -= songs.length;
	}
	song = n;
	if (playa) playa.pause();
	playa = new Audio(songs[song]);
	playa.tag = song[song];


	playa.addEventListener('progress',function()
	{
		var range = 0;
		for (var i=0; i<playa.buffered.length; i++)
		{
			range += playa.buffered.end(i) -
				playa.buffered.start(i);
//			range = playa.buffered.end(i);
		}
		buffered = range;
	}, false);

	playa.addEventListener('error', function(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 = 'Uknown Errol';
				breaak;
		}
		//alert(err + ': ' + src);
	}, true);

	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 remp3 = /\.mp3$/i;
	var reogg = /\.ogg$/i;
	var reaac = /\.(mp4|m4a|aac)$/i;
	var ismp3 = remp3.test(songs[song]);
	var isogg = reogg.test(songs[song]);
	var isaac = reaac.test(songs[song]);
//	mp3ok = false;
//	alert(ismp3 + ', ' + mp3ok + ', ' + isogg + ', ' + oggok);
	if (ismp3 == mp3ok || isogg == oggok || isaac == aacok)
	{
		try
		{
			playa.play();
		}
		catch (ex)
		{
			alert('caught');
		}
		$('#mpr a.act').removeClass('act');
		$('#mpr a').each(function(i)
		{
			var o = $(this);
			n = o.data('id');
			//alert(n + '/' + song + ' :: ' + o.html() );
			if (n == song)
			{
				//alert(n + ' == ' + song);
				o.addClass('act');
			}
		});
		return true;
	}
	badFile(song);
	return false;
}

function badFile(n)
{
	var oo = $('#mpr a[data-id="' + n + '"]');
	oo.addClass('bad');
	oo.html('Your web browser cannot play this filetype');
	if (n == song)
	{
		setTimeout('playSong('+(song+1)+');',250);
	}
}
