//Capture all links that point to the player.
new function(){
	debug("Init player");
	var queue = [];	
	var flash = null;

	//Buffer all the playlists we need to load when the Flash object
	//is ready. This type will be replaced in checkInterval when it is.
	var queuePlaylist = function(type, url, play) {
		debug("Queue item");
		queue.push([type, url, play]);
	};
	
	//Try and send queued messages to the Flash
	var flushQueue = function() {
		try {
			//Clear the buffers
			debug("Sending queue", queue.length);
			for (var i = 0; i < queue.length; i++) {
				sendPlaylist.apply(this, queue[i]);
			}			
			queue = [];
			return true;
		} catch (e) {
			debug("Error talking to flash", e, e.message);
			return false;
		}
	};

	//Send playlist info to flash
	var sendPlaylist = function(type, url, play) {
		debug("Send playlist", type, url, play);
		switch (type) {
			case 'library':
				flash.loadLibrary(url, play);
				break;
			case 'track':
				flash.loadTrack(url, play);
				break;
			case 'playlist':
			default:
				flash.loadPlaylist(url, play);
				break;
		}
	};
	
	//Add link to library
	var loadLink = function(element) {
		debug("Load link");
		var play = $(element).hasClass('queue') == false;
		var type = $(element).hasClass('library') ? 'library' : ($(element).hasClass('track') ? 'track' : 'playlist');
		queuePlaylist(type, element.href, play);
	};
	
	//Events to apply to all content
	window.PageLoader.register(function(){
		debug("Apply to ", this);
		
		//All anchors pointing to the player.
		this.find('a[rel=player]').each(function(event){
			var url = this.href;		
			$(this).click(function(event){
				event.stopImmediatePropagation();
				event.stopPropagation();
				loadLink(this);			
				return false;
			});
		});
		
		debug('Foobar');
		
		//User library links are located in the header
		this.find('link[rel=player]').each(function(event){
			debug(this.href);
			loadLink(this);
		});
	});
	
	//Expose interfaces for other modules.
	window.player = {
		loadPlaylist : queuePlaylist
	};
		
	//Set up listeners so we can talk to the Flash player.
	$(function(){
		debug("Initialising player interface");
		var collapsed = true;
		var collapsedHeight = 22;
		var expandedHeight = 380;
		var width = 984;
		
		window.swfobject.embedSWF('/flash/player.swf', 'player', width, expandedHeight, '9.0', '', {}, {wmode:'transparent'}, {});
		$('#player-container #player');
		$('#player-container').show();
		$('#player').css('height', collapsedHeight + 'px');
		
		//Start trying to talk to the Flash
		var checkInterval = window.setInterval(function() {
			flash = document.getElementById('player');
			debug(flash, flash.loadPlaylist);
			if (typeof flash.loadPlaylist != 'undefined') {
				if (flushQueue()) {
					window.clearInterval(checkInterval);
					queuePlaylist = sendPlaylist;
					window.player.loadPlaylist = sendPlaylist;			
					debug("Cleared queue");
					return;
				}
				else
				{
					flash = null;
				}
			}
		}, 500);
		
		//Set state of the player
		var setCollapsed = function(collapse) {
			var height = collapse ? collapsedHeight : expandedHeight;
			collapsed = collapse;
			debug("Setting height to " + height + " (" + (collapse ? 'collapsed' : 'expanded') + ')');

			//Set the player height to its eventual state.
			//This will be called before or after the animation depending on whether we are collapsing or expanding
			var resizePlayer = function() {
				$('#player-container #player').css('height', height + 'px');				
			};
			
			if (!collapse) {
				resizePlayer();
			}				
			
			//Animate the container.
			$('#player-container').
				animate( {height: height + 'px'}, 
					'fast', 
					null, 
					collapse ? resizePlayer : null
				);
		};
		
		//Callbacks from Flash
		window.playerState = function(state) {
			debug("State: " + state);
		};

		//Pass new page requests through the the AJAX page loader.
		window.playerNavigate = function(url) {
			debug("Navigate", url);
			PageLoader.get(url);
		};
		
		//Show player
		window.playerShow = function() {
			debug("Player show");
			setCollapsed(false);
		};

		//Collapse player
		window.playerHide = function() {
			debug("Player hide");
			setCollapsed(true);
		};
		
		//Collapse player
		window.playerAdd = function(objectId) {
			debug("Add track to playlist", objectId);
			url = '/collection/add';
			data = { 'object_id' : objectId, 'class' : 'audio', 'return' : 1 }; 
			
			//Manually add validation...
			$('input[type=hidden]').each(function(){
				data[this.name] = this.value;
			});
			
			PageLoader.post(url, data);
		};

		//Toggle player stage
		window.playerToggle = function() {
			setCollapsed(!collapsed);
		};
	});
}();
