jQuery(function ($) {
    //解决模态框背景色越来越深的问题
    $(document).on('show.bs.modal', '.modal', function (event) {
        $(this).appendTo($('body'));
    }).on('shown.bs.modal', '.modal.in', function (event) {
        setModalsAndBackdropsOrder();
    }).on('hidden.bs.modal', '.modal', function (event) {
        setModalsAndBackdropsOrder();
    });

    function setModalsAndBackdropsOrder() {
        var modalZIndex = 1040;
        $('.modal.in').each(function (index) {
            var $modal = $(this);
            modalZIndex++;
            $modal.css('zIndex', modalZIndex);
            $modal.next('.modal-backdrop.in').addClass('hidden').css('zIndex', modalZIndex - 1);
        });
        $('.modal.in:visible:last').focus().next('.modal-backdrop.in').removeClass('hidden');
    }

    //覆盖Modal.prototype的hideModal方法
    $.fn.modal.Constructor.prototype.hideModal = function () {
        var that = this
        this.$element.hide()
        this.backdrop(function () {
            //判断当前页面所有的模态框都已经隐藏了之后body移除.modal-open，即body出现滚动条。
            $('.modal.fade.in').length === 0 && that.$body.removeClass('modal-open')
            that.resetAdjustments()
            that.resetScrollbar()
            that.$element.trigger('hidden.bs.modal')
        })
    }


    function moveModal($this) {
        var $head = $this.find('.modal-header2');
        var $dialog = $this.find('.modal-dialog');
        var move = {
            isMove: false,
            left: 0,
            top: 0
        };
        //委托
        //console.log('点击的是', $this);
        $this.on('mousemove', function (e) {
            if (!move.isMove) return;
            //console.log('移动的是', e.target);
            $dialog.offset({
                top: e.pageY - move.top,
                left: e.pageX - move.left
            });
        }).on('mouseup', function (e) {
            move.isMove = false;
        });
        $head.on('mousedown', function (e) {
            move.isMove = true;
            var offset = $dialog.offset();
            move.left = e.pageX - offset.left;
            move.top = e.pageY - offset.top;
        });
    }

    var oldModal = $.fn.modal;
    $.fn.modal = function (o, _r) {
        var $this = $(this);
        if (!$this.attr('ifbindmv')) {
            $this.attr('isbindmv', '1');
            moveModal($this);
        }
        return oldModal.call(this, o, _r);
    }
    ////要拖动的div背景
    //$('#showErr').modal({backdrop: 'static'});
});


