/*
* NeoAjax - NeoBiz Asynchronous JavaScript And XML
* Marcio Ghiraldelli / André Cupini
* 20/04/2006
*/


// 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 ajaxSendRequest(idObj, url, form){


  if (document.getElementById('divLoading')) {
	  document.getElementById('divLoading').style.display = 'block';
  }


  // Adiciona variavel randomica para matar o cache do navegador
  var delimiter;
  if (url.indexOf("?") > 0) {
    delimiter = "&";
  } else {
    delimiter = "?";
  }
  url = url + delimiter + "rand=" + Math.floor(Math.random()*9999);

  // Empilha
  pilha[pilha.length] = [idObj, url, form];
  if (! form) {
	  //document.getElementById(idObj).innerHTML = "";
  }
  // 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];

  // Opta pelo método
  var method = "GET";
  if (form != null) {
    method = "POST";
  }

  // Abre a conexão
  xmlhttp.open(method, url, true);

  var formData = "";
  var boundary;
  // Se veio o form, manda os dados por POST, multipar/form-data
  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);

  // Tratamento do retorno
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4){
      // Mostra o HTML recebido
      retorno=unescape(xmlhttp.responseText.replace(/\+/g, " "));
      document.getElementById(idObj).innerHTML = retorno;
      // Roda o próximo
      ipilha++
      if (ipilha <pilha.length) {
        setTimeout('ajaxRun()',20);
      } else {

		  if (document.getElementById('divLoading')) {
			  document.getElementById('divLoading').style.display = 'none'
		  }
		  window.scrollBy(0,0);

	  }
    }
  }
}


// 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";
      } else 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";
      } else 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";
        }
      } else 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";
          }
        }
      } else 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;
}
