var player = null;
var currentItemId = 0;
var lastfm = true;
var newwindow = '';

function savelist() {
	var name = prompt('Provide a title for your playlist:','');
	if(name) {
		var lis = $('playlistthingie').getElementsByTagName('li');
		var tosave = new Array();
		for(var i = 0; i < lis.length; i++) {
			var matches = lis[i].getElementsByTagName('img')[0].getAttribute('src').match(/vi\/([^\/]+)\/default\.jpg/);
			if(matches) {
			 	var placeholder = {
					"song": lis[i].getAttribute('song'),
					"artist": lis[i].getAttribute('artist'),
					"fileloc": matches[1],
				};	
				tosave.push(placeholder);
			}
		}
		// todo, check if tosave is empty
		queryHandler('save',"&name="+name+"&json="+tosave.toJSON(),'');
	} else alert('Error saving: You have not provided a name for your playlist.');
}

function openlist() {
	queryHandler('open','','contentright'); // todo opts = user id
}

function getlist(name) {
	queryHandler('playlist','&name='+name,name);
}

function addAll(parentId) {
	if($(parentId)) {
		var lis = $(parentId).getElementsByTagName('li');	
		var len = lis.length;
		while(len > 0) {
			$('list-1').adopt(lis[0]);
			len--;
		}
	}
}

function popitup() {
	var url = 'fullscreen.html';
	if (!newwindow.closed && newwindow.location) {
		newwindow.location.href = url;
	}
	else {
		//newwindow=window.open(url,'name','height=768,width=1024');
		newwindow = window.open(url,'name','toolbar=no,scrollbars=0,location=no,statusbar=no,menubar=no,resizable=yes,width=768,height=1024,fullscreen=yes,dependent=yes');
		if (!newwindow.opener) newwindow.opener = self;
	}
	if (window.focus) {newwindow.focus()}
	setTimeout('playFile(currentItemId)',1000);
	return false;
}

function toggleLastFm() {
	var el = document.getElementById('lastfmtoggle');
	if(lastfm) {
		el.style.opacity = '0.5';
		el.style.filter  = 'alpha(opacity=50)';
		el.parentNode.setAttribute('title','Toggle music filter on');
		lastfm = false;
	} else {
		el.style.opacity = '1';
		el.style.filter = 'alpha(opacity=100)';
		el.parentNode.setAttribute('title','Toggle music filter off');
		lastfm = true;
	}
}

function playerReady(obj) {
	player  = document.getElementsByName('mpl')[0];
	player.addModelListener('STATE', 'stateMonitor');
	//player.addModelListener('TIME', 'timeMonitor');
	setTimeout('populatePlaylist(\"next\")',100);
	setTimeout('first()',150);
}

function first() {
	if($(currentItemId)) {
		title = $(currentItemId).getProperty('song') ;
		artist =  $(currentItemId).getProperty('artist');
		queryHandler("songs","&view=similarsongs&artist=" + artist + "&song=" + title ,"contentright",false);
	}
}

function stateMonitor(obj) {
	currentState = obj['newstate'];
	if(currentState == "COMPLETED") populatePlaylist('next');
}

function timeMonitor(obj) {
	var duration = obj['duration'];
	var currentTime = obj['position'];
	if(curation - currentTime < 10)
		console.log(duration + ' ' + currentTime);
}

function populatePlaylist(playsong) {
	var sorted = mySortables.serialize(0);
	// find next song
	if(playsong == 'next') {
	 	for(var i = 0; i < sorted.length; i++) {
			if(sorted[i] == currentItemId) {
				playsong = sorted[i+1];
			}
		}
	}
	if(playsong == 'next') { // if no item found, start from the beginning again
		playsong = sorted[0];
	}
	playFile(playsong);
}

function playFile(playsong) {
	currentItemId = playsong;
	setCurrentlyPlaying(currentItemId);
	if (!newwindow.closed && newwindow.location)
		playInSecondWindow(playsong);
	else if($(currentItemId)) {
		//setTimeout("player.sendEvent(\"LOAD\",$(currentItemId).getProperty('fileloc'));",500);
		setTimeout("jwplayer('player').load($(currentItemId).getProperty('fileloc'));",500);
	}
	displayAd();
}

function playInSecondWindow(playsong) {
	player.sendEvent("STOP");
	player2  = newwindow.document.getElementsByName('mpl')[0];
	if(player2) player2.sendEvent("LOAD",$(currentItemId).getProperty('fileloc'));
	else console.log('player2 could not be found');
}

function setCurrentlyPlaying(currentItemId) {
	var lis = $('list-1').getElements('li');
	for(var i = 0; i<lis.length; i++) {
		if(lis[i].hasClass('currentlyPlaying')) {
			lis[i].removeClass('currentlyPlaying');
		}
	}
	if($(currentItemId)) {
		$(currentItemId).addClass('currentlyPlaying');
	
		title = decodeURIComponent($(currentItemId).getProperty('song')).replace(/\+/g," ");	
		artist = decodeURIComponent($(currentItemId).getProperty('artist')).replace(/\+/g," ");
		var currentartist = document.getElementById('currentartist');
		if(currentartist) currentartist.innerHTML = decodeURIComponent(artist);
	
		var currentsong = document.getElementById('currentsong');
		if(currentsong) currentsong.innerHTML = decodeURIComponent(title) + " - " ;
	}
}

