/*
| -------------------------------------------------------------------
| CÓDIGOS PADRÃO DOS SITES
| -------------------------------------------------------------------
| Se for copiar esse código mantenha os créditos
| Obrigado
| marlon@marlonrenan.com | StudioA Design & Web » www.studioaweb.com.br
|
|*/
$(document).ready(function(){

    // HACK CSS CROSS BROWSER
    $.each($.browser, function(i, val){
        $('html').addClass(i);
        return false;
    });

    // verificando se o usuário esta utilizando o ie6
    if($.browser.msie && $.browser.version=="6.0"){

        var html = '<div id="box-ie">';
        html+='<div id="box-ie-text">';
        html+='<h1>ATENÇÃO<br/> <span>Seu browser esta desatualizado</span></h1>';
        html+='Você esta usando o Internet Explorer 6. Este é um navegador muito antigo que não oferece suporte para websites modernos.';
        html+=' Para ter melhor experiência em nosso website (e muitos outros), por favor atualize para o Internet Explorer 8, ou migre para um outro alternativo, como Firefox, Chrome ou Safari.';
        html+='</div>';
        html+='<div id="box-ie-icones">';
        html+='<a href="http://br.mozdev.org/download/" target="_blank" id="firefox">Firefox</a>';
        html+='<a href="http://www.google.com/chrome/index.html?hl=pt-BR&brand=CHMB&utm_campaign=pt-BR&utm_source=pt-BR-ha-latam-br-sk&utm_medium=ha" target="_blank" id="chrome">Google Chrome</a>';
        html+='<a href="http://www.apple.com/safari/download/" target="_blank" id="safari">Safari</a>';
        html+='<a href="http://www.microsoft.com/brasil/windows/internet-explorer/?WT.mc_id=1579" target="_blank" id="ie8">IE8<!-- fix bug --></a>';
        html+='</div>';
        html+='<div id="box-ie-close">Fechar</div>';
        html+='</div>';
        $('body').prepend(html);
        $('#box-ie').fadeIn('slow', function(){
            $('#box-ie-close').click(function(){
                $('#box-ie').fadeOut('slow');
            });
        });
    }

    function vemail(obj){
        var Email = $(obj).val();
        var reEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
        if (!reEmail.test(Email) || Email == "" || Email == null) {
            return false;
        } else {
            return true;
        }

    }

    
    // VERIFICANDO RETORNO DO CONTATO
    if($('#contato-mensagem').html()){

        window.setTimeout(function(){
            $('#contato-mensagem').slideUp('slow', function(){

            });
        }, 8000);

    }

    // PLUGIN DE MASCARA NO FORMULÁRIO
    if($('input[name="telefone"]').is(':visible')){
        $('input[name="telefone"]').mask('(99)9999-9999');
    }
    

    // VALIDANDO FORMULÁRIO DE CONTATO
    $('.form_contato').submit(function(ev){
        
        if($('input[name="nome"]').val()==''){
            $('input[name="nome"]').focus();
            return false;
        }
        if($('input[name="telefone"]').val()==''){
            $('input[name="telefone"]').focus();
            return false;
        }
        if(vemail('input[name="email"]')==false){
            alert('Formato de e-mail inválido! \n(Exemplo: nome@servidor.ext)');
            $('input[name="email"]').focus();
            return false;
        }
        if($('select[name="select-contato"]').val()==''){
            $('select[name="select-contato"]').focus();
            return false;
        }        
        if($('textarea[name="mensagem"]').val()==''){
            $('textarea[name="mensagem"]').focus();
            return false;
        }
        
    });
    
/*
| -------------------------------------------------------------------
| CONFIGURAÇÕES DO SITE
| -------------------------------------------------------------------
|*/

    // ==============================================================
    // VERIFICANDO SE DEVE EXIBIR INFORMAÇÃO DE RETORNO
    if($('#box-retorno').html()){
        
        $('#mascara').css('opacity',0.5);
        $('#mascara').css('height',$(document).height()+'px');

        //POSICIONA NO CENTRO
        var meioh = ($(window).width()/2)-($("#box-retorno").width()/2);
        var meiov = ($(window).height()/2)-($("#box-retorno").height()/2);
        $("#box-retorno").css({
            'margin-top':+meiov,
            'margin-left':+meioh
        });

        $('#mascara').fadeIn('fast', function(){
            $('#box-retorno').fadeIn('fast', function(){
                setTimeout(function(){
                    $('#box-retorno').fadeOut('fast',function(){
                        $('#mascara').fadeOut('fast');
                    })
                }, 2000);
            });
        });
    }

    // ==============================================================
    // AÇÕES COTAÇÃO ------------------------------------------------
    // ==============================================================

    // VERIFICANDO SE EXISTE PRODUTOS ADICIONADOS NO CARRINHO
    if(!$('.cartimg').is(':visible')){
        
        $('#shoppingcart').remove();
        $('.cartvisible').removeClass('cartvisible');

    }

    // TOTAL DE PRODUTOS NO CARRINHO
    var tprod = $('.cartimg').length==1?$('.cartimg').length+' item':$('.cartimg').length+' itens';
    $('#boxmycart').html($('#boxmycart').html()+' - '+tprod);

    // ACAO SLIDE NOS PRODUTOS ESCOLHIDOS ---------------------------
    var $div = $('#shoppingcart-prods');
    var height = $div.height();
    $div.css({ height : 0 });

    $('.show-cart').click(function(){
        $('.border-b').removeClass('border-b');

        var obj = $('#btao-show-cart');
        var imgpath = obj.attr('src');

        var pontopos = imgpath.lastIndexOf('.');
        var ext = imgpath.substr(pontopos);
        var img = imgpath.replace(ext,""); // NOME

        if ( $('.openprod').is(':visible') ) {
            $div.animate({height: 0 }, {duration: 10 , complete: function () {
                $('.openprod').hide();
                $('#shoppingcart-bar').addClass('border-b');
                img = img.replace(/up/,"down");
                obj.attr({
                    src:img+ext,
                    title:"clique para visualizar os produtos do carrinho"
                });
            }});

        } else {
            $div.addClass('openprod, border-b');
            $div.show().animate({ height : height }, { duration: 10 , complete: function(){
                    img = img.replace(/down/,"up");
                    obj.attr({
                        src:img+ext,
                        title:"clique para esconder os produtos do carrinho"
                    });
            }});
        }

    });
    $('#btao-show-cart').click();

    // VALIDANDO NÚMEROS DIGITADOS
    $('input[name="qtd"]').keypress(function(event){
        if (!(event.which >47 && event.which  < 58 || event.which ==8 || event.which ==0 || event.which ==13)) {
            alert('Favor digitar somente caracteres numéricos!');
            $('input[name="qtd"]').val('');
            return false;
        }
    });


    // ADICIONA O PRODUTO NO CARRINHO
    $('.addcart').click(function(ev){
        ev.preventDefault();
        var qtdval = $(this).parent().find('input[name="qtd"]').val();
        if(qtdval==''){
            $(this).parent().find('input[name="qtd"]').focus();
            return false;
        }
        // verifica se este produto ja foi adicionado no carrinho
        if($('li#prod_'+$(this).attr('id')).html()!=null){
            //if(confirm('Este produto já está incluso no seu carrinho.\nDeseja aumentar a quantidade deste produto?')){
            if(confirm('Este produto já está incluso no seu carrinho.\nDeseja adicionar mais '+qtdval+' unidade(s) deste produto no seu carrinho?')){
                var pqtd = parseInt($('li#prod_'+$(this).attr('id')).find('span.qtdprod').text());
                window.location=$(this).attr('href')+'qtd:'+(parseInt(qtdval)+pqtd);
                return false;
            } else {
                return false;
            }
        }
        window.location=$(this).attr('href')+'qtd:'+qtdval;
    });

    // EXCLUI PRODUTOS DO CARRINHO
    $('.cartexcluir').click(function(ev){
        ev.preventDefault();
        if(!confirm('Tem certeza que deseja remover este item?')) return false;
        window.location=$(this).attr('href');
    });

    // ==============================================================
    
    

    // ==============================================================
    // CATEGORIA DE PRODUTOS ----------------------------------------
    // ==============================================================
    var obj = ''; 
    function posiciona() {
        var $obj = $('#'+obj);
        var $objc = $('#'+obj+'_sublinks');
        var offset = $obj.offset();
        var cartbar = $('#shoppingcart-bar').height();
        
        var objh = $objc.height();

        if(offset=='' || offset==null){
            offset=0;
        }
        
        $('#'+obj+'_sublinks').css({
            'top':(offset.top-(objh/2)-$('#topo-box-cat').height()-cartbar)
        });

        $objc.stop().show();
    }
    //===========================================
    function oculta() {
            if (!$('#'+obj).hasClass('ativo'))
                    $('#'+obj+'_sublinks').hide();
    }
    //===========================================
    
    $('.linksmenu').hover(
        function(){
            $(this).addClass('ativo');
            $(this).find('a').addClass('linkativo');
            obj=$(this).attr('id');
            posiciona();
        },
        function(){
            $('.ativo').removeClass('ativo');
            $('.linkativo').removeClass('linkativo');
            oculta();
        }
    );


    // VERIFICANDO SE EXISTE SUBMENU
    $('.linksmenu').each(function(){
        if($(this).attr('id')=='')$(this).remove();
    });
    
    if(!$('.linksmenu').is(':visible')){
        $('#menu-categorias').html('<li><i>Nenhuma categoria foi cadastrada até o momento.</i></li>');
        $('.slidecat').removeClass('slidecat');
    }

    // AÇÃO SLIDE CATEGORIAS
    var boxh = $('#menu-categorias').height();
    var objh = ($('.linksmenu').length*($('.linksmenu').height()+2));
    // VERIFICANDO SE DEVE FAZER SLIDE
    if(boxh>objh){
        $('.slidecat').removeClass('slidecat');
    }

    $('.slidecat').click(function(){

        var obj = $(this);
        var imgpath = $(this).attr('src');
        
        var pontopos = imgpath.lastIndexOf('.');
        var ext = imgpath.substr(pontopos);
        var img = imgpath.replace(ext,""); // NOME

        if($('.opencat').is(':visible')){
            $('#menu-categorias').animate({
                height: boxh+'px'
            }, 500, function() {
                // Animation complete.
                $('.hiddencat').hide();
                $('.opencat').removeClass('opencat');

                // ALTERA A IMAGEM
                img = img.replace(/-top/,"");
                obj.attr('src',img+ext);
                
            });
        } else {
            $('#menu-categorias').animate({
                height: objh+'px'
            }, 500, function() {
                // Animation complete.
                $('.hiddencat').show();
                $(this).addClass('opencat');
                
                // ALTERA A IMAGEM
                obj.attr('src',img+'-top'+ext);
            });
        }
    });

    // ==============================================================
    // soma e subtração da quantidade de produtos
    $('.qtdplus').click(function(){
        var input = $(this).parent().parent().find('.wheelable');
        input.val(parseInt(input.val())+1);
    });
    $('.qtdless').click(function(){
        var input = $(this).parent().parent().find('.wheelable');
        if((parseInt(input.val())-1)>0)input.val(parseInt(input.val())-1);
        
    });

    // ==============================================================
    // AÇÃO HOVER NOS PRODUTOS
    $('.pag-prodimg, .pag-prodtitle').hover(
        function(){$(this).parent().addClass('mousehover');},
        function(){$('.mousehover').removeClass('mousehover');}
    );

    $('.cutimg').click(function(){
        window.location=$(this).parent().attr('href');
    });

});
