/* 未能缩小。正在返回未缩小的内容。
(10,1): run-time error CSS1019: Unexpected token, found '('
(10,11): run-time error CSS1031: Expected selector, found '('
(10,11): run-time error CSS1025: Expected comma or open brace, found '('
(78,104): run-time error CSS1002: Unterminated string: 'S the current page)
 */
/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.1
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
(function () {
    jQuery.fn.pagination = function (maxentries, opts) {
        opts = jQuery.extend({
            items_per_page: 10,
            num_display_entries: 10,
            current_page: 0,
            num_edge_entries: 0,
            link_to: "javascript:;",
            prev_text: "Prev",
            next_text: "Next",
            ellipse_text: "...",
            prev_show_always: true,
            next_show_always: true,
            callback: function () { return false; }
        }, opts || {});

        return this.each(function () {
            /**
            * Calculate the maximum number of pages
            */
            function numPages() {
                return Math.ceil(maxentries / opts.items_per_page);
            }

            /**
            * Calculate start and end point of pagination links depending on 
            * current_page and num_display_entries.
            * @return {Array}
            */
            function getInterval() {
                var ne_half = Math.ceil(opts.num_display_entries / 2);
                var np = numPages();
                var upper_limit = np - opts.num_display_entries;
                var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
                var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
                return [start, end];
            }

            /**
            * This is the event handling function for the pagination links. 
            * @param {int} page_id The new page number
            */
            function pageSelected(page_id, evt) {
                current_page = page_id;
                drawLinks();
                var continuePropagation = opts.callback(page_id, panel);
                if (!continuePropagation) {
                    if (evt.stopPropagation) {
                        evt.stopPropagation();
                    }
                    else {
                        evt.cancelBubble = true;
                    }
                }
                return continuePropagation;
            }

            /**
            * This function inserts the pagination links into the container element
            */
            function drawLinks() {
                panel.empty();
                var interval = getInterval();
                var np = numPages();
                // This helper function returns a handler function that calls pageSelected with the right page_id
                var getClickHandler = function (page_id) {
                    return function (evt) { return pageSelected(page_id, evt); }
                }
                // Helper function for generating a single link (or a span tag if it'S the current page)
                var appendItem = function (page_id, appendopts) {
                    page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // Normalize page id to sane value
                    appendopts = jQuery.extend({ text: page_id + 1, classes: "current" }, appendopts || {});
                    if (page_id == current_page) {
                        var lnk = $("<span class='current'>" + (appendopts.text) + "</span>");
                    }
                    else {
                        var lnk = $("<a href='javascript:void(0)'>" + (appendopts.text) + "</a>")
                            .bind("click", getClickHandler(page_id))
                            .attr('href', opts.link_to.replace(/__id__/, page_id));


                    }
                    if (appendopts.classes) { lnk.removeAttr('class'); lnk.addClass(appendopts.classes); }
                    panel.append(lnk);
                }
                // Generate "Previous"-Link
                if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
                    appendItem(current_page - 1, { text: opts.prev_text, classes: "disabled pre" });
                }
                // Generate starting points
                if (interval[0] > 0 && opts.num_edge_entries > 0) {
                    var end = Math.min(opts.num_edge_entries, interval[0]);
                    for (var i = 0; i < end; i++) {
                        appendItem(i);
                    }
                    if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
                        jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                    }
                }
                // Generate interval links
                for (var i = interval[0]; i < interval[1]; i++) {
                    appendItem(i);
                }
                // Generate ending points
                if (interval[1] < np && opts.num_edge_entries > 0) {
                    if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
                        jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                    }
                    var begin = Math.max(np - opts.num_edge_entries, interval[1]);
                    for (var i = begin; i < np; i++) {
                        appendItem(i);
                    }

                }
                // Generate "Next"-Link
                if (opts.next_text && (current_page < np - 1 || opts.next_show_always)) {
                    appendItem(current_page + 1, { text: opts.next_text, classes: "disabled next" });
                }
            }

            // Extract current_page from options
            var current_page = opts.current_page;
            // Create a sane value for maxentries and items_per_page
            maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
            opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1 : opts.items_per_page;
            // Store DOM element for easy access from all inner functions
            var panel = jQuery(this);
            // Attach control functions to the DOM element 
            this.selectPage = function (page_id) { pageSelected(page_id); }
            this.prevPage = function () {
                if (current_page > 0) {
                    pageSelected(current_page - 1);
                    return true;
                }
                else {
                    return false;
                }
            }
            this.nextPage = function () {
                if (current_page < numPages() - 1) {
                    pageSelected(current_page + 1);
                    return true;
                }
                else {
                    return false;
                }
            }
            // When all initialisation is done, draw the links
            drawLinks();
        });
    }
})();



/*
 * 工具类整合
 * lihd 20150908
 */
(function (fn, arr) {
    fn.bind || (fn.prototype.bind = function (c) {
        var f = this;
        return function () {
            return f.apply(c, arguments);
        };
    });
    arr.prototype.indexOf || (arr.prototype.indexOf = function (c) {
        for (var i = 0, imax = this.length; i < imax; i++) {
            if (this[i] === c) {
                return i;
            }
        }
        return -1;
    });
    String.prototype.trim || (String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, '');
    });
})(Function, Array);

