window.importFile = function (file) {
	var localizacao = location.href+" ";
	var posInterroga = localizacao.lastIndexOf("?");
	var posFim = localizacao.length;
	var parametros = (posInterroga!=-1)?localizacao.substring(posInterroga,posFim):'';
	var localizacao = (posInterroga!=-1)?localizacao.substring(0,posInterroga+1):localizacao;
	var posBarra = localizacao.lastIndexOf("/");
	var dirRef = location.href.substring(0,posBarra+1);
	if(file.indexOf("http://")==-1)
		file = dirRef+file+parametros;
	
	this.xmlhttp = null;
	this.dirRef = dirRef;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try { this.xmlhttp = new XMLHttpRequest(); }
		catch(ee) {
			try{ this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(e) {
				try{ this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch(E) { this.xmlhttp = false; }
	} } };

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};
	
	this.encVar = function(name, value, returnvars) {
		if (true == returnvars)
			return Array(escape(name), escape(value));
		else
			this.vars[escape(name)] = Array(escape(value), true);
	}
	
	this.processURLString = function(string, encode) {
		encoded = escape(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode)
				this.encVar(urlVars[0], urlVars[1]);
			else
				this.setVar(urlVars[0], urlVars[1]);
		}
	}
	
	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}
	
	this.runResponse = function() {	eval(this.response); }
	// Encontrar os arquivos JavasScript importados no arquivo aberto
	this.findAndImportJs = function () {
		var posIni = 0;
		var code = this.response;
		code = code.replace(/<SCRIPT/g,'<script');
		code = code.replace(/<\/SCRIPT>/g,'</script>');
		code = code.replace(/SRC=/g,'src=');
		code = code.replace(/TYPE=/g,'type=');
		code = code.replace(/LANGUAGE=/g,'language=');
		while(code.indexOf('<script')!=-1) {
			code = code.substr(code.indexOf('<script')+('<script').length);
			// SRC
			posSrc = code.indexOf('src=');
			src = code.substr(posSrc+('src=').length);
			src = src.substr(0,src.indexOf(" "));
			src = src.replace(/"/g,'');
			window.importJS(src);
		}		
	}
	// Encontrar os arquivos CSS importados no arquivo aberto
	this.findAndImportCss = function () {
		var getheadTag = document.getElementsByTagName('head')[0];
		var tagLink = document.getElementsByTagName('link');
		for(i=0;i<tagLink.length; i++){
			if(tagLink[i].imported)
				getheadTag.removeChild(tagLink[i]);
		}
		
		var posIni = 0;
		var code = this.response;
		code = code.replace(/<LINK/g,'<link');
		code = code.replace(/<\/LINK>/g,'</link>');
		code = code.replace(/HREF=/g,'href=');
		code = code.replace(/REL=/g,'rel=');
		code = code.replace(/TYPE=/g,'type=');
		while(code.indexOf('<link')!=-1) {
			code = code.substr(code.indexOf('<link')+('<link').length);
			// SRC
			posHref = code.indexOf('href=');
			href = code.substr(posHref+('href=').length);
			href = href.substr(0,href.indexOf(" "));
			href = href.replace(/"/g,'');
			
			window.importCSS(href);
		}		
	}
	// Encontrar os arquivos CSS importados no arquivo aberto
	this.findAndImportBody = function () {
				
		var posIni = 0;
		var code = this.response;
		code = code.replace(/<BODY/g,'<body');
		code = code.replace(/<\/BODY>/g,'</body>');
		
		if(code.indexOf('</body>')!=-1) {	
			// SRC
			pos1 = code.indexOf('<body')+5;
			pos2 = code.indexOf('/body>')-1
			code = code.substring(pos1, pos2);
			posMaior = code.indexOf('>')+1;
			this.response = code.substring(posMaior);
		}
	}
	// Roda o Ajax.. cria um objeto XMLHTTP e faz um request do arquivo.
	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				
				if (self.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					try{
						this.xmlhttp.open(this.method, this.requestFile, true);
						try {
							this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
						} catch (e) {
							alert('Erro Ajax!\n' +
								  '\n * Arquivo: '+ this.requestFile +
								  '\n * '+e['name']+': '+e['description']);
						}
					} catch (e) {
						alert('Erro Ajax!\n' +
							  '\n * Arquivo: '+ this.requestFile +
							  '\n * '+e['name']+': '+e['description']);
					}
				}
				
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							//if (self.execute) {
								//self.runResponse();
							//}
							if (self.elementObj) {								
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								 || elemNodeName == "select"
								 || elemNodeName == "option"
								 || elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.findAndImportJs();
									self.findAndImportCss();
									self.findAndImportBody();
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};
				this.xmlhttp.send(this.URLString);
	} } };
	this.reset();
	this.createAJAX();
}

// IMPORTAR ARQUIVO JAVASCRIPT
window.importJS = function (pArquivo) {
	var getheadTag = document.getElementsByTagName('head')[0];
	ajax = new window.importFile(pArquivo);
	ajax.runAJAX();
	
	setjs = document.createElement('script'); 
	setjs.setAttribute('type', 'text/javascript');
	getheadTag.appendChild(setjs);
	ajax.onCompletion = function () { setjs.text = this.response; }	
}
window.importJs = window.importJS

// IMPORTAR ARQUIVO CSS
window.importCSS = function (pArquivo) {
	var getheadTag = document.getElementsByTagName('head')[0];

	setcss = document.createElement('STYLE');
//	alert(getheadTag);
	getheadTag.appendChild(setcss);
	if(document.styleSheets[0].addImport)
		document.styleSheets[0].addImport(pArquivo);
	else{
		getheadTag.removeChild(setcss);
		setcss = document.createElement('link'); 
		setcss.setAttribute('type', 'text/css'); 
		setcss.setAttribute('rel', 'stylesheet');
		setcss.setAttribute('href', pArquivo);
		setcss.setAttribute('imported', true);
		getheadTag.appendChild(setcss);
	}	
}
window.importCss = window.importCSS