/* liteUploader v2.1.1 | https://github.com/burt202/lite-uploader | Aaron Burtnyk (http://www.burtdev.net) */
$.fn.liteUploader = function (options) {
    var defaults = {
        script: null,
        rules: {
            allowedFileTypes: null,
            maxSize: null
        },
        params: {},
        changeHandler: true,
        clickElement: null
    };

    return this.each(function () {
        $.data(this, 'liteUploader', new LiteUploader(this, $.extend(defaults, options)));
    });
};


function LiteUploader (element, options) {
    this.el = $(element);
    this.options = options;
    this.params = options.params;
    this.xhr = this._buildXhrObject();

    this._init();
}

LiteUploader.prototype = {
    _init: function () {
        if (this.options.changeHandler) {
            this.el.change(function () {
                this._start();
            }.bind(this));
        }

        if (this.options.clickElement) {
            this.options.clickElement.click(function () {
                this._start();
            }.bind(this));
        }
    },

    _buildXhrObject: function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', this._onProgress.bind(this), false);
        return xhr;
    },

    _onProgress: function (evt) {
        if (evt.lengthComputable) {
            this.el.trigger('lu:progress', Math.floor((evt.loaded / evt.total) * 100));
        }
    },

    _start: function () {
        var files = this.el.get(0).files;

        if (this._validateInput(files)) {
            this._resetInput();
            return;
        }

        if (this._validateFiles(files)) {
            this._resetInput();
            return;
        }

        this.el.trigger('lu:before', [files]);
        this._performUpload(this._collateFormData(files));
    },

    _resetInput: function () {
        this.el.val('');
    },

    _validateInput: function (files) {
        var errors = [];

        if (!this.el.attr('name')) {
            errors.push('the file input element must have a name attribute');
        }

        if (!this.options.script) {
            errors.push('the script option is required');
        }

        if (files.length === 0) {
            errors.push('at least one file must be selected');
        }

        this.el.trigger('lu:errors', [[{
            name: 'liteUploader_input',
            errors: errors
        }]]);

        if (errors.length > 0) {
            return true;
        }
        return false;
    },

    _validateFiles: function (files) {
        var errorsPresent = false,
            errorReporter = [];

        $.each(files, function (i, f) {
            var errorsFound = this._findErrors(files[i]);
            errorReporter.push({
                name: files[i].name,
                errors: errorsFound
            });
            if (errorsFound.length > 0) {
                errorsPresent = true;
            }
        }.bind(this));

        this.el.trigger('lu:errors', [errorReporter]);
        return errorsPresent;
    },

    _findErrors: function (file) {
        var errorsArray = [];

        $.each(this.options.rules, function (key, value) {
            if (key === 'allowedFileTypes' && value && $.inArray(file.type, value.split(',')) === -1) {
                errorsArray.push({'type': 'type', 'rule': value, 'given': file.type});
            }

            if (key === 'maxSize' && value && file.size > value) {
                errorsArray.push({'type': 'size', 'rule': value, 'given': file.size});
            }
        });

        return errorsArray;
    },

    _getFormDataObject: function () {
        return new FormData();
    },

    _collateFormData: function (files) {
        var formData = this._getFormDataObject();

        if (this.el.attr('id')) {
            formData.append('liteUploader_id', this.el.attr('id'));
        }

        $.each(this.params, function (key, value) {
            formData.append(key, value);
        });

        $.each(files, function (i) {
            formData.append(this.el.attr('name'), files[i]);
        }.bind(this));

        return formData;
    },

    _performUpload: function (formData) {
        $.ajax({
            xhr: function () {
                return this.xhr;
            }.bind(this),
            url: this.options.script,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false
        })
            .done(function(response){
                this.el.trigger('lu:success', response);
            }.bind(this))
            .fail(function(jqXHR) {
                this.el.trigger('lu:fail', jqXHR);
            }.bind(this))
            .always(function() {
                this._resetInput();
            }.bind(this));
    },

    addParam: function (key, value) {
        this.params[key] = value;
    },

    removeParam: function (key) {
        delete this.params[key];
    },

    cancelUpload: function () {
        this.xhr.abort();
        this.el.trigger('lu:cancelled');
        this._resetInput();
    },

    _validateOptions: function () {
        var requiredOptions = ["script", "ref"];
        var errors = requiredOptions.reduce(function (acc, option) {
            if (!this.options[option]) acc.push({ type: option + "Required" });
            return acc;
        }.bind(this), []);

        if (errors.length) {
            return [{
                name: "_options",
                errors: errors
            }];
        } else {
            return null;
        }
    }
};

/*!
 Zoom v1.7.13 - 2014-04-29
 Enlarge images on click or mouseover.
 (c) 2014 Jack Moore - http://www.jacklmoore.com/zoom
 license: http://www.opensource.org/licenses/mit-license.php
 */
(function (o) {
    var t = {
        url: !1,
        callback: !1,
        target: !1,
        duration: 120,
        on: "mouseover",
        touch: !0,
        onZoomIn: !1,
        onZoomOut: !1,
        magnify: 1
    };
    o.zoom = function (t, n, e, i) {
        var u, c, a, m, l, r, s, f = o(t).css("position"), h = o(n);
        return t.style.position = /(absolute|fixed)/.test(f) ? f : "relative", t.style.overflow = "hidden", e.style.width = e.style.height = "", o(e).addClass("zoomImg").css({
            position: "absolute",
            top: 0,
            left: 0,
            opacity: 0,
            width: e.width * i,
            height: e.height * i,
            border: "none",
            maxWidth: "none",
            maxHeight: "none"
        }).appendTo(t), {
            init: function () {
                c = o(t).outerWidth(), u = o(t).outerHeight(), n === t ? (m = c, a = u) : (m = h.outerWidth(), a = h.outerHeight()), l = (e.width - c) / m, r = (e.height - u) / a, s = h.offset()
            }, move: function (o) {
                var t = o.pageX - s.left, n = o.pageY - s.top;
                n = Math.max(Math.min(n, a), 0), t = Math.max(Math.min(t, m), 0), e.style.left = t * -l + "px", e.style.top = n * -r + "px"
            }
        }
    }, o.fn.zoom = function (n) {
        return this.each(function () {
            var e, i = o.extend({}, t, n || {}), u = i.target || this, c = this, a = o(c),
                m = document.createElement("img"), l = o(m), r = "mousemove.zoom", s = !1, f = !1;
            (i.url || (e = a.find("img"), e[0] && (i.url = e.data("src") || e.attr("src")), i.url)) && (function () {
                var o = u.style.position, t = u.style.overflow;
                a.one("zoom.destroy", function () {
                    a.off(".zoom"), u.style.position = o, u.style.overflow = t, l.remove()
                })
            }(), m.onload = function () {
                function t(t) {
                    e.init(), e.move(t), l.stop().fadeTo(o.support.opacity ? i.duration : 0, 1, o.isFunction(i.onZoomIn) ? i.onZoomIn.call(m) : !1)
                }

                function n() {
                    l.stop().fadeTo(i.duration, 0, o.isFunction(i.onZoomOut) ? i.onZoomOut.call(m) : !1)
                }

                var e = o.zoom(u, c, m, i.magnify);
                "grab" === i.on ? a.on("mousedown.zoom", function (i) {
                    1 === i.which && (o(document).one("mouseup.zoom", function () {
                        n(), o(document).off(r, e.move)
                    }), t(i), o(document).on(r, e.move), i.preventDefault())
                }) : "click" === i.on ? a.on("click.zoom", function (i) {
                    return s ? void 0 : (s = !0, t(i), o(document).on(r, e.move), o(document).one("click.zoom", function () {
                        n(), s = !1, o(document).off(r, e.move)
                    }), !1)
                }) : "toggle" === i.on ? a.on("click.zoom", function (o) {
                    s ? n() : t(o), s = !s
                }) : "mouseover" === i.on && (e.init(), a.on("mouseenter.zoom", t).on("mouseleave.zoom", n).on(r, e.move)), i.touch && a.on("touchstart.zoom", function (o) {
                    o.preventDefault(), f ? (f = !1, n()) : (f = !0, t(o.originalEvent.touches[0] || o.originalEvent.changedTouches[0]))
                }).on("touchmove.zoom", function (o) {
                    o.preventDefault(), e.move(o.originalEvent.touches[0] || o.originalEvent.changedTouches[0])
                }), o.isFunction(i.callback) && i.callback.call(m)
            }, m.src = i.url)
        })
    }, o.fn.zoom.defaults = t
})(window.jQuery);



var _resizeGood = function () {

};

var _resizeAll = {
    all: function () {
        if ($('.product_card_wrap').length > 0) {
            $('.product_card_wrap').each(function () {
                var w = 285;
                var m = 15;
                var am = 0;
                var items = $(this).find('.product_card');
                items.css('margin-left', 0);
                //$(items).css('display', 'none');
                var cw = $(this).width();
                for (var b = 1; ((b * (w + m)) - m) < cw; b++) {
                    am = Math.floor((cw - ((b * (w + m)) - m)) / (b - 1));
                }
                items.css('margin-left', (am + m) + 'px');
                $(this).find('.product_card:nth-child(' + (b - 1) + 'n + 1)').css('margin-left', 0);

            });
            $('.product_card_wrap').css('visibility', 'visible');
        }

    }

};

(function ($) {
    $.fn.customizeForm = function () {
        this.each(function () {
            var input = $(this);
            if (!input.data('initialized')) {
                doCustomInput(input);
            }
        });
        return this;
    };
    var doCustomInput = function (input) {
        if (!input.hasClass('not_custom')) {
            if (input.is('input')) {
                var type = input.attr('type');
                if (type == 'radio' || type == 'checkbox') {
                    input.parent().addClass('custom_input_label');
                    input.addClass('custom_input');
                    input.after($('<span class="custom_input custom_input_' + type + '"></span>'));
                }
                if (type == 'file') {
                    input.wrap('<span class="custom_input_file">' + input.data('btn') + '</span>');
                    input.parent().wrap('<label class="custom_input_file_label" />');
                    input.parent().parent().append('<span class="custom_input_file_tip">' + input.data('tip') + '</span>');
                    console.log(input);
                    input.attr('onchange', '$(this).val() == \'\' ?  $(this).parent().next().text(\'' + input.data('tip') + '\') : $(this).parent().next().text(($(this).val())) ')
                }
            } else if (input.is('select')) {
                // var prop = {w: input.outerWidth(true), h: input.outerHeight()};
                // input.wrap('<span class="custom_select" onclick="$(this).toggleClass(\'custom_select_opened\');" style="width:' + prop.w + 'px;height:' + prop.h + 'px;"></span>');

                // console.log(prop.w, input.outerWidth(true));
                // input.after('<span class="custom_select_toggle"></span>');
                // input.attr('onblur', '$(this).parent().removeClass(\'custom_select_opened\');');
                // input.outerWidth(prop.w + 30);
            }
            input.data('initialized', '1');
        }
    }
})(jQuery);

