var win_width = $(window).innerWidth();
var APP = APP || {};
(function ($) {
    // USE STRICT
    'use strict';
    APP.initialize = {
        init: function () {
            APP.initialize.defaults();
            APP.initialize.background();
            APP.initialize.changeImgSvg('body');
            APP.initialize.setUrlLang();
            APP.initialize.goTopStart();
            APP.initialize.boxSearch('.searchTop');
            // APP.initialize.searchAutocomplete('.pvt_box_search .search-box');
            APP.initialize.changeImgSvg('body');
            APP.initialize.fixslideSlick('.slick-slider');
            APP.initialize.owlSlide();
            APP.initialize.bannerPopup('#pvt-bannerPopup');
            // APP.initialize.responsiveMobile();
            // APP.initialize.sliderBanner('#pvt-slide-page');

            /*============================================================*/
            if (APP.initialize.elmCheck('#pvt-banner-popup')) {
                var s = document.createElement('script');
                s.type = 'text/javascript';
                if (document.location.hostname == 'localhost') {
                    s.src =
                        '//' +
                        document.location.hostname +
                        '/tu_bep_bien_hoa/public/js/fancybox/jquery.fancybox.min.js';
                } else {
                    s.src =
                        '//' +
                        document.location.hostname +
                        '/public/js/fancybox/jquery.fancybox.min.js';
                }
                $('head').append(s);
                APP.initialize.set_banner_popup();
            }
            /*============================================================*/
        },
        elmCheck: function (elm) {
            return $('body, html').find(elm).length;
        },
        defaults: function () {
            // alert('Height: '+$(window).innerHeight()+'px');
            /* WOW */
            if (APP.initialize.elmCheck('.wow')) {
                new WOW().init();
            }
            if (APP.initialize.elmCheck('[data-aos]')) {
                AOS.init();
            }
            if (APP.initialize.elmCheck('.entry')) {
                var iframe = $('.entry').find('iframe');
                $(iframe).wrap(
                    '<div class="embed-responsive embed-responsive-16by9"></div>'
                );
                $(iframe).addClass('embed-responsive-item');
            }
        },
        background: function () {
            if (win_width >= 1024) {
                $('[data-bg-image]').each(function () {
                    var img = $(this).data('bg-image');

                    $(this).css({
                        backgroundImage: 'url(' + img + ')',
                    });
                });
                $('[data-parallax="image"]').each(function () {
                    var actualHeight = $(this).position().top;
                    var speed = $(this).data('parallax-speed');
                    var reSize = actualHeight - $(window).scrollTop();
                    var makeParallax = -(reSize / 2) - 0;
                    var posValue = makeParallax + 'px';
                    var posValue_x = $(this).data('parallax-x')
                        ? $(this).data('parallax-x')
                        : '50';

                    if (win_width <= 768) {
                        $(this).css({
                            backgroundPosition: posValue_x + '% ' + posValue,
                        });
                    } else {
                        $(this).css({
                            backgroundPosition: posValue_x + '% ' + posValue,
                        });
                    }
                });
            }
        },
        sliderBanner: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                if ($(elm).find('a').length >= 2) {
                    $(elm).owlCarousel({
                        nav: false,
                        navText: [],
                        autoplay: true,
                        loop: true,
                        dots: true,
                        autoplayTimeout: 4000,
                        autoplayHoverPause: true,
                        autoplaySpeed: 3000,
                        rewindNav: true,
                        items: 1,
                        animateOut: 'fadeOut',
                    });
                }
            }
        },
        boxSearch: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $(elm)
                    .find('.icon')
                    .click(function () {
                        $('.pvt_box_search')
                            .find('input')
                            .trigger('start_search');
                        $('.pvt_box_search')
                            .find('.btn-cancel')
                            .removeClass('hidden');
                        if (!$(this).parents(elm).hasClass('active')) {
                            $(this).parents(elm).addClass('active');
                        } else {
                            $(this).parents(elm).removeClass('active');
                        }
                    });
                APP.initialize.start_search();
                $(window).bind('click', function (e) {
                    if (!$(e.target).parents(elm).hasClass('active')) {
                        $(elm).removeClass('active');
                    }
                });
            }
        },
        ajaxSearch: function (keyword) {
            $.ajax({
                url: ajaxurl + '?do=ajaxSearch',
                type: 'POST',
                dataType: 'json',
                data: {
                    keyword: keyword,
                    lang: lang,
                },
                success: function (res) {
                    if (res) {
                        // $('body').addClass('open-search');
                    } else {
                        $('body').removeAttr('class');
                    }
                    $('.box-result-search').html(res);
                },
            });
        },
        start_search: function () {
            var overlayBg = $('.overlay-bg');
            $('.pvt_box_search').each(function () {
                var elm = this,
                    jelm = $(elm),
                    jinput = jelm.find('input'),
                    jcontainer = $('#pvt-wrapper');
                jinput.on('start_search', function () {
                    elm.overlayBg = $('<div class="overlay-bg"></div>');
                    if (!jcontainer.find('.overlay-bg').length) {
                        jcontainer.append(elm.overlayBg);
                    }
                    elm.overlayBg.show();
                    jcontainer.addClass('search-mode');
                    jelm.find('.btn-cancel').on('click', function () {
                        jinput.val('').focus();
                    });
                    jelm.parent()
                        .find('.btn-cancel')
                        .on('click', function () {
                            jinput.val('');
                            $('.overlay-bg').remove();
                            jcontainer.removeClass('search-mode');
                            $(this).parents('.searchTop').removeClass('active');
                            $('body').removeClass('overflow-hidden');
                        });
                    elm.overlayBg.on('click', function () {
                        jelm.find('.btn-cancel').trigger('click');
                    });
                    $('body').addClass('overflow-hidden');
                });
            });
        },
        setUrlLang: function () {
            var elm = $('link[rel=alternate]');
            elm.each(function (i, e) {
                var href = $(e).attr('href');
                var lang = $(e).attr('hreflang');
                $('.languages > a, .menu-lang-mobile > a').each(function (
                    i,
                    e
                ) {
                    if ($(e).hasClass('active')) {
                        $(e).attr('href', 'javascript:;');
                    } else {
                        if ($(e).data('name') == lang) {
                            $(e).attr('href', href);
                        }
                    }
                });
            });
        },
        goTopStart: function () {
            $('#pvt-footer').append(
                '<a href="javascript:void(0)" onclick="jQuery(\'html,body\').animate({scrollTop: 0},1000);" class="go_top" style="display:none"><span class="icon"></span></a>'
            );
            $(window).scroll(function () {
                var top = $(window).scrollTop();
                if (top > 0) {
                    $('.go_top').show();
                } else {
                    $('.go_top').hide();
                }
            });
        },
        scrollTop: function (elm, height, time) {
            $(window).scroll(function () {
                if ($(window).scrollTop() == height) {
                    elm.stop(false, true).fadeOut(time);
                } else {
                    elm.stop(false, true).fadeIn(time);
                }
            });
            obj.click(function () {
                $('body,html').animate({ scrollTop: 0 }, time);
                return false;
            });
        },

        loadMenuMobile: function (elm) {
            APP.initialize.addMenuMobile(elm);
        },
        addMenuMobile: function (elm) {
            $('body').addClass('responsive');
            $('#mmenu').removeClass('hide');
            if (APP.initialize.elmCheck('.btn-menu') == 0) {
                $(elm).prepend('<a id="ico-bar" href="#mmenu"></a>');
                $(elm).find('#ico-bar').append('<span></span>');
                $(elm).find('#ico-bar').append('<span class="center"></span>');
                $(elm).find('#ico-bar').append('<span></span>');
            }
            APP.initialize.mmenu('#mmenu');
        },
        removeMenuMobile: function () {
            $('body').removeClass('responsive');
            $('#mmenu').addClass('hide');
            $('#ico-bar').remove();
        },
        mmenu: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                // var get_search = $(".pvt_box_search").find('.form').html();
                // var box_search_mobile = "<div class='pvt_box_search_mobile'>"+get_search+"</div>";
                $(elm).mmenu({
                    extensions: ['theme-light', 'effect-menu-slide'],
                    offCanvas: {
                        position: 'right',
                        zposition: 'front',
                    },
                    slidingSubmenus: false,
                });
                var API = $(elm).data('mmenu');
                $('.mm-btn-close').click(function () {
                    API.close();
                });
            }
        },
        searchAutocomplete: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $('.search-all', elm).click(function () {
                    $('#search_autocomplete ul').hide();
                });

                $('ul.dropdown-menu li:first-child a', elm).click(function () {
                    $('.search-all', elm).html(
                        'Tất cả <span class="caret"></span>'
                    );
                    $('input[name="w_search"]', elm).val('');
                });
                $('ul.dropdown-menu li:not(:first-child) a', elm).click(
                    function () {
                        var text = $(this).html();
                        var id = $(this).attr('id');
                        id = id.substr(2);
                        $('.search-all', elm).html(
                            text + '<span class="caret"></span>'
                        );
                        $('input[name="w_search"]', elm).val(id);
                    }
                );
            }
        },
        changeImgSvg: function (e) {
            $(e)
                .find('img.svg')
                .each(function () {
                    $(this).hide();
                    var $img = $(this);
                    var imgID = $img.attr('id');
                    var imgClass = $img.attr('class');
                    var imgURL = $img.attr('src');
                    $.get(
                        imgURL,
                        function (data) {
                            // Get the SVG tag, ignore the rest
                            var $svg = $(data).find('svg');
                            // Add replaced image's ID to the new SVG
                            if (typeof imgID !== 'undefined') {
                                $svg = $svg.attr('id', imgID);
                            }
                            // Add replaced image's classes to the new SVG
                            if (typeof imgClass !== 'undefined') {
                                $svg = $svg.attr(
                                    'class',
                                    imgClass + ' replaced-svg'
                                );
                            }
                            // Remove any invalid XML tags as per http://validator.w3.org
                            $svg = $svg.removeAttr('xmlns:a');
                            // Replace image with new SVG
                            $img.replaceWith($svg);
                        },
                        'xml'
                    );
                });
        },
        newsletter: function (elm) {
            // var frm = $("form[name=newsletter]");
            var ok = 1;
            if (APP.initialize.elmCheck(elm)) {
                elm.find('button[type=button]').on('click', function () {
                    var email = elm.find('input[name=f_n]').val();
                    if (!APP.initialize.is_email(email) || email.length == '') {
                        jAlert(
                            'Vui lòng nhập Email của bạn!',
                            'Báo lỗi',
                            function () {
                                elm.find('input[name=f_n]').focus();
                            }
                        );
                        ok = 0;
                    }
                    if (ok) {
                        $.ajax({
                            type: 'POST',
                            url: ajaxurl + '?do=newsletter',
                            dataType: 'json',
                            data: { email: email },
                            success: function (data) {
                                if (data.ok) {
                                    jAlert(
                                        data.mess,
                                        jLang['announce'],
                                        function () {
                                            location.reload();
                                        }
                                    );
                                } else {
                                    jAlert(
                                        data.mess,
                                        jLang['announce'],
                                        function () {
                                            elm.find('input[name=f_n]').focus();
                                        }
                                    );
                                }
                            },
                        });
                    }
                    return false;
                });
            }
        },
        loadImg: function () {
            $('img.lazy').lazyload({
                threshold: 200,
                effect: 'fadeIn',
            });
            $('img.lazy').on('appear', function () {
                $(this).removeClass('lazy');
                $(this).removeClass('banner-blur');
            });
        },
        loadImgDiv: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $(elm).find('img.lazy').lazyload({
                    threshold: 300,
                    effect: 'fadeIn',
                });
                $('img.lazy').on('appear', function () {
                    $(this).removeClass('lazy');
                    $(this).removeClass('banner-blur');
                });
            }
        },
        slideSlick: function (elm, numShow) {
            var show = numShow ? numShow : 4;
            if (APP.initialize.elmCheck(elm)) {
                $(elm).slick({
                    slidesToShow: show,
                    slidesToScroll: 2,
                    daptiveHeight: false,
                    arrows: true,
                    dots: false,
                    autoplay: false,
                    fade: false,
                    speed: 800,
                    pauseOnHover: true,
                    infinite: false,
                });
            }
        },
        unslideSlick: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $(elm).slick('unslick');
            }
        },
        fixslideSlick: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $(elm).each(function (i, e) {
                    var divParent = $(this);
                    $(divParent)
                        .find('button.slick-arrow')
                        .on('click', function () {
                            APP.initialize.loadImgDiv(divParent);
                            $(divParent).find('img.lazy').trigger('appear');
                        });
                });
            }
        },
        owlSlide: function () {
            var owl = $('.owl-slide');
            if (APP.initialize.elmCheck(owl)) {
                owl.owlCarousel({
                    nav: false,
                    navText: [],
                    autoplay: true,
                    loop: true,
                    dots: true,
                    autoplayTimeout: 4000,
                    autoplayHoverPause: true,
                    autoplaySpeed: 3000,
                    rewindNav: true,
                    items: 1,
                    //animateOut: 'slideOutDown',
                    //animateIn: 'flipInX',
                });
                $('.owl-slide-arrows .prev').click(function () {
                    owl.trigger('prev.owl.carousel');
                });

                $('.owl-slide-arrows .next').click(function () {
                    owl.trigger('next.owl.carousel');
                });
            }
        },
        loadStatistics: function () {
            $.ajax({
                type: 'POST',
                url: ajaxurl + '?do=statistics',
                dataType: 'json',
                success: function (data) {
                    $('#counter-online').html(data.online);
                    $('#counter-hits').html(data.hits);
                },
            });
        },
        bannerPopup: function (elm) {
            if (APP.initialize.elmCheck(elm)) {
                $(elm)
                    .find('.fancyboxPopup')
                    .fancybox({
                        width: 600,
                        height: 500,
                        maxWidth: '90%',
                        maxHeight: '90%',
                        fitToView: true,
                        autoSize: true,
                        closeClick: true,
                        padding: 5,
                        openEffect: 'fade',
                        overlayShow: true,
                        titleShow: false,
                        scrollOutside: true,
                        helpers: {
                            overlay: {
                                closeClick: true,
                                speedOut: 200,
                                showEarly: true,
                                css: {
                                    background: 'rgba(0, 0, 0, 0.8)',
                                },
                                locked: true,
                                fixed: true,
                            },
                            title: null,
                        },
                        beforeShow: function () {
                            // $.fancybox.wrap.bind('contextmenu', function (e) {
                            //     return false;
                            // });
                            var link_url = $('.fancyboxPopup').data('link');
                            $('.fancybox-image').on('click', function () {
                                window.open(link_url, '_blank');
                            });
                        },
                        afterClose: function () {},
                    });
                setTimeout(function () {
                    $(elm).find('.fancyboxPopup').trigger('click');
                }, 5000);
            }
        },
        responsiveMobile: function () {
            $('#box-menu .widget-title').click(function () {
                if (!$(this).parents('#box-menu').hasClass('active')) {
                    $(this).parents('#box-menu').addClass('active');
                    $(this)
                        .parents('#box-menu')
                        .find('.widget-content')
                        .stop()
                        .slideDown(300);
                } else {
                    $(this).parents('#box-menu').removeClass('active');
                    $(this)
                        .parents('#box-menu')
                        .find('.widget-content')
                        .stop()
                        .slideUp(300);
                }
            });
            $(window).resize(function () {
                var win_width = $(window).innerWidth();
                if (win_width > 991) {
                    $('#box-menu')
                        .find('.widget-content')
                        .css({ display: 'block' });
                    $('#box-menu').removeClass('active');
                } else {
                    $('#box-menu')
                        .find('.widget-content')
                        .css({ display: 'none' });
                }
            });
            /*----------*/
            if (win_width <= 768) {
                var copyright = $('.footer_main_left')
                    .find('.box_copyright')
                    .html();
                $('#pvt-footer').append(
                    '<div class="box_copyright_mobile">' + copyright + '</div>'
                );
            }
        },
        popup_notification: function (type, mess, eventClose) {
            var type_notifi = type ? type : 'notice';
            var messNotifi;
            switch (type_notifi) {
                case 'notice':
                case 'success':
                    messNotifi = mess;
                    break;
                case 'error':
                    messNotifi = mess;
                    break;
                default:
                    messNotifi = mess;
                    break;
            }
            var notification = new NotificationFx({
                wrapper: document.body,
                message: messNotifi,
                layout: 'attached',
                effect: 'bouncyflip',
                type: type_notifi,
                ttl: 4000,
            });
            if (eventClose) {
                notification.options.onClose = eventClose;
            } else {
                notification.options.onClose = function () {
                    return false;
                };
            }
            notification.show();
        },
        set_banner_popup: function () {
            $('#pvt-banner-popup .fancyboxPopup').fancybox({
                width: 600,
                height: 400,
                maxWidth: '90%',
                maxHeight: '90%',
                fitToView: true,
                autoSize: true,
                closeClick: true,
                padding: 0,
                openEffect: 'fade',
                overlayShow: true,
                titleShow: false,
                scrollOutside: true,
                helpers: {
                    overlay: {
                        closeClick: true,
                        speedOut: 200,
                        showEarly: true,
                        css: {
                            background: 'rgba(0, 0, 0, 0.8)',
                        },
                        locked: true,
                        fixed: true,
                    },
                    title: null,
                },
                beforeShow: function () {
                    // $.fancybox.wrap.bind('contextmenu', function (e) {
                    //     return false;
                    // });
                    var link_url = $('.fancyboxPopup').data('link');
                    $('.fancybox-image').on('click', function () {
                        window.open(link_url, '_blank');
                    });
                },
                afterClose: function () {},
            });

            setTimeout(function () {
                $('#pvt-banner-popup .fancyboxPopup').trigger('click');
                $('.fancybox-overlay')
                    .find('.fancybox-skin')
                    .css('background', 'none');
                $('.fancybox-overlay')
                    .find('.fancybox-skin')
                    .css('box-shadow', 'none');
            }, 5000);
        },
    };
    APP.documentOnReady = {
        init: function () {
            APP.initialize.init();
        },
    };
    APP.documentOnLoad = {
        init: function () {
            /* loader Init */
        },
    };
    APP.documentOnScroll = {
        init: function () {},
    };
    APP.documentOnResize = {
        init: function () {},
    };
    $(document).ready(APP.documentOnReady.init);
    $(window).on('load', APP.documentOnLoad.init);
    $(document).on('scroll', APP.documentOnScroll.init);
    $(window).on('resize', APP.documentOnResize.init);
})(jQuery);

