// JavaScript Document

function Flash(src) {
    document.write(src);
}

var posicaoAtual = 0, proximaPosicao = 0;
var ativoScroll = false;

var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;


function mycarousel_initCallback(carousel) {
    $('#cboxPrevious').bind('click', function () {
        carousel.prev();
    });

    $('#cboxNext').bind('click', function () {
        carousel.next();
    });

    /************************* TOUCHWIPE START *********************************/
    $("#imagens_carousel").touchwipe({
        wipeLeft: function() {
            carousel.next();
        },
        wipeRight: function() {
            carousel.prev();
        },
        min_move_x: 20,
        min_move_y: 20,
        preventDefaultEvents: true
    });
    /************************* TOUCHWIPE END *********************************/

    $('#imagens_carousel').bind("mousewheel", function(event, delta) {
        if(delta > 0) {
            carousel.prev();
        } else if(delta < 0) {
            carousel.next();
        }
        return false;
    });
};

function enviaMensagem() {
    var er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;

    if($('#nome').val() == "" || $('#nome').val() == "Seu nome") {
        $('#erro-mandar-mensagem').html("Informe corretamente seu nome");
        $('#nome').focus();
        return false;
    }

    if(!er.exec($('#email').val())) {
        $('#erro-mandar-mensagem').html("Informe corretamente seu e-mail");
        $('#email').focus();
        return false;
    }

    if($('#tel').val() == "" || $('#tel').val() == "Telefone") {
        $('#erro-mandar-mensagem').html("Informe seu telefone");
        $('#tel').focus();
        return false;
    }

    if($('#mensagem').val() == "" || $('#mensagem').val() == "Escreva sua mensagem") {
        $('#erro-mandar-mensagem').html("Informe sua mensagem");
        $('#mensagem').focus();
        return false;
    }

    var form_html = "";

    $.ajax({
        type: "POST",
        url: "/v3/paginas-ajax/conversar/processa_mensagem.php",
        data: $("#mandar-mensagem").serialize(),
        dataType: 'json',
        beforeSend: function() {
            $('#divMensagem').hide();
            $('#divEnviandoMensagem').fadeIn();
            $('#erro-mandar-mensagem').html("");
        //$('#divMensagem').html("<img src='/imagens/icon_wait.gif'>");
        // enquanto a função esta sendo processada, você
        // pode exibir na tela uma
        // msg de carregando
        },
        success: function(oJson) {
            if(oJson.bSucesso) {
                $('#divEnviandoMensagem').html('Mensagem enviada com sucesso! Em breve estaremos respondendo seu e-mail. Obrigado.');

                $('#mandar-mensagem').each(function(){
                    this.reset();
                });

                setTimeout("$('#divEnviandoMensagem').hide();$('#divMensagem').fadeIn();$('#divEnviandoMensagem').html('Enviando...');",(6 * 1000));
            } else {
                $('#erro-mandar-mensagem').html(oJson.sMensagem);
                $('#divEnviandoMensagem').hide();
                $('#divMensagem').fadeIn();
            }

        },
        error: function(sHtml) {
            // em caso de erro você pode dar um alert('erro');
            $('#divMensagem').html(form_html);
        }
    });
}

