/**
 * Função abre/fecha para as dicas
 */
 function abreFecha()
 {
	var conteudo = "dicasConteudo";
	var links = "dicasLink";
	var textoAntigo = document.getElementById(links).innerHTML.substr(3);
	 
	if (document.getElementById(conteudo).style.display=='block')
	   {
		document.getElementById(conteudo).style.display='none';
		document.getElementById(links).innerHTML = "[+] " + textoAntigo;
		}
	else{
		document.getElementById(conteudo).style.display='block';
		document.getElementById(links).innerHTML = "[-] " + textoAntigo;
		}
}
 function abreFechaImportante()
 {
	var conteudo = "importanteConteudo";
		
	if (document.getElementById(conteudo).style.display=='block')
		document.getElementById(conteudo).style.display='none';
	else
		document.getElementById(conteudo).style.display='block';
}

/**
 *
 */
function oninputfocus(e) 
{
  if (typeof e == 'undefined') 
  {
    var e = window.event;
  }
  
  var source;
  
  if (typeof e.target != 'undefined') 
  {
    source = e.target;
  } 
  else 
  {
    if (typeof e.srcElement != 'undefined') 
    {
      source = e.srcElement;
    } 
    else 
    {
      return;
    }
  }
   
  if ((source.style!='undefined') && (source.type != 'radio') && (source.type != 'checkbox'))
    source.style.backgroundColor='#FFFFFF';
}

/**
 *
 */
function oninputblur(e) 
{
  if (typeof e == 'undefined') 
  {
    var e = window.event;
  }
  
  var source;
  
  if (typeof e.target != 'undefined') 
  {
    source = e.target;
  } 
  else if (typeof e.srcElement != 'undefined') 
  {
    source = e.srcElement;
  } 
  else 
  {
    return;
  }
  
  if ((source.style!='undefined') && (source.type != 'radio') && (source.type != 'checkbox'))
    source.style.backgroundColor='#E4E4E4';
} 

/**
 *
 */
function mudaFocoProximo(el)
{
  if (el.value.length < el.getAttribute('maxlength')) return;

  var f = el.form;
  var els = f.elements;
  var x, nextEl;
  
  for (var i=0, len=els.length; i<len; i++)
  {
    x = els[i];
    
    if (el == x && (nextEl = els[i+1]))
    {
      if (nextEl.focus) nextEl.focus();
    }
  }
}

/**
 * 
 */
function mascaraData(campo, e)
{
  var mydata = ''; 
  var data = campo.value;
  var cod="";
  mydata = mydata + data; 

  if (document.all) 
  {
    cod = event.keyCode;
  } 
  else 
  {
    cod = e.which;
  }
  
  if ((cod == 0) || (cod == 8) || (cod == 13)) // Para o Mozilla
    return;
    
  if (cod < 48 || cod > 57)
  {
    cod = 0;
    campo.focus(); 
    return false;
  }
  
  if (mydata.length == 2)
  { 
    mydata = mydata + '/'; 
    campo.value = mydata; 
  } 
  
  if (mydata.length == 5)
  { 
    mydata = mydata + '/'; 
    campo.value = mydata; 
  }
}

/*
 * As funções a seguir são copias das existentes no projeto SelicIOS
 * Futuramente deverá existir um arquivo .js comum à todos os projetos RTM, assim como arquivo .css
 */

/**
 * ====================
 * PopUp(url, largura, altura, ComplWindowFeatures) - abre uma janela blank sem toolbar como default podendo passar como parametro
 * ====================
 *   parâmetros: url = local ou relativo
 *               largura = em pixel
 *               altura = em pixel
 *               ComplWindowFeatures = YES ou NO para "status, toolbar, menubar e/ou scrollbars"
 *   ex: PopUp("teste.html",300,200,"toolbar=yes")
 *
 */
