/**
 * We should consider which js library to use
 * jQuery doesn't support classes
 * 
 * Where do we want to have the require() function?
 * - Waf.require() vs Waf.Core.require()
 */
var Waf = {
	/**
	 * @todo better name / remove
	 */
	self: null,
	
	/**
	 * Determined include path
	 */
	includePath: null,
	
	/**
	 * Loaded classes
	 */
	loaded: [],

	/**
	 * Get include path
	 */
	getIncludePath: function() {
		if(null === this.includePath) {
			var scripts = document.getElementsByTagName('script');
			for(var i = 0; i < scripts.length; i++) {
				var src = scripts[i].getAttribute('src');
				if(!src) continue;
				
				var match = src.match(/Waf\/Core\.js(\W|$)/i);
				if(match) {
					this.self = scripts[i];
					this.includePath = src.substring(0, match.index);
					break;
				}
				
				if(!this.includePath) {
					alert('Error determining waf.js include path');
				}
			}
		}
		return this.includePath;
	},
	
	/**
	 * PEAR-style preloader
	 * 
	 * @todo: better name for async
	 */
	require: function(className, async) {
		async = async ? async : false;
		if(typeof(this.loaded[className]) == 'undefined') {
			this.loaded[className] = true;
			
			var parts = className.split('.');
			var file = parts.pop() + '.js';
			var url = this.getIncludePath() + ((parts.length >= 1) ? parts.join('/') + '/' : '') + file;
	
			if(async) {
				var element = document.createElement('script');
				element.setAttribute('src', url)
				element.setAttribute('type', 'text/javascript');;
				
				this.self.parentNode.insertBefore(element, this.self.nextSibling);
			}
			else {
				new Request({
					async: false,
					evalScripts: true,
					url: url,
					method: 'GET',
					onFailure: function() {
						alert(className + ' could not be loaded');
					}
				}).send();
			}
		}
	}
};

/**
 * Required to handle asynchronous requests
 */
Waf.require('Waf.Adapter.MooTools', true);
