var gRegExp = {
    mobile: /^1[3|4|5|8][0-9]\d{4,8}$/
};
(function () {
    var editors = {};
    var ketool = {
        uploadJson: "/Upload/Start/?ke=1",
        isGetUoloadToken: false, editors: editors
    }
    ketool.get=function (id) {
        return editors[id];
    }
    ketool.remove = function (ids) {
        if (ids == null) {
            for (var key in editors) {
                var editor = editors[key];
                if (editor && editor.remove) editor.remove();
            }
            editors = {};
        } else {
            var a = ids.split(",");
            $.each(a, function () {
                var editor = editors[this];
                if (editor && editor.remove) editor.remove();
                delete editors[this];
            });
        }
    }
    ketool.create= function (id, w, h, items, uops) {
        this.remove(id);
        var ops = {};
        if (w) ops.width = w;
        if (h) ops.height = h;
        if (items) ops.items = items;
        if (uops) $.extend(ops, uops);
        var editor = KindEditor.create('#' + id, ops);
        if (!editor) return null;
        editor.destroy = function () {
            delete editors[id];
            editor.remove();
            editor = null;
        }
        editors[id] = editor;
        return editor;
    }
    //默认文本编辑器
    //调用：ketool.default('content', '50%', '300px');
    ketool.default = function (id, w, h, uops) {
        var items = ['source', '|', 'undo', 'redo', '|', 'preivew', 'print', 'template', 'code', 'cut', 'copy', 'paster',
                        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', '|',
                        'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', '/',
                        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                        'strikethrough', 'lineheight', 'removeformat', '|', 'anchor', 'emoticons', 'link', 'unlink', '|', 'fullscreen', 'preview'
        ];
        return this.create(id, w, h, items, uops);
    }
    //简单文本编辑器
    //调用：setEditerSimple('contentSimple', '50%', '240px');
    ketool.simple= function (id, w, h, uops) {
        var items = ['source', 'print', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                    '|', 'table', 'pagebreak', 'emoticons', 'link', 'selectall', 'clearhtml', 'fullscreen', 'preview'
        ];
        return this.create(id, w, h, items, uops);
    }
    ketool.full= function (id, w, h, uploadJson) {
        uploadJson = uploadJson || this.uploadJson;
        return this.create(id, w, h, null, {
            imageUploadLimit: 20,
            imageSizeLimit: '5MB',
            imageFileTypes: '*.jpg;*.gif;*.png;*.bmp',
            uploadJson: uploadJson,
            items: ['source', '|', 'undo', 'redo', '|', 'preivew', 'print', 'template', 'code', 'cut', 'copy', 'paster',
                        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', '|',
                        'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', '/',
                        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                        'strikethrough', 'lineheight', 'removeformat', '|', 'anchor', 'emoticons', 'link', 'unlink', '|', 'image', 'multiimage', '|', 'fullscreen', 'preview'
            ]
        });
    }
    ketool.canUpImg = function (id, w, h, uops) {
        var ops = $.extend(true, {
            imageUploadLimit: 20,
            imageSizeLimit: '5MB',
            imageFileTypes: '*.jpg;*.gif;*.png;*.bmp',
            uploadJson: this.getUoloadToken(),
            items: ['source', 'print', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                    '|', 'table', 'pagebreak', 'emoticons', 'link', 'selectall', 'clearhtml', 'image', 'multiimage', 'fullscreen', 'preview'
            ]
        }, uops || {});
        return this.simple(id, w, h, ops);
    }
    window.setEditer = function () { return ketool.default.apply(ketool, arguments); }
    window.setEditerSimple = function () { return ketool.simple.apply(ketool, arguments); }
    window.removeEditer = function () { return ketool.remove.apply(ketool, arguments); }
    ketool.getUoloadToken=function (reload) {
        if (this.isGetUoloadToken && !reload) return this.uploadJson;
        var that = this;
        $.post("/Upload/Token/", {}, function (ret) {
            if (ret) {
                that.isGetUoloadToken = true;
                that.uploadJson = "/Upload/Start/?ke=1&timestamp=" + ret.timestamp + "&token=" + ret.token;
            }
        });
    }
    window.ketool = ketool;
})();

//可上传图片的编辑器
function setEditerImages(id, w, h, uploadJson) {
    var ops = uploadString ? { uploadJson: uploadJson } : {};
    return ketool.canUpImg(id, w, h);
}

//小日历
//调用：setJsCalendar('date', 'button', true);
function setJsCalendar(input, target, showtime) {
    Calendar.setup({
        inputField: input,
        trigger: target,
        onSelect: function () {
            this.hide();
        },
        showTime: showtime ? 24 : showtime,
        dateFormat: showtime ? '%Y-%m-%d %H:%M:%S' : '%Y-%m-%d'
    });
}

//大日历
function setJCal(name, callBack,extParam) {
    extParam = extParam || {};
    var dDates = {}
    var ops = $.extend({
        day: new Date(),
        days: 1,
        showMonths: 1,
        monthSelect: true,
        sDate: new Date(),
        dCheck: function (day) {
            if (dDates != null) {
                for (var i = 0; i < dDates.length; i++) {
                    var dday = new Date(dDates[i].date);
                    if (day.getTime() == dday.getTime())
                        return false;
                }
            }
            return true;
        },
        callback: callBack,
        dow: ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'],
        ml: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
    }, extParam)
    return $(name).jCal(ops);
}

//弹出框简单封装
(function () {
    function _replace(text) {
        if (!text) return text;
        if (typeof (text) != "string") return text;
        return text.replace(/\n/g, "<br />");
    }
    var showBox = function (text, status, btn) {
        text = _replace(text)
        return art.dialog({
            title: '系统提示',
            icon: status,
            content: text,
            lock: true,
            opacity: 0.5,
            cancel: true,
            cancelVal: '关闭',
            button: btn ? btn : false
        });
    }
    var noticBox = function (icon,text,callback,button,btnText) {
        text = _replace(text)
        if (button == null) {
            button = [{ name: btnText == null ? '关闭' : btnText, focus: true, callback: null }];
        }
        var d= art.dialog({
            title: '系统提示',
            icon: icon,
            content: text,
            lock: true,
            opacity: 0.5,
            close: callback,
            button: button
        });
        d._noGClose = true;
        return d;
    }
    messageBox = {
        notice:noticBox,
        //等同succeed 关闭带回调
        ok: function (text, callback,btnText) {
            return noticBox('succeed', text, callback, null, btnText);
        },
        //等同error 关闭带回调
        fail: function (text, callback) {
            return noticBox('error', text, callback);
        },
        succeed: function (text, btn) {
            return showBox(text, 'succeed', btn);
        },
        error: function (text, btn) {
            return showBox(text, 'error', btn);
        },
        warning: function (text, btn) {
            return showBox(text, 'warning', btn);
        },
        question: function (text, btn) {
            return showBox(text, 'question', btn);
        },
        openHtml: function (sTitle, sWidth, sHeight, sContent, btn, closeCall,dialongId,extParmas) {
            var ops={
                title: sTitle,
                content: sContent,
                opacity: 0.5,
                lock: true,
                cancel: true,
                cancelVal: '关闭',
                button: btn ? btn : false,
                close: closeCall,
                id: dialongId
            }
            if (sWidth) ops.width = sWidth;
            if (sHeight) ops.height = sHeight;
            if (extParmas) $.extend(ops, extParmas);
            var dialog = art.dialog(ops);
            //$(dialog.content()).css("padding", "10px 0px");
            return dialog;
        },
        openHtmlNoButton: function (sTitle, sWidth, sHeight, sContent, btn, closeCall) {
            return art.dialog({
                title: sTitle,
                width: sWidth,
                height: sHeight,
                content: sContent,
                opacity: 0.5,
                lock: true,
                button: btn ? btn : false,
                close: closeCall
            });
        },
        alert: function (text,close) {
            text = _replace(text)
            return art.dialog({
                title: '系统提示',
                content: text,
                lock: true,
                opacity: 0.5,
                ok: true,
                close:close
            });
        },
        close: function (id) {
            var list = art.dialog.list, d;
            if (!list) return;
            if (id) {
                d = list[id]
                if (d && !d._noGClose) d.close();
            } else {
                for (var i in list) {
                    d = list[i];
                    if (d && !d._noGClose) d.close();
                }
            }
        },
        confirm: function (text, callback) {
            return this.question(text, [{ name: '确定', focus: true, callback: callback }])
        },
        confirm2: function (text, okText, cancelText, okCallback, cancelCallback) {
            if (arguments.length == 2 && typeof(okText)=="function") {
                okCallback = okText;
                okText = null;
            }
            var btns = [{ name: okText == null ? '确定' : okText, focus: true, callback: okCallback }];
            var d= art.dialog({
                title: '系统提示',
                icon: 'question',
                content: text,
                lock: true,
                opacity: 0.5,
                cancel: true,
                cancelVal: cancelText == null ? '取消' : cancelText,
                close: cancelCallback,
                button: btns
            });
            d._noGClose = true;
            return d;
        }
    };
})();

