var swiff = null;
var swiffHome = null;

window.addEvent('domready', function() { 
	swiffHome = new Element('div', {id: 'swiffHome'}).setStyles({position:'absolute','top':1,'left':1}).inject(document.body);
	swiff = new Swiff('MooSound.swf', {width: 1, height: 1, container: swiffHome, swLiveConnect: true}); 
});

var AudioPlayer = new Class({
	songs: Array(),
	
	curSong : 0,
	playing: false,
	
	build : function () {
		$('playerList').innerHTML = "";
		this.seekbar = $('seekbar');
		title = $('playerTitle');
		title.fade('hide').set('text',this.playlistTitle).fade('in');
		this.progressFx   = new Fx.Tween(this.seekbar, 'width', {unit:'%', link: 'cancel'});
		this.positionFx   = new Fx.Tween($('position'), 'width', {unit:'%', link: 'cancel'});
		this.seekbar.addEvent('click', function(e) {
			var coords = this.seekbar.getCoordinates();
			var ms = ((e.page.x - coords.left)/coords.width)*this.songs[this.curSong].duration;
			this.songs[this.curSong].jumpTo(ms);
		}.bind(this));
		
		for (var i=0;i<this.songs.length;i++) {

			this.el = new Element('div', {'class':'song','id':'song'+i}).inject($('playerList'));
			this.title        = new Element('a', {'class':'title','href':'javascript:AudioPlayer.gotoAndPlay('+i+')', 'onclick':'this.blur()', text:this.songs[i].title}).inject(this.el);

		}
		this.controls = $('playerControls');
	},
	
	load : function (title, songs) {
		this.stop();
		this.playlistTitle = title;
		this.songs = Array();
		for (var i=0;i<songs.length;i++) {
			this.songs.push(new Sound(songs[i][0], this, {
				'onProgress' : this.onProgress.bind(this),
				'onPosition' : this.onPosition.bind(this),
				'onComplete' : this.onComplete.bind(this),
				'title' : songs[i][1]
			}));
		}
		this.curSong = 0;
	},
	
	play: function () {
		if (this.songs.length==0) return;
		
		$('song'+this.curSong).addClass('playing');
		this.songs[this.curSong].start(0);
		this.seekbar.fade('in');
		playBtn.src="img/btnPause.gif";
		this.playing = true;
	},
	
	playToggle : function () {
		if (this.playing)
			this.stop();
		else 
			this.play();
	},
	
	stop: function () {
		if (!this.playing) return;
		$('song'+this.curSong).removeClass('playing');
		this.songs[this.curSong].stop();
		this.seekbar.fade('out');
		playBtn.src="img/btnPlay.gif";
		this.playing = false;
	},
	
	next: function () {
		if (this.songs.length==0) return;
		this.stop()
		this.curSong++;
		if (this.curSong==this.songs.length)
			this.curSong=0;
		this.play();
	},

	prev: function () {
		this.stop();
		this.curSong--;
		if (this.curSong==-1)
			this.curSong=this.songs.length-1;
		this.play();
	},
	
	gotoAndPlay : function (nr) {
		this.stop();
		this.curSong = nr;
		this.play();
	},
	
	onProgress: function(loaded, total) {
		var percent = (loaded / total*100).round(2);
		this.progressFx.start(percent * .66);
	},
	
	onPosition: function(position,duration) {
		var percent = (position/duration*100).round(2);
		this.positionFx.start(percent);
	},
	
	onComplete: function() {
		this.next();
	}

});

AudioPlayer = new AudioPlayer();

