var playing = 0;
var songInterval;
var waitingTimeout;
var iwait = 1;
var auditory;
var playlist = new Array();
var playlista = new Array();
var progressbar = new Object();
var SM2_DEFER = true;

function createHandler(whichfunction,whichobject) {
    return function(){whichfunction(whichobject);return false};
} 

function draw() {

this.initialize = function() {
	progressbar.width = parseInt(document.getElementById("progressbar").width);
	playlista = document.getElementById("playlist").getElementsByTagName("a");
	var whichsong;
	var nextsong;
	var audiotester = document.createElement('audio');
	if(typeof(audiotester.networkState) != "undefined") { // audio tag supported
		playlist = document.getElementById("playlist").getElementsByTagName("audio");
		var i = 0;
		while(i < playlista.length) {
			whichsong = playlist[i];
			nextsong = playlist[(i+1)];
			whichsong.addEventListener("ended",createHandler(song.changesong,nextsong),false);
			whichsong.toggleMute = function() {
				if(this.muted) this.muted = null;
				else this.muted = true;
				}
			whichsong.getDuration = function() {
  							return parseInt(this.duration);
  							}
  			whichsong.getCurrentTime = function() {
  							return parseInt(this.currentTime);
  							}
  			whichsong.setCurrentTime = function(howfar) {
  							this.currentTime = howfar;
  							} 
  			whichsong.getWaitStatus = function() {
  							if(auditory.readyState <= 2) return true;
  							else return false;
  							}
  			whichsong.listEl = whichsong.parentNode;
			playlista[i].onclick = createHandler(song.changesong,whichsong); 
			i++; 
			}
			auditory = playlist[0];
			auditory.listEl.id = "current";
			draw.play();
			draw.progressbar();
			draw.volumebutton();
			setTimeout("song.changetime()",1000);
		} else { // audio tag not supported
				soundManager = new SoundManager();
				soundManager.url = 'soundmanager2_flash9.swf';
				soundManager.flashVersion = 9;
				soundManager.debugMode = false;
				soundManager.onload = function() {
					var i = 0;
					for (i = 0;i< playlista.length;i++) {
						playlist[i] = soundManager.createSound({
    							id: 'song'+i,
    							url: playlista[i].href,
    							onfinish: function() {song.changesong(auditory.nextsong)}
  								});
  						playlist[i].getDuration = function() {
  							return parseInt(this.durationEstimate/1000);
  							}
  						playlist[i].getCurrentTime = function() {
  							return parseInt(this.position/1000);
  							}
  						playlist[i].setCurrentTime = function(howfar) {
  							this.setPosition(howfar*1000);
  							}
  						playlist[i].getWaitStatus = function() {
  							return this.isBuffering;
  							}
  						playlist[i].listEl = playlista[i].parentNode; 
  						playlista[i].onclick = createHandler(song.changesong,playlist[i]);
  						}
  					var n = 0;
					for (n = 0;n < playlista.length;n++) 
						playlist[n].nextsong = playlist[n+1];
  					auditory = playlist[0];
  					auditory.listEl.id = "current";
					draw.play();
					draw.progressbar();
					draw.volumebutton();
				//	song.changetime(); 
 					}
 				soundManager.beginDelayedInit();
			} // end else
	} // end .initialize

this.play = function() {
	var ctx = document.getElementById("playpause").getContext("2d");
	ctx.clearRect(0,0,10,13);		
	ctx.beginPath();
   ctx.moveTo(0,0);
	ctx.lineTo(10,6);
	ctx.lineTo(0,13);
	ctx.fillStyle = "rgba(255,255,255, 1)";
	ctx.fill();
	}
	
this.pause = function() {
	var ctx = document.getElementById("playpause").getContext("2d");
	ctx.clearRect(0,0,10,13);
	ctx.fillStyle= "rgba(255,255,255, 1)";
	ctx.fillRect(0,0,4,13);
	ctx.fillRect(6,0,4,13);
	}	

this.progressbar = function() {
	var ctx2 = document.getElementById("progressbar").getContext("2d");
	ctx2.fillStyle = "rgba(255,255,255, 0.5)";
	roundedRect(ctx2,0,0,progressbar.width,8,5);	
	}

this.statusmarker = function(percentdone) {
	var ctx4 = document.getElementById("statusmarker").getContext("2d");
	ctx4.fillStyle = "rgba(255,255,255, 1)";
	ctx4.clearRect(0,0,progressbar.width,8);
	roundedRect(ctx4,0,0,percentdone,8,5);
	}

this.volumebutton = function(muted) {
	var ctx3 = document.getElementById("volumebutton").getContext("2d");
	ctx3.fillStyle = "rgba(255,255,255, 1)";
	ctx3.clearRect(0,0,20,17);
	ctx3.beginPath();
	ctx3.moveTo(0,5);
	ctx3.lineTo(0,12);
	ctx3.lineTo(4,12);
	ctx3.lineTo(10,17);
	ctx3.lineTo(10,0);
	ctx3.lineTo(4,5);
	ctx3.closePath();
	ctx3.fill();
	if(!muted) {
		ctx3.strokeStyle = "rgba(255,255,255,1)";
		ctx3.lineWidth = 3;
		ctx3.beginPath();
		ctx3.arc(13,9,4,(Math.PI/180)*270,(Math.PI/180)*90,0);
		ctx3.stroke();
		}
	}
	
this.waiting = function(done) {
	clearTimeout(waitingTimeout);
	var ctx = document.getElementById("waiting").getContext("2d");
	if(!done) {
		ctx.save();
		ctx.clearRect(0,0,20,20); 
  		var sin = Math.sin(Math.PI/6);
		var cos = Math.cos(Math.PI/6);
  		ctx.translate(10, 10);
  		ctx.rotate(Math.PI*iwait/6);
  		var i = 0;
  		for (i; i <= 12; i++) {
  	  		c = Math.floor(255 / 12 * i);
   		ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
  			ctx.fillRect(0, 3, 9, 2);
    		ctx.rotate(Math.PI/6);
  			}
  		if(iwait < 12) iwait++; else iwait = 0;
  		ctx.restore();
  		waitingTimeout = setTimeout("draw.waiting()",100);
  		} else {
  			ctx.clearRect(0,0,20,20);
  		} 
	}
}
var draw = new draw();

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
	return [curleft,curtop];
	}
}

