function $(s) {
   return document.getElementById(s);
}

function s(name) {
   return document.getElementsByName(name)[0];
}

function limparDiv(idDiv) {
	$(idDiv).innerHTML = "";
}

function aparecer(arquivo, parametros, local) {
   if(arguments.length == 1) {
      local = 'principal';
      parametros = '';
   }
   else if(arguments.length == 2) {
      local = 'principal';
   }
   var objTempNode= document.getElementById(local);
	
	$(local).style.display = "";
	var ajax = new AJAX();
	ajax.Updater(arquivo+'.php?'+parametros,local,"get","carregando os dados...");
	return;
}

function aparecer2(arquivo, local) {
   if(arguments.length == 1) {
      local = 'principal';
   }
   var objTempNode= document.getElementById(local);
	
	$(local).style.display = "";
	var ajax = new AJAX();
	ajax.Updater(arquivo,local,"get","carregando os dados...");
	return;
}

function telaInicial() {
   aparecer('login');
   return;
}

function pressionarEnter(obj, e, idform, parametros) {
   var keycode;
   if (window.event) {
      keycode = window.event.keyCode;
   }
   else if (e) { 
      keycode = e.which;
   }
   else return true;

   if (keycode == 13) {
      if (idform == 'formValidarLogin') {
         xajax_validarLogin(xajax.getFormValues(idform));
      }
      else if (idform == 'escolherHora') {
         argumentos = parametros.split(".");
         xajax_escolherHora(argumentos[0], argumentos[1]);
      }
      else if (idform == 'ajustarNRef') {
         argumentos = parametros.split(".");
         xajax_ajustarNRef(argumentos[0], argumentos[1]);
      }
      else if (idform == 'exibirMensagem') {
         argumentos = parametros.split(".");
         xajax_exibirMensagem(argumentos[0], argumentos[1], argumentos[2]);
      }
      else if (idform == 'exibirRelPluviometrico') {
         argumentos = parametros.split(".");
         xajax_exibirRelPluviometrico(argumentos[0], argumentos[1], argumentos[2]);
      }
      else if (idform == 'formTrocarSenha') {
         xajax_trocarSenha(xajax.getFormValues(idform));
      }
      return false;
   }
   else if (idform == 'escolherHora') {
      mascara(obj, diaMesAno);
      //return false;
   }
   else if (idform == 'verificarData') {
      mascara(obj, diaMesAno);
      //return false;
   }
   else if (idform == 'iscep') {
      mascara(obj, cep);
   }
   else if (idform == 'verificarTel') {
      mascara(obj, telefone);
   }
   else if (idform == 'ajustarNRef') {
      mascara(obj, numeroDecimal);
      //return false;
   }
   else if (idform == 'isNumeroDecimal') {
      mascara(obj, numeroDecimal);
      //return false;
   }
   else if (idform == 'soNumeros') {
      mascara(obj, soNumeros);
      //return false;
   }
   else if (idform == 'verificarCnpjCpf') {
      mascara(obj, cnpj_cpf);
      //return false;
   }
   else
      return true;
}

/* Funcoes usadas para utilizacao de máscaras nos campos */
function mascara(o,f){
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value);
}

function soNumeros(v){
    return v.replace(/\D/g,"");
}

function numeroDecimal(v) {
   v=v.replace(/\D/g,"");
   v=v.replace(/^([0]{2})([0])/,"$1");
   v=v.replace(/^(\d+)(\d{2})$/g,"$1,$2");
   v=v.replace(/^([0])([0]),(\d{2})/,"$2,$3");
   v=v.replace(/^([0])([^0]),(\d{2})/,"$2,$3");
   return v;
}

function telefone(v){
    v=v.replace(/\D/g,"");                 //Remove tudo o que não é dígito
/*
    v=v.replace(/^(\d{4})(\d)/,"$1-$2");
    v=v.replace(/^(\d{2})(\d{2})-(\d{2})(\d{2})(\d)/,"($1)$2$3-$4$5");
 */
    v=v.replace(/^(\d\d)(\d)/g,"($1)$2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    return v;
}

function cpf(v){
    v=v.replace(/\D/g,"");                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
                                              //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
    return v;
}

function cnpj(v){
    v=v.replace(/\D/g,"");                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2");             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3"); //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2");           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");              //Coloca um hífen depois do bloco de quatro dígitos
    return v;
}

