/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
(function ($) {
    $.fn.extend({
        serialize: function () {
            return jQuery.param(this.serializeArray());
        },
        serializeArray: function () {
            var rbracket = /\[\]$/,
                rCRLF = /\r?\n/g,
                rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
                rsubmittable = /^(?:input|select|textarea|keygen)/i,
                rcheckableType = (/^(?:checkbox|radio)$/i);
            return this.map(function () {
                // Can add propHook for "elements" to filter or add form elements
                var elements = jQuery.prop(this, "elements");
                return elements ? jQuery.makeArray(elements) : this;
            }).filter(function () {
                var type = this.type;
                // Use .is( ":disabled" ) so that fieldset[disabled] works
                //&& !jQuery(this).is(":disabled")
                return this.name && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
                    (this.checked || !rcheckableType.test(type) || $(this).is(':checkbox[unvalue]'));
            }).map(function (i, elem) {
                var val = jQuery(this).val();
                if (val == null) return null;
                if ($(this).is(':checkbox[unvalue]') && !this.checked) {
                    val = $(this).attr('unvalue');
                }
                if (Array.isArray(val)) {
                    return jQuery.map(val, function (val) {
                        return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
                    });
                }
                return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
            }).get();
        },
        ajaxConf: function (data) {
            var $this = $(this);
            return {
                url: $this.attr('href') || $this.attr('url') || $this.attr('action') || $this.data('href') || $this.data('url') || $this.data('action'),
                method: ($this.attr('method') || $this.data('method') || 'get').toLowerCase(),
                data: data ? data : ($this.is('form') ? $this.serialize() : ($this.attr('args') || $this.data('args') || {})),
                beforeSend: $this.data('beforeSend') || function () {
                },
                shade: $this.data('shade') !== false,
                dataType: $this.data('type') || $this.data('dataType') || 'json',
            };
        },
        ajax: function (callback) {
            var ajaxConf = $(this).ajaxConf(), vthis = this;
            if (!ajaxConf.url || ajaxConf.beforeSend.call(this) === false) return false;
            delete ajaxConf.beforeSend;
            ajaxConf.shade && $.loading.show();
            $.ajax($.extend(ajaxConf, {
                success: function (rs) {
                    ajaxConf.shade && $.loading.hide();
                    if (callback && callback.call(vthis, rs) === false) return;
                    $.callbackSuccess.call(vthis, rs);
                }
            }));
            return true;
        },
        gridReloadData: function (p, param, callback) {
            var grid = this, url = $(grid).data('url'),
                search = $('form.layui-grid-search', grid).serialize(),
                p = p || $(grid).data('curpage'),
                param = $.extend({ page: p || 1, checkType: $(grid).data('checkType') }, param || {});
            param = $.param(param) + '&' + search;
            if (!url) return;
            $.loading.show();
            $.post(url, param, function (rs) {
                $.loading.hide();
                if (callback && callback.call(grid, rs) === false) return;

                $(grid).data('curpage', rs.curr).data('pagetotal', rs.page_count);

                $('.layui-table tbody', grid).html(rs.data);
                $('.layui-laypage-count', grid).html('共 ' + rs.count + ' 条');
                $('.layui-laypage-curr em:last', grid).html(rs.curr + ' / ' + rs.page_count);
                $('.layui-laypage-prev', grid)[rs.curr <= 1 ? 'addClass' : 'removeClass']('layui-disabled');
                $('.layui-laypage-next', grid)[rs.curr >= rs.page_count ? 'addClass' : 'removeClass']('layui-disabled');
                window.layui && layui.render && layui.render();
            }, 'json');
        },
    });


    $.extend({
        loading: (function () {
            var loadlayer = null;
            return {
                show: function () {
                    loadlayer = layer.load();
                },
                hide: function () {
                    loadlayer >= 0 && layer.close(loadlayer);
                }
            };
        })(),
        showMsg: function (code, msg, callBack) {
            var status = '';
            if (code === 1 || code === true || code == 'success') status = 'success';
            if (code === 0 || code === false) status = 'error';
            var $div = $('<div>', {
                id: 'showMsg',
                style: 'position:absolute;top:30px;left:0;right:0;margin:0px auto;max-width:500px;height:auto;z-index:999999999;',
                html: [
                    '<div class="showMsgBox showMsgDown">',
                    '   <div class="icon ' + status + '"></div>',
                    '   <div class="msg">' + msg + '</div>',
                    '</div>'
                ].join('')
            }), m = $('body').append($div).scrollTop();
            m > 0 && $div.css('top', (m + 20) + 'px');
            window.setTimeout(function () {
                $('.showMsgBox', $div).removeClass('showMsgDown').addClass('showMsgUp');
                window.setTimeout(function () {
                    $div.remove();
                    typeof callBack == 'function' && callBack();
                }, 400);
            }, status == 'right' ? 2000 : 3000);
        },
        msg: function (msg, time, end) {
            var options = $.extend({ time: 3000 }, $.isPlainObject(msg) ? msg : {}, $.isPlainObject(time) ? time : {}), end;
            $.isFunction(end) && (options['end'] = end);
            $.isNumeric(time) && (options['time'] = time);
            $.isPlainObject(msg) && (msg = '');
            options['msg'] && (msg = options['msg']) && (delete options['msg']);
            layer.msg(msg, options);
        },
        confirm: function (msg, title) {
            var options = $.extend({ skin: '' }, $.isPlainObject(msg) ? msg : {}, $.isPlainObject(title) ? title : {}), yes, cancel;
            options.skin = 'layer-confirm ' + options.skin;
            $.isPlainObject(title) && (title = null);
            $.isFunction(title) && (options['yes'] = title) && (title = null);
            $.isPlainObject(msg) && (msg = '');
            options['msg'] && (msg = options['msg']) && (delete options['msg']);
            options['yes'] && (yes = options['yes']) && (delete options['yes']);
            options['cancel'] && (cancel = options['cancel']) && (delete options['cancel']);
            title && (options['title'] = title);
            return window.layui.layer.confirm(msg, options, function (index, layero) {
                var vthis = $('.layui-layer-btn .layui-layer-btn0', layero);
                if (yes && yes.call(vthis, layero, index) === false) return;
                layer.close(index);
            }, function (index, layero) {
                var vthis = $('.layui-layer-btn .layui-layer-btn1', layero);
                if (cancel && cancel.call(vthis, layero, index) === false) return;
                layer.close(index);
            });
        },
        prompt: function (title, yes) {
            var options = $.extend({}, $.isPlainObject(title) ? title : {}), success;
            if (!$.isEmptyObject(options)) {
                options['yes'] && (yes = options['yes']) && (delete options['yes']);
                options['success'] && (success = options['success']) && (delete options['success']);
                options['title'] && (title = options['title']) && (delete options['title']);
            }
            layer.prompt($.extend({
                title: title,
                formType: 0, //prompt风格，支持0-2
                success: function (layero, index) {
                    var $input = $('.layui-layer-input', layero);
                    options['attr'] && $input.attr(options['attr']);
                    $input.keyup(function (event) {
                        event.keyCode == 13 && $('.layui-layer-btn0', layero).click();
                    });
                    success && success.call($input, layero, index);
                },
                yes: function (index, layero) {
                    var $input = $('.layui-layer-input', layero), value = $input.val();
                    if (yes && yes.call($input, $.trim(value), layero) === false) return;
                    layer.close(index);
                }
            }, options));
        },
        dialog: function (options) {
            var options = $.extend({
                type: 1,
                yes: function (layero, index) {
                    $('.layui-layer-content form.layui-form', layero).submit();
                    return false;
                }
            }, options || {}), url = options['url'] || '';
            if (!url) return;
            return $.openpage(url, options['data'] || {}, function (rs) {
                $.confirm(rs, options);
            });
        },
        page: function (options) {
            options = options || {};
            var success = options['success'] || function () {
                },
                url = options['url'] || '',
                skin = options.skin || '';
            var options = $.extend(options || {}, {
                type: 1,
                skin: 'layer-grid ' + skin,
                resize: false,
                success: function (layero, index) {
                    if ($('.layui-card-header', layero).length) {
                        layero.addClass('layer-hide-title');
                        var $li = $('.layui-tab-title li', layero);
                        $('.layui-layer-title', layero).css('left', $li.length ? ($li.length * $li.outerWidth()) + 'px' : '100px');
                        var $title = $('.layui-layer-title', layero);
                        if ($title.length) {
                            var h = $('.layui-layer-content', layero).height();
                            $('.layui-layer-content', layero).height(h + $title.height())
                        }
                    }
                    return success.call(this, layero, index);
                },
            });
            if (!url) {
                return $.confirm(options);
            }
            return $.openpage(url, options['data'] || {}, function (rs) {
                $.confirm(rs, options);
            });
        },
        validatorFunc: function (control) {
            var validatorTips = function (type, msg) {
                if (type) {
                    $(this).removeClass('layui-form-danger');
                    layer.close($(this).data('layer.tips'));
                } else {
                    $(this).addClass('layui-form-danger').focus();
                    $(this).data('layer.tips', layer.tips(msg, this, { tipsMore: false, tips: [2, '#c00'] }));
                }
            };
            return validate(control, function () {
                validatorTips.call(this, true);
            }, function (msg) {
                validatorTips.call(this, false, msg);
            });
        },
        callbackSuccess: function (rs) {
            var callback = $(this).data('callback');
            if (callback && callback.call(this, rs) === false) return;
            rs && rs.msg && $.showMsg(rs.code, rs.msg);

            var $dialog = $(this).closest('.layui-layer'),
                $close = $('.layui-layer-close', $dialog),
                $grid = $(this).closest('.layui-grid');
            $grid.length || ($grid = $dialog.data('grid'));

            if (rs.code == 1 && $close.length) {
                if (!$grid || !$grid.length || !$.contains($dialog.get(0), $grid.get(0))){
                    $close.trigger('click');
                }
            }
            if ($grid && $grid.length && rs.url === true) {
                $grid.gridReloadData();
            } else if (rs.url && rs.url !== true) {
                setTimeout(function () {
                    $.openpage(rs.url);
                }, 1000);
            } else if (rs.data && rs.data.jump) {
                setTimeout(function () {
                    rs.data.jump === true ? window.location.reload(true) :
                        window.location.href = rs.data.jump;
                }, 1000);
            }
        },
        openpage: function (url, par, selectors) {
            if (!url) return false;
            $.loading.show();
            return $.get(url, par, function (rs) {
                $.loading.hide();
                $.isFunction(selectors) ? selectors(rs) :
                    $(selectors || '#manage-container>.page-container').html(rs);
                window.layui && layui.render && layui.render();
            });
        },
    });

})(window.jQuery);


