$(document).ready( function(){
    if (!$.browser.msie){
        $(".botaoazul, .botaocinza, .botaosup, .botaoespecial, input.busca, input.email, select.busca, #selos, #copyright, .quadro, #palavraschave, #colunaresultadoslista .cabresultadoslista .formexibicao select").corner("4px");
        $("#navegar, #navegar_adm, #caixars, #colunafiltrogeral .titulofiltro, #entradausuario .login").corner("4px left");
        $("#busca, #lancamentos .inforevista, #colunaresultadoslista .cabresultadoslista, #entradausuario .cadastro").corner("4px right");
        $("#caixars .aba").corner("4px bottom");
        $("#coluna2completo .textos .aba, #abaspagamento .abas a.aba").corner("4px top");
             $("#coluna2completo .textos .aba2, #abaspagamento .abas a.aba2").corner("4px top");
        $("#quadrototais").corner("10px");
    }
    $(".botaoazul, a.botaocinza, .botaosup, .botaosupPromo, .botaoespecial, #tell a, .inforevista .botaoazul").hover(function(){
        $(this).animate({opacity:.6});

    }, function(){
        $(this).animate({opacity:1});

    });
    $(".boxhome").find(".itemboxhome:last").css({marginBottom:0, paddingBottom:0, border:0});
    $("#linksgerais .coluna1 .minicoluna, #linksgerais .coluna2 .minicoluna").css({marginRight:"20px"}).parent().find(".minicoluna:last").css({marginRight:"0"});
    
    $("#posicoes .posicaoexpandida:first-child").css({paddingTop:"0", borderTop:"0"});
    $("#posicoes .posicaointer:first").css({paddingTop:"0", borderTop:"0"});
    
    /* Using custom settings fancy box */ 
    $("a#single_image").fancybox({'hideOnContentClick': true ,'easingIn': 'easeInOutElastic'});
    $("a#single_image2").fancybox({'hideOnContentClick': true ,'easingIn': 'easeInOutElastic'});

    $("a#inline").fancybox({ }); 

    $("a.group").fancybox({ 
                          'hideOnContentClick': true ,
                          'frameWidth' : 350
                          , 'frameHeight' : 380 }); 
	
			$("#various5").fancybox({
             
                'frameWidth' : 350,
				'frameHeight' : 200 ,
				
				'autoScale'     	: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe',
				'hideOnContentClick': false
        });
		
		$("#lala").trigger('click');
		
		
/**********************************************************************
* MODAL AVISE-ME - DETALHE.ASP | GRUPOS.ASP | BUSCA.ASP | BY NICOLETTI
***********************************************************************/
			$("a.aviseme").fancybox({
                'modal' : true,
                'frameWidth' : 600,
                'frameHeight' : 350 ,
                'autoScale'         : false,
                'transitionIn'      : 'none',
                'transitionOut'     : 'none',
                'hideOnContentClick': false
                
            }); 
/*************************************************************************
* FIM MODAL AVISE-ME - DETALHE.ASP | GRUPOS.ASP | BUSCA.ASP | BY NICOLETTI
**************************************************************************/
			
    PosAbas();
    
	
	//IMAGE ROLLOVER		   
	$('.rolloverTip').css("cursor", "hand");
	$('.rolloverTip').hover(function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	}, function() {	
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	});
	

	
    $("input.comtip").focus(function(){
        if ($(this).next(".tip").text() == $(this).val()) $(this).val("").removeClass("textotip");
    }).blur(function(){
        if ($(this).val() == "") $(this).val($(this).next(".tip").text()).addClass("textotip");
    });
    
    $(".fichaproduto .selos img:first-child, .itempopproduto .selos img:first-child").css({marginLeft:"0", paddingLeft:"0", border:"none"})
    $(".fichaproduto:last-child").css({border:"none", marginBottom:"20px"});
    $(".sugestoes .fichaproduto:last-child").css({marginBottom:"0"});
    $("#ampliacoescompleto .ampliacao:last-child").css({margin:"0"});
    $("#sugestoescarrinho .itemgaleriaproduto:first").css({paddingLeft:"0"});
    $("#sugestoescarrinho .itemgaleriaproduto:last").css({paddingRight:"0", border:"none"});
    $("#contcarrinho tr:last-child td").css({borderBottom:"none"});
    
    if ($("#colunaresultadoslista").size()>0){
        if ($("#colunaresultadoslista").height() > $("#colunafiltrogeral").height())
            $("#colunafiltrogeral").height($("#colunaresultadoslista").height());
    }
    if ($("#coluna2completo").size()>0){
        if ($("#coluna2completo").height() > $("#coluna1completo").height())
            $("#coluna1completo").height($("#coluna2completo").height());
    }
    
    $("#coluna2completo .textos .aba2").click(function(){
       
        if ($(this).hasClass("escolhida2").toString() == "false")
        {
             $("#coluna2completo .textos .aba2").toggleClass("escolhida2");
              $("#coluna2completo .textos .texto2").toggle();
        }
       
    });

     $("#coluna2completo .textos .aba").click(function(){
                                            
        $("#coluna2completo .textos .aba").removeClass("escolhida");
        $(this).addClass("escolhida");
        $("#coluna2completo .textos .texto:visible").hide();
        
        $("#aba_"+$(this).attr("rel")).show();
       // $("#coluna2completo #aba_"+$(this).attr("rel") ).show();
    });

    $("#abaspagamento .aba").click(function(){
        $("#abaspagamento .escolhida").removeClass("escolhida");
        $(this).addClass("escolhida");
        $("#abaspagamento .conteudoaba:visible").hide();
        $("#abaspagamento #aba_"+$(this).attr("rel")).show();
    });

    if ($("#coluna2completo .fichacompleta .fichaproduto .selos").size>0)
        $("#coluna2completo .fichacompleta .fichaproduto .selos").absolutizar();

    PopNavegacao();
    Titulos();
//    Lancamentos();
    RevistasSemana();
//    objetoJsonSlider = loadSlider();  
    
});
$.fn.absolutizar = function(){
    $(this).css({top:$(this).position().top, left:$(this).position().left, position:"absolute"});
    return this;
    
}
function PopNavegacao(){
    $("#navegar a.atalho").click(function(){ $("#popnavegacao").fadeIn("normal"); });
    $("#navegar_adm a.atalho").click(function(){ $("#popnavegacao").fadeIn("normal"); });
    $("#popnavegacao").css({left: parseInt($("#centralizador").offset().left + 1) + "px"}).find("a.fechar").click(function(){ $("#popnavegacao").fadeOut("normal") });
    if ($.browser.opera) $("#popnavegacao").css({left:0, top:0});
}