function formatNum(num) {
    return num.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}

$(document).ready(function () {

    /*$(window).resize(function () {
      _resizeGood();

      $.each(_resizeAll, function(i, fun){
        fun();
      });

    }).resize();*/
    $('input,select').customizeForm();

});


$(window).load(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.btn_to_up').addClass('show');
        } else {
            $('.btn_to_up').removeClass('show');
        }
    });


    var bad_variant = 0;

    $('.header_login_form #signin_username, .header_login_form #signin_password').keypress(function () {
        $('.error_login').css('display', 'none');
    });

    $('.header_login_form').submit(function (e) {
        var dataForm = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: '/personal/ajax_login/',
            dataType: 'JSON',
            data: dataForm,
            success: function (data) {
                if (data.state == 'success') {
                    window.location.href = '/personal/profile/';
                }
                if (data.state == 'error') {
                    $('.error_login').css('display', 'block');
                    bad_variant++;
                    if (bad_variant >= 3) {
                        var btn = $('.forgot_pass');
                        if (btn.hasClass('top_bottom_center_animation')) {
                            btn.removeClass('top_bottom_center_animation');
                            btn.width();
                        }
                        btn.addClass('top_bottom_center_animation');

                    }
                }
            }
        })


        e.preventDefault();
    });


    try {
        $('.phone_inp').mask("+7 (999) 999-9999");

    }
    catch (e) {

    }

    /*
    search = {
        quickSearch: function (query) {
            if (location.pathname == '/search/') {
                if (query.length > 2) {

                    $.ajax({
                        type: 'POST',
                        url: '/quick_search/?full',
                        data: {'query': query},
                        success: function (data) {
                            $('.refresh').html(data);
                        }
                    });
                }
                else {
                    $('.refresh').html('<div style="padding:6px 20px;color:#969696;">Ничего не найдено</div>');
                }
            }
            else {
                if (query.length > 2) {

                    $.ajax({
                        type: 'POST',
                        url: '/quick_search/',
                        data: {'query': query},
                        success: function (data) {
                            $('.search_result').html(data);
                            $('.er_content__main__search__clear').show();
                        }
                    });
                }
                else {
                    $('.search_result').html("");
                    $('.er_content__main__search__clear').hide();
                }
            }

        }

    }
    */


    profileApp = {


            comPass: function (_this) {
                var password = $(_this).val(),
                    passLengthTxt = $('.pass_length__txt'),
                    leng = password.length,
                    score = PassGenJS.getScore(password),
                    color = null,
                    txt = null,
                    onlyEng = $('.only_eng');

                if (password.search(/[А-яЁё]/) === -1) {
                    onlyEng.css({
                        'color': '#cdcdcb',
                        'text-decoration': 'none'
                    });
                    if (score.score == 1) {
                        color = '#ff6666';
                        txt = 'слабый';
                    } else if (score.score == 2) {
                        color = '#f0b154';
                        txt = 'средний';
                    } else if (score.score > 2) {
                        color = '#5bbb91';
                        txt = 'надежный';
                    }
                    $('.pass_length__level').css({
                        'width': score.reliabilityPercent + '%',
                        'background-color': color
                    });
                    passLengthTxt
                        .css({
                            'color': color,
                            'opacity': leng > 0 ? '1' : '0'
                        })
                        .find('span').html(txt);
                }
                else {
                    onlyEng.css({
                        'color': '#000',
                        'text-decoration': 'underline'
                    });
                    passLengthTxt.css('opacity', '0');
                    $('.pass_length__level').css('width', '0%');
                }


            },

            changePassword: function () {
                var dataForm = $('#change_password_form').serialize(),
                    checkNewPass = $('input[name="settings[password]"]').val();
                chechOldPass = $('input[name="settings[old_password]"]').val();

                if (chechOldPass.length > 0) {
                    if (checkNewPass.length >= 6 && checkNewPass.search(/[А-яЁё]/) === -1) {
                        $('#change_password_form').addClass('preloader');
                        $.ajax({
                            type: 'POST',
                            url: '/personal/profile/edit/?password',
                            dataType: 'JSON',
                            data: dataForm,
                            success: function (data) {
                                // console.log(data);
                                if (data.state == 'success') {
                                    document.getElementById('change_password_form').reset();
                                    $('#change_password_form').removeClass('preloader');
                                    $('.pass_length__level').css('width', '0%');
                                    $('.pass_length__txt').css('opacity', '0');
                                }
                                profileApp.message.onShow(data);
                            }
                        })
                    }
                    else {
                        profileApp.message.onShow({
                            'state': 'password_small',
                            'errorText': 'Пароль слишком короткий<br>Или содержит не допустимые символы'
                        });
                    }
                }
                else {
                    profileApp.message.onShow({
                        'state': 'old_password_empty',
                        'errorText': 'Не введен старый пароль'
                    });
                }


                return false;
            },

            saveSettings: function () {

                var dataForm = $('#settings_form').serialize();

                var org = $('.org').val();
                //$('#settings_form').addClass('preloader');

                $.ajax({
                    type: 'POST',
                    url: '/personal/profile/edit/?requisites',
                    dataType: 'JSON',
                    data: dataForm,
                    success: function (data) {
                        console.log(data);
                        if (data.state == 'success') {

                            $('.personal').html(org);
                            //$('#settings_form').removeClass('preloader');

                        }
                        profileApp.message.onShow(data);
                    }
                })
                return false;
            },

            ordersClick: function (_this) {
                var _this = $(_this);
                var id = _this.data('id');

                $('.total_table__goods[data-id="' + id + '"]').toggle();
                _this.toggleClass('total_table__orders_active');
            },

            tabsClick: function (_this) {
                var _this = $(_this);
                var id = _this.attr('href');

                $('.tabs_links_link').removeClass('tabs_links_link_active');
                $('.tabs_item').hide();
                $('.tabs_links_link[href="' + id + '"]').addClass('tabs_links_link_active');
                $('.tabs_item[data-id="' + id + '"]').show();
            },

            message: {
                onShow: function (o) {
                    var text = (o.state == 'success' ? o.text : o.errorText);
                    var html = $('<div onclick="$(this).hide();" class="main_message main_message_' + (o.state == 'success' ? 'green' : 'red') + '">' +
                        (typeof text == 'undefined' ? 'Неизвестная ошибка' : text) +
                        '</div>');
                    if ($('.main_message').length > 0) {
                        $('.main_message').remove();
                    }
                    $('body').append(html);
                    html.fadeOut(8000);
                    setTimeout(function () {
                        html.fadeOut(200).remove();
                    }, 8000);

                }

            },

            reg: {

                signUp: function (_this) {
                    var dataForm = $('#overlay__contain_registration_form').serialize();
                    var onlyEmail = $('#overlay__contain_registration_form').hasClass('onlyEmail');

                    if (onlyEmail) {
                        $.ajax({
                            type: 'POST',
                            url: '/newUserReg/',
                            dataType: 'JSON',
                            data: dataForm,
                            success: function (data) {
                                if (data.state == 'success') {
                                    $('.refresh').empty();
                                    $('.refresh').html(data.text + '<i class="br10"></i><a href="/">Вернуться на главную</a>');
                                } else {
                                    profileApp.message.onShow(data);
                                }
                            }
                        })
                    }
                    else {
                        $.ajax({
                            type: 'POST',
                            url: '/signup/',
                            dataType: 'JSON',
                            data: dataForm,
                            success: function (data) {
                                if (data.state == 'success') {
                                    $('.refresh').empty();
                                    $('.refresh').html(data.text + '<i class="br10"></i><a href="/">Вернуться на главную</a>');
                                } else {
                                    profileApp.message.onShow(data);
                                }
                            }
                        })
                    }

                },

                checkEmail: function (c) {
                    return /^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,7}$/.test(c);
                },

                checkInn: function (c) {
                    var cs = null;
                    c = c + '';
                    if (c.length == 10) {
                        cs = (2 * c[0] + 4 * c[1] + 10 * c[2] + 3 * c[3] + 5 * c[4] + 9 * c[5] + 4 * c[6] + 6 * c[7] + 8 * c[8]);
                        cs = cs % 11;
                        cs = cs % 10;
                        if (cs == c[9]) {
                            return c;
                        }
                    }
                    else if (c.length == 12) {
                        cs = (7 * c[0] + 2 * c[1] + 4 * c[2] + 10 * c[3] + 3 * c[4] + 5 * c[5] + 9 * c[6] + 4 * c[7] + 6 * c[8] + 8 * c[9]);
                        cs = cs % 11;
                        cs = cs % 10;
                        if (cs == c[10]) {
                            cs = (3 * c[0] + 7 * c[1] + 2 * c[2] + 4 * c[3] + 10 * c[4] + 3 * c[5] + 5 * c[6] + 9 * c[7] + 4 * c[8] + 6 * c[9] + 8 * c[10]);
                            cs = cs % 11;
                            cs = cs % 10;
                            if (cs == c[11]) {
                                return c;
                            }
                        }
                    }
                },

                check: function (elem, signUp) {
                    var inpCheck = true;

                    $('#overlay__contain_registration_form .requared').each(function (i, elem) {
                        var _this = $(elem),
                            val = _this.val().trim();

                        if (_this.hasClass('username')) {
                            if (val == profileApp.reg.checkInn(val)) {
                                _this.removeClass('no_valid');
                            } else if (val == "") {
                                _this.addClass('no_valid').next().html('Обязательное поле');
                            } else {
                                _this.addClass('no_valid').next().html('Неправильный формат ИНН');
                            }
                        }
                        if (_this.hasClass('organization')) {
                            if (val == "") {
                                _this.addClass('no_valid').next().html('Обязательное поле');
                            } else {
                                _this.removeClass('no_valid');
                            }
                        }
                        if (_this.hasClass('email')) {
                            if (profileApp.reg.checkEmail(val)) {
                                _this.removeClass('no_valid');
                            } else if (val == "") {
                                _this.addClass('no_valid').next().html('Обязательное поле');
                            } else {
                                _this.addClass('no_valid').next().html('Неправильный формат почты');
                            }
                        }
                        if (_this.hasClass('no_valid')) {
                            inpCheck = false;
                        }
                    });

                    if (inpCheck && signUp) {
                        profileApp.reg.signUp();
                    } else {
                        return false;
                    }

                },

                onKeyup: function (_this) {
                    var dataForm = null;
                    var _this = $(_this);
                    profileApp.reg.check(_this, false);

                    if (_this.hasClass('username')) {
                        if (_this.hasClass('no_valid')) {
                            return false;
                        }
                        dataForm = $('#overlay__contain_registration_form').serialize();
                        $.ajax({
                            type: 'POST',
                            url: '/checkinn/',
                            dataType: 'JSON',
                            data: dataForm,
                            success: function (data) {
                                var form = $('#overlay__contain_registration_form');
                                if (data.state == 'error') {

                                    form.find('input, textarea').addClass('no_valid');
                                    form.find('.requared_text').html('');


                                    profileApp.message.onShow(data);
                                    return false;
                                } else if (data.state == 'success_inn' && typeof data.organization != 'undefined') {
                                    $('.organization').val(data.organization).removeClass('no_valid');
                                    $('.email').focus();

                                    return false;
                                } else if (data.state == 'success') {
                                    $('#overlay__contain_registration_form').trigger('reset');

                                } else if (data.state == 'error_inn_in_db') {
                                    $('.reg_information').css('display', 'block');
                                    form.attr('onlyEmail', true);
                                }


                                //profileApp.message.onShow(data);


                            }
                        })
                    }
                }

            }


        }

    accountActivation = {
        sending: function (_this) {
            var no_error = true;
            $('.organization').trigger('onkeyup');
            $('.email').trigger('onchange');
            $('#overlay__contain_registration_form .requared').each(function (i, elem) {
                var _this = $(elem),
                    val = _this.val();

                if (_this.hasClass('no_valid')) {
                    no_error = false;
                    if (_this.next().html() == '') {
                        _this.next().html('Обязательне поле');
                    }
                }

            });
            console.log(no_error);
            if (no_error) {
                profileApp.reg.signUp(_this)
            }
        },

        org: function (_this) {
            var value = $(_this).val();
            if (value.length > 0) {
                $(_this).removeClass('no_valid').next().html('');
            }
            else {
                $(_this).addClass('no_valid').next().html('Обязательне поле');
            }
        },

        email: function (_this) {
            var value = $(_this).val();
            if (this.checkEmail(value)) {
                $(_this).removeClass('no_valid').next().html('');
            }
            else {
                $(_this).addClass('no_valid').next().html('Неверный формат');
            }
        },

        innInputChange: function (_this) {
            var value = $(_this).val();
            if (value == this.checkInn(value)) {
                $(_this).removeClass('no_valid').next().html('');

                $.ajax({
                    type: 'POST',
                    url: '/loadUserData/',
                    dataType: 'JSON',
                    data: {inn: value},
                    success: function (data) {
                        if (data.state == 'error_user_active') {
                            $(_this).addClass('no_valid').next().html('Данный ИНН уже зарегистрирован');
                            $('#overlay__contain_registration_form').removeClass('onlyEmail');
                        }
                        if (data.state == 'error_user_not_in_base') {
                            $('.reg_information').css('display', 'block');
                            $('#overlay__contain_registration_form').addClass('onlyEmail');
                        }
                        if (data.state == 'success_data_load') {

                            $('#overlay__contain_registration_form').removeClass('onlyEmail');
                            $('.organization').val(data.org).trigger('onkeyup');
                            $('.email').val(data.email).trigger('onchange');
                            $('.address').val(data.address);
                            $('.city').val(data.city);
                            $('.phone').val(data.phone);
                        }
                    }
                });


            }
            else {
                $(_this).addClass('no_valid').next().html('Неверный формат ИНН');
            }
        },
        checkEmail: function (c) {
            return /^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,7}$/.test(c);
        },
        checkInn: function (c) {
            var cs = null;
            c = c + '';
            if (c.length == 10) {
                cs = (2 * c[0] + 4 * c[1] + 10 * c[2] + 3 * c[3] + 5 * c[4] + 9 * c[5] + 4 * c[6] + 6 * c[7] + 8 * c[8]);
                cs = cs % 11;
                cs = cs % 10;
                if (cs == c[9]) {
                    return c;
                }
            }
            else if (c.length == 12) {
                cs = (7 * c[0] + 2 * c[1] + 4 * c[2] + 10 * c[3] + 3 * c[4] + 5 * c[5] + 9 * c[6] + 4 * c[7] + 6 * c[8] + 8 * c[9]);
                cs = cs % 11;
                cs = cs % 10;
                if (cs == c[10]) {
                    cs = (3 * c[0] + 7 * c[1] + 2 * c[2] + 4 * c[3] + 10 * c[4] + 3 * c[5] + 5 * c[6] + 9 * c[7] + 4 * c[8] + 6 * c[9] + 8 * c[10]);
                    cs = cs % 11;
                    cs = cs % 10;
                    if (cs == c[11]) {
                        return c;
                    }
                }
            }
        }
    }


    order = {
        sum_check: function (isBtnClick) {

            var sum = parseInt($('.summ').attr('js_valid'));

            if (sum >= 1000) {


                return true;
            } else {


                if (isBtnClick) {
                    var btn = $('.minsum');
                    btn.css('display', 'inline-block');
                    if (btn.hasClass('left_right_center_animation')) {
                        btn.removeClass('left_right_center_animation');
                        btn.width();
                    }

                    btn.addClass('left_right_center_animation');

                }
                return false;
            }

        },
        make: function (obj) {

            if (this.sum_check() == false) {
                return false;
            }

            var comment = $('.inp_comment');
            var delivery = $('input[name=delivery]:checked');
            var delivery_address = $('textarea[name=delivery_address]');
            var time_to_pickup = $('textarea[name=timeToPickup]');


            var shake = false;
            if (delivery.val() == 1 && delivery_address.val() == '') {
                shake = delivery_address.parent().parent();
            }
            if (delivery.val() == 0 && time_to_pickup.val() == '') {
                shake = time_to_pickup.parent().parent();
            }

            if (shake) {
                shake.css('display', 'inline-block');
                if (shake.hasClass('left_right_center_animation')) {
                    shake.removeClass('left_right_center_animation');
                    shake.width();
                }

                shake.addClass('left_right_center_animation');
            }
            else {
                $.ajax({
                    type: 'post',
                    url: '/basket/make_order/',
                    async: false,
                    cache: false,
                    dataType: 'JSON',
                    data: {
                        comment: comment.val(),
                        delivery: delivery.val(),
                        delivery_address: delivery_address.val(),
                        time_to_pickup: time_to_pickup.val()
                    },
                    success: function (data) {
                        if (data.state == 'success') {

                            window.location.href = '/basket/order_success/' + data.id + '/';

                            // $('.er_header__cart').html('<nobr>Корзина пуста</nobr>');
                            // $('.refresh').html('<div class="er_rows fs_20">Спасибо! Ваш заказ принят в обработку. Номер заказа ' + data.id + '</div>');
                            // $('.overlay_box').hide();
                        }
                    }
                });
            }


        },
        fast_make: function (obj) {

            var tel = obj.siblings('.phone_inp');
            var comment = $('.inp_comment');
            var delivery = $('input[name=delivery]:checked');
            var delivery_address = $('textarea[name=delivery_address]');
            var time_to_pickup = $('textarea[name=timeToPickup]');

            if (tel.val().length != 17) {
                tel.addClass('no_valid');
            }
            else {

                var shake = false;
                if (delivery.val() == 1 && delivery_address.val() == '') {
                    shake = delivery_address.parent().parent();
                }
                if (delivery.val() == 0 && time_to_pickup.val() == '') {
                    shake = time_to_pickup.parent().parent();
                }

                if (shake) {
                    $('.overlay_box').hide();
                    shake.css('display', 'inline-block');
                    if (shake.hasClass('left_right_center_animation')) {
                        shake.removeClass('left_right_center_animation');
                        shake.width();
                    }

                    shake.addClass('left_right_center_animation');
                }
                else {
                    if (tel.hasClass('no_valid')) {
                        tel.removeClass('no_valid');
                    }

                    $.ajax({
                        type: 'post',
                        url: '/basket/fast_make_order/',
                        async: false,
                        cache: false,
                        dataType: 'JSON',
                        data: {
                            phone: tel.val(),
                            comment: comment.val(),
                            delivery: delivery.val(),
                            delivery_address: delivery_address.val(),
                            time_to_pickup: time_to_pickup.val()
                        },
                        success: function (data) {
                            if (data.state == 'success') {

                                window.location.href = '/basket/order_success/' + data.id + '/';

                                //   console.log(data.id);
                                //   $('.er_header__cart').html('<nobr>Корзина пуста</nobr>');
                                //   $('.refresh').html('<div class="er_rows fs_20">Спасибо! Ваш заказ принят в обработку.</div>');
                                //   $('.overlay_box').hide();
                            }
                        }
                    });
                }
            }

        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    basketSender = {
        key_press_memory: 0,
        onfocusCheck: function (_this) {
            this.key_press_memory = _this.val();
        },
        keyUpCheck: function (_this) {
            var value = $(_this).val();
            var min_p = $(_this).parent().parent().data('product-min');
            var count = $(_this).parent().parent().data('product-count');
            var plashka = $(_this).parent().parent();

            if (!(value % min_p == 0) || value == '') {
                plashka.addClass('errorInpCount');
            }
            else {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }
            }
        },
        pageSendButton: function (_this) {
            var inp = $('.counter__num input'),
                prod_id = $('.counter').data('product-id'),
                minusAndPlus = $('.counter').children('.counter__button'),
                btn = _this;

            if (!btn.hasClass('disabledBtn')) {
                if (inp.val() == 0) {
                    var shake = inp.parent().parent().parent();
                    if (shake.hasClass('left_right_center_animation')) {
                        shake.removeClass('left_right_center_animation');
                        shake.width();
                    }
                    shake.addClass('left_right_center_animation');
                }
                else {
                    $.ajax({
                        type: 'post',
                        url: '/basket/ajax_add_product/',
                        cache: false,
                        dataType: 'html',
                        data: {
                            prod_id: prod_id,
                            value: inp.val()
                        },
                        success: function (data) {

                            $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                            btn.addClass('disabledBtn');
                            btn.html('В корзине');
                            minusAndPlus.attr('action', 'true');
                            console.log('sad');
                        }
                    });
                }

            }
        },
        sendByButton: function (_this) {
            var inp = $(_this).parent().parent().children('td').children('ul').children('.counter__num').children('input'),
                prod_id = $(_this).parent().parent().children('td').children('ul').data('product-id'),
                card = $(_this).parent().parent().parent().parent().parent(),
                minusAndPlus = $(_this).parent().parent().children('td').children('ul').children('.counter__button'),
                btn = _this;

            if (!btn.hasClass('disabledBtn')) {
                /*if (inp.val() == 0) {
                  var shake = inp.parent().parent().parent();
                  if (shake.hasClass('left_right_center_animation'))
                  {
                    shake.removeClass('left_right_center_animation');
                    shake.width();
                  }
                  shake.addClass('left_right_center_animation');
                }*/
                //else {
                if (inp.val() == 0) {
                    inp.val(1);
                }
                $.ajax({
                    type: 'post',
                    url: '/basket/ajax_add_product/',
                    cache: false,
                    dataType: 'html',
                    data: {
                        prod_id: prod_id,
                        value: inp.val()
                    },
                    success: function (data) {

                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                        card.clone()
                            .css({'position': 'absolute', 'z-index': '100'})
                            .prependTo(card)
                            .animate({
                                opacity: 0.1,
                                right: '0px',
                                top: '0px',
                            }, 350, function () {
                                $(this).remove();
                            });

                        btn.addClass('disabledBtn');
                        btn.html('В корзине');
                        minusAndPlus.attr('action', 'true');
                        console.log('sad');
                    }
                });
                //}
            }

        },
        singleUpCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var prod_id = $(_this).parent().data('product-id');

            if (price != '' && min_p != '') {
                inp.val(parseInt(inp.val()) + parseInt(min_p));
                $.ajax({
                    type: 'post',
                    url: '/basket/ajax_up_or_down_count_product/',
                    cache: false,
                    dataType: 'html',
                    data: {
                        prod_id: prod_id,
                        operation: 'plus'
                    },
                    success: function (data) {

                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                    }
                });
            }
        },
        pageUpCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var action = $(_this).attr('action');
            var prod_id = $(_this).parent().data('product-id');
            if (price != '' && min_p != '') {
                inp.val(parseInt(inp.val()) + parseInt(min_p));
                if (action == 'true') {
                    $.ajax({
                        type: 'post',
                        url: '/basket/ajax_up_or_down_count_product/',
                        cache: false,
                        dataType: 'html',
                        data: {
                            prod_id: prod_id,
                            operation: 'plus'
                        },
                        success: function (data) {

                            $('.er_header__cart').html('<nobr>' + data + '</nobr>');
                        }
                    });
                }
            }
            else {
                // если не указана цена
            }


        },
        upCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var action = $(_this).attr('action');
            var prod_id = $(_this).parent().data('product-id');
            var card = $(_this).parent().parent().parent().parent().parent().parent();
            if (price != '' && min_p != '') {
                inp.val(parseInt(inp.val()) + parseInt(min_p));
                if (action == 'true') {
                    $.ajax({
                        type: 'post',
                        url: '/basket/ajax_up_or_down_count_product/',
                        cache: false,
                        dataType: 'html',
                        data: {
                            prod_id: prod_id,
                            operation: 'plus'
                        },
                        success: function (data) {

                            $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                            card.clone()
                                .css({'position': 'absolute', 'z-index': '100'})
                                .prependTo(card)
                                .animate({
                                    opacity: 0.1,
                                    right: '0px',
                                    top: '0px',
                                }, 350, function () {
                                    $(this).remove();
                                });

                            console.log('sad');
                        }
                    });
                }
            }
            else {
                // если не указана цена
            }
        },
        singleDownCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var prod_id = $(_this).parent().data('product-id');

            if (price != '' && min_p != '') {
                if (parseInt(inp.val()) != 0) {
                    inp.val(parseInt(inp.val()) - parseInt(min_p));
                    $.ajax({
                        type: 'post',
                        url: '/basket/ajax_up_or_down_count_product/',
                        cache: false,
                        dataType: 'html',
                        data: {
                            prod_id: prod_id,
                            operation: 'minus'
                        },
                        success: function (data) {

                            $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                        }
                    });
                }
            }

        },
        pageDownCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var action = $(_this).attr('action');
            var prod_id = $(_this).parent().data('product-id');
            var minusAndPlus = $('.counter').children('.counter__button');
            var btn = $('.er_goods_item_bleat__add_cart');

            if (price != '' && min_p != '') {
                if (parseInt(inp.val()) != 0) {
                    inp.val(parseInt(inp.val()) - parseInt(min_p));
                    if (action == 'true') {
                        $.ajax({
                            type: 'post',
                            url: '/basket/ajax_up_or_down_count_product/',
                            cache: false,
                            dataType: 'html',
                            data: {
                                prod_id: prod_id,
                                operation: 'minus'
                            },
                            success: function (data) {

                                $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                                console.log(inp.val());

                                if (parseInt(inp.val()) == 0) {
                                    minusAndPlus.attr('action', 'false');
                                    btn.removeClass('disabledBtn');
                                    btn.html('В корзину')
                                }


                            }
                        });
                    }
                }
            }
            else {
            }


        },
        downCount: function (_this) {
            var price = $(_this).parent().data('product-price');
            var inp = $(_this).parent().children('.counter__num').children('input');
            var min_p = $(_this).parent().data('product-min');
            var action = $(_this).attr('action');
            var prod_id = $(_this).parent().data('product-id');
            var minusAndPlus = $(_this).parent().children('.counter__button');
            var btn = $(_this).parent().parent().parent().children('td').children('.green_button');
            if (price != '' && min_p != '') {
                if (parseInt(inp.val()) != 0) {
                    inp.val(parseInt(inp.val()) - parseInt(min_p));
                    if (action == 'true') {
                        $.ajax({
                            type: 'post',
                            url: '/basket/ajax_up_or_down_count_product/',
                            cache: false,
                            dataType: 'html',
                            data: {
                                prod_id: prod_id,
                                operation: 'minus'
                            },
                            success: function (data) {

                                $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                                console.log(inp.val());

                                if (parseInt(inp.val()) == 0) {
                                    minusAndPlus.attr('action', 'false');
                                    btn.removeClass('disabledBtn');
                                    btn.html('В корзину')
                                }


                            }
                        });
                    }
                }
            }
            else {
            }
        },
        singleByInput: function (_this) {
            var prod_id = $(_this).parent().parent().data('product-id');
            var value = $(_this).val();
            var min_p = $(_this).parent().parent().data('product-min');
            var count = $(_this).parent().parent().data('product-count');
            var plashka = $(_this).parent().parent();

            if (value % min_p == 0 && value != '') {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }
                $.ajax({
                    type: 'post',
                    url: '/basket/ajax_set_count_product/',
                    cache: false,
                    dataType: 'html',
                    data: {
                        prod_id: prod_id,
                        value: value,
                        can_new: true,
                    },
                    success: function (data) {

                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                    }
                });
            }
            else {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }
                _this.val(this.key_press_memory);
            }
        },
        pageByInput: function (_this) {
            var prod_id = $('.counter').data('product-id');
            var value = $(_this).val();
            var min_p = $('.counter').data('product-min');
            var count = $('.counter').data('product-count');
            var plashka = $('.counter');
            var btn = $('.er_goods_item_bleat__add_cart');

            if (value % min_p == 0 && value != '') {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }

                $.ajax({
                    type: 'post',
                    url: '/basket/ajax_set_count_product/',
                    cache: false,
                    dataType: 'html',
                    data: {
                        prod_id: prod_id,
                        value: value
                    },
                    success: function (data) {

                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                        if (value == 0) {
                            $('.counter__button').attr('action', 'false');
                            btn.removeClass('disabledBtn');
                            btn.html('В корзину');
                        }

                        // console.log(inp.val());
                        //
                        // if (parseInt(inp.val()) == 0)
                        // {
                        //   minusAndPlus.attr('action', 'false');
                        //   btn.removeClass('disabledBtn');
                        // }


                    }
                });

            }
            else {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }
                _this.val(this.key_press_memory);
            }

        },
        byInput: function (_this) {
            var prod_id = $(_this).parent().parent().data('product-id');
            var value = $(_this).val();
            var min_p = $(_this).parent().parent().data('product-min');
            var count = $(_this).parent().parent().data('product-count');
            var plashka = $(_this).parent().parent();
            if (value % min_p == 0 && value != '') {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }

                $.ajax({
                    type: 'post',
                    url: '/basket/ajax_set_count_product/',
                    cache: false,
                    dataType: 'html',
                    data: {
                        prod_id: prod_id,
                        value: value
                    },
                    success: function (data) {

                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');

                        if (value == 0) {
                            plashka.children('.counter__button').attr('action', 'false');
                            plashka.parent().parent().children('td').children('.green_button').removeClass('disabledBtn');
                            plashka.parent().parent().children('td').children('.green_button').html('В корзину');
                        }

                        // console.log(inp.val());
                        //
                        // if (parseInt(inp.val()) == 0)
                        // {
                        //   minusAndPlus.attr('action', 'false');
                        //   btn.removeClass('disabledBtn');
                        // }


                    }
                });

            }
            else {
                if (plashka.hasClass('errorInpCount')) {
                    plashka.removeClass('errorInpCount');
                }
                _this.val(this.key_press_memory);
            }

        }
    }


    // // try {
    //   var _profile = '';
    //   if(typeof localStorage == 'undefined'){
    //     lStorage.intExplorer = true;
    //   }else{
    //     lStorage.intExplorer = false;
    //   }
    //
    //   if(lStorage.existence('cart')){
    //     lStorage.cart = lStorage.jsonParse(lStorage.get('cart'));
    //
    //   }else{
    //     lStorage.set('cart', lStorage.jsonStringify(lStorage.cart));
    //   }
    //
    //   if(lStorage.existence('prop')){
    //     lStorage.prop = lStorage.jsonParse(lStorage.get('prop'));
    //   }else{
    //
    //     lStorage.set('prop', lStorage.jsonStringify(lStorage.prop));
    //   }
    //
    //
    //   if(lStorage.existence('profile')){
    //     // if(lStorage.intExplorer){
    //     //   // for(var i = 0; i <= lStorage.get('profile'); i++){
    //     //   //   _profile += lStorage.get('profile_' + i);
    //     //   // }
    //     //   // profile = lStorage.jsonParse(_profile);
    //     // }else{
    //       profile = lStorage.jsonParse(lStorage.get('profile'));
    //     // }
    //   }else{
    //     if(lStorage.intExplorer){
    //       lStorage.updateSaveProfile(profile);
    //     }else{
    //       lStorage.set('profile', lStorage.jsonStringify(profile));
    //     }
    //   }
    //
    //
    // // }
    //
    // // catch(err) {
    // //   if(typeof localStorage == 'undefined'){
    // //     lStorage.intExplorer = true;
    // //   }else{
    // //     lStorage.intExplorer = false;
    // //     localStorage.clear();
    // //     window.location.reload();
    // //   }
    // // }
    //
    // // console.log($.cookie('cart'));
    // // console.log(lStorage.get('profile'));
    //
    //
    // iElectro.init();
    // onLoadFragment();
    //
    // setInterval(function(){
    //   onLoadFragment();
    // }, 100);
    //
    // setInterval(function(){
    //   $.get('http://localhost:88');
    // }, 4000);
    //
    // $('body').css('visibility', 'visible');
    //
    // $('.gooods_num_select').val(lStorage.prop.limVisGoods);
    //
    // websocket = {
    //   prot: null,
    //   ws: null,
    //   timer: null,
    //   online: false,
    //   creatingUrl: function(prot){
    //     this.ws = new WebSocket('ws://app.elektro-ufa.ru/ws/sync');
    //   },
    //
    //   init: function(){
    //     var _this = this;
    //     _this.prot = window.location.protocol;
    //     _this.creatingUrl(_this.prot);
    //     _this.ws.onopen = function(){
    //       clearTimeout(_this.timer);
    //       _this.online = true;
    //       $('div.status_bar__sync')
    //         .addClass('status_bar__item_active')
    //         .find('span').html('активна');
    //
    //       $('.requared_internet')
    //         .attr({
    //           'onclick': '',
    //           'title': ''
    //         })
    //         .removeClass('disabled');
    //
    //     };
    //     _this.ws.onclose = function(){
    //       _this.online = false;
    //
    //       $('div.status_bar__sync')
    //         .removeClass('status_bar__item_active')
    //         .find('span').html('не активна');
    //       $('.requared_internet')
    //         .attr({
    //           'onclick': 'return false;',
    //           'title': 'Данное действие невозможно, т.к. отсутствует соединение с интернетом'
    //         })
    //         .addClass('disabled');
    //
    //       _this.timer = setTimeout(function(){
    //         websocket.init();
    //       }, 1000);
    //     };
    //   }
    // };
    //
    // websocket.init();
    //
    // $(document).ajaxSuccess(function(a,b,c,data) {
    //   var posUrlStr = iElectro.posUrl().join('/'),
    //       overlayAuth = $('.overlay__contain_authorization'),
    //       overlayReg = $('.overlay__contain_registration'),
    //       overlayPass = $('.overlay__contain_password'),
    //       overlayRecPass = $('.overlay__contain_recovery_password'),
    //       x = [];
    //
    //       console.log(data);
    //     if(c.url.indexOf('localhost') == -1){
    //       lStorage.updateSaveProfile(typeof data.profile != 'undefined' ? data.profile : 'false');
    //       iElectro.auth.check();
    //       if(data.state == 'redirect'){
    //         iElectro.saveHistoryUrl();
    //         window.location.hash = data.hash;
    //         if(typeof data.text != 'undefined'){
    //           iElectro.message.init('notice', data.text);
    //         }
    //       }
    //
    //       if(posUrlStr == 'overlay/authorization'){
    //         // console.log(lStorage.get('profile'))
    //         if(data.state == 'error'){
    //           overlayAuth.find('.overlay__error_box').html(data.errorText);
    //           overlayAuth.find('input').addClass('no_valid');
    //           return false;
    //         }else{
    //           overlayAuth.find('input').each(function(i, inp){
    //             x[i] = $(inp).val();
    //           });
    //           lStorage.set('lp', x[0] + ':' + x[1]);
    //           lStorage.updateSaveProfile(typeof data.profile != 'undefined' ? data.profile : 'false');
    //           iElectro.auth.check();
    //           return false;
    //         }
    //       }
    //       if(posUrlStr == 'cart'){
    //         if(data.state != 'error' && data.state != 'redirect'){
    //           // iElectro.message.init('notice', data.text);
    //           $('.status_bar__cart_remove').trigger('click');
    //           $('.empty_cart .txt_message').html('<div style="display:inline-block;text-align:left;">' + data.text + '<i class="br10"></i><a href="#list" class="link fs_14"><&nbsp;На главную</a></div>');
    //           return false;
    //         }
    //
    //         if(data.state == 'error'){
    //
    //           $.each(data.json, function(key, count){
    //             var elem = $('.goods_cart_table tbody .counter[data-id="' + key +'"]');
    //
    //             elem.data('max', count);
    //             elem.parent().parent().find('.max_product').text(count);
    //             elem.find('.counter__num input').focus().keyup();
    //           })
    //
    //         }
    //
    //       }
    //       if(posUrlStr == 'settings'){
    //         if(data.state != 'error'){
    //           if(data.state == 'success'){
    //             iElectro.message.init('notice', data.text, function(){
    //               window.location.reload();
    //             });
    //           }
    //           return false;
    //         }else{
    //           return false;
    //         }
    //       }
    //       if(posUrlStr == 'overlay/registration'){
    //         if(data.state == 'error'){
    //           overlayReg.find('.overlay__error_box').html(data.errorText);
    //           overlayReg.find('input, textarea').addClass('no_valid');
    //           overlayReg.find('.requared_text').html('');
    //           return false;
    //         }else if(data.state == 'success_inn' && typeof data.organization != 'undefined'){
    //           $('.organization').val(data.organization).removeClass('no_valid');
    //           $('.email').focus();
    //           return false;
    //         }else if(data.state == 'success'){
    //           $('#overlay__contain_registration_form').trigger('reset');
    //           window.location.hash = 'list';
    //         }
    //       }
    //       if(posUrlStr == 'overlay/password'){
    //         if(data.state == 'error'){
    //           overlayPass.find('.overlay__error_box').html(data.errorText);
    //           overlayPass.find('input').addClass('no_valid');
    //           return false;
    //         }
    //       }
    //
    //       if(iElectro.posUrl()[0] == 'overlay' && iElectro.posUrl()[1] == 'recovery_password'){
    //         if(data.state == 'error'){
    //           overlayRecPass.find('.overlay__error_box').html(data.errorText);
    //           overlayRecPass.find('input').addClass('no_valid');
    //           return false;
    //         }else if(data.state == 'success'){
    //           window.location.hash = 'list';
    //         }
    //       }
    //
    //       if(data.state == 'success'){
    //         iElectro.message.init('notice', data.text);
    //       }
    //       if(data.state == 'error'){
    //         iElectro.message.init('error', data.errorText);
    //       }
    //
    //     }else{
    //       if(data.trim() == 'onReloadPage:OK'){
    //         window.location.reload();
    //       }
    //     }
    //
    //   });


});