(function ($) {
    var $ajax = $.ajax;
    $.ajax = function (url, options) {
        options = options || {};
        if (typeof url === "object") {
            options = url;
            url = undefined;
        }
        if (url && !options.url) options.url = url;
        var fn = {
            error: options.error || function (XMLHttpRequest, textStatus, errorThrown) { },
            success: options.success || function (data, textStatus, jqXHR) { },
            beforeSend: options.beforeSend || function (XHR) { },
            complete: options.complete || function (jqXHR, textStatus) { }
        };
        $ajax($.extend(options, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //错误方法增强处理
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function (data, textStatus, jqXHR) {
                if (data && (data == 'no_login' || data['code'] == 'no_login')) {
                    $.loading.hide();
                    var msg = ($.isPlainObject(data) && data['msg']) ? data['msg'] : '您尚未登录，请先登录！',
                        url = ($.isPlainObject(data) && data['url']) ? data['url'] : '';
                    $.showMsg(false, msg);
                    setTimeout(function () {
                        url ? window.location.href = url : window.location.reload();
                    }, 1000);
                    return;
                }
                if (data && !$.isPlainObject(data) && data.substr(0, 5) == 'error') {
                    $.loading.hide();
                    var arry = data.split('|'), msg = arry[1] || '操作错误！';
                    $.showMsg(false, msg);
                    return;
                }
                //成功回调方法增强处理
                fn.success(data, textStatus, jqXHR);
            },
            beforeSend: function (XHR) {
                fn.beforeSend(XHR);
            },
            complete: function (jqXHR, textStatus) {
                fn.complete(jqXHR, textStatus);
            }
        }));
    };
    var $clone = $.fn.clone;
    $.fn.clone = function () {
        var result = $clone.apply(this, arguments),
            my_textareas = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects = this.find('select').add(this.filter('select')),
            result_selects = result.find('select').add(result.filter('select'));
        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
        return result;
    };

})(window.jQuery);