function PopUp(as_url, ai_width, ai_height, as_ComplWindowFeatures)
{
  IE = (document.all) ? true : false;

  li_tilt_up = (IE ? 40 : 20)

  /** para ai_width=0 ou nulo e ai_height=0 ou nulo "seta" o tamanho para o maior possível da resolução */

  ai_width = ((ai_width  == null) || (ai_width  == 0) ? screen.width - screen.width * 0.1 : ai_width)
  ai_height = ((ai_height == null) || (ai_height == 0) ? screen.height - screen.height * 0.2 : ai_height)

  /** FIM - para ai_width=0 ou nulo e ai_height=0 ou nulo seta o tamanho para o maior possível da resolução */

  var li_LeftPos = (screen.availWidth) ? (screen.availWidth - ai_width) / 2 : 0;
  var li_TopPos  = (screen.availHeight) ? (screen.availHeight - ai_height) / 2 - li_tilt_up : 0;
  var as_DefaultWindowFeatures = 'width=' + ai_width + ',height=' + ai_height + ',top=' + li_TopPos + ',left=' + li_LeftPos + ',resizable=yes,dependent=no';

  // assume defaults de "Window Features"
  as_ComplWindowFeatures = ((as_ComplWindowFeatures == null) ? '' : as_ComplWindowFeatures.toLowerCase());

  if ((',' + as_ComplWindowFeatures + ',').search(',status=') == -1)  { as_DefaultWindowFeatures += ',status=yes'  }
  if ((',' + as_ComplWindowFeatures + ',').search(',toolbar=') == -1) { as_DefaultWindowFeatures += ',toolbar=no'  }
  if ((',' + as_ComplWindowFeatures + ',').search(',menubar=') == -1) { as_DefaultWindowFeatures += ',menubar=yes' }
  if ((',' + as_ComplWindowFeatures + ',').search(',scrollbars=') == -1) { as_DefaultWindowFeatures += ',scrollbars=yes' }

  as_DefaultWindowFeatures += ',' + as_ComplWindowFeatures

  var lw_handle_popup = open(as_url, 'Popup', as_DefaultWindowFeatures)

  lw_handle_popup.focus()
}

/**
 * Destaca os campos referentas as tags de erros.
 */
function destacaCampos(campos)
{
  var listaCampos = new Array();
  var temp;
  listaCampos = campos.split(",");

  for (i=0;i<listaCampos.length;i++)
  {
    var temp = new String(listaCampos[i]);
    if (document.getElementById(temp) != null)
    {
      document.getElementById(temp).style.color="#990000";
    }
  }
}

/**
 * Objeto que armazena as posições inicial e final do cursor do teclado
 *  em uma caixa de texto.
 */
function CaretPosition()
{
  var start = null;
  var end = null;
}

/**
 * Obtem as posições inicial e final do cursor do teclado em uma caixa de texto.
 * OBS: Se existe parte do texto selecionada, a posição final será maior que a inicial.
 */ 
function getCaretPosition(field)
{
  // Initialise the CaretPosition object
  var caretPos = new CaretPosition();

  // IE support
  if (document.selection)
  {
    // Focus on the text box
    field.focus();

    // This returns us an object containing
    // information about the currently selected text
    var sel = document.selection.createRange();

    // Find out the length of the selected text
    // (you'll see why below)
    var selectionLength = sel.text.length;
    
    // Move the selection start to 0 position.
    //
    // This is where it gets interesting, and this is why
    // some have claimed you can't get the caret positions
    // in IE.
    //
    // IE has no 'selectionStart' or 'selectionEnd' property,
    // so we can not get or set this value directly. We can
    // only move the caret positions relative to where they
    // currently are (this should make more sense when you read
    // the next line of code).
    //
    // Note, that even though we have moved the start
    // position on our object in memory, this is not reflected
    // in the browser until we call sel.select() (which we're
    // not going to do here).
    //
    // Also note, the start position will never be a negative
    // number, no matter how far we try to move it back.
    sel.moveStart('character', -field.value.length);
 
    // This is where it should start to make sense. We now know
    // our start caret position is the length of the currently
    // selected text minus the original selection length
    // (think about it).
    caretPos.start = sel.text.length - selectionLength;

    // Since the start of the selection is at the start of the
    // text, we know that the length of the selection is also
    // the index of the end caret position.
    caretPos.end = sel.text.length;
  }
  // Firefox support
  else if (field.selectionStart || field.selectionStart == '0')
  {
    // This is a whole lot easier in Firefox
    caretPos.start = field.selectionStart;
    caretPos.end = field.selectionEnd;
  }

  // Return results
  return caretPos;
}

/**************************************************************************
 * Rotinas para formatação de campos numéricos.
 **************************************************************************/

/**
 * Permite a entrada apenas de sinais(+ ou - na posição 0), vírgula e
 *  dígitos, enquanto não ultrapassar os tamanhos das partes inteira e 
 *  decimal recebidas como parâmetros. Para números inteiros, utilize 
 *  o parâmetro numDec igual 0.
 */
