function _api_reader(action, form_data, result_in, if_empty) {
    var path = "/ajax/" + action;

    $.post(path, $.param(form_data))
        .done(function(data) {
            data = jQuery.parseJSON(data);
            if (data.length == 0) {
                if_empty(form_data, data    );
                return false;
            }
            else {
                result_in(form_data, data);
            }
        })
        .fail(function() {
            console.log("Ошибка загрузки " + path)
        });

}

String.prototype.replaceAll = function(token, newToken, ignoreCase) {
    var _token;
    var str = this + "";
    var i = -1;

    if (typeof token === "string") {

        if (ignoreCase) {

            _token = token.toLowerCase();

            while ((
                    i = str.toLowerCase().indexOf(
                        token, i >= 0 ? i + newToken.length : 0
                    )) !== -1
                ) {
                str = str.substring(0, i) +
                    newToken +
                    str.substring(i + token.length);
            }

        } else {
            return this.split(token).join(newToken);
        }

    }
    return str;
};

function emptyFunction() {}

function show_variant_image () {
    if ($('select.product_select option:selected').attr("relimage") == 1){
        $('div.variant_image').hide();
        $('div#variant_image' + $('select.product_select option:selected').val()).fadeIn(500);
    }

    $('div.variant_groups').hide();
    $('div#variant_groups' + $('select.product_select option:selected').val()).fadeIn(500);

    var h = $('div#variant_groups' + $('select.product_select option:selected').val()).height();

    $('div.variant_image img').unbind("click");
    $('div.variant_image img').click(function (e) {
       variant_image_show($(this));
    });

    if (h > 0){
        //console.log('not null');
        $('main').height($('div#variant_groups' + $('select.product_select option:selected').val()).height() + 1400);
    }else{
        //console.log('!!! null');
        $("main").css("height",(($( document).height())-500)+"px");
    }

    calculate_price($('select.product_select option:selected').val());
}

function variant_image_show(e){
    var pswpElement = document.querySelectorAll(".pswp")[0];

    var sizes = get_real_image_sizes($(e));

    var items = [
        {src: $(e).attr("src"), w: sizes.w, h: sizes.h}
    ];

    var options = {
        index: e,
        history: false,
        focus: false,
        showAnimationDuration: 0,
        hideAnimationDuration: 0,
        closeOnScroll: false,
        timeToIdle: 99999999,
        timeToIdleOutside: 99999999,
        tapToClose: true,
        clickToCloseNonZoomable: true,
    };

    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
}

function get_real_image_sizes(myimage){
    var i = new Image();
    i.src = $(myimage).attr("src");
    var rw = i.width;
    var rh = i.height;

    return {
        w : rw,
        h : rh
    }
}


function show_attribute_image (group_id) {
    if ($('select#attributes_select_group' + group_id + ' option:selected').attr("relimage") == 1){
        $('div.attribute_image_group' + group_id).hide();
        $('div#attribute_image' + $('select#attributes_select_group' + group_id + ' option:selected').val()).fadeIn(500);
    }

    $('div.attribute_image img').unbind("click");
    $('div.attribute_image img').click(function (e) {
        variant_image_show($(this));
    });

    //console.log($('select#attributes_select_group' + group_id + '').attr("relvariant") + " - " + $('select.product_select option:selected').val());

    if ($('select.product_select option:selected').val() == $('select#attributes_select_group' + group_id + '').attr("relvariant")){

        calculate_price($('select#attributes_select_group' + group_id + '').attr("relvariant"));
    }
}

function calculate_price (variant_id) {
    if ($('select.product_select option:selected').val() > 0){
        var price = parseInt($('select.product_select option:selected').attr("relprice"));
        var old_price = parseInt($('select.product_select option:selected').attr("reloldprice"));
        //console.log(price);
        //console.log(old_price);

        $('div#variant_groups'+variant_id+' select.attribute_select option:selected').each(function( index ) {
            price += parseInt($(this).attr('relprice'));
            old_price += parseInt($(this).attr('reloldprice'));
        });

        $('div#variant_groups'+variant_id+' input.check:checked').each(function( index ) {
            price += parseInt($(this).attr('relprice'));
            old_price += parseInt($(this).attr('reloldprice'));
        });

        $('span#price').html($.number(price, 0));
        if (old_price > 0){
            $('span#plusprice').html($.number(old_price, 0) + ' ₽');
        }else{
            $('span#plusprice').html(' ');
        }

        $('input#old_price').val(old_price);
        $('input#price').val(price);
    }
}

