// Global Variables
var jpPlayer, jpPlayTime, jpTotalTime, jpIsPlaying, jpTitle, jpAlbum, player, messageTimerID, divPlaylist;
var currentTrack = 0;

var playingTxt = "Playing";
var stoppedTxt = "Stopped";
var fromTxt = "from";
var nowPlayingTxt = "Now playing";

var remoteUpdate = "/includes/updatePlayCount.php";

/***********
 * Cookies *
 ***********/
var CookieCutter = function(options) {};
CookieCutter.prototype = {
	get: function(key) {
		var start = 0, end = 0;
		if (key && (document.cookie.length > 0)) {
			start = document.cookie.indexOf(key + '=');
			if (start != -1) {
				start = start + key.length+1; 
				end = document.cookie.indexOf(';', start);
				if (end == -1) {
					end = document.cookie.length;
				}
				return unescape(document.cookie.substring(start, end));
			} 
		}
		return '';
	},
	set: function(key, value, expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = key + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString() + ';path=/;');
	},
	check: function(key) {
		var cookie = this.get(key);
		return (cookie && ((cookie != null) && (cookie != ''))) ? true : false;
	}
	
};
// coookie handler
var cookie = new CookieCutter();
var cookieExpireDays = 90;
var config = {
	paused: false,
	trackFile: '',
	elapsed: 0,
	volume: 80,
	cookieCrumb: {
		paused		: 'jpPAU',
		trackFile	: 'jpTRF',
		elapsed		: 'jpTEL',
		volume		: 'jpVOL'
	}
};
var paused = (cookie.get(config.cookieCrumb.paused) == 1) ? true : config.paused;
var trackFile = cookie.get(config.cookieCrumb.trackFile) || config.trackFile;
var elapsed = cookie.get(config.cookieCrumb.elapsed) || config.elapsed;
var volume = cookie.get(config.cookieCrumb.volume) || config.volume;

