/**
 * This plugin allows you to specify a comma separated string or an array
 * of plugins to load. The tags that these plugins should apply to will be
 * found by whether or not they have a data-{pluginName} attribute. Passing
 * a object in the data-{pluginName} attribute will translate to the options
 * for the plugin. 
 *
 * In the initial call, the second parameter can be a hash of plugin names for
 * keys and functions for their values. Those function will be called instead
 * of the plugin name on the selected element. This allows you to customize the
 * plugin instantiation on a per plugin basis but still globally for all tags.
 *
 * Example: 
 * $(document).pluginLoader('plugin1, plugin2', {
 *     'plugin1': function(el, opt) {
 *         el.plugin1(opt);
 *         el.differentPluginInitialization();
 *     }
 * });
 *
 */
(function($) {
var loader = {};
var methods = {
	init: function($this, plugins) {
		return $this.each(function(index) {
			var self = $(this);
			var attrs = self[0].attributes;
			for (var i = 0; i < attrs.length; i++) {
				var attrName = attrs[i].nodeName;
				var dataKey = attrName.replace(/data-/, '');
				var plugin = methods.find(dataKey, plugins);
				// Call continue early if attr isn't a data- attr
				if (!attrName.match(/data-(.)*/) || !plugin) {
					continue;
				}
				// Strip data- off of the attrName
				if (dataKey !== plugin) {
					var data = self.data(dataKey);
					self.removeData(dataKey);
					self.data('data-' + plugin, data);
				}
				// Check if a callback for the plugin has been created
				var data = self.data('data-' + plugin);
				if (loader[plugin]) {
					loader[plugin](self, data);
				} else {
					// Check if the plugin exists
					if (self[plugin]) {
						self[plugin](data);
					}
				}
			}
		});
	},
	find: function(name, plugins) {
		name = String(name).toLowerCase();
		for (var i in plugins) {
			var plugin = String(plugins[i]).toLowerCase();
			if (plugin == name) {
				return plugins[i];
			}
		}
		return false;
	}
};
$.fn.pluginLoader = function(plugins, options) {
	if (!plugins) {
		plugins = pluginKeys;
	}
	else if (typeof plugins === 'string') {
		plugins = plugins.split(',').map(function(el) { return el.trim(); });
	} else if (plugins instanceof Array) {
		plugins = $.map(plugins, function(el) { return $.trim(el); });
	}
	loader = $.extend(loader, options);
	var find = $.map(plugins, function(el) { return '[data-'+el+']'; }).join(', ');
	methods.init($(find, this), plugins);
	return this;
}

var pluginKeys = ['moreLoader', 'facebookPrepopulateForm', 'submitButtonIndicator', 'googleMap', 'facebookInvite', 'foursquareConnect', 'twitterConnect', 'limitTextarea']; 

$(document).ready(function() {
	$(document).pluginLoader(pluginKeys);
});

})(jQuery);

