/**
 * Plugin Manager - loads plugin scripts from this.config.html5plugins using this.config.pluginDir
 * NOTE: Requires jquery.include.js from http://meta20.net/.include_script_inclusion_jQuery_plugin
 *
 * @author Joey Line <joey.line@skiclubz.com>
 */
(function($) {
	zPlayer.prototype.pluginManager = function(callback) {
		var player = this;
		// FIXME: I don't really like putting these variables here, because it makes looping
		//	through the plugins more complicated.
		this.plugins = {
			_callback: callback,
			_interval: undefined
		};
		
		// no plugins defined
		if(!this.config.html5plugins) {
			this.plugins._callback();
			return false;
		}
		
		// plugin directory not defined
		if(!this.config.pluginDir) {
			zPlayer.utils.log('zPlayer ERROR: pluginDir not defined!');
			this.plugins._callback();
			return false;
		}
		
		// parse the plugin names
		var pluginNames = this.config.html5plugins.split(/,/).map(function(value) {
			return zPlayer.utils.trim(value);
		});
		
		// loop over all the plugins
		for(var i=0;i<pluginNames.length;i++) {
			var name = pluginNames[i],
				url = this.config.pluginDir + name + '.js';
			// store this plugin so we can check if it loaded
			this.plugins[name] = {url: url};
			
			// load the plugin
			// this.pluginManager.include(player, name, url);
		}
		
		// set an interval to check if the plugins are loaded
		// FIXME: If a plugin is defined but it never loads, this will run repeatedly...
		//	plus the callback will never fire.
		this.plugins._interval = setInterval(this.pluginManager.createInterval(this), 100);
	};
	
	// load the plugin via $.include [see jquery.include.js]
	zPlayer.prototype.pluginManager.include = function(player, name, url) {
		$.include(url, function() {
			player.plugins[name].loaded = true;
		});
	};
	
	// returns a function to be used with setInterval to check if the plugins have been loaded
	zPlayer.prototype.pluginManager.createInterval = function(player) {
		return function() {
			// all plugins loaded! now let's init them...
			for(var i in player.plugins) {
				// FIXME: See note above
				if(i.substr(0,1)==='_')
					continue;
				
				player[i]();
			}
			
			// clear the interval - no more plugin loaded checking needed
			clearInterval(player.plugins._interval);
			
			// call the callback
			player.plugins._callback(player);
		}
	};
})(jQuery);