$(function(){
    $('a.anula').click(function () {
        return false;
    });
    // ############################################################


    $('#imagens_carousel').jcarousel({
        wrap: 'circular',
        scroll: 1,
        initCallback: mycarousel_initCallback
    });

    $('.jcarousel-skin-tango .jcarousel-container-horizontal, .jcarousel-skin-tango .jcarousel-clip-horizontal, .jcarousel-skin-tango')
    .css('width', ($(window).width() - 265) + "px");

    $("a[rel^='tag']").colorbox({
        width: $(document).width() + 'px',
        height: 'auto',
        current: "Imagens {current} de {total}",
        onOpen:function(){
            ativoScroll = false;
            $("#principal, .jcarousel-skin-tango").fadeOut();
        },
        onComplete:function () {
            /************************* TOUCHWIPE START *********************************/
            $("#cboxContent").touchwipe({
                wipeLeft: function() {
                    $('#cboxNext').trigger('click');
                    $.colorbox.prev();
                },
                wipeRight: function() {
                    $('#cboxPrevious').trigger('click');
                    $.colorbox.next();
                },
                min_move_x: 20,
                min_move_y: 20,
                preventDefaultEvents: true
            });
        /************************* TOUCHWIPE END *********************************/
        },
        onClosed:function(){
            $("#principal, .jcarousel-skin-tango").fadeIn();
            ativoScroll = true;
        }
    });


    $('.jcarousel-item').hover(function(){
        $(".Descricao", this).stop().animate({
            bottom:'0px'
        },{
            queue:false,
            duration:300
        });
    }, function() {
        $(".Descricao", this).stop().animate({
            bottom:'-323px'
        },{
            queue:false,
            duration:300
        });
    });

    /*
	$('.jcarousel-item').hover(function(){
        $(".Descricao", this).fadeIn();
    }, function() {
        $(".Descricao", this).fadeOut();
    });
	*/
    // ############################################################

    $(document).pngFix();

    $('.AbreJanela').click(function(){
        $("#principal, .jcarousel-skin-tango").fadeOut();
        $('.FaleAGente').animate({
            right:'50%',
            top:'97',
            width: '798',
            height:'570',
            marginRight:'-370'
        },{
            queue:true,
            duration:400
        });
        $(this).css({
            cursor: 'auto'
        });
        $('.Nuvem').css({
            zIndex: '1255'
        });
        $('.Verde').css({
            zIndex: '1270'
        });
        $('.FaleAGente').css({
            cursor:'auto',
            zIndex: '1280'
        });
        $('.BotaoFechar').css({
            display:'block'
        });
    });

    $('.BotaoFechar').click(function(){
        $(this).css({
            display:'none'
        });
        $('.AbreJanela').css({
            cursor:'pointer'
        });
        $('.Nuvem').css({
            zIndex:'90'
        });
        $('.Verde').css({
            zIndex:'1270'
        });
        $('.FaleAGente').animate({
            width: '237',
            height:'427',
            marginRight:'0',
            right:'-51',
            top:'97'
        },{
            queue:true,
            duration:200
        });
        $('.FaleAGente').css({
            cursor:'pointer',
            zIndex: '90'
        });

        $("#principal, .jcarousel-skin-tango").fadeIn();
        window.location.href = window.location.href;
    });

    //MENSAGEM FORM COTATO
    $('#nome').bind({
        focus: function() {
            if($(this).val() == 'Seu nome') {
                $(this).val('');
            }
        },
        blur: function() {
            if(!$(this).val()) {
                $(this).val('Seu nome');
            }
        }
    });

    $('#email').bind({
        focus: function() {
            if($(this).val() == 'Seu e-mail de contato') {
                $(this).val('');
            }
        },
        blur: function() {
            if(!$(this).val()) {
                $(this).val('Seu e-mail de contato');
            }
        }
    });

    $('#tel').bind({
        focus: function() {
            if($(this).val() == 'Telefone') {
                $(this).val('');
            }
        },
        blur: function() {
            if(!$(this).val()) {
                $(this).val('Telefone');
            }
        }
    });

    $('#mensagem').bind({
        focus: function() {
            if($(this).val() == 'Escreva sua mensagem') {
                $(this).val('');
            }
        },
        blur: function() {
            if(!$(this).val()) {
                $(this).val('Escreva sua mensagem');
            }
        }
    });

    // Script para mostrar tudo ( resolução > 1024) ou mostrar só nuvem (resolução =<1024) do menu clientes (fixo à direita)
    var clienteFixo = document.getElementById("clientes-fixo");
    var clienteFixoMenor = document.getElementById("clientes-fixo-menor");

    if(clienteFixo) {
        if(window.innerWidth) {
            if (window.innerWidth < 1200) {
                clienteFixo.style.display = "none";
            }
        } else if (document.body.clientWidth) {
            if (document.body.clientWidth < 1200) {
                clienteFixo.style.display = "none";
            }
        }
    }

    if(window.innerWidth) {
        if (window.innerWidth < 1200) {
            clienteFixoMenor.style.zIndex = 150;
        }
    }else if (document.body.clientWidth) {
        if (document.body.clientWidth < 1200) {
            clienteFixoMenor.style.zIndex = 150;
        }
    }
    // Fim posicionamento menu clientes fixo à direita

    // Plugin jQuery para o SCROLL da navegação do site
    function filterPath(string) {
        return string
        .replace(/^\//,'')
        .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
        .replace(/\/$/,'');
    }

    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement('html', 'body');

    // Use the first element that is "scrollable"  (cross-browser fix?)
    function scrollableElement(els) {
        for (var i = 0, argLength = arguments.length; i <argLength; i++) {
            var el = arguments[i],
            $scrollElement = $(el);
            if ($scrollElement.scrollTop()> 0) {
                return el;
            } else {
                $scrollElement.scrollTop(1);
                var isScrollable = $scrollElement.scrollTop()> 0;
                $scrollElement.scrollTop(0);
                if (isScrollable) {
                    return el;
                }
            }
        }
        return [];
    }
    // Fim Plugin jQuery para o SCROLL da navegação do site

    // Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
    $('a[href*=#nav-]').each(function() {
        // Ensure it's a same-page link
        var thisPath = filterPath(this.pathname) || locationPath;
        if (  locationPath == thisPath
            && (location.hostname == this.hostname || !this.hostname)
            && this.hash.replace(/#nav\-/,'') ) {

            // Ensure target exists
            var $target = $(this.hash), target = this.hash;
            if (target) {

                // Find location of target
                var targetOffset = $target.offset().top;
                $(this).click(function(event) {

                    // Prevent jump-down
                    event.preventDefault();

                    // Animate to target
                    $(scrollElem).animate({
                        scrollTop: targetOffset
                    }, 1000, function() {

                        // Set hash in URL after animation successful
                        location.hash = target;

                    });
                });
            }
        }

    });


    // Janela MODAL
    $('a[class=modal]').click(function(e) {
        e.preventDefault();

        var id = $(this).attr('href');

        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        $('#mask').css({
            'width':maskWidth,
            'height':maskHeight
        });

        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow",0.8);

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);
        $(id).fadeIn(2000);

    });

    $('.window input').click(function (e) {
        e.preventDefault();
        $('#mask').hide();
        $('.window').hide();
    });

    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });
    // Fim Janela MODAL

    /* xxxxxxxxxxx aparecer/desaparecer nuvens na Home xxxxxxxxxxx */
    /* Nuvem Mais Detalhes */
    $('.atres').hover(function(e) {
        if ( e.type === "mouseenter" ) {
            $('.atres .bh2').stop(true,true).slideDown();
        } else {
            $('.atres .bh2').slideUp();
        }
    })
    /* Fim Nuvem Mais Detalhes */

    /* Nuvem novos */
    $('.aum').hover(function(e) {
        if ( e.type === "mouseenter" ) {
            $('.aum .bh1').stop(true,true).slideDown();
        } else {
            $('.aum .bh1').slideUp();
        }
    })
    $('.adois').hover(function(e) {
        if ( e.type === "mouseenter" ) {
            $('.adois .bh1').stop(true,true).slideDown();
        } else {
            $('.adois .bh1').slideUp();
        }
    })
    /* Fim Nuvem novos */
    /* xxxxxxxxxxx Fim aparecer/desaparecer nuvens na Home xxxxxxxxxxx */

    /* xxxxxxxxxxx Efeito link corrente na navegação principal xxxxxxxxxxx */
    $('#menu a').click(function() {
        ativoScroll = false;
        proximaPosicao = $(this).attr("id");

        $(this).parent().siblings().children('a').css({
            fontSize: '',
            color: '',
            top: '0px'
        })
        $(this).css({
            fontSize: '30px',
            color: '#fff',
            top: '5px'
        })
    });

    $('#nome').bind({
        focus: function() {
            $(this).val('');
        },
        blur: function() {
            if(!$(this).val()) {
                $(this).val('seu nome');
            }
        }
    });
//#nav-ho
//$("#menu a:eq(0)").trigger('click');
/* xxxxxxxxxxx Fim Efeito link corrente na navegação principal xxxxxxxxxxx */
});

