// Variavel que define se pode expandir o livro/autor no catálogo
var podeAbrir = true;

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.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();
    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++){
      if (i == col){
        document.getElementById('ordena'+i).src='/images/ordena_a.gif';
      } else {
        document.getElementById('ordena'+i).src='/images/ordena_n.gif';
      }
    }
  }

  this.mostraPg();

  return true;
}

function meuShow(obj){
  document.getElementById(obj).style.display = '';
}
function meuHide(obj){
  document.getElementById(obj).style.display = 'none';
}
function showHide(obj){
  obj = document.getElementById(obj);
  if (obj.style.display == 'none'){
    obj.style.display = '';
  } else {
    obj.style.display = 'none';
  }
}

var buscaLivros = new Array();

function buscaLivrosAdd(cod){
  buscaLivros.push(cod);
}

function buscaExpande(cod, cor){
  var flecha = document.getElementById('busca_flecha_'+cod);
  var obj = document.getElementById('top_'+cod);

//  document.getElementById('conteudo_'+cod).style.display='';
  if ($('conteudo_'+cod).style.display=='none'){
    Effect.SlideDown('conteudo_'+cod, { duration: 0.5 });
  }
  obj.style.borderLeft = "solid 6px #"+cor;
  flecha.src = "imagens/busca_flecha_down.gif?cor="+cor;
}
function buscaComprime(cod, cor){
  var flecha = document.getElementById('busca_flecha_'+cod);
  var obj = document.getElementById('top_'+cod);

//  document.getElementById('conteudo_'+cod).style.display='none';
  if ($('conteudo_'+cod).style.display==''){
    Effect.SlideUp('conteudo_'+cod, { duration: 0.5 });
  }
  obj.style.borderLeft = "solid 6px #E6E6E6";
  flecha.src = "imagens/busca_flecha_right.gif?cor=cdcdcd";
}

function buscaEspandeTodos(cor){
  for (var i = 0; i < buscaLivros.length; i++){
    buscaExpande(buscaLivros[i], cor);
  }
}
function buscaComprimeTodos(cor){
  for (var i = 0; i < buscaLivros.length; i++){
    buscaComprime(buscaLivros[i], cor);
  }
}

function buscaIcon(obj, cor, texto, im, td){
  obj.src = "imagens/"+im+".gif?cor="+cor;
  document.getElementById(td).innerHTML = texto;
}

function buscaOver(cod, cor){
  var obj = document.getElementById('top_'+cod);
  obj.style.background='#F2F2F2';
  if (document.getElementById('conteudo_'+cod).style.display){
    var flecha = document.getElementById('busca_flecha_'+cod);
    flecha.src = "imagens/busca_flecha_right.gif?cor="+cor;
  }
}

function buscaOut(cod){
  var obj = document.getElementById('top_'+cod);
  obj.style.background='#FFFFFF';
  if (document.getElementById('conteudo_'+cod).style.display){
    var flecha = document.getElementById('busca_flecha_'+cod);
    flecha.src = "imagens/busca_flecha_right.gif?cor=cdcdcd";
  }
}

function buscaClick(cod, cor){
  if (podeAbrir) {
    if (document.getElementById('conteudo_'+cod).style.display){
      buscaExpande(cod, cor);
    } else {
      buscaComprime(cod, cor);
    }
  } else {
    podeAbrir = true;
  }
}

function getSelection(inputBox) {
  if ("selectionStart" in inputBox) {
    return {
      start: inputBox.selectionStart,
      end: inputBox.selectionEnd
    }
  }

  //and now, the blinkered IE way
  var bookmark = document.selection.createRange().getBookmark()
  var selection = inputBox.createTextRange()
  selection.moveToBookmark(bookmark)

  var before = inputBox.createTextRange()
  before.collapse(true)
  before.setEndPoint("EndToStart", selection)

  var beforeLength = before.text.length
  var selLength = selection.text.length

  return {
    start: beforeLength,
    end: beforeLength + selLength
  }
}

