// Copyright (C) 2007-2008 Stephane Lavergne <http://www.imars.com/>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

// Global essentials
// min(a,b)
if (!window['min']) {
	window.min = function (a, b) {
		return ((a<b) ? a : b);
	};
};
// max(a,b)
if (!window['max']) {
	window.max = function (a, b) {
		return ((a>b) ? a : b);
	};
};

// Global namespace
var imars = {
	base: document.getElementsByTagName ? (document.getElementsByTagName("base")[0] ? document.getElementsByTagName("base")[0].href : '') : null,
	head: document.getElementsByTagName ? document.getElementsByTagName('head')[0] : null,
	jsbase: '/lib/',
	includes: [],
	loaded: false,

	// Precautions in case some people don't use imars-require but still invoke it.
	require: function(s) { return false; },

	// Analogue to Java's namespace import.
	// Reserved word in JS, so I used another name. Imports to the global
	// namespace unless a specific context is specified.
	use: function(base, that) {
		if (typeof(base) == 'object') {
			if (!that) {
				that = window;
			};
			for (var i in base) {
				that[i] = base[i];
			};
		};
	},

	// Add a function call with arguments array to window.onload chain.
	// Run immediately if load event already fired.
	onLoad: function (hook, args) {
		var ready = document.readyState;
		if (imars.loaded || (ready && (ready == 4 || ready == 'complete' || ready == 'loaded'))) {
			hook.apply(null, args);
		} else {
			var oldonload = window.onload;
			if (typeof window.onload != 'function') {
				if (args && hook.apply) {
					window.onload = function() { hook.apply(null, args); };
				} else {
					window.onload = function() { hook(); };
				};
			} else {
				if (args && hook.apply) {
					window.onload = function() { oldonload(); hook.apply(null, args); };
				} else {
					window.onload = function() { oldonload(); hook(); };
				};
			};
		};
	}

};

imars.onLoad(function(){ imars.loaded = true; });
