function toolTips() {
    $(function () {
        var targets = $('[b2c-tooltip]'),
            target = false,
            tooltip = false,
            title = false;

        targets.bind('mouseenter', function () {
            target = $(this);
            tip = target.attr('b2c-tooltip-title');
            tooltip = $('<div b2c-tooltip-content></div>');

            if (!tip || tip == '')
                return false;

            target.removeAttr('b2c-tooltip-title');
            tooltip.css('opacity', 0)
                .html(tip)
                .appendTo('body');

            var inicia_tooltip = function () {
                if ($(window).width() < tooltip.outerWidth() * 1.5) {
                    tooltip.css('max-width', $(window).width() / 2);
                } else {
                    tooltip.css('max-width', 340);
                }
                var pos_left = target.offset().left + (target.outerWidth() / 2) - (tooltip.outerWidth() / 2),
                    pos_top = target.offset().top - tooltip.outerHeight() - 20;

                if (pos_left < 0) {
                    pos_left = target.offset().left + target.outerWidth() / 2 - 20;
                    tooltip.attr('b2c-tooltip-left', '');
                } else {
                    tooltip.removeAttr('b2c-tooltip-left');
                }

                if (pos_left + tooltip.outerWidth() > $(window).width()) {
                    pos_left = target.offset().left - tooltip.outerWidth() + target.outerWidth() / 2 + 20;
                    tooltip.attr('b2c-tooltip-right', '');
                } else {
                    tooltip.removeAttr('b2c-tooltip-right');
                }
                if (pos_top < 0) {
                    var pos_top = target.offset().top + target.outerHeight();
                    tooltip.attr('b2c-tooltip-top', '');
                } else {
                    tooltip.removeAttr('b2c-tooltip-top');
                }

                tooltip.css({left: pos_left, top: pos_top})
                    .animate({top: '+=10', opacity: 1}, 50);
            };

            inicia_tooltip();
            $(window).resize(inicia_tooltip);

            var remove_tooltip = function () {
                tooltip.animate({top: '-=10', opacity: 0}, 50, function () {
                    $(this).remove();
                });

                target.attr('b2c-tooltip-title', tip);
            };

            target.bind('mouseleave', remove_tooltip);
            tooltip.bind('click', remove_tooltip);
        });
    });
}

function iniciaSliderPrecoHotel() {
    var el = $(".slider-filtro-hotel");
    var slider = el.data('ionRangeSlider');
    if (typeof slider != "undefined") {
        slider.destroy();
    }
    el.ionRangeSlider({
        type: "double",
        prefix: el.data('prefix'),
        onChange: function (data) {
            var vlTotal = (B2C.getValorReserva() - B2C.getValorHotel());
            el.closest('.slider').find(".vlMin").text(Math.round(data.from + vlTotal));
            el.closest('.slider').find(".vlMax").text(Math.round(data.to + vlTotal));
        },
        onFinish: function (data) {
            B2C.hotel.init(true);
        },
        prettify: function (num) {
            return Math.round(num + (B2C.getValorReserva() - B2C.getValorHotel()));
        }
    });
}

function iniciaSliderPrecoAereo() {
    var el = $(".slider-filtro-preco-aereo");
    var slider = el.data('ionRangeSlider');
    if (typeof slider != "undefined") {
        slider.destroy();
    }
    el.ionRangeSlider({
        type: "double",
        prefix: el.data('prefix'),
        onChange: function (data) {
            var vlTotal = (B2C.getValorReserva() - B2C.getValorAereo());
            el.closest('.slider').find(".vlMin").text(Math.round(data.from + vlTotal));
            el.closest('.slider').find(".vlMax").text(Math.round(data.to + vlTotal));
        },
        onFinish: function (data) {
            B2C.aereo.init(true);
        },
        prettify: function (num) {
            return Math.round(num + (B2C.getValorReserva() - B2C.getValorAereo()));
        }
    });
}

