/*
    jQuery Masked Input Plugin
    Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
    Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
    Version: 1.4.1
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){var b,c=navigator.userAgent,d=/iphone/i.test(c),e=/chrome/i.test(c),f=/android/i.test(c);a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},a.fn.extend({caret:function(a,b){var c;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof a?(b="number"==typeof b?b:a,this.each(function(){this.setSelectionRange?this.setSelectionRange(a,b):this.createTextRange&&(c=this.createTextRange(),c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select())})):(this[0].setSelectionRange?(a=this[0].selectionStart,b=this[0].selectionEnd):document.selection&&document.selection.createRange&&(c=document.selection.createRange(),a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length),{begin:a,end:b})},unmask:function(){return this.trigger("unmask")},mask:function(c,g){var h,i,j,k,l,m,n,o;if(!c&&this.length>0){h=a(this[0]);var p=h.data(a.mask.dataName);return p?p():void 0}return g=a.extend({autoclear:a.mask.autoclear,placeholder:a.mask.placeholder,completed:null},g),i=a.mask.definitions,j=[],k=n=c.length,l=null,a.each(c.split(""),function(a,b){"?"==b?(n--,k=a):i[b]?(j.push(new RegExp(i[b])),null===l&&(l=j.length-1),k>a&&(m=j.length-1)):j.push(null)}),this.trigger("unmask").each(function(){function h(){if(g.completed){for(var a=l;m>=a;a++)if(j[a]&&C[a]===p(a))return;g.completed.call(B)}}function p(a){return g.placeholder.charAt(a<g.placeholder.length?a:0)}function q(a){for(;++a<n&&!j[a];);return a}function r(a){for(;--a>=0&&!j[a];);return a}function s(a,b){var c,d;if(!(0>a)){for(c=a,d=q(b);n>c;c++)if(j[c]){if(!(n>d&&j[c].test(C[d])))break;C[c]=C[d],C[d]=p(d),d=q(d)}z(),B.caret(Math.max(l,a))}}function t(a){var b,c,d,e;for(b=a,c=p(a);n>b;b++)if(j[b]){if(d=q(b),e=C[b],C[b]=c,!(n>d&&j[d].test(e)))break;c=e}}function u(){var a=B.val(),b=B.caret();if(o&&o.length&&o.length>a.length){for(A(!0);b.begin>0&&!j[b.begin-1];)b.begin--;if(0===b.begin)for(;b.begin<l&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}else{for(A(!0);b.begin<n&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}h()}function v(){A(),B.val()!=E&&B.change()}function w(a){if(!B.prop("readonly")){var b,c,e,f=a.which||a.keyCode;o=B.val(),8===f||46===f||d&&127===f?(b=B.caret(),c=b.begin,e=b.end,e-c===0&&(c=46!==f?r(c):e=q(c-1),e=46===f?q(e):e),y(c,e),s(c,e-1),a.preventDefault()):13===f?v.call(this,a):27===f&&(B.val(E),B.caret(0,A()),a.preventDefault())}}function x(b){if(!B.prop("readonly")){var c,d,e,g=b.which||b.keyCode,i=B.caret();if(!(b.ctrlKey||b.altKey||b.metaKey||32>g)&&g&&13!==g){if(i.end-i.begin!==0&&(y(i.begin,i.end),s(i.begin,i.end-1)),c=q(i.begin-1),n>c&&(d=String.fromCharCode(g),j[c].test(d))){if(t(c),C[c]=d,z(),e=q(c),f){var k=function(){a.proxy(a.fn.caret,B,e)()};setTimeout(k,0)}else B.caret(e);i.begin<=m&&h()}b.preventDefault()}}}function y(a,b){var c;for(c=a;b>c&&n>c;c++)j[c]&&(C[c]=p(c))}function z(){B.val(C.join(""))}function A(a){var b,c,d,e=B.val(),f=-1;for(b=0,d=0;n>b;b++)if(j[b]){for(C[b]=p(b);d++<e.length;)if(c=e.charAt(d-1),j[b].test(c)){C[b]=c,f=b;break}if(d>e.length){y(b+1,n);break}}else C[b]===e.charAt(d)&&d++,k>b&&(f=b);return a?z():k>f+1?g.autoclear||C.join("")===D?(B.val()&&B.val(""),y(0,n)):z():(z(),B.val(B.val().substring(0,f+1))),k?b:l}var B=a(this),C=a.map(c.split(""),function(a,b){return"?"!=a?i[a]?p(b):a:void 0}),D=C.join(""),E=B.val();B.data(a.mask.dataName,function(){return a.map(C,function(a,b){return j[b]&&a!=p(b)?a:null}).join("")}),B.one("unmask",function(){B.off(".mask").removeData(a.mask.dataName)}).on("focus.mask",function(){if(!B.prop("readonly")){clearTimeout(b);var a;E=B.val(),a=A(),b=setTimeout(function(){B.get(0)===document.activeElement&&(z(),a==c.replace("?","").length?B.caret(0,a):B.caret(a))},10)}}).on("blur.mask",v).on("keydown.mask",w).on("keypress.mask",x).on("input.mask paste.mask",function(){B.prop("readonly")||setTimeout(function(){var a=A(!0);B.caret(a),h()},0)}),e&&f&&B.off("input.mask").on("input.mask",u),A()})}})});


var popup = {

    onClose: null,

    open: function(selector, params) {
        var _this = this;

        popup.hideAll();

        $('.popup').find('.popup_item.'+ selector).addClass('active');
        $('.popup').addClass('show');
        $('body').addClass('popup_open');

        $('.popup_item__form_msg').text('');
    },

    close: function(e) {
        var _this = this;
        var $target = $(e.target);

        if($('.popup_item.active').hasClass('place_order')){
            window.location.href = "/";
        }

        if($target.hasClass("popup_close") || !$target.hasClass("popup_close") && !$target.closest('.popup_open').find('.login').hasClass("active")){
            $('.popup').removeClass('show');
            $('body').removeClass('popup_open');
            $('.service_form__success').remove();
            if(_this.onClose != null){
                _this.onClose();
                _this.onClose = null;
            }
        }
    },

    hideAll: function() {
        $('.popup').find('.popup_item.active').removeClass('active');
    },

    btnEditProfile: function(e) {
        var $target = $(e.target);
        var name = $target.closest('.popup_item__row').find('#profile_name').val();
        var phone = $target.closest('.popup_item__row').find('#profile_phone').val();
        var email = $target.closest('.popup_item__row').find('#profile_email').val();
        var address = $target.closest('.popup_item__row').find('#profile_address').val();
        var psw = $target.closest('.popup_item__row').find('#profile_password').val();
        var ph = $target.closest('.popup_item__row').find('#profile_phone').val().replace(/[^0-9]/gi, '');


        $('.popup_item__form_msg').text('');

        if(name == '' || name == null){
            $('.popup_item__form_msg').text('Укажите имя');
            return false;
        }

        if(phone == '' || phone == null){
            $('.popup_item__form_msg').text('Укажите номер телефона');
            return false;
        }

        if(ph.length != 11){
            $('.popup_item__form_msg').text('Номер телефона неверен');
            return false;
        }

        $.ajax({
            url: '/user/edit-profile/',
            method: 'post',
            dataType: 'json',
            data:  { name: name, phone:phone, email:email, address:address, psw:psw },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });

    },
    btnSignup: function(e) {
        var $target = $(e.target);
        var name = $target.closest('.popup_item__row').find('#signup_name').val();
        var phone = $target.closest('.popup_item__row').find('#signup_phone').val();
        var email = $target.closest('.popup_item__row').find('#signup_email').val();
        var address = $target.closest('.popup_item__row').find('#signup_address').val();
        var psw = $target.closest('.popup_item__row').find('#signup_password').val();
        var ph = $target.closest('.popup_item__row').find('#signup_phone').val().replace(/[^0-9]/gi, '');
        var cat_id = $('#cats option:selected').val();
        var weight = $('#weight').val().replace(/\D/, '');
        
        weight = Number.parseFloat(weight);

        $('.popup_item__form_msg').text('');

        if(name == '' || name == null){
            $('.popup_item__form_msg').text('Укажите имя');
            return false;
        }

        if(phone == '' || phone == null){
            $('.popup_item__form_msg').text('Укажите номер телефона');
            return false;
        }

        if(ph.length != 11){
            $('.popup_item__form_msg').text('Номер телефона неверен');
            return false;
        }

        if(email == '' || email == null){
            $('.popup_item__form_msg').text('Укажите электронную почту');
            return false;
        }

        if(address == '' || address == null){
            $('.popup_item__form_msg').text('Укажите адрес');
            return false;
        }

        $.ajax({
            url: '/user/signup/',
            method: 'post',
            dataType: 'json',
            data:  { name: name, phone:phone, email:email, address:address, psw:psw, cat_id:cat_id, weight:weight },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });
    },

    btnSignin: function(e) {
        var $target = $(e.target);
        var psw = $target.closest('.popup_item__row').find('#signin_password').val();
        var phone = $target.closest('.popup_item__row').find('#signin_phone').val().replace(/[^0-9]/gi, '');
        var cat_id = $('#cats option:selected').val();
        var weight = $('#weight').val().replace(/\D/, '');
        var _csrf_token = $('#signin__csrf_token').val();

        $('.popup_item__form_msg').text('');

        if(phone == '' || phone == null){
            $('.popup_item__form_msg').text('Укажите номер телефона');
            return false;
        }

        if(phone.length != 11){
            $('.popup_item__form_msg').text('Номер телефона неверен');
            return false;
        }

        if(psw == '' || psw == null){
            $('.popup_item__form_msg').text('Введите пароль');
            return false;
        }

        $.ajax({
            url: '/user/signin/',
            method: 'post',
            dataType: 'json',
            data:  { phone:phone, psw:psw, _csrf_token:_csrf_token, cat_id:cat_id, weight:weight, is_json:true },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });
    },

    btnRemBid: function(e) {
        var $target = $(e.target);
        var id = $target.closest('.remove_bid_form').data('id');

        $('.popup_item__form_msg').text('');

        $.ajax({
            url: '/user/remove-bid/',
            method: 'post',
            dataType: 'json',
            data:  { id:id },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });
    },

    btnRecoveryPsw: function(e) {
        var $target = $(e.target);
        var email = $target.closest('.popup_item__row').find('#recovery_email').val();
        var _this = $target.closest('.popup_item');

        $('.popup_item__form_msg').text('');

        if(email == '' || email == null){
            $('.popup_item__form_msg').text('Укажите электронную почту');
            return false;
        }

        $.ajax({
            url: '/user/recovery-form/',
            method: 'post',
            dataType: 'json',
            data:  { email:email },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    popup.reverseEvent(_this);
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });
    },

    btnRemindPsw: function(e) {
        var $target = $(e.target);
        var psw = $target.closest('.popup_item__row').find('#change_psw_password').val();
        var id = $target.closest('.popup_item__row').find('#change_psw_id').val();
        var secret = $target.closest('.popup_item__row').find('#change_psw_secret').val();
        var _this = $target.closest('.popup_item');

        $('.popup_item__form_msg').text('');

        if(psw == '' || psw == null){
            $('.popup_item__form_msg').text('Укажите пароль');
            return false;
        }

        $.ajax({
            url: '/user/change-psw-form/',
            method: 'post',
            dataType: 'json',
            data:  { psw:psw, id:id, secret:secret },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    popup.reverseEvent(_this);
                } else {
                    $('.popup_item__form_msg').text(data.msg);
                }
            }
        });
    },

    reverseEvent: function(_this) {
        if(!_this.find('.popup_item__title').hasClass('hidden_bl')){
            _this.find('.popup_item__title').addClass('hidden_bl');
        }
        if(!_this.find('.popup_item__form').hasClass('hidden_bl')){
            _this.find('.popup_item__form').addClass('hidden_bl');
        }
        if(!_this.find('.successfully_msg').hasClass('show')){
            _this.find('.successfully_msg').addClass('show');
        }
    },

};

$(document).ready(function(){
    $('.phone').mask('+7 (999) 999-99-99');
    
    function minWeightСheck () {
        var cat_id = $('#cats option:selected').val();
        var min_weight = $('#cats option:selected').data('min_weight');
        var weight = $('#weight').val().replace(/\D/, '');
        var price = $('#cats option:selected').data('price');
        var is_min = false;
        var temp_text = $('.wait_weight_msg').data('temp');
        //var remains = 0;

        min_weight = Number.parseFloat(min_weight);
        weight = Number.parseFloat(weight);
        price = Number.parseFloat(price);

        if(weight >= min_weight){
            is_min = true;
        }

        //remains = min_weight - weight;
        //$('.cats_item__sum_value').text(price * weight);

        if(weight > 0){
            if(is_min === false){
                // if(!$('.cats_item__sum').hasClass('show')){
                //     $('.cats_item__sum').addClass('show');
                // }

                // if(remains > 0){
                //     $('.cats_item__remains_value').text(remains);
                //
                //     if(!$('.cats_item__remains').hasClass('show')){
                //         $('.cats_item__remains').addClass('show');
                //     }
                // }

                if(!$('.cats_item__wait_weight').hasClass('show')){
                    $('.cats_item__wait_weight').addClass('show');
                }

                if(temp_text != '' && temp_text != null){
                    temp_text = temp_text.replace('#weight#', min_weight).replace('#sum#', price * min_weight);
                    $('.wait_weight_msg').text(temp_text);
                } else {
                    $('.wait_weight_msg').text('Если вы накопите ' + min_weight + ' кг вторсырья, мы вывезем его у вас из дома и заплатим ' + (price * min_weight) + ' ₽');
                }

                if(!$('.wait_weight_msg').hasClass('show')){
                    $('.wait_weight_msg').addClass('show');
                }

                $('.btn_add_bid').text('Буду копить');

                //$('.cats_item__wait_weight a.btn_signup').attr('href', window.location.protocol + '//' + window.location.hostname + "/user/signup/?cat_id=" + cat_id + "&weight=" + weight);

            } else {
                if($('.cats_item__remains').hasClass('show')){
                    $('.cats_item__remains').removeClass('show');
                }

                $('.wait_weight_msg').text('');

                if($('.wait_weight_msg').hasClass('show')){
                    $('.wait_weight_msg').removeClass('show');
                }

                if($("div").is(".profile") != true){
                    // if($('.cats_item__wait_weight').hasClass('show')){
                    //     $('.cats_item__wait_weight').removeClass('show');
                    // }

                    if(!$('.cats_item__wait_weight').hasClass('show')){
                        $('.cats_item__wait_weight').addClass('show');
                    }
                    $('.btn_add_bid').text('Буду копить');

                    // if($('.cats_item__sum').hasClass('show')){
                    //     $('.cats_item__sum').removeClass('show');
                    // }

                    popup.open('signup_form');

                    //window.location = window.location.protocol + '//' + window.location.hostname + "/user/signup/?cat_id=" + cat_id + "&weight=" + weight;
                } else {
                    // if(!$('.cats_item__sum').hasClass('show')){
                    //     $('.cats_item__sum').addClass('show');
                    // }

                    if(!$('.cats_item__wait_weight').hasClass('show')){
                        $('.cats_item__wait_weight').addClass('show');
                    }
                    $('.btn_add_bid').text('Добавить заявку');
                }

            }
        }

    };

    $('body').on('click', '.btn_cancel', function () {
        if($('.cats_item__wait_weight').hasClass('show')){
            $('.cats_item__wait_weight').removeClass('show');
        }
        $('.weight_inp').val('');
    });

    $('body').on('click', '.btn_edit_profile', function () {
        var name = $(this).closest('.popup_item__row').find('#profile_name').val();
        var phone = $(this).closest('.popup_item__row').find('#profile_phone').val();
        var email = $(this).closest('.popup_item__row').find('#profile_email').val();
        var address = $(this).closest('.popup_item__row').find('#profile_address').val();
        var psw = $(this).closest('.popup_item__row').find('#profile_password').val();
        var ph = $(this).closest('.popup_item__row').find('#profile_phone').val().replace(/[^0-9]/gi, '');

        $('.popup_item__form_msg').text('');

        if(name == '' || name == null){
            $('.popup_item__form_msg').text('Укажите имя');
            return false;
        }

        if(phone == '' || phone == null){
            $('.popup_item__form_msg').text('Укажите номер телефона');
            return false;
        }

        if(ph.length != 11){
            $('.popup_item__form_msg').text('Номер телефона неверен');
            return false;
        }

        $.ajax({
            url: '/user/edit-profile/',
            method: 'post',
            dataType: 'json',
            data:  { name: name, phone:phone, email:email, address:address, psw:psw },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {

                }
            }
        });

    });

    $('body').on('keyup', '#weight', function () {
        var cat_id = $('#cats option:selected').val();
        var weight = $(this).val();

        minWeightСheck();

    });

    $('body').on('change', '#cats', function () {
        minWeightСheck();
    });

    $('body').on('keyup', '.signup_form__field input', function () {
        $('.signup_form__msg').text('');
    });

    $('body').on('click', '.btn_add_bid', function () {
        var cat_id = $(this).closest('.new_bid_export__cats').find('#cats option:selected').val();
        var weight = $(this).closest('.new_bid_export__cats').find('.weight_inp').val().replace(/[^0-9]/gi, '');

        sendBid(cat_id, weight, null);
    });

    $('body').on('click', '.btn_weight_collect', function () {
        var cat_id = $(this).closest('tr').data('cat_id');
        var weight = $(this).closest('tr').find('.tb_weight_inp').val().replace(/[^0-9]/gi, '');
        var bid_id = $(this).closest('tr').data('id');

        sendBid(cat_id, weight, bid_id);
    });

    function sendBid (cat_id, weight, bid_id = null) {
        weight = Number.parseFloat(weight);

        if(weight > 0 && typeof cat_id != "undefined" && cat_id != null && cat_id != ''){
            $.ajax({
                url: '/user/add-bid/',
                method: 'post',
                dataType: 'json',
                data:  { cat_id: cat_id, weight:weight, bid_id:bid_id },
                success: function(data){
                    if(data.state != undefined && data.state == 'ok'){
                        window.location = window.location.protocol + '//' + window.location.hostname + "/";
                    } else {

                    }
                }
            });
        }
    };

    $('body').on('change', '.tb_weight_inp', function () {
        var weight = $(this).val();
        var min_weight = $(this).closest('tr').data('min_weight');
        var price = $(this).closest('tr').data('price');
        var sum = 0;
        var remains = 0;
        var balance = 0;

        min_weight = Number.parseFloat(min_weight);
        weight = Number.parseFloat(weight);
        price = Number.parseFloat(price);

        if(Number.isNaN(weight) != true){
            sum = price * weight;
            $(this).closest('tr').find('.price_td').text(sum);

            remains = min_weight - weight;
            if(remains <= 0){
                remains = 0;
            }
            $(this).closest('tr').find('.remains_td').text(remains);

            if(weight >= min_weight){
                if($(this).closest('tr').find('.btn_weight_collect').hasClass('disabled')){
                    $(this).closest('tr').find('.btn_weight_collect').removeClass('disabled');
                    $(this).closest('tr').find('.btn_weight_collect').prop("disabled", false);
                }
            } else {
                if(!$(this).closest('tr').find('.btn_weight_collect').hasClass('disabled')){
                    $(this).closest('tr').find('.btn_weight_collect').addClass('disabled');
                    $(this).closest('tr').find('.btn_weight_collect').prop("disabled", true);
                }
            }
        }

        var sum_tmp = 0;
        $(".price_td").each(function (ix, el){
            sum_tmp = Number.parseFloat($(el).text());
            balance = balance + sum_tmp;
        });

        $('.balance_content_r').text(balance + ' ₽');

    });
    
    $('body').on('click', '.btn_signup_form', function () {
        var name = $(this).closest('.signup_form').find('#signup_name').val();
        var phone = $(this).closest('.signup_form').find('#signup_username').val();
        var psw = $(this).closest('.signup_form').find('#signup_password').val();
        var psw_r = $(this).closest('.signup_form').find('#signup_password_repeat').val();
        var ph = $(this).closest('.signup_form').find('#signup_username').val().replace(/[^0-9]/gi, '');

        $('.signup_form__msg').text('');

        if(name == '' || name == null){
            $('.signup_form__msg').text('Укажите имя');
            return false;
        }

        if(phone == '' || phone == null){
            $('.signup_form__msg').text('Укажите номер телефона');
            return false;
        }

        if(ph.length != 11){
            $('.signup_form__msg').text('Номер телефона неверен');
            return false;
        }

        if(psw != psw_r){
            $('.signup_form__msg').text('Пароли не совпадают');
            return false;
        }

        $.ajax({
            url: '/user/signup/',
            method: 'post',
            dataType: 'json',
            data:  { name: name, phone:phone, psw:psw },
            success: function(data){
                if(data.state != undefined && data.state == 'ok'){
                    window.location = window.location.protocol + '//' + window.location.hostname + "/";
                } else {
                    $('.signup_form__msg').text(data.msg);
                }

            }
        });

    });

    $('body').on('click', '.top_menu__li', function () {
        var _this = $(this);
        var tab = _this.data('tab');
        var client_id = $('#bx_client_id').val();

        $('.top_menu__li').removeClass('active');
        _this.addClass('active');

        $('.tabs_container__item').removeClass('active');
        $('.tabs_container__item').each(function(i, el) {
            if($(el).data('tab') == tab){
                $(el).addClass('active');
            }
        });

        var new_url = window.location.protocol + '//' + window.location.host + '/?tab=' + tab;
        history.pushState(null, null, new_url);
    });

    $('body').on('click', '.remove_bid', function () {
        var id = $(this).closest('tr').data('id');

        $('.remove_bid_form').data('id', id);

        popup.open('remove_bid_form');
    });

});