/*
#---------------------------------------------------------------------------------------------------------------------------------
#Empresa Desenvolvedora: E-net             Data:01/03/2007
#E-mail: info@enetbr.com.br       Site:www.enetbr.com.br
#Descrição: Adaptação para os sistemas da Enet.
#Obs:
#---------------------------------------------------------------------------------------------------------------------------------
#Programador Responsável: Giselle Nogueira
#---------------------------------------------------------------------------------------------------------------------------------
#Histórico de alterações
#
#Nome:                          Data:
#Descrição:
#---------------------------------------------------------------------------------------------------------------------------------
*/







var _ajax = { handler: {}, idCounter: 0 };

//Objeto em que a requisiÃ§Ã£o deve ser empressa
var obj;
var Select;

var atualizaOption = 'nao';  // setar para sim para mostrar o numero crescente dos itens do option carregando


// FunÃ§Ã£o que escreve o retorno no objeto selecionado
var fncEscreve = function(texto) {
                     if(document.getElementById(obj))
 									 	   document.getElementById(obj).innerHTML = texto;
									 };

// FunÃ§Ã£o a ser usada em casos em que sÃ³ Ã© interresante o retorno se for uma mensagem
var fncMensagem = function(texto){
	                  if(texto != ""){
                      texto = texto.replace("<script>alert('", "");
											texto = texto.replace("')</script>");
											alert(texto);
										}
							};
var fncEscreveCampoTexto = function(texto){
                             if(texto != "")
														   document.getElementById(obj).value = texto;
													 };