function Titulos(){
    var colunastitulos = $("#areatotaltitulos .minicoluna").size();
    $("#areatotaltitulos").width(colunastitulos*115);
    
    $("#colunahomemarcas a.seta_ant").click(function(){
        $("#caixatitulos").animate({scrollLeft: $("#caixatitulos").scrollLeft()-115},function(){ 
            if( $(this).scrollLeft() == 0 ){
                $("#colunahomemarcas a.seta_ant, #colunahomemarcas span.seta_ant").toggle();
            }
            var scrollmax = $("#areatotaltitulos").width() - 230;
            if ($(this).scrollLeft() < scrollmax || $(this).scrollLeft() < (scrollmax-2)){
                $("#colunahomemarcas a.seta_prox").show();
                $("#colunahomemarcas span.seta_prox").hide();
            }
        });
    });
    $("#colunahomemarcas a.seta_prox").click(function(){
        $("#caixatitulos").animate({scrollLeft: $("#caixatitulos").scrollLeft()+115},function(){ 
            var scrollmax = $("#areatotaltitulos").width() - 230;
            if( $(this).scrollLeft() == scrollmax || $(this).scrollLeft() == (scrollmax - 2)){
                $("#colunahomemarcas a.seta_prox").hide();
                $("#colunahomemarcas span.seta_prox").toggle();
            }
            if ($(this).scrollLeft() > 0){
                $("#colunahomemarcas a.seta_ant").show();
                $("#colunahomemarcas span.seta_ant").hide();
            }
        });
    });
}

function botaoAdicionado(id)
{       
        newButon = " <div id='containerbotaoadicionado'><div class='botaoadicionado'>J&aacute; adicionado</div>"
        newButon +=" <a class='vercarrinho' href='carrinho.asp'>Ver carrinho</a></div>"
        $("#"+id).html(newButon)
}

function botaoAdicionado2(){ // chamada por textobotao.asp

		/* Mudado nome da DIV de containerbotaoadicionado para containerbotaoadicionadoindex, pois mudou-se layout de exibição dos botões em detalhes.asp*/
		newButon = " <div id='containerbotaoadicionadoindex' ><div class='botaoadicionado'>J&aacute; adicionado</div>"
		newButon +=" <a class='vercarrinho' href='carrinho.asp'>Ver carrinho</a></div>"
		$("#btn").html(newButon)
}