/******************************MOBILE********************************************/
var MOBILE = {
    mmenu: function (elm) {
        $(elm).mmenu({
            extensions: ['theme-light', 'effect-menu-slide'],
            offCanvas: {
                position: 'right',
                zposition: 'front',
            },
            slidingSubmenus: false,
        });
        var API = $(elm).data('mmenu');
        /*
			$("#btnMenu").click(function() {
			API.open();
			});
		*/
        $('.mm-btn-close').click(function () {
            API.close();
        });
    },
    boxSearch: function (elm) {
        var btn = $(elm);
        btn.on('click', function () {
            if ($('body').hasClass('open-search')) {
                $('body').attr('class', 'mobile');
            } else {
                $('body').attr('class', 'mobile overlay open-search');
                $('.text-search').focus();
            }
        });
    },
    box_menu: function () {
        $('.box-menu').attr('id', 'box-sidebar');
        $('#box-sidebar').attr('class', 'widget');
        $('#box-sidebar').prepend('<div class="widget-title"></div>');
        $('#box-sidebar .widget-title').text($('h1').text());
        $('#box-sidebar').find('ul').wrap('<div class="widget-content"></div>');
        var cls = 'open';
        var btn = $('.widget-title');
        btn.on('click', function () {
            var _parent = $(this).parent();
            if (_parent.hasClass(cls)) {
                _parent.find('.widget-content').stop().slideUp();
                _parent.removeClass(cls);
            } else {
                _parent.find('.widget-content').stop().slideDown();
                _parent.addClass(cls);
            }
        });
    },
    init: function () {
        APP.initialize.loadMenuMobile('.pvt-tool-header');
        // MOBILE.mmenu('#mmenu');
        // MOBILE.boxSearch('.search-btn');
        MOBILE.box_menu();

        $('body').addClass('mobile');

        $('#pvt-main').attr('class', 'mobile');

        $('.footer-menu').on('click', function () {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $(this).find('ul:first').stop().slideUp();
            } else {
                $('.footer-menu').removeClass('open');
                $('.footer-menu').find('ul:first').stop().slideUp();
                $(this).addClass('open');
                $(this).find('ul:first').stop().slideDown();
            }
        });
    },
};
/**************************************************************************/
var INPUT = {
    is_num: function (event) {
        var kc;
        if (event.srcElement) {
            kc = event.keyCode;
        } else {
            kc = event.which;
        }
        if ((kc < 47 || kc > 57) && kc != 8 && kc != 0) return false;
        return true;
    },
    is_email: function () {
        return /^[a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i.test(
            APP.initialize.util_trim(str)
        );
    },
    util_trim: function (str) {
        return /string/.test(typeof str) ? str.replace(/^\s+|\s+$/g, '') : '';
    },
};

/**************************************************************************/
// cnTLoadAjax
$.fn.cnTLoadAjax = function ({ url, data }, callback) {
    var e = this[0];
    // ajax
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: {
            lang: lang,
            data: data,
        },
        beforeSend: function (jqXHR, settings) {
            e.classList.add('loading');
            $(e).append(
                '<div class="loading_icon"><img src="' +
                    root +
                    'public/images/preloader.gif" /></div>'
            );
        },
        success: function (response) {
            if (response.success) {
                // e.classList.add('box');
                e.classList.remove('loading');
                $('.loading_icon').remove();
            } else {
                e.parentNode.removeChild(e);
            }

            // callback
            if (typeof (callback === 'function') && callback) {
                callback(response, e);
            }
        },
    });
};

$.fn.loadAjax = function ({ module, action, showposts, data }, callback) {
    var e = this[0];
    data = data || {};
    data.showposts = showposts;

    $(e).cnTLoadAjax(
        {
            url: root + module + '/ajax/' + action,
            data: data,
        },
        function (response) {
            callback(response);
        }
    );
};