function cnpj_cpf(v) {
    v=v.replace(/\D/g,"");                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
                                              //de novo (para o segundo bloco de números)
    v=v.replace(/^(\d{3})\.(\d{3})\.(\d{3})(\d)/,"$1.$2.$3-$4"); //Coloca um hífen entre o terceiro e o quarto dígitos
    v=v.replace(/^(\d{2})(\d)\.(\d{2})(\d)\.(\d{2})(\d)-(\d{2})(\d)/,"$1.$2$3.$4$5/$6$7$8");
    //v=v.replace(/(\d{4})(\d)/,"$1-$2");
    v=v.replace(/^(\d{2})\.(\d{3})\.(\d{3})\/(\d{4})(\d)/,"$1.$2.$3/$4-$5");
    return v;
}

function cep(v){
    v=v.replace(/\D/g,"");                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2"); //Esse é tão fácil que não merece explicações
    return v;
}

function diaMesAno(v) {
   v=v.replace(/\D/g,"");
   v=v.replace(/^([^0123])/,"");
   v=v.replace(/^([3])([^01])/,"$1");
   v=v.replace(/^([0])([0])/,"$1");
   v=v.replace(/^(\d{2})([^01])/,"$1");
   v=v.replace(/^(\d{2})([01])/,"$1/$2");
   v=v.replace(/^(\d{2})\/([0])([0])/,"$1/$2");
   v=v.replace(/^(\d{2})\/([1])([^012])/,"$1/$2");
   v=v.replace(/^(\d{2})\/(\d{2})([^12])/,"$1/$2");
   v=v.replace(/^(\d{2})\/(\d{2})([12])/,"$1/$2/$3");
   return v;
}

function habilitarData(valor) {
   if(valor == "0") {
      $('dataInicial').disabled = false;
      $('dataFinal').disabled = false;
      $('dataInicial').focus();
   }
   else {
      $('dataInicial').value = "";
      $('dataFinal').value = "";
      $('dataInicial').disabled = true;
      $('dataFinal').disabled = true;
   }
}

function verificarEstacao(tipo) {
   if (tipo == "p") {
      $('divrange').className="optional";
      $('divcacamba').className = "required";
   }
   else if (tipo == "n") {
      $('divrange').className="required";
      $('divcacamba').className = "optional";
   }
   else {
      $('divrange').className="required";
      $('divcacamba').className = "required";
   }
}

/* funcoes usadas no dhtmlmodal  */
function selecionar(id, valor) {
   $(id).value = valor;
   
   if (id == 'opcao') {
      if ($('opcao').value == "0") {
         $('dataInicial').disabled = false;
         $('dataFinal').disabled = false;
         $('dataInicial').focus();
      }
      else {
         $('dataInicial').value = "";
         $('dataFinal').value = "";
         $('dataInicial').disabled = true;
         $('dataFinal').disabled = true;
      }
   }
}

function desabilitarData(id) {
   if ($(id).disabled == false) {
      showCalendar(id, 'trigger_'+id, '%d/%m/%Y');
   }
}

/*
function desabilitarData(id) {
   if ($(id).disabled == false) {
      if (id == 'dataInicial') {
         showCalendar('dataInicial', 'trigger_dataInicial', '%d/%m/%Y');
      }
      else if (id == 'dataFinal') {
         showCalendar('dataFinal', 'trigger_dataFinal', '%d/%m/%Y');
      }
   }
}
*/