/*** Criada, pois mudou-se layout de exibição dos botões em detalhes.asp, e em index.asp ficava fora de layout ***/
function botaoAdicionadoIndex(id)
{       
        newButon = " <div id='containerbotaoadicionadoindex'><div class='botaoadicionado'>J&aacute; adicionado</div>"
        newButon +=" <a class='vercarrinho' href='carrinho.asp'>Ver carrinho</a></div>"
        $("#"+id).html(newButon)
}

function RevistasSemana(){
    $("#destaquesrs .imagemrevista").click(function(){
        var posrevista;
        if (!$(this).next().is(":visible") && $("#destaquesrs .inforevista:animated").size()==0){
            $("#destaquesrs .imagemrevista").each(function(){

                    $(this).find("div").removeClass('abaescolhida')
                if ($(this).next().is(":visible")){
                    $(this).next().hide("slow").parent().animate({width:90},"slow");
                }
            })
            $(this).next().eq(0).show("slow").parent().animate({width:458},"slow", function(){ PosAbas(); });
            $(this).find("div").addClass("abaescolhida")
        }
    });
}

function PosAbas(){
    var posrevista;
    $("#caixars .aba").each(function(){
        posrevista = $(this).prev("img").position();
        $(this).css({top: parseInt(posrevista.top + 120)+"px", left: parseInt(posrevista.left - 10)+"px"});
    })
    $("#caixars .aba:hidden").show();
    
}

function ajaxService() {};
ajaxService.prototype.iniciar = function() {
    try {
        // Mozilla / Safari
        this._xh = new XMLHttpRequest();
    } catch (e) {
        // Explorer
        var _ieModelos = new Array(
        'MSXML2.XMLHTTP.5.0',
        'MSXML2.XMLHTTP.4.0',
        'MSXML2.XMLHTTP.3.0',
        'MSXML2.XMLHTTP',
        'Microsoft.XMLHTTP'
        );
        var success = false;
        for (var i=0;i < _ieModelos.length && !success; i++) {
            try {
                this._xh = new ActiveXObject(_ieModelos[i]);
                success = true;
            } catch (e) {
                    alert(e)
            }
        }
        if ( !success ) {
            alert(e)
            return false;
        }
        return true;
    }
}

ajaxService.prototype.ocupado = function() {
    estadoActual = this._xh.readyState;
    return (estadoActual && (estadoActual < 4));
}

ajaxService.prototype.procesa = function() {
    if (this._xh.readyState == 4 && this._xh.status == 200) {
        this.procesado = true;
    }
}

ajaxService.prototype.enviar = function(urlget,datos) {
    if (!this._xh) {
        this.iniciar();
    }
    if (!this.ocupado()) {
        this._xh.open("POST",urlget,false);
        this._xh.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=iso-8859-1');
        this._xh.send(datos);
        if (this._xh.readyState == 4 && this._xh.status == 200) {
            return this._xh.responseText;
        }
        
    }
    return false;
}

function getInfo(indice)
{
    
	var vpreco, vdesc, formpreco
        
        $("#texto").html('<a href="detalhe.asp?id='+retornoDados[indice].id+'&grupo='+retornoDados[indice].grupo+'&cat='+retornoDados[indice].categoria+'">'+retornoDados[indice].title +'</a>')
        if (retornoDados[indice].desc!=""){
                edicao = retornoDados[indice].desc;
            }
        else{
            edicao = "";
        }
        
		
		
		vpreco =  CurrencyFormatted(retornoDados[indice].preco).replace(".", ",");
		vdesc  =  CurrencyFormatted(retornoDados[indice].desconto).replace(".", ",");
		vdesccedido  =  CurrencyFormatted(retornoDados[indice].valordesconto).replace(".", ",");
		if (vpreco ==vdesc ){
			formpreco = "<span class='preco2'>R$ "+vpreco + "</span>"
		}
		else{
			formpreco = "De R$ "+vpreco+" <br> Por <span class='preco2'>R$ " + vdesc + "</span ><br> Voc&ecirc; economiza <span class='economia'>R$ "+vdesccedido+"</span>"
		}

        $("#descricao").html(edicao)
        $("#preco").html(formpreco);
        $("#fotoGrande").html('<a href="detalhe.asp?id='+retornoDados[indice].id+'&grupo='+retornoDados[indice].grupo+'&cat='+retornoDados[indice].categoria+ '" border="0"><img src="'+retornoDados[indice].bigImagem+'" width="215" height= "275" alt="'+retornoDados[indice].title+'" title="Ver mais detalhes"></a>');  
		
		
		if ( verificaCarrinho(retornoDados[indice].id) == false ){
	
		hrefItem = 'href="javascript:GravaCesto('+retornoDados[indice].id+', '+String.fromCharCode(39)+'a'+String.fromCharCode(39)+', '+String.fromCharCode(39)+retornoDados[indice].title+String.fromCharCode(39)+','+String.fromCharCode(39)+'cesta'+String.fromCharCode(39)+  ') ;botaoAdicionado2() "'
		$("#btn").html("<a class='botaoazul' style='-moz-border-radius: 4px 4px 4px 4px; opacity: 1;' id='botao"+retornoDados[indice].id+"' "+hrefItem+" >Adicionar ao carrinho</a>")
		
		}
		
		else{
			botaoAdicionado2()
		}
	
}