//通用全选
$(document).ready(function () {
    $('.checkAll').live('click', function () {
        //if ($(this).attr('checked'))
        //    $('input[name="checkbox"]').attr('checked', true);
        //else
        //    $('input[name="checkbox"]').attr('checked', false);
        var chkall=this;
        var chks = $('input[name="checkbox"]');
        chks.each(function () {
            if ($(this).prop("disabled")) return;
            this.checked = chkall.checked;
        });
    });
});

//统计全选的值
function checkAll(getDisabled,isArr) {
    var deleteIds = {}, i = 0, ids = [];

    $('input[name="checkbox"]').each(function () {
        var chk = $(this);
        if (chk.val() && chk.attr('checked')) {
            //if (!getDisabled && chk.prop("disabled")) return;
            if (!isArr) deleteIds['deleteIds[' + i + ']'] = chk.val();
            else ids.push(chk.val());
            i++;
        }
    });
    deleteIds.length = i;
    return isArr ? ids : deleteIds;
}

//来电弹屏 
(function () { 
    callDialog = {
        goto: function (type) {
            switch (type) {
                case 1:
                    goto('/Services/Calls'); break;
                case 2:
                    goto('/Customer/AddCustomer'); break;
                case 3:
                    goto('/Customer/Contacts'); break;
            }
        },
        showContact: function (number,name, company, address) {
            var html = '',
                thatcolose = "callDialog.close('callModel" + number + "')"
            if (name) {
                html = '<div id="callModel' + number + '" class="callModel modal in" data-width="375px" style="width: 375px; display:none;">';
                html += '<div class="modal-header"><button type="button" id="closeCall" class="close" data-dismiss="modal" onclick="' + thatcolose + '">×</button><h3>来电提示</h3></div>';
                html += '<div class="modal-body" style="min-height: 155px; padding-top: 5px; ">';
                html += '<div class="ctop"><div style="float:left;" class="comeCall"></div>';
                html += '<div class="modal-cont w-248 right" style=" overflow:hidden; overflow-y:auto;"><ul class="topul">';
                html += '<li class="cname">' + name + '</li>';
                html += '<li class="cnum">' + number;
                if (myOCX.LocalNum) {
                    html += '&nbsp;<a id="softDialout" title="点击拨号' + number + '" target="_blank" onclick="ec_SoftDialOut(' + number + ')" style="font-size:10px;cursor:pointer;"><img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/pulldown.png"></a> ';
                    html += '<a id="stopSoftDialout" title="挂断" target="_blank" onclick="ec_StopSoftDialOut()" style="font-size:10px;cursor:pointer;display:none;"><img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/pullup.png"></a> ';
                }
                html += '<a title="百度搜索" target="_blank" href="http://www.baidu.com/s?wd=' + number + '"> <img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/c_baidu.jpg"></a>';
                html += '<a title="谷歌搜索" target="_blank" href="http://www.google.com.hk/search?q=' + number + '"> <img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/c_google.jpg"></a></li>';
                html += '</ul></div><div class="clear"></div></div>';
                html += '<div class="cbot"><ul class="botul">';
                html += '<li><span>客户名称：</span>' + company + '</li>';
                html += '<li><span>详细地址：</span>' + address + '</li>';
                html += '</ul></div></div>';
                html += '<div class="modal-footer"><input type="button" onclick="callDialog.goto(1)" class="btn btn-primary" value="新增来电" /></div>';
            } else {
                html = '<div id="callModel' + number + '" class="callModel modal in" style="width: 375px; display:none;">';
                html += '<div class="modal-header"><button type="button" id="closeCall" class="close" data-dismiss="modal" onclick="' + thatcolose + '">×</button><h3>来电提示</h3></div>';
                html += '<div class="modal-body" style="min-height: 155px; padding-top: 5px; ">';
                html += '<div class="ctop"><div style="float:left;" class="straCall"></div>';
                html += '<div class="modal-cont w-248 right" style=" overflow:hidden; overflow-y:auto;"><ul class="topul">';
                html += '<li class="cnot">未知来电</li>';
                html += '<li class="cnum">' + number + '&nbsp;';
                if (myOCX.LocalNum) {
                html += '<a id="softDialout" title="点击拨号' + number + '" target="_blank" onclick="ec_SoftDialOut(' + number + ')" style="font-size:10px;cursor:pointer;"><img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/pulldown.png"></a>';
                    html += '<a id="stopSoftDialout" title="挂断" target="_blank" onclick="ec_StopSoftDialOut()" style="font-size:10px;cursor:pointer; display:none;"><img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/pullup.png"></a>';
                }
                html += '<a title="百度搜索" target="_blank" href="http://www.baidu.com/s?wd=' + number + '"> <img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/c_baidu.jpg"></a>';
                html += '<a title="谷歌搜索" target="_blank" href="http://www.google.com.hk/search?q=' + number + '"> <img style="margin-top:5px;" src="/Content/Themes/base/Images/ico/c_google.jpg"></a></li>';
                html += '</ul></div><div class="clear"></div></div>';
                html += '<div class="cbot">';
                html += '<div class="notcall">无来电号码相关信息记录</div>';
                html += '</div></div>';
                html += '<div class="modal-footer"><input type="button"  onclick="callDialog.goto(2)" class="btn btn-primary" value="新增客户" />';
                html += '<input type="button" onclick="callDialog.goto(3)" class="btn btn-primary" value="新增联系人" /></div>';
            } 
            $('#callModel' + number).remove();
            $('.callModel').each(function (i) {
                var top = $(this).offset().top - 264; 
                $(this).css({ 'top': top + 'px' }); 
            });
            $('body').append(html);
            var postion = $(window);
            var top = (postion.height() - 264);
            var left = (postion.width() - 120);
            $('#callModel' + number).css({ 'top': top + 'px', 'left': left + 'px' }).fadeIn(); 
        },
        showMessage: function (array) {
            var close = "callDialog.close('messageCall')";
            var html = '';
            html += '<div id="messageCall" class="callModel modal in" data-width="375px" style="width: 375px; display:none;">';
            html += '<div class="modal-header"><button type="button" id="closeCall" class="close" data-dismiss="modal" onclick="' + close + '">×</button><h3>消息提示</h3></div>';
            html += '<div class="modal-body" style="min-height: 155px; padding-top: 5px; ">';
            html += '<div class="modal-cont w-248 right" style=" overflow:hidden; overflow-y:auto; width: 340px;height:150px;">';
            html += '<ul class="msgul">';
            array.forEach(function (item) {
                html += '<li><p style="margin-bottom:0px;"><a href="#/Tools/Email/' + item.Id + '/view" onclick="' + close + '">' + showSlice(item.MailTitle, 26) + '</a></p><span>' + item.MailSendTime + '</span></li>';
            })
            html += '</ul></div><div class="clear"></div></div>';

            if (array.length > 0) {
                if (myCache.time != array[0].MailSendTime) { //加入缓存
                    myCache.time = array[0].MailSendTime
                    $('#messageCall').remove();
                    $('body').append(html);
                    var postion = $(window);
                    var top = (postion.height() - 220);
                    var left = (postion.width() - 120);
                    $('#messageCall').css({ 'top': top + 'px', 'left': left + 'px' }).fadeIn();
                }
            }
        },
        close: function (id) { 
            var that = $('#' + id)
            var thatTop = that.offset().top;
            that.remove();
            $('.callModel').each(function (i) { 
                var top = $(this).offset().top;
                if (top < thatTop) {
                    top = top + 254;
                   $(this).css({ 'top': top + 'px'});
                }
            }); 
        }
    }
})();

