var Player = new Class({
	Implements: Options,
	options: {
	},
	initialize: function(sound_manager, options){
		if(options) this.setOptions(options);
		this.sm = sound_manager;
		this.currentTrack = false;
		this.currentSound = false;
		this.tracklist = $('tracklist');
		
		this.master_button = $('play_button');
		this.master_button.addEvent('click', function(e){
			e.stop();
			this.play();
		}.bind(this));
	},
	
	loadTracks: function(url){
		var req = new Request.JSON({url: url});
		req.addEvent('success', this.onLoadTracks.bind(this));
		req.send();
	},
	
	onLoadTracks: function(rsp){
		this.tracks = rsp;
		this.tracks.each(function(el){
			this.sm.createSound(el.id, el.url);
		}.bind(this));
	},
	
	play: function(track_id){
	
		if( ! track_id){
			track_id = this.currentTrack ? this.currentTrack : this.tracks[0].id;
		}
		
		// Master button set to pause
		this.master_button.addClass('pause');
		
		
		// deal with the passed track
		if(track_id == this.currentTrack){
			this.pause();
		}else{
			this.sm.stopAll();
			this.sm.play(track_id, {
				onfinish: this.next.bind(this),
				onload: this.trackLoaded.bind(this),
				onbufferchange: this.bufferChange.bind(this)
			});
			
			if(this.currentTrack) $(this.currentTrack).removeClass('buffering');
			
			this.currentTrack = track_id;
			this.currentSound = this.sm.getSoundById(track_id);
						
			this.tracklist.getElements('li.selected').each(function(el){
				el.removeClass('selected');
			}.bind(this));
			$(track_id).getParent().addClass('selected');
		}
	},
	
	pause: function(){
		if(this.currentSound.paused){
			this.currentSound.resume();
			// Set master button to pause
			this.master_button.addClass('pause');
		}else{
			this.currentSound.pause();
			// Set master button to plause
			this.master_button.removeClass('pause');
		}
	},
	
	next: function(){
		var next_track = 0;
		this.tracks.each(function(el, key){
			if(el.id == this.currentTrack){
				next_track = key+1;
			}
		}.bind(this));
		
		if(next_track >= this.tracks.length){
			next_track = 0;
		}
		
		this.play(this.tracks[next_track].id);
	},
	
	
	setLoading: function(){
		$(this.currentTrack).getParent().getElement('.statusbar').set('opacity', 1);
		$(this.currentTrack).getParent().getElement('.loadingbar').tween('width', Math.ceil((this.currentSound.bytesLoaded/this.currentSound.bytesTotal)*$(this.currentTrack).getParent().getElement('.statusbar').getSize().x));
	},
	
	trackLoaded: function(){
		//$(this.currentTrack).getParent().getElement('.statusbar').tween('opacity', 0);
	},	
	
	
	bufferChange: function(){
		if(this.currentSound){
			if(this.currentSound.isBuffering){
				$(this.currentTrack).addClass('buffering');
			}else{
				$(this.currentTrack).removeClass('buffering');
			}
		}
	}
});