/* Funções genéricas */
	
	//retorna focus
	function SetFocus(){
		el = document.all;
		for(i=0; i<el.length; i++){
			if(el[i].NeedFocus == 'true'){
				el[i].focus();
				break;
			}
		}
	}
	
	
	//retorna true se for numérico
	function isNum(t){
		var code;
		
		if(t.which)
			code = t.which;
		else
			code = t.keyCode;
		
		if(code > 47 && code < 58)
			return true;
		else
			return false;
	}
	
	//Ajusta campo para data 12/34/5678
	function SetDate(campo, evt){
		if(!isNum(evt)){
			return false;
		}
		
		if(campo.maxLength != 10)
			campo.maxLength = 10;
			
		var texto = campo.value;
					
		if(texto.length == 2)
			campo.value = texto + '/';
		
		if(texto.length == 5)
			campo.value = texto + '/';		
	}
	
	//Ajusta campo para data 34/5678
	function SetMesAno(campo, evt){
		if(!isNum(evt)){
			return false;
		}
		
		if(campo.maxLength != 7)
			campo.maxLength = 7;
			
		var texto = campo.value;
					
		if(texto.length == 2)
			campo.value = texto + '/';
	}
	
	//Ajusta campo para data 34/5678
	function SetDiaMes(campo, evt){
		if(!isNum(evt)){
			return false;
		}
		
		if(campo.maxLength != 5)
			campo.maxLength = 5;
			
		var texto = campo.value;
					
		if(texto.length == 2)
			campo.value = texto + '/';
	}
	
	//ajusta hora
	function SetHour(campo, evt){
		if(!isNum(evt)){
			return false;
		}
		
		if(campo.maxLength != 5)
			campo.maxLength = 5;
			
		var texto = campo.value;
					
		if(texto.length == 2)
			campo.value = texto + ':';
	}
	
	//decrementa do total o numero de letras do campo e coloca em mostra
	function RemainDigits(campo, mostra, total){
		var atual  = campo.value.length;
		var remain = total - atual;
		
		campo.maxLength = total;
		
		if(remain > 0){
			document.getElementById(mostra).innerText = '+' + remain
		}
		else if(remain == 0){
			document.getElementById(mostra).innerText = remain;
		}
	}
	
	function setCep(campo, evt){
		if(!isNum(evt))
			return false;
		
		var texto = campo.value;
		
		if(campo.maxLength != 9)
			campo.maxLength = 9;
			
		if(texto.length == 5)
			campo.value = texto + '-';
	}
	
	
	//12.345.678/0001-99
	function setCNPJ(campo, evt){
		if(!isNum(evt))
			return false;
		
		var x = campo.value;
					
		if(x.length == 2)
			campo.value = x+'.';
	
		if(x.length == 6)
			campo.value = x+'.';
		
		if(x.length == 10)
			campo.value = x+'/';
		
		if(x.length == 15)
			campo.value = x+'-';
	}
	
	// 999/9999999
	function setIE(campo, evt){
		if(!isNum(evt))
			return false;
			
		if(campo.value.length == 3){
			campo.value = campo.value + '/';
		}
	}
	
	function setClasFiscal(campo, evt){
		if(!isNum(evt))
			return false;
			
		if(campo.value.length == 2){
			campo.value = campo.value + '.';
		}
		if(campo.value.length == 5){
			campo.value = campo.value + '.';
		}
		if(campo.value.length == 8){
			campo.value = campo.value + '.';
		}
	}
	
	
	/* NEVER TUCH THIS PART OF CODE */
	
	//Vamos para a minha implementaçao AJAX!!!!
	
	function loadCity(idest, destObj, path) {
      //verifica se o browser tem suporte a ajax
	  try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 destObj.options.length = 1;
	     
		 ajax.open("POST", path+"loadxmldata.php", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			
			if(ajax.readyState == 1) {
			   destObj.disabled = true;   
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processXML(ajax.responseXML, destObj);
				  destObj.disabled = false;				  
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   //idOpcao.innerHTML = "--Primeiro selecione o estado--";
				   var a = 1;
			   }
            }
         }
		 //passa o código do estado escolhido
         ajax.send("codigo=1&idest="+idest);
      }
   }
   
   function processXML(obj, destSelect){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("cidade");
      
	  	  
	  //total de elementos contidos na tag cidade
      for(var i = 0 ; i < dataArray.length ; i++) {
         var val = dataArray[i];
		//contéudo dos campos no arquivo XML
		var codigo    =  val.getElementsByTagName("codigo")[0].firstChild.nodeValue;
		var descricao =  val.getElementsByTagName("descricao")[0].firstChild.nodeValue;
		
		//cria um novo option dinamicamente  
		var novo = document.createElement("option");
	    //atribui um ID a esse elemento
	    //novo.setAttribute("id", "opcoes");
		//atribui um valor
	    novo.value = codigo;
		//atribui um texto
	    novo.text  = descricao;
		//finalmente adiciona o novo elemento
		destSelect.options.add(novo);
	  }  
   }
   
   
	//use whit onKeyUp
	function moeda(campo){			
		var val = campo.value;
		
		if(val.indexOf('-') != -1)
			var neg = '-';
		else
			var neg = '';
		
		while(val.indexOf('.') != -1 || val.indexOf(',') != -1 || val.indexOf('-') != -1){
			val = val.replace('.', '');
			val = val.replace(',', '');
			val = val.replace('-', '');
		}
		
		while(val.charAt(0) == '0'){
			val = val.substr(1);
		}
		
		if(val.length == 0)
			campo.value = neg + '0,00';
			
		if(val.length == 1)
			campo.value = neg + '0,0' + val;
		
		if(val.length == 2)
			campo.value = neg + '0,' + val;
			
		if(val.length > 2){
			var cents = val.substr(val.length-2);
			var resto = val.substr(0, val.length-2);
			var aux = '';
			if(resto.length < 4){
				aux = resto+','+cents;
			}
			else{
				var mod   = resto.length % 3;
				var init  = resto.substr(0, mod);
				resto	  = resto.substr(mod);
				for(var i=0; i<resto.length; i += 3)
					aux += resto.substr(i, 3) + '.';
				aux = ((init) ? init+'.' : '') + aux.substr(0, aux.length-1) + ',' + cents;
			}
			campo.value = neg + aux;
		}
	}
	
	
	
	/*
		classe genérica para comunicação Aajax
	*/
	function AjaxSet(){
		this.con = null;                 //conexão com o servidor
		this.ProcessResult = null;       //função de processamento de retorno
		this.responseStatus = false;     //indica se ocorreu comunicação sem falhas
		this.RespKind = 'X';
		
		//conexão para Mozila / Netscape
		if(window.XMLHttpRequest){
			this.con = new XMLHttpRequest();
		}
		else{
			if(window.ActiveXObject){ //conexão com IE
				try{
					this.con = new window.ActiveXObject('Msxml2.XMLHTTP'); //tenta conectar pelo protocolo
				}
				catch(e){
					try{
						this.con = new window.ActiveXObject('Microsoft.XMLHTTP'); //se não, tenta por este protocolo
					}
					catch(e){
						return null;						
					}
				}
			}
			else{
				return null;
			}
		}
		
		var obj = this;
		this.con.onreadystatechange = function(){ obj.ProcessReturn.call(obj); }
		
		this.ProcessReturn = function(){
			if(this.con.readyState == 4){
				if(this.con.status == 200){
					var resp = (this.RespKind == 'X') ? this.con.responseXML : this.con.responseText;
					if(this.ProcessResult != null){
						this.ProcessResult(resp); 
					}
				}
				else{
					//var a = 1;
					//alert(this.con.status);
				}
			}
		}
		
		this.Run = function(url, fun, params, respkind, Assinc){
			this.RespKind = (respkind) ? respkind : 'X';
			this.ProcessResult = fun;
			this.con.open('POST', url, Assinc);
			this.con.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 	this.con.setRequestHeader("Content-Type", "text/html;charset=iso-8859-1");
			this.con.send(params);
		}		
	}	
	
	
	function toFloat(val){
		while(val.indexOf('.') != -1 || val.indexOf(',') != -1 || val.indexOf('-') != -1){
			val = val.replace('.', '');
			val = val.replace(',', '');
			val = val.replace('-', '');
		}
		return parseInt(val);
	}
	
	
	