// JavaScript Document

function initPlayer(songURL, title) {
	var player = '';
	player += '<div class="player"><p class="songtitle">'+title+'</p><span id="timeleft" /><span id="playtoggle" /><span id="gutter" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all"><span id="loading" /><span id="handle" class="ui-slider-handle" /></span><audio><source src="'+songURL+'" type="audio/mpeg"></audio></div>';
	return player;
}

function initControls() {
	audio = $('.player audio').get(0);
	loadingIndicator = $('.player #loading');
	positionIndicator = $('.player #handle');
	timeleft = $('.player #timeleft');
	var manualSeek = false;
	var loaded = false;
	positionIndicator.hide();
	

	if ((audio.buffered != undefined) && (audio.buffered.length != 0)) {
		$(audio).bind('progress', function() {
		var loaded = parseInt(((audio.buffered.end(0) / audio.duration) * 100), 10);
		loadingIndicator.css({width: loaded + '%'});
		});
	} else {
	  loadingIndicator.remove();
	}
	$(audio).bind('timeupdate', function() {
		if (audio.duration == 'Infinity') {
			var timeLeft = parseInt(audio.currentTime, 10),
			mins = Math.floor(timeLeft/60,10),
			secs = timeLeft-mins*60;
			timeleft.text(mins + ':' + (secs > 9 ? secs : '0' + secs));
		} else {
			var rem = parseInt(audio.duration - audio.currentTime, 10),
			pos = (audio.currentTime / audio.duration) * 100,
			mins = Math.floor(rem/60,10),
			secs = rem - mins*60;
			timeleft.text('-' + mins + ':' + (secs > 9 ? secs : '0' + secs));
		}
		if (!manualSeek) { positionIndicator.css({left: pos + '%'}); }
		if (!loaded) {
			loaded = true;
		   
			$('.player #gutter').slider({
				value: 0,
				step: 0.01,
				orientation: "horizontal",
				range: "min",
				max: audio.duration,
				animate: true,         
				slide: function() {            
					manualSeek = true;
				},
				stop: function(e,ui) {
					manualSeek = false;        
					audio.currentTime = ui.value;
				}
			});
		}
	});
	$(audio).bind('play',function() {
		$("#playtoggle").addClass('playing');
	}).bind('pause ended', function() {
		$("#playtoggle").removeClass('playing');   
	});  
		   
	$("#playtoggle").click(function() {    
		if (audio.paused) { audio.play(); positionIndicator.show();
		} else { audio.pause();
		}    
	});
}

function html5AudioPlayer(params){
		var musicPaths = 1;
		$.ajax({
			type : "GET",
			url : params.xmlPath,
			dataType : "text",
			data: "ARTICLE_ID=" + params.artID,
			statusCode: {
    			404: function() {
      			alert('page not found');
    			}
  			},
			success : function( xml ) {
				//console.log("data: " + data);
				musicPaths = xml;
				
				
				//Check to see if browser is prehistoric or not
				var elem = document.createElement('audio');
				var canPlayMP3 = !!(elem.canPlayType && elem.canPlayType('audio/mpeg'));
				var songlist = '<div id="songlist"><ul>';
				if (canPlayMP3) {
					//Insert player
					var songURL = $(xml).find('song:first').text();
					var songTitle = $(xml).find('song:first').attr('tittel');
					
					var songlist = '<div id="songlist"><ul>';
					
					$(xml).find('song').each(function() {
						songlist += '<li class="songbutton"><a href="'+params.baseURL+'/'+$(this).text()+'">'+$(this).attr('tittel')+'</li>';
					});
					
					songlist += '</ul></div>';
					$(songlist).insertAfter(params.insertAfter);
					
					player = initPlayer(params.baseURL+'/'+songURL, songTitle);
					$(player).insertAfter(params.insertAfter);
									
					initControls();
					
					$('#songlist ul li.songbutton a').click(function(e) {
						e.preventDefault();
						loadSong($(this).attr('href'), $(this).text());
					});
					
				} else {
					loadFlashPlayerInstead(params);
				}
			}
		});
};

function loadFlashPlayerInstead(params){
	var swfplayerBefore = '<div id="player" class="nSongs'+ params.nSongs + '">';
	$(swfplayerBefore).insertAfter(params.insertAfter);
	var so = new SWFObject(params.baseURL + '/swf/musicplayer.swf?ARTICLE_ID=114','mpl','336','400','8');
	so.addParam('allowscriptaccess','always');
	so.addParam('wmode','transparent');
	so.write('player');
	var swfplayerAfter = '</div>';
	$(swfplayerAfter).insertAfter('.player');
}

function loadSong(songURL, title) {
	console.log(songURL);
	console.log(title);
	if ($('#subArea p.songtitle').text() != title) {
		audio.pause();
		$('.player').remove();
		var newPlayer = initPlayer(songURL, title);
		$(newPlayer).insertAfter('h2.description.audioplayer');
		initControls();
	}
}