function verificaCarrinho(codprd){
		 acessoRemoto = new ajaxService;
         retornoDados3 = acessoRemoto.enviar("ajax/AjaxResponser.asp", "action=cart");
		 itemEncontrado = false
		 if (retornoDados3 != "null") {
			 vetorItens = retornoDados3.split(",")
			 for (i = 0; i < vetorItens.length; i++) {
				 	
					
					//alert("vetorItens[i]" + vetorItens[i] + "codprd" + codprd)
				    if (vetorItens[i].toString()==codprd.toString()) {
					//	alert("vetorItens[i]" + vetorItens[i] + "codprd" + codprd)
						itemEncontrado = true 
					}
				 	
                }
				
			if (itemEncontrado){
				return true
			}
			
			else {
				return false
			}
			 
		 
		 }
		 
		 else {
				return false
		 }
		 
}

function sliderBtnCarrinho(codItem, preco, nome)
{
    //$("#sliderBotaoCarrinho").attr("id","botao"+codItem)
    $("#sliderBotaoCarrinho").attr("href","javascript:GravaCesto("+codItem+",  'a' , '"+nome+"', 'cesta')");
}

function GravaCesto( CodProd, Operacao, Nome, Modo ){
    
    if (CodProd !="" && Operacao != "" && CodProd != null && Operacao!= null )
    {
        var dadosCarrinh, retornoDados, url, dados, ValorCesta, quantidadeCesta;
        url             = "ajax/AjaxCarrinho.asp";
        dados           = "id=" + CodProd + "&o=" + Operacao;
        dadosCarrinho   = new ajaxService;
        retornoDados    = dadosCarrinho.enviar(url,dados).split("qtd");
        ValorCesta      = retornoDados[0];
        quantidadeCesta = retornoDados[1];
        $("#quantidadeCesta").html(quantidadeCesta);
        $("#ValorCesta").html(ValorCesta);
        if(Modo == "cesta")
        {
            showFlap(Nome);
        }
        else
        {
            window.location.href = "carrinho.asp"       
        }

    }
    else
    {
        alert("O codigo do produto esta incorreto contate o administrador erro X100006Z.")
    }
}

function showFlap(Nome)
{   

    $('#carrinhoMensagem .textoInterno').html( "<b>"+ Nome + " </b>foi adicionado ao carrinho com sucesso.")
    $('#carrinhoMensagem').animate({bottom:"0px"},{queue: false, duration: 350}); 
    setTimeout(function(){$('#carrinhoMensagem').animate({bottom:"-100px"},{queue: false, duration: 350}); }, 5000);
}


function _gr(reqseccion,divcont) {
    remotos = new ajaxService;
    nt = remotos.enviar(reqseccion,"");
    document.getElementById(divcont).innerHTML = nt;
}

function CurrencyFormatted(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}



function contaPalavras(texto){
    var splited;
    var textoRetorno = "";
    splited = texto.split(" ");
    
    if (splited.length <10 )
    {
        return texto;
    }
    else
    {   
        for (i=0;i<7;i++)
        {
            textoRetorno += splited[i]+ " "
        }   
    
        return textoRetorno + "..."
    }
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}