var basket = {
    product_id: null,
    lang: 'ru',
    add: function (obj, much, update, preloader) {
        obj = $(obj);
        var basketPage = $('.basket_wrap').length > 0;
        var offers = {};
        if(much){
            var val = 0;
            $('.product_counter').each(function (i, counter) {
                val = $(counter).find('.product_counter_val').val();
                if(val != '' && val >= 0){
                    offers[$(counter).data('id')] = val;
                }
            });
        }else{
            offers[obj.data('offer_id')] = ($('.product_main_two_sel').length > 0 || $('.product_main_one').length > 0 ? $('.product_counter_val').val() : 1);
        }
        //console.log(Object.keys(offers).length);
        if(Object.keys(offers).length >= 0){


            //console.log(much);
            //console.log(obj);
            //console.log('2');
            if(update && typeof preloader == 'undefined'){
                $('.basket_refresh').append('<div class="preloader"></div>');
            }
            $.get('/basket/ajax/', {type: (update ? 'update' : 'add'), offers: offers, lang: basket.lang}, function (json) {

                //console.log('3');
                if(update && basketPage){
                    $('.basket_refresh').html(json.html);
                    if(json.info.offerCount > 0){
                        $('.basket_btn').addClass('basket_btn_full');
                        $('.basket_btn__product_count').text(json.info.offerCountText);
                        $('.basket_btn__price__val').text(json.info.priceText);

                        var delivery_info = $('.basket_total').data('delivery-info');
                        if (delivery_info == '0') {
                            $('.basket_delivery_info').html('Свяжитесь с нами, для уточнения стоимости доставки +7 (635) 644-75-75.<br/>Или уточните у оператора, после оформления заказа');
                        }else {
                            $('.basket_delivery_info').html('Доставка бесплатная');
                        }
                    }else{
                        $('.basket_btn').removeClass('basket_btn_full');
                    }
                }else if(json.state == 'success'){
                    if(json.info.offerCount > 0){
                        $('.basket_btn').addClass('basket_btn_full');
                        $('.basket_btn__product_count').text(json.info.offerCountText);
                        $('.basket_btn__price__val').text(json.info.priceText);
                    }else{
                        $('.basket_btn').removeClass('basket_btn_full');
                    }
                }else{

                }
            }, 'json');

            //console.log(.shift());
            var key = Object.keys(offers)[0];
            if (Object.keys(offers).length == 1 && offers[key] == 0 && basketPage)
            {
                //console.log('ya tyt');
                $('.cart_empty').show();
                $('.truecount').hide();
                $('.formsuccess').hide();
            }
            //console.log('4');
        }
    },
    cunterJobProductPage: function () {
        if (!isNaN(parseInt($('.product_price').html()))) {
            if ($('.counter__num input').val() < $('.counter__num input').data('stock')) {

                $('.counter__num input').val(
                    parseInt($('.counter__num input').val()) + parseInt($('.counter__num input').data('min-p'))
                );
            }
            else {
                var btn = $('.inner_view__control button');
                if (btn.hasClass('left_right_center_animation')) {
                    btn.removeClass('left_right_center_animation');
                    btn.width();
                }

                btn.addClass('left_right_center_animation');
            }
        }
    },

    handWrite: function (obj) {
        this.ajaxSend(obj, parseInt(obj.val()));
    },

    addCount: function (id, count) {
        $.ajax({
            type: 'post',
            url: '/basket/ajax/',
            async: false,
            cache: false,
            data: {product_id: id, operation: count},
            success: function (data) {
                $('.er_header__cart').html('<nobr>' + data + '</nobr>');
            }
        })
    },

    blockViewShowProdCount: function (_this) {
        var input = $(_this).parent().parent().children('td').children('ul').children('.counter__num').children('input');
        var card = $(_this).parent().parent().parent().parent().parent();
        if (!isNaN(parseInt(input.data('price'))) && input.val() < input.data('stock')) {
            var old_val = input.val();
            var new_val = parseInt(old_val) + parseInt(input.data('min-p'));
            input.val(new_val);


            card.clone()
                .css({'position': 'absolute', 'z-index': '100'})
                .prependTo(card)
                .animate({
                    opacity: 0.1,
                    right: '0px',
                    top: '0px',
                }, 350, function () {
                    $(this).remove();
                });

        }
        else {
            var btn = $(_this);
            if (btn.hasClass('left_right_center_animation')) {
                btn.removeClass('left_right_center_animation');
                btn.width();
            }

            btn.addClass('left_right_center_animation');
        }
    },
    delete: function (obj) {
        $(obj).closest('tr').find('.product_counter_val').val('0');
        basket.add(null, true, true);
    },
    clean: function () {
        $.get('/basket/ajax/', {type: 'clean'}, function () {
            window.location.reload();
        });
    },
    remove: function (obj) {

        this.ajaxSend(obj, 'down');
    },

    ajaxSend: function (obj, operation) {
        this.product_id = obj.parents('.counter').data('product-id');

        var min_p = parseInt(obj.siblings('.counter__num').children('input').data('min-p'));
        var stock = parseInt(obj.siblings('.counter__num').children('input').data('stock'));
        var price = parseInt(obj.siblings('.counter__num').children('input').data('price'));
        var val = parseInt(obj.siblings('.counter__num').children('input').val());

        if (operation == 'down' && val > stock) {
            obj.siblings('.counter__num').children('input').val(val - min_p);
        }
        else {
            $.ajax({
                type: 'post',
                url: '/basket/ajax/',
                async: false,
                cache: false,
                data: {product_id: this.product_id, operation: operation},
                success: function (data) {

                    if (!isNaN(parseInt(price))) {
                        $('.er_header__cart').html('<nobr>' + data + '</nobr>');
                        if (operation == 'up') {
                            var val = parseInt(obj.siblings('.counter__num').children('input').val()) + min_p;

                            obj.siblings('.counter__num').children('input').val(val);
                        }
                        if (operation == 'down') {
                            var val = obj.siblings('.counter__num').children('input').val() - min_p;
                            if (val < 0) {
                                val = 0
                            }
                            obj.siblings('.counter__num').children('input').val(val);
                        }

                        if (val > stock) {
                            obj.parent().css('box-shadow', '0px 0px 5px red');
                        } else {
                            obj.parent().css('box-shadow', 'none');
                        }
                    }

                }
            })
        }


    },

    check: function (obj) {
        var value = parseInt(obj.val());
        var parent = obj.parent().parent();
        var min_p = obj.parents('.counter__num').children('input').data('min-p');
        var stock = obj.parents('.counter__num').children('input').data('stock');
        if (value < 0 || isNaN(value) || value % min_p != 0 || value > stock) {
            parent.css('box-shadow', '0px 0px 5px red');
            $('.er_goods_item_bleat__add_cart').prop('disabled', true);

        } else {
            parent.css('box-shadow', 'none');
            $('.er_goods_item_bleat__add_cart').prop('disabled', false);
        }
    }

};