function abrirJanelaOpcaoExcel(id,tE,Cl) {
   janelaOpcaoExcel = dhtmlmodal.open('jOpcaoExcel', 'iframe', './includes/janelaOpcaoExcel.php?idEstacao='+id+'&tE='+tE+'&idCliente='+Cl, 'Exportar para Excel', 'width=365px,height=435px,center=1,resize=0,scrolling=0')

janelaOpcaoExcel.onclose=function(){
	var formOpcaoExcel = this.contentDoc.forms[0]; 
	var opcao = this.contentDoc.getElementById("opcao");
	var dataI = this.contentDoc.getElementById("dataInicial");
	var dataF = this.contentDoc.getElementById("dataFinal");
	//var ordem = this.contentDoc.getElementById("ordem");
	
	var erro = "";
   // alert(opcao.value+' e '+ordem.value);
   if (opcao.value == '0') {
      if (dataI.value == '') {
         erro = "- Data Inicial não pode estar em branco...\n";
		   dataI.className="erro";
		   dataI.focus();
	   }
      else {
         dataI.className = "campo";
      }
      if (dataF.value == '') {
         if (erro == "") {
            dataF.focus();
         }
         erro += "- Data Final não pode estar em branco...\n";
         dataF.className="erro";
      }
      else {
         dataF.className = "campo";
      }
      if (erro != "") {
         var msg = "Erro(s):\n"+erro;
		   alert(msg);
		   return false; //cancel closing of modal window
      }
   }
   //else {
   formOpcaoExcel.submit();
   return true;
   //}
}   
}

function gerarExcelMensagem(intervalo, dataInicial, dataFinal) {
    var erro = "";
    if (intervalo == "0") {
      if (dataInicial == '') {
         erro = "- Data Inicial não pode estar em branco...\n";
		 $('dataInicial').className="erro";
		 $('dataInicial').focus();
	  }
	  if (dataFinal == '') {
	     if (erro == "") {
		    $('dataFinal').focus();
		 }
	     erro += "- Data Final não pode estar em branco...\n";
		 $('dataFinal').className="erro";
	  }
	  if (erro != "") {
	     var msg = "Erro(s):\n"+erro;
		 alert(msg);
		 return;
	  }
   }
   else {
      /* xajax_closeWindow(); */
      $('formOpcaoExcel').submit();
      return false;
   }
}

function abrirJanelaOpcaoPdf(id,tE,Cl) {
   janelaOpcaoPdf = dhtmlmodal.open('jOpcaoPdf', 'iframe', './includes/janelaOpcaoPdf.php?idEstacao='+id+'&tE='+tE+'&idCliente='+Cl, 'Exportar para PDF', 'width=365px,height=435px,center=1,resize=0,scrolling=0')

janelaOpcaoPdf.onclose=function(){
	var formOpcaoPdf = this.contentDoc.forms[0]; 
	var opcao = this.contentDoc.getElementById("opcao");
	var dataI = this.contentDoc.getElementById("dataInicial");
	var dataF = this.contentDoc.getElementById("dataFinal");
	//var ordem = this.contentDoc.getElementById("ordem");
	
	var erro = "";
   // alert(opcao.value+' e '+ordem.value);
   if (opcao.value == '0') {
      if (dataI.value == '') {
         erro = "- Data Inicial não pode estar em branco...\n";
		   dataI.className="erro";
		   dataI.focus();
	   }
      else {
         dataI.className = "campo";
      }
      if (dataF.value == '') {
         if (erro == "") {
            dataF.focus();
         }
         erro += "- Data Final não pode estar em branco...\n";
         dataF.className="erro";
      }
      else {
         dataF.className = "campo";
      }
      if (erro != "") {
         var msg = "Erro(s):\n"+erro;
		   alert(msg);
		   return false; //cancel closing of modal window
      }
   }
   //else {
   formOpcaoPdf.submit();
   return true;
   //}
}   
}

function gerarPdfMensagem(intervalo, dataInicial, dataFinal) {
    var erro = "";
    if (intervalo == "0") {
      if (dataInicial == '') {
         erro = "- Data Inicial não pode estar em branco...\n";
		 $('dataInicial').className="erro";
		 $('dataInicial').focus();
	  }
	  if (dataFinal == '') {
	     if (erro == "") {
		    $('dataFinal').focus();
		 }
	     erro += "- Data Final não pode estar em branco...\n";
		 $('dataFinal').className="erro";
	  }
	  if (erro != "") {
	     var msg = "Erro(s):\n"+erro;
		 alert(msg);
		 return;
	  }
   }
   else {
      /* xajax_closeWindow(); */
      $('formOpcaoPdf').submit();
      return false;
   }
}

