window.onerror = function (error, url, line) {
    $.ajax({
        'url': '/err',
        'method': 'post',
        'data': "error=" + error + "&url=" + url + "&line=" + line,
        'dataType': 'json'
    }).done(function (resp) {
        console.log('done');
    });
};

function WI2() {
    var self = this;
    self.deleteAddressId = false;
    self.deleteProductId = false;
    self.deleteProductIdx = false;
    self.ajaxFilterLoading = false;
    self.productVersions = false;
    $("body").on("click", ".js-ask-gift-card-balance", function (e) {
        e.preventDefault();
        let num = $.trim($("#js-gift-card-num-balance").val());
        $.ajax({
            'method': 'post',
            'url': '/check/getgiftcardbalance',
            'data': 'code=' + num,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.html) {
                $(".js-show-gift-card-balance").addClass("sys");
                $(".js-gift-card-alax-balance").html(resp.html)
            }
        });


    });

    $("body").on("click", ".js-btn-favorite", function (e) {
        e.preventDefault();
        let product_id = $(this).data('product-id');
        let status = $(this).data('favorite-status');
        let url = '/product-favorite/add';
        $(this).data('favorite-status', '1')
        $(this).addClass('active');
        if (status == '1') {
            $(this).removeClass('active');
            $(this).data('favorite-status', '0')
            url = '/product-favorite/remove';
        }
        if (product_id > 0) {
            $.ajax({
                'method': 'post',
                'url': url,
                'data': 'product_id=' + product_id,
                'dataType': 'json'
            }).done(function (resp) {
                if (resp.counter) {
                    $(".js-favorite-counter").html(resp.counter);
                }
            });
        }
        if ($(".js-refresh-page").length > 0) {
            self.regeneralProductList();
        }
    });

    $("body").on("click", ".js-accept-delete", function (e) {
        var successTitle = $(this).parents('.popup').data('successtitle'),
            succesText = $(this).parents('.popup').data('successtext'),
            successButtonText = $(this).parents('.popup').data('successbutton');

        e.preventDefault();
        $.ajax({
            'method': 'post',
            'url': '/profile/remove-address',
            'data': 'id=' + self.deleteAddressId,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.message) {
                /*alert(resp.message);*/
                createPopup(successTitle, succesText, successButtonText);
            }
            if (resp.listHtml) {
                $("#js-ajax-address-list").html(resp.listHtml);
            }
        });
    });
    $("body").on("click", ".js-remove-address", function (e) {
        e.preventDefault();
        self.deleteAddressId = $(this).data('id');
    });

    $("body").on("click", ".js-edit-address", function (e) {
        e.preventDefault();

        showPopup('editaddress');
        ///
        $("#addrid").val($(this).data('id'));
        $("#editcompanyname").val($(this).data('companyname'));
        $("#editfirstname").val($(this).data('firstname'));
        $("#editlastname").val($(this).data('lastname'));
        $("#editzip").val($(this).data('zip'));
        $("#editcity").val($(this).data('city'));
        $("#editstreet").val($(this).data('street'));
        $("#editdoor").val($(this).data('door'));
        $("#editcomment").val($(this).data('comment'));
        $("#editphone").val($(this).data('phone'));
        $("#editcountry").val($(this).data('country')).change();
        $("#editphonezone").val($(this).data('phonezone')).change();

        formWI();
    });

    $("body").on("click", ".js-order-delivery-type", function (e) {
        $.ajax({
            'method': 'post',
            'url': '/payment-types',
            'data': 'lang=' + $('html')[0].lang + '&id=' + $(this).val(),
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.html) {
                $(".js-payment-order-ajax").html(resp.html);
            }
            if (resp.htmlBasketPageSumma) {
                $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
            }
            if (resp.addressHtml) {
                $(".js-address-order-ajax").html(resp.addressHtml);
            } else {
                $(".js-address-order-ajax").html("");
            }
        });
    });


    $("body").on("click", ".js-check-delivery-addr", function (e) {
        $.ajax({
            'method': 'post',
            'url': '/payment-types',
            'data': 'lang=' + $('html')[0].lang + '&addid=' + $(this).val(),
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.html) {
                $(".js-payment-order-ajax").html(resp.html);
            }
            if (resp.htmlBasketPageSumma) {
                $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
            }
            if (resp.addressHtml) {
                $(".js-address-order-ajax").html(resp.addressHtml);
            } else {
                $(".js-address-order-ajax").html("");
            }
        });
    });

    $("body").on("click", ".js-add-basket-gift-card", function (e) {
        e.preventDefault();
        let pid = $(this).data('pid');
        let price = $(this).data('price');
        let qty = $(".js-add-basket-gift-card-qty-" + price).val();
        self.callBasket('giftcard', pid, qty,0, $(this),price);
    });

    $("body").on("click", ".js-add-basket-custom-gift-card", function (e) {
        e.preventDefault();
        let pid = $(this).data('pid');
        let price = $(".js-add-basket-custom-price").val();
        let qty = $(".js-add-basket-custom-gift-card-qty").val();
        self.callBasket('giftcard', pid, qty,0, $(this),price);
    });

    $("body").on("click", ".js-add-btn-one", function (e) {
        e.preventDefault();
        let pid = $(this).data('pid');
        let idx = $(this).data('idx');
        let qty = 1;
        self.callBasket('add', pid, qty,idx, $(this),0);
    });



    $("body").on("click", ".js-add-btn", function (e) {
        e.preventDefault();
        let pid = $(this).data('pid');
        let idx = $(this).data('idx');
        let qty = $(".js-qty-" + idx + "-" + pid).val();
        self.callBasket('addFirst', pid, qty, idx,$(this),0);
    });

    $("body").on("click", ".js-minus-btn", function (e) {
        e.preventDefault();
        let pid = $(this).data('pid');
        let idx = $(this).data('idx');
        let qty = $(".js-qty-" + idx + "-" + pid).val();
        self.callBasket('minus', pid, qty,idx, $(this),0);
    });


    $("body").on("click", ".js-remove-product", function (e) {
        e.preventDefault();
        self.deleteProductId = $(this).data('pid');
        self.deleteProductIdx = $(this).data('idx');
        showPopup('deleteprodfromcart');
    });

    $("body").on("click", ".js-accept-remove-product", function (e) {
        e.preventDefault();
        $(".popup-deleteprodfromcart").removeClass('active');
        self.callBasket('remove', self.deleteProductId, 0, self.deleteProductIdx,$(this),0);
    });

    $("body").on("click", ".js-qty-minus-correction", function (e) {

        e.preventDefault();
        let refP = $(this).closest('.js-basket-controller');
        let pid = $(refP).data('pid');
        let idx = $(refP).data('idx');
        let qty = $(refP).children().children('.js-qty').val();
        self.callBasket('correction', pid, qty,idx, $(this),0);
    });
    $("body").on("click", ".js-qty-plus-correction", function (e) {
        console.log('plusz');
        e.preventDefault();
        let refP = $(this).closest('.js-basket-controller');
        let pid = $(refP).data('pid');
        let idx = $(refP).data('idx');
        let qty = $(refP).children().children('.js-qty').val();
        self.callBasket('correction', pid, qty,idx, $(this),0);
    });

    this.callBasket = function (command, pid, qty,idx, source,price) {
        if($(".js-product-version-item-" + pid).length > 0 && command == "addFirst"){
            if(command == 'addFirst'){
                command = 'add';
            }
            let xlength = $(".js-product-version-item-" + pid).length;
            let counter = 1;
            $.each($(".js-product-version-item-" + pid), function( key, value ) {
                productVersion = $(value).val();
                if($(value).val() == null){
                    createPopup("Hiba", "kérem válaszon termékváltozatott", "ok");
                    return;
                }
                if(xlength == counter){
                    self._callBasket(command, pid, qty,idx, source,price);
                }
                counter++;
            });
        }else{
            if(command == 'addFirst'){
                command = 'add';
            }
            self._callBasket(command, pid, qty,idx, source,price);
        }
    }

    this._callBasket = function (command, pid, qty,idx, source,price) {

        let productVersion = '';

        if($(".js-product-version-item-" + pid).length > 0){
            $.each($(".js-product-version-item-" + pid), function( key, value ) {
                if($(".js-product-version-item-" + pid).length == 1){
                    productVersion = $(value).text();
                }else{
                    productVersion = $(value).val();
                }

            });
        }




        if(typeof qty === 'undefined'){
            qty = 1;
        }

        if(typeof idx === 'undefined'){
            idx = 0;
        }

        $.ajax({
            'method': 'post',
            'url': '/basket-modify',
            'data': 'lang=' + $('html')[0].lang + '&command=' + command + '&product_id=' + pid + '&qty=' + qty + '&idx=' + idx + '&price=' + price + '&version=' + productVersion,
            'dataType': 'json',
            beforeSend: function(xhr) {
                console.log('beforeSend Start');
                console.log(xhr);
                console.log('beforeSend End');
            },
            success: function(data) {
                console.log('success Start');
                console.log(data)
                console.log('success End');
            },
            error: function(xhr) { // if error occured
                console.log('error Start');
                console.log(xhr);
                console.log('error End');
            },
        }).done(function (resp) {
            console.log('sikeres');
            if (resp.redirect) {
                document.location.href = resp.redirect;
            }
            if (resp.htmlBasketLayer) {
                $(".js-basket-layer-ajax").html(resp.htmlBasketLayer);
            } else {
                $(".js-basket-layer-ajax").html("");
            }
            if (resp.htmlBasketPageItems) {
                $(".js-basketItems").html(resp.htmlBasketPageItems);
            } else {
                $(".js-basketItems").html("")
            }
            if (resp.htmlBasketPageSumma) {
                $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
            }
            if (resp.basketCounter != null) {
                $(".js-basket-counter").html(resp.basketCounter);
            }
            if (resp.crsf) {
                $("[name=crsf]").val(resp.crsf);
            }
            if (resp.openBasketLayer) {
                if (!$(".cart").hasClass("sys")) {
                    cartLayerScroll();
                    $(".cart").addClass("sys");

                    setTimeout(function () {
                        $(".cart").removeClass("sys");
                    }, 2000);
                }
            }
            if (resp.closeBasketLayer) {
                setTimeout(function () {
                    $(".cart").removeClass("sys");
                    $(".backdrop").css('display', 'none');
                }, 2000);
            }

            /*
            if (source.hasClass('js-add-btn')) {
                if (!$(".cart").hasClass("sys")) {
                    cartLayerScroll();
                    $(".cart").addClass("sys");

                    setTimeout(function () {
                        $(".cart").removeClass("sys");
                    }, 2000);
                }
            }
           */
            if (resp.messageTitle && resp.messageText && resp.messageButton) {
                createPopup(resp.messageTitle, resp.messageText, resp.messageButton);
            }
        });
    }


    this.findFormFieldsByName = function (name) {
        if ($(".js-form-" + name).length > 0) {
            var data = {};
            $(".js-form-" + name).find('input, textarea, select').each(function (i, elem) {
                var name = $(elem).attr('name');
                if (name) {
                    if ($(elem).attr('type') == 'checkbox') {
                        data[name] = $(elem).prop('checked') ? 1 : 0;
                    } else if ($(elem).attr('type') == 'radio') {
                        if (data[name] == null || data[name] < 1) {
                            data[name] = $(elem).prop('checked') ? $(elem).val() : 0;
                        }
                    } else {
                        data[name] = $(elem).val();
                    }
                }
            });
            return data;
        }
    }

    this.makeErrors = function (name, errors) {
        if ($(".js-form-" + name).length > 0) {
            $(".js-form-" + name).find('.error').removeClass('error');
            $(".js-form-" + name).find('.js-errMessage').remove();
            for (i in errors) {
                var cont = $(".js-form-" + name).find('[name="' + i + '"]');
                if (cont.length == 0) {
                    cont = $(".js-form-" + name).find('#' + i);
                }
                cont.parents('.form-group').addClass('has-error');
                cont.after('<span class="js-errMessage form-error">' + errors[i] + '</span>');
            }
            try {

                $('html, body').animate({
                    scrollTop: $('.js-errMessage:visible:first').offset().top - 150
                }, 1000);

            } catch (err) {

                console.log('scrolling error')

            }

        }
    }


    this.resetForm = function (name, errors) {
        if ($(".js-form-" + name).length > 0) {
            $(".js-form-" + name).find('.js-errMessage').remove();
            $(".js-form-" + name).find('input, textarea, select').each(function (i, elem) {
                var name = $(elem).attr('name');
                if (name) {
                    if ($(elem).attr('type') == 'checkbox') {
                        $(elem).prop('checked', false);
                    } else if ($(elem).attr('type') == 'radio') {
                        $(elem).prop('checked', false);
                    } else {
                        $(elem).val('');
                    }
                }
            });
            return true;
        }
    }

    self.sendForm = function () {
        $(".js-save-form").click(function (e) {
            var successTitle = $(this).parents('.popup').data('successtitle'),
                succesText = $(this).parents('.popup').data('successtext'),
                successButtonText = $(this).parents('.popup').data('successbutton');

            e.preventDefault();
            let form = $(this).data('form');
            let url = $(this).data('url');
            $(".js-form-" + form).find('.error').removeClass('error');
            $(".js-form-" + form).find('.js-errMessage').remove();
            let data = self.findFormFieldsByName(form);
            $.ajax({
                'method': 'post',
                'url': url,
                'data': data,
                'dataType': 'json'
            }).done(function (resp) {
                console.log(resp)
                if (resp.redirect) {
                    document.location.href = resp.redirect;
                }
                if (resp.errors) {
                    self.makeErrors(form, resp.errors);
                }
                if (resp.reset) {
                    self.resetForm(form);
                }
                if (resp.showPopup) {
                    showPopup(resp.showPopup);
                }
                if (resp.closePopup) {
                    bd.trigger('click');
                }
                if (resp.messageTitle && resp.messageText && resp.messageButton) {
                    createPopup(resp.messageTitle, resp.messageText, resp.messageButton);
                } else if (resp.messageText && resp.messageButton) {
                    createPopup('', resp.messageText, resp.messageButton);
                }
                if (resp.crsf) {
                    $("[name=crsf]").val(resp.crsf);
                }
                if (resp.message) {
                    createPopup('', resp.message, 'Ok');
                }
                if (resp.listHtml) {
                    $("#js-ajax-address-list").html(resp.listHtml);
                }
                if (resp.addressHtml) {
                    $(".js-address-order-ajax").html(resp.addressHtml);
                }
            });
        })
    }

    self.productListPage = function () {
        if ($(".js-product-list-page").length > 0) {
            $('#js-page-limit').on("change", function (e, args) {
                e.preventDefault();
                self.regeneralProductList();
            });
            $('#js-page-ordering').on("change", function (e, args) {
                e.preventDefault();
                self.regeneralProductList();
            });
            $('.js-page-option-item').on("click", function (e, args) {
                // e.preventDefault();
                self.regeneralProductList();
            });
            $('.js-page-filter').on("click", function (e, args) {
                //e.preventDefault();
                self.regeneralProductList();
            });
        }
    }

    this.regeneralProductList = function () {
        if(!self.ajaxFilterLoading) {
            let url = $(".js-product-list-page").data('url');
            let searchText = $(".js-product-list-page").data("searchtext");
            let page = 1;
            let limit = $('#js-page-limit').val();
            let ordering = $('#js-page-ordering').val();
            let options = '';
            let redirectFlag = true;
            let filter = '';
            let slider = $(".js-range-slider-value").val();
            let sliderValues;
            if ($(".js-range-slider-value").length > 0) {
                sliderValues = slider.split(";");
            } else {
                let sliderValues = [];
                sliderValues[0] = false;
                sliderValues[1] = false;
                let slider = false;
                redirectFlag = false;
            }
            if ($(".js-option-panel").length > 0) {
                $(".js-option-panel").find('.js-page-option-item').each(function (i, elem) {
                    var name = $(elem).attr('name');
                    if (name) {
                        if ($(elem).attr('type') == 'checkbox') {
                            if ($(elem).prop('checked')) {
                                if (options.length > 0) {
                                    options += ',' + name;
                                } else {
                                    options += name;
                                }
                            }
                            ;
                        }
                    }
                });
            }
            $(".js-page-option-filter").find('.js-page-option-filter-item').each(function (i, elem) {
                var name = $(elem).attr('name');
                if (name) {
                    if ($(elem).attr('type') == 'checkbox') {
                        if ($(elem).prop('checked')) {
                            if (filter.length > 0) {
                                filter += ',' + name;
                            } else {
                                filter += name;
                            }
                        }
                    }
                }
            });
            if (options.length == 0) {
                options = 'none';
            }
            let redirect = url;
            if (sliderValues === undefined) {
                redirect = url + '/' + page + '/limit/' + limit + '/order/' + ordering + '/options/' + options + '/filters/' + filter + '/?q=' + searchText;

            } else {
                redirect = url + '/' + page + '/limit/' + limit + '/order/' + ordering + '/min/' + sliderValues[0] + '/max/' + sliderValues[1] + '/options/' + options + '/filters/' + filter + '/?q=' + searchText;

            }


            window.history.replaceState({
                id: 'walterland',
                source: 'web'
            }, 'walterland', redirect);
            $(".js-page-option-filter-item").prop( "disabled", true );
            self.ajaxFilterLoading = true;
            $.ajax({
                'method': 'post',
                'url': redirect,
                'data': 'ajax=1',
                'dataType': 'json'
            }).done(function (resp) {
                $(".js-page-option-filter-item").prop( "disabled", false );
                self.ajaxFilterLoading = false;
                if (resp['productList']) {
                    $(".js-product-list").html(resp['productList']);
                } else {
                    $(".js-product-list").html('');
                }
                if (resp['pager']) {
                    $(".js-product-pager").html(resp['pager']);
                } else {
                    $(".js-product-pager").html('');
                }
                if (resp['total']) {
                    $(".js-product-total").html(resp['total']);
                } else {
                    $(".js-product-total").html(0);
                }
                if (resp['filters']) {
                    $(".js-product-filters").html(resp['filters']);
                    self.rangeSlider();
                    self.productListPage();
                    boxFilterList();
                } else {
                    $(".js-product-filters").html(0);
                }
                if (resp.redirect) {
                    document.location.href = resp.redirect;
                }
            });
        }
    }
    this.taxNumAutocomplate = function () {
        let countryIdMustBe = 25;
        if ($("#company-tax").length > 0) {
            $('#company-tax').on("keyup", function (e, args) {
                let tax = $('#company-tax').val();
                let country = $(this).data('country');
                let countryId = $("#" + country).val();
                if (tax.length > 8) {
                    tax = tax.slice(0, 8);
                }
                if (tax.length == 8 && countryId == countryIdMustBe) {
                    $.ajax({
                        'method': 'post',
                        'url': '/taxnum',
                        'data': 'tax=' + tax,
                        'dataType': 'json'
                    }).done(function (resp) {
                        if (resp['taxNum']) {
                            $('#company-tax').val(resp['taxNum']);
                        }
                        if (resp['companyName']) {
                            $("#company-name").val(resp['companyName']);
                        }
                        if (resp['zip']) {
                            $("#zip").val(resp['zip']);
                        }
                        if (resp['city']) {
                            $("#city").val(resp['city']);
                        }
                        if (resp['street']) {
                            $("#street").val(resp['street']);
                        }
                        if (resp['door']) {
                            $("#door").val(resp['door']);
                        }
                    });
                }
            });
        }

        if ($("#tax").length > 0) {
            $('#tax').on("keyup", function (e, args) {
                let tax = $('#tax').val();
                if (tax.length > 8) {
                    tax = tax.slice(0, 8);
                }
                if (tax.length == 8) {
                    $.ajax({
                        'method': 'post',
                        'url': '/taxnum',
                        'data': 'tax=' + tax,
                        'dataType': 'json'
                    }).done(function (resp) {
                        if (resp['taxNum']) {
                            $('#company-tax').val(resp['taxNum']);
                        }
                        if (resp['companyName']) {
                            $("#companyname").val(resp['companyName']);
                        }
                        if (resp['zip']) {
                            $("#zip").val(resp['zip']);
                        }
                        if (resp['city']) {
                            $("#city").val(resp['city']);
                        }
                        if (resp['street']) {
                            $("#street").val(resp['street']);
                        }
                        if (resp['door']) {
                            $("#door").val(resp['door']);
                        }
                    });
                }
            });
        }
        if ($(".js-check-company-tax").length > 0) {
            $('.js-check-company-tax').click(function () {
                if ($('.js-check-company-tax').prop('checked')) {
                    $('.js-check-company-tax-panel').removeClass('form-hys');
                } else {
                    $('.js-check-company-tax-panel').addClass('form-hys');
                }
            });
        }
    }

    this.tryToUseGiftCard = function (){
        console.log("tryToUseGiftCard");
        $(".js-valid-giftcard").removeClass("has-error");
        let code = $("#js-giftcard-value").val();
        $.ajax({
            'method': 'post',
            'url': '/check/giftcard',
            'data': 'code=' + code,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp['status']) {
               // $("#js-giftcard-value").prop('disabled', true);
               // $("#js-coupon-value").prop('disabled', true);
            }
            if (resp['errorMessage']) {
                $(".js-valid-giftcard").addClass("has-error");
                $(".js-giftcard-error-message").html(resp['errorMessage']);
            } else {
                if (resp.htmlBasketLayer) {
                    $(".js-basket-layer-ajax").html(resp.htmlBasketLayer);
                }
                if (resp.htmlBasketPageItems) {
                    $(".js-basketItems").html(resp.htmlBasketPageItems);
                }
                if (resp.htmlBasketPageSumma) {
                    $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
                }
                if (resp.basketCounter != null) {
                    $(".js-basket-counter").html(resp.basketCounter);
                }
            }
        });
    }

    this.tryToUseCoupon = function(){
        let code = $("#js-coupon-value").val();
        $(".js-valid-coupon").removeClass("has-error");
        $.ajax({
            'method': 'post',
            'url': '/check/coupon',
            'data': 'code=' + code,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp['status']) {
                $("#js-giftcard-value").prop('disabled', true);
                $("#js-coupon-value").prop('disabled', true);
            }
            if (resp['errorMessage']) {
                $(".js-valid-coupon").addClass("has-error");
                $(".js-coupon-error-message").html(resp['errorMessage']);
            } else {
                if (resp.htmlBasketLayer) {
                    $(".js-basket-layer-ajax").html(resp.htmlBasketLayer);
                }
                if (resp.htmlBasketPageItems) {
                    $(".js-basketItems").html(resp.htmlBasketPageItems);
                }
                if (resp.htmlBasketPageSumma) {
                    $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
                }
                if (resp.basketCounter != null) {
                    $(".js-basket-counter").html(resp.basketCounter);
                }
            }
        });
    }

    this.GiftandCoupon = function () {


        $("#js-giftcard-value").on('keypress',function(e) {
            $(".js-valid-giftcard").removeClass("has-error");
            if(e.which == 13) {
                e.preventDefault();
                self.tryToUseGiftCard();
            }
        });

        $("#js-coupon-value").on('keypress',function(e) {
            $(".js-valid-coupon").removeClass("has-error");
            if(e.which == 13) {
                e.preventDefault();
                self.tryToUseCoupon();
            }
        });






        $("body").on("click", ".js-try-to-use-giftcard", function (e) {
            e.preventDefault();
            self.tryToUseGiftCard();

        });
        $("body").on("click", ".js-try-to-use-coupon", function (e) {
            e.preventDefault();
            self.tryToUseCoupon();
        });

        $("body").on("click", ".js-remove-giftCard", function (e) {
            e.preventDefault();
            self.deletegiftCard = $(this).data('card');
            showPopup('deletediscount');
        });
        $("body").on("click", ".js-remove-CouponCode", function (e) {
            e.preventDefault();
            showPopup('deletecoupon');
        });
        $("body").on("click", ".js-remove-giftCard-accept", function (e) {
            e.preventDefault();
            $.ajax({
                'method': 'post',
                'url': '/delete/giftcard',
                'data': 'go=1&card=' + self.deletegiftCard,
                'dataType': 'json'
            }).done(function (resp) {
                if (resp.htmlBasketLayer) {
                    $(".js-basket-layer-ajax").html(resp.htmlBasketLayer);
                }
                if (resp.htmlBasketPageItems) {
                    $(".js-basketItems").html(resp.htmlBasketPageItems);
                }
                if (resp.htmlBasketPageSumma) {
                    $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
                }
                if (resp.basketCounter != null) {
                    $(".js-basket-counter").html(resp.basketCounter);
                }
                $("#js-giftcard-value").prop('disabled', false);
                $("#js-coupon-value").prop('disabled', false);
                $("#js-giftcard-value").val("");
            });
        });
        $("body").on("click", ".js-remove-CouponCode-accept", function (e) {
            e.preventDefault();
            $.ajax({
                'method': 'post',
                'url': '/delete/coupon',
                'data': 'go=1',
                'dataType': 'json'
            }).done(function (resp) {
                if (resp.htmlBasketLayer) {
                    $(".js-basket-layer-ajax").html(resp.htmlBasketLayer);
                }
                if (resp.htmlBasketPageItems) {
                    $(".js-basketItems").html(resp.htmlBasketPageItems);
                }
                if (resp.htmlBasketPageSumma) {
                    $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
                }
                if (resp.basketCounter != null) {
                    $(".js-basket-counter").html(resp.basketCounter);
                }
                $("#js-giftcard-value").prop('disabled', false);
                $("#js-coupon-value").prop('disabled', false);
                $("#js-coupon-value").val("");
            });
        });
        $("body").on("click", ".js-try-to-use-regularcustomercard", function (e) {
            e.preventDefault();
            let code = $("#js-regularcustomercard-value").val();
            $(".js-valid-regularcustomercard").removeClass("has-error");
            $.ajax({
                'method': 'post',
                'url': '/check/regularcustomercard',
                'data': 'code=' + code,
                'dataType': 'json'
            }).done(function (resp) {
                if (resp['status']) {
                    $("#js-regularcustomercard-value").prop('disabled', true);
                    $(".js-try-to-use-regularcustomercard").remove();
                }
                if (resp['errorMessage']) {
                    $(".js-valid-regularcustomercard").addClass("has-error");
                    $(".js-regularcustomercard-error-message").html(resp['errorMessage']);
                }
            });
        });


    }


    this.rangeSlider = function () {
        if ($('.range-slider').length) {
            $('.range-slider').each(function (i, v) {
                var rangeMin = $(v).data('min'),
                    rangeMax = $(v).data('max'),
                    rangeFrom = $(v).data('from'),
                    rangeTo = $(v).data('to'),
                    rangePostfix,
                    rangeStep;

                if ($(v).data('postfix')) {
                    rangePostfix = $(v).data('postfix');
                } else {
                    rangePostfix = '';
                }

                if ($(v).data('step')) {
                    rangeStep = $(v).data('step');
                } else {
                    rangeStep = 1;
                }

                $(v).ionRangeSlider({
                    type: 'double',
                    grid: false,
                    skin: 'round',
                    min: rangeMin,
                    max: rangeMax,
                    from: rangeFrom,
                    to: rangeTo,
                    step: rangeStep,
                    postfix: rangePostfix,
                    onStart: function () {
                        console.log('start2');
                        // inicializálás
                    },
                    onChange: function () {
                        console.log('change2');
                    },
                    onFinish: function () {
                        console.log('finish2');
                        self.regeneralProductList();
                    },
                    onUpdate: function () {
                        console.log('update2');
                    }
                });
            });
        }
    }


    this.updateCountry = function (id) {
        let lang = $('.search-box-input').data('lang');
        let url = 'setcountry';
        if ($('html')[0].lang == 'en') {
            url = 'en/setcountry';
        }
        $.ajax({
            'method': 'post',
            'url': '/' + url,
            'data': 'lang=' + $('html')[0].lang + '&country_id=' + id,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.redirect) {
                document.location.href = resp.redirect;
            }
            if (resp.paymentHtml) {
                $(".js-payment-order-ajax").html(resp.paymentHtml);
            }
            if (resp.htmlBasketPageSumma) {
                $(".js-basket-sum-box").html(resp.htmlBasketPageSumma);
            }

            if (resp.htmlDeliveryType) {
                $(".js-delivery-order-ajax").html(resp.htmlDeliveryType);
            }

            if (resp.crsf) {
                $("[name=crsf]").val(resp.crsf);
            }

            if (resp.messageTitle && resp.messageText && resp.messageButton) {
                createPopup(resp.messageTitle, resp.messageText, resp.messageButton);
            }
        });
    }

    this.getCountryPhonePrefix = function (id, target) {
        $.ajax({
            'method': 'post',
            'url': '/phoneprefix',
            'data': 'country_id=' + id,
            'dataType': 'json'
        }).done(function (resp) {
            if (resp.phonePrefix) {
                $(target).val(resp.phonePrefix).trigger('change');
                ;
            }
        });
    }

    this.zipNumAutocomplateCity = function () {
        let countryIdMustBe = 25;

        if ($(".js-county-selector").length > 0) {
            $(document).on('change', '.js-county-selector', function (e) {
                let auto = $("#" + e.target.id).data('auto');
                let noauto = $("#" + e.target.id).data('noauto');
                let jumpFocus = $("#" + e.target.id).data('jumpfocus');
                let sameAddrFlag = false;
                let phonePrefix = false;
                if ($("#" + e.target.id).data('sameaddselector')) {
                    if ($('.' + $("#" + e.target.id).data('sameaddselector')).prop('checked') == true) {
                        self.updateCountry($("#" + e.target.id).val())
                    }
                }
                if ($("#" + e.target.id).data('phoneprefix')) {
                    let id = "#" + $("#" + e.target.id).data('phoneprefix');
                    let phoneZone = self.getCountryPhonePrefix($("#" + e.target.id).val(), id);
                }
                let countryId = e.target.value;
                if (countryId == countryIdMustBe) {
                    $("#" + noauto).hide();
                    $("#" + auto).show();
                } else {
                    $("#" + auto).hide();
                    $("#" + noauto).show();
                }
                if ($(this).val() != "25") {
                    if ($(this).parents('.form-group').find('.warning-box').length) {
                        $(this).parents('.form-group').find('.warning-box').show();
                    }
                } else {
                    if ($(this).parents('.form-group').find('.warning-box').length) {
                        $(this).parents('.form-group').find('.warning-box').hide();
                    }
                }
            });
        }

        if ($(".js-check-same-addr").length > 0) {
            $('.js-check-same-addr').click(function () {
                if ($('.js-check-same-addr').prop('checked')) {
                    if ($('.js-check-same-addr').data('country1')) {
                        let country = $("#" + $('.js-check-same-addr').data('country1')).val();
                        self.updateCountry(country);
                    }
                } else {
                    if ($('.js-check-same-addr').data('country2')) {
                        let country = $("#" + $('.js-check-same-addr').data('country2')).val();
                        self.updateCountry(country);
                    }
                }
            });
        }


        if ($(".js-delivery-country-selector").length > 0) {
            $(document).on('change', '.js-delivery-country-selector', function (e) {
                self.updateCountry($("#" + e.target.id).val())
            });
        }

        if ($(".js-zip-autocomplete-city").length > 0) {
            $('.js-zip-autocomplete-city').on("keyup", function (e, args) {
                let zip = $(this).val();
                let fill = $(this).data('fill');
                let country = '';
                let countryId = countryIdMustBe;

                if ($(this).val() && $(this).val().length >= 10) {
                    $(this).val($(this).val().substr(0, 10));
                }

                if ($(this).data('country')) {
                    country = $(this).data('country');
                    countryId = $("#" + country).val();
                }
                if (countryId == countryIdMustBe) {
                    if (zip.length == 4) {
                        $.ajax({
                            'method': 'post',
                            'url': '/zip',
                            'data': 'zip=' + zip,
                            'dataType': 'json'
                        }).done(function (resp) {
                            if (resp['city']) {
                                $('#' + fill).val(resp['city']);
                                $("#" + fill).parents('.form-group').addClass('has-value');
                            }
                        });
                    }
                }
            })
        }
        if ($(".js-zip-autocomplete-street").length > 0) {
            $(".js-zip-autocomplete-street").select2({
                ajax: {
                    method: 'post',
                    url: '/streetAutocomplet',
                    dataType: 'json',
                    data: function (params) {
                        console.log(params);
                        return {
                            q: params.term,
                            page: params.page,
                            zip: $("#" + $(this).data('zip')).val(),
                        };
                    },
                    processResults: function (data, params) {
                        console.log('1: ' + params);

                        params.page = params.page || 1;
                        return {
                            results: data.results,
                        };
                    }
                }
            });
        }
    }


    this.enterCallForm = function () {
        $('.js-enter-call-form').keyup(function (e) {
            let form = false;
            if (e.keyCode == 13) {
                if ($(this).data('form')) {
                    form = $(this).data('form');
                    let btn = $(".js-form-" + form).find('button').each(function (i, elem) {
                        if ($(elem).hasClass("js-save-form")) {
                            $(elem).trigger('click');
                        }
                    });
                }
            }
        });
    }

    this.searchTerm = function () {
        let minLength = $('.search-box-input').data('minlength');
        let lang = $('.search-box-input').data('lang');
        $('.search-box-input').keyup(function (e) {
            var thisLength = $(this).val().length;

            if (thisLength >= minLength) {
                if (e.keyCode == 13) {
                    let url = $('.search-box-input').data('url') + '?q=' + $(this).val();
                    document.location.href = url;
                    return;
                }


                $.ajax({
                    'method': 'get',
                    'url': '/search',
                    'data': 'lang=' + lang + '&q=' + $(this).val(),
                    'dataType': 'json'
                }).done(function (resp) {
                    if (resp['html']) {
                        $("#js-ajax-search").html(resp['html']);
                        searchScroll();
                        hasResult();
                    }
                    if (resp['link']) {
                        $(".js-search-link").attr('href', resp['link']);
                    }
                    if (resp['noResult']) {
                        searchNoResult();
                    }
                });
            } else if (thisLength == 0) {
                // Ha 0 karakter van keyup után, akkor üritem a listát és eltüntetem a találati dobozd
                clearResults();
            } else {
                // Ha a leütött karakterekszáma nagyobb, mint 0, de kisebb, mint 3, akkor a találati lista ürül, és kiírja, hogy Nincs találat.
                searchNoResult();
            }
        });

        $('.search-box-close').click(function () {
            $('.sr-list .product-item').remove();
            $('.search-box-input').val('');
            bd.trigger('click');
        });

    }

    this.cookie = function () {
        if ($(".js-accept-cookie").length > 0) {
            $(".js-accept-cookie").click(function () {
                let cookieOption = $(".js-accept-cookie-option").prop('checked');
                let cookieOptionFlag = 0;
                if (cookieOption) {
                    cookieOptionFlag = 1;
                }
                $.ajax({
                    'method': 'post',
                    'url': '/cookie-accept',
                    'data': 'cookie=' + cookieOptionFlag,
                    //   'dataType': 'json'
                }).done(function (resp) {
                    $(".js-cooke-layer").remove();
                });
            });
        }
    }

    this.productVersion = function (){
        if($("#js-select-product-version-first").length >0){
            self.productVersions = $("#js-select-product-version-first").data("pv");
            $('#js-select-product-version-first').on("change", function (e, args) {
                e.preventDefault();
                let pid = $(this).data('pid');
                let parentId = $('#js-select-product-version-first').val();

                let parentName = '';
                $.each(self.productVersions, function( key, value ) {
                    if(value.self_Id == parentId){
                        parentName = value.PropValue
                    }
                });
                $(".js-product-version-remove").remove();
                    let anyOptions = false;
                   let html = '<div class="col-6 col-xs-12 form-group  js-product-version-remove">\n' +
                       '<select class="form-control form-select text-center js-product-version-item-' + pid + '" data-anim="true" name="" id="" required>\n' +
                       '<option value="" selected disabled hidden></option>\n';
                        $.each(self.productVersions, function( key, value ) {
                            if(value.ParentId == parentId){
                                anyOptions = true;
                                html+='<option value="' +parentName +': '+ value.PropValue + '">' + value.PropValue + '</option>\n';
                            }
                        });
                       html+='</select>\n';
                       let firstShort = false;
                    $.each(self.productVersions, function( key, value ) {
                        if(value.ParentId == parentId && !firstShort){
                            firstShort = true;
                            html+='    <label for="" class="form-label">' + value.PropName + '*</label>\n';
                        }
                    });
                html+='</div>';
                if(anyOptions){
                    $("#productVersionAjax").append(html);
                }
                formSelect();


            });
        }
    }


    this.init = function () {
        self.sendForm();
        self.productListPage();
        self.taxNumAutocomplate();
        self.GiftandCoupon();
        self.rangeSlider();
        self.zipNumAutocomplateCity();
        self.searchTerm();
        self.enterCallForm();
        self.cookie();
        self.productVersion();
    }
    this.init();
}


$(document).ready(function () {
    new WI2();
});