var counterLite = {
    offerImages: {},
    update: function (e) {
        var val = 0;
        var total = 0;
        var symbol = e.data('symbol');
        var count = e.closest('.product_counter').find('.product_counter_val');
        var value = parseInt(count.val());
        var price_value = $('.product_price_value');
        var basketPage = $('.basket_wrap').length > 0;

        if (value == '' || value <= 0 || isNaN(value)) {
            value = 0;
        }
        if (symbol !== false) {
            if (symbol == '+') {
                value += 1;
            } else if (symbol == '-') {
                if (value > 0 || (value >= 0 && basketPage)) {
                    value -= 1;
                }
            } else if (symbol == '-+') {
                if (value >= 0) {
                    value = value;
                }else
                {
                    value = 0;
                }
            }
            if(value == 0 && ($('.product_main_two_sel').length > 0 || $('.product_main_one').length > 0)){
                value = 1;
            }
            count.val(value);
            basket.add(null, true, true, 1);
            // if(basketPage){
            //     //console.log('qwe');
            //     basket.add(null, true, true, 1);
            //     return false;
            // }
        }
        if($('.product_main_two_sel').length > 0){
            $('.selectPriceOffer').each(function (i, offer) {
                if($(offer).is(':checked')){
                    if(value > 0){
                        total = (parseInt($(offer).data('price')) * value);
                    }
                    return false;
                }
            });
        }else{
            $('.product_counter').each(function (i, counter) {
                counter = $(counter);
                val = counter.find('.product_counter_val').val();
                if (val == '' || val <= 0 || isNaN(val)) {
                    val = 0;
                }
                if(val > 0){
                    total += (parseInt(counter.data('price')) * val);
                }
            });
        }

        var arr_price = (''+total).split('');
        if (arr_price.length > 3) {
            if (arr_price.length > 6) {
                arr_price.splice(arr_price.length-6, 0, ' ');
            }
            arr_price.splice(arr_price.length-3, 0, ' ');
            console.log(arr_price);
            total = arr_price.join('');


        }

        price_value.text(total == 0 ? '' : total);
        $('.product_main_much .product_price .rub').css('visibility', (total.length > 0 ? 'visible' : 'hidden'));
    },

    change: function (e) {
        var price_value = $('.product_price_value');
        var _this = this;
        if (e.closest('.product_price_trigger').length > 0) {
            var price = parseInt(e.data('price')) * $('.product_counter_val').val();
            price_value.data('price', price).text(price);
            $('.in_basket_btn').data('offer_id', e.data('offer_id'));
        } else if (e.closest('label').length > 0 && Object.keys(_this.offerImages).length > 0) {
            var offerId = e.closest('label').find('.product_counter').data('id');
            if(typeof _this.offerImages[offerId] != 'undefined'){
                fotorama.show({index: _this.offerImages[offerId]});
            }
        }
    }
};