var Sound = new Class({ 

	Implements: [Options, Events],

	options: {
		autostart: false,  //autostart
		streaming: true,   //streaming
		volume: 50,        //volume to start at
		pan: 0,            //pan between -100 (left) and 100 (right)
		progressInterval: 500, //milliseconds between getProgress(); calls
		positionInterval: 500,//milliseconds between getPosition(); calls
		onRegister: $empty,//fires when the sound is registered
		onLoad: $empty,    //fires when the sound is downloaded
		onPlay: $empty,    //fires when the sound begins playing
		onPause: $empty,   //fires when the sound is paused
		onStop: $empty,    //fires when the sound stops playing
		onComplete: $empty, //fires when the sound completes playing
		onProgress: $empty,//fires when download makes progress
		onPosition: $empty,//fires when position within the song changes
		onID3: $empty      //fires when ID3 tags become available
	},

	initialize: function(url, manager, options) {
		this.setOptions(options);
		this.url = url;
		this.id3 = new Hash();
		this.manager = manager;
		this.swf = swiff;
		this.playing = false;
		this.listeners = {};
		this.filesize = null;
		this.duration = null;
		this.pausedAt = 0;
		this.position = 0;
		this.register();
		this.title = this.options.title || url;
	},

	start: function(position) {
		var pos = position || this.pausedAt;
		this.swf.startSound(this.url, pos, this.options.volume, this.options.pan);
		this.fireEvent('onPlay');
		this.pausedAt = 0;
		return this;
	},

	stop: function() {
		this.swf.stopSound(this.url);
		this.fireEvent('onStop');
		return this;
	},

	jumpTo: function(seconds) {
		$clear(this.listeners.position);
		this.start(seconds);
	},

	pause: function() {
		this.swf.stopSound(this.url);
		this.pausedAt = this.getPosition();
		this.fireEvent('onPause', this.pausedAt);
		this.fireEvent('onStop');
	},

	setVolume: function(volume) {
		//this.obj.setVolume(this.url, volume);
		this.options.volume = volume;
		return this;
	},

	setPan: function(pan) {
		this.swf.setPan(this.url, pan);
		this.options.pan = pan;
		return this;
	},

	getVolume: function() {
		return this.options.volume;
	},

	getPan: function() {
		return this.options.pan;
	},

	getID3: function(tag) {
		return this.id3.get(tag);	
	},

	getBytesLoaded: function() {
		return this.swf.getBytesLoaded(this.url);
	}, 

	getFilesize: function() {
		return this.swf.getBytesTotal(this.url);
	},

	getPosition: function() {
		return this.swf.getPosition(this.url);
	}, 

	getDuration: function() {
		return this.swf.getDuration(this.url);
	},

	checkProgress: function() {
		if ($type(this.filesize) !== "number") { this.filesize = this.getFilesize(); }
		var loaded = this.getBytesLoaded(); 
		if ($type(loaded) === "number" && loaded !== this.listeners.lastProgress) { 
			var total = this.getFilesize();
			this.listeners.lastProgress = loaded;
			this.fireEvent('onProgress', [loaded, total]); 
		}
	},

	checkPosition: function() {
		var position = this.getPosition();
		this.duration = this.getDuration();
		if ($type(position) === "number" && position !== this.listeners.lastPosition) { 
			this.listeners.lastPosition = position;
			this.fireEvent('onPosition', [(position / 1000).round(), (this.duration / 1000).round()]);
			if (position == this.duration) this.fireEvent('onComplete');
		}
	},

	register: function() {
		this.fireEvent('onRegister');
		if (this.options.streaming === false) {
			this.swf.preloadSound(this.url);
			this.listeners.progress = this.checkProgress.periodical(this.options.progressInterval, this);
		}
		this.addEvents({'onLoad': this.onLoad, 'onStop': this.onStop, 'onPlay': this.onPlay});
	},

	onLoad: function() {
		$clear(this.listeners.progress);
		this.checkProgress();
	},

	onPlay: function() {
		if (this.options.streaming === true) {
			this.listeners.progress = this.checkProgress.periodical(this.options.progressInterval, this);
		}
		this.playing = true;
		this.listeners.position = this.checkPosition.periodical(this.options.positionInterval, this);
		//this.manager.playing.push(this);
	},

	onStop: function() {
		$clear(this.listeners.position);
		if (this.pausedAt === 0) { this.fireEvent('onPosition', [0, this.duration]); }
		this.playing = false;
	}

});