// Variável global para ser utilizada nas máscaras de objetos
var g_obj;

function paginas(tabela, pp){
  this.tabela = document.getElementById(tabela);
  this.pp = pp;
  this.pg = 1;
  this.pgs = document.getElementById(tabela+'_pg');
  this.totalRows = this.tabela.rows.length - 1;
  this.total = Math.ceil(this.totalRows/this.pp);

  this.mostraPg = function() {
    for (var i=1; i <= this.totalRows; i++){
      if (i > this.pp * this.pg || i <= this.pp * (this.pg - 1)){
        this.tabela.rows[i].style.display = 'none';
      } else {
        this.tabela.rows[i].style.display = '';
      }
    }
    this.pgs.innerHTML = "Página " +this.pg+" de "+this.total+" | "+this.totalRows+" registros encontrados";
  }

  this.next = function() {
    this.pg++;
    if (this.pg > this.total){
      this.pg = 1;
    }
    this.mostraPg();
  }
  this.prev = function() {
    this.pg--;
    if (this.pg <= 0){
      this.pg = this.total;
    }
    this.mostraPg();
  }

  this.order = function(col) {
    var rows = [];
    while(this.tabela.rows.length > 1){
      rows.push([this.tabela.rows[1].cells[col].innerHTML, this.tabela.rows[1].cloneNode(true)]);
      this.tabela.deleteRow(1);
    }
    rows.sort();
    if (document.getElementById('ordena'+col).src.match(/ordena_a.gif/)){
      rows.reverse();
    }
    for (var i=0; i < rows.length; i++){
      this.tabela.lastChild.appendChild(rows[i][1]);
    }
    this.mostraPg();

    for(i = 0; !document.getElementById('ordena'+i); i++);
    for (; document.getElementById('ordena'+i); i++){
      if (i == col){
        if(document.getElementById('ordena'+i).src.match(/ordena_a.gif/)){
          document.getElementById('ordena'+i).src='/images/ordena_d.gif';
        } else {
          document.getElementById('ordena'+i).src='/images/ordena_a.gif';
        }
      } else {
        document.getElementById('ordena'+i).src='/images/ordena_n.gif';
      }
    }
  }

  this.mostraPg();

  return true;
}

function urlencode(str) {
  str = escape(str);
  str = str.replace('+', '%2B');
  str = str.replace('%20', '+');
  str = str.replace('*', '%2A');
  str = str.replace('/', '%2F');
  str = str.replace('@', '%40');
  return str;
}

function getSelectionStart(o) {
  if (o.createTextRange) {
    var r = document.selection.createRange().duplicate()
    r.moveEnd('character', o.value.length)
    if (r.text == '') return o.value.length
    return o.value.lastIndexOf(r.text)
  } else return o.selectionStart
}