var myCache = {};

//字符串阶段
function showSlice(target, length, truncation) {
    //length，新字符串长度，truncation，新字符串的结尾的字段,返回新字符串
    length = length || 30
    truncation = truncation === void (0) ? "..." : truncation
    return target.length > length ? target.slice(0, length - truncation.length) + truncation : String(target)
}

//来电呼叫弹屏
function MyFuncCallIn(s1, callInNum) {
    avalon.log("call in ,line:" + s1 + ",num:" + callInNum);
    var CBCRM = avalon.vmodels.CBCRM;
    var user = CBCRM.memberShip;
    var show = callInNum && (user.IsSuperAdmin || (myOCX.LocalNum && myOCX.LocalNum.indexOf(s1) > -1));
    if (show) {
        CBCRM.callCenter(callInNum);
        //$.get('/Customer/ContactsByCall', { 'telphone': callInNum }, function (ret) {
        //    if (ret.data.IsExist) {
        //        var customer = ret.data.contacts.Customer
        //        var name = ret.data.contacts.Name
        //        var address = customer.Address
        //        var customerName = customer.Name
        //        callDialog.showContact(callInNum, name, customerName, address)
        //    }
        //    else
        //        callDialog.showContact(callInNum);
        //});
    }
}
//软拨号
function ec_SoftDialOut(RemoteNum) {
    if (myOCX.LocalNum) {
        var LocalNum = myOCX.LocalNum.split(',')[0] 
        myOCX.EC_SoftDialOut(LocalNum, RemoteNum.replace("(", "").replace(")", "").replace("-", ""))
        $("#softDialout").css("display", "none")
        $("#stopSoftDialout").css("display", "inline")
    } 
} 
//挂断软拨号
function ec_StopSoftDialOut() { 
    if (myOCX.LocalNum) {
        var LocalNum = myOCX.LocalNum.split(',')[0]
        myOCX.EC_StopSoftDialOut(LocalNum)
        $("#softDialout").css("display", "inline")
        $("#stopSoftDialout").css("display", "none")
    } 
}

//判断是否图片格式
function isImage(src) {
    var i = src.indexOf('.');
    if (i > 0) {
        var ex = src.substring(i + 1, src.length);
        if (ex == 'jpg' || ex == 'gif' || ex == 'bmp' || ex == 'png')
            return true;
        else
            return false;
    }
    else return false;
}

//判断是否EXCEL格式
function isExcle(src) {
    var i = src.indexOf('.');
    if (i > 0) {
        var ex = src.substring(i + 1, src.length);
        if (ex == 'xls' || ex == 'xlsx')
            return true;
        else
            return false;
    }
    else return false;
}

//常用日期格式
(function () {
    function createDate(d) {
        var date = d || new Date();
        var now = {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate(),
            hours: date.getHours(),
            minutes: date.getMinutes(),
            seconds: date.getSeconds()
        }
        return now;
    }
    
    telesa = {
        datetime: {
            ymd: function (d) {//年月日
                var now = createDate(d);
                return now.year + '-'
                    + (now.month < 10 ? ('0' + now.month) : now.month) + '-'
                    + (now.day < 10 ? ('0' + now.day) : now.day)
            },
            now: function (d) {//年月日时分秒
                var now = createDate(d);
                return now.year + '-'
                    + (now.month < 10 ? ('0' + now.month) : now.month) + '-'
                    + (now.day < 10 ? ('0' + now.day) : now.day) + ' '
                    + (now.hours < 10 ? ('0' + now.hours) : now.hours) + ':'
                    + (now.minutes < 10 ? ('0' + now.minutes) : now.minutes) + ':'
                    + (now.seconds < 10 ? ('0' + now.seconds) : now.seconds);
            },
            cut: function (d) {//年月日时分
                var now = createDate(d);
                return now.year + '-'
                    + (now.month < 10 ? ('0' + now.month) : now.month) + '-'
                    + (now.day < 10 ? ('0' + now.day) : now.day) + ' '
                    + (now.hours < 10 ? ('0' + now.hours) : now.hours) + ':'
                    + (now.minutes < 10 ? ('0' + now.minutes) : now.minutes);
            }
        }
    }
})()

//颜色函数
function colorWithIndex(index) {
    var colors = [];
    var borders = [];
    var d = "666666888888aaaaaabbbbbbdddddda32929cc3333d96666e69999f0c2c2b1365fdd4477e67399eea2bbf5c7d67a367a994499b373b3cca2cce1c7e15229a36633cc8c66d9b399e6d1c2f029527a336699668cb399b3ccc2d1e12952a33366cc668cd999b3e6c2d1f01b887a22aa9959bfb391d5ccbde6e128754e32926265ad8999c9b1c2dfd00d78131096184cb05288cb8cb8e0ba52880066aa008cbf40b3d580d1e6b388880eaaaa11bfbf4dd5d588e6e6b8ab8b00d6ae00e0c240ebd780f3e7b3be6d00ee8800f2a640f7c480fadcb3b1440edd5511e6804deeaa88f5ccb8865a5aa87070be9494d4b8b8e5d4d47057708c6d8ca992a9c6b6c6ddd3dd4e5d6c6274878997a5b1bac3d0d6db5a69867083a894a2beb8c1d4d4dae54a716c5c8d8785aaa5aec6c3cedddb6e6e41898951a7a77dc4c4a8dcdccb8d6f47b08b59c4a883d8c5ace7dcce";
    var theme = 1;
    var init = theme * 6;
    for (var i = init; i < d.length; i = i + 30) {
        colors.push(d.substr(i, 6));
        borders.push(d.substr(i - 6, 6));
    }
    if (index >= 0 && index < colors.length)
        return '#' + colors[index];
    return "#FFFFFF";
};

//幻灯片
function slideShow(title) {
    $('#gallery a').css({ opacity: 0.0 });
    $('#gallery a:first').css({ opacity: 1.0 });
    $('#container .caption').css({ opacity: 0.7 });
    $('#container .caption').css({ width: $('#gallery a').find('img').css('width') });
    $('#container .content').html(title).animate({ opacity: 0.7 }, 400);
    slideId = setInterval('gallery()', 6000);
}

function gallery() {
    var current = ($('#gallery a.show') ? $('#gallery a.show') : $('#gallery a:first'));
    var next = ((current.next().length) ? ((current.next().hasClass('caption')) ? $('#gallery a:first') : current.next()) : $('#gallery a:first'));
    var caption = next.find('img').attr('rel');
    next.css({ opacity: 0.0 }).addClass('show').animate({ opacity: 1.0 }, 1000);
    current.animate({ opacity: 0.0 }, 1000).removeClass('show');
    $('#container .caption').animate({ opacity: 0.0 }, { queue: false, duration: 0 }).animate({ height: '1px' }, { queue: true, duration: 300 });
    $('#container .caption').animate({ opacity: 0.7 }, 28).animate({ height: '28px' }, 300);
    $('#container .content').html(caption);
}

