/**
 * YTFeedReader.js - YouTube Feed Reader v2.0
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

var ytPlayerListeners = {};


var YTFeedReader = function(pId, options) {
	
	var PLAYER_SRC = 'http://www.youtube.com/apiplayer';
	
	var _pId = pId;
	
	var player = null;
	var videos = [];
	var current = '';
	
	var feed = options.feed || '';
	var width = options.width || 640;
	var height = options.height || 385;
	var videoId = options.videoId || '';
	var autoplay = options.autoplay || false;
	var playStart = options.playStart || '';
	var stateChangeCallback = options.stateChangeCallback || '';
	var youTubePlayerReadyCallback = options.youTubePlayerReadyCallback || '';
	
	
	/**
	 * Parse the feed to usable video objects
	 * 
	 * @param {Object} response
	 */	
	var parseFeed = function(response) {
		var result = WS.Util.parseJSON(response);
		var entries = result.feed.entry;
		
		for(var i = 0; i < entries.length; i++) {
			videos.push({
				id: entries[i].id.$t.split('/').last(),
				title: entries[i].title.$t
			});
		}
		
		if(!videoId) {
			playObject(videos.first());
		}
		
		if(playerReady) {
			playerReady(player);
		}
	};
	
	/**
	 * onYoutubePlayerReady event handler
	 * 
	 * @param {String} playerId The YouTube player's ID
	 */
	var youTubePlayerReady = function(playerId) {
		player = $(playerId);
		
		ytPlayerListeners[playerId] = stateChange;
		player.addEventListener('onStateChange', 'ytPlayerListeners.' + playerId);
		
		if(videoId) {
			if(autoplay) {
				player.loadVideoById(videoId);
			}
			else {
				player.cueVideoById(videoId);
			}
			current = videoId;
		}
		
		if(feed) {
			WS.Ajax.request(feed, function(response) {
				parseFeed(response);
			});
		}
		
		if(youTubePlayerReadyCallback) {
			youTubePlayerReadyCallback();
		}
	};
	
	/**
	 * onStateChange event handler
	 * 
	 * Note: if a video doesn't seem to play, check the feed first!
	 *       When a user deletes a video, YouTube leaves a ghost entry
	 *       in the feed for a few hours!
	 * 
	 * @param {Number} state The YouTube player's state
	 */
	var stateChange = function(state) {
		if(state === 0 && videos.length) {
			var next = (videos.indexOf(current) == -1 || current == videos.last()) ? videos[0] : videos[videos.indexOf(current) + 1];
			playObject(next);
		}
		
		if(state == 1 && playStart) {
			playStart(player);
		}
		
		if(stateChangeCallback) {
			stateChangeCallback(state);
		}
	};
	
	/**
	 * Plays a video object
	 * 
	 * @param {Object} obj The video object to play
	 */
	var playObject = function(obj) {
		if(autoplay) {
			player.loadVideoById(obj.id);
		}
		else {
			player.cueVideoById(obj.id);
		}
		current = obj;
	};
	
	/**
	 * Initialize the player
	 */
	var initialize = function() {
		swfobject.embedSWF(PLAYER_SRC + '?enablejsapi=1&playerapiid=' + _pId,
		                   _pId, width, height, '8', null, null,
						   { allowScriptAccess: 'always', bgcolor: '#000000' }, { id: pId });
		
		onYouTubePlayerReady = youTubePlayerReady;
	}();
	
	
	/**
	 * Public API
	 */
	return {	
		play: function() {
			player.playVideo();
		},
		
		pause: function() {
			player.pauseVideo();
		},
		
		stop: function() {
			player.stopVideo();
		},
		
		clear: function() {
			player.clearVideo();
		},
		
		mute: function() {
			player.mute();
		},
		
		unMute: function() {
			player.unMute();
		},
		
		isMuted: function() {
			return player.isMuted();
		},
		
		getPlayerState: function() {
			return player.getPlayerState();
		},
		
		getDuration: function() {
			return player.getDuration();
		},
		
		getCurrentTime: function() {
			return player.getCurrentTime();
		},
		
		loadVideoById: function(videoId, startSeconds) {
			player.loadVideoById(videoId, startSeconds);
		},
		
		cueVideoById: function(videoId, startSeconds) {
			if ( player )
				player.cueVideoById(videoId, startSeconds);
		},
		
		togglePlay: function() {
			player.getPlayerState() == 1 ? this.pause() : this.play();
		},
		
		toggleMute: function() {
			player.isMuted() ? this.unMute() : this.mute();
		},
		
		getPlaylist: function() {
			return videos;
		}
	};
};
