// JavaScript Document

function Mascara(objeto, evt, mask) {
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var Numeros = '0123456789';
	var Fixos  = '().-:/ '; 
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";
	
	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
	 var ntecla = (evt.which) ? evt.which : evt.keyCode;
	 tecla = Charset.substr(ntecla - 32, 1);
	 if (ntecla < 32) return true;
	
	 var tamanho = value.length;
	 if (tamanho >= mask.length) return false;
	
	 var pos = mask.substr(tamanho,1); 
	 while (Fixos.indexOf(pos) != -1) {
	  value += pos;
	  tamanho = value.length;
	  if (tamanho >= mask.length) return false;
	  pos = mask.substr(tamanho,1);
	 }
	
	 switch (pos) {
	   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
	   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
	   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
	   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
	   case '*' : objeto.value = value; return true; break;
	   default : return false; break;
	 }
	}
	objeto.value = value; 
	return true;
}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
	var t = new String(objTextBox.value);
	if (whichCode == 8){ objTextBox.value = t.substring(0, t.length-1);	} 
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function Janela(url,w,h,s) {
	var l = ((screen.width/2)-(w/2));
	var t = ((screen.height/2)-(h/2));
    window.open(url,"Janela","width="+w+",height="+h+",scrollbars="+s+",menubar=NO,titlebar=NO,toolbar=NO,status=YES,top="+t+",left="+l+"") 
}

function valida_email(email)
{
	var erEmail = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	
	if(erEmail.test(email)) {
		return true;
	}else if(email != null && email != "") {
		return false;
	}else{
		return false;
	}
}

function get_cidades(estado) {
  //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) {
    	
	 document.getElementById('cidade').options.length = 1;

	 ajax.open("POST", "xml_cidades.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) {
	 		document.getElementById('msgCidade').innerHTML = "Carregando...";
		}
		//apÃ³s ser processado - chama funÃ§Ã£o processXML que vai varrer os dados
		if(ajax.readyState == 4 ) {
		   if(ajax.responseXML) {
			  set_cidades(ajax.responseXML);
		   }
		   else {
			   //caso nÃ£o seja um arquivo XML emite a mensagem abaixo
				document.getElementById('msgCidade').innerHTML = "";
		   }
		}
	 }
	 //passa o cÃ³digo do estado escolhido
	 var params = "estado="+estado;
	 ajax.send(params);
  }
}

function set_cidades(obj){
  //pega a tag linha
  var dataArray = obj.getElementsByTagName("linha");
  
  //total de elementos contidos na tag cidade
  if(dataArray.length > 0) {
	 //percorre o arquivo XML paara extrair os dados
	 for(var i = 0; i < dataArray.length; i++) {
		var item = dataArray[i];
		//contÃ©udo dos campos no arquivo XML
		var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
		var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
		
		document.getElementById('msgCidade').innerHTML = "";
		
		//cria um novo option dinamicamente  
		var novo = document.createElement("option");
		//atribui um valor
		novo.value = codigo;
		//atribui um texto
		novo.text  = descricao;
		//finalmente adiciona o novo elemento
		document.getElementById('cidade').options.add(novo);
	 }
  }
  else {
	//caso o XML volte vazio, printa a mensagem abaixo
	document.getElementById('msgCidade').innerHTML = "";
  }
}

