var debug = 0;
var firefox = false;

try {
 	xmlhttp = new XMLHttpRequest();
	firefox = true;
} catch(e) {
 	try {
 		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch(e) {
		try {
 			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch(e) {
 			xmlhttp = false;
 		}
	}
}

pilha = [];
ipilha = 0;

function ajaxSendRequest(idObj,url,form,newStyle) {
 	if (debug > 0) alert("ajaxSendRequest('" + idObj + "', '" + url + "', '" + form + "', '"+ newStyle + "')");
	if (document.getElementById('esLoading')) document.getElementById('esLoading').style.display = 'block';
 	if (url != null) var delimiter;
 	if (url.indexOf("?") > 0) delimiter = "&";
 	else delimiter = "?";
 	url = url + delimiter + "rand=" + Math.floor(Math.random()*9999);
 	if (debug > 0) alert("Empilhando " + idObj + ", " + url + ", " + form + ", " + newStyle);
 	pilha[pilha.length] = [idObj,url,form,newStyle];
 	if ((ipilha + 1) == pilha.length) ajaxRun();
}

function ajaxRun() {
	var idObj = pilha[ipilha][0];
	var url = pilha[ipilha][1];
	var form = pilha[ipilha][2];
	var newStyle = pilha[ipilha][3];
	var method = "GET";
	if (form != null) method = "POST";
	if (url != null) {
		xmlhttp.open(method,url,true);
		var formData = "";
		var boundary;
		if (form != null) {
			boundary = "---------------------------"+ Math.floor(Math.random()*99999999999999);
			formData = generateMultiPart(form,boundary);
			xmlhttp.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundary);
			if (firefox) {
				var browser = navigator.appName;
				if (browser != 'Microsoft Internet Explorer') xmlhttp.overrideMimeType("text/XML");
			}
		}
		xmlhttp.send(formData);
	} else {
		if (newStyle != null) document.getElementById(idObj).className = newStyle;
		if (debug > 0) alert("URL nula, apenas alterando CSS da div " + idObj + " para: " + newStyle);
		ipilha++;
		if (ipilha < pilha.length) setTimeout('ajaxRun()',20);
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4){
			if (document.getElementById('esLoading')) document.getElementById('esLoading').style.display = 'none';
			if (newStyle != null) document.getElementById(idObj).className = newStyle;
			retorno = unescape(xmlhttp.responseText.replace(/\+/g, " "));
			document.getElementById(idObj).innerHTML = retorno;
			ipilha++;
			if (ipilha < pilha.length) setTimeout('ajaxRun()',20);
		}
	}
}

function ajaxSendJavascript(url) {
 	if (url != null) var delimiter;
 	if (url.indexOf("?") > 0) delimiter = "&";
 	else delimiter = "?";
 	url = url + delimiter + "rand=" + Math.floor(Math.random()*9999);
 	if (debug > 0) alert("Empilhando " + url);
 	pilha[pilha.length] = url;
 	if ((ipilha + 1) == pilha.length) ajaxRunJavascript();
}

function ajaxRunJavascript() {
	url = pilha[ipilha];
	if (debug > 0) alert(url);
	if (url != null) {
		xmlhttp.open("GET",url,true);
		if (firefox) {
			var browser = navigator.appName;
			if (browser != 'Microsoft Internet Explorer') xmlhttp.overrideMimeType("text/XML");
		}
		xmlhttp.send(null);
	} else ipilha++;
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			retorno = unescape(xmlhttp.responseText.replace(/\+/g, " "));
			if (debug > 0) alert(retorno);
			jsExecute(retorno);
			ipilha++;
			if (ipilha < pilha.length) setTimeout('ajaxRunJavascript()',20);
		}
	}
}

function ajaxExecuteReady(url) {
	if (url != null) var delimiter;
 	if (url.indexOf("?") > 0) delimiter = "&";
 	else delimiter = "?";
 	url = url + delimiter + "rand=" + Math.floor(Math.random()*9999);
	if (debug > 0) alert(url);
	pilha[pilha.length] = url;
 	if ((ipilha + 1) == pilha.length) ajaxExecute();
}

function ajaxExecute() {
	url = pilha[ipilha];
	if (debug > 0) alert(url);
	if (url == null) ipilha++;
	else {
		xmlhttp.open("GET",url,true);
		if (firefox) {
			var browser = navigator.appName;
			if (browser != 'Microsoft Internet Explorer') xmlhttp.overrideMimeType("text/XML");
		}
		xmlhttp.send(null);
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			retorno = unescape(xmlhttp.responseText.replace(/\+/g, " "));
			if (debug > 0) alert(retorno);
			ipilha++;
			if (ipilha < pilha.length) setTimeout('ajaxExecute()',20);
		}
	}
}

function generateMultiPart(theForm,boundary) {
	var formData = "";
	var cDisposition = 'Content-Disposition: form-data; name="';
	for (i = 0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].name) {
			var inputType = theForm.elements[i].type;
			if (inputType == "text" || inputType == "textarea" || inputType == "button" || inputType == "hidden") {
				formData += '--' + boundary + '\r\n';
				formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
				formData += theForm.elements[i].value + "\r\n";
			}
			if (inputType == "select-one") {
				formData += '--' + boundary + '\r\n';
				formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
				formData += theForm.elements[i].options[theForm.elements[i].selectedIndex].value + "\r\n";
			}
			if (inputType == "radio") {
				if (theForm.elements[i].checked == true) {
					formData += '--' + boundary + '\r\n';
					formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
					formData += theForm.elements[i].value + "\r\n";
				}
			}
			if (inputType == "select-multiple") {
				for (j = 0; j < theForm.elements[i].length; j++) {
					if (theForm.elements[i][j].selected) {
						formData += '--' + boundary + '\r\n';
						formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
						formData += theForm.elements[i][j].value + "\r\n";
					}
				}
			}
			if (inputType == "checkbox") {
				if (theForm.elements[i].checked) {
					formData += '--' + boundary + '\r\n';
					formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
					formData += theForm.elements[i].value + "\r\n";
				}
			}
		}
	}
	formData += "--" + boundary + "--\r\n";
	return formData;
}

function jsExecute(result) {
    var ini = 0;
    while (ini != -1) {
        ini = result.indexOf('<script',ini);
        if (ini >= 0) {
            ini = result.indexOf('>',ini) + 1;
            var fim = result.indexOf('</script>',ini);
            cod = result.substring(ini,fim);
            eval(cod);
        }
    }
}
//**************************************************************************************************
function sack(file){
	this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;

	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {
				this.xmlhttp = null;
			}
		}
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp)
			this.failed = true; 
	};
	
	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}
	
	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}
	
	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}
	
	this.runResponse = function(){
		eval(this.response);
	}
	
	this.runAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (urlstring){ 
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring; 
				} else {
					this.URLString = urlstring; 
				}
			}
			if (this.encodeURIString){
				var timeval = new Date().getTime(); 
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile + "?" + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded; charset=iso-8859-1');
						this.xmlhttp.setRequestHeader('Cache-Control','no-store, no-cache, must-revalidate');
					} catch (e) {}
				}

				this.xmlhttp.send(this.URLString);
				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;
							self.onCompletion();
							if(self.execute){ self.runResponse(); }
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}
