/*
 * author: John O'Rourke on behalf of Versatilia Ltd
 * licence: http://creativecommons.org/licenses/by-nc-sa/2.0/
 * contact: support@versatilia.com
 * 
 * This is a cookie written to be used with the Flash MP3 Player provided by Jeroen Wijering @
 * http://www.jeroenwijering.com/?item=Flash_MP3_Player. This cookie is licenced under the same licence used
 * by the Flash MP3 Player. It stores the current player information as in playlist item, volume and track time 
 * and loads the cookie when the page refreshes or changes and the same playlist is on screen. Can be used with 
 * multiple playlists. For an example see the initial case for use at http://brendan.o-rourke.org
 * 
 * To-do:
 * The window.onunload event requires the saveState function. Currently we need a way to neatly attach the 
 * saveState function to the window.onunload event, if you have any ideas or if you manage to sort this out please 
 * send us the update!
 * 
 * How to use:
 * 
 * 1. To use this cookie just add the javascript to the document head and add some variables to a javascript 
 * within the document body e.g.
 * 
 * <script type="text/javascript">
 * 	var playlistname="playlist.xml"; // the playlist's name, can be generated server-side
 * 	var playername="player1"; 		 // the player's id, can also be generated but typically the same
 * </script>
 * 
 * note: these variables can appear at the top of the script below for step 2 if preferred.
 * 
 * 2. Then you will need to alter the inline script you use to call the Flash Object.
 * 
 * <div id="player1"><a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.</div>
 * <script type="text/javascript">
 * 			
 * 			var FU = { 	movie:"mp3player.swf",width:"300",height:"200",majorversion:"7",build:"0",bgcolor:"#000000",id:"player_"+playername,
 * 
 * 						// must enable js (enablejs=true) and set the playlist via the variable or just use a fixed value
 * 						flashvars:"file="+playlistname+"&repeat=false&shuffle=false&autostart=true&enablejs=true&showdigits=true&showeq=true&lightcolor=0xffffff&backcolor=0x343434&frontcolor=0xcccccc&autoscroll=false" };
 * 
 * 			// replace the player id with the playername variable or use a fixed value
 * 			UFO.create(	FU, playername); 
 * 
 * 			// load the state of the mp3 player
 * 			loadState();
 * </script>
 * 
 */

//var playlistname="chalk-n-cheesexml";
//var playername="player1";
var playervars=new Array();
var playerloaded=false;
var playerloadattempts=20;
var playerskip=0.0;


function getUpdate(typ,pr1,pr2) {
	playervars[typ]=Math.round(pr1);
	if(pr2!=undefined){
		playervars[typ]+=":"+Math.round(pr2);
	}
}

// cookie functions thanks to quirksmode.org
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}



function thisMovie(playerName) {
	var movieName="player_"+playerName;
    if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function loadState(){
	setTimeout("loadStateReally()",100);
}

function loadStateReally(){
	if(thisMovie(playername) && thisMovie(playername).sendEvent){
	}else{
		if(playerloadattempts){
			playerloadattempts--;
			setTimeout("loadStateReally()",100);
		}
		return false;
	}
	if(playlistname==""){ return false; }
	var cname=playername+"_"+playlistname;
	var c=readCookie(cname);
	var loadvars=new Array();
	if(c != null ){
		var csplit=c.split("@");
		for(var i in csplit){
			var cval=""+csplit[i];
			var cvalsplit=cval.split("=");
			loadvars[""+cvalsplit[0]]=cvalsplit[1];
			playervars[""+cvalsplit[0]]=cvalsplit[1];
		}
		// now use loadvars["item"] etc
		if(loadvars["item"]!=""){
			//thisMovie(playername).sendEvent('playitem',loadvars["item"]);
			for(var i = 0;i<parseInt(loadvars["item"]);i++) {
				thisMovie(playername).sendEvent('next');
			}
		}
		if(loadvars["volume"]!=""){
			thisMovie(playername).sendEvent('volume',loadvars["volume"]);
		}
		if(playervars["state"]!="0" && loadvars["state"]=="0"){
			thisMovie(playername).sendEvent('playpause');
		}
		if(loadvars["time"]!=""){
			var timesplit=loadvars["time"].split(":");
			if(parseInt(timesplit[0])>0 && parseInt(timesplit[1])>0){
				var percent=100.0*parseFloat(timesplit[0])/(parseFloat(timesplit[0])+parseFloat(timesplit[1]));
				window.setTimeout("skipTrackTo("+percent+")",100);
			}
		}
	}
}

function skipTrackTo(percent){
	var state=playervars["state"];
	var loaded=parseFloat(playervars["load"]);
	if(state=="2" && loaded>=percent){
		window.setTimeout("skipTrackToReally("+percent+")",100);
	}else{
		window.setTimeout("skipTrackTo("+percent+")",100);
	}
	return false;
}

function skipTrackToReally(percent){
	thisMovie(playername).sendEvent('scrub',percent);
}

function saveState(){
	if(playlistname==""){ return true; }
	var cname=playername+"_"+playlistname;
	var cjoin=new Array;
	for(var ckey in playervars){
		if(ckey=="item"||ckey=="volume"||ckey=="time"||ckey=="state"){
			var cvarjoin=ckey+"="+playervars[ckey];
			cjoin[cjoin.length]=cvarjoin;
		}
	}
	var cval=cjoin.join("@");
	createCookie(cname,""+cval);
}

// replace this with something better:
window.onunload=saveState;
//document.body.addEventListener('onunload',saveState,false);
//document.body.attachEvent('onunload',saveState,false);