function product_to_basket () {
    var form_data = {
        'product_id': $('input#product_id').val(),
        'price': $('input#price').val(),
        'old_price': $('input#old_price').val(),
        'form_serialized': $('form#order_form').serialize()
    };

    _api_reader('add_to_basket', form_data, product_added_to_basket, emptyFunction);
}

function calculate_button (e) {
    show_calculate_window(e);
}

function show_price_button (e) {
    show_show_price_window(e);
}

function fly_to_basket(count){
    var left = $("a#checkout").offset()['left'];
    if (left == 0) {left = $("i.fa-shopping-cart").offset()['left'];}
    var top = $("a#checkout").offset()['top'];
    if (top == 0) {top = $("i.fa-shopping-cart").offset()['top'];}

    $('.order-text').show();

    setTimeout(function(){
        $('.order-text').hide();
    }, 1300)

    $("img#main_image") // Анимашка улета в корзину
        .clone()
        .css({'position' : 'absolute', 'z-index' : '11100', top: $("img#main_image").offset().top, left:$("img#main_image").offset().left})
        .appendTo("body")
        .animate({opacity: 0.05,
            left: left,
            top: top,
            width: 20,
            height: 20}, 1000, function() {
            $('span.checkout_count').html('' + count + '');
            $('span.checkout_count_mobile').html(count);

            if (count > 0){
                $('span.checkout_count').show();
            }else{
                $('span.checkout_count').hide();
            }

            $(this).remove();
        });
}

function product_added_to_basket(out, inc){
    if (inc.status == 0){
        //console.log(inc);
        fly_to_basket(inc.count);

        var personal_discount_activated = $('#personal_discount_activated').val();
        var promo_disabled = $('#disable_personal_discount').val();

        if (personal_discount_activated != "1" && promo_disabled != "1") {
            if ($('#user_logged').val() != 1){
                if ($('#personal_discount_active').val() != 1) {
                    show_promo_modal();
                }
            }
        }
    }else{
        console.log(inc);
    }
}


function locate_basket(){
    $.ajax({
        url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCVVNe7ez25nNyJZb89HFFwHIBmAkYYhN0',
        data: JSON.stringify({ "considerIp": "true" }),
        type: 'POST',
        contentType: 'application/json',
        success: function(data) {
            if(data.location) {
                $('input#lat').val(data.location.lat);
                $('input#lng').val(data.location.lng);

                get_address_from_map(data.location)
            } else {
                $('input#lat').val(0);
                $('input#lng').val(0);
            }
        }
    });
}

function get_address_from_map(location) {
    var input_address = document.getElementById('address');

    var geocoder = new google.maps.Geocoder;

    geocoder.geocode({'location': location}, function(results, status) {
        if (status === 'OK') {
            if (results[1]) {
                //console.log(results);
                $('input#address').val(results[0].formatted_address);
            } else {
                console.log('No results found');
            }
        } else {
            console.log('Geocoder failed due to: ' + status);
        }
    });
}

function send_order(){
    $('p#error').hide(300);

    $('#submit_order').attr('disabled', true);
    $('#submit_order').val('Отправка заказа...');

    var form_data = {
        'name': $('input#fio').val(),
        'email': $('input#email').val(),
        'phone': $('input#phone').val(),
        'comment': $('input#comment').val(),
        'client_id': $('input#client_id').val(),
        'use_bonus': $('input#use_bonus').val(),
        'captcha': $('input#checkout_captcha').val(),
        'total': $('input#total').val(),
    };

    _api_reader('save_order', form_data, verify_order, emptyFunction);
}

