/**
 * Some init procs
 * Author 2007-2008 Oleg V. Lubarsky aka Dr.LOV
 * Copyright (c) 2008 CREATIVE ZONE Studio (http://www.cz-site.com/)
 *
 * usage:
 *   include(PATH_ROOT+"framework/js/md5.js");
 *   include("js#kernel.js.php");
 */


(function() { 
	var arrLoaded = [];
	var arrToLoad = [];
	var ismodal = false;
	
	function getExt(name) {
		var dot = name.lastIndexOf("."); 
		if (dot<0) return ""; 
		return name.substr(dot+1,name.length)
	}

	window.include = function (name,modal) {
		var url, type, arr;
		if (ismodal) {
			arrToLoad.push({name:name,modal:modal});
			return;
		}
		arr = name.split("#");
		if (arr.length==1) {
			url = arr[0];
			type = getExt(url);
		} else {
			url = arr[1];
			type = arr[0];
		}
		switch (type) {
			case "js":
				include_script(url,modal);
				break;
			case "css":
				include_css(url);
				break;
			default:
		}
		arrLoaded.push(name);
	};

	window.include_script = function (url,modal) {
		if (modal) ismodal = true;
		var head = document.getElementsByTagName("head")[0];
		var elem = document.createElement("script");
		elem.setAttribute('type', "text/javascript");
		elem.setAttribute('src', url);
		var done = false;
		if (modal) {
			elem.onload = elem.onreadystatechange = function(){
				if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
					done = true;
					ismodal = false;
					if (arrToLoad.length>0) {
						do {
							var param = arrToLoad.shift();
							include(param.name,param.modal)
						} while (arrToLoad.length>0 && param.modal!=true);
					}
				}
			};
		}
		head.appendChild(elem);
	};

	window.include_css = function (url) {
		var head = document.getElementsByTagName("head")[0];
		var elem = document.createElement('link');
		elem.setAttribute('href', url);
		elem.setAttribute('rel', 'stylesheet');
		elem.setAttribute('type', 'text/css');
		head.appendChild(elem);
	};
	
	var single = "framework/js/init.js";
	var elems = document.getElementsByTagName('script');
	for (var i=0; i<elems.length; i++) {
		var src = elems[i].src;
		if (src.indexOf(single)>0) {
			window.PATH_ROOT = src.substring(0, src.lastIndexOf(single));
			break;
		}
	}
	
	// todo del or not ???
	if (document.location.protocol == "file:") {
		window.PATH_BASE = decodeURIComponent(document.location.pathname.substr(1)).replace(/\\/g, "/");
		window.PATH_BASEFULL = window.PATH_BASE = "file:///" + window.PATH_BASE.substring(0,window.PATH_BASE.lastIndexOf('/')+1) ;
	} else {
		window.PATH_BASE = document.location.pathname.substring(0,document.location.pathname.lastIndexOf("/")+1) ;
		window.PATH_BASEFULL = document.location.protocol + "//" + document.location.host + window.PATH_BASE ;
	}
	
})();