var ftm = {
    adId: null,
    elem: null,
    rotateActive: false,
    openSize: '',
    rotate: function(btn){
        if(!ftm.rotateActive){
            ftm.rotateActive = true;
            btn.title = '';
            btn.className = 'ftm__rotate ftm__rotate_active';
            var src = null;
            var path = null;
            var pathS = null;
            var uplItem = null;
            if(ftm.elem){
                src = ftm.elem.activeFrame.img.replace(/\?u=.*/, '');
                path = $.trim(src).substr(5);
                pathS = path.replace('-' + ftm.openSize + '.', '-S.');
                path = $.trim(src.replace('-' + ftm.openSize + '.', '.').substr(5));

                if(path != ''){
                    $.post('/arm/rotate-image/', 'path=' + path, function(data){
                        if(data == 'ok'){
                            src = ftm.addParam(src);
                            ftm.elem.splice(ftm.elem.activeIndex, 1, {img: src});
                            if(ftm.adId){
                                $('.ftm_used_image_' + ftm.adId).each(function(_idx, _img){
                                    if(_img.src.indexOf(pathS) != -1){
                                        _img.src = ftm.addParam(_img.src);
                                        return false;
                                    }
                                });
                            }
                            uplItem = $('.uploader_preview__item');

                            if(uplItem.length > 0){
                                uplItem.each(function (_idx, _item) {
                                    var _itemImg = $(_item).find('img');
                                    if(_itemImg.length > 0 && _itemImg.attr('src').indexOf(pathS) != -1){
                                        _itemImg.attr('src', ftm.addParam(_itemImg.attr('src')));
                                        return false;
                                    }
                                });
                            }
                        }else{
                            alert('Ошибка. Обновите страницу.');
                        }
                        btn.className = 'ftm__rotate';
                        btn.title = 'Повернуть по часовой стрелке';
                        ftm.rotateActive = false;
                    });
                }else{
                    alert('Ошибка. Обновите страницу.');
                }
            }
        }
    },
    addParam: function(str){
        str = $.trim(str);
        if(str != ''){
            str = str.replace(/\?u=.*/, '');
            str += '?u=' + Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
            return str;
        }
        return '';
    },
    init: function (type, _this) {
        _this = $(_this);
        var src = null;
        var images = [];
        var p = _this.parent();

        if(ftm.onDrag == true){
            ftm.onDrag = false;
            return false;
        }
        if(type == 'item'){
            p = p.parent();
        }
        p = p.find('img');
        var idx = p.index(_this);
        p.each(function (_idx, _elem) {
            src = $(_elem).attr('src');
            src = src.replace(/S\.(jpg|jpeg|png)/g, ftm.openSize + '.$1');
            src = src.replace(/-.(jpg|jpeg|png)/g, '.$1');
            images.push({img: src});
        });
        $('.fotorama').html();
        $('.ftm_wrap').show();
        var $fotoramaDiv = $('.fotorama').fotorama({
            nav: "thumbs",
            width: "100%",
            thumbwidth: "70",
            thumbheight: "60",
            maxheight: "500",
            data: images
        });


        ftm.elem = $fotoramaDiv.data('fotorama');
        ftm.elem.load(images);

        ftm.adId = _this.data('ad_id');
        /*
         if(ftm.adId != _this.data('ad_id') || _this.data('ad_id') == undefined){
         ftm.elem.load(images);
         ftm.adId = _this.data('ad_id');
         }
         */

        ftm.elem.show({index: idx, time: 0});
    }
};

