/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	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 ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(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);
	}

	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 (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
          this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				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.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();
}

// Pegar posicao do Scroll horizontal e vertical
function getScrollCoordinatesX() { 
  return (document.all)?document.body.scrollLeft:window.pageXOffset; 
} 
function getScrollCoordinatesY() { 
  return (document.all)?document.body.scrollTop:window.pageYOffset; 
} 

// Criar Objetos AJAX
var ajax = new sack();

// Criar referencias GLOBAIS para objetos 
var tmpCombo = '';
var telaEspera = undefined;
var bloquearComponentes = undefined;

//------------------------------------------------//
// Rotinas para atualizar combos(SELECT) via AJAX //
//------------------------------------------------//

// onchange="ajaxCarregaCombo(document.forms[0].action, 'acao=BUSCA&mesAno='+this.value, 'subfatura')"
function ajaxCarregaCombo(action, params, combo){
  //exibeAguarde();
  document.body.style.cursor = 'wait';
  if (document.getElementById(combo) == undefined){
    alert('Componente '+combo+' não localizado. Contacte suporte');
    return;
  }
  var obj = document.getElementById(combo);
  obj.options.length = 0;	// Limpa o combo destino
  obj.options[0] = new Option('Carregando opções...','');
  tmpCombo = combo;
  ajax.requestFile = action+'?'+params; // link a ser chamado
	ajax.onCompletion = ajaxCarregaComboSucesso;	// Especifica função de Callback
	ajax.onError = ajaxErro;	// Especifica função de Callback
	ajax.runAJAX();		// Executa
}

function ajaxCarregaComboSucesso(){
  document.body.style.cursor = 'default';
  var obj = document.getElementById(tmpCombo);
  retorno = ajax.response;
  var item = "";
  var valor = "";
  var descricao = "";
  obj.options.length = 0;	// Limpa o combo destino
  while (retorno.indexOf("|-|")  != -1){
    item = retorno.substr(0, retorno.indexOf("|-|"));
    valor = item.substr(0, retorno.indexOf("|")); 
    descricao = item.substr(retorno.indexOf("|")+1); 
    obj.options[obj.options.length] = new Option(descricao,valor);
    retorno = retorno.substr(retorno.indexOf("|-|")+3);
  }
	fecharMessagem();
  obj.focus();
}

function ajaxErro(){
   fecharMessagem();
   document.body.style.cursor = 'default';
   var erro = document.getElementById('erros');
   if (erro != undefined){
     erro.innerHTML = '<tr><td class="textoMsgErro">Erro conectando com servidor. Tente novamente.</td></tr>';
   } else {
     alert('Erro conectando com servidor. Tente novamente.');
   }
}

//----------------------------------------//
// Rotinas para atualizar campos via AJAX //
//----------------------------------------//

//onchange="ajaxAtualizaInputs(document.forms[0].action, 'acao=TESTE&mesAno='+this.value)"
function ajaxAtualizaInputs(action, params){
  document.body.style.cursor = 'wait';
  ajax.requestFile = action+'?'+params; // link a ser chamado
	ajax.onCompletion = ajaxAtualizaInputsSucesso;	// Especifica função de Callback
	ajax.onError = ajaxErro;	// Especifica função de Callback
	ajax.runAJAX();		// Executa
}

function ajaxAtualizaInputsSucesso(){
  document.body.style.cursor = 'default';
  retorno = ajax.response;
  var item = "";
  var campo = "";
  var valor = "";
  var obj;
  while (retorno.indexOf("|-|")  != -1){
    item = retorno.substr(0, retorno.indexOf("|-|"));
    campo = item.substr(0, retorno.indexOf("|")); 
    valor = item.substr(retorno.indexOf("|")+1); 
  	obj = document.getElementById(campo);
    if (obj != undefined){ // DIV
      if (obj.type == undefined)
        obj.innerHTML = valor;
      else
        obj.value = valor;
    }
    retorno = retorno.substr(retorno.indexOf("|-|")+3);
  }
  if ((obj != undefined) && (obj.type != 'hidden') && (!obj.disabled)) obj.focus();
}

//-------------------------------------//
// Rotinas para exibir tela de Aguarde //
//-------------------------------------//

function exibeAguarde(){
  exibeMensagem(true, 'Aguarde... / Espera... /Wait...');
}