function iniciaSliderPeriodoAereo() {
    var $rangeHora = $(".hora-slider");
    var start = moment("00:00", "HH:mm");
    var end = moment("23:59", "HH:mm");

    $rangeHora.ionRangeSlider({
        type: "double",
        hide_min_max: true,
        grid: false,
        min: start.format("x"),
        max: end.format("x"),
        step: 1800000, // 30 minutes in ms
        prettify: function (num) {
            return moment(num, 'x').format("H:mm");
        },
        onFinish: function (data) {
            $(data.input).attr('data-b2c-periodo', JSON.stringify([moment(data.from, "x").format("HH:mm"), moment(data.to, "x").format("HH:mm")]));
            B2C.aereo.init(true);
        },
        onUpdate: function (data) {
            $(data.input).attr('data-b2c-periodo', JSON.stringify([moment(data.from, "x").format("HH:mm"), moment(data.to, "x").format("HH:mm")]));
            B2C.aereo.init(true);
        }
    });

    $(document).off('click.sliderHoraPerido');
    $(document).on('click.sliderHoraPerido', '.horarios-periodos a ', function (event) {
        var btn = $(this);
        var slider = $(btn.attr('data-slider')).data("ionRangeSlider");
        slider.update({
            from: moment(btn.attr("data-from"), "HH:mm").format("x"),
            to: moment(btn.attr("data-to"), "HH:mm").format("x")
        });
    });
}

function iniciaSliderDuracaoAereo() {

    function init($rangeDuracao) {
        var end = $rangeDuracao.attr('data-b2c-duracao');

        var values = ['00:00'];
        var a = Math.ceil(Number(end) / 10) * 10;

        function paddingLeft(value, paddingValue) {
            return String(paddingValue + value).slice(-paddingValue.length);
        }

        while (a > 0) {
            var print = paddingLeft(a, "0000");
            if (print.slice(2, 4) <= 60) {
                values.push(print);
            }
            a = a - 10;
        }
        values = values.sort();
        $($rangeDuracao).attr('data-b2c-duracao', values[values.length - 1]);
        $rangeDuracao.ionRangeSlider({
            type: "single",
            hide_min_max: false,
            grid: false,
            from: values[values.length - 1],
            values: values,
            prettify: function (num) {
                return paddingLeft(num.toString(), "0000").replace(/(\d{2})(\d{2})/, '$1:$2');
            },
            onFinish: function (data) {
                $(data.input).attr("data-b2c-duracao", paddingLeft(data.from_value.toString(), "0000").replace(/(\d{2})(\d{2})/, '$1:$2'));
                B2C.aereo.init(true);
            }
        });
    }

    init($('[data-b2c-input="inboundDurationRange"]'));
    init($('[data-b2c-input="outboundDurationRange"]'));
}

function motorJS() {
    $('.pnlMotor input.idDestino').off('click.selected');
    $('.pnlMotor input.idDestino').on('click.selected', function () {
        $(this).select();
    });
    $('.pnlMotor input.idOrigem').off('click.selected');
    $('.pnlMotor input.idOrigem').on('click.selected', function () {
        $(this).select();
    });
}

function initJSHotelPesquisa() {
    motorJS();

    iniciaSliderPrecoHotel();
    $('.hotel-select-nome').selectpicker();

    $('select.hotel-select-nome').on('change', function () {
        if ($(this).val() != '' && $(this).val() != null) {
            B2C.hotel.init(true);
        }
    });

    $('.btn-limpa-filtro-nome').on('click', function () {
        if ($('select.hotel-select-nome').val() != '' && $('select.hotel-select-nome').val() != null) {
            $('.hotel-select-nome').selectpicker('val', '');
            B2C.hotel.init(true);
        }
        $('.hotel-select-nome').selectpicker('val', '');
    });

    $(document).on('click', '.paginacao ul li a', function (e) {
        if (!$(this).hasClass('disabled')) {
            setTimeout(function () {
                $('html,body').animate({
                    scrollTop: $(".submenu").offset().top
                }, 'slow');
            }, 50);
        }
    });
}