function ajax(timeLimit, errorFunc) {
this.Select = '';
this.id = ++_ajax.idCounter;
_ajax.handler[this.id] = this;
this.timeout = timeLimit ? timeLimit : 0;
this.timeHand = null;
this.errorFunction = fncMensagem;//(errorFunc || null);
this.returnXML = false;
this.param = [];
this.paramStr = '';
this.returnValue = null;
this.status = ['Não foi possivel iniciar a requisição','Carregando...','Carregado','Interagindo','Completo'];

this.sendLoad = function(url, waitFunc, loadFunc, type) {
  this.loadFunction = (loadFunc || (this.loadFunction || function() {}));
  this.waitFunction = (waitFunc || (this.waitFunction || function() {}));
  type = /^post$/i.test(type) ? 'POST' : 'GET';
  this.req.onreadystatechange = new Function("_ajax.handler["+this.id+"].onChange();");
	this.req.open(type, url+((type == 'GET' && this.param.length > 0) ? '?'+this.paramStr : ''), true);
    if(type == 'POST') this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		else this.req.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
		this.req.setRequestHeader("encoding", "utf-8");
    if(!document.all) // O Netscape nÃ£o envia o HTTP_REFERER se a pÃ¡gina nÃ£o recarregar
      this.req.setRequestHeader('REFERER', window.location.href);
  this.req.send((type == 'POST' && this.param.length > 0) ? this.paramStr : null);
	  if(this.timeout > 0)
		  this.timeHand = setTimeout("_ajax.handler["+this.id+"].interrupt();", this.timeout * 1000);
  };

this.sendForm = function(frm, waitFunc, loadFunc) {
  this.loadFunction = (loadFunc || (this.loadFunction || function() {}));
  this.waitFunction = (waitFunc || (this.waitFunction || function() {}));
  var arr = [], str = '', act = frm.action, mtd = (frm.method || 'GET');
    if(!act) return false;
    for(i = 0; i < frm.elements.length; i++) {
      if(frm.elements[i].name != '') {
        if(/^radio|checkbox$/i.test(frm.elements[i].type) && frm.elements[i].checked == false) continue;
        if(!inArray(arr,frm.elements[i].name) || new RegExp('\\[\\]$').test(frm.elements[i].name)) {
        arr.push(frm.elements[i].name);
        arr.push(frm.elements[i].value);
        }
      }
    }

    if(arr.length > 0) str += "_ajax.handler["+this.id+"].setParams('"+arr.join("','")+"'); ";
  str += "_ajax.handler["+this.id+"].sendLoad('"+act+"',_ajax.handler["+this.id+"].waitFunction,"+
         "_ajax.handler["+this.id+"].loadFunction,'"+mtd+"');";
  new Function(str)();

    function inArray(arr, val) {
      for(var i = 0; i < arr.length; i++) if(arr[i] == val) return true;
    return false;
    }
  };

  this.onChange = function() {
  this.waitFunction(this.status[this.req.readyState]);
    if(this.req.readyState == 4) {
		  if(this.timeHand != null) {
			clearTimeout(this.timeHand);
			this.timeHand = null;
			}
    var resp = this.returnXML ? 'responseXML' : 'responseText';
    this.returnValue = this.req.status == 200 ? this.req[resp] : this.req.status+' - '+this.req.statusText;
    this.loadFunction(this.returnValue);
    }
  };

  this.setParams = function() {
    if(!this.req || this.setParams.arguments.length < 2) return;
    for(var i = 0; i < this.setParams.arguments.length; i += 2)
      if(typeof(this.setParams.arguments[i + 1]) != 'undefined')
        this.param.push(this.setParams.arguments[i]+'='+escape(this.setParams.arguments[i + 1]));
  return this.paramStr = this.param.join('&');
  };

	this.interrupt = function() {
	this.req.abort();
	  if(this.errorFunction != null) this.errorFunction();
	};

  this.makeXHR = function() {
    if(typeof window.XMLHttpRequest != 'object') {
      window.XMLHttpRequest = function() {
      var types = ['Microsoft.XMLHTTP','MSXML2.XMLHTTP.5.0',
									 'MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'];
        for(var i = 0; i < types.length; i++) {
        var xhr = (new ActiveXObject(types[i]) || false);
          if(xhr) return xhr;
        }
      return false;
      };
    }
  };

  this.getRequestObject = function(){
		var req = null;
		if(typeof XMLHttpRequest != "undefined") req = new XMLHttpRequest();
		if(!req && typeof ActiveXObject != "undefined"){
			try{
				req	= new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e){
				try{
					req	= new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e){
					try{
						req	= new ActiveXObject("Msxml2.XMLHTTP.4.0");
					}
					catch (e){
						req=null;
					}
				}
			}
		}

		if(!req && window.createRequest) req = window.createRequest();

		if (!req) return false;

		return req;
	};

//this.makeXHR();
this.req = this.getRequestObject();

/* FunÃ§Ãµes adicionadas em 03/10/2006 */

  this.obj = function(Id){

		if(!Id) return null;

		var returnObj = document.getElementById(Id);
		if(!(returnObj) && document.all){
			returnObj = document.all[Id];
		}
		return returnObj;
	}; // end OBJ

  // ajax.include(FileName) inclui dinamicamente arquivos javascript externos
	this.include = function(FileName){
		var objHead		= document.getElementsByTagName('head');
		var objScript	= document.createElement('script');
		objScript.type	= 'text/javascript';
		objScript.src	= FileName;
		objHead[0].appendChild(objScript);
	}; // end Include

	this.stripOnPrefix = function(EventName){
		EventName = EventName.toLowerCase();
		if(EventName.indexOf('on') == 0){
			EventName = EventName.replace(/on/,'');
		}
		return EventName;
	}; // end stripOnPrefix

	this.addOnPrefix = function(EventName){
		EventName = EventName.toLowerCase();
		if(EventName.indexOf('on') != 0){
			EventName = 'on' + EventName;
		}
		return EventName;
	}; //end addOnPrefix

	// ajax.addHandler Adiciona um evento a um elemento
	this.addHandler = function(ElementId, Event, FunctionName){
		if (window.addEventListener){
			Event = this.stripOnPrefix(Event);
			eval("this.obj('"+ElementId+"').addEventListener('"+Event+"',"+FunctionName+",false);");
		}
		else{
			AltEvent = this.addOnPrefix(Event);
			eval("this.obj('"+ElementId+"').attachEvent('"+AltEvent+"',"+FunctionName+",false);");
		}
	}; // end addHandler

	// ajax.removeHandler remove um evento de um elemento
	this.removeHandler = function(ElementId, Event, FunctionName){
		if(window.addEventListener){
			Event = this.stripOnPrefix(Event);
			eval("this.obj('"+ElementId+"').removeEventListener('"+Event+"',"+FunctionName+",false);");
		}
		else{
			AltEvent = this.addOnPrefix(Event);
			eval("this.obj('"+ElementId+"').detachEvent('"+AltEvent+"',"+FunctionName+",false);");
		}
	}; //end removeHandler

	// ajax.create creates a new child node under a parent
	this.create = function(ParentId, Tag, Id){
		var objParent = this.obj(ParentId);
		objElement = document.createElement(Tag);
		objElement.setAttribute('id',Id);
		if (objParent) objParent.appendChild(objElement);
	}; // end create

	// ajax.insert inserts a new node before another node
	this.insert = function(BeforeId, Tag, Id){
		var objSibling = this.obj(BeforeId);
		objElement = document.createElement(Tag);
		objElement.setAttribute('id',Id);
		objSibling.parentNode.insertBefore(objElement, objSibling);
	}; // end insert

	// ajax.insertAfter inserts a new node after another node
	this.insertAfter = function(AfterId, Tag, Id){
		var objSibling = this.obj(AfterId);
		objElement = document.createElement(Tag);
		objElement.setAttribute('id',Id);
		objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
	}; // end insertAfter

	this.getInput = function(Type, Name, Id){
		var Obj;
		if(!window.addEventListener){
			Obj = document.createElement('<input type="'+Type+'" id="'+Id+'" name="'+Name+'">');
		}
		else{
			Obj = document.createElement('input');
			Obj.setAttribute('type',Type);
			Obj.setAttribute('name',Name);
			Obj.setAttribute('id',Id);
		}
		return Obj;
	}; // end getInput

	// ajax.createInput creates a new input node under a parent
	this.createInput = function(ParentId, Type, Name, Id){
		var objParent = this.obj(ParentId);
		var objElement = this.getInput(Type, Name, Id);
		if(objParent && objElement)
			objParent.appendChild(objElement);
	}; // end createInput

	// ajax.insertInput creates a new input node before another node
	this.insertInput = function(BeforeId, Type, Name, Id){
		var objSibling = this.obj(BeforeId);
		var objElement = this.getInput(Type, Name, Id);
		if (objElement && objSibling && objSibling.parentNode)
			objSibling.parentNode.insertBefore(objElement, objSibling);
	}; // end insertInput

	// ajax.insertInputAfter creates a new input node after another node
	this.insertInputAfter = function(AfterId, Type, Name, Id){
		var objSibling = this.obj(AfterId);
		var objElement = this.getInput(Type, Name, Id);
		if(objElement && objSibling && objSibling.parentNode){
			objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
		}
	}; // end insertInputAfter

	// ajax.remove deletes an element
	this.remove = function(Id){
		objElement = this.obj(Id);
		if(objElement && objElement.parentNode && objElement.parentNode.removeChild){
			objElement.parentNode.removeChild(objElement);
		}
	}; // end remove

	// ajax.createOption cria um novo option em determinado select
	this.createOption = function(selectId, value, texto, selected){
		  var objParent = this.obj(selectId);
		if(!objParent)return;
		objElement = document.createElement("option");
		objElement.setAttribute('value', value);
		if(selected != null && selected != "")
		  objElement.setAttribute("selected", "selected");
		var textNode = document.createTextNode(texto);
		objElement.appendChild(textNode); //Adiciona o texto a OPTION.
		if (objParent) objParent.appendChild(objElement);
	}; // end createOption

	// ajax.removeOption apaga um option em determinado select
	this.removeOption = function(selectId, option){
		var objParent = this.obj(selectId);
		if(!objParent)return;
		var objElement = objParent.options[option];
		if(objElement && objParent && objParent.removeChild){
			objParent.removeChild(objElement);
		}
	}; // end removeOption

	// ajax.removeOption apaga um option em determinado select
	this.removeAllOption = function(selectId){
		var objParent = this.obj(selectId);
		if(!objParent)return false;
		var tamanho = objParent.length;
		for(i=0; i < tamanho; i++){
		  if(objParent.options[i])
			  this.removeOption(selectId, i)
			else if((objParent.options[objParent.length-1]))
			  this.removeOption(selectId, objParent.length-1)
		}
	}; // end removeOption

	this.preencheSelect = function(texto){
	    dados = texto.split("#");
		tamanho = dados.length;
		if(tamanho == 0) return;
		this.removeAllOption(this.Select);
		if(atualizaOption == 'sim'){
		  for(i = 0 ; i < tamanho-1; i = i + 3){
			  this.createOption(this.Select, this.url_decode(dados[i]), this.url_decode(dados[i+1]), this.url_decode(dados[i+2]));
			 }
		  this.removeOption(this.Select, 0);
	  }
		else{
			for(i = 0 ; i < tamanho-1; i = i + 3){
			  this.createOption(this.Select, this.url_decode(dados[i]), this.url_decode(dados[i+1]), this.url_decode(dados[i+2]));
			}
		}
	    return true;
	}

	this.atualizaOption = function(selectId, chave, valorTxt, valor){
	  var objParent = this.obj(selectId);
		objParent.options[chave].text = valorTxt;
	}





	// url_encode version 1.0
	this.url_encode = function(str) {
			var hex_chars = "0123456789ABCDEF";
			var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
			var n, strCode, hex1, hex2, strEncode = "";

			for(n = 0; n < str.length; n++) {
					if (noEncode.test(str.charAt(n))) {
							strEncode += str.charAt(n);
					} else {
							strCode = str.charCodeAt(n);
							hex1 = hex_chars.charAt(Math.floor(strCode / 16));
							hex2 = hex_chars.charAt(strCode % 16);
							strEncode += "%" + (hex1 + hex2);
					}
			}
			return strEncode;
	}

	// url_decode version 1.0
	this.url_decode = function (str) {
			var n, strCode, strDecode = "";

			for (n = 0; n < str.length; n++) {
					if (str.charAt(n) == "%") {
							strCode = str.charAt(n + 1) + str.charAt(n + 2);
							strDecode += String.fromCharCode(parseInt(strCode, 16));
							n += 2;
					}
					else if (str.charAt(n) == "+") {
					  strDecode += " ";
					}
					else {
							strDecode += str.charAt(n);
					}
			}
			return strDecode;
	}

}

