var app_class = function ()
{
    var self = this;

    self.events = function ()
    {
        self.InitMenu();
        self.AddSubscribe();
        self.InitFixedMenu();
        self.InitScrollToTop();
        self.InitPhoneMask();
        self.InitFancyBox();
        self.InitPhoneMask();
        self.InitContactForm();
        self.InitDotDotDot();
        self.InitServiceBtn();
        self.initPrice();
        self.InitSwiper();
        self.InitObjectFitImages();
        self.InitResizeCategoriesMenu();
    }

    /****************************** METHOD'S ******************************/
    self.InitObjectFitImages = function () { 
        objectFitImages();
    };
    
    self.InitResizeCategoriesMenu = function() {

        var width = $(document).width();

        initResizeCategoriesMenu(width);

        $(window).resize(function(){

            width = $(document).width();

            initResizeCategoriesMenu(width);
        });

        $(window).on('scroll', function () {

            width = $(document).width();

            initResizeCategoriesMenu(width);
        });
    }
    
    self.InitSwiper = function() {
    //initialize swiper when document ready
            var mySwiperNews = new Swiper ('#news .swiper-container', {
                slidesPerView: 4,
                spaceBetween: 30,
                navigation: {
                    nextEl: '.nav-news .swiper-button-next',
                    prevEl: '.nav-news .swiper-button-prev',
                },
                breakpoints: {
                    0: {
                      slidesPerView: 1
                    },
                    400: {
                      slidesPerView: 1
                    },
                    764: {
                      slidesPerView: 1
                    },
                    1000: {
                      slidesPerView: 2
                    },
                    1200: {
                      slidesPerView: 3
                    }
                }
            });
            var mySwiperBrands = new Swiper ('#brands .swiper-container', {
                slidesPerView: 5,
                navigation: {
                    nextEl: '.nav-brands .swiper-button-next',
                    prevEl: '.nav-brands .swiper-button-prev',
                },
                breakpoints: {
                    400: {
                      slidesPerView: 1
                    },
                    600: {
                      slidesPerView: 2
                    },
                    900: {
                      slidesPerView: 3
                    },
                    1020: {
                      slidesPerView: 4
                    },
                }
            });
            var mySwiperProduct = new Swiper ('#carousel-product-1 .swiper-container, #carousel-product-2 .swiper-container, #carousel-product-3 .swiper-container', {
                slidesPerView: 4,
                navigation: {
                    nextEl: '.nav-product .swiper-button-next',
                    prevEl: '.nav-product .swiper-button-prev',
                },
                breakpoints: {
                    0: {
                      slidesPerView: 1
                    },
                    400: {
                      slidesPerView: 1
                    },
                    764: {
                      slidesPerView: 1
                    },
                    1000: {
                      slidesPerView: 2
                    },
                    1200: {
                      slidesPerView: 3
                    }
                }
            })
    }
    
    self.initPrice = function() {

        if( $("#summ-range-slider").length > 0 )
        {
            $("#summ-range-slider").slider().on('slideStop', function (ev) {
                
               
                $( 'input[name=min_sum]' ).val(ev.value[0]);

                $( 'input[name=max_sum]' ).val(ev.value[1]);
            });
        }
    }

    self.AddSubscribe = function() {
        $('#subscribe-form').off('submit').on('submit', function(e) {
            e.preventDefault();
            if (form_validate(this)) {
                $.ajax({
                    url: '/subscribes/ajax/add_subscribes',
                    data: new FormData(this),
                    dataType: 'json',
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: "POST",
                    beforeSend: function() {
                        $('#loader-pic').show();
                    },
                    complete: function() {
                        $('#loader-pic').hide();
                    },
                    success: function(obj) {
                        $("#message").text(obj.message);
                    }
                });
            }
        });
        $('#subscribe-footer').off('submit').on('submit', function(e) {
            e.preventDefault();
            if (form_validate(this)) {
                $.ajax({
                    url: '/subscribes/ajax/add_subscribes',
                    data: new FormData(this),
                    dataType: 'json',
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: "POST",
                    beforeSend: function() {
                        $('#loader-pic1').show();
                    },
                    complete: function() {
                        $('#loader-pic1').hide();
                    },
                    success: function(obj) {
                        $("#message1").text(obj.message);
                    }
                });
            }
        });
    }
    
    self.InitFixedMenu = function () {

        $(window).scroll(function(){

            var header_height = 100,
                menu_height   = 80;

            if( $(this).scrollTop() > header_height+menu_height  )
            {
                $('#header-top').addClass('fixed-header');
            }
            else if ( $(this).scrollTop() < header_height )
            {
                $('#header-top').removeClass('fixed-header');
            }
        });
    }

    self.InitScrollToTop = function()
    {
        var scrollup = $('#scrollToTop')

        $(window).scroll(function(){
            if( $(this).scrollTop() > 150 ) {
                scrollup.fadeIn();
            }
            else {
                scrollup.fadeOut();
            }
        });

        scrollup.click(function(){
            $("html, body").animate({ scrollTop: 0 }, 600);
            return false;
        });
    }

    self.InitPhoneMask = function()
    {
        $(".phone-mask").mask("+7 (999) 999-99-99");
    }

    self.InitMenu = function() {

        /*var height = 100;

        if( $('#categories-block').hasClass('tiny-categories') ) {

            height = 51;
        }

        if( $(window).scrollTop() > 0 && $('#categories-block').offset().top > height )
        {
            $( '#categories-block' ).addClass('static-block');
        }
        else
        {
            $( '#categories-block' ).removeClass('static-block');
        }

        $(window).scroll( function(){

            if( $(this).scrollTop() > height ) {

                $( '#categories-block' ).addClass('static-block').slideDown();
            }
            else
            {
                $( '#categories-block' ).removeClass('static-block');
            }
        });*/

        $('.catalogBtnShow').off('click').on('click', function () {

            $('#catalogCategoriesList').toggleClass('showCategoriesSideBar');

            if ( $('#catalogCategoriesList').hasClass('showCategoriesSideBar') ) {

                $(this).find('use').attr('xlink:href', '#productRemove');
            }
            else
            {
                $(this).find('use').attr('xlink:href', '#menu-icon')
            }

            if ( $(document).width() < 992 ) {

                $('body').toggleClass('overflow-hidden');
            }
        });

        $('.categories-menu__item').off('mouseenter').on('mouseenter', function(){

            if( $(this).hasClass('subitem') )
            {
                var categoryID = parseInt($(this).attr('data-category_id'),10), time;

                $('.categories-menu__item').removeClass('active');

                $(this).addClass('active');

                clearTimeout(time);

                time = setTimeout(function(){

                    $('.categories-block-item').removeClass('active');

                    $('#subCategoryId_'+categoryID).addClass('active');

                },290);

                $(this).on('mouseleave', function () {clearTimeout(time);});
            }
        });

        $('.categories-block-item').off('mouseenter').on('mouseenter', function () {

            var categoryID = $(this).attr('id').split('_')[1];

            $('.categories-block-item').removeClass('active');
            $('.categories-menu__item').removeClass('active');

            $('#subCategoryId_'+categoryID).addClass('active');
            $('#menuCategoryID_'+categoryID).addClass('active');

        });

        $('.categories-block-item').off('mouseleave').on('mouseleave', function () {
            var categoryID = $(this).attr('id').split('_')[1];
            $('#subCategoryId_'+categoryID).removeClass('active');
            $('#menuCategoryID_'+categoryID).removeClass('active');
        });

        $('.header-app-categories > .container').off('mouseleave').on('mouseleave', function () {

            $('.categories-block-item').removeClass('active');
            $('.categories-menu__item').removeClass('active');
        });

        $('.categories-block-item-sub-wrp').off('mouseenter').on('mouseenter', function(){

            if ( $(this).find('.categories-block-level2-link').length > 0 ) {

                $(this).addClass('active');

                $(this).find('.categories-block-level2').addClass('d-flex');

                $(this).on('mouseleave', function () {

                    $(this).removeClass('active');

                    $(this).find('.categories-block-level2').removeClass('d-flex');
                });
            }
        });

    }

    self.InitFancyBox = function()
    {
        $( '.viewContentImage, .ra-certificate-img, .ra-projects-item' ).fancybox();
    }

    self.InitContactForm = function()
    {
        self.InitWordCounter();

        $( '.message-form' ).off('submit').on('submit', function (e) {

            e.preventDefault();

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

            if( form_validate(this) )
            {
                var input_label  = $( 'form#' + id + ' button[type=submit]' ).html(),
                    loader_label = '<i class="fa fa-refresh fa-spin fa-fw"></i> Отправка...',
                    class_alert  = 'alert-danger';

                $( 'form#' + id + ' button[type=submit]' ).html(loader_label);

                $.ajax({url: '/messages',
                        data: new FormData(this),
                        dataType: 'json',
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: "POST",
                        success: function(obj)
                        {
                            if( obj.status == 'success' )
                            {
                                $( 'form#' + id ).trigger('reset');

                                class_alert = 'alert-success';
                            }

                            $( 'form#' + id + ' .form-message').removeClass().addClass('form-message alert '+class_alert).html(obj.message).fadeIn('slow').delay(5000).fadeOut(1500);
                        },
                        error: function (xhr, ajaxOptions, thrownError)
                        {
                            console.log(String(xhr.status + ' ' + thrownError));
                        }
                });

                $( 'form#' + id + ' button[type=submit]' ).html(input_label);
            }

        });
    }

    self.InitWordCounter = function()
    {
        $( '#ra-contact-form textarea' ).keyup(function(){

            var num = parseInt($(this).val().length);

            $( '#ra-contact-form-text').text( num +' симв.');

        });
    }
    
    self.InitDotDotDot = function (){
         
        $(".dot-text").dotdotdot({
                ellipsis: "... ",
                wrap: "word",
                fallbackToLetter: true,
                after: null,
                watch: true,
                height: null,
                tolerance: 0,
                callback: function(isTruncated, orgContent){},
                lastCharacter: {
                        remove: [" ", ",", ";", ".", "!", "?"],
                        noEllipsis: []
                }
        });
    }

    self.InitServiceBtn = function () {

        $( '#modalServiceOrderBtn' ).click(function () {

            var service_id = $(this).attr('data-service-id');

            $( '#cb_service' ).val(service_id);

            $( '#modalServiceOrder' ).modal('show');

        });
    }
    
    initResizeCategoriesMenu = function( width ) {

        var heightScreen = $(window).height(),
            heightHeader = $('.header-wrp').outerHeight(),
            css          = '';

        if ( $('body').hasClass('fixed-header') ) {

            heightHeader = $('.header-app-bottom').outerHeight()
        }

        //alert(heightHeader);

        if ( width < 768 ) {

            css = heightScreen - heightHeader;
        }

        $('#categoriesMenuMobile').css('height', css);
    }
}

var template = new app_class();

$(document).ready(function(){template.events();});