// Preenchimento de cidade/regiao de acordo com o estado
function alteraSelect(value, field){
  var uf = document.getElementById('estado').value;
  var myselect = document.getElementById(field);
  while(myselect.length) {
    myselect.remove(myselect.length-1);
  }
  if (!uf){
    try{
      myselect.add(new Option('Selecione primeiro um estado', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Selecione primeiro um estado', ''));
    }
  } else {
    if (field == 'cidade'){
      fetch('/cidades/'+uf, value, myselect);
    } else {
      fetch('/regiao.php?uf='+uf, value, myselect);
    }
  }
}
function alteraSelectDepartamento(value) {
  var cliente = document.getElementById('cliente').value;
  var myselect = document.getElementById('departamento');
  while(myselect.length) {
    myselect.remove(myselect.length-1);
  }
  if (!cliente){
    try{
      myselect.add(new Option('Todos', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Todos', ''));
    }
  } else {
    fetch('/departamentos.php?cliente='+cliente, value, myselect);
  }
}

// INSERIDO POR MÔNICA PARA LINKAR TIPO DE CONTATO A CARGO

function alteraSelectCargo(value, id) {
  var tipo = document.getElementById('tipo'+id).value;
  var myselect = document.getElementById('cargo'+id);
  while(myselect.length) {
    myselect.remove(myselect.length-1);
  }
  if (!tipo){
    try{
      myselect.add(new Option('Todos', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Todos', ''));
    }
  } else {
    fetch('/cargos.php?tipo='+tipo, value, myselect);
  }
}

// FIM DA INSERÇÃO MÔNICA

// INSERIDO POR MÔNICA PARA LINKAR ENTREVISTADO A TEMA EM ENTREVISTAS AO VIVO

var alteraSelectTemaEmUso = false;

function alteraSelectTema(value, id_entrevistadoev) {
  if(alteraSelectTemaEmUso){
    setTimeout("alteraSelectTema('"+value+"', "+id_entrevistadoev+")", 100);
  } else {
    alteraSelectTemaEmUso = true;
    var tipo = document.getElementById('entrevistadoev').value;
    var myselect = document.getElementById('tema');
    while(myselect.length) {
      myselect.remove(myselect.length-1);
    }
    if (!tipo){
      try{
        myselect.add(new Option('Todos', ''), null);
      } catch(e) { //in IE, try the below version instead of add()
        myselect.add(new Option('Todos', ''));
      }
    } else {
      fetch('/entrevistadotema.php?id_entrevistadoev='+id_entrevistadoev, value, myselect);
    }
  }
}


// FIM DA SEGUNDA INSERÇÃO MÔNICA


function alteraSelectEntrevistado() {
  var data_emissao = document.getElementById('data_emissao').value;
  var myselect = document.getElementById('entrevistado');
  while(myselect.length) {
    myselect.remove(myselect.length-1);
  }
  if (!data_emissao){
    try{
      myselect.add(new Option('Todos', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Todos', ''));
    }
  } else {
    fetch('/dataentrevistados.php?data_emissao='+data_emissao, '', myselect);
  }
}


function alteraSelectPrograma(i, value) {
  var emissora = document.getElementById('emissora'+i).value;
  var myselect = document.getElementById('id_programa'+i);
  while(myselect.length) {
    myselect.remove(myselect.length-1);
  }
  if (!emissora){
    try{
      myselect.add(new Option('Selecione', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Selecione', ''));
    }
  } else {
    fetch('/programas.php?emissora='+escape(emissora)+"&rand="+Math.random(), value, myselect);
  }
}
function fetch(url, value, myselect) {
  var http;
  try {
    http = new XMLHttpRequest();
  }
  catch(e) {
    http = new ActiveXObject("Microsoft.XMLHTTP");
  }
  http.onreadystatechange = function() {
    if(http.readyState == 4) {
      if(http.status == 200) {
        preenche(http.responseText, value, myselect);
      }
    }
  };
  http.open('GET', url, true);
  http.send(null);
}
function alteraCidadeERegiao(cidade, regiao) {
  alteraSelect(cidade, 'cidade');
  alteraSelect(regiao, 'regiao');
}
function alteraCidade(cidade){
  alteraSelect(cidade, 'cidade');
}
function preenche(texto, value, myselect){
  var valores = texto.split("\n");
  if (value == 'departamento'){
    try{
      myselect.add(new Option('Todos', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Todos', ''));
    }
  } else {
    try{
      myselect.add(new Option('Selecione', ''), null);
    } catch(e) { //in IE, try the below version instead of add()
      myselect.add(new Option('Selecione', ''));
    }
  }
  var aux = new Array();
  for (var i = 0; i < valores.length; i++){
    if (valores[i]){
      if (valores[i].match(/\|/)){
        aux = valores[i].split("|");
      } else {
        aux[0] = valores[i];
        aux[1] = valores[i];
      }
      try{
        myselect.add(new Option(aux[1], aux[0]), null);
      } catch(e) { //in IE, try the below version instead of add()
        myselect.add(new Option(aux[1], aux[0]));
      }
      if (value == aux[0]){
        myselect.options[myselect.length - 1].selected = true;
      }
    }
  }
  alteraSelectTemaEmUso = false;
}
// Fim preenchimento de cidade/regiao de acordo com o estado

function setMicrorregiao() {
  var estado = document.getElementById("estado").value;
  var cidade = urlencode(document.getElementById("cidade").value);

  var http;
  try {
    http = new XMLHttpRequest();
  }
  catch(e) {
    http = new ActiveXObject("Microsoft.XMLHTTP");
  }
  http.onreadystatechange = function() {
    if(http.readyState == 4) {
      if(http.status == 200) {
        document.getElementById("regiao").value=http.responseText;
      }
    }
  };
  http.open('GET', "/microregiao.php?cidade="+cidade+"&estado="+estado, true);
  http.send(null);
}

var nome_dia = new Array ('Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado');
var nome_mes = new Array ('Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');

function data_por_extenso(hoje) {
  var dia = nome_dia[hoje.getDay()];
  var dia_do_mes=hoje.getDate();
  var mes = nome_mes[hoje.getMonth()];
  var ano = hoje.getYear();
                              
  if (ano < 200) {
    var ano = ano + 1900;
  }
  var xyz = dia + ', ' + dia_do_mes + ' de ' + mes + ' de ' + ano;
  return xyz;
}
function showHide(obj, img){
  obj = document.getElementById(obj);
  img = document.getElementById(img);
  if (obj.style.display == 'none'){
    obj.style.display = '';
    img.src="/images/fecha.gif";
  } else {
    obj.style.display = 'none';
    img.src="/images/abre.gif";
  }
}

function fazFone(campo, e) {
  var cod="";
  if(document.all) {cod=event.keyCode;} else {cod=e.which;}

  if (cod == 0 || cod == 8 || cod == 9 || cod == 46){
    return true;
  }

  setTimeout(function(){ 
	  mascaraFone(campo);
	}, 50);
  return true;
}
function mascaraFone(campo) {
  var valor = campo.value.replace(/[^0-9]/g, "");
  if (valor.length > 10) {
    valor = valor.replace(/([0-9]{2})([0-9]{4})([0-9]{4})([0-9]*)/, "($1) $2-$3 r. $4");
  } else if (valor.length >= 6){
    valor = valor.replace(/([0-9]{2})([0-9]{4})([0-9]{0,4}).*/, "($1) $2-$3");
  } else if (valor.length >= 2){
    valor = valor.replace(/([0-9]{2})([0-9]*)/, "($1) $2");
  } else if (valor.length > 0){
    valor = valor.replace(/([0-9]*)/, "($1");
  }
  campo.value = valor;
}
function checaFone(campo) {
  if (campo.value && !campo.value.match(/^\([0-9]{2}\) [0-9]{4}-[0-9]{4}$/) && !campo.value.match(/^\([0-9]{2}\) [0-9]{4}-[0-9]{4} r. [0-9][0-9]*$/)){
    campo.style.backgroundColor = "#CA0101";
    campo.style.color = "#FFFFFF";
    campo.focus();
  } else {
    campo.style.backgroundColor = "#FFFFFF";
    campo.style.color = "#000000";
  }
}

function fazData(campo,e){
  var cod="";
  if(document.all) {cod=event.keyCode;} else {cod=e.which;}
  if ((cod < 47 || cod > 58) && cod != 08 && cod != 0 && cod != 9 && cod != 32){
    cod=0;
    campo.focus(); return false;
  } else if (cod == 08) { //backspace
    campo.value = '';
  } else if (cod == 47) { //slash
    if (campo.value.length == 1) {
      campo.value = 0+campo.value;
    } else if (campo.value.length == 4) {
      campo.value = campo.value.substr(0, 3)+0+campo.value.substr(3, 1);
    } else if (campo.value.length != 2 && campo.value.length != 5){
      cod=0;
      campo.focus(); return false;
    }
  } else if (cod == 58) { // :
    if (campo.value.length < 12 || campo.value.length > 13) {
      cod=0;
      campo.focus(); return false;
    } else if (campo.value.length == 12) {
      campo.value = campo.value.substr(0, 11)+0+campo.value.substr(11, 1);
    }
  } else if (cod == 32) { // space
    if (campo.value.length == 8){
      campo.value = campo.value.substr(0, 6)+'20'+campo.value.substr(6, 2);
    } else if (campo.value != 10) {
      cod=0; campo.focus(); return false;
    }
  } else {
    if (campo.value.length == 2 || campo.value.length == 5){
      campo.value = campo.value+'/';
    } else if (campo.value.length == 10) {
      campo.value = campo.value+' ';
    } else if (campo.value.length == 13) {
      campo.value = campo.value+':';
    }
  }
  if (campo.value.length == 3){
    if (campo.value.substr(0,2) < 1 || campo.value.substr(0,2) > 31){
      alert ("A data deve ser no formato dd/mm/aaaa hh:mm");
      campo.value = '';
      cod=0;
      campo.focus(); return false;
    }
  }
  if (campo.value.length == 6){
    if (campo.value.substr(3,2) < 1 || campo.value.substr(3,2) > 12){
      alert ("A data deve ser no formato dd/mm/aaaa hh:mm");
      campo.value = '';
      cod=0;
      campo.focus(); return false;
    }
  }
  return true;
}
function checaData(obj){
  if (obj.value.length == 16){
    var data = new Date(obj.value.substr(6,4), parseInt(obj.value.substr(3,2), 10)-1, obj.value.substr(0,2), obj.value.substr(11,2), obj.value.substr(14,2));
    if (parseInt(obj.value.substr(14,2), 10) != data.getMinutes()){
      alert("Erro nos minutos digitados");
      obj.focus();
    } else if (parseInt(obj.value.substr(11,2), 10) != data.getHours()){
      alert("Erro na hora digitada");
      obj.focus();
    } else if (parseInt(obj.value.substr(0,2), 10) != data.getDate()){
      alert ("Erro no dia digitado");
      obj.focus();
    } else if (parseInt(obj.value.substr(3,2), 10)-1 != data.getMonth()){
      alert ("Erro no mês digitado: " + i);
      obj.focus();
    } else if (parseInt(obj.value.substr(6,4), 10) != data.getFullYear()){
      alert ("Erro no ano digitado");
      obj.focus();
    } else {
      obj.style.background = "#FFFFFF";
    }
  } else if(obj.value.length != 0) {
    obj.style.background = "#FF0000";
    obj.focus();
  } else {
    obj.style.background = "#FFFFFF";
  }
}

function mascara(obj, e, func) {
  var cod = (window.Event) ? e.which : e.keyCode;
  g_obj = obj;
  if (cod != 8 && cod != 46 && cod > 0) setTimeout(func+"(g_obj)", 1);
  return true;
}
function mascaraDuracao(obj){
  var txt = obj.value.replace(/[^0-9]/g, "");
  // remove os "0" iniciais
//  txt = parseInt(txt) + "";
//  while (txt.length < 3) txt = '0'+txt;
  if (txt.length > 0) txt += '"';
  if (txt.length > 3) txt = txt.substr(0, txt.length - 3) + "'" + txt.substr(txt.length - 3, 3);
  obj.value = txt;
}

function showHideDir(i) {
  var obj = document.getElementById('dired'+i);
  var img = document.getElementById('dired_img'+i);
  if (obj.style.display == 'none') {
    obj.style.display = "";
    img.src = "/images/download_up.gif";
  } else {
    obj.style.display = "none";
    img.src = "/images/download_off.gif";
  }
}

function copiaRetrancas(retranca, retranca_cliente, copiaRetranca) {
  if (copiaRetranca) retranca_cliente.value = retranca.value;
}

function copiaClientes(cliente, departamento, copiaCliente) {
  if (copiaCliente) departamento.value = cliente.value;
}

function getElementsByClass(searchClass,node,tag) {
  var classElements = new Array();
  if ( node == null ) node = document;
  if ( tag == null ) tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( pattern.test(els[i].className) ) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

function marcaAll(){
  var main = document.getElementById('chkMain');
  var cks = getElementsByClass('checkMarca', document, 'input');
//  alert(main);
  for (var i=0; i < cks.length; i++){
    cks[i].checked = main.checked;
  }
}

Array.prototype.in_array = function(p_val) {
  for(var i = 0; i < this.length; i++) {
    if(this[i] == p_val) {
      return true;
    }
  }
  return false;
}

// Clientes auto-preenchimento

function fechaCliente(){
  setTimeout("fechaClienteAgora()", 300);
}
function fechaClienteAgora(){
  var obj = document.getElementById('auxCli');
  obj.innerHTML = '';
  obj.style.display = 'none';
}

function abreCliente(){
  setTimeout("opcoesCliente()", 1);
}

function opcoesCliente(){
  var cliente = document.getElementById('cliente').value;
  if (cliente.length > 0){
    fetchCliente(cliente);
  } else {
    fechaCliente();
  }
}

function fetchCliente(cliente) {
  var http;
  try {
    http = new XMLHttpRequest();
  } catch(e) {
    http = new ActiveXObject("Microsoft.XMLHTTP");
  }
  http.onreadystatechange = function() {
    if(http.readyState == 4) {
      if(http.status == 200) {
        var valor = http.responseText;
        if (valor.length > 0){
          var obj = document.getElementById('auxCli');
          obj.style.display = '';
          obj.innerHTML = "";
          var valores = valor.split("\n");
          var obj = document.getElementById('auxCli');
          for (var i = 0; i < valores.length; i++){
            if (valores[i].length > 0)
              obj.innerHTML += "<div style=\"padding: 3px; cursor: pointer;\" onMouseOver=\"overCliente(this);\" onMouseOut=\"outCliente(this);\" onClick=\"clickCliente(this);\">"+valores[i]+"</div>";
          }
        }
      }
    }
  };
  http.open('GET', "/clientes.php?cliente="+cliente, true);
  http.send(null);
}

function overCliente(obj){
  obj.style.backgroundColor='#447BCD';
  obj.style.color='#FFFFFF';
}
function outCliente(obj){
  obj.style.backgroundColor='#FFFFFF';
  obj.style.color='#000000';
}
function clickCliente(obj) {
  document.getElementById('cliente').value = obj.innerHTML;
}

Array.prototype.inArray = function (value){
  // Returns true if the passed value is found in the
  // array. Returns false if it is not.
  for (var i=0; i < this.length; i++) {
    if (this[i] === value) {
      return true;
    }
  }
  return false;
}

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

