var Player = function() {
	var nifty = new NiftyPlayer("player"),
		playlist = [],
		currentTrackNum = -1,
		keepPlaying = false,
		nextInterval = null;
		
	this.play = function(file) {
		nifty.load(file);
		nifty.play();
	}
	
	this.autopause = false;
	
	this.stop = function() {
		clearInterval(nextInterval);
		keepPlaying = false;
		nifty.stop();
	}
	
	this.pause = function() {
		nifty.pause();
	}
	
	this.setAutopause = function () {
		this.autopause = true;
		this.pause();
	}

	this.removeAutopause = function () {
		if (this.autopause) {
			this.autopause = false;
			nifty.play();
		}
	}
	
	this.setPlaylist = function(newPlaylist) {
		playlist = newPlaylist;
		if (playlist.length) {
			nifty.load(playlist[0]);
		}
	}
	
	this.playPlaylist = function(startTrack, newPlaylist) {
		//console.log("playPlayList with track # ", startTrack);

		var t = this;

		if (!newPlaylist.length) {
			return false;
		}
		
		currentTrackNum = startTrack - 1;
		this.stop();
		keepPlaying = true;
		this.setPlaylist(newPlaylist);
		nextInterval = setInterval(function(){t.next.call(t)}, 100);
	}
	
	this.getPlayingState = function () {
		return nifty.getPlayingState();
	}
	
	this.next = function(){
		var state = nifty.getState(),
			playState = nifty.getPlayingState();
		
		if (["playing", "paused"].contains(playState)) {
			return;
		}
		
		if (["finished", "empty", "stopped"].contains(state) && keepPlaying) {
			this.play(playlist[++currentTrackNum % playlist.length]);
		}
		
		if (["error"].contains(state)) {
			this.stop();
		}
		
	}
	
	this.playNext = function(){
		this.play(playlist[++currentTrackNum % playlist.length]);
	}
	
	this.playPrev = function() {
		this.play(playlist[--currentTrackNum % playlist.length]);
	}
	
	this.playToggle = function() {
		var t = this;
		nifty.playToggle();
		nextInterval = setInterval(function(){t.next.call(t)}, 100);
	}
	
	this.setVolume = function(x) {
		nifty.setVolume(x);
	}
};

