var general = {
    init: function() {
        general.actions();
        general.initSlider();
        general.initMarquee();
        general.homeTabs();
        general.catalogFilters();
        general.productEvents();
        general.bannerTimer();
    },

    productEvents: function() {
        $('.btn-filial-box').on('click', function() {
            if ($('#popup-background').is(':visible') || $(this).hasClass('block')) return false;
            var iid = $('.product-detail .addWishlists').data('id') + ':' + $('.product-detail .addWishlists').data('sid') + ':' + $('.product-detail .addWishlists').data('wid');
            $.post(null, { 'action': 'filialAvailability', 'iid': iid }, function(res) {
                if (res['status'] == '200') {
                    $('#popup-wrapper').addClass('filter');
                    $('#popup-wrapper .popup-overlay').append(res['data']);
                    $('#popup-background,#popup-wrapper').show();
                }
            }, 'json');
            return false;
        });
 
        $('.addtobasket').on('click', function(event) {
            var obj = $(this);
            var bask= $('.basket');
            prod.animatedBasket( bask,obj,window.scrollY);
            var pid = parseInt($(this).data('id'));
            if (!pid) return false;
            var sid = parseInt($(this).data('sid'));
            var wid = parseInt($(this).data('wid'));
            var data = {};
            data['pid'] = pid;
            data['sid'] = sid;
            data['wid'] = wid;
            data['count'] = 1;
            var delay = 1300;
            var variant= '';
			if($('.product-weights li.active a').text()) variant='weight ' +$('.product-weights li.active a').text();
            if($('.product-sizes li.active a').text()) variant+='size ' +$('.product-sizes li.active a').text();
            var price=$('.iprice').html();
            price=price.replace('€ ','');
            dataLayer.push({
                'event': 'addToCart',	
                'ecommerce': {
                    'currencyCode': 'EUR',	
                    'add': {
                        'products': [{
                            'name': $('h3').html(),	
                            'id': pid,
                            'brand': $(this).data('brand'),
                            'variant': variant,
                            'category': $(this).data('ctitle'),
                            'price': price,
                            'quantity': 1
                        }]
                    }
                }
            });
            setTimeout(function() {
                $.post(_sitepath + 'ajax/', data, function(res) {
                    $('.basket-count').html(res['count']).data('cnt', res['count']);
                    (parseInt(res['count'])) ? $('.basket-count').removeClass('ihidden'): $('.basket-count').addClass('ihidden');
                    if ($('.product-weight-box .product-weights li.active').length) {
                        var amount = parseInt($('.product-weight-box .product-weights li.active a').data('amount')) - 1;
                        $('.product-weight-box .product-weights li.active a').data('amount', amount);
                        if (amount < 1) {
                            $('.product-weight-box .product-weights li.active a').data('status', 'outofstock');
                            $('.product-weight-box .product-weights li.active').removeClass('instock').addClass('outofstock');
                            $('.addtobasket').addClass('ihidden');
                            $('.product-outofstock').removeClass('hidden');
                        }
                    } else {
                        if ($('.product-size-box .product-sizes li.active').length) {
                            var amount = parseInt($('.product-size-box .product-sizes li.active a').data('amount')) - 1;
                            $('.product-size-box .product-sizes li.active a').data('amount', amount);
                            if (amount < 1) {
                                $('.product-weight-box .product-sizes li.active a').data('status', 'outofstock');
                                $('.product-weight-box .product-sizes li.active').removeClass('instock').addClass('outofstock');
                                $('.addtobasket').addClass('ihidden');
                                $('.product-outofstock').removeClass('hidden');
                            }
                        } else {
                            var amount = obj.data('amount') - 1;
                            obj.data('amount', amount);
                            if (amount < 1) {
                                $('.addtobasket').addClass('ihidden');
                                $('.product-outofstock').removeClass('hidden');
                            }
                        }
                    }
              
                }, 'json');
            }, delay);
          
            data['action'] = 'addtobasket';
            return false;
        });

        $('.sliders-count').on('click',function() {   
            if ($.trim($(this).attr('href')) == '#') return false;
            var sid = $(this).attr('data-id');
            $.post(_sitepath+'ajax/', {'action':'slidersClick','sid': sid});
          });

        $('.props-box > a').on('click', function() {
            if ($(this).parent().find('> ul').is(':visible')) {
                $(this).parent().find('> ul').slideUp();
                $(this).parent().removeClass('open');
            } else {
                $(this).parent().find('> ul').slideDown();
                $(this).parent().addClass('open');
            }
            return false;
        });

        $('.toggleDesc').on('click', function() {

            if ($('.product-detail .descr-box').hasClass('open')) {
                $(this).html($(this).data('open'));
                $('.product-detail .descr-box').removeClass('open');
                $('.product-detail .collapse-fade').show();
            } else {
                $(this).html($(this).data('close'));
                $('.product-detail .descr-box').addClass('open');
                $('.product-detail .collapse-fade').hide();
            }
            return false;
        });

        $('.product-detail .descr-box > a').on('click', function() {
            if (!$('.toggleDesc').is(':hidden')) $('.toggleDesc').click();
            return false;
        });

        if ($('.product-detail .descr-box').length) {
            var ah = parseInt($('.product-detail .descr-box > a').outerHeight(true));
            var dh = parseInt($('.product-detail .descr-box .detail').outerHeight(true))+24;
            var dsh = parseInt($('.product-detail .descr-box').outerHeight(true));
            if (ah + dh <= dsh) $('.toggleDesc').hide();
        }
    },
    actions: function() {
        
        $(document).on('click', '.toggle-users li', function(e) {

            let inputAnotherUser = $(document).find('#user-like-another-user');
            let anotherUserFields = $(document).find('.another-user-fields');
            
            (inputAnotherUser.is(':checked')) ? anotherUserFields.removeClass('hidden') : anotherUserFields.addClass('hidden');
        });
        
        if ($('#cookie_block').length) {
            var h_box = $('header').outerHeight() + 10;
            $('#content').css('margin-top', h_box + 'px');
        }

        $(document).on('click', '.search-box:visible input[type=submit]', function() {
            $('.search-box:visible input[type=search]').prop('value', $.trim($('.search-box:visible input[type=search]').prop('value')));
        });

        $('#accept_btn').on('click', function() {
            var date = new Date(new Date().getTime() + 60 * 1000 * 60 * 24 * 17);
            document.cookie = "ia_tr=Y; path=/; expires=" + date.toUTCString();
            window.location.reload();
        });
        $(document).on('click', '.popup-close', function() {
            if ($('#popup-wrapper .news-popup-box').length) $.cookie('news-popup', 'true', { expires: 1, path: _basepath, secure: false });
            $('#popup-wrapper').removeClass('size-guide');
            $('#popup-wrapper').removeAttr("style");
            $('.news-popup-box').remove();
            $('#popup-background').addClass('hidden').removeAttr("style");
            $('#popup-background').addClass('unvisible');
            $('html').css('overflow-y', 'scroll');
            return false;
        });
        $(document).on('scroll', function() {
            if ($('#popup-wrapper').hasClass('searchPopup show')) return false;
            var sc = parseInt($(document).scrollTop());
            if ($('#home').length) {
                (sc >= 65) ? $('header .search').css('visibility', 'visible'): $('header .search').css('visibility', 'hidden');
            }
            if ($('#back-top').length) {
                if (sc > 0) $('#back-top').show();
                else $('#back-top').hide();
            }
        });

        $(document).trigger('scroll');

        $('#back-top').on('click', function() {
            $("body,html").animate({ "scrollTop": 0 }, 800);
            return false;
        });

        $('header .search').on('click', function() {
            if (!$(this).is(':visible')) return false;
            if ($('#popup-wrapper .popup-overlay .search-box').length) return false;
            if ($('#content .search-box').length) {
                $('#popup-wrapper .popup-overlay').append($('#content .search-box').clone(true));
                $('#popup-background,#popup-wrapper').show();
                $('#popup-wrapper').addClass('searchPopup show');
            }
            return false;
        });

        $('.filterBtn').on('click', function() {
            if ($('#content .filterbox').length) {
                $('#popup-wrapper .popup-overlay').append($('#content .filterbox').clone(true));
                if ($('#popup-wrapper #form-filter').length) $('#popup-wrapper #form-filter').prop('id', 'formcatalogfilter');
                if ($('#popup-wrapper #search-filter').length) $('#popup-wrapper #search-filter').prop('id', 'formsearchfilter');
                if ($('#popup-wrapper #brands-filter').length) $('#popup-wrapper #brands-filter').prop('id', 'formbrandsfilter');
                $('#popup-background,#popup-wrapper').show();
                $('#popup-wrapper').addClass('filter show');
            }
            return false;
        });

        $('#popup-background,#popup-wrapper .popup-overlay-close').on('click', function() {
            if ($('#popup-background').is(':visible')) {
                $('#popup-wrapper .popup-overlay > *').last().remove();
                $('#popup-background,#popup-wrapper').hide();
                $('#popup-wrapper').removeClass('searchPopup filter show alertPopup');
                $('#popup-background').removeClass('alertPopup');
                $(document).trigger('scroll');
            }
            return false;
        });

        $('#navigation .submenu a,.catalog-home .tab-content a').on('click', function() {
            if ($(this).hasClass('last') || $(this).hasClass('logout')) return true;
            if ($(this).hasClass('login') && !$(this).hasClass('logined')) return true;
            if ($(this).parent().hasClass('newsale')) return true;
            if ($(this).parent().find('> ul').is(':visible')) {
                $(this).parent().find('> ul').slideUp();
                $(this).removeClass('selected');
            } else {
                $(this).parent().find('> ul').slideDown();
                $(this).addClass('selected');
            }
            return false;
        });
        
        $('.benefit-item:not(.benefit-item-alone) > a').on('click', function() {
            if ($(this).parent().find('.benefit-content').is(':visible')) {
                $(this).parent().find('.benefit-content').slideUp();
                $(this).find('.benefit-icon.toggle').removeClass('selected');
            } else {
                $(this).parent().find('.benefit-content').slideDown();
                $(this).find('.benefit-icon.toggle').addClass('selected');
            }
            return false;
        });

        $('.switch-view a').on('click', function() {
            $.cookie('view', $(this).prop('class'), { expires: 3, path: _basepath, secure: false });
            $('.switch-view a').removeClass('selected');
            $(this).addClass('selected');
            if ($(this).hasClass('one-column')) {
                $('.product-container hr').hide();
                $('.product-container .product-element').addClass('one');
            } else {
                $('.product-container hr').show();
                $('.product-container .product-element').removeClass('one');
            }
            return false;
        });

        if ($('.switch-view').length) {
            var view = $.trim($.cookie('view'));
            switch (view) {
                case 'one-column':
                    {}
                case 'two-column':
                    {
                        $('.switch-view a.' + view).click();
                        break;
                    }
                default:
                    {
                        $('.switch-view a').first().click();
                    }
            }
        }
        if ($('.news-popup-box').length) {
            // console.log('gere');
            $('html').css('overflow-y', 'hidden');
            var obj = $('.news-popup-box').clone().removeClass('hidden');
            $('#popup-wrapper').append(obj).show();
            $('#popup-background').show().css('margin-top', '-100px');
            $('#popup-wrapper').css({'width':'auto','height':'auto','padding':'0'});
            general.resizePopup();
            $('#popup-background').removeClass('unvisible');
        }
        $('.banners-count').on('click',function() {   
            if ($.trim($(this).attr('href')) == '#') return false;
            var bid = $(this).attr('data-id');
            $.post(_sitepath+'ajax/', {'action':'bannersClick','bid': bid});
        });
        $('a.relative').on('click',function(){
            var price=$(this).data('price');
            price=price.replace('€ ','');
            dataLayer.push({
                'event': 'productClick',	
                'ecommerce': {	
                    'click': {
                        'actionField': {'list': $(this).data('ctitle')}, 
                        'products': [{
                            'name':$(this).data('title'),	
                            'id': $(this).data('id'),
                            'brand': $(this).data('manuf'),
                            'category': $(this).data('ctitle'),
                            'price': parseFloat(price).toFixed(2)
                        }]
                    }
                }
            });
        });
    },
    catalogFilters: function() {

       

    },
    homeTabs: function() {

        if ($('.catalog-home .tabs').length) {
            $('.catalog-home .tabs li').on('click', function() {
                if ($(this).find('a').hasClass('sale')) return true;
                $('.catalog-home .tabs li').removeClass('active');
                $(this).addClass('active');
                var tindex = $('.catalog-home .tabs li').index(this);
                $('.tab-content-box .tab-content').addClass('hidden');
                $('.tab-content-box .tab-content').eq(tindex).removeClass('hidden');
                return false;
            });

            $('.catalog-home .tabs li').first().click();
        }

    },
    initSlider: function() {

        if ($('#slider-product').length) {
            $('#slider-product').slick({
                dots: true,
                infinite: true,
                speed: 500,
                slidesToShow: 1,
                autoplay: false,
                autoplaySpeed: 4000,
                adaptiveHeight: true
            });
        }

        if ($('#slider').length) {
            $('#slider').slick({
                dots: false,
                infinite: true,
                speed: 500,
                slidesToShow: 1,
                autoplay: true,
                autoplaySpeed: 4000,
                adaptiveHeight: true
            });
        }

        if ($('#newarrivals-slider-home,#sales-slider-home,#similar-slider,#recommended-slider').length) {
            var sItems = 4;
            var wWd = parseInt($(document).width());
            if (wWd < 850) sItems = 3;
            if (wWd < 530) sItems = 2;
            $('#newarrivals-slider-home,#sales-slider-home,#similar-slider,#recommended-slider').slick({
                dots: false,
                infinite: true,
                speed: 500,
                slidesToShow: sItems,
                slidesToScroll: sItems,
                autoplay: false,
                autoplaySpeed: 4000,
                adaptiveHeight: true
            });
        }

        if ($('.pswp').length) {
            $('#slider-product a').on('click', function() {
                var eli = $('#slider-product a').index(this);
                openPhotoSwipe(eli - 1);
                return false;
            });
        }

        if ($('.datepicker').length) {
            $('.datepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                numberOfMonths: 1,
                dateFormat: 'dd.mm.yy',
                firstDay: 1,
                yearRange: '-100:+0'
            });
        }

    },
    initMarquee: function() {
		$(".marquee-slider").slick({
		  arrows: false,
		  infinite: true,
		  autoplay: true,
		  centerMode: true,
		  dots: false,
		  // slidesToShow: 5,
		  variableWidth: true,
		  slidesToScroll: 1,
		  speed: 5000,
		  autoplay: true,
		  autoplaySpeed: 0,
		  cssEase: "linear",
		  pauseOnhover: false,
		  responsive: [
		    {
		      breakpoint: 1200,
		      settings: {
		        slidesToShow: 4
		      }
		    },
		    {
		      breakpoint: 767,
		      settings: {
		        slidesToShow: 3,
		        speed: 1000,
		        dots: false
		      }
		    }
		  ]
		});
	},

    
    resizePopup: function() {
        var bh = $('.news-popup-box').outerHeight();
        var bw = $('.news-popup-box').outerWidth();
        var wh = $(window).height();
        var ww = $(window).width();
        var bleft = 0;
        var btop = 0;

        if (bh < wh) btop = parseInt((wh / 2)) - parseInt((bh / 2));
        if (bw < ww) bleft = parseInt((ww / 2)) - parseInt((bw / 2));
        $('#popup-wrapper').css({ 'left': bleft, 'top': btop });
    },
    bannerTimer: function(){
        if($('.clock').length){
            var currentDate = new Date(parseInt($('.clock').data('servertime')) *1000);
            var futureDate  = new Date(parseInt($('.clock').data('banner-timer')) * 1000);
            var lng =$('.clock').data('lang');
            var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
            if(diff < 0) diff=0;
            var clock;
            clock = $('.clock').FlipClock(diff, {
                clockFace: 'DailyCounter',
                countdown: true,
                language:lng,
                howSeconds: true
            });
        }
    }

};

$(document).ready(function() {
    general.init();
});

function formSubscribleSuccess() {
    $('#form-subscrible').hide();
    $('#form-subscrible-success').show();
}



function formsearchfilter_success(data) {
    $('#formsearchfilter').html(data['res']);
    $('#popup-wrapper .filter-items-count').html(data['count']);
    $('#popup-wrapper .loading').hide();
}

function formbrandsfilter_success(data) {
    $('#formbrandsfilter').html(data['res']);
    $('#popup-wrapper .filter-items-count').html(data['count']);
    $('#popup-wrapper .loading').hide();
}

function form_order_success() {
    $('.basket-count').html(0).addClass('ihidden');
    $('#makeorder').hide();
    $('#form-makeorder-success').show();
}

function makeorder_success(data,objForm){
    if(data['class']) return;
    if(data['dataLayer']){
        console.log(JSON.parse(data['dataLayer']));
        dataLayer.push({
            'ecommerce':{
                'purchase': JSON.parse(data['dataLayer']),
            }
        });
    }
    // $('.basket-count').html(0)
    // $('#makeorder').hide();
    if(data['dataLocation'])document.location = data['dataLocation'];
    // $('#form-makeorder-success').show();
}