function enviaAvaliacao(nota,codProduto, divretorno)  {
        acessoRemoto    = new ajaxService;
        url             = "ajax/AjaxAvaliacao.asp"
        dados           = "acao=avaliacao&codproduto="+codProduto+"&nota="+nota;
        nt              = acessoRemoto.enviar(url,dados);
        
    
        formulario = document.getElementById("form"+codProduto)
    
        if (nt =='false'){
            retorno = "Voce ja avaliou esse produto hoje."
        }
        else{
            retorno     = "Produto avaliado com sucesso."
            nt          = nt.split("qtd")
             nota       = nt[1];
                quantidade      = nt[0];
            
            $("#voteResponse").html(nota.substring(0,1)+".0 ("+quantidade+" voto(s))")
        }
        
        
        $("input", formulario).rating('readOnly',true)
}





function quantidadeBrindeLarousse()  {

execbrinde();

}


function execbrinde(){
	        acessoRemoto    = new ajaxService;
        url             = "ajax/AjaxBrindeLarousse.asp"
        dados           = "";
        nt              = acessoRemoto.enviar(url,dados);
 
        $(".msgLaroussePromo").html(nt)
		 $(".msgLaroussePromo2").html(nt)
	}


function atualizarCarrinho(cepExterno){
        
        
        var cep;
        
        if (cepExterno=="init"){
            dados           = "";   
        }
        else if (cepExterno!=""){
            dados           = "cep=" + cepExterno;
        }
        else if (cepExterno==""){
            cep             = document.getElementById("cep").value;
            dados           = "cep=" + cep;
        }
        else{
            cep             = document.getElementById("cep").value;
            dados           = "cep=" + cep;
        }
        $("#produtosContainer").html("<div id='carrinhoload'><img src='imagens/load.gif' border='0'></div>");
        
        url             = "ajax/AjaxCarrinhoView.asp";
        dadosCarrinho   = new ajaxService;
        retornoDados    = dadosCarrinho.enviar(url,dados)
        $("#produtosContainer").html(retornoDados);
}



function modificaItemCarrinho(codproduto, quantidade, acao){
    var cep, dadosCarrinho, retornoDados, ValorCesta, quantidadeCesta;
    cep             =  document.getElementById("cep").value;

    $("#produtosContainer").html("<div id='carrinhoload'><img src='imagens/load.gif' border='0'></div>");
    url             = "ajax/AjaxAlterarCarrinho.asp";
    if (acao=="change")
    {
        dados           = "acao=change&codproduto="+codproduto+"&qtatual="+quantidade + "&cep=" + cep
    }
    else if (acao=="remove")
    {
        dados           = "acao=remove&codproduto="+codproduto  + "&cep=" + cep
    }
    else if (acao =="clean")
    {
        dados           = "acao=clean"
    }
    else
    {
        
    }

    dadosCarrinho   = new ajaxService
    
    retornoDados    = dadosCarrinho.enviar(url,dados).split("qtd");
    ValorCesta      = retornoDados[0];
    quantidadeCesta = retornoDados[1];
    
    $("#quantidadeCesta").html(quantidadeCesta);
    $("#ValorCesta").html(ValorCesta);
    if (cep=="")
    {
        cep = "init"
    }
    atualizarCarrinho(cep)
}
function popup(pagina){
       window.open(pagina,'AntiPopUp','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=350,height=200');  
}

function localizarEndereco(pagina, cep){
    window.location.href = pagina + "&cepLocaliza="+cep;
    }
    


function filterExpand(divid, containerOpenClose){
    
    tamanhoDiv = document.getElementById(divid).style.height    
    
    if (tamanhoDiv == "200px") 
    {   
        document.getElementById("colunafiltrogeral").style.height = "auto"
        document.getElementById(divid).style.height = "auto"
        document.getElementById(divid).style.overflow = "hidden"
        document.getElementById(containerOpenClose).innerHTML = '<a href="javascript:filterExpand('+String.fromCharCode(39)+divid+String.fromCharCode(39)+', ' +String.fromCharCode(39)+ containerOpenClose +String.fromCharCode(39)+ '  )">Agrupar todas <img src="imagens/filtros_menos.gif" border="0"></a>'
        $("#"+containerOpenClose).removeClass('todosgenerico').addClass('todosgenerico2');

    }
    else
    {
        document.getElementById(divid).style.height = "200px"
        document.getElementById(divid).style.overflow = "hidden"
        document.getElementById(containerOpenClose).innerHTML = '<a href="javascript:filterExpand('+String.fromCharCode(39)+divid+String.fromCharCode(39)+', ' +String.fromCharCode(39)+ containerOpenClose +String.fromCharCode(39)+ ')">Exibir todas <img src="imagens/filtros_mais.gif" border="0"></a>'
            $("#"+containerOpenClose).removeClass('todosgenerico2').addClass('todosgenerico');

    }

}

