// Create the monokro.me namespace
if (!window.me) { me = {}; if (!window.me.monokro){me.monokro = {}} }

(function(){
	var SCRIPT_BASE_DIR = 'http://monokro.me/media/scripts/';
	var INIT_SCRIPTS = [
		[
			'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
			'http://cookies.googlecode.com/svn/trunk/jquery.cookies.js'
		],
		[
			'admin',
		]
	];
	var LOADED_SCRIPTS = [];
	var LOADING_SCRIPTS = [];

	var URL_EXPRESSION = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

	var bootstrap = {
		'init': function(level)
		{
			if (INIT_SCRIPTS[level])
			{
				for (index in INIT_SCRIPTS[level])
				{
					bootstrap.insert(INIT_SCRIPTS[level][index]);
				}

				next_level_interval = setInterval(function()
				{
					if (LOADING_SCRIPTS.length < 1)
					{
						clearInterval(next_level_interval);
						bootstrap.init(level+1);
					}
				}, 1000);
			}
		},
		'insert': function(script_name, level)
		{
			if (!script_name.match(URL_EXPRESSION))
			{
				script_name = SCRIPT_BASE_DIR + script_name;
			}

			if (!script_name.match(/.+\.js/))
			{
				script_name += '.js';
			}


			if (!(script_name in LOADED_SCRIPTS) && !(script_name in LOADING_SCRIPTS))
			{
				LOADING_SCRIPTS.push(script_name);

				thisScript = document.createElement('script');
				thisScript.src = script_name;

				head_element = document.getElementsByTagName('head')[0];
				head_element.appendChild(thisScript);

				onload_func = function(script_src)
				{
					for (i in LOADING_SCRIPTS)
					{
						if (LOADING_SCRIPTS[i] == script_src)
						{
							LOADING_SCRIPTS.splice(i, 1);
						}
					}

					LOADED_SCRIPTS.push(script_src);
				}

				if (!document.all)
				{
					// Real browsers.
					thisScript.onload = function(script_src) {
						return function()
						{
							onload_func(script_src);
						}
					}(script_name);
				}
				else
				{
						// Internet Explorer makes coding much less exciting...
					thisScript.onreadystatechange = function(script_element){
						return function()
						{
							if (script_element.readyState == 'loaded')
							{
								onload_func(script_element.src);
							}
						}
					}(thisScript);
						// See? Horrible browsers suck.
				}

				return thisScript;
			}
		}
	};

	init_method = function() { bootstrap.init(0); }

		/**
		 * This safely adds an item for "onload"
		 **/
	if (typeof window.onload != 'function')
	{
		window.onload = init_method;
	}
	else
	{
		current_onload = window.onload;

		window.onload = function()
		{
			if (current_onload)
			{
				current_onload();
			}

			init_method();
		}
	}

	window.me.monokro.bootstrap = bootstrap;
})();