// Início das funções rollover do bookmenu
function imgOver(img) {
  var imagem = img.src.match(/\/[^\/]*$/);
  img.src = "/imagens" + imagem;
}

function imgOut(img) {
  var imagem = img.src.match(/\/[^\/]*$/);
  img.src = "/images" + imagem;
}
// Fim das funções rollover do bookmenu

function checaEmail(obj) {
  httpGet("/checaEmail.php?email="+obj.value, "respChecaEmail");
}

function enviaSenha(){
  httpGet("/mandaSenha.php?email="+$('email_esqueceu').value, "respEmail");
}

function httpGet(url, dest) {
  var http;
  try {
    http = new XMLHttpRequest();
  }
  catch(e) {
    http = new ActiveXObject("Microsoft.XMLHTTP");
  }
  http.onreadystatechange = function() {
    if(http.readyState == 4) {
      if(http.status == 200) {
        $(dest).innerHTML = http.responseText;
      }
    }
  };
  http.open('GET', url, true);
  http.send(null);
}

// Início de funções de preenchimento de cidade
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 preenche(texto, value, myselect){
  var valores = texto.split("\n");
  try{
    myselect.add(new Option('Selecione', ''), null);
  } catch(e) { //in IE, try the below version instead of add()
    myselect.add(new Option('Selecione', ''));
  }
  for (var i = 0; i < valores.length; i++){
    if (valores[i]){
      try{
        myselect.add(new Option(valores[i], valores[i]), null);
      } catch(e) { //in IE, try the below version instead of add()
        myselect.add(new Option(valores[i], valores[i]));
      }
      if (value == valores[i]){
        myselect.options[myselect.length - 1].selected = true;
      }
    }
  }
}

function alteraCidade(cidade){
  alteraSelect(cidade, 'cidade');
}

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);
    }
  }
}
// Fimm das funções de preenchimento de cidade

// Inicio das funções de Palavra do leitor
function mostra_pl(dd){
  var min_nota = document.getElementById('pl_nota').value;
  var obj_pg = document.getElementById('pl_pg');
  var atual = obj_pg.selectedIndex;
  atual += dd;
  if (atual < 0) atual = obj_pg.options.length-1;
  else if(atual >= obj_pg.options.length) atual = 0;
  obj_pg.selectedIndex = atual;
  var pg = obj_pg.value;
  var total = 0;
  for (var i = 1; i < nota.length; i++){
    if (nota[i] >= min_nota) {
      total++;
      if (total <= pp * pg && total > pp * (pg-1)){
        document.getElementById('pl_'+i).style.display = "";
      } else {
        document.getElementById('pl_'+i).style.display = "none";
      }
    } else {
      document.getElementById('pl_'+i).style.display = "none";
    }
  }
}
function reseta_nota(){
  var min_nota = document.getElementById('pl_nota').value;
  var total = 0;
  for (var i = 1; i <= nota.length; i++){
    if (nota[i] >= min_nota) {
      total++;
    }
  }
  var obj = document.getElementById('pl_pg');
  obj.options.length = 0;
  var pgs = Math.ceil(total/pp);
  var aux;
  for (i = 1; i <= pgs; i++){
    if (i < 10) aux = '0'+i+'/';
    else aux = i+'/';
    if (pgs < 10) aux += '0';
    aux += pgs;
    obj.options[obj.options.length] = new Option (aux, i);
  }
  mostra_pl(0);
}
function altNota(i, id, val){
  var http = new Image();
  http.src = "/altNota.php?id="+id+"&val="+val;
  if (val == 1) {
    nota[i]++;
  } else if (val == -1) {
    nota[i]--;
  }
  var cor = '3f983e';
  if (nota[i] <= 0) cor = '8c8c8c';
  document.getElementById('nota'+i).src = "/botoes/"+nota[i]+".gif?cor="+cor;
}
// Fim das funções de Palavra do leitor

// Funções do menu livro/autor
function alteraFavorito(img, cod) {
  var http = new Image();
  if (img.src.match(/estrela_on/)) {
    http.src = "/favorito.php?codigo="+cod+"&favorito=N&random="+Math.random();
    img.src="/images/estrela.gif";
  } else {
    http.src = "/favorito.php?codigo="+cod+"&favorito=S&random="+Math.random();
    img.src="/images/estrela_on.gif";
  }
}
// Fim Funções do menu livro/autor

