/*
* NeoAjax - NeoBiz Asynchronous JavaScript And XML
* Marcio Ghiraldelli / André Cupini
* 20/04/2006
*/
var debug=0;


// Tenta criar objeto xmlHTTP
try {
	xmlhttp = new XMLHttpRequest();
} catch(e) {
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) {
			xmlhttp = false;
		}
	}
}

// Pilha de conexões
pilha=[];
ipilha=0;


function ajaxRequest(idObj, url, form, newStyle) {

	if (debug > 0)
	alert("ajaxRequest('" + idObj + "', '" + url + "', '" + form + "', '"+ newStyle + "')");

	// DivLoading
	if (document.getElementById('divLoading')) {
		document.getElementById('divLoading').style.display = 'block';
		document.getElementById('divLoading').innerHTML = '<img src="/imagens/loading.gif" /> Carregando, aguarde...';
	}

	// Adiciona variavel randomica para matar o cache do navegador
	if (url != null) {
		var delimiter;
		if (url.indexOf("?") > 0) {
			delimiter = "&";
		} else {
			delimiter = "?";
		}
		url = url + delimiter + "rand=" + Math.floor(Math.random()*9999);
	}

	// Empilha
	if (debug > 0)
	alert("Empilhando " + idObj + ", " + url + ", " + form + ", " + newStyle);
	pilha[pilha.length] = [idObj, url, form, newStyle];

	// Se não há conexões pendentes, executa
	if ( (ipilha + 1) == pilha.length)
	ajaxRun();

}


function ajaxRun(){

	// Recupera dados da pilha
	var idObj = pilha[ipilha][0];
	var url = pilha[ipilha][1];
	var form = pilha[ipilha][2];
	var newStyle = pilha[ipilha][3];

	// Opta pelo método
	var method = "GET";
	if (form != null) {
		method = "POST";
	}

	if (url != null) {
		// Se veio a URL, faz requisicao e so desempilha no retorno
		xmlhttp.open(method, url, true);

		// Se veio o form, manda os dados por POST, multipar/form-data
		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);
		}
		xmlhttp.send(formData);

	} else {
		// Se a URL veio null, so muda o
		// CSS se passado no ajaxRequest
		if (newStyle != null)
		document.getElementById(idObj).className = newStyle;
		if (debug > 0)
		alert("URL nula, apenas alterando CSS da div " + idObj + " para: " + newStyle);
		// Desempilhando
		ipilha++
		if (ipilha < pilha.length) {
			setTimeout('ajaxRun()', 20);
		}
	}

	// Tratamento do retorno
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4){
			if (document.getElementById('divLoading'))
			document.getElementById('divLoading').style.display = 'none';
			// CSS se passado no ajaxRequest
			if (newStyle != null)
			document.getElementById(idObj).className = newStyle;
			// Mostra o HTML recebido
			retorno=unescape(xmlhttp.responseText.replace(/\+/g, " "));
			document.getElementById(idObj).innerHTML = retorno;
			// Desempilhando
			ipilha++
			if (ipilha < pilha.length) {
				setTimeout('ajaxRun()',20);
			}
		}
	}
}


// Gera multipart/form-data dos dados do formulário, conforme RFC 2388
// RFC 2388 --> http://www.faqs.org/rfcs/rfc2388.html
function generateMultiPart(theForm, boundary) {

	var formData = "";
	var cDisposition = 'Content-Disposition: form-data; name="';

	// Percorre todos os elementos do formulário
	for(i = 0; i < theForm.elements.length; i++){

		if (theForm.elements[i].name) {

			if (
			theForm.elements[i].type == "text" ||
			theForm.elements[i].type == "textarea" ||
			theForm.elements[i].type == "button" ||
			theForm.elements[i].type == "hidden"
			) {
				formData += '--' + boundary + '\r\n';
				formData += cDisposition + theForm.elements[i].name +'"\r\n\r\n';
				formData += theForm.elements[i].value + "\r\n";
			}

			if (theForm.elements[i].type == "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 (theForm.elements[i].type == "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 (theForm.elements[i].type == "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 (theForm.elements[i].type == "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 initAjax() {
	// Inicializacao automatica
	var divConteudo = "conteudo";
	var query=this.location.search.substring(1);
	if (query.length > 0){
		var params=query.substring(query.indexOf("=") + 1);
		var url = divConteudo + ".php?pagina=" + params;
		ajaxRequest(divConteudo, url, null);
	} else
	ajaxRequest(divConteudo, 'principal.htm', null);
}