$(window).scroll(function(){
    posicaoAtual = $(window).scrollTop();

    if(ativoScroll) {
        switch(true){
            case posicaoAtual >= 100 && posicaoAtual < 1700:
                $("#menu a:eq(1)").trigger('click');
                proximaPosicao = 2398;
                ativoScroll = false;
                break;
            case posicaoAtual >= 1700 && posicaoAtual < 2398:
                $("#menu a:eq(0)").trigger('click');
                proximaPosicao = 0;
                ativoScroll = false;
                break;


            case posicaoAtual >= 2800 && posicaoAtual < 4000:
                $("#menu a:eq(2)").trigger('click');
                proximaPosicao = 4796;
                ativoScroll = false;
                break;
            case posicaoAtual >= 4000 && posicaoAtual < 4796:
                $("#menu a:eq(1)").trigger('click');
                ativoScroll = false;
                proximaPosicao = 2398;
                break;


            case posicaoAtual >= 5656:
                $("#menu a:eq(0)").trigger('click');
                ativoScroll = false;
                proximaPosicao = 0;
                break;
        }
    } else {
        if(posicaoAtual == proximaPosicao) {
            ativoScroll = true;
            proximaPosicao = 0;
        }
    }
//$("#teste").html(posicaoAtual + " : " + proximaPosicao);
});