function verify_order(out, inc){
    if (inc.status == 0){

        $('#top_h2').hide(300);
        $('form#order_form').hide(300);
        $('table#basket_table').hide(300);
        $('div#order_successful').show(500)

        up();

        $('main').css('height', 'auto');

        //console.log(inc);
    }else{
        $('#submit_order').attr('disabled', false);
        $('#submit_order').val('Оформить предзаказ');

        $('p#error').html(inc.error);
        $('p#error').show(300);
    }
}

function up() {
    var top = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    if(top > 0) {
        window.scrollBy(0,-100);
        t = setTimeout('up()',20);
    } else clearTimeout(t);
    return false;
}

function show_promo_modal(){
    var text = $('#promo-header-counter').html();
    $.ajax({
        url: '/ajax/get_promocodes_count',
        data: '',
        type: 'POST',
        contentType: 'application/json',
        success: function(data) {
            if(data) {
                text = text.replaceAll("#c#", data);
                $('#promo-header-counter').html(text);
                show_promo_modal_window()
            } else {
                text = text.replaceAll("#c#", 457);
                $('#promo-header-counter').html(text);
                show_promo_modal_window()
            }
        }
    });
}

function activate_promocode(){
    $('#promocode_status').html('');
    $.ajax({
        url: '/ajax/activate_promocode',
        data: JSON.stringify({ "code": $('#promocode').val() }),
        type: 'POST',
        contentType: 'application/json',
        success: function(data) {
            data = jQuery.parseJSON(data);
            if(data.status == 0) {
                $('#promocode_status').addClass('success');
                $('#promocode_status').removeClass('error');
                $('#promocode').hide(10);
                $('.promocode_activate').hide(10);
                $('.promocode_br').hide(10);
                $('#promocode_status').html('Промокод <b>' + $('#promocode').val() + '</b> успешно активирован.');

                setTimeout(function() {
                    window.location.reload(true);
                }, 1500);
            } else {
                $('#promocode_status').removeClass('success');
                $('#promocode_status').addClass('error');
                $('#promocode_status').html(data.error);
            }
        }
    });
}

function show_promo_modal_window(){
    $("#discount_modal").modal({
        fadeDuration: 800,
        fadeDelay: 0.10
    });

    $('#promo_form').unbind('submit');

    $('#promo_form').submit(function (e) {
       e.preventDefault();
       var code_sended = $('#code_sended').val();


       if (code_sended == 0 && code_sended != null){
           var phone = $('#promo-phone').val();

           if (phone != ''){
               var form_data = {
                   'phone': phone
               };

               _api_reader('send_promocode', form_data, verify_phone, emptyFunction);
           }else{
               alert('Укажите Ваш номер телефона');
           }
       }else{
           var code = $('#promo-code').val();

           if (code != ''){
               var form_data = {
                   'code': code,
                   'form_serialized': $('form#order_form').serialize()
               };

               _api_reader('check_promocode', form_data, verify_code, emptyFunction);
           }else{
               alert('Вы не ввели код');
           }
       }

    });

    $('.promo-cancel').click(function (e) {
        $('#disable_personal_discount').val(1);

        var form_data = {
            'form_serialized': $('form#order_form').serialize()
        };

        _api_reader('disable_personal_discount', form_data, emptyFunction, emptyFunction);
    });

    $('#promo-send-code').click(function (e) {
        $('#promo_form').submit();
    });
}