//业务明细状态
function setContractDetailState(type) {
    var result = ''
    switch (type) {
        case 0: result = "未付款"; break;
        case 1: result = "已付部分"; break;
        case 2: result = "已付清"; break;
    }
    return result
}

//自定义显示列
(function () {
    customBox = {
        show: function (obj) {
            var offset = obj.offset();
            var custom = $('.cb_custom');
            custom.toggle();
        }
    }
})()

//自定义显示列事件
$(document).ready(function () {
    $('.cb_ul li').on({
        mouseover: function () { $(this).css('background-color', '#F1F1F1'); },
        mouseout: function () { $(this).css('background-color', '#FFFFFF'); }
    })
    $('body').on({
        click: function (event) {
            var target = event.target.className
            if (target != 'cb_label' && target != 'pad10' && target != 'custom')
                $('.cb_custom').css('display', 'none');
        }
    });
})
function frameSubmit(url,method,data,callback) {
    data = data || {};
    ///*Math.random()*/
    var rnd = 2015, ifrid = "_actframe_" + rnd, body = document.body;
    var ifr = $("#" + ifrid);
    if(ifr.length==0) ifr = $('<iframe  src="about:blank" name="' + ifrid + '" id="' + ifrid + '" width="1" height="1" style="display:none;"></iframe>').appendTo(body);
    ifr.bind("load", function () {
        //ifr.remove();
        if (callback) callback.call(ifr)
    });
    if (method == "post") {
        var fid = "_actform_" + rnd;
        var form = $("#" + fid);
        if(form.length==0) form = $("<form></form>").attr({
            id:fid,name:fid,method:"post",action:url,target:ifrid
        }).appendTo(body);
        form.empty();
        for (var key in data) {
            var val = data[key];
            if (typeof (val) == "function") continue;
            $('<input />').attr({ type: "hidden",value:val,name:key }).appendTo(form);
        }
        form.submit();
        form.remove();
    } else {
        url += "?" + $.param(data);
        ifr.attr("src", url);
    }
}
//导出当前页到Excel
function ExportExcel(fileName, colModel, list) {
    var table = ["<table class='bd'>"];
    table.push("<tr>");
    for (var key in colModel) {
        table.push("<th>" + colModel[key] + "</th>");
    }
    table.push("</tr>");
    list.forEach(function (item) {
        table.push("<tr>");
        for (var key in colModel) {
            var val = item[key] != null ? item[key] : "";
            table.push("<td>" + val + "</td>");
        }
        table.push("</tr>");
    });
    table.push("</table>");
    var hel = $("<input type='hidden' name='html'>").val(table.join(""));
    var fel = $("<input type='hidden' name='fileName'>").val(fileName);
    var form = $("<form id='_actform_' method='post'></form>").hide().appendTo(document.body);
    form.append(hel).append(fel);
    form.append($("<input type='submit' name='_btnact_' value='submit' />"))
    form.attr("action", "/Tools/ExportExcel");
    form.submit();
    form.remove();
}
function ExportWord(html, fileName) {
    var hel = $("<input type='hidden' name='html'>").val(html),
        fel = $("<input type='hidden' name='fileName'>").val(fileName),
        ctel = $("<input type='hidden' name='contentType'>").val("application/ms-word"),
        extel= $("<input type='hidden' name='ext'>").val("doc"),
        form = $("<form id='_actform_' method='post'></form>").hide().appendTo(document.body);
    form.append(hel).append(fel).append(ctel).append(extel);
    form.append($("<input type='submit' name='_btnact_' value='submit' />"))
    form.attr("action", "/Tools/ExportExcel");
    form.submit();
    form.remove();
}
//释放UI
function destroyui(uis) {
    if (typeof (uis) == "string") uis = uis.split(",");
    var ui;
    uis.forEach(function (item) {
        ui = avalon.vmodels[item];
        if (ui && ui.destroy) ui.destroy();
        delete avalon.vmodels[item];
        ui = null;
    });
}
//初始化Grid,准备撤掉，使用createGrid
function initGridvm(vm, list, entityId, path, modelFactory) {
    var that = this;
    vm.checkall = false;
    vm.$watch("checkall", function (n) {
        list.forEach(function (item) {
            item.checked = n;
        });
    });
    vm.initChecked = function (list) {
        vm.checkall = false;
        list.forEach(function (item) {
            if (item.checked == null) item.checked = false;
            if (item.nocheck == null) item.nocheck = false;
        });
        return list;
    }
    vm.getChecked = function () {
        var a = [];
        list.forEach(function (item) {
            if (item.checked && !item.nocheck) a.push(item);
        });
        return a;
    }
    vm.getIds = function (name) {
        var a = vm.getChecked();
        var o = { length: a.length }, arr = [];
        a.forEach(function (item, i) {
            if (name) o[name + "[" + i + "]"] = item.Id;
            else arr.push[item.Id];
        });
        return name ? o : arr;
    }
    vm.doRemoveAll = function () {
        var that = this, ids = vm.getIds("deleteIds");
        if (ids.length == 0) {
            messageBox.error("请选择数据！");
            return;
        }
        messageBox.confirm2("您确定要删除数据吗？", function () {
            if (vm.removeAll) vm.removeAll.call(that, ids);
        });

    }
    vm.doRemove = function (item) {
        var that = this;
        messageBox.confirm2("您确定要删除数据吗", function () {
            if (vm.remove) vm.remove.call(that, item);
        })
    }
    vm.getEntity = function (id, callback) {
        var entity;
        if (!id) {
            entity = $.extend(true, {}, modelFactory.create(entityId));
            callback(entity);
        } else {
            $.each(list.$model, function () {
                if (this.Id == id) {
                    entity = this;
                    callback(entity);
                    return false;
                }
            });
            if (!entity) {
                $.get(path || that.path, { id: id }, function (ret) {
                    var CBCRM = avalon.vmodels.CBCRM;
                    if (!ret.result) return CBCRM.showResult(ret);
                    var arr = ret.data.Source;
                    if (!arr || arr.length == 0)
                        messageBox.warning("抱歉，该数据不存在或已经被删除！");
                    else
                        callback(arr[0]);
                });
            }
        }
    }
}
function createGrid(ops) {
    ops = ops || {};
    var dops = {
        listkey: "Source", totalkey: "RecordTotal", pageindexkey: "PageIndex", idkey: "Id", method: "get",
        multiple: true, gridmsg: "", showmsg: false,loading:false
    };
    ops = $.extend(true, {}, dops, ops);
    var lang = ops.$lang || {};
    var grid = { checkall: false, list: [], $params: [], pageid: ops.pageid, total: 0, gridmsg: lang.NoListData, loading: false,multiple:ops.multiple }, gvm;
    if (ops.pageid) {
        ops.pageOps = $.extend({}, {
            paging: function (pageIndex, pageSize) {
                var data = gvm.createQuery();
                data.pageSize = pageSize
                data.pageIndex = pageIndex
                gvm.loadData(data);
            }
        }, ops.pageOps || {});
        if (ops.pageinitload != null) ops.pageOps.initload = ops.pageinitload;
        grid.$pageOps = ops.pageOps
    }
    grid.init = grid.bindWatch = function () {
        gvm = this;
        gvm.$watch("checkall", function (n) {
            gvm.list.forEach(function (item) {
                if (!item.nocheck && !item.chkDisabled) item.checked = n;
            })
        });
        gvm.$watch("loading", function (n) {
            if (n) {
                gvm.gridmsg = "loading...";
                gvm.showmsg = true;
            } else {
                gvm.gridmsg = "";
                gvm.showmsg = false;
            }
        });
    }
    grid.initList = function (list, total,pageIndex) {
        if (total == null) total = list.length;
        gvm.gridmsg = total > 0 ? "" : lang.NoListData;
        gvm.checkall = false
        list.forEach(function (item) {
            gvm.initItem(item);
        });
        gvm.list = list;
        gvm.total = total;
        var page = gvm.getPage();
        if (page) {
            if (pageIndex) page.setIndex(pageIndex);
            page.total = total;
            
        }
        gvm.list.forEach(function (item,index) {
            gvm.watchItem(item, index);
        })
        gvm.loading = false;
        return list;
    }
    grid.initItem = function (item) {
        if (item.checked == null) item.checked = false;
        if (item.nocheck == null) item.nocheck = false;
        if (item.chkDisabled == null) item.chkDisabled = false;
    }
    grid.watchItem = function (item, index) {
        item.$watch("checked", function (n, o) {
            if (!ops.multiple && n) {
                gvm.list.forEach(function (m) {
                    if (item[ops.idkey] != m[ops.idkey]) m.checked = false;
                });
            }
            var callback = gvm.onSelectChange;
            if (typeof (callback) == "function") callback.call(gvm, index, item, n, o);
        });
    }
    grid.addRow = function (item) {
        gvm.initItem(item);
        gvm.list.push(item);
        gvm.total += 1;
        var index=gvm.list.length-1;
        gvm.watchItem(gvm.list[index], index);
        gvm.gridmsg = "";
    }
    grid.updateRow = function (index,item) {
        //gvm.initItem(item);
        //gvm[index] = item;
        //gvm.watchItem(gvm.list[index], index);
        //return gvm.list[index];
        var oitem = gvm[index];
        avalon.mix(oitem, item);
    }
    grid.updateRowById = function (id, item) {
        var index = gvm.getIndex(id);
        if (index == null) return null;
        return gvm.updateRow(index, item);
    }
    grid.getRow = function (id) {
        return findArr(gvm.list, function (item) {return item[ops.idkey]==id });
    }
    grid.getIndex = function (id) {
        return findArr(gvm.list, function (item) { return item[ops.idkey] == id }, "@index");
    }
    grid.getPage = function () {
        if (!ops.pageid) return null;
        return avalon.vmodels[ops.pageid];
    }
    grid.destroyPage = function () {
        var page = gvm.getPage();
        if (page && page.destroy) page.destroy();
    }
    grid.selectId = function (id) {
        var item = gvm.getRow(id);
        if (item) item.checked = true;
    }
    grid.select = function (index) {
        gvm.doSelect(index, true);
    }
    grid.unSelect = function (index) {
        gvm.doSelect(index, false);
    }
    grid.doSelect = function (index,b) {
        if (index > gvm.list.length) {
            console.log("所选的值：" + index + "超过Grid的最大行数：" + gvm.list.length);
            return;
        }
        var item = gvm.list[index];
        item.checked = b;
    }
    grid.selectAll = function (b) {
        if (this && this.nodeType == 1) b = this.checked;
        console.log(this)
        gvm.list.forEach(function (item) {
            if (item.chkDisabled) return;
            item.checked = b;
        })
    }
    grid.getChecked = function (tselect) {
        var list = gvm.list;
        var a = where(list, function (item) {
            return (item.checked && !item.nocheck);
        },tselect)
        return a;
    }
    grid.getCheckedIds = function (name) {
        var a = gvm.getChecked();
        var o = { length: a.length }, arr = [];
        a.forEach(function (item, i) {
            if (name) o[name + "[" + i + "]"] = item.Id;
            else arr.push(item.Id);
        });
        return name ? o : arr;
    }
    //建议用removeChecked
    grid.removeAll = function () {
        gvm.removeChecked(true, null);
    }
    grid.removeChecked = function (isConfirm,msg,msg2) {
        if (isConfirm == null) isConfirm = true;
        if (msg == null) msg = "您确定要删除数据吗？";
        if (msg2 == null) msg2 = "请选择数据！";
        var ids = gvm.getCheckedIds("deleteIds");
        if (ids.length == 0) {
            messageBox.error(msg2);
            return;
        }
        var ids2 = gvm.getCheckedIds();
        var rows = gvm.getChecked();
        var args = [ids, ids2, rows];
        var callback = gvm.onRemove;
        if (!isConfirm) {
            if (callback) callback.apply(gvm, args);
            return;
        }
        messageBox.confirm2(msg, function () {
            if (callback) callback.apply(gvm, args);
        });

    }
    grid.remove=function(item,index,isConfirm,msg){
        gvm.removeById(item.Id,index,isConfirm,msg);
    }
    grid.removeById = function (id,index,isConfirm,msg) {
        var ids = { "deleteIds[0]": id, length: 1 };
        var ids2 = [id];
        var callback = gvm.onRemove;
        if (index == null) {
            $.each(gvm.list.$model, function (i) {
                if (this[ops.idkey] == id) {
                    index = i;
                    return false;
                }
            });
        }
        var rows = gvm.list[index];
        var args=[ids, ids2, rows];
        if (isConfirm == null) isConfirm = true;
        if (!isConfirm) {
            if (callback) callback.apply(gvm, args);
            return;
        }
        if (!msg) msg = "您确定要删除数据吗";
        messageBox.confirm2(msg, function () {
            if (callback) callback.apply(gvm, args);
        })
    }
    grid.removeRow = function (row) {
        if (typeof (row) == "number") {
            var row = findArr(gvm.list, row);
        }
        if (row != null) {
            gvm.list.remove(row);
            gvm.total -= 1;
            if (gvm.total == 0) gvm.gridmsg = lang.NoListData;
        }
    }
    grid.removeIndex = function (index) {
        gvm.list.removeAt(index);
        gvm.total -= 1;
        if (gvm.total == 0) gvm.gridmsg = lang.NoListData;
    }
    grid.view = function (id) {
        gvm.getEntity(id, function (entity) {
            var callback = gvm.onView;
            if (callback) callback.call(this, entity);
        })
    }
    grid.clear = function () {
        gvm.initList([], 0);
        gvm.checkall = false;
    }
    grid.getEntity = function (id, callback,isQuery) {
        var list = gvm.list, entity;
        if (!id) {
            entity = ops.modelFactory.create(ops.entityId);
            if (callback) callback(entity);
            return entity;
        } else {
            if (!isQuery) {
                $.each(list.$model, function () {
                    if (this.Id == id) {
                        entity = this;
                        callback(entity);
                        return false;
                    }
                });
            }
            if (!entity) {
                var eurl = ops.entityUrl;
                if (eurl) eurl = eurl.replace("{id}", id);
                var url =  eurl || ops.url;
                $[ops.method](url, { id: id }, function (ret) {
                    var CBCRM = avalon.vmodels.CBCRM;
                    if (!ret.result) return CBCRM.showResult(ret);
                    if (!eurl) {
                        var arr = ret.data[ops.listkey];
                        if (!arr || arr.length == 0)
                            messageBox.warning("抱歉，该数据不存在或已经被删除！");
                        else
                            callback(arr[0], ret);
                    } else {
                        var entity = ops.entityKey ? ret.data[ops.entityKey] : ret.data;
                        callback(entity, ret);
                    }
                });
            }
        }
    }
    grid.doSearch = function (cb) {
        var data = gvm.createQuery();
        var page = gvm.getPage();
        if (page) {
            data.pageIndex = 1;
            data.pageSize = page.pagesize
        }
        gvm.loadData(data,cb);
    }
    grid.loadData = function (data, cb) {
        gvm.$params = data || {};
        //gvm.clear();
        gvm.gridmsg = lang.LoadingMsg;
        $[ops.method](ops.url, data, function (ret) {
            if (!ret || !ret.result) return CBCRM.showResult(ret);
            var list = ops.listkey ? ret.data[ops.listkey] : ret.data, total = ret.data[ops.totalkey], pageindex = ret.data[ops.pageindexkey];
            var p = null;
            if (typeof (gvm.onLoadData) == "function") p = gvm.onLoadData.call(gvm, ret, list);
            if (p) {
                list = p.Source; total = p.RecordTotal; pageindex = p.PageIndex;
            }
            gvm.initList(list, total, pageindex);
            if (typeof (cb) == "function") cb.call(gvm, ret);
            if (typeof (gvm.afterLoadData) == "function") gvm.afterLoadData.call(gvm, ret, gvm.list);
        })
    }
    grid.reloadData = function (cb) {
        var data = gvm.$params || {};
        gvm.loadData(data,cb);
    }
    grid.showLoad = function (msg) {
        gvm.loading = true;
        if (msg != null) gvm.gridmsg = msg;
    }
    grid.destroy = function () {
        if (!ops.pageid) return;
        var page = gvm.getPage();
        if (page && page.destroy) {
            page.destroy();
        }
    }
    for (var key in ops) {
        var _t = typeof (ops[key]);
        if (_t == "function") { grid[key] = ops[key];}
    }
    if (ops.extParam) {
        for (var key in ops.extParam) {
            grid[key] = ops.extParam[key];
        }
    }
    return grid;
}
//初始化查询对象,只有一个查询对象时候使用这个比较方便
function initQuerys(vm, onQueryChange) {
    vm.queryData = {};
    vm.queryMore = false;
    vm.hasQuery = false;
    vm.hasLength = 0;
    vm.queryHistory = [];
    vm.queryHistoryMax=5;
    //最终生成查询数据的方法
    vm.createQuery = function () {
        var data = {};
        vm.hasQuery = false;
        for (var name in vm.queryData.$model) {
            var c = vm.queryData[name], val = c.val;
            if (val != null && val.$model != null) val = val.$model;
            if (val !== "" && val !== null) {
                if (c.syncLabel) {//为true
                    c.valLabel = val;
                }
                if (!c.noRemove) {//为true表示条件不会被clear方法清除
                    if (!vm.hasQuery) vm.hasQuery = true;
                    vm.hasLength++;
                }
                if ($.isArray(val)) {
                    $.extend(data, jsonToSubmit(name, val));
                } else {
                    data[name] = val;
                }
            }
        }
        return data;
    }
    vm.addQuery = function (name, val, label, disableChange,addHistory) {
        if (addHistory == null) addHistory = true;
        var c = vm.queryData[name];
        c.val = val;
        if (val === "" || val === null) return vm.removeQuery(name, disableChange);
        if (c.items) {
            $.each(c.items, function (i, item) {
                if (item.val == c.val) {
                    item.curr = true;
                    if (label==null) label = item.label;
                } else {
                    item.curr = false;
                }
            });
        }
        var b;
        if (!disableChange) b=vm.queryChange(name, val, "add");
        c.valLabel = "";
        if (label) {
            c.valLabel = label;
            if (addHistory && b!==false) {
                vm.queryHistory.push({ name: name, val: val, label: label });
                if (vm.queryHistory.length > vm.queryHistoryMax) vm.queryHistory.splice(0, 1);
            }
        }
        
    }
    vm.addQuerys = function (data, disableChange) {
        var name, val;
        for (var key in data) {
            name = key;
            val = data[key];
            if (typeof (val) == "function") continue;
            vm.addQuery(name, val, null, true);
        }
        if (!disableChange) vm.queryChange(name, val, "add");
    }
    vm.removeQuery = function (name, disableChange) {
        var c = vm.queryData[name];
        if (c.noRemove) return;
        var oldval = c.val;
        c.val = "";
        c.valLabel = "";
        if (c.items) {
            c.items.forEach(function (item) {
                if (item.val == c.val) item.curr = true;
                else item.curr = false;
            });
        }
        if (!disableChange) {
            if (vm.onRemoveQuery) vm.onRemoveQuery(name, "remove");
            vm.queryChange(name, oldval, "remove");
        } else {
            vm.createQuery();
        }
    }
    vm.clearQuery = function (isChange) {
        for (var name in vm.queryData.$model) {
            vm.removeQuery(name, true);
        }
        if (isChange) {
            if (vm.onRemoveQuery) vm.onRemoveQuery(name, "clear");
            vm.queryChange("all", "", "clear");
        }
    }
    vm.queryChange = function (name, val, type) {
        var data = vm.createQuery();
        if (vm.onQueryChange) vm.onQueryChange(data, name, val, type);
    }
    vm.onQueryChange = onQueryChange ? onQueryChange : function (data, name, val, type) {
    }
}
//构建一个查询对象，可以多个查询对象一起使用
function createQuerys(data,onQueryChange) {
    var query = { data: data || {}, hasQuery: false,hasLength:0, history: [], historyMax: 5 };
    var vm = {};
    query.setVm = function () {
        vm = this;
    }
    query.createQuery = function () {
        var data = {};
        vm.hasQuery = false;
        vm.hasLength = 0;
        for (var name in vm.data.$model) {
            var c = vm.data.$model[name];
            if (c.val != "") {
                if (!c.noRemove) {
                    if (!vm.hasQuery) vm.hasQuery = true;
                    vm.hasLength++;
                }
                data[name] = c.val;
            }
        }
        return data;
    }
    query.addQuery = function (name, val, label, disableChange, addHistory) {
        if (addHistory == null) addHistory = true;
        if (val == "" || val == null) return vm.removeQuery(name, disableChange);
        var c = vm.data[name];
        c.val = val;
        if (c.items) {
            $.each(c.items, function (i, item) {
                if (item.val == c.val) {
                    item.curr = true;
                    if (!label) label = item.label;
                } else {
                    item.curr = false;
                }
            });
        }
        c.valLabel = "";
        if (label) {
            c.valLabel = label;
            if (addHistory) {
                vm.history.push({ name: name, val: val, label: label });
                if (vm.history.length > vm.historyMax) vm.history.splice(0, 1);
            }
        }
        if (!disableChange) vm.queryChange(name, val, "add");
    }
    query.removeQuery = function (name, disableChange) {
        var c = vm.data[name];
        c.val = "";
        c.valLabel = "";
        if (c.items) {
            c.items.forEach(function (item) {
                if (item.val == c.val) item.curr = true;
                else item.curr = false;
            });
        }
        if (!disableChange) vm.queryChange(name, c.val, "remove");
    }
    query.clearQuery = function () {
        for (var name in vm.data.$model) {
            var c = vm.data[name];
            vm.removeQuery(name, true);
        }
        vm.queryChange("all", "", "clear");
    }
    query.queryChange = function (name, val, type) {
        var data = vm.createQuery();
        if (vm.onQueryChange) vm.onQueryChange(data, name, val, type);
    }
    query.onQueryChange = onQueryChange ? onQueryChange : function (data, name, val, type) {
    }
    return query;
}
function createZtree(id,ops,dataSource) {
    var dops = {
        async: {
            url: '',
            type: 'GET',
            enable: false,
            autoParam: ["Id=id"],
            dataFilter: function (treeId, parentNode, responseData) {
                var ret = []
                if (responseData.data && responseData.data.length) {
                    ret = responseData.data
                }
                return ret
            }
        },
        data: {
            simpleData: {
                enable: true,
                idKey: 'Id'
            },
            key: {
                name: 'Name'
            }
        },
        view: {}
    }
    var options = $.extend(true, {}, dops, ops || {});
    var el = typeof (id) == "string" ? $("#" + id) : id;
    return $.fn.zTree.init(el, options, dataSource);
}
//json对象转成提交给MVC的参数格式
function jsonToSubmit(name, list) {
    if (arguments.length == 1) {
        var data = {},val;
        for (var key in name) {
            val=name[key];
            if (typeof (val) == "function") continue;
            if (typeof (val) == "object") $.extend(data, jsonToSubmit(key, val));
            else data[key] = val;
        }
        return data;
    }
    var o={},isArr = $.isArray(list);
    if (!isArr) list = list.$model || list;
    $.each(list, function (i, item) {
        var m =item==null?item: item.$model || item;
        if (!isArr) {
            o[name + "." + i] = m;
            return;
        }
        if (typeof (m) == "object") {
            for (var k in m) {
                if (typeof (m[k]) == "function") continue;
                o[name + "[" + i + "]." + k] = m[k];
            }
        } else {
            o[name + "[" + i + "]"] = m;
        }
    });
    return o;
}
//以json的数据形式提交
function jsonPost(url,data,callback) {
    var jsonStr = JSON.stringify(data);
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data:jsonStr,
        success:callback
    })
}
//以弹窗的形式打开页面
function openWin(title, ctrid, url, w, h, btns, onload, onclose,extParam) {
    var CBCRM = avalon.vmodels.CBCRM;
    var args = {};
    if (arguments.length == 1) {
        args = title;
        ctrid = args.ctrid, url = args.url, w = args.w, h = args.h;
        btns = args.btns, onload = args.onload, onclose = args.onclose;
        extParam = args.extParam, title = args.title;
    }
    var dialog = null, ops = {
        title: title,
        content: '',
        opacity: 0.5,
        lock: true,
        cancel: true,
        cancelVal: '关闭',
        button: btns,
        close: function () {
            var ovm = avalon.vmodels[ctrid];
            if (ovm && ovm.destroy) ovm.destroy();
            ovm = null;
            delete avalon.vmodels[ctrid];
        }
    }
    if (w) ops.width = w;
    if (h) ops.height = h;
    if (extParam) $.extend(ops, extParam);
    function fillBefore(tmpl, lang, contentId, module, vmodel) {
        ops.close = function () {
            if (onclose) onclose.call(this, tmpl, lang, contentId, module, vmodel);
            if (ctrid) avalon.vmodels[ctrid] = null;
        }
        dialog = art.dialog(ops);
        var content = $(dialog.content()).html(tmpl);
        content.css("padding", "10px").css("padding-bottom", "10px");
        if (onload) var b = onload.call(dialog, tmpl, vmodel, lang, content, module);
        if (b === false) return false;
        avalon.scan(content[0], vmodel);
        if (args.afterload) {
            avalon.nextTick(function () {
                args.afterload.call(dialog, tmpl, vmodel, lang, content, module);
            });
        }
        return false;
    }
    CBCRM.fillContentBefore = args.fillContentBefore || fillBefore;
    //CBCRM.onLoadModuleBefore = function (arg) {
    //    //arg={ tmpl: tmpl, module: m, lang: lang }
    //    //avalon.vmodels[ctrid] = null;
    //}
    CBCRM.loadModule(url, null, function (action,module) {
        if (ctrid != null) action = ctrid;
        else ctrid = action;
        var vm = avalon.vmodels[ctrid];
        if (typeof (args.vmready) === "function") args.vmready.call(this, vm,dialog,module);
    });
    var win = {
        close: function () {
            if (dialog) {
                dialog.close();
                dialog = null;
            }
        }
    }
    return win;
}
//打开页面内的模板，可以是某个id的模板或者直接html
function openTmpl(vm, title, tmplId, w, h, button, onClose,extParam,isContent) {
    var CBCRM = avalon.vmodels.CBCRM;
    var defArgs = { padding: "10px 0px" }, defPading2 = "20px", args = {};
    if (arguments.length == 1) {
        args=vm,title = vm.title; tmplId = vm.tmplId || vm.tmplid;
        w = vm.w; h = vm.h; button = vm.button || vm.btns; onClose = vm.onClose || vm.onclose;
        extParam = vm.extParam; isContent = vm.isContent || vm.iscontent; vm = vm.vm;
    }
    if (!args.padding) args.padding = defArgs.padding;
    if (args.padding == "def2") args.padding = defPading2;
    var ops = {
        title: title,
        content: '',
        opacity: 0.5,
        lock: true,
        cancel: true,
        cancelVal: '关闭',
        button: button,
        close: function () {
            if (styles) styles.remove();
            if (typeof (onClose) == "function") onClose.call(this);
        }
    }
    if (w) ops.width = w;
    if (h) ops.height = h;
    if (args.dialogId) ops.id = args.dialogId;
    if (extParam) $.extend(ops, extParam);
    var dialog = art.dialog(ops),url=args.url,styles;
    if (url) {
        if (url.indexOf(".html") == -1) url += ".html";
        CBCRM.loadView(url, function (tmpl) {
            if (!tmplId) _setContent(tmpl);
            else _setContent(_getTmplById(tmplId, tmpl), tmpl);
        })
    } else {
        if (!isContent) _setContent(_getTmplById(tmplId, args.tmpl));
        else _setContent(tmplId);
    }
    function _getTmplById(id,tmpl) {
        id = "#" + id;
        var c = tmpl ? $(tmpl) : $(document), el = c.find(id);
        if (el.length == 0) el = c.filter(id);
        return el.text();
    }
    function _setContent(contentTmpl,pageTmpl) {
        var content = $(dialog.content());
        var wrap = ["<div style='"];
        if (w) wrap.push("width:" + w + "px;")
        wrap.push("'>");
        wrap.push(contentTmpl);
        wrap.push("</div>");
        content.html(wrap.join(""));
        if (pageTmpl) {
            styles = pageTmpl.filter("style");
            styles.add(pageTmpl.find("style"));
            content.append(styles);
        }
        content.css("padding", args.padding).css("margin", "0 auto;");
        if (args.padding == "0px") content.css("margin-bottom", "-5px");//修正content离底部有5px距离的问题
        if (args.css) content.css(args.css);
        avalon.scan(content[0], vm);
        var onLoad = args.onLoad || args.onload || args.afterload, onScan = args.onScan || args.onscan || args.afterscan;
        if (typeof (onLoad) == "function") onLoad.call(dialog, ops);
        if (typeof (onScan) == "function") {
            avalon.nextTick(function () {
                onScan.call(dialog, ops);
            });
        }
    }

    return dialog;
}
//获取数据字典
function getDicts(dicts, mvvm,callBack) {
    var arr = [], key = "",v, ids = {};
    for (var k in dicts) {
        key = k;
        v = dicts[k];
        arr.push(v);
        ids[v] = k;
    }
    $.post('/Settings/GetDictionarys', jsonToSubmit("ids", arr))
    .done(function (ret) {
        if (ret.result && ret.data) {
            if (arr.length == 1) {
                if (mvvm[key]) mvvm[key] = ret.data;
            } else {
                ret.data.forEach(function (item) {
                    key=ids[item.DictionaryId];
                    if (mvvm[key] && mvvm[key].push) mvvm[key].push(item);
                });
            }
            if (callBack) callBack(ret);
        }
    })
}
//按函数查找数组区配元素
function findArr(arr, fn,key) {
    if(typeof(fn)!="function"){
        var id = fn;
        var t = typeof (id);
        fn = function (item,i) {
            if (t == "number") return item.Id == id;
            else if (t == "string") return item.Id.toString() == id;
            else {
                var b = true;
                for (var k in id) {
                    if (id[k] != item[k]) {
                        b = false;
                        break;
                    }
                }
                return b;
            }
        }
    }
    for (var i = 0, l = arr.length; i < l; i++) {
        if (fn(arr[i],i)) {
            if(key=="@index")return i;
            return key ? arr[i][key] : arr[i];
        }
    }
    return null;
}
function findChecked(list,copy) {
    var a = [];
    list.forEach(function (item) {
        if (item.checked) {
            if (!copy) a.push(item);
            else a.push(avalon.mix(true, {}, item));
        }
    });
    return a;
}
function getDefDict(dicts,key) {
    if (key == null) key = "Id";
    var dict = findArr(dicts, function (c) { return c.IsDefault });
    if (dict == null && dicts.length > 0) dict = dicts[0];
    return dict == null ? "" : dict[key];
}
//递归获取树节点下所有的id
function getNodeIds(node, iconSkin,key) {
    if (key == null) key = "Id";
    var ids = [];
    if (iconSkin) {
        if (node.iconSkin == iconSkin) ids.push(node[key]);
    } else ids.push(node[key]);
    if (!node.children) return ids;
    for (var i = 0, l = node.children.length; i < l; i++) {
        ids = ids.concat(getNodeIds(node.children[i], iconSkin,key));
    }
    return ids;
}
//根据id获取ztree的某个节点
function getzTreeNode(nodes, id) {
    for (var i0 = 0, l0 = nodes.length; i0 < l0; i0++) {
        var node = nodes[i0];
        if (node.Id == id) return node;
        if (node.children) {
            node = getzTreeNode(node.children, id);
            if (node != null) return node;
        }
    }
    return null;
}
//遍历数组、对象，返回符合条件的结果
//obj需要遍历的数组、对象
//
function where(obj,fn,tselect) {
    var arr = [], data = {}, isArr = $.isArray(obj);
    var tIsString = (typeof (tselect) == "string"), tIsArray = $.isArray(tselect);
    if (tIsArray) {
        for (var i = 0, l = tselect.length; i < l; i++) arr[i] = [];
    }
    $.each(obj, function (i,item) {
        if (!isArr && typeof (item) == "function") return;
        if (fn===true || fn(item,i)) {
            if (isArr) {
                if (!tselect) arr.push(item);
                else {
                    if (tIsString) arr.push(item[tselect]);
                    else if (tIsArray) {
                        for (var j = 0, l = tselect.length; j < l; j++) arr[j].push(item[tselect[j]]);
                    }
                    else {
                        var newItem = {};
                        for (var key in tselect) {
                            var val = item[key], oldv = tselect[key]
                            if (val == null && typeof (oldv) == "string") val = item[oldv];
                            if (val == null) val = oldv;
                            newItem[key] = val;
                        }
                        arr.push(newItem);
                    }
                }
            }
            else data[i] = item;
        }
    })
    return isArr ? arr : data;
}
function arrSum(arr, fn) {
    var c = 0, isStr = typeof (fn) == "string";
    arr.forEach(function (item,i) {
        if (isStr) c = c + parseFloat(item[fn], 10);
        else c = c + fn(item, i);
    })
    return c;
}
//配置信息读取与保存
var Config = {
    get: function (config, callback) {
        $.get("/Settings/GetSettingConfigs", { cname: config.cname }, function (ret) {
            if (ret.result && ret.data && ret.data.length > 0) {
                if (!config.configs) config.configs = {};
                ret.data.forEach(function (item) {
                    config.configs[item.Name] = item.Value;
                });
                if (callback) callback(config.configs);
            }
        });
    },
    set: function (config, callback) {
        var list = [], configs = config.configs;
        for (var key in configs) {
            list.push({ Cname: config.cname, Name: key, Value: configs[key] });
        }
        var data = jsonToSubmit("configs", list);
        $.post("/Settings/UpdateSettingConfigs", data, function (ret) {
            if (callback) callback(ret);
        });
    },
    set: function (config, callback) {
        var list = [], configs = config.configs;
        for (var key in configs) {
            list.push({ Cname: config.cname, Name: key, Value: configs[key] });
        }
        var data = jsonToSubmit("configs", list);
        $.post("/Settings/UpdateSettingConfigs", data, function (ret) {
            if (callback) callback(ret);
        });
    },
    getOne: function (config, callback) {
        $.get("/Settings/GetSettingConfigsOne", config, function (ret) {
            if (ret.result && ret.data) {
                if (callback) callback(ret.data.config);
            }
        });
    },
    setOne: function (config, callback) {
        $.post("/Settings/UpdateSettingConfigsOne", config, function (ret) {
            if (callback) callback(ret);
        });
    }
};
//快速检索区域展开或收缩
function quickwordShow() {
    var isshow = $(this).prop('isshow');
    var fn = isshow ? "hide" : "show";
    $('.quickword.hide')[fn]();
    $(this).prop('isshow', !isshow)
    $('.quickwordul .quickwordmore').html(isshow ? '更多选项<span class="quickdown"></span>' : '收起<span class="quickup"></span>')
}