// Função para abrir nova janela de carrinho
function openwdwVenda(isbn, macao){
  var winX = 780;
  var winY = 700;
  var chamada="https://paravola.kinghost.net/~paginaviva-ecommerce/lojas/CIA_LETRAS/carrinho.cfm?id_ProdutoLoja="+isbn+"&macao="+macao;
  var janela_inferface = window.open(chamada,"LojaVenda","toolbar=no,directories=no,menubar=no, scrollbars=yes,status=no,width="+winX+", height="+winY+",left=0, right=0");
  janela_inferface.focus();
}
// Fim da função para abrir nova janela de carrinho

function limpaSel(obj, str, strs) {
  for (var i = 0; i < $(obj).options.length; i++){
    $(obj).options[i].selected = false;
  }
  alteraSel(obj, str, strs);
}

function alteraSel(obj, str, strs) {
  var conta = 0;
  for (var i = 0; i < $(obj).options.length; i++){
    if ($(obj).options[i].selected) conta++;
  }
  if (conta == 1) {
    $('itens_'+obj).innerHTML = "1 "+str+" selecionado";
  } else {
    $('itens_'+obj).innerHTML = conta+" "+strs+" selecionados";
  }
}

function showHideBA() {
  if($('todosGeneros')) {
    $('todosGeneros').style.display='none';
  }
  if ($('busca_avancada').style.display=='none') {
    Effect.SlideDown('busca_avancada');
    $('flecha_ba').src='/imagens/flecha_cabecalho_up.gif';
  } else {
    Effect.SlideUp('busca_avancada');
    $('flecha_ba').src='/imagens/flecha_cabecalho_down.gif';
  }
  if ($('homeDefaultPosition')){
    homeAjustaDestaque();
  }
}

var mySelectID = 0;
function mySelect(nome, titulos, w){
  if (!Prototype.Browser.IE) w -= 22;
  mySelectID++;
  document.write('<div class="mySelect mouseLink" id="mySelectID'+mySelectID+'" style=\"width: '+w+'px;\" onClick="showHideMySelect('+mySelectID+')">'+nome+'</div>');
  document.write('<div id="mySelectListID'+mySelectID+'" class="mySelectList">');
  titulos.each(function(pair) {
    document.write('<a href="/detalhe.php?codigo='+pair.key+'" class="mySelectHref">'+pair.value+'</a>');
  });
  document.write('</div>');
}
function showHideMySelect(id) {
  if ($('mySelectListID'+id).style.display == 'block'){
    $('mySelectListID'+id).style.display='none';
  } else {
    $('mySelectListID'+id).style.display='block';
  }

  if (Prototype.Browser.IE) {
    var antHeight = $('mySelectListID'+id).getHeight();
    var antWidth = $('mySelectListID'+id).getWidth();
    $('mySelectListID'+id).style.width = 300;
    while (antHeight >= $('mySelectListID'+id).getHeight()){
      antWidth = $('mySelectListID'+id).getWidth();
      antHeight = $('mySelectListID'+id).getHeight();
      $('mySelectListID'+id).style.width = antWidth - 20;
    }
    $('mySelectListID'+id).style.width = antWidth + 1;
    if ($('mySelectListID'+id).getHeight() > 400) {
      $('mySelectListID'+id).style.height = 400;
      $('mySelectListID'+id).style.width = antWidth + 5;
    }
  }

  $('mySelectListID'+id).style.left = $('mySelectID'+id).cumulativeOffset().left + $('mySelectID'+id).getWidth() - $('mySelectListID'+id).getWidth();
  $('mySelectListID'+id).style.top = $('mySelectID'+id).cumulativeOffset().top - $('mySelectListID'+id).getHeight() - 10;
}


function alteraCidadeDistribuidor(cidade){
  alteraSelect(cidade, 'cidade');
}