function show_calculate_window(e){
    $("#calculate_modal").modal({
        closeExisting: true,
        fadeDuration: 800,
        fadeDelay: 0.10
    });

    $(".promo-phone").inputmask("+7 (\\999) 999-99-99");

    if ($(e).attr('rel')){
        $('#promo-header-logo').css('background-image', 'url("' + $(e).attr('relimage') + '")');
        $('#send-calculate').html($(e).attr('rel'));
        $('#promo-header').html($(e).attr('relheader'));
        $('#calculate-brand').val($(e).attr('relbrand'));

        if ($(e).attr('relcomment') == 0){
            $('#calculate-question').hide();
        }else{
            $('#calculate-question').show();
        }
    }

    $('#calculate_form').off('submit');
    $('#calculate_form').unbind('submit');

    $('#calculate_form').submit(function (e) {
        e.preventDefault();

        var phone = $('#calculate-phone').val();
        var name = $('#calculate-name').val();
        var question = $('#calculate-question').val();
        var captcha = $('#promo_captcha').val();

        if (phone != '' && name != ''){
            $('#promo-errors').html('');
            $('#promo-errors').hide();

            var form_data = {
                'phone': phone,
                'name': name,
                'question': question,
                'captcha': captcha,
                'form_serialized': $('form#order_form').serialize()
            };

            _api_reader('send_calculate', form_data, send_calculate, emptyFunction);
        }else{
            $('#promo-errors').html('Вы не ввели телефон или имя');
            $('#promo-errors').show();
        }
    });

    $('#send-calculate').off('click');
    $('#send-calculate').unbind('click');

    $('#send-calculate').click(function (e) {
        $('#calculate_form').submit();
    });
}

function send_calculate(out, inc){
    if (inc.status == 0){
        $("#calculate-body-main").hide(100);
        $("#calculate-success-main").show(100);
    }else{
        $('#promo-errors').html(inc.error);
        $('#promo-errors').show();
    }
}
function verify_phone(out, inc){
    if (inc.status == 0){
        var use_basket = $('#use_basket').val();

        if (use_basket == 1){
            window.location.href = '/checkout/';
        }else{
            $("#discount_modal").modal('close');
            $("#calculate-success-promo").modal({
                fadeDuration: 800,
                fadeDelay: 0.10
            });
        }
    }else{
        alert(inc.error);
    }
}

function verify_code(out, inc){
    if (inc.status == 0){
        window.location.href = '/checkout/';
    }else{
        alert(inc.error);
    }
}

function send_login(){
    $('p#login_error').hide(300);

    var form_data = {
        'phone': $('input#login_phone').val(),
        'password': $('input#login_password').val(),
    };

    _api_reader('login', form_data, verify_login, emptyFunction);
}

function verify_login(out, inc){
    if (inc.status == 0){

        setTimeout(function() {
            window.location.reload(true);
        }, 500);

    }else{
        $('p#login_error').html(inc.error);
        $('p#login_error').show(300);
    }
}



function send_register(){
    $('p#register_error').hide(300);

    if ($('input#register_code_sended').val() != 1)
    {
        var form_data = {
            'fio': $('input#register_fio').val(),
            'phone': $('input#register_phone').val(),
            'email': $('input#register_email').val(),
            'captcha': $('input#register_captcha').val(),
        };

        _api_reader('register', form_data, verify_register, emptyFunction);
    }else{
        var form_data = {
            'fio': $('input#register_fio').val(),
            'phone': $('input#register_phone').val(),
            'email': $('input#register_email').val(),
            'captcha': $('input#register_captcha').val(),
            'code': $('input#register_code').val(),
        };

        _api_reader('register_code', form_data, verify_register_code, emptyFunction);
    }
}

function verify_register(out, inc){
    if (inc.status == 0){
        $('div#registraion_confirm').show(50);
        $('input#register_code_sended').val('1');
    }else{
        $('p#register_error').html(inc.error);
        $('p#register_error').show(300);
    }
}

function verify_register_code(out, inc){
    if (inc.status == 0){
        setTimeout(function() {
            window.location.reload(true);
        }, 500);
    }else{
        $('p#register_error').html(inc.error);
        $('p#register_error').show(300);
    }
}


function send_forgot(){
    $('p#forgot_error').hide(300);

    if ($('input#forgot_code_sended').val() != 1)
    {
        var form_data = {
            'phone': $('input#forgot_phone').val(),
            'captcha': $('input#forgot_captcha').val(),
        };

        _api_reader('forgot', form_data, verify_forgot, emptyFunction);
    }else{
        var form_data = {
            'phone': $('input#forgot_phone').val(),
            'code': $('input#forgot_code').val(),
            'captcha': $('input#forgot_captcha').val(),
        };

        _api_reader('forgot_code', form_data, verify_forgot_code, emptyFunction);
    }
}