function filtraTeclasNumero(campo, event, numInt, numDec, aceitaSinal)
{
  var caretPos = getCaretPosition(campo);
  var posVirgula = campo.value.indexOf(",");

  // Obtendo o caracter pressionado.
  if (document.all)
    cod = event.keyCode;
  else 
    cod = event.which;

  // Verificando se o caracter pressionado é um dos caracteres especiais para o Mozilla: del, esc, setas, etc.
  if ((cod == 0) || (cod == 8))
    return true;
  
  // Verificando se o caracter pressionado é um enter.
  if (cod == 13)
  {
    mascaraValor(campo, numInt, numDec, aceitaSinal);
    return true;
  }
  
  // Verificando se o caracter pressionado é uma vírgula. Se não há uma vírgula já digitada no campo e 
  // o campo permitir números decimais (numDec > 0), esta será aceita.
  if (cod == 44)  
    return ((numDec > 0) && ((posVirgula == -1) || ((posVirgula >= caretPos.start) && (posVirgula < caretPos.end)))); // Se permite casas decimais e é a primeira vírgula.

  // Verificando se o caracter pressionado é um sinal de '+' ou '-'. Se não há um sinal já digitado e 
  // se o campo permitir sinal e este estiver sendo digitado na primeira posição, ele será aceito.
  if ((cod == 43) || (cod == 45))
  {
    existeSinal = (((campo.value.charAt(0) == '+') || (campo.value.charAt(0) == '-')) && 
     ((caretPos.start > 0) || ((caretPos.start == 0) && (caretPos.end == 0))));

    return ((aceitaSinal) && (!existeSinal) && (caretPos.start == 0));
  }
  
  // Verificando se o caracter pressionado não é um dígito. 
  if (cod < 48 || cod > 57)
    return false;

  // Caso seja um dígito e o tamanho do número ainda não ultrapassou os limites dos tamanhos passados 
  // como parâmetro (numInt e numDec), este deverá ser aceito. 
  if ((caretPos.start == caretPos.end) &&
      (((posVirgula >= 0) && (caretPos.start > posVirgula) && (totalDigitos(campo.value.substring(posVirgula)) >= numDec)) ||
       (totalDigitos(campo.value) >= numInt + numDec)))
    return false;
  
  return true; 
}

/**
 * Formata um campo segundo um valor número. Para números inteiros, utilize 
 *  o parâmetro numDec igual 0.
 */
function formataCampoNumero(campo, numInt, numDec, aceitaSinal)
{
  if (campo.value.length > 0)
  {
    var novoValor = formataNumero(campo.value, numInt, numDec, aceitaSinal);
    
    if (campo.value != novoValor)
    {
      campo.value = novoValor;
      return true;
    }  
  }

  return false;
}

/**
 * Formata um valor segundo um número. Para números inteiros, utilize 
 *  o parâmetro numDec igual 0.
 */
function formataNumero(valor, numInt, numDec, aceitaSinal)
{
  var novoValor = retiraCaractersAlfaNumerico(valor, numInt, numDec, aceitaSinal);
    
  if (novoValor.length > 0)
  {
    // Verificando se existe sinal e retirando-o do número a ser formatado.
    var sinal = (((novoValor.charAt(0) == '-') || (novoValor.charAt(0) == '+')) ? novoValor.charAt(0): "");
  
    if (sinal.length > 0)
      novoValor = novoValor.substring(sinal.length); 

    // Verificando se existe vígula e retirando-o do número a ser formatado.
    var posVirgula = novoValor.indexOf(",");
    var exiteVirgula = (posVirgula >= 0);

    if (exiteVirgula)
      novoValor = novoValor.substring(0, posVirgula) + novoValor.substring(posVirgula + 1);
 
    // Formatando o número com a quantidade de casas inteiras e decimais passadas como parâmetro.
    if ((novoValor.length > 1) && (novoValor.charAt(0) == '0') && (numDec > 0))
      posVirgula = 1;
  
    if ((posVirgula < 0) || (posVirgula > numInt))
      posVirgula = numInt;

    valorInt = novoValor.substring(0, posVirgula);
    valorDec = novoValor.substring(posVirgula, posVirgula + numDec);

    if ((valorInt.length == 0) && (valorDec.length > 0))
      valorInt = "0";

    novoValor = sinal + valorInt;

    if ((exiteVirgula) || (valorDec.length > 0))
      novoValor += "," + valorDec;
  }
  
  return novoValor;
}

/**
 *
 */
function mascara_PU(campo)
{
  var valorCmp = campo.value;
  var valorAntes = "";
  var valorDepois = "";

  if (valorCmp == "")
    return;

  if (valorCmp.indexOf(",") == -1)
  {
    valorAntes = valorCmp;
  }
  else
  {
    valorAntes = valorCmp.substring(0, valorCmp.indexOf(","));
    valorDepois = valorCmp.substring((valorCmp.indexOf(",")+1), valorCmp.length);
  }

  valorCmp = valorAntes + "," + preencheZerosDireita(valorDepois, 8);
  campo.value = valorCmp;
}