var slider = {
    initTimeout: false,
    move: function(obj){
        if($(obj).hasClass('slideshow__radio__btn_active')){
            return false;
        }
        var slideshow = ($(obj).hasClass('slideshow__radio__btn') ? $(obj).parent().parent().find('.slideshow') : $(obj).parent().find('.slideshow'));
        if(slideshow.length == 0){
            slideshow = $(obj).closest('.slideshow');
        }
        if(slideshow.length == 0){
            return false;
        }
        var slideshowItem = slideshow.find('.slideshow__item');
        var group = (typeof slideshow.data('group') != 'undefined' ? slideshow.data('group') : 1);
        var slide = (typeof slideshow.data('slide') != 'undefined' ? slideshow.data('slide') : 0);
        var slideshowItemLength = Math.ceil(slideshowItem.length / group) - 1;
        slideshow.addClass('slideshow_move');
        if($(obj).hasClass('slideshow__radio__btn')){
            slide = $(obj).index();
        }else{
            slide += parseInt(($(obj).hasClass('slideshow__left') ? '-' : '') + 1);
        }
        if(slide < 0){
            slide = slideshowItemLength;
        }
        if(slide > slideshowItemLength){
            slide = 0;
        }
        slideshow.parent().find('.slideshow__radio__btn').removeClass('slideshow__radio__btn_active');
        slideshow.parent().find('.slideshow__radio__btn').eq(slide).addClass('slideshow__radio__btn_active');
        slideshow.find('.slideshow__items').css('left', '-' + (slide * slideshow.width()) + 'px');
        slideshow.data('slide', slide);
        setTimeout(function () {
            slideshow.removeClass('slideshow_move');
        }, 500);
    },
    init: function (scroll) {
        var _this = this;
        clearTimeout(_this.initTimeout);
        _this.initTimeout = setTimeout(function () {
            var slideshowItems = null;
            var slideshowItem = null;
            var group = null;
            var radio = '';
            $('.slideshow:not(.mobile)').each(function (i, slideshow) {
                slideshow = $(slideshow);
                slideshowItem = slideshow.find('.slideshow__item');
                group = (typeof slideshow.data('group') != 'undefined' ? slideshow.data('group') : 1);
                slideshowItem.css('width', slideshow.width() / group);
                slideshowItems = slideshow.find('.slideshow__items');
                slideshowItems.css('left', 0);
                slideshow.css('height', slideshowItems.height());
                if(slideshow.data('radio')){
                    if(scroll){
                        slideshow.parent().find('.slideshow__radio__btn')
                            .removeClass('slideshow__radio__btn_active')
                            .eq(0).addClass('slideshow__radio__btn_active');
                    }else{
                        for(var j = 0; j < Math.ceil(slideshowItem.length / group); j++){
                            radio += '<div class="slideshow__radio__btn' + (j == 0 ? ' slideshow__radio__btn_active' : '') + '" onclick="slider.move(this);"></div>';
                        }
                        if(radio != ''){
                            radio = '<div class="slideshow__radio">' + radio + '</div>';
                            slideshow.after(radio);
                        }
                    }
                }
            });
            if(!scroll){
                $(window).resize(function () {
                    slider.init(true);
                });
            }
        }, (scroll ? 1000 : 0));
    }
};