function initJSAereoPesquisa() {
    motorJS();

    iniciaSliderPrecoAereo();
    iniciaSliderPeriodoAereo();
    iniciaSliderDuracaoAereo();

    $(document).on('click', '.detalhe-btn', function (event) {
        var $link = $(event.target);
        event.preventDefault();
        event.stopImmediatePropagation();
        if (!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {

            var next = $(this).closest('.voo-item').next();

            if (!next.hasClass('detalhe-aberto')) {
                $(this).closest('.aereo-item').find('.voo-item-detalhe').each(function (i, v) {
                    if ($(v).hasClass('detalhe-aberto')) {
                        $(v).slideToggle();
                        $(v).prev().find('.detalhe-btn').removeClass('rotate180');
                    }
                    $(v).removeClass('detalhe-aberto');
                });
                if (next.hasClass('voo-item-detalhe')) {
                    next.slideToggle();
                    next.addClass('detalhe-aberto');
                }
            } else {
                if (next.hasClass('voo-item-detalhe')) {
                    next.slideToggle();
                    next.removeClass('detalhe-aberto');
                }
            }

            $(this).toggleClass('rotate180');
        }
        $link.data('lockedAt', +new Date());
    });

    $(document).on('click', '.voo-check', function (event) {
        // var $link = $(event.target);
        // if (!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
        var next = $(this).closest('.voo-item').next();

        $(this).closest('.voo-section').find('.voo-check').removeClass('active');
        // $(this).find('.voo-check').addClass('active');
        $(this).addClass('active');

        // }
        // $link.data('lockedAt', +new Date());
    });

    $(document).on('click', '.filtro-titulo', function (event) {
        var $link = $(event.target);
        event.preventDefault();
        if (!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
            $(this).next().slideToggle();
            $(this).find('.icone').toggleClass('rotate180');
        }
        $link.data('lockedAt', +new Date());
    });

    toolTips();
}

function initJSHotelDetalhe() {
    motorJS();
    // $(document).off('click.lermaishotel');
    // $(document).on('click.lermaishotel', '.page-detail .box .descricao .btn-ver-mais', function () {
    //     console.log($('.page-detail .box .descricao .descricao-conteudo'));
    //     $(this).find('i').toggleClass('fa-chevron-down fa-chevron-up');
    //     $('.page-detail .box .descricao .descricao-conteudo').toggleClass('maxHeight');
    // });

    var $lg = $('#lightgallery');
    $lg.lightGallery({
        pager: true,
        download: false,
        loop: true,
        counter: false,
        thumbnail: true,
        autoplay: true,
        share: true,
        hash: false,
        fullScreen: true,
    });
    if (ST_IFRAME) {
        $lg.on('onAfterOpen.lg', function () {
            $lg.data('lightGallery').modules.fullscreen.requestFullscreen();
        });
    }

    $(document).on('click.alterauh', '.box-quarto .col-tarifas .tarifa', function (e) {
        if (!$(this).hasClass('off')) {
            $('.box-quarto .col-tarifas .tarifa').removeClass('active');
            $(this).addClass('active');
        }
    });

    $(".abre-detalhes-pacote").on('click', function (event) {
        var $link = $(event.target);
        event.preventDefault();
        if (!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
            var detalhePacote = $(this).closest('[data-b2c-pacote-detalhe]');

            detalhePacote.find('.abre-detalhes-pacote').toggleClass('rotate');
            detalhePacote.find('.pacote-detalhe-content').slideToggle();
        }
        $link.data('lockedAt', +new Date());
    });

    $(".pacote-detalhe-content ul.nav-tabs li ").on('click', function (event) {
        event.preventDefault();

        const el = $(this);

        el.closest('[data-b2c-pacote-detalhe]').find('ul li').removeClass('current');
        el.closest('[data-b2c-pacote-detalhe]').find('.tab-content').hide();

        el.addClass('current');
        $(el.find('a').attr('rel')).show();
    });

    // $(window).scroll(function fix_element() {
    //     if ($(window).width() > 1200) {
    //         $('.box-sidebar').css(
    //             $(window).scrollTop() > 159
    //                 ? {'position': 'fixed', 'top': '2px'}
    //                 : {'position': 'relative', 'top': 'auto'}
    //         );
    //     }
    //     return fix_element;
    // }());

    function slidetoggle() {

        document.querySelectorAll(this.getAttribute('data-slidetoggle-height')).forEach(el => {

            var min = this.getAttribute('data-min-height') || 0;
            min = Number(min);

            const ch = el.clientHeight,
                sh = el.scrollHeight,
                isCollapsed = min > 0 ? ch == min : !ch,
                noHeightSet = false; //!el.style.height;

            el.style.height = (isCollapsed || noHeightSet ? sh : min) + "px";
            if (noHeightSet) return slidetoggle.call(this);
        });
    }

    document.querySelectorAll("[data-slidetoggle-height]").forEach(function (el) {
        el.addEventListener('click', slidetoggle);
    });

    toolTips();
}

function initJSServicoDetalhe() {
    motorJS();

    $('.page-servico .nav-tabs li').on('click', function (e) {
        var li = $(this);
        var rel = li.find('a').attr('rel');

        $('.page-servico .nav-tabs li').removeClass('current');
        li.addClass('current');

        $('.page-servico .tab-content-list .tab-content').hide();

        $(rel).show();
    });

}

function setMascaras() {
    window.mascaras = [];
    Array.prototype.forEach.call($('input[name="nrTelefone"]'), function (element) {
        if (B2C.lang == "pt_BR") {
            var select = $(element).parent().parent().find('select[name="tpTelefone"]').val();
            var mask = '(00) [0]0000-0000';
            if (typeof select != "undefined") {
                if (select == "RESIDENCIAL") {
                    mask = '(00) 0000-0000';
                }
            }
            if (mask != null) {
                var mascara = new IMask(element, {
                    mask: mask
                });
                window.mascaras.push(mascara);
            }
        }
    });
    Array.prototype.forEach.call($('input[name="nrDocumento"]'), function (element) {
        if (B2C.lang == "pt_BR") {
            var select = $(element).parent().parent().find('select[name="tpDocumento"]').val();
            var mask = '000.000.000-00';
            if (typeof select != "undefined") {
                if (select == "PASSAPORTE" || select == "RG") {
                    mask = null;
                }
            }
            if ($(element).hasClass('passaporte')) {
                mask = null;
            }
            if (mask != null) {
                var mascara = new IMask(element, {
                    mask: mask
                });
                window.mascaras.push(mascara);
            }
        }
    });
    Array.prototype.forEach.call($('input[name="dtNascimento"]'), function (element) {
        var mascara = new IMask(element, {
            mask: '00/00/0000'
        });
        window.mascaras.push(mascara);
    });
    Array.prototype.forEach.call($('input[name="nrCep"]'), function (element) {
        var unmask = $(element).attr('unmask');
        if(!unmask){
            if (B2C.lang == "pt_BR") {
                var mascara = new IMask(element, {
                    mask: '00000-000'
                });
                window.mascaras.push(mascara);
            }
        }
    });
    Array.prototype.forEach.call($('input[name="nrCartao"]'), function (element) {
        var mascara = new IMask(element, {
            mask: '0000 0000 0000 0000'
        });
        window.mascaras.push(mascara);
    });
    Array.prototype.forEach.call($('input[name="mesAnoValidade"]'), function (element) {
        var mascara = new IMask(element, {
            mask: '00/0000'
        });
        window.mascaras.push(mascara);
    });
    Array.prototype.forEach.call($('input[name="cdSeguranca"]'), function (element) {
        var mascara = new IMask(element, {
            mask: '0000'
        });
        window.mascaras.push(mascara);
    });
    Array.prototype.forEach.call($('input[name="valor"]'), function (element) {
        $(element).mask('000.000.000.000.000,00', {reverse: true});
    });
}

function initJSCheckout() {

    setMascaras();

    $('[data-b2c-input="mesmoPagador"]').off('change.mesmoPagador');
    $('[data-b2c-input="mesmoPagador"]').on('change.mesmoPagador', function () {
        $('[data-b2c-segundo-pagador]').slideToggle();
    });

    $("[data-b2c-pacote-sidebar] ul.nav-tabs li ").on('click', function (event) {
        event.preventDefault();

        const el = $(this);

        el.closest('[data-b2c-pacote-sidebar]').find('ul li').removeClass('current');
        console.log(el.closest('[data-b2c-pacote-sidebar]').find('ul li a'))
        el.closest('[data-b2c-pacote-sidebar]').find('ul li a').removeClass('border-bottom-azul-1');
        el.closest('[data-b2c-pacote-sidebar]').find('.tab-content').hide();


        el.addClass('current');
        el.find('a').addClass('border-bottom-azul-1');
        $(el.find('a').attr('rel')).show();
    });

    $(".cel").bind('focusin', function (event) {
        var target, phone, element;
        target = (event.currentTarget) ? event.currentTarget : event.srcElement;
        element = $(target);
        element.unmask();
        element.mask("(99) 99999-9999");
    }).bind('focusout', function (event) {
        var target, phone, element;
        target = (event.currentTarget) ? event.currentTarget : event.srcElement;
        phone = target.value.replace(/\D/g, '');
        element = $(target);
        element.unmask();
        if (phone.length > 10) {
            element.mask("(99) 99999-9999");
        } else {
            element.mask("(99) 9999-9999");
        }
    });

    $(document).off('change.tel.doc');
    $(document).on('change.tel.doc', 'select[name="tpTelefone"], select[name="tpDocumento"]', function (e) {
        window.mascaras.filter(function (mascara) {
            mascara.destroy();
        });
        window.mascaras = [];
        var input = $(this).parent().find('input[name="nrDocumento"]');
        input.val("");
        setMascaras();
    });

    $('[data-b2c-input="mesmoPagador"]').off('change.msmpagto');
    $('[data-b2c-input="mesmoPagador"]').on('change.msmpagto', function (e) {

        if ($(this).is(":checked")) {
            $('[data-b2c-segundo-pagador]').attr('data-b2c-selected', 'falsse');
        } else {
            $('[data-b2c-segundo-pagador]').attr('data-b2c-selected', 'true');
        }
    });

    $(document).off('click.pagto-li');
    $(document).on('click.pagto-li', '.form-pagto ul li', function () {
        var attr = $(this).attr('data-b2c-change');
        $('.form-pagto ul li').removeClass('current');
        $(this).addClass('current');

        if (attr === '#0C') {
            $('.pag-um-cart').show();
            $('.pag-dois-cart').hide();
        } else if (attr === '#2C') {
            $('.pag-um-cart').hide();
            $('.pag-dois-cart').show();
        }
    });

    $(document).off('click.tp-pagto');
    $(document).on('click.tp-pagto', '[data-b2c-tp-pagto]', function (event) {
        var $link = $(event.target);
        event.preventDefault();
        if (!$link.data('lockedAtS') || +new Date() - $link.data('lockedAtS') > 300) {

            $(this).closest('[data-b2c-checkout-pagamentos]').find('button .check').removeClass('checked');
            $(this).find('button .check').addClass('checked');

            if (!$(event.target).hasClass('btn')) {
                $(this).find('button').trigger('click');
            }
        }
        $link.data('lockedAtS', +new Date());
    });

    function fix_element() {
        if ($(window).width() > 1000) {
            $('.box-resumo').css(
                $(window).scrollTop() > 159
                    ? {
                        'position': 'fixed',
                        'top': '2px',
                        'width': $('[data-b2c-valores-checkout-sidebar]').width(),
                        'z-index': 1
                    }
                    : {'position': 'relative', 'top': 'auto'}
            );
        } else {
            $('[data-b2c-valores-checkout-mobile]').css(
                $(window).scrollTop() > 62
                    ? {
                        'position': 'fixed'
                    }
                    : {'position': 'relative'}
            );
        }
        return fix_element;
    }

    $(window).scroll(fix_element());
    $(window).resize(fix_element());

    $('[data-b2c-tp-pagto]').eq(0).find('button').trigger('click');
}

$(".nrCupom").focusout(function () {
    ("" === $(this).val()) ? $(this).removeClass("ativo") : $(this).addClass("ativo");
});

function montaDescricaoPaxmotor(form) {

    var qtUh = form.find('.quartoItem').length;
    var qtAdt = 0;
    var qtSnr = 0;
    var qtChd = 0;

    form.find('.quartoAdt select').each(function () {
        qtAdt += Number($(this).val());
    });

    form.find('.quartoSnr select').each(function () {
        qtSnr += Number($(this).val());
    });

    form.find('.quartoChd select').each(function () {
        qtChd += Number($(this).val());
    });

    var value = '';

    if (qtUh && !form.hasClass('aereo') && !form.hasClass('servico')) {
        if (qtUh > 1) {
            value += qtUh + ' ' + __('quartos') + ', '
        } else {
            value += qtUh + ' ' + __('quarto') + ', '
        }
    }

    if (qtAdt) {
        if (qtAdt > 1) {
            value += qtAdt + ' ' + __('adultos');
        } else {
            value += qtAdt + ' ' + __('adulto');
        }
    }

    if (qtSnr) {
        if (qtSnr > 1) {
            value += (value.trim().slice(-1) != ',' ? ', ' : '') + qtSnr + ' ' + __('seniors');
        } else {
            value += (value.trim().slice(-1) != ',' ? ', ' : '') + qtSnr + ' ' + __('senior');
        }
    }

    if (qtChd) {
        if (qtChd > 1) {
            value += (value.trim().slice(-1) != ',' ? ', ' : '') + qtChd + ' ' + __('criancas');
        } else {
            value += (value.trim().slice(-1) != ',' ? ', ' : '') + qtChd + ' ' + __('crianca');
        }
    }

    form.find('.fake-input').text(value);
}

$(document).off('click.fi');
$(document).off('touch.fi');
$(document).on('click.fi touch.fi', '.fake-input', function (e) {
    e.preventDefault();
    $(this).closest('form').find('.box-pax').eq(0).slideToggle();
});

$(document).off('click.abq');
$(document).off('touch.abq');
$(document).on('click.abq touch.abq', '.box-pax > a', function (e) {
    e.preventDefault();
    $(this).closest('.box-pax').slideToggle();

    var form = $(this).closest('.pnlMotor');
    montaDescricaoPaxmotor(form);
});

$(document).off('click.bab');
$(document).on('click.bab', '.btn-alterar-busca', function (e) {
    e.preventDefault();
    $('.submenu').slideToggle();
});

$(document).off('click.fbab');
$(document).on('click.fbab', '.pnlMotor .header a', function (e) {
    e.preventDefault();
    $('.submenu').slideToggle();
});