// Trim
function trim(str){return str.replace(/^\s+|\s+$/g,"");}

function showErro(erro) {document.getElementById('div_erro').innerHTML = erro;}

function hideErro(){document.getElementById('div_erro').innerHTML="";}

// Busca domínios
function buscaDominios() {
  var coluna_p;
  // Página interna é a principal?
  coluna_p = document.getElementById('coluna_p').innerHTML;
  if(!coluna_p.match(/(.*)lbl_resultados(.*)/)) {
    myRequest = new ajaxObject('home.php',loading('coluna_p',1));
    myRequest.callback = function(responseText) {
      document.getElementById('coluna_p').innerHTML=responseText;
    }
    myRequest.update();
    window.setTimeout('buscaDominios()', 250);
    return false;
  }
  
  // Se a página já estiver carregada
  var palavras  = document.getElementById('palavras').value;
  var com       = document.getElementById('com').checked == 1 ? 1 : 0;
  var combr     = document.getElementById('combr').checked == 1 ? 1 : 0;
  var pref_e    = document.getElementById('pref_e').checked == 1 ? 1 : 0;
  var pref_i    = document.getElementById('pref_i').checked == 1 ? 1 : 0;
  var suf_ster  = document.getElementById('suf_ster').checked == 1 ? 1 : 0;
  var suf_online = document.getElementById('suf_online').checked == 1 ? 1 : 0;
  
  // Validação
  if(trim(palavras).length < 1 || palavras == "palavras separadas por espaço") {
    showErro('Digite ao menos uma palavra.');
    return false;
  }
  
  if(com == 0 && combr == 0) {
    showErro('Selecione alguma extensão de domínio.');
    return false;
  }
  
  if(palavras == "palavras separadas por espaço") {
    palavras = "";
  }
  
  // Apaga os erros se existirem
  hideErro();
  
  // Mostra as palavras no campo
  boxPalavras(palavras);
  
  // String de post
  var poststr = "p=" + encodeURI(palavras) + "&com=" + parseInt(com) + "&combr=" + parseInt(combr) + "&pref_e=" + parseInt(pref_e)
                + "&pref_i=" + parseInt(pref_i) + "&suf_ster=" + parseInt(suf_ster) + "&suf_online=" + parseInt(suf_online);
  
  // Faz consulta
  myRequest = new ajaxObject('bdom.php',loading('dominios_resultados'));
  myRequest.callback = function(responseText) {
    document.getElementById('dominios_resultados').innerHTML=responseText;
    palavras = "";
  }
  myRequest.update(poststr,'POST');
  
  // Desabilita e reabilita o botão de busca por alguns segundos
  desabilitaBusca();
  setTimeout(habilitaBusca, 1000);
}

function desabilitaBusca() {
  //document.getElementById('palavras').value = "";
  document.getElementById('palavras').disabled = true;
  document.getElementById('btn_pesquisar').style.color = "#999999";
  document.getElementById('btn_pesquisar').disabled = true;
}

function habilitaBusca() {
  document.getElementById('palavras').value = "palavras separadas por espaço";
  document.getElementById('palavras').disabled = false;
  document.getElementById('btn_pesquisar').style.color = "#000000";
  document.getElementById('btn_pesquisar').disabled = false;
}

function loading(divid, transp) {
var divID = document.getElementById(divid);
  if(transp == 1) {
    divID.innerHTML = "<img src=\"imagens/corpo/ajax-loader-transp.gif\" alt\"\" />";
  } else {
    divID.innerHTML = "<img src=\"imagens/corpo/ajax-loader.gif\" alt\"\" />";
  }
}

function boxPalavras(palavras) {
  // String de post
  var poststr = "p=" + encodeURI(palavras);
  
  // Faz consulta
  myRequest = new ajaxObject('lst_palavras.php',loading('palavras_texto'));
  myRequest.update(poststr,'POST');
  myRequest.callback = function(responseText) {
    document.getElementById('palavras_texto').innerHTML=responseText;
  }
  myRequest.update(poststr,'POST');
}

function limpaBusca() {
  // Faz consulta
  myRequest = new ajaxObject('limpaBusca.php');
  myRequest.update();
  
  document.getElementById('dominios_resultados').innerHTML="";
  document.getElementById('palavras_texto').innerHTML="";
}

function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.setRequestHeader("Content-Length", passData.length);
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

function delSilaba(silaba) {
  // String de post
  var poststr = "delsilaba=" + encodeURI(silaba);
  
  // Faz consulta
  myRequest = new ajaxObject('bdom.php',loading('dominios_resultados'));
  myRequest.callback = function(responseText) {
    document.getElementById('dominios_resultados').innerHTML=responseText;
  }
  myRequest.update(poststr,'POST');

  myRequest = new ajaxObject('lst_palavras.php',loading('palavras_texto'));
  myRequest.callback = function(responseText) {
    document.getElementById('palavras_texto').innerHTML=responseText;
  }
  myRequest.update(poststr,'POST');
  
}

// Função simples pra abrir links ajax
function abrirLink(pagina,divID) {
  myRequest = new ajaxObject(pagina,loading(divID,1));
  myRequest.callback = function(responseText) {
    document.getElementById(divID).innerHTML=responseText;
  }
  myRequest.update();
}

function redir_seller(seller, dominio) {
  window.open('redir_seller.php?seller='+ seller +'&dominio='+ dominio, "_blank");
}

function mostraUltimo() {
  var coluna_p;
  // Página interna é a principal?
  coluna_p = document.getElementById('coluna_p').innerHTML;
  if(!coluna_p.match(/(.*)lbl_resultados(.*)/)) {
    myRequest = new ajaxObject('home.php',loading('coluna_p',1));
    myRequest.callback = function(responseText) {
      document.getElementById('coluna_p').innerHTML=responseText;
    }
    myRequest.update();
    window.setTimeout('mostraUltimo()', 250);
    return false;
  }
  
  // Mostra as palavras
  myRequest = new ajaxObject('lst_palavras.php',loading('palavras_texto'));
  myRequest.callback = function(responseText) {
    document.getElementById('palavras_texto').innerHTML=responseText;
  }
  myRequest.update();
  
  // Mostra os domínios
  myRequest = new ajaxObject('bdom.php',loading('dominios_resultados'));
  myRequest.callback = function(responseText) {
    document.getElementById('dominios_resultados').innerHTML=responseText;
    palavras = "";
  }
  myRequest.update();
  
}

function injectPagina(divId1, divId2) {
/*
  divId1 -> Pegar desta DIV
  divId2 -> Inserir nesta DIV
*/
  divId1 = document.getElementById(divId1);
  divId2 = document.getElementById(divId2);

  divId2.innerHTML = divId1.innerHTML;
  
}