AudioPlayer = Class.create ({
	initialize: function () { // MUST BE DONE WHEN PAGE IS LOADED!
		this.cursor = 0;
		this.playing = false;
		this.started = false;
		this.startAtLoading = true;
		if (! this.startAtLoading) 
			Event.observe (window, 'load', this.init.bind(this));
		else
			soundManager.onload = this.start.bind(this);
	},
	
	init: function () {
		$('player-next').observe('click', this.next.bind(this));
		$('player-prev').observe('click', this.prev.bind(this));
		$('player-play').observe('click', this.play.bind(this));
		$('player-stop').observe('click', this.stop.bind(this));
	},
	
	start: function (notAtLoading) {
		if (! notAtLoading)	this.init();
		this.getTracksCount();
	},
	
	getTracksCount: function () {
		new Ajax.Request('./Home/GetSongCount', {onSuccess: this.updateTrackCount.bind(this)});
	},
	
	updateTrackCount: function (t) {
		this.count = parseInt(t.responseText);
		this.started = true;
		if (this.count > 0) {
			this.setCursor (0);
		}
	},
	
	next: function () {
		this.setCursor (+1);
	},

	prev: function () {
		this.setCursor (-1);
	},
	
	setCursor: function (delta) {
		this.stop();	
		this.cursor = this.cursor + delta;
		if (this.cursor < 0) this.cursor = 0;
		if (this.cursor >= this.count) this.cursor = 0;
		new Ajax.Request('./Home/GetSong?n='+this.cursor, {onSuccess: this.getTrack.bind(this)});
	},
	
	getTrack: function (t) {
		this.current = t.responseText.evalJSON();
		$('player-txt').innerHTML = this.current.Name+'<br/>'+this.current.Performer;
		this.createSound();
		this.play();
	},
	
	createSound: function () {
		this.sound = soundManager.createSound({
			id: 'aSound'+this.cursor,
			url: this.current.Attachment.Filename,
			volume: 50,
			onfinish: this.next.bind(this)
		});
	},

	play: function () {
		if (! this.started) {
			this.start(true);
		} else if (this.sound && ! this.playing) {
			this.sound.play();
			this.playing = true;
		}
	},
	
	stop: function () {
		if (this.sound && this.playing) {
			this.sound.stop();
			this.playing = false;
		}
	}
});