function exibeMensagem(desabilita, mensagem) {
   if (telaEspera == undefined){
      // Pega o tamanho da área do documento
      var bodyWidth = document.documentElement.clientWidth;
      var bodyHeight = document.documentElement.clientHeight;
      if (bodyWidth < 1) bodyWidth = document.body.clientWidth;
      if (bodyHeight < 1) bodyHeight = document.body.clientHeight;
      
      // Cria DIV transparente para desabilitar os componentes
      if (desabilita){
        var divs_transparentDiv = document.createElement('DIV');
        //divs_transparentDiv.className='modalDialog_transparentDivs';
        divs_transparentDiv.style.filter='alpha(opacity=20)';
        divs_transparentDiv.style.opacity='0.4';
        divs_transparentDiv.style.zIndex='1';
        divs_transparentDiv.style.backgroundColor='#FFF';
        divs_transparentDiv.style.position='absolute';
        divs_transparentDiv.style.left = '0px';
        divs_transparentDiv.style.top = '0px';
        document.body.appendChild(divs_transparentDiv);
        divs_transparentDiv.style.height = bodyHeight+getScrollCoordinatesY()+'px';   
        divs_transparentDiv.style.width = bodyWidth+'px';   
        divs_transparentDiv.style.display='block';
        bloquearComponentes = divs_transparentDiv;
      }
      // Cria DIV que vai ter o conteudo do aguarde
      var divs_content = document.createElement('DIV');
      // Tamanho da tela
      var tmpWidth = 330;
      var tmpHeight = 93;
      divs_content.style.zIndex='100';
      divs_content.style.position='absolute';
      divs_content.style.left = '0px';
      divs_content.style.top =  '0px';
      divs_content.style.width = tmpWidth+'px';
      divs_content.style.height= tmpHeight+'px';  	
      divs_content.style.backgroundColor='#FFF';
      divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';
      divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  5)+getScrollCoordinatesY() + 'px';
      //divs_content.style.overflowY = 'scroll';
      document.body.appendChild(divs_content);
      divs_content.style.display='block';
      
      //if ((mensagem == undefined) || (mensagem == '')) mensagem = 'Aguarde Processando...';
      divs_content.innerHTML = '<table width="330" height="93" border="0" cellpadding="0" cellspacing="0" background="img/fundo mensagem.jpg"><tr><td width="330"><div align="center"><b>'+mensagem+'<b></div></td></tr></table>';
    
      //  Esconde todos os Selects pq ficaria por cima dos DIVs no IE
      divs_content.ieFix = document.getElementsByTagName("select");
      for(var i = divs_content.ieFix.length; i; divs_content.ieFix[--i].style.visibility = "hidden");
      
      // Guarda referencia para os DIVs para ocultar 
      telaEspera = divs_content;
   } else {
      if (telaEspera != undefined)
        telaEspera.style.visibility = 'visible';
      if (bloquearComponentes != undefined)
        bloquearComponentes.style.visibility = 'visible';
   }
}

function fecharMessagem(){
	if (telaEspera!=undefined){
    telaEspera.style.display = "none";
  	for(var i = telaEspera.ieFix.length; i; telaEspera.ieFix[--i].style.visibility = "visible");
  }
	if (bloquearComponentes!=undefined)
    bloquearComponentes.style.display = "none";
}

//----------------------------------------------------//
// Rotina para montar um link GET a partir de um form //
//----------------------------------------------------//

function form2link(form){
  var ret, len, i;
  ret = "";
  cont = 0;
  len=form.elements.length;
  for (i=0;i<len;i++){
    var tipo = document.forms[0].elements[i].type;
    if ((tipo=='button') || (tipo=='submit') || (tipo=='reset')) continue;
    var valor = document.forms[0].elements[i].value;
    if (valor == undefined) valor = "";
    var nome = document.forms[0].elements[i].name;
    ret+=nome+"="+valor;
    if (i<len-2) ret+="&";
  }
  return ret;
}

function campos2link(form, campos)
{
  var ret = "";
	if (campos!=''){
		arraycampos = campos.split(","); //Transforma a string em um array
		for (var i=0; i < arraycampos.length; i++){
      var nome = arraycampos[i];
      var campo = document.getElementById(nome);
      if (campo == undefined) alert('Campo '+nome+' não localizado em campos2link');
      var valor = document.getElementById(nome).value;
      ret+=nome+"="+valor;
			if (i<arraycampos.length-1) ret+="&";
		}
	}
  return ret;
}