/**
 * Máscara para valores numéricos.
 */
function mascaraValor(campo, numInt, numDec, aceitaSinal)
{
  if (campo.value.length > 0)
  {
    // Formatando o número com a quantidade de casas inteiras e decimais passadas como parâmetro.
    var valor = formataNumero(campo.value, numInt, numDec, aceitaSinal);

    if (totalDigitos(valor) == 0)
      valor = "";

    // Completando com zeros à direita.
    if (valor.length > 0)
    {
      var posVirgula = valor.indexOf(",");

      if (posVirgula >= 0)
      {
        valorDec = valor.substring(posVirgula + 1, posVirgula + 1 + numDec);
        valor = preencheZerosDireita(valor, valor.length + (numDec - valorDec.length));
      }
      else if (numDec > 0)
      {
        valor += ",";
        valor = preencheZerosDireita(valor, valor.length + numDec);
      }
    }
        
    campo.value = valor;
  }  
}

/**
 *
 */
function mascara_valorFinanc(campo)
{
  var valorCmp = campo.value;
  var valorAntes = "";
  var valorDepois = "";

  if (valorCmp == "")
    return;
    
  if (valorCmp.indexOf(",") == -1)
  {
    valorAntes = valorCmp;
  }
  else
  {
    valorAntes = valorCmp.substring(0,valorCmp.indexOf(","));
    valorDepois = valorCmp.substring((valorCmp.indexOf(",") + 1), valorCmp.length);
  }
    
  valorCmp = valorAntes + "," + preencheZerosDireita(valorDepois, 2);
  
  campo.value = valorCmp;
}

/**
 *
 */
function preencheZerosDireita(valor, tamValor)
{
  while (valor.length < tamValor)
    valor = valor + "0";

  return valor;
}

/**
 *
 */
function preencheZerosEsquerda(valor, tamValor)
{
  while (valor.length < tamValor)
    valor = "0" + valor;
  
  return valor;
}

/**
 * Retira os caracters alfa-numéricos que não devem fazer parte de um número.
 * Os caracters válidos são digitos, vírgula (se o número possui casas decimeis) e
 * os sinais de '+' ou '-' na primeira posição do número. 
 */
function retiraCaractersAlfaNumerico(valor, numInt, numDec, aceitaSinal)
{
  var novoValor = "";

  for (var i = 0; i < valor.length; i++) 
  {
    if (((valor.charAt(i) >= '0') && (valor.charAt(i) <= '9')) ||
        ((valor.charAt(i) == '+' || valor.charAt(i) == '-') && (i == 0) && (aceitaSinal)) ||
        ((valor.charAt(i) == ',') && (i <= numInt) && (numDec > 0)))
    {    
      novoValor += valor.charAt(i);
    }  
  } 

  return novoValor; 
}

/**
 * Retorna o número total de digitos(sem contar vírgulas, pontos, sinais, etc) no campo.
 */
function totalDigitos(valor)
{
  var total = 0;
 
  for (var i = 0; i < valor.length; i++) 
  {
    if (valor.charAt(i) >= '0' && valor.charAt(i) <= '9')
      total++;
  }  

  return total;
}


/**************************************************************************
 * Rotinas para formatação de campos alfa numéricos.
 **************************************************************************/

/**
 * Retira brancos à esquerda de um string.
 */
function lTrim(str)
{
  while (str.charAt(0) == " ")
  {
    str = str.replace(str.charAt(0), "");
  }

  return str;
}

/**
 * Retira brancos à direita de um string.
 */
function rTrim(str)
{
  while (str.charAt((str.length - 1)) == " ")
  {
    str = str.substring(0, str.length - 1);
  }

  return str;
}

/**
 * Retira brancos à esquerda e à direita de um string.
 */
function trim(str)
{
  return rTrim(lTrim(str));
}

/**
 * Testa o tamanho máximo de caracteres de um campo TextArea.
 */
function testaTamanhoMaximoTextArea(campo, e, tamMax)
{
  if (document.all) 
  {
    cod = event.keyCode;
  } 
  else 
  {
    cod = e.which;
  }
 
  if (cod  >= 32)  // Códigos de teclas correspondente a dígito qualquer.
    return (campo.value.length < tamMax);
  else  
    return true;
}

