(function($){
	$.fn.mpWToggle = function(opts){
		var defaults = {
			minWidth: 0,
			narrowData: '',
			wideData: '',
			dataImportType: 'ajax',
			listen: true,
			defaultKey: ''
		};
		var config = $.extend(defaults, opts);
		var cache = {
			wide: '',
			narrow: '',
			current: config.defaultKey,
			scripts: []
		};
		var update = function(jObj)
		{
			var w = $(window).width();
			var isRetina = false;
			if (typeof window.devicePixelRatio != 'undefined')
			{
				if (window.devicePixelRatio >= 2) isRetina = true;
			}
			if (w < config.minWidth || isRetina)
			{
				var dType = 'narrow';
				var data = config.narrowData;
			} else {
				var dType = 'wide';
				var data = config.wideData;
			}
			if (dType != cache.current)
			{
				cache.current = dType;
				if (config.dataImportType == 'ajax')
				{
					if (cache[dType]) $(jObj).html(cache[dType]);
					else {
						$.get(data, function(response){
							cache[dType] = response;
							$(jObj).html(response);
						});
					}
				} else if (config.dataImportType == 'script') {
					var c = cache.scripts.length;
					var found = false;
					for (var x=0; x<c; x++)
					{
						if (cache.scripts[x] == data)
						{ found = true; break; }
					}
					if (!found)
					{
						$(jObj)
							.attr('src', data)
							.appendTo($('head'));
						cache.scripts.push(data);
					}
				} else if (config.dataImportType == 'css') {
					$(jObj).attr('href', data);
				} else if (config.dataImportType == 'html') {
					$(jObj).html(data);
				}
			}
		};
		return this.each(function(){
			update(this);
			if (config.listen)
			{
				var jObj = this;
				$(window).resize(function(){
					update(jObj);
				});
			}
		});
	};
	$.extend({
		mpwt: {
			toggleScript: function(opts)
			{
				var results = $('<script></script>').mpWToggle(opts);
				return results;
			}
		}
	});
})(jQuery);
