// JavaScript Document
function NewAjax(){
	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;
				}
			 }
	}
	return ajax;
}

function IniGaragista()
{
	document.frmGaragista.NOME_FANTASIA.focus();
	/*
	document.frmGaragista.NOME_FANTASIA.value = '';
	document.frmGaragista.RAZAO_SOCIAL.value = '';
	document.frmGaragista.ENDERECO.value = '';
	document.frmGaragista.BAIRRO.value = '';
	document.frmGaragista.UF.value = '';
	document.frmGaragista.MUNICIPIO.value = '';
	document.frmGaragista.CEP.value = '';
	document.frmGaragista.CPF.value = '';
	document.frmGaragista.RG.value = '';
	document.frmGaragista.EMAIL.value = '';
	document.frmGaragista.EMAIL.value = '';
	document.frmGaragista.COLABORADOR.value = '';
	document.frmGaragista.SENHA.value = '';
	*/	
}
function GaragistaCancel()
{
 if(confirm('Desejas relamente cancelar o cadastramento deste garagista ?')){
   window.location.href='garagista.php'; 
   return false;
 }
}
function GaragistaSave(){
	if(ValidaGaragista()==true){
		ajxGaragista = new NewAjax();
		if(ajxGaragista){
				 ajxGaragista.open("POST", "cadastra_garagista.php", true);
				 ajxGaragista.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxGaragista.onreadystatechange = function() {
					if(ajxGaragista.readyState == 4 ) {
					   if(ajxGaragista.responseXML) {
						  processGaragista(ajxGaragista.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'NOME_FANTASIA='                  +document.frmGaragista.NOME_FANTASIA.value+
				 '&RAZAO_SOCIAL='                  +document.frmGaragista.RAZAO_SOCIAL.value+
				 '&ENDERECO='                      +document.frmGaragista.ENDERECO.value+
				 '&BAIRRO='                        +document.frmGaragista.BAIRRO.value+
				 '&UF='                            +document.frmGaragista.UF.value+
				 '&MUNICIPIO='                     +document.frmGaragista.MUNICIPIO.value+
				 '&CEP='                           +document.frmGaragista.CEP.value+
				 '&CPF='                           +document.frmGaragista.CPF.value+
				 '&FONE='                          +document.frmGaragista.FONE.value+
				 '&FAX='                           +document.frmGaragista.FAX.value+
				 '&RG='                            +document.frmGaragista.RG.value+
				 '&EMAIL='                         +document.frmGaragista.EMAIL.value+
				 '&HOMEPAGE='                      +document.frmGaragista.HOMEPAGE.value+
				 '&SITUACAO='                      +document.frmGaragista.SITUACAO.value+
				 '&MENSALIDADE='                   +document.frmGaragista.MENSALIDADE.value+
				 '&COLABORADOR='                   +document.frmGaragista.COLABORADOR.value+
				 '&SENHA='                         +document.frmGaragista.SENHA.value;
				 ajxGaragista.send(params);
				 ajxGaragista.send(params);
		}
	}
}


function processGaragista(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
	 window.location.href='garagista.php'; 
   }
}






function GaragistaUpdate(){
	if(ValidaGaragista()==true){
		ajxGaragistaUp = new NewAjax();
		if(ajxGaragistaUp){
				 ajxGaragistaUp.open("POST", "update_garagista.php", true);
				 ajxGaragistaUp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxGaragistaUp.onreadystatechange = function() {
					if(ajxGaragistaUp.readyState == 4 ) {
					   if(ajxGaragistaUp.responseXML) {
						  processGaragista(ajxGaragistaUp.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'CLI_CODIGO='                     +document.frmGaragista.CLI_CODIGO.value+
				 '&NOME_FANTASIA='                 +document.frmGaragista.NOME_FANTASIA.value+
				 '&RAZAO_SOCIAL='                  +document.frmGaragista.RAZAO_SOCIAL.value+
				 '&ENDERECO='                      +document.frmGaragista.ENDERECO.value+
				 '&BAIRRO='                        +document.frmGaragista.BAIRRO.value+
				 '&UF='                            +document.frmGaragista.UF.value+
				 '&MUNICIPIO='                     +document.frmGaragista.MUNICIPIO.value+
				 '&CEP='                           +document.frmGaragista.CEP.value+
				 '&CPF='                           +document.frmGaragista.CPF.value+
				 '&FONE='                          +document.frmGaragista.FONE.value+
				 '&FAX='                           +document.frmGaragista.FAX.value+
				 '&RG='                            +document.frmGaragista.RG.value+
				 '&EMAIL='                         +document.frmGaragista.EMAIL.value+
				 '&HOMEPAGE='                      +document.frmGaragista.HOMEPAGE.value+
				 '&SITUACAO='                      +document.frmGaragista.SITUACAO.value+
				 '&MENSALIDADE='                   +document.frmGaragista.MENSALIDADE.value+
				 '&COLABORADOR='                   +document.frmGaragista.COLABORADOR.value+
				 '&SENHA='                         +document.frmGaragista.SENHA.value;
				 ajxGaragistaUp.send(params);
				 //alert(params);

		}
	}
}


function processGaragista(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             if(confirm('Cadastro efetuado com sucesso. Desejas cadastrar novo cliente ?')){
				   window.location.href='novo_garagista.php';  
			 }else{
				   window.location.href='garagista.php'; 
			 }
   }
}





function Enter(id, e)
{
  if(e.keyCode==13)
    document.getElementById(id).focus(); else return false;
}
	


function formatar(src, mask)
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
  {
	src.value += texto.substring(0,1);
  }
}


function CreateUF(){
	ajxUF = new NewAjax();
	if(ajxUF){
		 ajxUF.open("POST", "xml_uf.php", true);
		 ajxUF.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajxUF.onreadystatechange = function() {
            if(ajxUF.readyState == 4 ) {
			   if(ajxUF.responseXML) {
			      processUF(ajxUF.responseXML);
			   }
             }
         }
		 var param = '';
         ajxUF.send(param);
	}
}

function processUF(obj){
   var dataArray   = obj.getElementsByTagName("uf");
   var item = dataArray[0];
   if(dataArray.length > 0) {
       document.getElementById('UF').innerHTML="";
       var novo1 = document.createElement("option");
	   novo1.setAttribute("id", "opcoes");
	   novo1.value = "--";
	   novo1.text  = "Selecione uma Unidade Federal";
	   document.forms[0].UF.options.add(novo1);
       for(var i = 0 ; i < dataArray.length ; i++) {
             var item = dataArray[i];
             var novo = document.createElement("option");
             novo.setAttribute("id", "opcoes");
			 novo.value = item.getElementsByTagName("UNF_SIGLA")[0].firstChild.nodeValue;
			 novo.text  = item.getElementsByTagName("UNF_NOME")[0].firstChild.nodeValue;
			 document.forms[0].UF.options.add(novo);
	   }
  }
}

function CreateMunicipio(UF){
	ajxMunicipio = new NewAjax();
	if(ajxMunicipio){
		 ajxMunicipio.open("POST", "xml_municipio.php", true);
		 ajxMunicipio.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajxMunicipio.onreadystatechange = function() {
			if(ajxMunicipio.readyState == 4 ) {
			   if(ajxMunicipio.responseXML) {
			      processMunicipio(ajxMunicipio.responseXML);
			   }
             }
         }
		 var param = 'uf='+UF;
         ajxMunicipio.send(param);
	}
}

function processMunicipio(obj){
   var dataArray   = obj.getElementsByTagName("municipio");
   var item = dataArray[0];
   if(dataArray.length > 0) {
       document.getElementById('MUNICIPIO').innerHTML="";
       var novo1 = document.createElement("option");
	   novo1.setAttribute("id", "opcoes");
	   novo1.value = "--";
	   novo1.text  = "Selecione uma Municipio";
	   document.forms[0].MUNICIPIO.options.add(novo1);
       for(var i = 0 ; i < dataArray.length ; i++) {
             var item = dataArray[i];
             var novo = document.createElement("option");
             novo.setAttribute("id", "opcoes");
			 novo.value = item.getElementsByTagName("MUN_CODIGO")[0].firstChild.nodeValue;
			 novo.text  = item.getElementsByTagName("MUN_NOME")[0].firstChild.nodeValue;
			 document.forms[0].MUNICIPIO.options.add(novo);
	   }
  }
}


function LoadColaborador(){
	ajxColaborador = new NewAjax();
	if(ajxColaborador){
		 ajxColaborador.open("POST", "xml_colaborador.php", true);
		 ajxColaborador.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajxColaborador.onreadystatechange = function() {
            if(ajxColaborador.readyState == 4 ) {
			   if(ajxColaborador.responseXML) {
			      processColaboradorLoad(ajxColaborador.responseXML);
				   ajxColaborador = null;
			   }
             }
         }
		 var param = '';
         ajxColaborador.send(param);
	}
}

function processColaboradorLoad(obj){
   var dataArray   = obj.getElementsByTagName("colaborador");
   var item = dataArray[0];
   if(dataArray.length > 0) {
       document.getElementById('COLABORADOR').innerHTML="";
       var novo1 = document.createElement("option");
	   novo1.setAttribute("id", "opcoes");
	   novo1.value = "--";
	   novo1.text  = "Selecione um Colaborador";
	   document.forms[0].COLABORADOR.options.add(novo1);
       for(var i = 0 ; i < dataArray.length ; i++) {
             var item = dataArray[i];
             var novo = document.createElement("option");
             novo.setAttribute("id", "opcoes");
			 novo.value = item.getElementsByTagName("USU_CODIGO")[0].firstChild.nodeValue;
			 novo.text  = item.getElementsByTagName("USU_NOME")[0].firstChild.nodeValue;
			 document.forms[0].COLABORADOR.options.add(novo);
	   }
  }
}

function ValidaGaragista()
{
  var erro = 0;
  var msg = '';
  var campo = '';
  //Validacao de Nome Fantasia
  if(document.getElementById('NOME_FANTASIA').value==''){
	document.getElementById('NOME_FANTASIA').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Nome Fantasia\n';
	erro++; 
	if(campo=='') campo='NOME_FANTASIA';
  }else{
	document.getElementById('NOME_FANTASIA').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de RAZAO SOCIAL
  if(document.getElementById('RAZAO_SOCIAL').value==''){
	document.getElementById('RAZAO_SOCIAL').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Razao Social\n';
	erro++; 
	if(campo=='') campo='RAZAO_SOCIAL';
  }else{
	document.getElementById('RAZAO_SOCIAL').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de UF
  if((document.getElementById('UF').value=='--') || (document.getElementById('UF').value=='')){
	document.getElementById('UF').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Unidade Federal\n';
	erro++; 
	if(campo=='') campo='UF';
  }else{
	document.getElementById('UF').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de Municipio
  if((document.getElementById('MUNICIPIO').value=='--') || (document.getElementById('MUNICIPIO').value=='')){
	document.getElementById('MUNICIPIO').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Municipio\n';
	erro++; 
	if(campo=='') campo='MUNICIPIO';
  }else{
	document.getElementById('MUNICIPIO').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de CPF
  if(document.getElementById('CPF').value==''){
	document.getElementById('CPF').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de CPF/CNPJ\n';
	erro++; 
	if(campo=='') campo='CPF';
  }else{
	document.getElementById('CPF').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de Colaborador
  if(document.getElementById('COLABORADOR').value=='--'){
	document.getElementById('COLABORADOR').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Colaborador\n';
	erro++; 
	if(campo=='') campo='COLABORADOR';
  }else{
	document.getElementById('COLABORADOR').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de Senha
  if(document.getElementById('SENHA').value==''){
	document.getElementById('SENHA').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Senha\n';
	erro++; 
	if(campo=='') campo='SENHA';
  }else{
	document.getElementById('SENHA').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de Mensalidade (Maior que zero)
  if(Number(document.getElementById('MENSALIDADE').value)<=0){
	document.getElementById('MENSALIDADE').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Mensalidade\n';
	erro++; 
	if(campo=='') campo='MENSALIDADE';
  }else{
	document.getElementById('MENSALIDADE').style.backgroundColor='#FFFFFF';
  }
  /////////////////  
  if(erro>0){
	 alert('Foram encontrados os seguintes campos incoerentes:\n'+msg);
	 document.getElementById(campo).focus();
	 return false;
  }else{
	 return true;  
  }
	
}














//onkeypress="reais(this,event)" onkeydown="backspace(this,event)"
documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "" + t.substr(p);
    }
    return t+"."+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency,tam){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
  		return 0.00;		
	}

	if (currency ==true){
		/* Elimina os zeros à esquerda
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/

		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;

		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;

		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;

	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda,
			* sem considerar os últimos 2 algarismos como casas decimais
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}
	return val3;
	}
}

function reais(obj,event,tam){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;

	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if
}// end backspace

function FormataReais(fld, milSep, decSep, 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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}



///////////////////////////////////////////COLABORADOR ////////////////////////////////////////////

function ColaboradorCancel()
{
 if(confirm('Desejas relamente cancelar o cadastramento deste colaborador ?')){
   window.location.href='colaborador.php'; 
   return false;
 }
}
function ColaboradorSave(){
	if(ValidaColaborador()==true){
		ajxColaborador = new NewAjax();
		if(ajxColaborador){
				 ajxColaborador.open("POST", "cadastra_colaborador.php", true);
				 ajxColaborador.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxColaborador.onreadystatechange = function() {
					if(ajxColaborador.readyState == 4 ) {
					   if(ajxColaborador.responseXML) {
						  processColaborador(ajxColaborador.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'NOME='                        +document.frmColaborador.NOME.value+
				 '&USUARIO='                    +document.frmColaborador.USUARIO.value+
				 '&SENHA='                      +document.frmColaborador.SENHA.value;
				 ajxColaborador.send(params);
		}
	}
}


function processColaborador(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             if(confirm('Cadastro efetuado com sucesso. Desejas cadastrar novo colaborador ?')){
				   window.location.href='novo_colaborador.php';  
			 }else{
				   window.location.href='colaborador.php'; 
			 }
   }
}


function ValidaColaborador()
{
  var erro = 0;
  var msg = '';
  var campo = '';
  //Validacao de Nome
  if(document.getElementById('NOME').value==''){
	document.getElementById('NOME').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Nome\n';
	erro++; 
	if(campo=='') campo='NOME';
  }else{
	document.getElementById('NOME').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de USUARIO
  if(document.getElementById('USUARIO').value==''){
	document.getElementById('USUARIO').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Usuario\n';
	erro++; 
	if(campo=='') campo='USUARIO';
  }else{
	document.getElementById('USUARIO').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de SENHA
  if(document.getElementById('SENHA').value==''){
	document.getElementById('SENHA').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Senha\n';
	erro++; 
	if(campo=='') campo='SENHA';
  }else{
	document.getElementById('SENHA').style.backgroundColor='#FFFFFF';
  }
  /////////////////

  if(erro>0){
	 alert('Foram encontrados os seguintes campos incoerentes:\n'+msg);
	 document.getElementById(campo).focus();
	 return false;
  }else{
	 return true;  
  }
}

///////////////////////////////////////////COLABORADOR ////////////////////////////////////////////


/////////////////////////////////////////// USUARIO   ////////////////////////////////////////////

function UsuarioCancel()
{
 if(confirm('Desejas relamente cancelar o cadastramento deste colaborador ?')){
   window.location.href='colaborador.php'; 
   return false;
 }
}
function UsuarioSave(){
	if(ValidaUsuario()==true){
		ajxUsuario = new NewAjax();
		if(ajxUsuario){
				 ajxUsuario.open("POST", "cadastra_usuario.php", true);
				 ajxUsuario.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxUsuario.onreadystatechange = function() {
					if(ajxUsuario.readyState == 4 ) {
					   if(ajxUsuario.responseXML) {
						  processUsuario(ajxUsuario.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'NOME='                        +document.frmUsuario.NOME.value+
				 '&USUARIO='                    +document.frmUsuario.USUARIO.value+
				 '&SENHA='                      +document.frmUsuario.SENHA.value;
				 ajxUsuario.send(params);
		}
	}
}


function processUsuario(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             if(confirm('Cadastro efetuado com sucesso. Desejas cadastrar novo usuario ?')){
				   window.location.href='novo_usuario.php';  
			 }else{
				   window.location.href='usuarios.php'; 
			 }
   }
}


function ValidaUsuario()
{
  var erro = 0;
  var msg = '';
  var campo = '';
  //Validacao de Nome
  if(document.getElementById('NOME').value==''){
	document.getElementById('NOME').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Nome\n';
	erro++; 
	if(campo=='') campo='NOME';
  }else{
	document.getElementById('NOME').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de USUARIO
  if(document.getElementById('USUARIO').value==''){
	document.getElementById('USUARIO').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Usuario\n';
	erro++; 
	if(campo=='') campo='USUARIO';
  }else{
	document.getElementById('USUARIO').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de SENHA
  if(document.getElementById('SENHA').value==''){
	document.getElementById('SENHA').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Senha\n';
	erro++; 
	if(campo=='') campo='SENHA';
  }else{
	document.getElementById('SENHA').style.backgroundColor='#FFFFFF';
  }
  /////////////////

  if(erro>0){
	 alert('Foram encontrados os seguintes campos incoerentes:\n'+msg);
	 document.getElementById(campo).focus();
	 return false;
  }else{
	 return true;  
  }
}

/////////////////////////////////////////// USUARIO   ////////////////////////////////////////////


/////////////////////////////////////////// NOTICIA   ////////////////////////////////////////////

function UsuarioNoticia()
{
 if(confirm('Desejas relamente cancelar o cadastramento desta noticia ?')){
   window.location.href='noticia.php'; 
   return false;
 }
}
function NoticiaSave(){
	if(ValidaNoticia()==true){
		ajxNoticia = new NewAjax();
		if(ajxNoticia){
				 ajxNoticia.open("POST", "cadastra_noticia.php", true);
				 ajxNoticia.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxNoticia.onreadystatechange = function() {
					if(ajxNoticia.readyState == 4 ) {
					   if(ajxNoticia.responseXML) {
						  processNoticia(ajxNoticia.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'TITULO='                    +document.frmNoticia.TITULO.value+
				 '&TEXTO='                    +document.frmNoticia.TEXTO.value+
				 '&DATA='                     +document.frmNoticia.DATA.value+
				 '&FONTE='                    +document.frmNoticia.FONTE.value;
				 ajxNoticia.send(params);
		}
	}
}


function processNoticia(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             if(confirm('Cadastro efetuado com sucesso. Desejas cadastrar nova noticia ?')){
				   window.location.href='nova_noticia.php';  
			 }else{
				   window.location.href='noticias.php'; 
			 }
   }
}


function ValidaNoticia()
{
  var erro = 0;
  var msg = '';
  var campo = '';
  //Validacao de Nome
  if(document.getElementById('TITULO').value==''){
	document.getElementById('TITULO').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Titulo\n';
	erro++; 
	if(campo=='') campo='TITULO';
  }else{
	document.getElementById('TITULO').style.backgroundColor='#FFFFFF';
  }
  /////////////////
  //Validacao de USUARIO
  if(document.getElementById('DATA').value==''){
	document.getElementById('DATA').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Data\n';
	erro++; 
	if(campo=='') campo='DATA';
  }else{
	document.getElementById('DATA').style.backgroundColor='#FFFFFF';
  }
  if(erro>0){
	 alert('Foram encontrados os seguintes campos incoerentes:\n'+msg);
	 document.getElementById(campo).focus();
	 return false;
  }else{
	 return true;  
  }
}

/////////////////////////////////////////// NOTICIA   ////////////////////////////////////////////














/////////////////////////////////////////// COMBUSTIVEL   ////////////////////////////////////////////

function CombustivelCancel()
{
 if(confirm('Desejas relamente cancelar o cadastramento deste combustivel ?')){
   window.location.href='combustivel.php'; 
   return false;
 }
}
function CombustivelSave(){
	if(ValidaCombustivel()==true){
		ajxCombustivel = new NewAjax();
		if(ajxCombustivel){
				 ajxCombustivel.open("POST", "cadastra_combustivel.php", true);
				 ajxCombustivel.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxCombustivel.onreadystatechange = function() {
					if(ajxCombustivel.readyState == 4 ) {
					   if(ajxCombustivel.responseXML) {
						  processCombustivel(ajxCombustivel.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'COMBUSTIVEL='+document.frmCombustivel.COMBUSTIVEL.value;
				 ajxCombustivel.send(params);
		}
	}
}


function processCombustivel(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             if(confirm('Cadastro efetuado com sucesso. Desejas cadastrar novo Combustivel ?')){
				   window.location.href='novo_combustivel.php';  
			 }else{
				   window.location.href='combustivel.php'; 
			 }
   }
}


function ValidaCombustivel()
{
  var erro = 0;
  var msg = '';
  var campo = '';
  //Validacao de COMBUSTIVEL
  if(document.getElementById('COMBUSTIVEL').value==''){
	document.getElementById('COMBUSTIVEL').style.backgroundColor='#FEDAE0';
	msg += '*Preencha o campo de Combustivel\n';
	erro++; 
	if(campo=='') campo='COMBUSTIVEL';
  }else{
	document.getElementById('COMBUSTIVEL').style.backgroundColor='#FFFFFF';
  }

  if(erro>0){
	 alert('Foram encontrados os seguintes campos incoerentes:\n'+msg);
	 document.getElementById(campo).focus();
	 return false;
  }else{
	 return true;  
  }
}


function CombustivelUpdate(){
	if(ValidaCombustivel()==true){
		ajxCombustivel = new NewAjax();
		if(ajxCombustivel){
				 ajxCombustivel.open("POST", "update_combustivel.php", true);
				 ajxCombustivel.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				 ajxCombustivel.onreadystatechange = function() {
					if(ajxCombustivel.readyState == 4 ) {
					   if(ajxCombustivel.responseXML) {
						  processCombustivel(ajxCombustivel.responseXML);
					   }
					 }
				 }
		
				 var params =
				 'COM_CODIGO='+document.frmCombustivel.COM_CODIGO.value+
				 '&COM_NOME='+document.frmCombustivel.COMBUSTIVEL.value;
				 ajxCombustivel.send(params);
		}
	}
}


function processCombustivel(obj){
   var dataArray   = obj.getElementsByTagName("cadastro");
   var item = dataArray[0];
   if(item.getElementsByTagName("result")[0].firstChild.nodeValue=="1") {
             alert('Erro ao cadastrar. Tente novamente.');
			 return false;
   }else{
             alert('Alteração efetuada com sucesso !')
			  window.location.href='pesquisa_combustivel.php';  
   }
}
/////////////////////////////////////////// COMBUSTIVEL   ////////////////////////////////////////////





//////////////////////////////////////////  MIOLO ////////////////////////////////////////////////////
//////////////////////////////////////////  MIOLO ////////////////////////////////////////////////////

function CreateMarca(UF){
	ajxMarca = new NewAjax();
	if(ajxMarca){
		 ajxMarca.open("POST", "xml_veiculo2.php", true);
		 ajxMarca.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajxMarca.onreadystatechange = function() {
			if(ajxMarca.readyState == 4 ) {
			   if(ajxMarca.responseXML) {
			      processMarca(ajxMarca.responseXML);
			   }
             }
         }
		 var param = 'mar='+UF;
         ajxMarca.send(param);
	}
}

function processMarca(obj){
   var dataArray   = obj.getElementsByTagName("registro");
   var item = dataArray[0];
   
   if(dataArray.length > 0) {
	    document.getElementById('marca').innerHTML="";
		for(var i = 0 ; i < dataArray.length ; i++) {
             var item = dataArray[i];
             var novo = document.createElement("option");
             novo.setAttribute("id", "opcoes");
			 novo.value = item.getElementsByTagName("MAR_CODIGO")[0].firstChild.nodeValue;
			 novo.text  = item.getElementsByTagName("MAR_NOME")[0].firstChild.nodeValue;
			 document.getElementById('marca').options.add(novo);
	   }
  }
}


function CreateModelo(UF, VEI){
	ajxModelo = new NewAjax();
	if(ajxModelo){
		 ajxModelo.open("POST", "xml_modelo.php", true);
		 ajxModelo.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajxModelo.onreadystatechange = function() {
			if(ajxModelo.readyState == 4 ) {
			   if(ajxModelo.responseXML) {
			      processModelo(ajxModelo.responseXML);
			   }
             }
         }
		 var param = 'mar='+UF+'&vei='+VEI;
         ajxModelo.send(param);
	}
}

function processModelo(obj){
   var dataArray   = obj.getElementsByTagName("registro");
   var item = dataArray[0];
   if(dataArray.length > 0) {
	    document.getElementById('modelo').innerHTML="";
		for(var i = 0 ; i < dataArray.length ; i++) {
             var item = dataArray[i];
             var novo = document.createElement("option");
             novo.setAttribute("id", "opcoes");
			 novo.value = item.getElementsByTagName("MOD_CODIGO")[0].firstChild.nodeValue;
			 novo.text  = item.getElementsByTagName("MOD_NOME")[0].firstChild.nodeValue;
			 document.getElementById('modelo').options.add(novo);
	   }
  }
}