var video = {
    open: function (obj) {
        var wndowWidth = $(window).width() - 120;
        var wndowHeight = $(window).height() - 120;
        var w = 640;
        var h = 360;
        if(wndowWidth >= 900 && wndowHeight >= 620){
            w = 900;
            h = 620;
        }
        $('body')
            .append('<div class="video_overlay" onclick="video.close();">'
                + '<div class="video_overlay__item"><iframe id="inframe_video_overlay__item" src="' + $(obj).data('src') + '" width="' + w + '" height="' + h + '" frameborder="0" allowfullscreen></iframe>'
                + '</div><div class="video_overlay__close"></div></div>')
            .addClass('scroll_hidden');

    },
    close: function () {
        var body = $('body');
        $('.video_overlay').remove();
        if(!body.hasClass('search_active')){
            body.removeClass('scroll_hidden');
        }
    },
    ready: function () {
    }
};

var search = {
    preloader: function(){
        var p = $('<div class="brsc_search_preloader"><span><i></i></span><span><i></i></span><span><i></i></span><span><i></i></span><span><i></i></span></div>');
        return p;
    },
    _show: function(){
        $('body').addClass('search_active scroll_hidden');
        $('.search_overlay__line__inp').focus();
    },
    close: function () {
        $('body').removeClass('search_active scroll_hidden');
    },

    clear: function(closeBtn){
        var searchDrop = $(closeBtn).closest('.brsc_search_drop');
        searchDrop.find('.brsc_search__inp').val('');
        searchDrop.find('.brsc_search_drop__qbox').empty();
        $('.brsc_search__inp_header').val('');
    },

    onKeyup: function(inp){
        var _this = this;
        var $inp = $(inp);
        if($.trim($inp.val()) == ''){
            $('.search_overlay__result').empty();
            if(_this.ajax != null){
                _this.ajax.abort();
            }
            return false;
        }
        if($inp.val() == $inp.data('old-q')){
            return false;
        }
        $inp.data('old-q', $inp.val());
        _this.send('.search_overlay__result', $inp.val());
    },

    send: function(box, q){
        var search = this;
        var box = (typeof box == 'object' ? box : $(box));
        var p = null;

        if(search.ajax != null){
            search.ajax.abort();
            clearTimeout(search.pTimer);
        }
        search.ajax = $.ajax({
            url: '/' + culture + '/search/?q=' + q,
            type: 'GET',
            dataType: 'html',
            beforeSend: function(){
                p = search.preloader();
                search.pTimer = setTimeout(function(){
                    box.html(p);
                }, 500);
            },
            success: function(html){
                clearTimeout(search.pTimer);
                box.html(html);
                // box.html($(html).find('.brsc_search_page_qbox').html());
                // brsc.search.highlightMatch({inp: $(html).find('.brsc_search_page_inp').find('input[name="q"]'), elems: $('.brsc_search__item__link, .brsc_search__item__text')});
            }
        })
    }};

var filter = {
    timeout: null,
    change: function(){
        var _this = this;
        if(_this.timeout != null){
            clearTimeout(_this.timeout);
        }
        _this.timeout = setTimeout(function(){
            _this.submit();
        },500);
    },
    submit: function(page){
        $('.catalog_refresh').append('<div class="preloader"></div>');
        $params = [];
        $('.catalog_filters input[type=checkbox]').each(function(i, inp){
            if(inp.checked){
                $params.push(inp.name + '=' + inp.value);
            }
        });
        var sliderProp = null;
        $('.catalog_filters__range').each(function (i, range) {
            sliderProp = $(range).find('.slider_prop');
            if($(range).find('.slider_power_inp_min').val() != sliderProp.data('min') || $(range).find('.slider_power_inp_max').val() != sliderProp.data('max')){
                $params.push($(range).find('.slider_power_inp_min').attr('name') + '=' + $(range).find('.slider_power_inp_min').val() + '&' + $(range).find('.slider_power_inp_max').attr('name') + '=' + $(range).find('.slider_power_inp_max').val());
            }
        });
        $.get(window.location.pathname, $params.join('&') + (page ? '&page=' + page : ''), function (html) {
            $('.catalog_refresh').html(html);
            $('.preloader').remove();
        });
    }
};