function minsec(t) {
	var minutes = parseInt(t/60);
	var seconds = parseInt(t % 60);
	if(seconds < 10) {var num = new Number(0); seconds = num.toString() + seconds; }
	return [minutes, seconds];
}

function roundedRect(ctx,x,y,width,height,radius){ // from https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes with modifications
  ctx.beginPath();
  ctx.moveTo(x,y+radius);
  ctx.lineTo(x,y+height-radius);
  ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
  ctx.lineTo(x+width-radius,y+height);
  ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
  ctx.lineTo(x+width,y+radius);
  ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
  ctx.lineTo(x+radius,y);
  ctx.quadraticCurveTo(x,y,x,y+radius);
  ctx.fill();
}

function song() {

this.changesong = function(which) {
	clearInterval(songInterval);
	if(!which) song.playpause();
		else {
		if(playing) song.playpause();
		if(auditory.muted) song.volumeonoff();
		auditory.listEl.id = "";
		auditory = which;
		auditory.listEl.id = "current";
		song.playpause();
		auditory.setCurrentTime(0); // setting it to 0.0 causes Firefox to stutter a bit at the beginning
		}
	}
	
this.playpause = function() {
	if(!playing) {
		draw.pause();
		song.changetime();
		auditory.play();
		songInterval = setInterval("song.changetime()", 1000);		
		playing = 1;
		} else {
		draw.play();
		auditory.pause();
		clearInterval(songInterval);
		playing = 0;
		}
	}
this.seek = function(e) {
	var statuscoords = findPos(document.getElementById("statusmarker"));	
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	var percentseek = (posx - statuscoords[0])/progressbar.width;
	var auditoryduration = auditory.getDuration();
	auditory.setCurrentTime((auditoryduration*percentseek));
	draw.statusmarker(posx - statuscoords[0]);
	var auditorycurrenttime = auditory.getCurrentTime();
	var timedone = minsec(auditorycurrenttime);
	var seekstring = timedone[0] + ":" + timedone[1];
	var songtime = minsec(auditoryduration);
	var durationstring = songtime[0] + ":" + songtime[1];
	document.getElementById("seekandduration").innerHTML = seekstring + " / " + durationstring;
	}
	
this.changetime = function() {
	if(auditory.getWaitStatus()) {
		document.getElementById("seekandduration").style.visibility = "hidden";
		draw.waiting();
	} else {  
		document.getElementById("seekandduration").style.visibility = "visible";
		draw.waiting(1);
		var auditoryduration = auditory.getDuration();
		if(auditoryduration) { // so SM2 doesn't crash
			var auditorycurrenttime = auditory.getCurrentTime();		
			var songtime = minsec(auditoryduration);
			var durationstring = songtime[0] + ":" + songtime[1];
			var percentdone = parseInt((auditorycurrenttime/auditoryduration)*progressbar.width);			draw.statusmarker(percentdone);
			var timedone = minsec(auditorycurrenttime);
			var seekstring = timedone[0] + ":" + timedone[1];
			document.getElementById("seekandduration").innerHTML = seekstring + " / " + durationstring;
			}
		}
	}

this.volumeonoff = function() {
	if(auditory.muted) draw.volumebutton();
	else draw.volumebutton(1);
	auditory.toggleMute();
	}
}

var song = new song();