

var Loader = {};

Loader.init = function(){
	this.root = {};
	this.header = document.getElementsByTagName("head")[0];
}




Loader.root = {};


Loader.getPath = function(n,v,t){
	return t + '/' + n + '.' + v + '.' + t;
}

Loader.isReady = function(namespace) {
	return this.check(namespace,'ready');
}

Loader.setReady = function(namespace){
	this.root[namespace].ready = true;
}

Loader.loadModule = function(namespace,version,obj){
	this.modObj = obj;
	this.v = version;
	Loader.addToHeader(namespace,version,'css');
	Loader.addToHeader(namespace,version,'js',this);
	
}

Loader.readyJS = function(){
	Loader.loadHTML(this.ns,this.v,this);
}

Loader.readyHTML = function(){
	this.setReady(this.ns);
	this.modObj.readyMod();
}
	

Loader.loadHTML = function(namespace,version,obj){
	this.obj = obj;
	var type = 'html';
	
	var path = this.getPath(namespace,version,type);
	
	if (this.check(namespace,type)){
		if (this.obj) this.obj.readyHTML();
		return;
	}
	
	var c = new AjaxConnection(path);
	c.connect(this,'loadCallback');
}

Loader.parseHTML = function(html){
	this.root[this.ns].html = document.createElement('div');
	this.root[this.ns].html.innerHTML = html;
	
}

Loader.check = function(namespace,type){
	this.ns = namespace;
	
	if (!this.root[this.ns]){
		this.root[this.ns] = {};
		return false;
	}
	
	if (!this.root[this.ns][type]){
		return false;
	}
		
	return true;

}

Loader.loadCallback = function(data){
		this.parseHTML(data);
		if (this.obj) this.obj.readyHTML();
}

Loader.addToHeader = function(namespace, version, type, obj){
 if (this.check(namespace,type)){
	alert("allready have: " + this.getPath(namespace,version,type));
	return;
 }

 var path = this.getPath(namespace,version,type);
 if (type=="js"){ //if filename is a external JavaScript file
  var script=document.createElement('script')
  script.setAttribute("type","text/javascript")
  script.setAttribute("src", path)
  var done = false;
	script.onload = script.onreadystatechange = function() {
		if ( !done && (!this.readyState ||
            this.readyState === "loaded" || this.readyState === "complete") ) {
			done = true;
			obj.readyJS();
     
		}
	};
	
	
	
 }
 else if (type=="css"){ //if filename is an external CSS file
  var script=document.createElement("link")
  script.setAttribute("rel", "stylesheet")
  script.setAttribute("type", "text/css")
  script.setAttribute("href", path)
 }
 
  this.header.appendChild(script)
  this.root[this.ns][type] = true;
  
}

Loader.getNode = function(id){
	
	for (var i = 0; i < this.root[this.ns].html.childNodes.length; i++){
		if (this.root[this.ns].html.childNodes[i].id == id){
				return this.root[this.ns].html.childNodes[i].cloneNode(true);
		}
	}

	return null; // throw exception

}