//异步上传(需要HTML5支持)
function CBCRMUpload(cfg) {
    if (!window.FormData) {
        alert("你的浏览器不支持此上传功能");
    }
    //如果是null or undefined 返回true, 否则false
    this.isNullOrUndefined = function (v, errMsg) {
        if (!v) {
            alert(errMsg);
            return true;
        }
        return false;
    };
    var cfg = cfg || {};
    if (this.isNullOrUndefined(cfg.url, "上传路径不能为空")) return;

    this.id = cfg.id;
    this.method = cfg.method || "POST";
    this.url = cfg.url;
    this.async = !cfg.sync;
    this.resultType = cfg.resultType || "json";
    this.formData = cfg.formData;
    this.xhr = new XMLHttpRequest();

    //超时事件 配置格式：timeout : xxx,onTimeout: function(event){}
    if (cfg.timeout) {
        this.xhr.timeout = cfg.timeout;
        this.xhr.ontimeout = cfg.onTimeout || function (event) {
            alert('连接超时');
        };
    }

    //发送过程事件 配置格式:onProgress: function(loaded, total)
    if (cfg.onProgress) { //发送数据过程
        this.xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                cfg.onProgress(e.loaded, e.total);
            }
        };
    }

    //上传完成事件
    if (cfg.onComplete) {
        this.xhr.onload = function (event) {
            var res = event.target.responseText;
            if (cfg.resultType === 'json') {
                if ((typeof JSON) === 'undefine') {
                    res = eval("(" + res + ")");
                } else {
                    res = JSON.parse(res);
                }
            }
            cfg.onComplete(res);
        };
    }

    //发出请求
    this.start = function () {
        this.xhr.open(this.method, this.url, this.async);
        this.xhr.send(this.formData);
    };
};

