var mp3player; // one and only actual instance

var MP3Player = Class.create ({
	initialize: function(player) {
	
		
	
		
		this.player = window.document[player];
		/* only one mp3player should exist */
		/* removed as causes malfunction on move and minimize  */
		if (mp3player) {
			//	console.log(mp3player);
		}
		this.player.addModelListener('TIME', 'mp3player.trackTime');
		this.player.addModelListener("STATE", "mp3player.stateListener");
		this.totalWidth = 188; // total width of bar
		this.tribeId = 0; // all tribes

		Event.observe($('volume_off'), 'click', this.setVolume.bindAsEventListener(this), false);
		Event.observe($('volume_on'), 'click', this.setVolume.bindAsEventListener(this), false);
		Event.observe($('position'), 'click', this.seek.bindAsEventListener(this), false);

		this.isLooping = false;
		this.isShuffling = false;
		this.playTime = 0;
		if(playMode=="random"){
			//this.tribeId = 52;
			this.loadRandom(1);
		}


		if(playMode=="randomWithPlaylist"){
	
			this.loadRandomPlaylist(1);

		}
		if(playMode=="tracklist"){
			this.loadTrackList(1);
		}
		
		if(playMode=="eventPlaylist"){
			this.loadEventPlaylist(1);
		}


	},

	/* build HTML UL list of tracks */
	buildList: function() {
		/* clear list first */
		this.currentTrack = 0;
		this.isPlaying = false;
		this.currentDuration = null;
		$('mp3trackUL').childElements().each(function(el){el.remove()});

		var trackNo = 0;
		/* rebuild list */
		this.trackList.each( function(track){
			var li = new Element('li');
			if (track.isBonus == 'Y')
			li.insert(new Element('div', {'class': 'bonus'}).update('bonus'));

			li.trackNo = trackNo;

			li.observe('click', function(e) {
				mp3player.load(Event.findElement(e, 'li').trackNo );
			});

			li.insert(new Element('div').update(track.title.substr(0, 34)));
			li.insert(new Element('div', {'class': 'artist'}).update(track.author));
			$('mp3trackUL').insert(li);
			trackNo++;
		});

	},

	stateListener: function (obj) {
		//IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
		currentState = obj.newstate;
		previousState = obj.oldstate;

		if ((currentState == "COMPLETED")) {
			if (this.isLooping)
			this.player.sendEvent('ITEM', this.currentTrack);
			else
			this.next(true);
		}
	},

	setVolume: function(e) {
		var x = e.pointerX();
		var level = x - $('volume_off').cumulativeOffset().left + 1;
		$('volume_on').setStyle({width: level+'px'});
		var level_pct = Math.round((level/33)*100);
		this.player.sendEvent('VOLUME',level_pct);
	},

	seek: function(e) {
		if (!this.isPlaying)
		return;

		var currentPos = e.pointerX()-e.element().cumulativeOffset().left;

		var unit = this.totalWidth/this.currentDuration;
		var targetPos = Math.round(currentPos / unit);
		this.player.sendEvent('SEEK', targetPos);
	},


	play: function(autoNext) {

		this.isPlaying = true;
		if($('mp3Details')){
			if(this.trackList[this.currentTrack].tribeDesc==null ){
				var tribeDesc = "";
			} else {
				var tribeDesc = this.trackList[this.currentTrack].tribeDesc;
			}
			$('mp3Details').update(tribeDesc);
		}

		$('play').addClassName('pause');
		$('mp3trackUL').childElements()[this.currentTrack].addClassName('playing');
		$('mp3trackUL').childElements()[this.currentTrack].setStyle('playing');
		$('display').down().setStyle({backgroundImage: 'url('+this.trackList[this.currentTrack].totem+')'});
		$('display').down(1).update(this.trackList[this.currentTrack].title.substr(0, 50));
		$('display').down(2).update(this.trackList[this.currentTrack].tribe);
		this.player.sendEvent('PLAY', true);

	},

	playcurrent: function(autoNext){
		if($('mp3Details')){
			if(this.trackList[this.currentTrack].tribeDesc==null){
				var tribeDesc = "";
			} else {
				var tribeDesc = this.trackList[this.currentTrack].tribeDesc;
			}
			$('mp3Details').update(tribeDesc);
		}

		this.isPlaying = true;
		$('play').addClassName('pause');
		$('mp3trackUL').childElements()[this.currentTrack].addClassName('playing');
		$('mp3trackUL').childElements()[this.currentTrack].setStyle('playing');
		$('display').down().setStyle({backgroundImage: 'url('+this.trackList[this.currentTrack].totem+')'});
		$('display').down(1).update(this.trackList[this.currentTrack].title.substr(0, 50));
		$('display').down(2).update(this.trackList[this.currentTrack].tribe);
		this.player.sendEvent('ITEM', this.currentTrack);

	},

	next: function(autoNext) {
		$('mp3trackUL').childElements()[this.currentTrack].removeClassName('playing');

		if (this.isShuffling) {
			this.currentTrack = Math.floor(Math.random()*this.trackList.length)
		}
		else {
			if (this.currentTrack >= this.trackList.length-1)
			this.currentTrack = -1;
			this.currentTrack++;
		}
		this.playcurrent(autoNext);
	},

	prev: function() {
		if (this.currentTrack <= 0)
		return;

		$('mp3trackUL').childElements()[this.currentTrack].removeClassName('playing');
		this.currentTrack--;
		this.playcurrent();
	},

	loop: function() {
		if (this.isLooping) {
			this.isLooping = false;
			$('loop').removeClassName('looping');
		}
		else {
			this.isLooping = true;
			$('loop').addClassName('looping');
		}
	},

	shuffle: function() {
		if (this.isShuffling) {
			this.isShuffling = false;
			$('shuffle').removeClassName('shuffling');
		}
		else {
			this.isShuffling = true;
			$('shuffle').addClassName('shuffling');
		}
	},

	pause: function() {
		$('play').removeClassName('pause');
		$('play').addClassName('playing');
		this.player.sendEvent('PLAY',false);
	},

	togglePlay: function() {
		if (this.isPlaying == true) {
			this.pause();
			this.isPlaying = false;
		}
		else {
			this.play();
			this.player.sendEvent('PLAY',true);
			this.isPlaying = true;
		}
	},

	load: function(trackNo) {
		$('mp3trackUL').childElements()[this.currentTrack].removeClassName('playing');
		this.currentTrack = trackNo;
		this.playcurrent();

	},


	loadRandomPlaylist: function(page) {
		new Ajax.Request('?func=PageModule', {
			method: 'post',
			postBody: 'ClassName=Music&Method=getRandomPlaylist&TribeId='+this.tribeId+'&Music_pageNo='+page,
			onSuccess: function(r) {
				this.trackList = r.responseJSON[0];
				this.details = r.responseJSON[2];
				this.pager = r.responseJSON[1];
				if (!this.trackList[0])
				return(false);

				this.buildList();
				this.player.sendEvent('LOAD', this.trackList);
				$('mp3Pager').update(this.pager);

				$('display').down().setStyle({backgroundImage: 'url('+this.trackList[0].totem+')'});
				$('display').down(1).update(this.trackList[0].title);
				$('display').down(2).update(this.trackList[0].tribe);

			}.bind(this)
		});
	},

	loadRandom: function(page) {
		new Ajax.Request('?func=PageModule', {
			method: 'post',
			postBody: 'ClassName=Music&Method=getRandom&TribeId='+this.tribeId+'&Music_pageNo='+page,
			onSuccess: function(r) {
				this.trackList = r.responseJSON[0];
				this.pager = r.responseJSON[1];
				if (!this.trackList[0])
				return(false);

				this.buildList();
				this.player.sendEvent('LOAD', this.trackList);
				$('mp3Pager').update(this.pager);

				$('display').down().setStyle({backgroundImage: 'url('+this.trackList[0].totem+')'});
				$('display').down(1).update(this.trackList[0].title);
				$('display').down(2).update(this.trackList[0].tribe);

				if($('mp3Details')){
					if(this.trackList[0].tribeDesc==null){
						var tribeDesc = "";
					} else {
						var tribeDesc = this.trackList[0].tribeDesc;
					}
					$('mp3Details').update(tribeDesc);
				}
				
				
				//play track after loading
				//this.play();

			}.bind(this)
		});


	},

	
	loadEventPlaylist: function(page) {
		new Ajax.Request('?func=PageModule', {
			method: 'post',
			postBody: 'ClassName=Music&Method=getEventPlaylist&evntId='+evntId+'&Music_pageNo='+page,
			onSuccess: function(r) {
				this.trackList = r.responseJSON[0];
				this.pager = r.responseJSON[1];
				if (!this.trackList[0])
				return(false);

				this.buildList();
				this.player.sendEvent('LOAD', this.trackList);
				$('mp3Pager').update(this.pager);
				$('display').down().setStyle({backgroundImage: 'url('+this.trackList[0].totem+')'});
				$('display').down(1).update(this.trackList[0].title);
				$('display').down(2).update(this.trackList[0].tribe);

			}.bind(this)
		});
	},

	loadTrackList: function(page) {
		new Ajax.Request('?func=PageModule', {
			method: 'post',
			postBody: 'ClassName=Music&Method=getTrackList&TribeId='+this.tribeId+'&Music_pageNo='+page,
			onSuccess: function(r) {
				this.trackList = r.responseJSON[0];
				this.pager = r.responseJSON[1];
				if (!this.trackList[0])
				return(false);

				this.buildList();
				this.player.sendEvent('LOAD', this.trackList);
				$('mp3Pager').update(this.pager);
				$('display').down().setStyle({backgroundImage: 'url('+this.trackList[0].totem+')'});
				$('display').down(1).update(this.trackList[0].title);
				$('display').down(2).update(this.trackList[0].tribe);

			}.bind(this)
		});
	},

	loadTribe: function (tribeId) {
		this.tribeId = tribeId;
		this.loadTrackList(1);
	},

	trackTime: function(obj) {
		this.currentDuration = obj.duration;
		var unit = this.totalWidth/obj.duration;
		var remain = Math.round(obj.duration-obj.position)
		var min = Math.floor(remain/60);
		var sec = remain - min*60;
		$('counter').update(min.toPaddedString(2)+':'+(sec).toPaddedString(2));
		$('pos').setStyle({width: ((obj.position*unit)+1).round()+'px'});

		/* give points according to tracked time */
		var prevPlayTime = this.playTime;
		this.playTime = Math.floor(obj.position/60);
		if (this.playTime <= prevPlayTime)
		return (false);

		new Ajax.Request("index.php?func=PageModule", {
			parameters: {
				ClassName: 'Music',
				Method: 'trackMedia',
				MediaLibraryId: this.trackList[this.currentTrack].mediaLibraryId,
				Minutes: this.playTime
			},
			onSuccess: function(t) {
				var obj = t.responseJSON[0];
				$('currentPoints').update(obj.pointsTotal);
				$('pointsToday').update(obj.pointsToday);
			}
		});
	}
});


function initMP3Player() {
	var params = { allowfullscreen:'false', allowscriptaccess: 'always', wmode: 'transparent', bgcolor:'#000000' };
	var flashvars = { type: 'sound', playlist: 'none' };
	var atts = { id: "mp3pl", name: "mp3pl" };
	swfobject.embedSWF('js/player/player.swf','player_flv','1','1','9.0.0', null, flashvars, params, atts, playerReady );
}

Event.observe(window, 'load', initMP3Player);

