// Programmed by joep@joep-i.nl
// Feel free to use and modify this.

function Player(sound) {
    this.playing = false;
    this.sound = sound;
    this.frequency = 200;
    this.song = '';
    this.id = '';
    this.release = '';
    this.timeleft = 5;
    this.position = 0;
    this.registerCallback();      
}

Player.prototype.registerCallback = function() {
   setInterval(this.onTimerEvent.bind(this), this.frequency);
}

Player.prototype.play = function(song,id,iid) {
	jQuery.get('listen.php', { iid : iid });
    if (this.playing) {
        if (this.song == song) {
            this.hideslider();
            this.onSoundComplete();
        } else {
            jQuery("#"+this.id).removeClass('playing'); 
			try {
			jQuery('.'+this.release).removeClass('playing');
			} catch(e) { }
            this.hideslider();
            this.onSoundComplete();

            this.id = id;
            this.currentid = id;
			this.tracktitle = jQuery('#' + this.id + " a").attr('title'); 
			try {
				this.release = jQuery('#' + this.id + " a").attr('rel'); 
			} catch (err) { }
			this.pagetitle = document.title;
			this.lastposition = 0;
            this.song = song;
            soundManager.createSound({id: this.id, url: this.song, autoPlay : true});
			this.sound = soundManager.getSoundById(this.id);
            this.playing = true;
            this.showslider();
        }
    } else {
        this.id = id;
		this.currentid = id;
		this.tracktitle = jQuery('#' + this.id + " a").attr('title'); 
		try {
			this.release = jQuery('#' + this.id + " a").attr('rel'); 
		} catch (err) { }
		this.pagetitle = document.title;
        this.song = song;
        soundManager.createSound({id: this.id, url: this.song, autoPlay : true});
        this.sound = soundManager.getSoundById(this.id);

        this.playing = true;
        this.showslider();
    }
    return false;
}

Player.prototype.onTimerEvent = function() {
    if(this.playing) {
        this.position = document.player.sound.position;
        this.duration = document.player.sound.duration;
		this.loading = (document.player.sound.bytesLoaded < document.player.sound.bytesTotal);

        var progress = this.position/this.duration;
        this.timeleft = this.duration - this.position;

        var rest = (this.timeleft % 60000);
        var seconds = Math.round(rest/1000);
        var minutes = Math.round((this.timeleft - rest) / 60000);
        if (seconds == 60) {
            seconds = 0;
            minutes = minutes + 1;
        }
        if (!(isNaN(minutes)) && !(isNaN(seconds))) {
			if (seconds < 0) {
            	jQuery('#slider a.ui-slider-handle').html(sprintf("<span class='time'>&nbsp;</span>")); 
			} else {
            	jQuery('#slider a.ui-slider-handle').html(sprintf("<span class='time'>%d:%02d</span>",minutes,seconds)); 
			}
			if (seconds > 0) {
				document.title = sprintf("[%d:%02d] - %s", minutes, seconds, this.tracktitle);
			}
			if ((!this.loading) && (this.position > 1000)) {
				if ((this.timeleft < 1000) && (this.lastposition == this.position)) {
					this.onSoundComplete();
					this.skipNext();
				}
			}
        }
        if (isNaN(progress)) {
            progress = 0
        }
        try {
            jQuery('#slider').slider('option', 'max',(this.duration * 1.05));
            jQuery('#slider').slider('value',this.position);
        } catch (e) { }
		this.lastposition = this.position
    }
}

Player.prototype.onSoundComplete = function() {
    this.hideslider();
    this.playing = false;
    soundManager.destroySound(this.id);
    jQuery('#' + this.id).removeClass('playing'); 
	try {
		jQuery('.'+this.release).removeClass('playing');
	} catch(e) { }
	document.title = this.pagetitle;
    this.sound = null;
    this.song = '';
    this.id = '';
}

Player.prototype.hideslider = function() {
    jQuery('#slider').hide();
    jQuery('#slider').remove();
}

Player.prototype.showslider = function() {
    jQuery('#'+this.id).addClass('playing'); 
	try {
		jQuery('.'+this.release).addClass('playing');
	} catch(e) {}
    jQuery('#'+this.id).append("<div id='slider'></div>");
    jQuery('#slider').slider({
        animate : false,
        start : function(event,ui) {
            document.player.playing = false;
        },
        slide : function(event,ui) { 
            var duration = document.player.sound.duration;
            var position = jQuery('#slider').slider('value');
            var timeleft = (duration - position);
            var rest = (timeleft % 60000);
            var seconds = Math.round(rest/1000);
            var minutes = Math.round((timeleft - rest) / 60000);
            if (!(isNaN(minutes)) && !(isNaN(seconds))) {
                jQuery('#slider a.ui-slider-handle').html(sprintf("<span class='time'>%d:%02d</span>",minutes,seconds)); 
            }
            document.player.playing = false;
        },
        stop : function(event,ui) {
            var newpos = jQuery('#slider').slider('value');
            soundManager.setPosition(document.player.id,newpos);
            document.player.playing = true;
        }
    });
}

Player.prototype.skipNext = function() {
	var current = jQuery('#'+this.currentid)
    var index = current.parent().children().index(current)
    if ((index + 1) < current.parent().children().length) {
		var nextid = jQuery(current.parent().children()[index+1]).attr('id')
        jQuery('#' + nextid + ' a').click()
	}
}