function inserirSelectTodos(idSelect) {
   var x = $(idSelect);
   var y = document.createElement('option');
   if (idSelect == 'estacao') {
      y.text = "Todas as Estações";
   }
   else if (idSelect == 'piezometro') {
      y.text = "Todos os Piezômetros";
   }
   else {
      y.text = "Todos(as)";
   }
   y.value = "0";
   var sel = x.options[1];
   try {
      x.add(y, sel);
   }
   catch (ex) {
      x.add(y, 1); // IE only
   }
}


/* Funções usadas para o funcionamento do calendário  */
/*
function escolherHora(id, idbutton, idEstacao) {
   if (!showCalendar(id, idbutton, '%d/%m/%Y'))
      xajax_escolherHora(idEstacao, $(id).value);   
}
*/

function onUpdate(calendar, date) {
   var functionName = calendar.onUpdate;
   var parametros = calendar.parametros;
   if (functionName == "escolherHora") {
      //_dynarch_popupCalendar.hide();
      //calendar.callCloseHandler(); // this calls "onClose" (see above)
      xajax_escolherHora(parametros[0], date);
      //return;
   }
}

function onSelect(calendar, date) {
   //var input_field = $('data'); 
   //var input_field = calendar.sel;
   var input_field = $(calendar.inputField);
   //var input_field = _dynarch_popupCalendar.sel;
   //input_field.value = date;
   if (calendar.dateClicked) {
      if (!(typeof calendar.onUpdate == "undefined")) {
      //if (typeof calendar.onUpdate == "function") {
         //input_field.value = calendar.parametros[0];
         onUpdate(calendar, date);
      }
      input_field.value = date;
      calendar.callCloseHandler(); // this calls "onClose" (see above)  
   }
}

function onClose(calendar) {
   calendar.hide();
   // or calendar.destroy();
   //if (!(typeof calendar.onUpdate == "undefined")) {
   //   onUpdate(calendar, date);
   //}
   _dynarch_popupCalendar = null;
   //return;
}

function showCalendar(id, idbutton, format, updateFunction, showsTime, showsOtherMonths) {
   //var el = $(id);
   if (_dynarch_popupCalendar != null) {
      // we already have some calendar created
      _dynarch_popupCalendar.hide();                 // so we hide it first.
   } 
   else {
      // first-time call, create the calendar.
      var cal = new Calendar(0, null, onSelect, onClose);
      // uncomment the following line to hide the week numbers
      // cal.weekNumbers = false;
      if (typeof showsTime == "string") {
         cal.showsTime = true;
         cal.time24 = (showsTime == "24");
      }
      if (showsOtherMonths) {
         cal.showsOtherMonths = true;
      }
      _dynarch_popupCalendar = cal;    // remember it in the global var
      cal.setRange(1970, 2070);        // min/max year allowed.
      cal.create();
   }
   _dynarch_popupCalendar.setDateFormat(format);       // set the specified date format
   //_dynarch_popupCalendar.setFirstDayOfWeek(0);
   _dynarch_popupCalendar.parseDate($(id).value);      // try to parse the text in field
   //_dynarch_popupCalendar.sel = $(id);                 // inform it what input field we use
   _dynarch_popupCalendar.inputField = id;
   if(arguments.length > 3) {
      _dynarch_popupCalendar.onUpdate = updateFunction.split(".",1);
      _dynarch_popupCalendar.parametros = updateFunction.split(".").slice(1);
   }
   else {
      _dynarch_popupCalendar.onUpdate = null;
   }

   // the reference element that we pass to showAtElement is the button that
   // triggers the calendar.  In this example we align the calendar bottom-right
   // to the button.
   _dynarch_popupCalendar.showAtElement($(idbutton), "Br");        // show the calendar

   return false;
}

function checkTime(i) {
   if (i<10) {
     i="0" + i;
   }
   return i;
}

function startTime(id) {
   var x=$(id);
   var today=new Date();
   var h=today.getHours();
   var m=today.getMinutes();
   var s=today.getSeconds();
   // add a zero in front of numbers<10
   h=checkTime(h);
   m=checkTime(m);
   s=checkTime(s);
   x.innerHTML=h+":"+m+":"+s;
   t=setTimeout('startTime('+id+')',1000);
}