function verify_forgot(out, inc){
    if (inc.status == 0){
        $('div#forgot_confirm').show(50);
        $('input#forgot_code_sended').val('1');
        $('#show-price-send-forgot').html('Ввести код подтверждения');
    }else{
        $('p#forgot_error').html(inc.error);
        $('p#forgot_error').show(300);
    }
}

function verify_forgot_code(out, inc){
    if (inc.status == 0){
        $('#forgot').hide(50);
        $('#registraion').hide(50);
        $('#login').show(50);

        $('p#login_error').html("Новый пароль выслан Вам в SMS.");
        $('#show-price-forgot').hide(50);
        $('#show-price-login').show(50);
        setTimeout(function() {
            window.location.reload(true);
        }, 500);
    }else{
        $('p#forgot_error').html(inc.error);
        $('p#forgot_error').show(300);
    }
}



function send_update(){
    $('p#update_error').hide(300);

    var password = $('input#update_password').val();
    var password2 = $('input#update_password2').val();

    var error = false;

    if (password != '' && (password != password2)){
        $('p#update_error').html('Пароли не совпадают');
        $('p#update_error').show(300);
        error = true;
    }

    if (error == false){
        if ($('input#update_code_sended').val() != 1)
        {
            var form_data = {
                'fio': $('input#update_fio').val(),
                'email': $('input#update_email').val(),
            };

            _api_reader('update', form_data, verify_update, emptyFunction);
        }else{
            var form_data = {
                'fio': $('input#update_fio').val(),
                'email': $('input#update_email').val(),
                'password': $('input#update_password').val(),
                'password2': $('input#update_password2').val(),
                'code': $('input#update_code').val(),
            };

            _api_reader('update_code', form_data, verify_update_code, emptyFunction);
        }
    }
}

function verify_update(out, inc){
    if (inc.status == 0){
        $('div#update_confirm').show(50);
        $('input#update_code_sended').val('1');
    }else{
        $('p#update_error').html(inc.error);
        $('p#update_error').show(300);
    }
}

function verify_update_code(out, inc){
    if (inc.status == 0){
        setTimeout(function() {
            window.location.reload(true);
        }, 500);
    }else{
        $('p#update_error').html(inc.error);
        $('p#update_error').show(300);
    }
}

function show_price_send_code(out, inc){
    if (inc.status == 0){
        $('#show-price-send-code').unbind('click');
        $('#send-code-register-buttons').show();
        $('#show-price-name').attr('disabled', true);
        $('#show-price-phone').attr('disabled', true);
        $('#show-price-email').attr('disabled', true);
        $('#show-price-password').attr('disabled', true);
        $('#show-price-password2').attr('disabled', true);

        $('#show-price-code').focus();

        $("#calculate-body").hide(100);
        $("#calculate-success").show(100);
    }else{
        $('#show-price-errors').html(inc.error);
        $('#show-price-errors').show();
    }
}

function show_price_register_code(out, inc){
    if (inc.status == 0){
        $('#show-price-register').hide();
        window.location.reload();
    }else{
        $('#show-price-errors').html(inc.error);
        $('#show-price-errors').show();
    }
}