//单位转换
function setUnit(val) {
    var kUnit = 1024 * 1024
    var mUnit = 1024 * 1024 * 1024
    if (val < kUnit) {
        return (val / 1024).toFixed(2) + 'K'
    } else if (val >= kUnit && val <= mUnit) {
        return ((val / 1024) / 1024).toFixed(2) + 'M'
    } else
        return val;
}
//按需复制另一个实体的值
function extendValue(m1, m2, map) {
    map = map || {};
    if (typeof (map) == "string") {
        map.split(",").forEach(function (k) {
            if (m2[k] != null) m1[k] = m2[k];
        })
    } else {
        for (var key in m1) {
            if (map[key] != null) m1[key] = m2[map[key]];
            else {
                if (m2[key] != null && typeof (m2[key]) != "object") m1[key] = m2[key];
            }
        }
    }
    return m1;
}
function msdropdown(e) {
    var ele = $(this);
    if (e.over) ele.addClass("open");
    else ele.removeClass("open");
}
//扩展回车时间
avalon.bindingHandlers.enter = function (data,vmodels) {
    data.param = "enter"
    var removeFn,ele;
    data.specialBind = function (elem, callback) {
        ele = elem;
        removeFn = avalon.bind(elem, "keyup", function (e) {
            if (e.keyCode == 13) {
                callback.call(elem,e);
            }
        });
    }
    data.specialUnbind = function () {
        avalon.unbind(ele, "keyup", removeFn);
    }
    avalon.bindingHandlers.on.apply(0, arguments)
}
//扩展鼠标悬停事件
avalon.bindingHandlers.mhover = function (data, vmodels) {
    data.param = "mhover"
    var fnover, fnout,ele;
    data.specialBind = function (elem, callback) {
        ele = elem;
        fnover=avalon.bind(elem, "mouseover", function (e) {
            e.over = true;
            callback.call(this, e);
        });
        fnout=avalon.bind(elem, "mouseout", function (e) {
            e.over = false;
            callback.call(this, e);
        });
    }
    data.specialUnbind = function () {
        avalon.unbind(ele, "mouseover", fnover);
        avalon.unbind(ele, "mouseout", fnout);
    }
    avalon.bindingHandlers.on.apply(0, arguments)
}