/*
function atualizaValorTotal()
{
  var total      = 0;
  var totalCores = document.getElemenById('listaItens');
  var listaItens = totalCores.split(",");
  
  for (var i = 0; i < listaItens.length ; i++)
  {
    idProduto =  substring;
    idCor     =  ;
    
    quantidadeItem = document.getElemenById('preco_idProduto_'+idProduto+'_idCor_'+idCor);
    idCodItem      = document.getElemenById('preco_idProduto_'+idProduto+'_idCor_'+idCor);
    precoItem      = document.getElemenById('preco_idProduto_'+idProduto+'_idCor_'+idCor);
    
    total += quantidadeItem * precoItem;
  }
  
  document.getElemenById('valorTotal').value = total;
  
}
*/

function atualizarFotoFrente() {
  var novoCaminho = 'produtos/'+document.getElementById('linkFotoPrincipalHidden').value;
  document.getElementById('foto').src = novoCaminho;
  document.getElementById('single_image').href= novoCaminho;
}

function atualizarFotoDetalhe() {
  var novoCaminho = 'produtos/'+document.getElementById('linkFotoDetalheHidden').value;
  document.getElementById('foto').src = novoCaminho;
  document.getElementById('single_image').href= novoCaminho;
}

function atualizarFotoDetalhe2() {
  var novoCaminho = 'produtos/'+document.getElementById('linkFotoDetalhe2Hidden').value;
  document.getElementById('foto').src = novoCaminho;
  document.getElementById('single_image').href= novoCaminho;
}

function mudarFoto(novaFotoFrente, novaFotoDetalhe, novaFotoDetalhe2, numFoto, totalFotos, idFoto, novoNome) {
  var novoCaminho = 'produtos/'+novaFotoFrente;
  
  if ( document.getElementById('foto') != null )
     document.getElementById('foto').src = novoCaminho;

  document.getElementById('nomeCor').innerHTML             = novoNome;
  document.getElementById('idCorSelecionada').value        = idFoto;
  document.getElementById('linkFotoPrincipalHidden').value = novaFotoFrente;
  document.getElementById('linkFotoDetalheHidden').value   = novaFotoDetalhe;
  document.getElementById('linkFotoDetalhe2Hidden').value  = novaFotoDetalhe2;
  //document.getElementById('linkFotoPrincipal').onclick   = "atualizarFotoFrente";

  if (novaFotoDetalhe != '') {
    document.getElementById('linkFotoDetalheDiv').style.display='';
  } else {
    document.getElementById('linkFotoDetalheDiv').style.display='none';
  }

  if (novaFotoDetalhe2 != '') {
    document.getElementById('linkFotoDetalhe2Div').style.display='';
  } else {
    document.getElementById('linkFotoDetalhe2Div').style.display='none';
  }

  document.getElementById('corFoto'+numFoto).className = "corAtivo";

  for (var k=1; k <= totalFotos; k++) {
    //alert ('k = '+k);
    if (k != numFoto) {
	  document.getElementById('corFoto'+k).className = "cor";
	}
  }
}

function excluirProduto(categoria, idProduto) {
  if(confirm("Deseja realmente excluir o produto?")) {
    window.location.href = "colecaoDetalhe.php?categoria="+categoria+"&acao=excluir&idProduto="+idProduto;
  }
}

function mudarEstado(idProduto, novoEstado, categoria) {
  if(confirm("Deseja realmente alterar o status do produto?")) {
    window.location.href = 'colecaoDetalhe.php?categoria='+categoria+'&idProduto='+idProduto+'&novoEstado='+novoEstado;
  }
}

function criaGaleria(mygallery, foto1, foto2, foto3) {

	var arrayFotos = new Array();
	
	arrayFotos[0] = ['produtos/' + foto1, "", "", ""];
	
	if (foto2 != '')
		arrayFotos[1] = ['produtos/' + foto2, "", "", ""];
		
	if (foto3 != '')
		arrayFotos[2] = ['produtos/' + foto3, "", "", ""];

	mygallery = new simpleGallery({
		wrapperid: "single_image", //ID of main gallery container,
		dimensions: [280, 278], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
		imagearray: arrayFotos,
		autoplay: [true, 2500, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
		persist: false, //remember last viewed slide and recall within same session?
		fadeduration: 500, //transition duration (milliseconds)
		oninit:function(){ //event that fires when gallery has initialized/ ready to run
			//Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
		},
		onslide:function(curslide, i){ //event that fires after each slide is shown
			//Keyword "this": references current gallery instance
			//curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
			//i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
		}
	})
	
	return mygallery;
}

