mootunes = new Class({
	Implements: [Options,Log,Events],
	
	options: {
		type: 'remote',
		target: null,
		masterUrl: 'http://feddelegrand.com/player/popup.php',
		masterWidth: 700,
		masterHeight: 531,
		userId: 0,
		playerSwf: 'swf/mootunes_core.swf',
		debug: true,
		playlistNames: ['userplaylist','usertracks','flamingolist'],
		defaultPlaylist: 'flamingolist'
	},

	initialize: function(options){
		this.setOptions(options);
		this.options.target.addClass('loading');
		
		this.master = null;
		this.i = 0;
		this.flashplayer = null;
		this.type = this.options.type;
		this.startUp = false;
		this.windowOpen = this.cookieDo('read','playerOpen', null);
		this.remoteListening = false;
		
		this.currentLoad = 0;
		this.currentPosition = 0;
		this.currentTrackLength = 0;
		this.clickedElm = null;
		
		this.trackerBallBase = 0;
		this.trackerBaseLength = 0;
		
		this.dragging = false;
		
		this.playlists = new Hash({});
		this.currentPlaylist = null;
		this.selectedPlaylist = null;
		
		this.startPlay = false;
		this.loadedTrackId = null;
		this.loadedTrack = null;
		this.trackIsPlaying = false;
		
		this.userLoggedIn = false;
		this.userId = this.options.userId;
		
		if(this.options.type == 'remote') {
			this.initAsRemote();
		} else if (this.options.type == 'master') {
			this.initAsMaster();
		}
		
		if(this.options.debug) {
			this.enableLog();
		} else {
			this.disableLog();
		}
		
		window.addEvent('beforeunload', this.shutDown.bindWithEvent(this));
		window.addEvent('error', this.crashHandling.bindWithEvent(this));
		
		this.log(this.type);
		this.blurs = 0;
		
		$$('a.addtoplaylist','a.removeplaylist').each(function(elm) {
			elm.addEvent('click', this.playlistAction.bindWithEvent(this,elm));
		}.bind(this));
	},
	
	
	initAsMaster: function() {
		this.master = window;
		
		if(this.master.opener == null) this.master.close();
		
		this.cookieDo('write', 'playerOpen', 'true');
		
		this.master.opener.mootunesHandler.setRemoteListening();
		
		this.flashplayer = new Swiff(this.options.playerSwf, {
			id: 'mootunes_core_swf',
			width: 1,
			height: 1,
			params: {
				wmode: 'transparent',
				bgcolor: '#ffffff'
			}
		});
		
		
		this.flashplayer.inject($('flashcontainer'), 'top');
		this.checkUser();
		this.setControlEvents();
	},
	
	initAsRemote: function() {
		window.addEvent('domready', this.setRemoteEvents.bindWithEvent(this));
		if(this.windowOpen != null) {
			$('footer').addClass('playerloaded');
			$('musicplayerremote').removeClass('notloaded');
			this.loadMaster(null);
			this.setControlEvents();
			if(this.master != null) {
				this.log('master user: '+this.master.mootunesHandler.userId+' & this user: '+this.userId);
				if (this.master.mootunesHandler.userId > 0 && this.userId == 0) {
					this.master.close();
				}
			}
		} else {
			this.cookieDo('dispose','loadedTrack',null);
		}
	},
	
	startUpRemote: function() {
		if(this.master != null) {
			this.master.removeEvents('startup');
			this.playTrack(null, this.clickedElm);
			$('footer').addClass('playerloaded');
			$('musicplayerremote').removeClass('notloaded');
		}
		this.setControlEvents();
		this.startUp = false;
	},
	
	testFlash: function() {
		this.log('flash is ready');
		if(this.master.opener.mootunesHandler.startPlay) {
			this.playTrack(null, this.master.opener.mootunesHandler.clickedElm);
		}
		this.master.opener.focus();
		this.master.blur();
	},
	
	checkUser: function() {
		var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.setUserInfo.bindWithEvent(this)}).post({'type': 'checkuser'});
	},
	
	setUserInfo: function(userInfo) {
		if(userInfo.iUserId != 0) {
			this.userLoggedIn = true;
			this.userId = userInfo.iUserId;
		} else {
			this.cookieDo('dispose', 'loadedTrack', null);
		}
		if(this.type == 'master') {
			this.loadPlaylists();
			window.fireEvent('setuserinfo', userInfo);
		}
	},
	
	setCurrentTrackLength: function(trackLength) {
		if(this.type == 'master') window.fireEvent('setCurrentTrackLength', trackLength);
		this.currentTrackLength = trackLength.toInt();
	},
	
	setControlEvents: function() {
		$$('table.playercontrols a.playerbutton').each(function(elm) {
				elm.addEvent('click', this.playerButtonAction.bindWithEvent(this, elm));
		}.bind(this));
		this.initTracker();
	},
	
	userlink: function(e, elm) {
		if(e != null) e.preventDefault();
		
		this.master.opener.location = elm.get('href');
		this.master.opener.focus();
	},
	
	playerButtonAction: function(e, elm) {
		if(elm != null) elm = $(elm);
		if(e != null) e.preventDefault();
		action = elm.get('rel');
		if(action == 'play') {
			this.playCurrentTrack();
		} else if (action == 'pause') {
			this.pauseTrack();
		} else if (action == 'prev') {
			this.prevTrack();
		} else if (action == 'next') {
			this.nextTrack();
		}
	},
	
	playCurrentTrack: function() {
		this.log(this.trackIsPlaying);
		if(this.master == null) {
			this.startPlay = true;
			this.loadMaster(null);
		} else if(this.type == 'remote') {
			this.master.mootunesHandler.playCurrentTrack();
		} else {
			if(!this.trackIsPlaying) {
				this.loadTrack(this.loadedTrack.iPlayerTrackId);
			} else {
				this.resumeTrack();
			}
		}
	},
	
	prevTrack: function() {
		if(this.clickedElm != null) {
			trackItem = this.clickedElm.getParent('.trackitem');
		} else if(this.currentPlaylist != null) {
			trackItem = $(this.currentPlaylist).getElement('.trackitem[rel='+this.loadedTrack.iPlayerTrackId+']');
		}
		if(trackItem != null) {
			prevTrackItem = trackItem.getPrevious('.trackitem');
			if(prevTrackItem != null) {
				trackId = prevTrackItem.get('rel');
				if(this.type == 'remote') {
					this.master.mootunesHandler.loadTrackInfo(trackId);
				} else {
					this.loadTrackInfo(trackId);
				}
				this.setClickedElm(prevTrackItem.getElement('.playerbutton'));
			} else {
				this.log('no previous item!');
			}
		} else {
			this.log('no track item present');
		}
	},
	
	nextTrack: function() {
		if(this.clickedElm != null) {
			trackItem = this.clickedElm.getParent('.trackitem');
		} else if(this.currentPlaylist != null) {
			trackItem = $(this.currentPlaylist).getElement('.trackitem[rel='+this.loadedTrack.iPlayerTrackId+']');
		}
		if(trackItem != null) {
			nextTrackItem = trackItem.getNext('.trackitem');
			if(nextTrackItem != null) {
				trackId = nextTrackItem.get('rel');
				if(this.type == 'remote') {
					this.master.mootunesHandler.loadTrackInfo(trackId);
				} else {
					this.loadTrackInfo(trackId);
				}
				this.setClickedElm(nextTrackItem.getElement('.playerbutton'));
			} else {
				this.log('no next item!');
			}
		} else {
			this.log('no track item present');
		}
	},
	
	setClickedElm: function(elm, mastercall) {
		if(elm != null) elm = $(elm);
		if(this.type == 'master' && mastercall != false) {
			//window.fireEvent('setClickedElm', [elm, true]);
			this.master.opener.mootunesHandler.setClickedElm(elm,true);
		} else if((mastercall == null || mastercall == false) && this.master != null && this.type == 'remote') {
			if(!this.startUp) this.master.mootunesHandler.setClickedElm(elm, false);
		}
		this.clickedElm = $(elm);
	},
	
	initTracker: function() {
		$('trackerloader').setStyle('width', '0%');
		$('trackerprocess').setStyle('width', '0%');
		
		trackerDimensions = $('tracker').getCoordinates();
		trackerBallDimensions = $('trackerball').getCoordinates();
		trackerBallLeft = $('trackerball').getStyle('left').toInt();
		trackerBallTop = $('trackerball').getStyle('top').toInt();
		this.trackerBallBase = trackerBallLeft;
		this.trackerBaseLength = trackerDimensions.width;
		
		this.trackerBall = new Drag('trackerball', {
			limit: {x:[trackerBallLeft,(trackerBallLeft+(trackerDimensions.width-14))],y:[trackerBallTop, trackerBallTop]},
			onStart: function(){this.dragging = true;}.bind(this),
			onComplete: this.scrubTrack.bind(this)
		});
	},
		
	setRemoteListening: function() {
		this.master.addEvent('popupClose', this.popupClose.bindWithEvent(this));
		this.master.addEvent('trackPlaying', this.trackPlaying.bindWithEvent(this));
		this.master.addEvent('trackStop', this.trackStop.bindWithEvent(this));
		this.master.addEvent('updateUI', this.updateUI.bindWithEvent(this));
		this.master.addEvent('updateTrackUI', this.updateTrackUI.bindWithEvent(this));
		this.master.addEvent('updateTime', this.updateTime.bindWithEvent(this));
		this.master.addEvent('updateLoader', this.updateLoader.bindWithEvent(this));
		this.master.addEvent('setCurrentTrackLength', this.setCurrentTrackLength.bindWithEvent(this));
		this.master.addEvent('setClickedElm', this.setClickedElm.bind(this));
		this.master.addEvent('setTotalRating', this.setTotalRating.bindWithEvent(this));
		this.master.addEvent('handleVoting', this.handleVoting.bindWithEvent(this));
		this.master.addEvent('handlePlaylistAction', this.handlePlaylistAction.bindWithEvent(this));
		this.master.addEvent('resetTrackUI', this.resetTrackUI.bindWithEvent(this));
		this.master.addEvent('soundLoaded', this.soundLoaded.bindWithEvent(this));
		this.master.addEvent('setuserinfo', this.setUserInfo.bindWithEvent(this));
		if(this.startUp) this.startUpRemote();
		this.remoteListening = true;
		this.log('remote listening active');
	},
	
	unsetRemoteListening: function() {
		if(this.master != null) this.master.removeEvents();
		this.log('remote listening inactive');
		this.remoteListening = false;
	},
	
	toggleListening: function(e, type) {
		this.blurs++;
		this.log(this.blurs+': toggle listening');
		if(type == 'off' && this.remoteListening) {
			this.master.removeEvents('updateUI');
			this.master.removeEvents('updateTime');
			this.remoteListening = false;
		} else if (type == 'on' && !this.remoteListening && this.master != null) {
			this.master.addEvent('updateUI', this.updateUI.bindWithEvent(this));
			this.master.addEvent('updateTime', this.updateTime.bindWithEvent(this));
			this.remoteListening = true;
		}
	},
	
	setRemoteEvents: function() {
		$$('#musicplayerremote .manageplaylist').addEvent('click', this.loadMaster.bindWithEvent(this));
		
		$$('.trackdetails a.votebutton','.feddepick a.votebutton','body.contest div.trackitem a.votebutton').each(function(elm){
			elm.addEvent('click', this.voteTrack.bindWithEvent(this, elm));
		}.bind(this));
		
		$$('.trackitem').each(function(elm) {
			elm.addEvent('mouseenter', function(e, elm){
				if(e != null) {
					e.preventDefault();
					e.stopPropagation();
				}
				elm.addClass('over');
			}.bindWithEvent(this, elm));
			elm.addEvent('mouseleave', function(e, elm){
				if(e != null) {
					e.preventDefault();
					e.stopPropagation();
				}
				elm.removeClass('over');
			}.bindWithEvent(this, elm));
		}.bind(this));
	},
	
	updateUI: function(trackPos) {
		if(!this.dragging) {
			if(this.type == 'master') window.fireEvent('updateUI', trackPos);
			this.updateTime(trackPos);
			leftPos = (trackPos/this.currentTrackLength)*(this.trackerBaseLength-14);
			$('trackerball').setStyle('left', (this.trackerBallBase+leftPos)+'px');
			$('trackerprocess').setStyle('width', leftPos+'px');
		}
	},
	
	scrubTrack: function() {
		trackerBallLeft = $('trackerball').getStyle('left').toInt();
		trackPos = ((trackerBallLeft*this.currentTrackLength)/(this.trackerBaseLength-14)).round();
		if(this.type == 'remote') {
			this.master.mootunesHandler.flashplayer.remote('scrubTrack', trackPos);
		} else {
			this.flashplayer.remote('scrubTrack', trackPos);
		}
		this.dragging = false;
	},
	
	updateLoader: function(loaded,total,length) {
		if(this.type == 'master') window.fireEvent('updateLoader', [loaded,total,length]);
		this.loaded = ((loaded/total)*100).round();
		$('trackerloader').setStyle('width', this.loaded+'%');
	},
	
	pauseTrack: function() {
		this.log('pause');
		this.trackStop();
		if(this.type == 'master') {
			this.flashplayer.remote('pauseTrack');
		} else if(this.type == 'remote') {
			this.master.mootunesHandler.pauseTrack();
		}
	},
	
	resumeTrack: function() {
		this.log('resume');
		this.trackPlaying(this.loadedTrack.iPlayerTrackId);
		if(this.type == 'master') {
			this.flashplayer.remote('playTrack');
		} else if(this.type == 'remote') {
			this.master.mootunesHandler.resumeTrack();
		}
	},
	
	playTrack: function(e, elm) {
		if(elm != null) elm = $(elm);
		this.removeEvents('trackInfoLoaded');
		if(e != null) e.preventDefault();
		
		link = elm.get('href');
		
		if(this.userId == 0 && this.type == 'remote' && link == '#') {
			openLogin('community');
			return false;
		}
		
		if(this.master == null){ 
			this.loadMaster();
			this.startPlay = true;
			if(elm != null) this.setClickedElm(elm);
			return false;
		}
		
		
		if(elm != null) {
			playlist = elm.getParent('ul.playlist');
			if(playlist != null) {
				playlistName = playlist.get('id');
				this.currentPlaylist = playlistName;
				this.activatePlaylist(playlistName);
			} else {
				this.currentPlaylist = null;
			}
			
			action = elm.get('rel');
			this.setClickedElm(elm);
			if(action != null && action == 'pause') {
				this.pauseTrack();
			} else {
				trackId = elm.getParent().get('rel');
				if(this.loadedTrack != null && trackId == this.loadedTrack.iPlayerTrackId && this.trackIsPlaying) {
					this.resumeTrack();
				} else if(this.type == 'master') {
					this.addEvent('trackInfoLoaded', this.loadTrack.bindWithEvent(this));
					this.loadTrackInfo(trackId);
				} else if(this.type == 'remote') {
					if(!this.startUp) this.master.mootunesHandler.playTrack(e,elm);
				}
			}
		} else {
			this.loadTrack(this.loadedTrack.iPlayerTrackId);
		}
	},
	
	trackStop: function() {
		if(this.type == 'master') window.fireEvent('trackStop');
		this.log('track stop');
		$$('.trackitem a[rel=pause]').each(function(elm) {
			elm.set('rel','play');
			spanElm = elm.getElement('span');
			spanElm.removeClass('pauseicon');
			spanElm.addClass('playicon');
		}.bind(this));
		$$('table.playercontrols a[rel=pause]').each(function(elm){
			elm.set('rel','play');
			spanElm = elm.getElement('span');
			spanElm.removeClass('pauseicon');
			spanElm.addClass('playicon');
		}.bind(this));
	},
	
	trackPlaying: function(iPlayerTrackId) {
		this.trackIsPlaying = true;
		this.log('track playing');
		if(this.type == 'master') window.fireEvent('trackPlaying', iPlayerTrackId);
		$$('.trackitem[rel='+iPlayerTrackId+'] a.playerbutton').each(function(elm) {
			elm.set('rel','pause');
			spanElm = elm.getElement('span');
			spanElm.removeClass('playicon');
			spanElm.addClass('pauseicon');
		}.bind(this));
		$$('.trackitem[rel='+iPlayerTrackId+'] div.trackinfo').each(function(elm) {
			elm.addClass('played');
		}.bind(this));
		$$('table.playercontrols a[rel=play]').each(function(elm){
			elm.set('rel','pause');
			spanElm = elm.getElement('span');
			spanElm.removeClass('playicon');
			spanElm.addClass('pauseicon');
		}.bind(this));
	},
	
	loadTrack: function(iPlayerTrackId) {
		this.flashplayer.remote('loadTrack', iPlayerTrackId);
	},
	
	soundLoaded: function() {
		if(this.type == 'master') fireEvent('soundLoaded');
		this.loaded = 100;
		$('trackerloader').setStyle('width', '100%');
	},
	
	trackComplete: function() {
		this.trackIsPlaying = false;
		this.trackStop();
		this.log('track completely played');
		this.nextTrack();
	},
	
	loadPlaylists: function() {
		this.playlists.empty();
		this.log('load them playlists');
		this.playlistsLength = this.options.playlistNames.length;
		this.options.playlistNames.each(function(playlist){
			if(this.userId != 0) {
				var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.setPlaylist.bindWithEvent(this, playlist)}).post({'type': 'getplaylistjson', 'playlisttype': playlist});
			} else if (playlist == this.options.defaultPlaylist) {
				var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.setPlaylist.bindWithEvent(this, playlist)}).post({'type': 'getplaylistjson', 'playlisttype': playlist});
			}
		}.bind(this));
	},
	
	setPlaylist: function(playlist, playlistName) {
		if(playlist != null) {
			this.playlists.set(playlistName,playlist);
			$$('li[rel='+playlistName+']').setStyle('display','block');
		} else {
			$$('li[rel='+playlistName+']').setStyle('display','none');
			this.playlistsLength--;
		}
		loadedPlaylistsLength = this.playlists.getLength();
		this.log('loaded length: '+loadedPlaylistsLength);
		this.log('needed length: '+this.playlistsLength);
		finish = false;
		if(this.userId != 0 && loadedPlaylistsLength == this.playlistsLength) {
			finish = true;
		} else if (this.userId === 0 && this.options.defaultPlaylist != null && loadedPlaylistsLength == 1){
			$$('li[rel=userplaylist]','li[rel=usertracks]').setStyle('display','none');
			finish = true;
		}
		this.log(finish);
		if(finish) {
			this.createPlaylist();
		}
	},
	
	createPlaylist: function() {
		userPlaylist = false;
		this.playlists.each(function(playlist, playlistName) {
			$(playlistName).empty();
			if(playlist.length != null) { 
				playlist.each(function(trackInfo){
					eListItem = new Element('li', {
						'class': 'trackitem',
						'rel': trackInfo.iPlayerTrackId,
						'html':'<a href="#" class="playerbutton smallbutton left" rel="play"><span class="playicon">&gt;</span></a>&nbsp;<img src="http://www.feddelegrand.com/images/r-23-23-c/0-0-'+trackInfo.iCoverId+'.jpg" class="coverimage left" />&nbsp;<span class="tracktitle">'+trackInfo.sArtist+'&nbsp;-&nbsp;'+trackInfo.sTitle+'</span><span class="tracktime">'+trackInfo.sTime+'</span>'
					});
					eListItem.inject($(playlistName), 'bottom');
				});
			}
			if(playlistName == 'userplaylist') userPlaylist = true;
		});
		activePlaylist = this.options.defaultPlaylist;
		if(userPlaylist) activePlaylist = 'userplaylist';
		this.setPlaylistEvents();
		$('tabbars').getElement('a[rel='+activePlaylist+']').fireEvent('click');
	},
	
	setPlaylistEvents: function() {
		this.log('playlist events set');
		$$('#playlists ul li a.playerbutton','#playlists ul li span.tracktitle','#playlists ul li img.coverimage').each(function(elm){
			elm.addEvent('click', this.playTrack.bindWithEvent(this, elm));
		}.bind(this));
		
		$$('#tabbars ul li a').each(function(elm){
			elm.removeEvents('click');
			elm.addEvent('click', this.switchPlaylist.bindWithEvent(this, elm));
		}.bind(this));
		
		playlistScroller = new Scroller($('playlists'));
		
		var playlistSorting = new Sortables($('userplaylist'), {
		    revert: { duration: 500, transition: 'elastic:out' },
			clone: true,
			//constrain: true, TODO set contstrain to false for IE, true for others
			opacity: 0.5,
			onStart: function(elm, clone) {
		    	playlistScroller.start();
		    },
		    onComplete: function(elm) {
		    	playlistScroller.stop();
		    	this.setPlaylistOrder();
		    }.bind(this)
		});
		
		$$('.trackitem').each(function(elm) {
			elm.addEvent('mouseenter', function(e, elm){
				if(e != null) {
					e.preventDefault();
					e.stopPropagation();
				}
				elm.addClass('over');
			}.bindWithEvent(this, elm));
			elm.addEvent('mouseleave', function(e, elm){
				if(e != null) {
					e.preventDefault();
					e.stopPropagation();
				}
				elm.removeClass('over');
			}.bindWithEvent(this, elm));
		}.bind(this));
	},
	
	setPlaylistOrder: function() {
		trackIds = [];
		listItems = $('userplaylist').getElements('li');
		listItems.each(function(elm) {
			trackIds.include(elm.get('rel'));
		});
		trackIdString = trackIds.join('|');
		if(trackIdString != null) var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php"}).post({'type': 'playlistorder', 'playlist': trackIdString});	
	},
	
	switchPlaylist: function(e, elm) {
		if(elm != null) elm = $(elm);
		if(e != null) e.preventDefault();
		playlistName = elm.get('rel');
		this.activatePlaylist(playlistName);
	},
	
	activatePlaylist: function(playlistName) {
		this.log(playlistName);
		$$('#playlists ul.playlist').setStyle('display', 'none');
		$$('#tabbars ul li').removeClass('active');
		$(playlistName).setStyle('display', 'block');
		$$('#tabbars ul li[rel='+playlistName+']').addClass('active');
		
		this.selectedPlaylist = playlistName;
	},
	
	playlistAction: function(e, elm) {
		if(elm != null) elm = $(elm);
		if(e != null) e.preventDefault();
		if(this.userId == 0 && this.type == 'remote') {
			openLogin('community');
			return false;
		}
		elm.addClass('handleloading');
		trackId = elm.get('rel');
		if(elm.getParent('div.trackitem') != null && trackId == null) trackId = elm.getParent('div.trackitem').get('rel');
		if(trackId == null) trackId = this.loadedTrack.iPlayerTrackId;
		if(elm.hasClass('addtoplaylist')) {
			this.addToPlaylist(trackId);
		} else if(elm.hasClass('removeplaylist')) {
			this.removeFromPlaylist(trackId);
		}
	},
	
	addToPlaylist: function(trackId) {
		if(trackId != null) var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.handlePlaylistAction.bindWithEvent(this)}).post({'type': 'addtoplaylist', 'trackId': trackId});
	},
	
	removeFromPlaylist: function(trackId) {
		if(trackId != null) var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.handlePlaylistAction.bindWithEvent(this)}).post({'type': 'removefromplaylist', 'trackId': trackId});
	},
	
	handlePlaylistAction: function(playlistResult, mastercall) {
		this.log('handle playlist');
		if(this.type == 'master' && mastercall != false) {
			//window.fireEvent('handlePlaylistAction', [playlistResult, false]);
			this.master.opener.mootunesHandler.handlePlaylistAction(playlistResult, false);
		} else if(this.type == 'remote' && mastercall != false && this.master != null) {
			this.master.mootunesHandler.handlePlaylistAction(playlistResult, false);
		}
		
		if(playlistResult.succes == 'true'){
			trackId = playlistResult.iPlayerTrackId;
			
			if(this.loadedTrack != null && trackId == this.loadedTrack.iPlayerTrackId) {
				buttonSelection = $$('#playerbarcontainer a.playlistbutton','.trackitem[rel='+trackId+'] a.playlistbutton','.trackdetails[rel='+trackId+'] a.playlistbutton','.feddepick .playlistbuttons .playlistbutton[rel='+trackId+']');
			} else {
				buttonSelection = $$('.trackitem[rel='+trackId+'] a.playlistbutton','.trackdetails[rel='+trackId+'] a.playlistbutton','.feddepick .playlistbuttons .playlistbutton[rel='+trackId+']');
			}
			
			if(this.type == 'remote') {
				notify.alert(playlistResult.message);
			} else if(this.type == 'master') {
				this.loadPlaylists();
			}
			
			if(playlistResult.type == 'add') {
				sRemoveClass = 'addtoplaylist';
				sAddClass = 'removeplaylist';
				sSetHtml = '- remove from playlist';
				sParentDisplay = 'block';
			} else if(playlistResult.type == 'remove') {
				sRemoveClass = 'removeplaylist';
				sAddClass = 'addtoplaylist';
				sSetHtml = 'add to playlist';
				sParentDisplay = 'none';
			}
			
			buttonSelection.each(function(elm){
				elm.removeClass('handleloading');
				if(!elm.hasClass('manageplaylist')) {
					elm.removeClass(sRemoveClass);
					elm.addClass(sAddClass);
					elm.set('html',sSetHtml);
					if(elm.getParent('.trackitem') != null) {
						elm.getParent('.playlistbuttons').setStyle('display',sParentDisplay);
						if(sParentDisplay == 'none') elm.getParent('.playlistbuttons').erase('style');
					}
				}
			}.bind(this));
		} else {
			notify.alert('We could not handle your playlist request right now. Please try again later.');
		}
	},
	
	setDefaultTrack: function() {
		loadedTrackId = Cookie.read('loadedTrack');
		if(loadedTrackId == null && this.loadedTrack == null) {
			playlist = this.playlists.get(this.options.defaultPlaylist);
			this.currentPlaylist = this.options.defaultPlaylist;
			if(this.userId != 0) {
				userPlaylist = this.playlists.get('userplaylist');
				if(userPlaylist.length != 0) {
					playlist = userPlaylist;
					this.currentPlaylist = 'userplaylist';
				}
			}
			this.loadTrackInfo(playlist[0].iPlayerTrackId);
		} else {
			this.loadTrackInfo(loadedTrackId);
		}
	},
	
	loadTrackInfo: function(iPlayerTrackId) {
		this.trackStop();
		var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.setTrackInfo.bindWithEvent(this)}).post({'type': 'gettrackinfo', 'iplayertrackid': iPlayerTrackId});
		this.resetTrackUI();
	},
	
	setTrackInfo: function(trackInfo) {
		this.loadedTrack = trackInfo;
		this.log(trackInfo);
		if(this.loadedTrack.iPlayerTrackId != null) {
			this.cookieDo('write', 'loadedTrack', this.loadedTrack.iPlayerTrackId);
			this.updateTrackUI(this.loadedTrack);

			this.fireEvent('trackInfoLoaded', this.loadedTrack.iPlayerTrackId);
		} else {
			alert('could not load track');
		}
	},
	
	goToTrack: function(e) {
		if(e != null) e.preventDefault();
		trackInfo = this.loadedTrack;
		trackUrl = 'http://'+trackInfo.staticInfo.sLogin+'.feddelegrand.com/tracks/'+trackInfo.sUrl;
		if(this.type == 'master') {
			this.master.opener.location = trackUrl;
			this.master.opener.focus();
		} else {
			window.location = trackUrl;
		}
	},
	
	updateTrackUI: function(trackInfo) {
		this.loadedTrack = trackInfo;

		titleElm = $('playerbarcontainer').getElement('div.tracktitle');
		uploaderElm = $('playerbarcontainer').getElement('span.uploadedinfo');
		imageCoverElm = $('playerbarcontainer').getElement('img.coverimage');
		trackTitle = trackInfo.sArtist+' - '+trackInfo.sTitle;
		titleElm.set('html', trackTitle);
		titleElm.removeEvents('click');
		titleElm.addClass('hand');
		imageCoverElm.set('src','http://www.feddelegrand.com/images/r-92-92-c/0-0-'+trackInfo.iCoverId+'.jpg');
		if(this.loadedTrack.sType != 'flamingo') {
			uploaderElm.set('html', 'by <a href="http://'+trackInfo.staticInfo['sLogin']+'.feddelegrand.com/tracks">'+trackInfo.staticInfo['sFullName']+'</a>');
			if(this.type == 'master') {
				$$('span.uploadedinfo a').each(function(elm) {
					elm.addEvent('click', this.userlink.bindWithEvent(this, elm));
				}.bind(this));
			}
			titleElm.addEvent('click', this.goToTrack.bindWithEvent(this));
			//uploaderElm.setStyle('display','block');
			$$('div.buybuttons').setStyle('display','none');
			$$('div.trackstats #fans').setStyle('display','block');
			$$('div.trackstats #comments').setStyle('display','block');
			$$('div.trackstats #playsnr').set('html',trackInfo.iPlays);
			$$('div.trackstats #fansnr').set('html',trackInfo.iTotalFans);
			$$('div.trackstats #commentsnr').set('html',trackInfo.iTotalComments);
			
			$$('div.votingcontainer').setStyle('display','block');
			$$('#playerbarcontainer a.voteup').removeClass('inactiveup');
			$$('#playerbarcontainer a.votedown').removeClass('inactivedown');
			if(trackInfo.iRating == false) {
				this.log('novoting');
				$$('#playerbarcontainer a.votebutton').each(function(elm){
					elm.removeEvents('click');
					elm.addEvent('click', this.voteTrack.bindWithEvent(this, elm));
				}.bind(this));
			} else {
		
				if(this.loadedTrack.iUserId.toInt() == this.userId.toInt()) {
					upclass = 'inactiveup';
					downclass = 'inactivedown';
				} else if(trackInfo.iRating.toInt() >= 0) {
					upclass = 'votedup';
					downclass = 'inactivedown';
				} else {
					upclass = 'inactiveup';
					downclass = 'voteddown';
				}
				$$('#playerbarcontainer a.voteup').addClass(upclass);
				$$('#playerbarcontainer a.votedown').addClass(downclass);
			}
			extraVotes = ' +';
			if(trackInfo.iTotalRating.toInt() < 0) extraVotes = ' -';
			$$('#playerbarcontainer span.totalrating').set('html', trackInfo.iTotalRating+extraVotes);
		} else {
			uploaderElm.set('html', '');
			if(this.loadedTrack.shops != null && this.loadedTrack.shops.length > 0) {
				$$('div.buybuttons a.buybutton').setStyle('display','none');
				this.loadedTrack.shops.each(function(shopInfo){
					buyButton = $$('div.buybuttons a.'+shopInfo.sName.toLowerCase());
					buyButton.set('href',shopInfo.sUrl);
					buyButton.setStyle('display','block');
				});
				$$('div.buybuttons').setStyle('display','block');
			}			
			$$('div.buybuttons a.buybutton')
			$$('div.trackstats #fans').setStyle('display','none');
			$$('div.trackstats #comments').setStyle('display','none');
			$$('div.trackstats #playsnr').set('html',trackInfo.iPlays);
			$$('#playerbarcontainer div.votingcontainer').setStyle('display','none');
		}
		
		if(trackInfo.bInPlaylist) {
			sRemoveClass = 'addtoplaylist';
			sAddClass = 'removeplaylist';
			sSetHtml = '- remove from playlist';
		} else if(!trackInfo.bInPlaylist) {
			sRemoveClass = 'removeplaylist';
			sAddClass = 'addtoplaylist';
			sSetHtml = 'add to playlist';
		}
		
		$$('#playerbarcontainer a.playlistbutton').each(function(elm){
			if(!elm.hasClass('manageplaylist')) {
				elm.removeClass(sRemoveClass);
				elm.addClass(sAddClass);
				elm.set('html',sSetHtml);
			}
		});
		
		$$('#playerbarcontainer div.trackstats').setStyle('display','block');
		
		$('totaltime').set('html', this.millisecondsToTime(this.loadedTrack.iLength));
		if(this.currentTrackLength == 0 && this.master != null && this.type == 'remote') {
			this.currentTrackLength = this.master.mootunesHandler.currentTrackLength;
			this.loaded = this.master.mootunesHandler.loaded;
			if(this.loaded != null) $('trackerloader').setStyle('width', this.loaded+'%');
		}
		
		$$('#playerbarcontainer div.trackinfo').setStyle('display','block');
		
		this.options.target.removeClass('loading');
		if(this.type == 'master') window.fireEvent('updateTrackUI', trackInfo);
	},
	
	resetTrackUI: function() {
		if(this.type == 'master') window.fireEvent('resetTrackUI');
		
		titleElm = $('playerbarcontainer').getElement('div.tracktitle');
		uploaderElm = $('playerbarcontainer').getElement('span.uploadedinfo');
		imageCoverElm = $('playerbarcontainer').getElement('img.coverimage');;
		titleElm.set('html', '&nbsp;');
		titleElm.removeEvents('click');
		titleElm.removeClass('hand');
		$$('#playerbarcontainer div.trackinfo').setStyle('display','none');
		imageCoverElm.set('src','http://data.feddelegrand.nl/images/r-92-92-c/0-0-0.jpg');
		$$('#playerbarcontainer div.trackstats').setStyle('display','none');
		$('trackerball').setStyle('left', this.trackerBallBase+'px');
		$('trackerprocess').setStyle('width', '0px');
		$('trackerloader').setStyle('width', '0%');
		$('timeplayed').set('html', '0:00');
		$('totaltime').set('html', '0:00');
		this.options.target.addClass('loading');
		
	},
	
	updateTime: function(trackPosition) {
		time = this.millisecondsToTime(trackPosition);
		$('timeplayed').set('html', time);
		if(this.type == 'master') window.fireEvent('updateTime', trackPosition);
	},
	
	loadMaster: function(e) {
		if(isNaN(e) && e != null) e.preventDefault();
		if(this.master == null) {
			windowOpen = this.cookieDo('read', 'playerOpen', null);
			if(windowOpen != null) url = '';
			else url = this.options.masterUrl;
			
			this.removeEvents('trackInfoLoaded');
			
			this.master = this.openWindow.attempt(url, this);
			window.focus();
			if(this.master != null) {
				if(url == '') {
					if(this.master.mootunesHandler != null) {
						this.setRemoteListening();
						this.loadMasterInfo();
					} else {
						this.popupClose();
						this.master.close();
					}
				} else {
					this.startUp = true;
				}
			} else {
				this.popupClose();
			}
			window.focus();
		} else {
			if(navigator.userAgent.indexOf('Chrome/') > 0 || navigator.userAgent.indexOf('Opera/') > 0) {
				this.master.alert('You can now edit your playlist!');
			} else {
				this.master.focus();
			}
		}
	},
	
	openWindow: function(url) {
		return window.open(url, "mootunesPlayer", "width="+this.options.masterWidth+",height="+this.options.masterHeight+",scrollbars=no");
	},
	
	loadMasterInfo: function() {
		this.log('load master info');
		
		//this.userId = this.master.mootunesHandler.userId;
		this.userLogged = this.master.mootunesHandler.userLogged;
		this.setTrackInfo(this.master.mootunesHandler.loadedTrack);
		if(this.master.mootunesHandler.trackIsPlaying) this.trackPlaying(this.loadedTrack.iPlayerTrackId);
		this.log(this.master.mootunesHandler.loaded);
		this.loaded = this.master.mootunesHandler.loaded;
		this.currentTrackLength = this.master.mootunesHandler.currentTrackLength;
		$('trackerloader').setStyle('width', this.loaded+'%');
	},
	
	popupClose: function() {
		this.log('popup closed');
		this.trackStop();
		this.master = null;
		this.startPlay = true;
		this.trackIsPlaying = false;
		this.cookieDo('dispose','playerOpen', null);
		this.resetTrackUI();
		$('footer').removeClass('playerloaded');
		$('musicplayerremote').addClass('notloaded');
	},
	
	shutDown: function(e) {
		if(this.type == 'master') {
				window.fireEvent('popupClose');
				this.cookieDo('dispose','playerOpen', null);
		} else {
			this.unsetRemoteListening();
		}
	},
	
	cookieDo: function(type, name, value) {
		if(type == 'write') {
			return Cookie.write(name, value, {domain: '.feddelegrand.com', path: '/'});
		} else if (type == 'read') {
			return Cookie.read(name);
		} else if (type == 'dispose') {
			return Cookie.dispose(name, {domain: '.feddelegrand.com', path: '/'});
		}
			
	},
	
	millisecondsToTime: function(milliseconds) {
		milliseconds = parseInt(milliseconds);
		var d = new Date(milliseconds);
		seconds = d.getSeconds();
		if(isNaN(seconds)) return '0:00';
		minutes = d.getMinutes();
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
		return minutes+':'+seconds;
	},
	
	voteTrack: function(e, elm) {
		if(elm != null) elm = $(elm);
		if(e != null) e.preventDefault();
		if(this.userId == 0 && this.type == 'remote') {
			openLogin('community');
			return false;
		}
		voteId = elm.getParent('div.votingcontainer').get('rel');
		if (voteId != null) {
			if(voteId != 'voted') {
				type = 'up';
				if(elm.hasClass('votedown')) type = 'down';
			} else {
				notify.alert('You\'ve already voted or this is your own track!');
				return false;
			}
		} else {
			voteId = this.loadedTrack.iPlayerTrackId;
			type = 'up';
			if(elm.hasClass('votedown')) type = 'down';
		}
		var jsonRequest = new Request.JSON({url: "/assets/handlers/handler.tracks.php", onSuccess: this.handleVoting.bindWithEvent(this)}).post({'type': 'vote', 'iPlayerTrackId': voteId, 'vote': type});
	},
	
	handleVoting: function(votingInfo, mastercall) {
		this.log('voteinfo: '+votingInfo);
		if(this.type == 'master' && mastercall != false) {
			//window.fireEvent('handleVoting', [votingInfo, false]);
			this.master.opener.mootunesHandler.handleVoting(votingInfo, false);
		} else if(this.type == 'remote' && mastercall != false && this.master != null) {
			this.master.mootunesHandler.handleVoting(votingInfo, false);
		}
		
		if(votingInfo.succes == 'true') {
			if(votingInfo.vote == 'up') {
				upclass = 'votedup';
				downclass = 'inactivedown';
			} else {
				upclass = 'inactiveup';
				downclass = 'voteddown';
			}
			if(this.loadedTrack != null && this.loadedTrack.iPlayerTrackId == votingInfo.iPlayerTrackId) {
				buttonSelection = $$('#playerbarcontainer .votingcontainer a.votebutton','.trackdetails .votingcontainer a.votebutton','.feddepick .votingcontainer a.votebutton','body.contest div.trackitem div.votingcontainer[rel='+votingInfo.iPlayerTrackId+'] a.votebutton');
				textSelection = $$('#playerbarcontainer .votingcontainer span.totalrating', '.trackdetails .votingcontainer span.totalrating','.feddepick .votingcontainer a.votebutton');
			} else {
				buttonSelection = $$('.trackdetails .votingcontainer a.votebutton','.feddepick .votingcontainer a.votebutton','body.contest div.trackitem div.votingcontainer[rel='+votingInfo.iPlayerTrackId+'] a.votebutton');
				textSelection = $$('.trackdetails .votingcontainer span.totalrating','.feddepick .votingcontainer a.votebutton');
			}
			
			buttonSelection.each(function(elm){
				if(elm.hasClass('voteup')) {
					elm.addClass(upclass);
				} else if(elm.hasClass('votedown')) {
					elm.addClass(downclass);
				}
			}.bind(this));
			
			extraVotes = ' +';
			if(votingInfo.iTotalVotes.toInt() < 0) extraVotes = ' -';
			textSelection.set('html', votingInfo.iTotalVotes+extraVotes);
			this.setTotalRating(votingInfo.iTotalVotes, null);
			if(this.type == 'remote') {
			  notify.alert('Thank you for your vote!');
        publishPage('Check out this track on feddelegrand.com!')
			}
			
		} else if(votingInfo.error == 'not_active') {
			if(this.type == 'remote') Sexy.alert('<h1>You\'re account is not activated yet!</h1><br />Check your e-mail ('+votingInfo.email+') for the activation link before voting! Be sure to check your spam folder as well.');
		} else if(votingInfo.error == 'no_contest') {
			if(this.type == 'remote') Sexy.alert('<h1>This contest has ended!</h1><br />You cannot vote for this track anymore because it is a contest remix entry.');
		} else {
			if(this.type == 'remote') notify.alert('We can\'t handle your vote right now, please try again later!');
		}
	},
	
	setTotalRating: function(rating) {
		this.log('rating: '+rating);
		if(this.loadedTrack != null) this.loadedTrack.iTotalRating = rating;
		/*if(this.type == 'master') {
			window.fireEvent('setTotalRating', [rating, true]);
		} else if((mastercall == null || mastercall == false) && this.master != null) {
			this.master.mootunesHandler.setTotalRating(rating, false); 
		}*/
	},
	
	crashHandling: function() {
		this.cookieDo('dispose', 'playerOpen', '');
		if(this.type == 'remote') {
			if(this.master != null) {
				//this.master.close();
				//this.popupClose();
			}
			//notify.alert('Error in the script please reload!!');
		} else {
			//window.fireEvent('popupClose');
			//window.close();
		}
	},
	
	catchClick: function(e) {
		e.preventDefault();
		return false;
	}
});