var imgUpload = {
    status: null,
    dirName: '/u/i/',
    closeBtn: '<span class="inp_file__item__close" title="Удалить" onclick="imgUpload.delItem(this);return false;"></span><span class="inp_file__item__rotate" title="Повернуть по часовой стрелке" onclick="imgUpload.rotate.fun(this);return false;"></span>',
    rotateActive: false,
    previewImg: function(href, size){
        var _this = this;
        if(href != '' && size != ''){
            if(href.indexOf('preloader.gif') != -1){
                return '<img width="30" height="30" src="/i/preloader.gif" />';
            }
            var types = ['jpeg', 'jpg', 'png', 'gif'];
            for(var i = 0; i < types.length; i++){
                href = href.replace('.' + types[i], '-' + size + '.' + types[i]);
            }
            return '<img src="' + href + '?u=' + Math.floor(Math.random() * (10000 - 1 + 1)) + 1 + '" />';
        }
    },
    disabledBtnUpload: function () {
        var _this = this;
        var btnUpload = $('.button_upload');
        var btnUploadInfo = $('.button_upload__info');
        if(_this.status){
            btnUpload.attr({'onclick': 'return false', 'title': 'Дождитесь окончания загрузки', 'style': 'cursor:default'});
            btnUploadInfo.text('Файл загружается...');
        }else{
            btnUpload.removeAttr('onclick title style');
            btnUploadInfo.text('Прикрепить файл');
        }
    },
    buildBothArray: function(inp, fs){
        var _this = this;
        var $inp = $(inp);
        var wrap = $inp.closest('.inp_file_wrap');
        var files = wrap.find('.inp_file__files .inp_file__item');
        var oldItemLeng = wrap.find('.a_layout_work__ct__inp_file').val().trim() != '' ? wrap.find('.a_layout_work__ct__inp_file').val().split(';').length : 0;
        var progress = wrap.find('.inp_file__progress');
        var errorMess = wrap.find('.error_list__mess');

        if(wrap.find('.a_layout_work__ct__inp_file').data('multiple') == undefined || wrap.find('.a_layout_work__ct__inp_file').data('multiple') == false){
            oldItemLeng = 0;
        }
        $.each(fs.files, function(i, file){
            var i = i + oldItemLeng;
            var $link = files.eq(i);
            if(file.status == 'success'){
                var href = _this.dirName + file.path;
                $link.replaceWith('<a href="' + href + '" target="_blank" class="inp_file__imgs__item inp_file__item">' + _this.closeBtn + _this.previewImg(href, 'S'));
                $link.attr('href', _this.dirName + file.path);
                if($link.hasClass('inp_file__imgs__item')){
                    $link.find('img').attr('src', _this.dirName + file.preview);
                }
                errorMess.text('');
            }else{
                $link.parent().remove();
                errorMess.text(file.status);
            }
        });
        _this.updateInp(inp);
        progress.removeClass('inp_file__progress_active');
    },
    updateInp: function(inp){
        var _this = this;
        var $inp = (typeof inp == 'object' ? inp : $(inp));
        var wrap = $inp.closest('.inp_file_wrap');
        var val = [];

        $.each(wrap.find('.inp_file__item'), function(i, elem){
            var elem = $(elem);
            var href = elem.attr('href');
            if(typeof href == 'undefined' || href == ''){
                return;
            }
            if(href.indexOf('preloader.gif') != -1){
                return;
            }
            href = elem.attr('href').replace(_this.dirName, '');
            href = href.replace(/\?u=.*/, '');
            var size = elem.data('size');
            var name = elem.data('name');
            val[i] = href;
        });
        wrap.find('.a_layout_work__ct__inp_file').val(val.join(';'));
        var btnUpload = $('.button_upload');
        if($('.inp_file__imgs__item_wrap').length >= 8){
            btnUpload.hide();
        }else{
            btnUpload.show();
        }
    },
    temp: function(o){
        var temp = '';
        temp += '<label class="button_upload" title="' + o.title + '"><span class="button_upload__info">Прикрепить файл</span>';
        temp += '<input type="file" accept="image/jpeg,image/png" name="' + o.name + '" data-url="' + o.url + '"' + (o.multiple == undefined || o.multiple == false ? '' : 'multiple') + ' />';
        temp += '<span class="inp_file__progress"></span>';
        temp += '</label>';
        temp += '<ul class="error_list"><li class="error_list__mess"></li></ul>';

        if(o.placement == 'before'){
            temp = '<div class="inp_file__files inp_file__files_before"></div>' + temp;
        }else if(o.placement == 'after'){
            temp = temp + '<div class="inp_file__files inp_file__files_after"></div>';
        }
        return temp;
    },
    delItem: function(thisLink){
        var _this = this;
        var wrap = $(thisLink).closest('.inp_file_wrap');
        var thisLink = $(thisLink).closest('.inp_file__item');

        thisLink.hasClass('inp_file__imgs__item') ? thisLink.parent().remove() : thisLink.remove();
        _this.updateInp(wrap.find('.a_layout_work__ct__inp_file'));

        var dCount = $('.inp_file__item__download').length;
        if(dCount == 0 && _this.status){
            $('.button_upload').find('input[type=file]').data('liteUploader').cancelUpload();
        }
    },
    typeTemp: function(o){
        var _this = this;
        var f = null;
        var wrap = $(o.inp).closest('.inp_file_wrap');
        var src = (o.file.base64 == undefined ? _this.dirName + o.file.src : o.file.base64);
        var type = null;
        var inpText = wrap.find('.a_layout_work__ct__inp_file');
        type = o.file.name.indexOf('.jp') != -1 || o.file.name.indexOf('.png') != -1 || o.file.name.indexOf('.gif') != -1 ? 'image' : 'all';

        if(type == 'image'/* && inpText.data('img-preview') != undefined*/){
            f = '<div class="inp_file__imgs__item_wrap">';
            if(src.indexOf('preloader.gif') != -1){
                f += '<span data-name="' + o.file.name + '" class="inp_file__imgs__item inp_file__item inp_file__item__download" data-size="' + o.file.size + '">' + (_this.status ? this.closeBtn.replace('inp_file__item__rotate', 'inp_file__item__rotate inp_file__item__rotate__hide') : this.closeBtn) + _this.previewImg(src, 'S') + '</span>';
            }else{
                f += '<a href="' + src + '" data-name="' + o.file.name + '" target="_blank" class="inp_file__imgs__item inp_file__item" data-size="' + o.file.size + '">' + _this.closeBtn + _this.previewImg(src, 'S') + '</a>';
            }
            f += '</div>';
        }else{
            f = '<a data-size="' + o.file.size + '" href="' + src + '" data-name="' + o.file.name + '" class="inp_file__files__item inp_file__item">' + _this.closeBtn + o.file.name + '<br/><i class="inp_file__files__item__size">' + Math.ceil(o.file.size / 1000) + '&nbsp;Kb</i></a>';
        }
        if(inpText.data('multiple') == undefined || inpText.data('multiple') == false){
            wrap.find('.inp_file__files').html(f);
        }else{
            wrap.find('.inp_file__files').append(f);
        }
        return f;
    },

    init: function(){
        var _this = this;
        var $inpWrap = null;
        var $inp = null;

        $('.a_layout_work__ct__inp_file').each(function(i, inp){
            var $inp = $(inp);
            var val = $inp.val().trim() != '' ? $inp.val().split(';') : undefined;
            $inp.attr('type', 'hidden');

            if(!$inp.parent().hasClass('inp_file_wrap')){
                $inp.wrap('<div class="inp_file_wrap" />');
            }else{
                var p = $inp.parent();
                p.find('.button_upload').remove();
                p.find('.error_list').remove();
                p.find('.inp_file__files').remove();
            }
            $inp.parent().append(_this.temp({
                name: $inp.data('name'),
                url: $inp.data('url'),
                title: $inp.data('title'),
                multiple: $inp.data('multiple'),
                placement: ($inp.data('placement') == undefined ? 'before' : $inp.data('placement'))
            }));

            var img_length = 0;
            if(val != undefined){
                $('.a_layout_work__ct__inp_file').val(val[0]);
                $('.button_upload__info').text('Файл загружен');
                $.each(val, function(i, val){
                    var prop = '';
                    var nameSplit = val.split('/');
                    var name = nameSplit[nameSplit.length - 1];
                    var size = '';
                    var src = val;
                    _this.typeTemp({
                        file: {src: src, name: name, size: size},
                        inp: inp
                    });
                    img_length++;
                });
            }
            if(img_length >= 8){
                $('.button_upload').hide();
            }
        });

        $inpWrap = $('.inp_file_wrap');
        $inp = $inpWrap.find('input[type="file"]');
        $inp.liteUploader({
            script: $inp.data('url')
        })
            .on('lu:error', function (e, response){
                var response = JSON.parse(response);
                _this.status = null;
                _this.disabledBtnUpload();
            })
            .on('lu:before', function (ev, files){
                _this.status = 'before';
                _this.disabledBtnUpload();
                var $inp = $(this);
                $.each(files, function(i, file) {
                    var reader = new FileReader();
                    reader.onload = function(e){
                        var f = null;
                        // file.base64 = e.target.result;
                        file.src = 'preloader.gif';
                        f = _this.typeTemp({
                            file: file,
                            inp: ev.target
                        });

                        return;
                    };
                    reader.readAsDataURL(file);
                });
            })
            .on('lu:progress', function (e, state){
                _this.status = 'progress';
                var wrap = $(this).closest('.inp_file_wrap');
                var progress = wrap.find('.inp_file__progress');
                progress.addClass('inp_file__progress_active');
                progress.css('width', state + '%');
            })
            .on('lu:success', function (e, response){
                _this.status = null;
                _this.disabledBtnUpload();
                var response = JSON.parse(response);
                var inp = $(e.target);
                $('.button_upload__info').text('Файл загружен');
                if(response.state == 'success'){
                    $('.a_layout_work__ct__inp_file').val(response.filename);
                }else{
                    return false;
                }
            })
            .on("lu:cancelled", function () {
                _this.status = null;
                _this.disabledBtnUpload();
                _this.init();
            });
    }
};

var callback = {
    submit: function(form){
        form = $(form);
        $.post(form.attr('action'), form.serialize(), function (html) {
            form.parent().html(html);
        });
    },
    open:function (_this) {
        if (_this)
        {
            $('#callback_offer').show();
            $('#callback').hide();
            offer_id = $(_this).attr('data-offer-id');
            $('#callback_offer_id').val(offer_id);
        }else
        {
            $('#callback').show();
            $('#callback_offer').hide();
            $('#callback_offer_id').val('');
        }
        var callbackForm = $('.callback_form');
        callbackForm.removeClass('callback_form_done');
        $('.overlay_callback').addClass('overlay_callback_active');
        $('body').addClass('scroll_hidden');
        callbackForm.find('input[type="text"]').eq(0).focus();
    },
    close: function(){
        $('.overlay_callback').removeClass('overlay_callback_active');
        $('body').removeClass('scroll_hidden');
    }
};

var form_validator = {


    disabler: function (_this) {

        var form = $(_this).parents('form');
        var needValidToOpen = $(form).find('.validate_it').length;
        var validField = $(form).find('.valid').length;

        console.log('need', needValidToOpen, ' valid', validField);

        if (needValidToOpen == validField)
        {
            $(form).find('input[type="submit"]').removeAttr('disabled');
            $(form).find('input[type="submit"]').removeClass('btn_disabled');
        }
        else
        {
            $(form).find('input[type="submit"]').attr('disabled', 'disabled');
            $(form).find('input[type="submit"]').addClass('btn_disabled');
        }


    },

    check: function (_this) {
        var rules = $(_this).attr('data-check-rule').split(',');

        $(rules).each(function (i, rule) {

            console.log('rule:', rule);
            if (rule == 'email')
            {
                form_validator._email($(_this));
            }
            if (rule == 'noempty')
            {
                form_validator._noempty($(_this));
            }
            if (rule == 'checked')
            {
                form_validator._checked($(_this));
            }
            if (rule == 'phone')
            {
                form_validator._phone($(_this));
            }



        });

        form_validator.disabler(_this);

    },

    _checked: function (_this) {
        if($(_this).prop('checked'))
        {
            $(_this).removeClass('not-valid');
            $(_this).addClass('valid');
        }
        else
        {
            $(_this).removeClass('valid');
            $(_this).addClass('not-valid');
        }
    },

    _noempty: function (_this) {
        if($(_this).val().trim() != '')
        {
            $(_this).removeClass('not-valid');
            $(_this).addClass('valid');
            //$(_this).val($(_this).val().trim());
        }
        else
        {
            $(_this).addClass('not-valid');
            $(_this).removeClass('valid');
        }
    },

    _email: function (_this) {
        if(/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/.test($(_this).val()))
        {
            $(_this).removeClass('not-valid');
            $(_this).addClass('valid');
        }
        else
        {
            $(_this).addClass('not-valid');
            $(_this).removeClass('valid');
        }
    },

    _phone: function (_this) {
        if(/^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){11,14}(\s*)?$/.test($(_this).val()))
        {
            $(_this).removeClass('not-valid');
            $(_this).addClass('valid');
        }
        else
        {
            $(_this).addClass('not-valid');
            $(_this).removeClass('valid');
        }
    }

};
function setUrlHash(hash) {
    if ('replaceState' in window.history && window.location.hash !== hash) window.history.replaceState('', '', hash);
}
$(document).ready(function () {
    //slider.init();
    if ($('.phone_mask').length > 0) {
        $('.phone_mask').mask("+7 (999) 999-9999");
    }
});