function obterAtendimento() {
    window.open('http://www.escala.com.br/atendimento/default.asp',
    'popAtendimento','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,height=550,width=750');
}

function mudaParcela(opcao){
    var parcelamentoCartao, campoParcela;
    parcelamentoCartao = document.getElementById("parcelamentoCartao")
    campoParcela       = document.getElementById("parc_cartao")
        if (opcao==4)
        {
            alert("Atenção\nCartão de crédito AmEx não possui opção de parcelamento.")
            parcelamentoCartao.style.display = "none"
            campoParcela.selectedIndex = 0
            campoParcela.disabled = true
        }
        else
        {
            document.getElementById("parcelamentoCartao").style.display = "block"
            campoParcela.disabled = false
        }
    }
    function enderecoAjax(cep){
        var acessoRemoto, url, dados, retornoDados, myOption;
        acessoRemoto    = new ajaxService;
        url             = "ajax/AjaxEndereco.asp";
        dados           = "cep="+cep;
        retornadovalor = acessoRemoto.enviar(url,dados)
        if (retornadovalor!="")
        {
            retornoDados = eval("(" +retornadovalor+ ")");

            document.getElementById("cep").value            =retornoDados[0].cep.replace(/  /gi, '').replace(")", "]").replace("(", " [")
            document.getElementById("endereco").value       =retornoDados[0].endereco.replace(/  /gi, '').replace(")", "]").replace("(", " [")
            document.getElementById("bairro").value         =retornoDados[0].bairro.replace(/  /gi, '').replace(")", "]").replace("(", " [")
            document.getElementById("cidade").value         =retornoDados[0].cidade.replace(/  /gi, '').replace(")", "]").replace("(", " [")
            myOption = retornoDados[0].estado
            document.getElementById(myOption).selected = true
        }
        else
        {
                alert("Endereco nao encontrado.")
            document.getElementById("endereco").value       =""
            document.getElementById("bairro").value         =""
            document.getElementById("cidade").value         =""
            }
        
    }

    ///////////////////////////////////////////////////
    // Validação de cadastro
    ///////////////////////////////////////////////////

var erros;

function add_error(msg) {
  erros = erros + "\n" + "- " + msg
}

function tem_erros() {
  return (erros.length != 0)
}

function mostra_erros() {
  alert("Erros no formulário: \n" + erros);
}

function vazio(texto) {
  var formato_correto = "([ ])*[a-zA-Z0-9\\-\\.]+([ ])*";
  var correto = new RegExp(formato_correto);
  var vazio
  vazio = false
  if (texto.length == 0) {
    vazio = true
  }
  return ((!correto.test(texto)) || vazio)
}

function email_valido(email) {
  var formato_errado = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
  var formato_certo = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
  var errado = new RegExp(formato_errado);
  var certo = new RegExp(formato_certo);
  return (!errado.test(email) && certo.test(email))
}

function n_parcelas(data_compra, data_viagem) {
  var dia1 = data_compra.substring(0,2);
  var mes1 = data_compra.substring(3,5);
  var ano1 = data_compra.substring(6,10);
  var dia2 = data_viagem.substring(0,2);
  var mes2 = data_viagem.substring(3,5);
  var ano2 = data_viagem.substring(6,10);
  var data1 = new Date(ano1, mes1 - 1, dia1);
  var data2 = new Date(ano2, mes2 - 1, dia2);
  var meses = data2.getMonth() - data1.getMonth()
  meses = meses + 3
  if (meses >= 12) {
    return 12
  }
  else return meses
}

function data_br_valida(data) {
  var formato = "[0-3][0-9]/[0-1][0-9]/[0-9][0-9][0-9][0-9]";
  var reg = new RegExp(formato);
  var formato_ok = reg.test(data);
  var dia = data.substring(0,2);
  var mes = data.substring(3,5);
  var ano = data.substring(6,10);
  var nova_data = new Date(ano, mes - 1, dia);
  var dia_ok = (nova_data.getDate() == dia);
  var mes_ok = (nova_data.getMonth() + 1 == mes);
  return (formato_ok && dia_ok && mes_ok)
}

function data_br_valida_mes_ano(data) {
  var formato = "[0-1][0-9]/[0-9][0-9][0-9][0-9]";
  var reg = new RegExp(formato);
  var formato_ok = reg.test(data);
  var mes = data.substring(0,2);
  var ano = data.substring(3,7);
  var nova_data = new Date(ano, mes - 1);
  var mes_ok = (nova_data.getMonth() + 1 == mes);
  return (formato_ok && mes_ok)
}