/*扩展jQuery center*/
/*lihd 2016-1-6 update(增加配置参数，
    changeposition：是否改变dom元素的定位为absolute。默认为true。)
    only：是否仅变动 sign 为 top 或 left 时对应的 位置。默认为 false（即是都改变）
*/
(function ($, win) {
    if (!$) { return; }
    $.fn.center = function (sign, changeposition, only) {
        var top, left, $win = $(win);
        if (!sign) { sign = 'all'; }
        changeposition = changeposition == false ? false : true;
        changeposition && this.css("position", "absolute");
        only = only || false;
        switch (sign) {
            case 'top':
                top = Math.max(0, (($win.height() - this.outerHeight(true)) / 2) + $win.scrollTop()) + "px";
                left = '0px';
                if (only) { this.css('top', top); }
                else { this.css({ top: top, left: left }); };
                break;
            case 'left':
                top = '0px';
                left = Math.max(0, (($win.width() - this.outerWidth(true)) / 2) + $win.scrollLeft()) + "px";
                if (only) { this.css('left', left); }
                else { this.css({ top: top, left: left }); }
                break;
            default:
                top = Math.max(0, (($win.height() - this.outerHeight(true)) / 2) + $win.scrollTop()) + "px";
                left = Math.max(0, (($win.width() - this.outerWidth(true)) / 2) + $win.scrollLeft()) + "px";
                this.css({ top: top, left: left })
                break;
        }
        return this;
    }

})(jQuery, window);