jQuery(document).ready(function($) {
	/****************
	 * Audio Player *
	 ****************/
	jpPlayer = $('#jquery_jplayer');
	jpPlayTime = $("#jplayer_play_time");
	jpTotalTime = $("#jplayer_total_time");
	jpIsPlaying = $('#info .isPlaying');
	jpTitle = $('#info .title');
	jpAlbum = $('#info .album');	

	jpPlayer.jPlayer({
		swfPath: '/js/jplayer',
		volume: volume,
		ready: function() {
			if(trackFile.length > 0){
				var isPaused = paused;
				var timeElapsed = elapsed;
				playListConfig(trackFile);
				if(!isPaused)
					jpPlayer.jPlayer("playHeadTime", timeElapsed);
			} else
				playListInit(!paused);
		}
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));	
		
		paused = !this.element.jPlayer("getData", "diag.isPlaying");
		jpIsPlaying.text((!paused ? playingTxt : stoppedTxt)+": ");
		$('.playlist_current').toggleClass("pause", !paused);
		if(paused)
			hideMessages();
		
		elapsed = this.element.jPlayer("getData", "diag.playedTime");
		
		cookie.set(config.cookieCrumb.paused, (paused ? 1 : 0), cookieExpireDays);		
		cookie.set(config.cookieCrumb.elapsed, elapsed, cookieExpireDays);
	})
	.jPlayer("onSoundComplete", function() {
		playListNext();
	});

	$("a.player_track").each(function() {		
		var file = $(this).attr('href');
		var title = $(this).attr('title'); // Used only if the file is not in the playlist
		var album = $(this).attr('alt'); // Used only if the file is not in the playlist
		var i = getTrackIndex(file, title, album);

		$(this).attr('id', "tracks_item_"+i);
		$(this).attr('href', "#");

		$("#tracks_item_"+i).data( "index", i ).click( function() {
			var index = $(this).data("index");
			trackClicked(index)
			$(this).blur();
			return false;
		});
	});
	$("#tracks_item_"+currentTrack).addClass("playlist_current");
	
	$("#next").click(function() { playListNext(); }); // Listen for Next Track button click	
	$("#previous").click(function() { playListPrev(); }); // Listen for Previous Track button click
	$("#playlist").click(function() { showPlaylist(); }); // Listen for Playlist button click
	$("#jplayer_volume_bar, #jplayer_volume_bar_value").click(function() { // Listen for Volume Bar button click
		volume = jpPlayer.jPlayer("getData", "volume");
		cookie.set(config.cookieCrumb.volume, volume, cookieExpireDays);	
	});
	$("#lyrics").click(function() { // Listen for Lyrics button click
		$.prettyPhoto.open('/includes/letraTema.php?id='+playList[currentTrack].id+'&iframe=true&width=50%&height=90%');
	});

	$(window).resize(function () { adjustPlaylist(); }); //Each time the viewport is adjusted/resized, execute the function
	$('#content').click(function() { hidePlaylist(); }); //Click event outside of playlist

	/*************
	 * Functions *
	 *************/
	function playListInit(autoplay) {
		if(autoplay)
			playListChange( currentTrack );
		else
			playListConfig( currentTrack );
	}

	function getTrackIndex(file, title, album){
		var track = -1;
		var i = 0;
		for (i=0; i < playList.length; i++) {
			if (playList[i].file === file) {
				track = i;
				break;
			}
		}
		if (track === -1) { // Add the file to the playlist
			var info = [];
			info.title = title;
			info.album = album;
			info.file = file;
			playList.push(info);
			track = (playList.length - 1);
		}
		return track;
	}

	function playListConfig(track, title, album) {
		var oldTrack = currentTrack;
		if (typeof track === 'number')			
			currentTrack = track;
		else
			currentTrack = getTrackIndex(track, title, album);
		
		$("#tracks_item_"+oldTrack).removeClass("playlist_current");
		$("#tracks_item_"+currentTrack).addClass("playlist_current");
		
		$("#playlist_item_"+oldTrack).removeClass("playlist_current").parent().removeClass("playlist_current");
		$("#playlist_item_"+currentTrack).addClass("playlist_current").parent().addClass("playlist_current");
		
		jpPlayer.jPlayer("setFile", playList[currentTrack].file);
		
		trackFile = playList[currentTrack].file;
		cookie.set(config.cookieCrumb.trackFile, trackFile, cookieExpireDays);
		
		jpTitle.text(playList[currentTrack].title);
		$('#info .from').text(fromTxt);
		jpAlbum.text(playList[currentTrack].album);
		
		$("#lyrics").parent().css({ 'display' : ((playList[currentTrack].lyrics) ? '' : 'none') });
		
		scrollToCurrentTrack();		
	}

	// Change current song
	function playListChange(track, title, album) {
		playListConfig(track, title, album);
		
		jpPlayer.jPlayer("play");
		
		showMessage('<small>'+nowPlayingTxt+':</small> <strong><em>"' + playList[currentTrack].title + '"</em></strong>');
		
		if(remoteUpdate!=null)
			$.post(remoteUpdate, { "id": playList[currentTrack].id });
	}
	
	// Play next track. If already on last track, start back at the begining
	function playListNext() {
		var index = (currentTrack + 1 < playList.length) ? currentTrack + 1 : 0;
		playListChange(index);
	}
	
	// Play previous track. If already on first track, start back at the end
	function playListPrev() {
		var index = (currentTrack - 1 >= 0) ? currentTrack - 1 : playList.length-1;
		playListChange(index);
	}
	
	/*********************
	 * Message functions *
	 *********************/
	// Show message in bottom-right hand screen
	function showMessage(message) {
		var messageBox = $('#message');
		
		if (messageBox.length > 0) {
			clearInterval(messageTimerID);
			messageBox.html(message);
		} else {
			$('<div id="message" style="display: none;">' + message + '</div>').appendTo('#player .wrapper');
			$('#message').show(500);
		}

		messageTimerID = setInterval(hideMessages, 5000);
	}
	
	function hideMessages() {
		clearInterval(messageTimerID);
		$('#message').hide(500, deleteMessages);
	}
	
	function deleteMessages() {
		$('#message').remove();
	}
	
	/**********************
	 * Playlist functions *
	 **********************/
	function showPlaylist() {
		var playlistBox = $('#playlist_panel');
		
		if (playlistBox.length > 0)
			hidePlaylist();
		else {
			displayPlayList();
			adjustPlaylist();	
			$('#playlist_panel').show(500, scrollToCurrentTrack);
			$('#playlist').toggleClass("down", true);
		}
	}
	
	function displayPlayList() {
		$('<div id="playlist_panel" style="display: none;"><ul></ul></div>').appendTo('#player .wrapper');
		
		var playlistUL = $("#playlist_panel ul");
		var i = 0;
		var album = '';
		for (i=0; i < playList.length; i++) {
			if(playList[i].album != album){
				album = playList[i].album;
				if(i!=0)
					playlistUL.append('<br>');
				playlistUL.append('<h3>' + album + '</h3>');
			}			
			
			var listItem = "<li><a href='#' id='playlist_item_"+i+"' tabindex='1'>"+ playList[i].title +"</a></li>";
			playlistUL.append(listItem);
			$("#playlist_item_"+i).data( "index", i ).click( function() {
				var index = $(this).data("index");
				trackClicked(index);
				$(this).blur();
				return false;
			});
		}
		
		$("#playlist_item_"+currentTrack).addClass("playlist_current").parent().addClass("playlist_current");		
	}
	
	function trackClicked(index){
		if (currentTrack != index)
			playListChange( index );
		else if(paused)
			jpPlayer.jPlayer("play");
		else
			jpPlayer.jPlayer("pause");
	}

	function adjustPlaylist() {
		$('#playlist_panel').css({ 'width' : ($(window).width()-40) });
	}
	
	function hidePlaylist() {
		var playlistBox = $('#playlist_panel');
		if (playlistBox.length > 0) {
			$('#playlist_panel').hide(500, deletePlaylist);
			$('#playlist').toggleClass("down", false);
		}
	}
	
	function deletePlaylist() {
		$('#playlist_panel').remove();
	}
	
	function scrollToCurrentTrack(){
		try {
			$('#playlist_panel').scrollTo('.playlist_current', 800, {offset:-100});
		} catch(e){
			//Need to include jquery.scrollTo-min.js
		}
	}
});