function inteiro_valido(numero) {
  var validos = "0123456789";
  if (numero.length == 0)
     return (false);
  for (j = 0; j < numero.length; j++)  {
    if (validos.indexOf(numero.charAt(j)) == -1)
      return (false)
  }
  return (true)
}

function menor_4000(texto) {
  if (texto.length > 4000)
    return false
  else
    return true
}

function menor_96(texto) {
  if (texto.length > 95)
    return false
  else
    return true
}

function extrai_numeros(texto) {
  var novo = ""
  for (var i = 0; i < texto.length; i++) {
    caracter = texto.charAt(i)
    if (inteiro_valido(caracter))
      novo = novo + caracter
  }
  return (novo)
}

function cgc_valido(cgc) {
  var n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14
  var d1,d2
  var digitado, calculado
  cgc = extrai_numeros(cgc)
  if(cgc.length < 14) return false
  n1 = cgc.substring(0,1)
  n2 = cgc.substring(1,2)
  n3 = cgc.substring(2,3)
  n4 = cgc.substring(3,4)
  n5 = cgc.substring(4,5)
  n6 = cgc.substring(5,6)
  n7 = cgc.substring(6,7)
  n8 = cgc.substring(7,8)
  n9 = cgc.substring(8,9)
  n10 = cgc.substring(9,10)
  n11 = cgc.substring(10,11)
  n12 = cgc.substring(11,12)
  n13 = cgc.substring(12,13)
  n14 = cgc.substring(13,14)
  d1 = n12*2+n11*3+n10*4+n9*5+n8*6+n7*7+n6*8+n5*9+n4*2+n3*3+n2*4+n1*5
  d1= 11-(d1 % 11)
  if (d1 >= 10) d1=0
  d2 = d1*2+n12*3+n11*4+n10*5+n9*6+n8*7+n7*8+n6*9+n5*2+n4*3+n3*4+n2*5+n1*6
  d2 = 11-(d2 % 11)
  if (d2 >= 10) d2=0
  calculado = d1 + d2
  digitado = n13*1 + n14*1
  return (calculado == digitado)
}

function cpf_valido(cpf) {
  cpf = extrai_numeros(cpf)
  if (cpf.length < 1) return (false)
  var d1,d4,xx,nCount,resto,digito1,digito2,check;
  d1 = 0;  d4 = 0;  xx = 1;
  for (nCount = 0; nCount < (cpf.length - 1); nCount++) {
    d1 = d1 + (11 - xx) * cpf.substring(nCount, nCount + 1)
    d4 = d4 + (12 - xx) * cpf.substring(nCount, nCount + 1)
    xx++
  }
  resto = (d1 % 11)
  if (resto < 2)
    digito1 = 0
  else
    digito1 = 11 - resto
  d4 = d4 + 2 * digito1
  resto = (d4 % 11)
  if (resto < 2)
    digito2 = 0 
  else
    digito2 = 11 - resto
  check = digito1 + digito2
  return (check == cpf.substring(cpf, cpf.length - 1, cpf.length + 1))
}

function decimal_valido(numero) {
  var validos = "0123456789.";
  if (numero.length == 0)
     return (false);
  for (i = 0; i < numero.length; i++)  {
    if (validos.indexOf(numero.charAt(i)) == -1)
      return (false)
  }
  if (numero.indexOf(".") == -1)
    return (false);
    
  if (numero.indexOf(".") != numero.lastIndexOf("."))
    return (false);
    
  return (true)
}

function hora_valida(hora) {
  var formato = "[0-2][0-9]:[0-5][0-9]";
  var reg = new RegExp(formato);
  var formato_ok = reg.test(hora);
  var h = hora.substring(0,2);
  var m = hora.substring(3,5);
  var nova_hora = new Date(2000, 1, 1, h, m);
  var h_ok = (nova_hora.getHours() == h);
  var m_ok = (nova_hora.getMinutes() == m);
  return (formato_ok && h_ok && m_ok)
}

function DataMaior(parametro1,parametro2){
    
  dia1 = parametro1.slice(0,2)
  mes1 = parametro1.slice(3,5)
  ano1 = parametro1.slice(6,10)
    
  dia2 = parametro2.slice(0,2)
  mes2 = parametro2.slice(3,5)
  ano2 = parametro2.slice(6,10)
    
  data1 = new Date(ano1,mes1,dia1)
  data2 = new Date(ano2,mes2,dia2)
    
  if (data2 <= data1)
    return false
  else
    return true
}