(function (doc, win) {
    var formatRe = /\{(\d+)\}/g, ArraySlice = Array.prototype.slice,
        charToEntityRegex = new RegExp('(' + ['&', '>', '<', '"', "'"].join('|') + ')', 'g'),
        entityToCharRegex = new RegExp('(' + ['&amp;', '&gt;', '&lt;', '&quot;', '&#39;'].join('|') + '|&#[0-9]{1,5};' + ')', 'g'),
        charToEntity = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', "'": '&#39;' },
        entityToChar = { '&amp;': '&', '&gt;': '>', '&lt;': '<', '&quot;': '"', '&#39;': "'" },
        htmlEncodeReplaceFn = function (match, capture) {
            return charToEntity[capture];
        },
         htmlDecodeReplaceFn = function (match, capture) {
             return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
         },
         emptyFn = function () { },
         AUTOCREATEID = 0,
         /*0-9,A-Z,a-z 的字符数组*/
         CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

    function isChinese(str) { //判断是不是中文
        var reCh = /[u00-uff]/;
        return !reCh.test(str);
    }

    function _buildNewFn(fn, scope) {
        var args = ArraySlice.call(arguments, 2);
        return function () {
            if (typeof fn == 'function') fn.apply(scope, args);
        }
    }

    var utils = {
        urlPre: urlPre || '',
        /*绝对路径请求地址格式化*/
        urlFormat: function (controller, action, area) {
            area = typeof area == 'undefined' ? 'PCUI' : area;
            return this.stringFormat('{2}/{0}/{1}', controller, action, area ? ("/" + area) : area);
        },
        /*格式化字符串数据*/
        stringFormat: function (format) {
            var args = ArraySlice.call(arguments, 1);
            return format.replace(formatRe, function (m, i) {
                return args[i];
            });
        },
        /*字符串截断，只取想要的长度，最后追加...*/
        stringEllipsis: function (value, len) {
            if (value && value.length > len) {
                return value.substr(0, len - 3) + "...";
            }
            return value;
        },
        /*请求地址追加参数字符串 如“a=1&b=2...”*/
        urlAppend: function (url, string) {
            if (string) {
                return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
            }
            return url;
        },
        /*html解码*/
        htmlDecode: function (value) {
            return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
        },
        /*html编码*/
        htmlEncode: function (value) {
            return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
        },
        /* 
         * 提示信息框
         * content：提示内容
         * fn：自动关闭后的回调函数（关闭时间可通过options配置）
         * delay:自动关闭时间
         * mask:是否显示遮罩层
         */
        msg: function (content, fn, delay, mask) {
            if (typeof delay == "number") {
                layer.msg(content, { time: delay, shade: mask ? 0.3 : 0 }, fn);
            } else if (typeof delay == "object") {
                layer.msg(content, delay, fn);
            } else {
                layer.msg(content, fn);
            }
        },
        limitText: function (message, MaxLenght) {
            var strlen = 0; //初始定义长度为0
            var txtval = $.trim(message);
            for (var i = 0; i < txtval.length; i++) {
                if (isChinese(txtval.charAt(i)) == true) {
                    strlen = strlen + 2; //中文为2个字符
                } else {
                    strlen = strlen + 1; //英文一个字符
                }
            }
            return strlen > MaxLenght ? false : true;
        },
        /*
         * 显示类似浏览器自带的 alert 弹出框
         * content：提示内容
         * fn：单击确定时的回调函数（若没有，可为null）
         * options:参考layer的基础配置
         * 用法：Utils.alert("我是alert");
         */
        alert: function (content, fn, options) {
            if (typeof fn == 'function') {
                layer.alert(content, options, function (index) {
                    fn();
                    layer.close(index)
                });
            } else {
                layer.alert(content, options);
            }
        },
        /*
         * 显示类似浏览器自带的 confirm 弹出框
         * content：提示内容
         * fn：单击确定时的回调函数（若没有，可为null）
         * options:参考layer的基础配置
         * 用法：Utils.confirm("我是confirm");
         */
        confirm: function (content, fn, options) {
            if (typeof fn == 'function') {
                layer.confirm(content, options, function (index) {
                    if (fn() === false) {
                        return;
                    };
                    layer.close(index);
                });
            } else {
                layer.confirm(content, options);
            }
        },
        /*
         * 显示iframe层 jxx 2016-6-7
         * title：显示层的标题
         * width：显示层的宽度，字符串 例 380px 或者 90%
         * height：显示层的宽度，字符串 例 380px 或者 90%
         * url：iframe的链接url
         * skin: 外层layer的皮肤class类
         */
        OpenIframe: function (title, width, height, url, skin) {
            return layer.open({
                type: 2,
                title: title,
                shadeClose: true,
                shade: 0.4,
                area: [width, height],
                content: url,
                skin: skin || '',
                scrollbar: false
            });
        },
        /*
         * 显示页面层 jxx 2016-6-7 
         * width：显示层的宽度，字符串 例 380px 或者 90%
         * height：显示层的宽度，字符串 例 380px 或者 90%
         * content：需要显示的html 
         * skin:外层layer的皮肤class类
         */
        OpenWin: function (width, height, content, skin) {
            //页面层
            return layer.open({
                type: 1,
                title: ['扫描二维码', 'font-size: 16px;font-weight: 400;'], //不显示标题 
                //  skin: 'layui-layer-rim', //加上边框
                area: [width, height], //宽高
                content: content,
                skin: skin || '',
                scrollbar: false
            });
        },
        /*
         * 显示Load层
         */
        loadLayer: function (type, options) {
            this.LOADLAYERINDEX = layer.load(type || 0, options);
            return this.LOADLAYERINDEX;
        },
        /*隐藏Load层*/
        hideLoadLayer: function (index) {
            if (index) {
                layer.close(index);
                if (index == this.LOADLAYERINDEX) {
                    delete this.LOADLAYERINDEX;
                }
            } else if (this.LOADLAYERINDEX) {
                layer.close(this.LOADLAYERINDEX);
                delete this.LOADLAYERINDEX;
            } else {
                layer.closeAll('loading');
            }
        },
        showMask: function () {
            var tpl = '<div class="doMask"></div>';
            $(tpl).appendTo(document.body);
        },
        hideMask: function () {
            $(".doMask").hide().remove();
        },
        /*依赖jQuery的Post方法 增加 简单封装*/
        jQueryAjax: function (url, params, successFn, options, layouttips) {
            if (!jQuery) { return; }
            if (!options) options = {};
            if (layouttips !== false) { layouttips = true; }
            var defaults = {
                context: this,
                data: params,
                dataType: 'json',
                error: emptyFn,
                success: successFn ? function (data, textStatus, jqXHR) {
                    //lihd 2016-8-4 update:对于不是json格式的情况下，自动切换下看能否转换成json格式。
                    if (options.dataType != undefined && options.dataType != 'json') {
                        try { data = $.parseJSON(data); } catch (ex) { }
                    }
                    //登录超时验证
                    if (data && typeof data.Level != 'undefined') {
                        if (data.Level == 3) {
                            Utils.hideMask();
                            Utils.hideLoadLayer();
                            if (layouttips) {
                                Utils.msg(data.Msg, function () {
                                    Utils._showLoginQRCode()
                                    //window.location.href = data.Data;
                                }, 2000);
                            } else {
                                Utils._showLoginQRCode();
                                // window.location.href = data.Data;
                            }
                            return;
                        } else if (data.Level == 5 && (typeof options.AutoDealByLevel == 'undefined' || options.AutoDealByLevel === true)) {
                            Utils.hideMask();
                            Utils.hideLoadLayer();
                            //重定向
                            if (data.Msg) {
                                Utils.msg(data.Msg, function () {
                                    window.location.href = data.Data;
                                }, 2000);
                            } else {
                                window.location.href = data.Data;
                            }
                            return;
                        } else if (data.Level == 6 && (typeof options.AutoDealByLevel == 'undefined' || options.AutoDealByLevel === true)) {
                            Utils.hideMask();
                            Utils.hideLoadLayer();
                            //刷新界面
                            if (data.Msg) {
                                Utils.msg(data.Msg, function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                location.reload();
                            }
                            return;
                        }
                    }
                    //执行成功回调函数
                    if (typeof options.async != 'undefined' && options.async == false) {
                        successFn.call(this, data, textStatus);
                    } else {
                        setTimeout(_buildNewFn(successFn, this, data, textStatus), 10);
                    }
                } : emptyFn,
                type: 'post',
                url: url
            };
            $.extend(defaults, options);
            return $.ajax(defaults);
        },
        /*构建新函数*/
        buildNewFn: _buildNewFn,
        /*判断元素中滚动条位置是否到顶部*/
        isTop: function (el) {
            var scrollTop = el ? el.scrollTop : doc.body.scrollTop;
            return scrollTop === 0;
        },
        /*判断元素中滚动条位置是否到底部*/
        isBottom: function (el, diffHeight) {
            var scrollTop, _height, _winHeight;
            if (!el) {
                el = doc.body;
                _height = el.clientHeight;
                _winHeight = win.screen.height;
                diffHeight = diffHeight || 0;
            } else {
                _height = el.scrollHeight;
                _winHeight = el.clientHeight;
                diffHeight = -2;
            }
            scrollTop = el.scrollTop;
            return scrollTop >= _height - _winHeight + diffHeight;
        },
        /* containid[String]：字段容器id，用于查找其子元素。
         * property[String]:要查找包含property的元素,默认为:name。
         * isValidate[Boolean]：是否进行字段验证处理，默认为true
         */
        getSubmitValue: function (containid, property, isValidate) {
            if (!containid) { return null; }
            property = property || 'name';
            isValidate = typeof isValidate == 'undefined' ? true : isValidate;
            var fields = jQuery("#" + containid + ' [' + property + ']'), dom, i, len = fields.length
                , val = {}, item, validatrValue;
            if (isValidate) {
                for (i = 0; i < len; i++) {
                    dom = fields[i];
                    for (item in validate) {
                        validatrValue = dom.getAttribute(item);
                        if (validatrValue && validate.hasOwnProperty(item)) {
                            if (!validate[item](dom.value, validatrValue)) {
                                this.msg(dom.getAttribute('data-msg-' + item) || '格式不正确', null, 1500);
                                return null;
                            };
                        }
                    }
                }
            }
            for (i = 0; i < len; i++) {
                dom = fields[i];
                val[dom[property]] = dom.value;
            }
            return val;
        },
        /* 获取url中的参数 jxx 2015-9-24*/
        GetQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return (r[2]); return null;
        }
        ,
        /* 正则html 转义 jxx 2015-11-26*/
        TransferHTML: function (value) {
            value = value.replace(/&(quot|#34);/g, "\"");
            value = value.replace(/&(amp|#38);/g, "&");
            value = value.replace(/&(lt|#60);/g, "<");
            value = value.replace(/&(gt|#62);/g, ">");
            value = value.replace(/&(nbsp|#160);/g, "   ");
            value = value.replace(/&(iexcl|#161);/g, "\xa1");
            value = value.replace(/&(cent|#162);/g, "\xa2");
            value = value.replace(/&(pound|#163);/g, "\xa3");
            value = value.replace(/&(copy|#169);/g, "\xa9");
            value = value.replace(/<br\/>/g, "\n");
            return value;
        },
        //检查支持的css3样式
        getSupportPropertyName: function (prop) {
            var testElem = document.createElement("div")
            if (prop in testElem.style) { testElem = null; return prop; }
            var testProp = prop.charAt(0).toUpperCase() + prop.substr(1),
                prefixs = ["Webkit", "Moz", "ms", "O"];

            for (var i = 0, l = prefixs.length; i < l; i++) {
                var prefixProp = prefixs[i] + testProp;
                if (prefixProp in testElem.style) {
                    testElem = null;
                    return prefixProp;
                }
            }
        },
        /*
         * lihd 2016-6-8 update:显示二维码扫码登录框
         */
        _showLoginQRCode: function (url, title) {
            //获取登录页面的html和css
            this._SHOWLOGINQRCODE_INDEX = this.OpenIframe(title || '用户登录', '500px', '500px', url || this.urlFormat("Login", "ScanLogin?IS_IFRAME=true"), "layer-curstom-radius");
        },
        /*
         * lihd 2016-6-8 update：关闭二维码扫码登录框
         */
        _hideLoginQRCode: function () {
            if (typeof this._SHOWLOGINQRCODE_INDEX != 'undefined') {
                layer.close(this._SHOWLOGINQRCODE_INDEX);
                delete this._SHOWLOGINQRCODE_INDEX;
            }
        },
        /*
         * lihd 2016-6-12 update:显示二维码弹出层
         */
        _showQRCodeUrl: function (title, url) {
            this.jQueryAjax(this.urlFormat('News', 'postUrl_QrCode'), { title: title, url: url }, function (rs) {
                if (rs.Success) {
                    this.OpenWin("500px", "380px"
                        , [
                            //'<div style="text-align:center;">'
                            //, '<img width="200" src="' + rs.Data + '" />'
                            //, '<p>' + title.replace("点击进入", "微信扫二维码在手机上显示") + '</p>'
                            //, '</div>'
                            '<div class="popup">'
	                            //, '<ul class="tit">'
    	                        //    , '<h3>扫描二维码</h3>'
                                //    , '<b><a href="#"><img src="../../../Content/images/PCUI/close.gif" /></a></b>'
                                //, '</ul>'
                                , '<ul class="text"> '
	                                , '<p class="p_wz1">' + title.replace("点击进入", "微信扫二维码在手机上显示")
                                        .replace("点击查看", "微信扫二维码在手机上显示")
                                        .replace("点击连接", "微信扫二维码在手机上") + '</p>'
		                            , '<p class="p_wz2"></p>'
                                    , '<p><img  width="200"  src="' + rs.Data + '" /></p>'
                                , '</ul>'
                            , '</div>'
                        ].join('')
                        , "layer-curstom-radius");
                } else {
                    this.alert(rs.Msg);
                }
            });
        },
        emptyFn: emptyFn,
        adjustContainerHeight: function (selecter, subtractHeightClassArray) {
            subtractHeightClassArray = subtractHeightClassArray || ['head', 'foot'];
            var winHeight = window.screen.height, subtractHeight = 0, i = 0, len = subtractHeightClassArray.length;
            for (; i < len; i++) {
                subtractHeight += $('.' + subtractHeightClassArray[i]).outerHeight();
            }
            $(selecter).css('min-height', (winHeight - subtractHeight) + 'px');
        },
        head: document.getElementsByTagName("head")[0] || document.documentElement,
        //加载Script、Style 函数
        Myload: function (B, A, C) {
            var that = this;
            C = C === false ? false : true;
            B.onload = B.onreadystatechange = function () {
                if (!this._done_ && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                    this._done_ = true;
                    A();
                    B.onload = B.onreadystatechange = null;
                    if (that.head && B.parentNode && C) {
                        that.head.removeChild(B);
                    }
                }
            };
        },
        //加载Script
        getScript: function (A, C, E, id) {
            E = E === false ? false : true;
            id = id || this.getJsGuid();
            var B = function () { };
            if (typeof C == 'function') {
                B = C;
            }
            var D = document.createElement("script");
            D.setAttribute("language", "javascript");
            D.setAttribute("type", "text/javascript");
            D.setAttribute("id", id);
            D.setAttribute("src", A);
            this.head.appendChild(D);
            this.Myload(D, B, E);
        },
        //加载Style
        getStyle: function (A, D, E, id) {
            E = E === false ? false : true;
            id = id || this.getJsGuid();
            var B = function () { };
            if (typeof D == 'function') {
                B = D;
            }
            var C = document.createElement("link");
            C.setAttribute("type", "text/css");
            C.setAttribute("rel", "stylesheet");
            C.setAttribute("id", id);
            C.setAttribute("href", A);
            this.head.appendChild(C);
            this.Myload(C, B, E);
        },
        //获取随机请求参数
        getVerNum: function () {
            var D = new Date();
            return D.getFullYear().toString().substring(2, 4) + '.' + (D.getMonth() + 1) + '.' + D.getDate() + '.' + D.getHours() + '.' + (D.getMinutes() < 10 ? '0' : D.getMinutes().toString().substring(0, 1));
        },
        /*
         * 数据模板替换
         * lihd 2016-12-8
         * @param {String} str 用于替换数据模板字符串
         * @param {Object} data 用于替换的数据
         * @param {Boolean} trimNull 是否用空字符串替换找不到的数据项 默认为否
         */
        formateString: function (str, data, trimNull) {
            trimNull = trimNull == true ? true : false;
            return str.replace(/@\{(\w+)\}/g, function (match, key) {
                return typeof data[key] === "undefined" ? (trimNull ? '' : match) : data[key];
            });
        },
        /*
         * 获取唯一的css。（避免对相同文件重复获取）
         * lihd 2016-12-16
         * @param {String} path css文件路径
         * @param {Function} callback 回调方法
         */
        getUnionStyle: function (path, callback) {
            var _id_;
            if (typeof this._LOADPATHS_DIC_ == 'undefined') {
                this._LOADPATHS_DIC_ = {};
            }
            if (typeof this._LOADPATHS_DIC_[path] != 'undefined') {
                if (typeof callback == 'function') {
                    setTimeout(callback, 100);
                }
                return;
            }
            _id_ = this.getAutoUnionId();
            this._LOADPATHS_DIC_[path] = _id_;
            this.getStyle(path, callback, false, _id_);
        },
        /*
         * 获取唯一的js。（避免对相同文件重复获取）
         * lihd 2016-12-16
         * @param {String} path css文件路径
         * @param {Function} callback 回调方法
         */
        getUnionScript: function (path, callback) {
            var _id_, _dom_;
            if (typeof this._LOADPATHS_DIC_ == 'undefined') {
                this._LOADPATHS_DIC_ = {};
            }
            if (typeof this._LOADPATHS_DIC_[path] != 'undefined') {
                _id_ = this._LOADPATHS_DIC_[path];
                if (typeof callback == 'function') {
                    _dom_ = doc.getElementById(_id_);
                    if (!_dom_ || typeof _dom_._done_ == 'undefined') {
                        setTimeout(this.buildNewFn(this.getUnionScript, this, path, callback), 1000);
                        return;
                    }
                    setTimeout(callback, 100);
                }
                return;
            }
            _id_ = this.getAutoUnionId();
            this._LOADPATHS_DIC_[path] = _id_;
            this.getScript(path, callback, false, _id_);
        },
        /*
         * 获取Guid 全局唯一值 （发送碰撞的可能性比较小，但不排除这种可能）
         * lihd 2016-12-16
         */
        getJsGuid: function () {
            var chars = CHARS, uuid = new Array(36), rnd = 0, r;
            for (var i = 0; i < 36; i++) {
                if (i == 8 || i == 13 || i == 18 || i == 23) {
                    uuid[i] = '-';
                } else if (i == 14) {
                    uuid[i] = '4';
                } else {
                    if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                    r = rnd & 0xf;
                    rnd = rnd >> 4;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
            return uuid.join('');
        },
        /*
         * 获取自动生成的唯一id
         * lihd 2017-01-03
         */
        getAutoUnionId: function (pre) {
            var _id = (pre || '') + "auto_unionid_" + AUTOCREATEID;
            AUTOCREATEID++;
            return _id;
        },
        /*
         * 执行全局函数
         * lihd 2016-01-09
         * @param {globalName} 函数全名称 如：Utils.alert
         * @param {scope} 函数执行时的作用域 
         */
        execGlobalFn: function (globalName, scope) {
            if (typeof globalName != 'string') { return; }
            scope = scope || win;
            var fn_les = globalName.split('.'), i, len,
                temp_les = win[fn_les[0]];
            if (!temp_les) { return; }
            for (i = 1, len = fn_les.length; i < len; i++) {
                temp_les = temp_les[fn_les[i]];
            }
            if (typeof temp_les == 'function') {
                return temp_les.apply(scope, ArraySlice.call(arguments, 2));
            }
        }
    }
    win.Utils = win.Utils || utils;
})(document, window);


/*
 * 基于jQuery、jquery.pagination 和 Utils 的选择分页封装
 * lihd 2015-6-18
 */
(function ($, util, win) {
    var ArraySlice = Array.prototype.slice;

    function Pager(options, limit, page) {
        if (!options || typeof options != 'object') { throw "请提供配置数据！"; }
        this.defaults = {
            TOTAL: 0,
            url: '',
            isRowRenderFn: false,
            dataCmt: '',
            loadingAfterScrollTop: true,
            isCoverDataCmtHtml:true,//是否以覆盖的方式添加html。否时使用追加的方式
            pageCmt: '',
            pageNum_display_entries:2,
            loadingMask: true,
            renderer: null,
            ISLOADING: false,
            emptyDataText: '暂无数据！'
        };
        this.defaultsParams = {
            page: page || 0,
            limit: limit || 10
        }
        $.extend(this.defaults, options);
        this.ev = {
            'beforeload': null,
            'afterload': null
        }
        Utils.adjustContainerHeight(".contain_right");
    }

    function _tempFn(fn, scope) {
        return function () {
            fn.apply(scope, arguments);
        }
    }

    Pager.prototype.pageselectCallback = function (page, jq) {
        this.defaultsParams.page = page;
        this.doSearch();
    }


    Pager.prototype.setExtendParams = function (p) {
        if (typeof p != 'object') { throw "请提供请求参数对象！"; }
        $.extend(this.defaultsParams, p);
        return this;
    };

    //清空扩展参数 lihd 2016-7-25
    Pager.prototype.clearExtendParams = function (page, limit) {
        this.defaultsParams = { page: page || 0, limit: limit || 10 };
        return this;
    }

    Pager.prototype.doSearch = function () {
        var that = this, _layerIndex;
        if (that.defaults.ISLOADING) { return; }

        if (typeof that.ev.beforeload == 'function') {
            if (this.ev.beforeload.call(this, this.defaultsParams) == false) { return; }
        }

        that.defaults.ISLOADING = true;
        if (that.defaults.loadingMask) {
            _layerIndex = Utils.loadLayer();
        }
        that.defaultsParams.start = that.defaultsParams.page * that.defaultsParams.limit;
        util.jQueryAjax(that.defaults.url, that.defaultsParams, function (rs) {
            var o = that, htmlStr, data, defaults = o.defaults, $dataCmt;
            if (rs.Success) {
                data = rs.Data;
                if (rs.Total != -1) {
                    o.defaults.TOTAL = rs.Total;
                }
                if (data) {
                    if (defaults.isRowRenderFn) {
                        var tempArray = [];
                        for (var i = 0, len = data.length; i < len; i++) {
                            tempArray.push(defaults.renderer(data[i]));
                        }
                        htmlStr = tempArray.join('');
                    } else {
                        htmlStr = defaults.renderer(data);
                    }
                    if (htmlStr) {
                        $dataCmt = $("#" + defaults.dataCmt);
                        defaults.isCoverDataCmtHtml ? $dataCmt.html(htmlStr) : $dataCmt.append(htmlStr);
                        if (defaults.loadingAfterScrollTop) {
                            win.scrollTo(0, 0);
                        }
                    } else if (o.defaults.TOTAL <= 0) {
                        $("#" + defaults.dataCmt).html('<p style="color:red;text-align:center;padding:20px 0;" >' + defaults.emptyDataText + '</p>');
                    }
                    //有设置分页插件时才初始化分页插件
                    if (defaults.pageCmt.length > 0) {
                        if (o.defaults.TOTAL > 0) {
                            $("#" + defaults.pageCmt).pagination(o.defaults.TOTAL, {
                                callback: _tempFn(o.pageselectCallback, o),
                                prev_text: ' &nbsp;上一页',
                                next_text: '下一页&nbsp; ',
                                items_per_page: o.defaultsParams.limit,
                                num_display_entries: defaults.pageNum_display_entries,
                                current_page: o.defaultsParams.page,
                                num_edge_entries: 2
                            }).show();
                        } else {
                            $("#" + defaults.pageCmt).hide();
                        }
                    }
                }
            } else {
                this.alert(rs.Msg);
            }

            if (defaults.loadingMask) { this.hideLoadLayer(); }
            defaults.ISLOADING = false;
            if (typeof o.ev.afterload == 'function') {
                setTimeout(this.buildNewFn(o.ev.afterload, o), 10);
            }
        }, { type: 'get' });
    }

    Pager.prototype.addEv = function (name, fn) {
        if (typeof this.ev[name] != 'undefined' && typeof fn == 'function') {
            this.ev[name] = fn;
        }
        return this;
    };

    Pager.prototype.removeEv = function (name) {
        if (typeof this.ev[name] != 'undefined') {
            this.ev[name] = null;
        }
        return this;
    }

    Pager.prototype.emptyData = function () {
        $("#" + this.defaults.dataCmt).empty();
        this.defaultsParams.page = 0;
        return this;
    }

    win.Pagination = Pager;
})(jQuery, Utils, window);

/*
 * 基于jQuery、和 Utils 的 代理方式click事件触发封装 BindCustomFn
 * lihd 2016-6-18
 * 默认有四种事件 跳转（redirect） 和 打开登录框 (openloginpanel) 和 显示用户二维码扫描界面（showpersonqrcode） 、 打开ifram弹出框 (openiframe)
 *                标签页面（tabpage）
 * lihd 2016-8-23 增加对标签页面（tabpage） 的处理：
 * 标签页面（tabpage）参数说明： data-tabcls 为必选项，存放单击该标签时切换的class
 *                               data-tabrelationids 为必选项，存放控制显示或隐藏的html元素id，格式:id1,id2,id3。id1会显示，其他的则隐藏。
 *                               data-htmlajaxurl 可选,用于为显示的html元素加载html数据的地址，必须为可进行ajax的地址。
 *                               data-alwaysload 可选，针对 data-htmlajaxurl,用于是否强制每次显示时都重新获取数据。格式：true/false
 *                               showfn  可选，用于每次显示后的执行的函数名。格式：函数名称 或 对象.函数的名称
 */
(function ($, util, win) {
    var _hasSetIds = [];

    function _bindCustomFn(id, deep) {
        if (_hasSetIds.indexOf(id) != -1) { throw util.stringFormat("该id:【{0}】的配置已经存在了!", id); }
        this.id = id || '';
        this.deep = deep || 2;
        _hasSetIds.push(id);
        this.otherFn = {};
        $("#" + id).on('click', _jqTempFn(this));
    }

    function _jqTempFn(t) {
        return function (e) {
            _handlerFn.call(this, e, t);
        }
    }

    function _handlerFn(e, that) {
        var target = e.target, click = target.getAttribute("data-click"), deep = that.deep, otherFn;
        while (!click && deep-- && target.getAttribute('id') != that.id) {
            target = target.parentNode;
            if (!target.getAttribute) { return; }
            click = target.getAttribute("data-click");
        }
        if (!click) {
            return;
        }
        //若是有自定义的其他 处理方式，则采用自己的处理方式(会将当前对象 target 和 事件代理节点的jQuery对象 传入 。自定义处理方式中的 this 为 BindCustomFn 的实例 )。否则采用 提供的方式
        otherFn = that.otherFn;
        if (otherFn && typeof otherFn[click] == 'function') {
            e.preventDefault();
            e.stopPropagation();
            otherFn[click].call(that, target, this);
        } else {
            e.preventDefault();
            e.stopPropagation();
            switch (click) {
                case "redirect":
                    e.preventDefault();
                    that.redirect(target.getAttribute('data-jumpurl'), target.getAttribute('data-opennew') === 'false' ? false : true);
                    break;
                    //打开扫码登录框
                case "openloginpanel":
                    e.preventDefault();
                    util._showLoginQRCode();
                    break;
                    //显示用户二维码扫描界面
                case "showpersonqrcode":
                    e.preventDefault();
                    setTimeout(Utils.buildNewFn(Utils._showQRCodeUrl, Utils, target.getAttribute("data-showtips"), target.getAttribute("data-jumpurl")));
                    break;
                    //打开iframe
                case "openiframe":
                    e.preventDefault();
                    Utils.OpenIframe(target.getAttribute("data-title"), target.getAttribute('data-width') || '728px', target.getAttribute('data-height') || '90%', target.getAttribute("data-url"));
                    break;
                    //标签页面
                case "tabpage":
                    e.preventDefault();
                    setTimeout(Utils.buildNewFn(tabPageFn, win, target));
                    break;
            }
        }
    }

    _bindCustomFn.prototype.setOtherFn = function () {
        var otherFn = this.otherFn;
        if (arguments.length == 1 && typeof arguments[0] == 'object') {
            $.extend(otherFn, arguments[0]);
        } else {
            var fn = arguments[1], name = arguments[0];
            if (typeof fn == 'function' && !otherFn.hasOwnProperty(name)) {
                otherFn[name] = fn;
            }
        }
    }

    //lihd 2016-12-1 update：扩展redirect 方法 让其能处理javascript的情况。
    _bindCustomFn.prototype.redirect = function (url, isnew) {
        var tempsubstring = '';
        if (url && url.length > 0) {
            tempsubstring = url.substring(0, 11);
            if (tempsubstring == 'javascript:') {
                eval(url.substring(11));
            } else {
                if (isnew === false) {
                    location.href = url;
                } else {
                    window.open(url, "_blank");
                }
            }
        }
    }

    //标签切换方法 lihd 2016-01-09
    _bindCustomFn.prototype._TabPageMethod = tabPageFn;

    //tab标签切换页面函数 lihd 2016-8-23
    function tabPageFn(target) {
        var cls = target.getAttribute("data-tabcls"),
                    ids = target.getAttribute("data-tabrelationids"),
                    ids_arr, $target, i, len, showfn, beforefn, $showContainer,
                    ajaxhtmlurl, ajaxhtmlhasLoad;
        if (!cls || !ids) { return; }
        $target = $(target);
        //执行标签中包含的html元素的显示和隐藏
        if (!$target.hasClass(cls)) {
            ids_arr = ids.split(',');
            $("." + cls).removeClass(cls);
            $target.addClass(cls);

            //如果设置了 html显示之前 执行的方法，则从window中找到该对应的方法并执行
            beforefn = target.getAttribute("data-beforefn");
            //如果有设置了 html元素显示后 执行的方法，则从window中找到对应的方法并执行
            showfn = target.getAttribute("data-showfn");

            Utils.execGlobalFn(beforefn, null, target);

            //第一个html元素显示，其他的html元素则隐藏
            $showContainer = $('#' + ids_arr[0]).show();
            for (i = 1, len = ids_arr.length; i < len; i++) {
                $('#' + ids_arr[i]).hide();
            }

            //若是有获取html数据的url路径，则执行加载html数据到显示的html元素中
            ajaxhtmlurl = target.getAttribute("data-htmlajaxurl");
            if (ajaxhtmlurl) {
                ajaxhtmlhasLoad = target.getAttribute("data-htmlurlloaded") === 'true' ? true : false;
                //没加载过 或者 设置了每次显示都加载 才去获取数据
                if (!ajaxhtmlhasLoad || target.getAttribute("data-alwaysload") === 'true') {
                    $showContainer.addClass("layui-layer-loading").html("<div class='layui-layer-content' style='margin:0 auto;' ></div>");
                    Utils.jQueryAjax(ajaxhtmlurl, null, function (data) {
                        $showContainer.html(data);
                        !ajaxhtmlhasLoad && (target.setAttribute("data-htmlurlloaded", 'true'));
                        Utils.execGlobalFn(showfn, null, target);
                    }, { dataType: 'html' });
                } else {
                    Utils.execGlobalFn(showfn, null, target);
                }
            } else {
                Utils.execGlobalFn(showfn, null, target);
            }


            //if (showfn) {
            //    Utils.execGlobalFn(showfn, null, target);
            //showfn_les = showfn.split('.');
            //temp_les = this[showfn_les[0]];
            //if (!temp_les) { return; }
            //for (i = 1, len = showfn_les.length; i < len; i++) {
            //    temp_les = temp_les[showfn_les[i]];
            //}
            //if (typeof temp_les == 'function') {
            //    temp_les(target);
            //}
            //}
        }
    }



    win.BindCustomFn = _bindCustomFn;
})(jQuery, Utils, window);

/*
 * 倒计时插件
 * lihd 2016-12-21
 */
(function () {
    function CountDown(opts) {
        this.options = $.extend(true, {}, this.defaults, opts);
        this.endDate = new Date(new Date().getTime() + this.options.totalTime);
        this._dealFn();
    }
    CountDown.prototype.defaults = {
        miniDom: null,
        secDom: null,
        hmDom: null,
        totalTime: 1000,
        endFn: null
    }

    CountDown.prototype.zero = function (n) {
        var _n = parseInt(n, 10);//解析字符串,返回整数
        if (_n > 0) {
            if (_n <= 9) {
                _n = "0" + _n
            }
            return String(_n);
        } else {
            return "00";
        }
    };

    CountDown.prototype._dealFn = function () {
        var now = new Date(), endDate = this.endDate, opts = this.options;
        var dur = (endDate - now.getTime()) / 1000, mss = endDate - now.getTime();
        if (mss > 0) {
            //opts.hmDom.innerHTML = this.zero(mss % 1000);
            opts.hmDom.innerHTML = this.zero(mss % 100);
            opts.secDom.innerHTML = this.zero(dur % 60);
            opts.miniDom.innerHTML = Math.floor((dur / 60)) > 0 ? this.zero(Math.floor((dur / 60)) % 60) : "00";
            setTimeout(Utils.buildNewFn(arguments.callee, this), 10);
        } else {
            opts.miniDom.innerHTML = opts.secDom.innerHTML = opts.hmDom.innerHTML = "00";
            this._dispose();
            if (typeof opts.endFn == 'function') {
                opts.endFn();
            }
        }
    };
    /*析构方法 lihd 2016-12-28*/
    CountDown.prototype._dispose = function () {
        this.options.hmDom = null;
        this.options.miniDom = null;
        this.options.secDom = null;
    }

    window.CountDown = CountDown;
})();


