var mu = {};

/**
 * Require a javascript file. If file is not already in the head will write it and return true. Otherwise will return false
 *
 * @param string filename
 *
 * @returns bool
 */
mu.require = function require( filename )
{
	var require_uri = mu.parseUri(filename);
	var current_js = document.getElementsByTagName('script');
	var check_host = true;
	// The required file is a relative link.
	if( require_uri.host == '' || require_uri.host == filename )
	{
		check_host = false;
	}

	// Go through all the js and make sure the file has not already been included.
	for( var i=0; current_js.length > i; i++ )
	{
		if( current_js[i].src != "" )
		{
			var uri = mu.parseUri(current_js[i].src);

			if( uri.path == require_uri.path )
			{
				// The paths match
				if( check_host )
				{
					var current_page = mu.parseUri(location.href);

					// We where passed an absolute link make sure the hosts match aswell.
					if( require_uri.host == current_page.host )
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
		}
	}

	var fileref=document.createElement('script')
	fileref.setAttribute("type","text/javascript")
	fileref.setAttribute("src", filename)

	if( typeof fileref!="undefined" )
	{
		document.getElementsByTagName("head")[0].appendChild(fileref)
		return true;
	}

	return false;
}

/**
 * Splits a string into its uri components
 *
 * @param string str
 *
 * @returns obj
 */
mu.parseUri =  function parseUri( str )
{
	var	o   = mu.parseUri.options;
	var	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
	var	uri = {};
	var	i   = 14;

	while( i-- ) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function( $0, $1, $2 )
	{
		if( $1 )
		{
			uri[o.q.name][$1] = $2;
		}
	});

	return uri;
};

mu.parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