function DataMaiorIgual(parametro1,parametro2){
    
  dia1 = parametro1.slice(0,2)
  mes1 = parametro1.slice(3,5)
  ano1 = parametro1.slice(6,10)
    
  dia2 = parametro2.slice(0,2)
  mes2 = parametro2.slice(3,5)
  ano2 = parametro2.slice(6,10)
    
  data1 = new Date(ano1,mes1 -1,dia1)
  data2 = new Date(ano2,mes2 -1,dia2)
  if (data2 > data1){
    return false
  }
  else {
    return true
  }
}


function Passado(parametro1){
    
  dia = parametro1.slice(0,2)
  mes = parametro1.slice(3,5)
  ano = parametro1.slice(6,10)
    
  data1 = new Date(ano,mes,dia)
  data2 = new Date()  
  if (data1 < data2)
    return true
  else
    return false
}

function preecheCadastro(cep, email){
	$("#email").val(email);
	$("#cep").val(cep);
	$("#localizaEndereco").trigger('click');
}

function DataMaiorCompleta(parametro1,parametro2){
    
  dia1 = parametro1.slice(0,2)
  mes1 = parametro1.slice(3,5)
  ano1 = parametro1.slice(6,10)
  hora1 = parametro1.slice(10,12)
  minuto1 = parametro1.slice(13,15)
    
  dia2 = parametro2.slice(0,2)
  mes2 = parametro2.slice(3,5)
  ano2 = parametro2.slice(6,10)
  hora2 = parametro2.slice(10,12)
  minuto2 = parametro2.slice(13,15)

  data1 = new Date(ano1,mes1,dia1,hora1,minuto1)
  data2 = new Date(ano2,mes2,dia2,hora2,minuto2)
    
  if (data2 <= data1)
    return false
  else
    return true
}

/***********************************************
* BOX DA POSIÇÃO DO TOP 10 ESCALA
* Cool DHTML tooltip script II- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var offsetfromcursorX=12 //Customize x offset of tooltip
var offsetfromcursorY=10 //Customize y offset of tooltip

var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

document.write('<div id="dhtmltooltip"></div>') //write out tooltip DIV
document.write('<img id="dhtmlpointer" src="imagens/arrow2.gif" height="15 px" width="15 px">') //write out pointer image

var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thewidth, thecolor){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor


tipobj.innerHTML = makeLink(thetext);
enabletip=true;
return false;
}
}

function positiontip(e){
if (enabletip){
var nondefaultpos=false
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20

var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX
var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY

var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth){
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=curX-tipobj.offsetWidth+"px"
nondefaultpos=true
}
else if (curX<leftedge)
tipobj.style.left="5px"
else{
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px"
pointerobj.style.left=curX+offsetfromcursorX+"px"
}

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight){
tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
nondefaultpos=true
}
else{
tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px"
pointerobj.style.top=curY+offsetfromcursorY+"px"
}
tipobj.style.visibility="visible"
if (!nondefaultpos)
pointerobj.style.visibility="visible"
else
pointerobj.style.visibility="hidden"
}
}

function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
pointerobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}

function makeLink(text){
	
	if (text.indexOf("#LINKARTESANATO#")>0){
			newText = text.replace("#LINKARTESANATO#", "<a href='http://www.escala.com.br/artesanato.asp'>www.escala.com.br/artesanato.asp</a>");
		}
	else if (text.indexOf("#LINKLAROUSSE#")>0){
		newText = text.replace("#LINKLAROUSSE#", "<a href='http://www.escala.com.br/promocaolivros.asp'>www.escala.com.br/promocaolivros.asp</a>");
	}
	else{
		newText = text;
		}
	return newText;
}

document.onmousemove=positiontip

/***********************************************
* FIM - BOX DA POSIÇÃO DO TOP 10 ESCALA
***********************************************/

/****************************************************
* ADICIONAR AOS FAVORITOS - RODAPE.ASP | BY NICOLETTI
*****************************************************/
function addFav(){
    var url      = "http://www.escala.com.br";
    var title    = "Editora Escala";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}
/**********************************************************
* FIM | ADICIONAR AOS FAVORITOS - RODAPE.ASP | BY NICOLETTI
***********************************************************/

function reloadURL()
    {
       document.location.reload();
    }