function show_show_price_window(e){
    $("#show_price_modal").modal({
        closeExisting: true,
        fadeDuration: 800,
        clickClose: false,
        showSpinner: true,
        fadeDelay: 0.10
    });

    $('.show-price-open-login').click(function (e) {
        e.preventDefault();

        $('#show-price-register').hide();
        $('#show-price-forgot').hide();
        $('#show-price-login').show();
    });

    $('.show-price-open-registration').click(function (e) {
        e.preventDefault();

        $('#show-price-register').show();
        $('#show-price-login').hide();
        $('#show-price-forgot').hide();
    });

    $('.show-price-open-forgot').click(function (e) {
        e.preventDefault();

        $('#show-price-register').hide();
        $('#show-price-login').hide();
        $('#show-price-forgot').show();
    });

        $(".promo-phone").inputmask("+7 (\\999) 999-99-99");

    if ($(e).attr('rel')){
        $('#send-calculate').html($(e).attr('rel'));
        $('#promo-header').html($(e).attr('relheader'));
        $('#calculate-brand').val($(e).attr('relbrand'));

        if ($(e).attr('relcomment') == 0){
            $('#calculate-question').hide();
        }else{
            $('#calculate-question').show();
        }
    }

    $('#show_price_form').off('submit');
    $('#show_price_form').unbind('submit');

    $('#show-price-send-code').click(
        function (e) {
            e.preventDefault();

            var phone = $('#show-price-phone').val();
            var name = $('#show-price-name').val();
            var email = $('#show-price-email').val();
            var password = $('#show-price-password').val();
            var password2 = $('#show-price-password2').val();
            var captcha = $('#show-price-captcha').val();

            if (phone != '' && name != ''){
                if (password == password2 && password != ''){
                    $('#show-price-errors').html('');
                    $('#show-price-errors').hide();

                    var form_data = {
                        'phone': phone,
                        'name': name,
                        'email': email,
                        'captcha': captcha,
                        'password': password
                    };

                    console.log(form_data);

                    _api_reader('register', form_data, show_price_send_code, emptyFunction);
                }else{
                    $('#show-price-errors').html('Пароли не должны быть пустыми и совпадать');
                    $('#show-price-errors').show();
                }
            }else{
                $('#show-price-errors').html('Вы не ввели телефон или имя');
                $('#show-price-errors').show();
            }
        }
    );

    $('#show_price_login_form').off('submit');
    $('#show_price_login_form').unbind('submit');
    $('#show-price-send-login').click(function (e) {
        e.preventDefault();
        $('#show_price_login_form').submit();
    });
    $('#show_price_login_form').submit(function (e) {
        e.preventDefault();
        send_login();
    });

    $('#show_price_forgot_form').off('submit');
    $('#show_price_forgot_form').unbind('submit');
    $('#show-price-send-forgot').click(function (e) {
        e.preventDefault();
        $('#show_price_forgot_form').submit();
    });
    $('form#show_price_forgot_form').submit(function(e){
        e.preventDefault();
        send_forgot();
    });

    $('#show_price_form').submit(function (e) {
        e.preventDefault();

        console.log(333);

        var phone = $('#show-price-phone').val();
        var name = $('#show-price-name').val();
        var email = $('#show-price-email').val();
        var password = $('#show-price-password').val();
        var code = $('#show-price-code').val();

        if (code != ''){
            $('#show-price-errors').html('');
            $('#show-price-errors').hide();

            var form_data = {
                'phone': phone,
                'name': name,
                'email': email,
                'code': code,
                'password': password
            };

            console.log(form_data);

            _api_reader('register_code', form_data, show_price_register_code, emptyFunction);
        }else{
            $('#show-price-errors').html('Вы не ввели код');
            $('#show-price-errors').show();
        }
    });

    $('#send-show-register').off('click');
    $('#send-show-register').unbind('click');

    $('#send-show-register').click(function (e) {
        $('#show_price_form').submit();
    });
}


$(document).ready(function (e){
    $(".phone").inputmask("+7 (\\999) 999-99-99");;
    $(".promo-phone").inputmask("+7 (\\999) 999-99-99");;

    $('button.callbutton').click(function (e){
        e.preventDefault();

        calculate_button($(this));
    });

    var promo_delay = $('#promo_delay').val();
    var use_global_promo = $('#use_global_promo').val();

    if (parseInt(use_global_promo)){
        setTimeout(() => {
            var personal_discount_activated = $('#personal_discount_activated').val();
            var promo_disabled = $('#disable_personal_discount').val();

            if (personal_discount_activated != "1" && promo_disabled != "1") {
                if ($('#user_logged').val() != 1){
                    if ($('#personal_discount_active').val() != 1) {
                        show_promo_modal();
                    }
                }
            }
        }, parseInt(promo_delay) * 1000);
    }

});


