o2.js 100.7 KB
Newer Older
NoSubject's avatar
NoSubject 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/** ***** BEGIN LICENSE BLOCK *****
 * |------------------------------------------------------------------------------|
 * | O2OA 活力办公 创意无限    o2.js                                                 |
 * |------------------------------------------------------------------------------|
 * | Distributed under the AGPL license:                                          |
 * |------------------------------------------------------------------------------|
 * | Copyright © 2018, o2oa.net, o2server.io O2 Team                              |
 * | All rights reserved.                                                         |
 * |------------------------------------------------------------------------------|
 *
 *  This file is part of O2OA.
 *
 *  O2OA is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  O2OA is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ***** END LICENSE BLOCK ******/


/* load o2 Core
 * |------------------------------------------------------------------------------|
 * |addReady:     o2.addReady(fn),                                                |
 * |------------------------------------------------------------------------------|
 * |load:         o2.load(urls, callback, reload)                                 |
 * |loadCss:      o2.loadCss(urls, dom, callback, reload, doc)                    |
 * |------------------------------------------------------------------------------|
 * |typeOf:       o2.typeOf(o)                                                    |
 * |------------------------------------------------------------------------------|
 * |uuid:         o2.uuid()                                                       |
 * |------------------------------------------------------------------------------|
 */
NoSubject's avatar
NoSubject 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
//Element.firstElementChild Polyfill
(function(constructor) {
    if (constructor &&
        constructor.prototype &&
        constructor.prototype.firstElementChild == null) {
        Object.defineProperty(constructor.prototype, 'firstElementChild', {
            get: function() {
                var node, nodes = this.childNodes, i = 0;
                while (node = nodes[i++]) {
                    if (node.nodeType === 1) {
                        return node;
                    }
                }
                return null;
            }
        });
    }
})(window.Node || window.Element);

NoSubject's avatar
NoSubject 已提交
60 61 62 63 64 65 66 67 68 69 70
(function(){
    var _href = window.location.href;
    var _debug = (_href.indexOf("debugger")!==-1);
    var _par = _href.substr(_href.lastIndexOf("?")+1, _href.length);
    var _lp = "zh-cn";
    if (_par){
        var _parList = _par.split("&");
        for (var i=0; i<_parList.length; i++){
            var _v = _parList[i];
            var _kv = _v.split("=");
            if (_kv[0].toLowerCase()==="lg") _lp = _kv[1];
R
roo00 已提交
71
            if (_kv[0].toLowerCase()==="lp") _lp = _kv[1];
NoSubject's avatar
NoSubject 已提交
72 73
        }
    }
NoSubject's avatar
NoSubject 已提交
74 75
    this.o2 = window.o2 || {};
    this.o2.version = {
NoSubject's avatar
NoSubject 已提交
76 77 78
        "v": "5.1.1",
        "build": "2020.06.12",
        "info": "O2OA 活力办公 创意无限. Copyright © 2020, o2oa.net O2 Team All rights reserved."
NoSubject's avatar
NoSubject 已提交
79 80 81
    };
    if (!this.o2.session) this.o2.session ={
        "isDebugger": _debug,
82
        "path": "../o2_core/o2"
NoSubject's avatar
NoSubject 已提交
83 84 85 86 87 88 89 90 91 92 93 94
    };
    this.o2.language = _lp;
    this.o2.splitStr = /\s*(?:,|;)\s*/;

    //     this.o2 = {
    //     "version": {
    //         "v": "2.3.1",
    //         "build": "2019.07.31",
    //         "info": "O2OA 活力办公 创意无限. Copyright © 2018, o2oa.net O2 Team All rights reserved."
    //     },
    //     "session": {
    //         "isDebugger": _debug,
95
    //         "path": "../o2_core/o2"
NoSubject's avatar
NoSubject 已提交
96 97 98 99 100
    //     },
    //     "language": _lp,
    //     "splitStr": /\s*(?:,|;)\s*/
    // };

NoSubject's avatar
NoSubject 已提交
101
    this.wrdp = this.o2;
NoSubject's avatar
NoSubject 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114

    var debug = function(reload){
        if (reload){
            window.location.assign(_href + ((_href.indexOf("?")==-1) ? "?" : "&")+"debugger");
        }else{
            if (!o2.session.isDebugger){
                o2.session.isDebugger = true;
                if (o2.session.isMobile || layout.mobile) o2.load("../o2_lib/eruda/eruda.js");
            }
        }
    };
    this.o2.debug = debug;

NoSubject's avatar
NoSubject 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    var _attempt = function(){
        for (var i = 0, l = arguments.length; i < l; i++){
            try {
                arguments[i]();
                return arguments[i];
            } catch (e){}
        }
        return null;
    };
    var _typeOf = function(item){
        if (item == null) return 'null';
        if (item.$family != null) return item.$family();
        if (item.constructor == window.Array) return "array";

        if (item.nodeName){
            if (item.nodeType == 1) return 'element';
            if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
        } else if (typeof item.length == 'number'){
            if (item.callee) return 'arguments';
        }
        return typeof item;
    };
    this.o2.typeOf = _typeOf;

    var _addListener = function(dom, type, fn){
        if (type == 'unload'){
            var old = fn, self = this;
            fn = function(){
                _removeListener(dom, 'unload', fn);
                old();
            };
        }
        if (dom.addEventListener) dom.addEventListener(type, fn, !!arguments[2]);
        else dom.attachEvent('on' + type, fn);
    };
    var _removeListener = function(dom, type, fn){
        if (dom.removeEventListener) dom.removeEventListener(type, fn, !!arguments[2]);
        else dom.detachEvent('on' + type, fn);
    };

    //http request class
    var _request = (function(){
        var XMLHTTP = function(){ return new XMLHttpRequest(); };
        var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); };
        var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP'); };
        return _attempt(XMLHTTP, MSXML2, MSXML);
    })();
NoSubject's avatar
NoSubject 已提交
162
    this.o2.request = _request;
NoSubject's avatar
NoSubject 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    var _returnBase = function(number, base) {
        return (number).toString(base).toUpperCase();
    };
    var _getIntegerBits = function(val, start, end){
        var base16 = _returnBase(val, 16);
        var quadArray = new Array();
        var quadString = '';
        var i = 0;
        for (i = 0; i < base16.length; i++) {
            quadArray.push(base16.substring(i, i + 1));
        }
        for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
            if (!quadArray[i] || quadArray[i] == '')
                quadString += '0';
            else
                quadString += quadArray[i];
        }
        return quadString;
    };
    var _rand = function(max) {
        return Math.floor(Math.random() * (max + 1));
    };
NoSubject's avatar
NoSubject 已提交
186 187
    this.o2.addListener = _addListener;
    this.o2.removeListener = _removeListener;
NoSubject's avatar
NoSubject 已提交
188 189

    //uuid
NoSubject's avatar
NoSubject 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    var _uuid = function(){
        var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
        var dc = new Date();
        var t = dc.getTime() - dg.getTime();
        var tl = _getIntegerBits(t, 0, 31);
        var tm = _getIntegerBits(t, 32, 47);
        var thv = _getIntegerBits(t, 48, 59) + '1';
        var csar = _getIntegerBits(_rand(4095), 0, 7);
        var csl = _getIntegerBits(_rand(4095), 0, 7);

        var n = _getIntegerBits(_rand(8191), 0, 7)
            + _getIntegerBits(_rand(8191), 8, 15)
            + _getIntegerBits(_rand(8191), 0, 7)
            + _getIntegerBits(_rand(8191), 8, 15)
            + _getIntegerBits(_rand(8191), 0, 15);
        return tl + tm + thv + csar + csl + n;
    };
    this.o2.uuid = _uuid;


NoSubject's avatar
NoSubject 已提交
210 211 212 213 214
    var _runCallback = function(callback, key, par, bind){
        var b = bind || callback;
        var type = o2.typeOf(callback).toLowerCase();
        if (!key) key = "success";

215
        if (key.toLowerCase()==="success" && (type==="function" || type==="o2_async_function")){
NoSubject's avatar
NoSubject 已提交
216
            callback.apply(b, par);
NoSubject's avatar
NoSubject 已提交
217
        }else{
218
            if (type==="function" || type==="object" || type==="o2_async_function"){
219 220 221
                var name = ("on-"+key).camelCase();
                if (callback[name]){
                    callback[name].apply(b, par);
NoSubject's avatar
NoSubject 已提交
222
                }else{
223
                    if (callback[key]) callback[key].apply(b, par);
NoSubject's avatar
NoSubject 已提交
224
                }
NoSubject's avatar
NoSubject 已提交
225 226
            }
        }
NoSubject's avatar
NoSubject 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249


        // if (typeOf(callback).toLowerCase() === 'function'){
        //     if (key.toLowerCase()==="success"){
        //         callback.apply(b, par);
        //     }else{
        //         if (callback[key]){
        //             callback[key].apply(b, par);
        //         }else{
        //             var name = ("on-"+key).camelCase();
        //             if (callback[name]) callback[name].apply(b, par);
        //         }
        //     }
        // }else{
        //     if (typeOf(callback).toLowerCase()==='object'){
        //         if (callback[key]){
        //             callback[key].apply(b, par);
        //         }else{
        //             var name = ("on-"+key).camelCase();
        //             if (callback[name]) callback[name].apply(b, par);
        //         }
        //     }
        // }
NoSubject's avatar
NoSubject 已提交
250 251 252
    };
    this.o2.runCallback = _runCallback;

NoSubject's avatar
NoSubject 已提交
253 254

    //load js, css, html adn all.
NoSubject's avatar
NoSubject 已提交
255
    var _getAllOptions = function(options){
NoSubject's avatar
NoSubject 已提交
256 257
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
258
        var type = (options && options.type) || "text/javascript";
NoSubject's avatar
NoSubject 已提交
259 260 261 262
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
263
            "type": type,
NoSubject's avatar
NoSubject 已提交
264
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
265
            "dom": (options && options.dom) || document.body,
NoSubject's avatar
NoSubject 已提交
266 267
            "module": (options && options.module) || null,
            "noConflict": (options && options.noConflict) || false,
NoSubject's avatar
NoSubject 已提交
268
            "bind": (options && options.bind) || null,
R
roo00 已提交
269
            "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'debugger
NoSubject's avatar
NoSubject 已提交
270 271 272
        }
    };
    var _getCssOptions = function(options){
NoSubject's avatar
NoSubject 已提交
273 274
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
275 276 277 278
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
279
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
280 281 282 283
            "dom": (options && options.dom) || null
        }
    };
    var _getJsOptions = function(options){
NoSubject's avatar
NoSubject 已提交
284 285
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
286
        var type = (options && options.type) || "text/javascript";
NoSubject's avatar
NoSubject 已提交
287 288 289
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
NoSubject's avatar
NoSubject 已提交
290
            "sequence": (!(options && options.sequence == false)),
NoSubject's avatar
NoSubject 已提交
291
            "type": type,
NoSubject's avatar
NoSubject 已提交
292
            "doc": doc
NoSubject's avatar
NoSubject 已提交
293 294 295
        }
    };
    var _getHtmlOptions = function(options){
NoSubject's avatar
NoSubject 已提交
296 297
        var doc = (options && options.doc) || document;
        if (!doc.unid) doc.unid = _uuid();
NoSubject's avatar
NoSubject 已提交
298 299 300 301
        return {
            "noCache": !!(options && options.nocache),
            "reload": !!(options && options.reload),
            "sequence": !!(options && options.sequence),
NoSubject's avatar
NoSubject 已提交
302
            "doc": doc,
NoSubject's avatar
NoSubject 已提交
303
            "dom": (options && options.dom) || null,
NoSubject's avatar
NoSubject 已提交
304 305
            "module": (options && options.module) || null,
            "noConflict": (options && options.noConflict) || false,
NoSubject's avatar
NoSubject 已提交
306
            "bind": (options && options.bind) || null,
NoSubject's avatar
NoSubject 已提交
307
            "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'
NoSubject's avatar
NoSubject 已提交
308 309
        }
    };
NoSubject's avatar
NoSubject 已提交
310 311 312 313 314 315 316 317 318 319 320 321
    _filterUrl = function(url){
        if (o2.base){
            if (url.indexOf(":")===-1){
                var s = url.substring(0, url.indexOf("/")+1);
                var r = url.substring(url.indexOf("/")+1, url.length);
                if ("../"===s || "./"===s || "/"===s){
                    return s+o2.base+r;
                }else{
                    return o2.base+url
                }
            }
        }
322

NoSubject's avatar
NoSubject 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336
        // if (!window.layout) window.layout = {};
        // if (!window.layout.config){
        //     new Request.JSON({
        //         url: "../x_desktop/res/config/config.json",
        //         secure: false,
        //         method: "get",
        //         noCache: true,
        //         async: false,
        //         onSuccess: function(responseJSON, responseText){
        //             window.layout.config = responseJSON;
        //         }.bind(this),
        //     }).send();
        // }

337 338 339 340 341 342 343 344 345
        if (window.layout && layout.config && layout.config.urlMapping){
            for (var k in layout.config.urlMapping){
                var regex = new RegExp(k);
                if (regex.test(url)){
                    return url.replace(regex, layout.config.urlMapping[k]);
                }
            }
        }

NoSubject's avatar
NoSubject 已提交
346 347 348
        return url;
    };
    this.o2.filterUrl = _filterUrl;
NoSubject's avatar
NoSubject 已提交
349
    var _xhr_get = function(url, success, failure, completed){
NoSubject's avatar
NoSubject 已提交
350
        var xhr = new _request();
NoSubject's avatar
NoSubject 已提交
351
        url = _filterUrl(url);
NoSubject's avatar
NoSubject 已提交
352 353 354
        xhr.open("GET", url, true);

        var _checkCssLoaded= function(_, err){
NoSubject's avatar
NoSubject 已提交
355 356 357 358 359
            if (!(xhr.readyState == 4)) return;
            if (err){
                if (completed) completed(xhr);
                return;
            }
NoSubject's avatar
NoSubject 已提交
360 361 362 363 364

            _removeListener(xhr, 'readystatechange', _checkCssLoaded);
            _removeListener(xhr, 'load', _checkCssLoaded);
            _removeListener(xhr, 'error', _checkCssErrorLoaded);

NoSubject's avatar
NoSubject 已提交
365
            if (err) {if (failure) failure(xhr); return}
NoSubject's avatar
NoSubject 已提交
366 367 368
            var status = xhr.status;
            status = (status == 1223) ? 204 : status;
            if ((status >= 200 && status < 300))
NoSubject's avatar
NoSubject 已提交
369
                if (success) success(xhr);
NoSubject's avatar
NoSubject 已提交
370 371 372 373
                else if ((status >= 300 && status < 400))
                    if (failure) failure(xhr);
                    else
                        failure(xhr);
NoSubject's avatar
NoSubject 已提交
374
            if (completed) completed(xhr);
NoSubject's avatar
NoSubject 已提交
375 376 377 378 379 380 381 382
        };
        var _checkCssErrorLoaded= function(err){ _checkCssLoaded(err) };

        if ("load" in xhr) _addListener(xhr, "load", _checkCssLoaded);
        if ("error" in xhr) _addListener(xhr, "load", _checkCssErrorLoaded);
        _addListener(xhr, "readystatechange", _checkCssLoaded);
        xhr.send();
    };
NoSubject's avatar
NoSubject 已提交
383
    this.o2.xhr_get = _xhr_get;
NoSubject's avatar
NoSubject 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    var _loadSequence = function(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun){
        loadSingle(ms[n], function(module){
            if (module) thisLoaded.push(module);
            n++;
            if (fun) fun(module);
            if (n===ms.length){
                if (cb) cb(thisLoaded);
            }else{
                _loadSequence(ms, cb, op, n, thisLoaded, loadSingle, uuid, fun);
            }
        }, op, uuid);
    };
    var _loadDisarray = function(ms, cb, op, thisLoaded, loadSingle, uuid, fun){
        var count=0;
        for (var i=0; i<ms.length; i++){
            loadSingle(ms[i], function(module){
                if (module) thisLoaded.push(module);
                count++;
                if (fun) fun(module);
                if (count===ms.length) if (cb) cb(thisLoaded);
            }, op, uuid);
        }
    };

NoSubject's avatar
NoSubject 已提交
408
    //load js
NoSubject's avatar
NoSubject 已提交
409 410
    //use framework url
    var _frameworks = {
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        "o2.core": ["../o2_core/o2/o2.core.js"],
        "o2.more": ["../o2_core/o2/o2.more.js"],
        "ie_adapter": ["../o2_core/o2/ie_adapter.js"],
        "jquery": ["../o2_lib/jquery/jquery.min.js"],
        "mootools": ["../o2_lib/mootools/mootools-1.6.0_all.js"],
        "ckeditor": ["../o2_lib/htmleditor/ckeditor4114/ckeditor.js"],
        "ckeditor5": ["../o2_lib/htmleditor/ckeditor5-12-1-0/ckeditor.js"],
        "raphael": ["../o2_lib/raphael/raphael.js"],
        "d3": ["../o2_lib/d3/d3.min.js"],
        "ace": ["../o2_lib/ace/src-min-noconflict/ace.js","../o2_lib/ace/src-min-noconflict/ext-language_tools.js"],
        "monaco": ["../o2_lib/vs/loader.js"],
        "JSBeautifier": ["../o2_lib/JSBeautifier/beautify.js"],
        "JSBeautifier_css": ["../o2_lib/JSBeautifier/beautify-css.js"],
        "JSBeautifier_html": ["../o2_lib/JSBeautifier/beautify-html.js"],
        "JSONTemplate": ["../o2_lib/mootools/plugin/Template.js"],
        "kity": ["../o2_lib/kityminder/kity/kity.js"],
        "kityminder": ["../o2_lib/kityminder/core/dist/kityminder.core.js"]
NoSubject's avatar
NoSubject 已提交
428 429 430
    };
    var _loaded = {};
    var _loadedCss = {};
NoSubject's avatar
NoSubject 已提交
431
    var _loadedHtml = {};
NoSubject's avatar
NoSubject 已提交
432 433
    var _loadCssRunning = {};
    var _loadCssQueue = [];
434
    var _loadingModules = {};
NoSubject's avatar
NoSubject 已提交
435

NoSubject's avatar
NoSubject 已提交
436 437 438 439
    var _loadSingle = function(module, callback, op){
        var url = module;
        var uuid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uuid : addr_uri+"?v="+uuid;
NoSubject's avatar
NoSubject 已提交
440 441 442 443
        var key = encodeURIComponent(url+op.doc.unid);
        if (!op.reload) if (_loaded[key]){
            if (callback)callback(); return;
        }
NoSubject's avatar
NoSubject 已提交
444

445 446 447 448 449 450 451 452
        if (_loadingModules[key]){
            if (!_loadingModules[key].callbacks) _loadingModules[key].callbacks = [];
            _loadingModules[key].callbacks.push(callback);
        }else{
            _loadingModules[key] = { callbacks: [callback] };

            var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
            var s = op.doc.createElement('script');
NoSubject's avatar
NoSubject 已提交
453
            s.type = op.type || "text/javascript";
454 455 456
            head.appendChild(s);
            s.id = uuid;
            s.src = this.o2.filterUrl(url);
NoSubject's avatar
NoSubject 已提交
457

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            var _checkScriptLoaded = function(_, isAbort, err){
                if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
                    var scriptObj = {"module": module, "id": uuid, "script": s, "doc": op.doc};
                    if (!err) _loaded[key] = scriptObj;
                    _removeListener(s, 'readystatechange', _checkScriptLoaded);
                    _removeListener(s, 'load', _checkScriptLoaded);
                    _removeListener(s, 'error', _checkScriptErrorLoaded);
                    if (!isAbort || err){
                        if (err){
                            if (s) head.removeChild(s);
                            while (_loadingModules[key].callbacks.length){
                                (_loadingModules[key].callbacks.shift())();
                            }
                            //if (callback)callback();
                        }else{
                            //head.removeChild(s);
                            while (_loadingModules[key].callbacks.length){
                                (_loadingModules[key].callbacks.shift())(scriptObj);
                            }
                            //if (callback)callback(scriptObj);
                        }
NoSubject's avatar
NoSubject 已提交
479 480
                    }
                }
481 482 483 484 485
            };
            var _checkScriptErrorLoaded = function(e, err){
                console.log("Error: load javascript module: "+module);
                _checkScriptLoaded(e, true, "error");
            };
NoSubject's avatar
NoSubject 已提交
486

487 488 489 490
            if ('onreadystatechange' in s) _addListener(s, 'readystatechange', _checkScriptLoaded);
            _addListener(s, 'load', _checkScriptLoaded);
            _addListener(s, 'error', _checkScriptErrorLoaded);
        }
NoSubject's avatar
NoSubject 已提交
491 492
    };

NoSubject's avatar
NoSubject 已提交
493 494 495
    var _load = function(urls, options, callback){
        var ms = (_typeOf(urls)==="array") ? urls : [urls];
        var op =  (_typeOf(options)==="object") ? _getJsOptions(options) : _getJsOptions(null);
496 497 498 499 500 501 502
        var cbk = (_typeOf(options)==="function") ? options : callback;

        var cb = cbk;
        if (typeof define === 'function' && define.amd){
            define.amd = false;
            cb = (cbk) ? function(){define.amd = true; cbk();} : function(){define.amd = true;}
        }
NoSubject's avatar
NoSubject 已提交
503 504 505 506 507 508 509 510 511

        var modules = [];
        for (var i=0; i<ms.length; i++){
            var url = ms[i];
            var module = _frameworks[url] || url;
            if (_typeOf(module)==="array"){
                modules = modules.concat(module)
            }else{
                modules.push(module)
NoSubject's avatar
NoSubject 已提交
512 513
            }
        }
NoSubject's avatar
NoSubject 已提交
514 515 516 517 518
        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(modules, cb, op, 0, thisLoaded, _loadSingle);
        }else{
            _loadDisarray(modules, cb, op, thisLoaded, _loadSingle);
NoSubject's avatar
NoSubject 已提交
519 520 521 522
        }
    };
    this.o2.load = _load;

NoSubject's avatar
NoSubject 已提交
523
    //load css
NoSubject's avatar
NoSubject 已提交
524 525 526 527
    var _loadSingleCss = function(module, callback, op, uuid){
        var url = module;
        var uid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
NoSubject's avatar
NoSubject 已提交
528

NoSubject's avatar
NoSubject 已提交
529
        var key = encodeURIComponent(url+op.doc.unid);
NoSubject's avatar
NoSubject 已提交
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        if (_loadCssRunning[key]){
            _loadCssQueue.push(function(){
                _loadSingleCss(module, callback, op, uuid);
            });
            return;
        }

        if (_loadedCss[key]) uuid = _loadedCss[key]["class"];
        if (op.dom) _parseDom(op.dom, function(node){ if (node.className.indexOf(uuid) == -1) node.className += ((node.className) ? " "+uuid : uuid);}, op.doc);

        var completed = function(){
            if (_loadCssRunning[key]){
                _loadCssRunning[key] = false;
                delete _loadCssRunning[key];
            }
            if (_loadCssQueue && _loadCssQueue.length){
                (_loadCssQueue.shift())();
            }
        };

        if (_loadedCss[key])if (!op.reload){
            if (callback)callback(_loadedCss[key]);
            completed();
            return;
        }
NoSubject's avatar
NoSubject 已提交
555 556 557 558 559

        var success = function(xhr){
            var cssText = xhr.responseText;
            try{
                if (cssText){
NoSubject's avatar
NoSubject 已提交
560
                    cssText = cssText.replace(/\/\*(\s|\S)*?\*\//g, "");
NoSubject's avatar
NoSubject 已提交
561
                    if (op.bind) cssText = cssText.bindJson(op.bind);
NoSubject's avatar
NoSubject 已提交
562
                    if (op.dom){
NoSubject's avatar
NoSubject 已提交
563

NoSubject's avatar
NoSubject 已提交
564 565
                        var rex = new RegExp("(.+)(?=\\{)", "g");
                        var match;
NoSubject's avatar
NoSubject 已提交
566
                        var prefix = "." + uuid + " ";
NoSubject's avatar
NoSubject 已提交
567
                        while ((match = rex.exec(cssText)) !== null) {
NoSubject's avatar
NoSubject 已提交
568 569 570 571 572
                            // var rule = prefix + match[0];
                            // cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
                            // rex.lastIndex = rex.lastIndex + prefix.length;

                            var rulesStr = match[0];
NoSubject's avatar
NoSubject 已提交
573 574 575 576
                            if (rulesStr.substr(0,1)=="@" || rulesStr.indexOf("%")!=-1){
                                // var begin = 0;
                                // var end = 0;

NoSubject's avatar
NoSubject 已提交
577 578

                            }else{
NoSubject's avatar
NoSubject 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592
                                if (rulesStr.indexOf(",")!=-1){
                                    var rules = rulesStr.split(/\s*,\s*/g);
                                    rules = rules.map(function(r){
                                        return prefix + r;
                                    });
                                    var rule = rules.join(", ");
                                    cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
                                    rex.lastIndex = rex.lastIndex + (prefix.length*rules.length);

                                }else{
                                    var rule = prefix + match[0];
                                    cssText = cssText.substring(0, match.index) + rule + cssText.substring(rex.lastIndex, cssText.length);
                                    rex.lastIndex = rex.lastIndex + prefix.length;
                                }
NoSubject's avatar
NoSubject 已提交
593
                            }
NoSubject's avatar
NoSubject 已提交
594 595
                        }
                    }
NoSubject's avatar
NoSubject 已提交
596
                    var style = op.doc.createElement("style");
NoSubject's avatar
NoSubject 已提交
597
                    style.setAttribute("type", "text/css");
NoSubject's avatar
NoSubject 已提交
598
                    var head = (op.doc.head || op.doc.getElementsByTagName("head")[0] || op.doc.documentElement);
NoSubject's avatar
NoSubject 已提交
599 600 601 602 603 604 605 606 607 608 609
                    head.appendChild(style);
                    if(style.styleSheet){
                        var setFunc = function(){
                            style.styleSheet.cssText = cssText;
                        };
                        if(style.styleSheet.disabled){
                            setTimeout(setFunc, 10);
                        }else{
                            setFunc();
                        }
                    }else{
NoSubject's avatar
NoSubject 已提交
610
                        var cssTextNode = op.doc.createTextNode(cssText);
NoSubject's avatar
NoSubject 已提交
611 612 613
                        style.appendChild(cssTextNode);
                    }
                }
NoSubject's avatar
NoSubject 已提交
614
                style.id = uid;
NoSubject's avatar
NoSubject 已提交
615
                var styleObj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid};
NoSubject's avatar
NoSubject 已提交
616 617
                _loadedCss[key] = styleObj;
                if (callback) callback(styleObj);
NoSubject's avatar
NoSubject 已提交
618 619 620 621 622 623
            }catch (e){
                if (callback) callback();
                return;
            }
        };
        var failure = function(xhr){
NoSubject's avatar
NoSubject 已提交
624
            console.log("Error: load css module: "+module);
NoSubject's avatar
NoSubject 已提交
625 626
            if (callback) callback();
        };
NoSubject's avatar
NoSubject 已提交
627 628 629 630

        _loadCssRunning[key] = true;

        _xhr_get(url, success, failure, completed);
NoSubject's avatar
NoSubject 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    };

    var _parseDomString = function(dom, fn, sourceDoc){
        var doc = sourceDoc || document;
        var list = doc.querySelectorAll(dom);
        if (list.length) for (var i=0; i<list.length; i++) _parseDomElement(list[i], fn);
    };
    var _parseDomElement = function(dom, fn){
        if (fn) fn(dom);
    };
    var _parseDom = function(dom, fn, sourceDoc){
        var domType = _typeOf(dom);
        if (domType==="string") _parseDomString(dom, fn, sourceDoc);
        if (domType==="element") _parseDomElement(dom, fn);
        if (domType==="array") for (var i=0; i<dom.length; i++) _parseDom(dom[i], fn, sourceDoc);
    };
NoSubject's avatar
NoSubject 已提交
647 648 649 650 651 652 653 654 655 656 657
    var _loadCss = function(modules, options, callback){
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getCssOptions(options) : _getCssOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var uuid = "css"+_uuid();
        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleCss, uuid);
        }else{
            _loadDisarray(ms, cb, op, thisLoaded, _loadSingleCss, uuid);
NoSubject's avatar
NoSubject 已提交
658
        }
NoSubject's avatar
NoSubject 已提交
659
    };
NoSubject's avatar
NoSubject 已提交
660
    var _removeCss = function(modules, doc){
NoSubject's avatar
NoSubject 已提交
661
        var thisDoc = doc || document;
NoSubject's avatar
NoSubject 已提交
662 663
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        for (var i=0; i<ms.length; i++){
R
roo00 已提交
664
            var module = ms[i];
NoSubject's avatar
NoSubject 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

            var k = encodeURIComponent(module+(thisDoc.unid||""));
            var removeCss = _loadedCss[k];
            if (!removeCss) for (key in _loadedCss){
                if (_loadedCss[key].id==module){
                    removeCss = _loadedCss[key];
                    k = key;
                    break;
                }
            }
            if (removeCss){
                delete _loadedCss[k];
                var styleNode = removeCss.doc.getElementById(removeCss.id);
                if (styleNode) styleNode.parentNode.removeChild(styleNode);
                removeCss = null;
NoSubject's avatar
NoSubject 已提交
680 681 682 683
            }
        }
    };
    this.o2.loadCss = _loadCss;
NoSubject's avatar
NoSubject 已提交
684
    this.o2.removeCss = _removeCss;
NoSubject's avatar
NoSubject 已提交
685
    if (window.Element) Element.prototype.loadCss = function(modules, options, callback){
NoSubject's avatar
NoSubject 已提交
686 687 688 689 690 691
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadCss(modules, op, cb);
    };

NoSubject's avatar
NoSubject 已提交
692
    //load html
NoSubject's avatar
NoSubject 已提交
693 694 695 696
    _loadSingleHtml = function(module, callback, op){
        var url = module;
        var uid = _uuid();
        if (op.noCache) url = (url.indexOf("?")!==-1) ? url+"&v="+uid : url+"?v="+uid;
NoSubject's avatar
NoSubject 已提交
697
        var key = encodeURIComponent(url+op.doc.unid);
NoSubject's avatar
NoSubject 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
        if (!op.reload) if (_loadedHtml[key]){ if (callback)callback(_loadedHtml[key]); return; }

        var success = function(xhr){
            var htmlObj = {"module": module, "id": uid, "data": xhr.responseText, "doc": op.doc};
            _loadedHtml[key] = htmlObj;
            if (callback) callback(htmlObj);
        };
        var failure = function(){
            console.log("Error: load html module: "+module);
            if (callback) callback();
        };
        _xhr_get(url, success, failure);
    };

    var _injectHtml = function(op, data){
NoSubject's avatar
NoSubject 已提交
713
        if (op.bind) data = data.bindJson(op.bind);
NoSubject's avatar
NoSubject 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        if (op.dom) _parseDom(op.dom, function(node){
            if (op.module){
                _parseModule(node, data, op);
                //node.insertAdjacentHTML(op.position, data);
            }else{
                node.insertAdjacentHTML(op.position, data);
            }
        }, op.doc);
    };
    var _parseModule = function(node, data, op){
        var dom = op.noConflict ? document.createElement("div") : node;
        if (op.noConflict){
            dom.insertAdjacentHTML("afterbegin", data);
        }else{
            dom.insertAdjacentHTML(op.position, data);
        }
        var els = dom.querySelectorAll("[data-o2-element]");
        for (var i=0; i<els.length; i++){
            var el = els.item(i);
            var name = el.getAttribute("data-o2-element").toString();
            if (name) _bindToModule(op.module, el, name);
            if (el.hasAttribute("data-o2-events")){
                var events = el.getAttribute("data-o2-events").toString();
                if (events) _bindToEvents(op.module, el, events);
            }
        }

        if (op.noConflict){
            var n = dom.firstElementChild;
            var newNode = node.insertAdjacentElement(op.position, n);
            nextNode = dom.firstElementChild;
            while (nextNode) {
                newNode = newNode.insertAdjacentElement("afterend", nextNode);
                nextNode = dom.firstElementChild;
            }
            dom.destroy();
        }
    };

    var _bindToEvents = function(m, node, events){
        var eventList = events.split(/\s*;\s*/);
        eventList.forEach(function(ev){
            var evs = ev.split(/\s*:\s*/);
            if (evs.length>1){
                node.addEventListener(evs[0], function(e){
                    if (m[evs[1]]) m[evs[1]].apply(m, [e]);
                }, false);
            }
        });
    }
    var _bindToModule = function(m, node, name){
        // if (m[name]){
        //     if (o2.typeOf(m[name])!=="array"){
        //         var tmp = m[name];
        //         m[name] = [];
        //         m[name].push(tmp);
        //     }
        //     m[name].push(node);
        // }else{
NoSubject's avatar
NoSubject 已提交
773
        m[name] = node;
NoSubject's avatar
NoSubject 已提交
774
        // }
NoSubject's avatar
NoSubject 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788
    };
    var _loadHtml = function(modules, options, callback){
        var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getHtmlOptions(options) : _getHtmlOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var thisLoaded = [];
        if (op.sequence){
            _loadSequence(ms, cb, op, 0, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
        }else{
            _loadDisarray(ms, cb, op, thisLoaded, _loadSingleHtml, null, function(html){ if (html) _injectHtml(op, html.data ); });
        }
    };
    this.o2.loadHtml = _loadHtml;
NoSubject's avatar
NoSubject 已提交
789
    if (window.Element) Element.prototype.loadHtml = function(modules, options, callback){
NoSubject's avatar
NoSubject 已提交
790 791 792 793 794
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadHtml(modules, op, cb);
    };
NoSubject's avatar
NoSubject 已提交
795 796 797 798 799 800 801 802 803
    this.o2.injectHtml = function(html, op){
        _injectHtml(op, html);
    };
    if (window.Element) Element.prototype.injectHtml = function(html, options){
        var op =  (_typeOf(options)==="object") ? options : {};
        op.dom = this;
        op.position = (options && options.position) || "beforeend"
        _injectHtml(op, html);
    };
NoSubject's avatar
NoSubject 已提交
804

NoSubject's avatar
NoSubject 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    //load all
    _loadAll = function(modules, options, callback){
        //var ms = (_typeOf(modules)==="array") ? modules : [modules];
        var op =  (_typeOf(options)==="object") ? _getAllOptions(options) : _getAllOptions(null);
        var cb = (_typeOf(options)==="function") ? options : callback;

        var ms, htmls, styles, sctipts;
        var _htmlLoaded=(!modules.html), _cssLoaded=(!modules.css), _jsLoaded=(!modules.js);
        var _checkloaded = function(){
            if (_htmlLoaded && _cssLoaded && _jsLoaded) if (cb) cb(htmls, styles, sctipts);
        };
        if (modules.html){
            _loadHtml(modules.html, op, function(h){
                htmls = h;
                _htmlLoaded = true;
                _checkloaded();
            });
        }
        if (modules.css){
            _loadCss(modules.css, op, function(s){
                styles = s;
                _cssLoaded = true;
                _checkloaded();
            });
        }
        if (modules.js){
            _load(modules.js, op, function(s){
                sctipts = s;
                _jsLoaded = true;
                _checkloaded();
            });
        }
    };
    this.o2.loadAll = _loadAll;
NoSubject's avatar
NoSubject 已提交
839
    if (window.Element) Element.prototype.loadAll = function(modules, options, callback){
NoSubject's avatar
NoSubject 已提交
840 841 842 843 844 845
        var op =  (_typeOf(options)==="object") ? options : {};
        var cb = (_typeOf(options)==="function") ? options : callback;
        op.dom = this;
        _loadAll(modules, op, cb);
    };

NoSubject's avatar
NoSubject 已提交
846 847 848 849 850 851 852 853 854 855 856
    var _getIfBlockEnd = function(v){
        var rex = /(\{\{if\s+)|(\{\{\s*end if\s*\}\})/gmi;
        var rexEnd = /\{\{\s*end if\s*\}\}/gmi;
        var subs = 1;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            if (fullMatch.search(rexEnd)!==-1){
                subs--;
                if (subs==0) break;
            }else{
                subs++
NoSubject's avatar
NoSubject 已提交
857 858
            }
        }
NoSubject's avatar
NoSubject 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
        if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
        return {"codeIndex": v.length-1, "lastIndex": v.length-1};
    }
    var _getEachBlockEnd = function(v){
        var rex = /(\{\{each\s+)|(\{\{\s*end each\s*\}\})/gmi;
        var rexEnd = /\{\{\s*end each\s*\}\}/gmi;
        var subs = 1;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            if (fullMatch.search(rexEnd)!==-1){
                subs--;
                if (subs==0) break;
            }else{
                subs++;
            }
        }
        if (match) return {"codeIndex": match.index, "lastIndex": rex.lastIndex};
        return {"codeIndex": v.length-1, "lastIndex": v.length-1};
    }

    var _parseHtml = function(str, json){
        var v = str;
        var rex = /(\{\{\s*)[\s\S]*?(\s*\}\})/gmi;

        var match;
        while ((match = rex.exec(v)) !== null) {
            var fullMatch = match[0];
            var offset = 0;

            //if statement begin
            if (fullMatch.search(/\{\{if\s+/i)!==-1){
                //找到对应的end if
                var condition = fullMatch.replace(/^\{\{if\s*/i, "");
                condition = condition.replace(/\s*\}\}$/i, "");
                var flag = _jsonText(json, condition, "boolean");

                var tmpStr = v.substring(rex.lastIndex, v.length);
                var endIfIndex = _getIfBlockEnd(tmpStr);
                if (flag){ //if 为 true
                    var parseStr = _parseHtml(tmpStr.substring(0, endIfIndex.codeIndex), json);
                    var vLeft = v.substring(0, match.index);
                    var vRight = v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
                    v = vLeft + parseStr + vRight;
                    offset = parseStr.length - fullMatch.length;
                }else{
                    v = v.substring(0, match.index) + v.substring(rex.lastIndex+endIfIndex.lastIndex, v.length);
                    offset = 0-fullMatch.length;
                }
            }else  if (fullMatch.search(/\{\{each\s+/)!==-1) { //each statement
                var itemString = fullMatch.replace(/^\{\{each\s*/, "");
                itemString = itemString.replace(/\s*\}\}$/, "");
                var eachValue = _jsonText(json, itemString, "object");

                var tmpEachStr = v.substring(rex.lastIndex, v.length);
                var endEachIndex = _getEachBlockEnd(tmpEachStr);

                var parseEachStr = tmpEachStr.substring(0, endEachIndex.codeIndex);
                var eachResult = "";
                if (eachValue && _typeOf(eachValue)==="array"){
                    for (var i=0; i<eachValue.length; i++){
                        eachValue[i]._ = json;
                        eachResult += _parseHtml(parseEachStr, eachValue[i]);
NoSubject's avatar
NoSubject 已提交
921
                    }
NoSubject's avatar
NoSubject 已提交
922 923 924 925 926 927 928
                    var eLeft = v.substring(0, match.index);
                    var eRight = v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
                    v = eLeft + eachResult + eRight;
                    offset = eachResult.length - fullMatch.length;
                }else{
                    v = v.substring(0, match.index) + v.substring(rex.lastIndex+endEachIndex.lastIndex, v.length);
                    offset = 0-fullMatch.length;
NoSubject's avatar
NoSubject 已提交
929
                }
NoSubject's avatar
NoSubject 已提交
930 931 932 933 934 935 936

            }else{ //text statement
                var text = fullMatch.replace(/^\{\{\s*/, "");
                text = text.replace(/\}\}\s*$/, "");
                var value = _jsonText(json, text);
                offset = value.length-fullMatch.length;
                v = v.substring(0, match.index) + value + v.substring(rex.lastIndex, v.length);
NoSubject's avatar
NoSubject 已提交
937
            }
NoSubject's avatar
NoSubject 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950
            rex.lastIndex = rex.lastIndex + offset;
        }
        return v;
    };
    var _jsonText = function(json, text, type){
        try {
            var $ = json;
            var f = eval("(function($){\n return "+text+";\n})");
            returnValue = f.apply(json, [$]);
            if (returnValue===undefined) returnValue="";
            if (type==="boolean") return (!!returnValue);
            if (type==="object") return returnValue;
            returnValue = returnValue.toString();
NoSubject's avatar
NoSubject 已提交
951 952 953 954
            returnValue = returnValue.replace(/\&/g, "&amp;");
            returnValue = returnValue.replace(/>/g, "&gt;");
            returnValue = returnValue.replace(/</g, "&lt;");
            returnValue = returnValue.replace(/\"/g, "&quot;");
NoSubject's avatar
NoSubject 已提交
955 956 957 958 959
            return returnValue || "";
        }catch(e){
            if (type==="boolean") return false;
            if (type==="object") return null;
            return "";
NoSubject's avatar
NoSubject 已提交
960 961 962
        }
    };

NoSubject's avatar
NoSubject 已提交
963 964
    o2.bindJson = function(str, json){
        return _parseHtml(str, json);
NoSubject's avatar
NoSubject 已提交
965 966
    };
    String.prototype.bindJson = function(json){
NoSubject's avatar
NoSubject 已提交
967
        return _parseHtml(this, json);
NoSubject's avatar
NoSubject 已提交
968
    };
969 970
})();

NoSubject's avatar
NoSubject 已提交
971

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/** ***** BEGIN LICENSE BLOCK *****
 * |------------------------------------------------------------------------------|
 * | O2OA 活力办公 创意无限    o2.core.js                                            |
 * |------------------------------------------------------------------------------|
 * | Distributed under the AGPL license:                                          |
 * |------------------------------------------------------------------------------|
 * | Copyright © 2018, o2oa.net, o2server.io O2 Team                              |
 * | All rights reserved.                                                         |
 * |------------------------------------------------------------------------------|
 *
 *  This file is part of O2OA.
 *
 *  O2OA is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  O2OA is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ***** END LICENSE BLOCK ******/
(function (){
    var _Class = {
        create: function(options) {
NoSubject's avatar
NoSubject 已提交
1001 1002 1003 1004 1005 1006 1007
            // var newClass = function() {
            //     this.initialize.apply(this, arguments);
            // };
            return _copyPrototype(function() {
                return this.initialize.apply(this, arguments) || this;
            }, options);
            //return newClass;
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
        }
    };
    var _copyPrototype = function (currentNS, props){
        if (!props){return currentNS;}
        if (!currentNS){return currentNS;}
        if ((typeof currentNS).toLowerCase()==="object"){
            for (var prop in props){
                currentNS[prop] = props[prop];
            }
        }
        if ((typeof currentNS).toLowerCase()==="function"){
            for (var propfun in props){
                currentNS.prototype[propfun] = props[propfun];
            }
        }
        return currentNS;
    };

    var _loaded = {};

    var _requireJs = function(url, callback, async, compression, module){
        var key = encodeURIComponent(url);
        if (_loaded[key]){o2.runCallback(callback, "success", [module]); return "";}

        var jsPath = (compression || !this.o2.session.isDebugger) ? url.replace(/\.js/, ".min.js") : url;
        jsPath = (jsPath.indexOf("?")!==-1) ? jsPath+"&v="+this.o2.version.v : jsPath+"?v="+this.o2.version.v;

        var xhr = new Request({
            url: o2.filterUrl(jsPath), async: async, method: "get",
            onSuccess: function(){
                //try{
                _loaded[key] = true;
                o2.runCallback(callback, "success", [module]);
                //}catch (e){
                //    o2.runCallback(callback, "failure", [e]);
                //}
            },
            onFailure: function(r){
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
                var rex = /lp\/.+\.js/;
                if (rex.test(url)){
                    var zhcnUrl = url.replace(rex, "lp/zh-cn.js");
                    if (zhcnUrl!==url){
                        _requireJs(zhcnUrl, callback, async, compression, module)
                    }else{
                        o2.runCallback(callback, "failure", [r]);
                    }
                }else{
                    o2.runCallback(callback, "failure", [r]);
                }
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
            }
        });
        xhr.send();
    };
    var _requireSingle = function(module, callback, async, compression){
        if (o2.typeOf(module)==="array"){
            _requireAppSingle(module, callback, async, compression);
        }else{
            module = module.replace("MWF.", "o2.");
            var levels = module.split(".");
            if (levels[levels.length-1]==="*") levels[levels.length-1] = "package";
            levels.shift();
            var o = o2;
            var i = 0;
            while (o && i<levels.length){
                o = o[levels[i]];
                i++
            }
            if (!o){
                var jsPath = this.o2.session.path;
                jsPath +="/"+levels.join("/")+".js";
                var loadAsync = (async!==false);
                _requireJs(jsPath, callback, loadAsync, compression, module);
            }else{
                o2.runCallback(callback, "success", [module]);
            }
        }
    };
    var _requireSequence = function(fun, module, thisLoaded, thisErrorLoaded, callback, async, compression){
        var m = module.shift();
        fun(m, {
            "onSuccess": function(m){
                thisLoaded.push(m);
                o2.runCallback(callback, "every", [m]);
                if (module.length){
                    _requireSequence(fun, module, thisLoaded, thisErrorLoaded, callback, async, compression);
                }else{
                    if (thisErrorLoaded.length){
                        o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
                    }else{
                        o2.runCallback(callback, "success", [thisLoaded, thisErrorLoaded]);
                    }
                }
            },
            "onFailure": function(){
                thisErrorLoaded.push(module[i]);
                o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
            }
        }, async, compression);
    };
    var _requireDisarray = function(fun, module, thisLoaded, thisErrorLoaded, callback, async, compression){
        for (var i=0; i<module.length; i++){
            fun(module[i], {
                "onSuccess": function(m){
                    thisLoaded.push(m);
                    o2.runCallback(callback, "every", [m]);
                    if ((thisLoaded.length+thisErrorLoaded.length)===module.length){
                        if (thisErrorLoaded.length){
                            o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
                        }else{
                            o2.runCallback(callback, "success", [thisLoaded, thisErrorLoaded]);
                        }
                    }
                },
                "onFailure": function(){
                    thisErrorLoaded.push(module[i]);
                    o2.runCallback(callback, "failure", [thisLoaded, thisErrorLoaded]);
                }
            }, async, compression);
        }
    };
    var _require = function(module, callback, async, sequence, compression){
        var type = typeOf(module);
        if (type==="array"){
            var sql = !!sequence;
            var thisLoaded = [];
            var thisErrorLoaded = [];
            if (sql){
                _requireSequence(_requireSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);

            }else{
                _requireDisarray(_requireSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
            }
        }
        if (type==="string"){
            _requireSingle(module, callback, async, compression);
        }
    };

    var _requireAppSingle = function(modules, callback, async, compression){
        var module = modules[0];
        var clazz = modules[1];
        var levels = module.split(".");

        var o = o2.xApplication;
        var i = 0;
        while (o && i<levels.length){
            o = o[levels[i]];
            i++
        }
        if (o) o = o[clazz || "Main"];

        if (!o){
            //levels.shift();
            var root = "x_component_"+levels.join("_");
            var clazzName = clazz || "Main";
            var path = "../"+root+"/"+clazzName.replace(/\./g, "/")+".js";
            var loadAsync = (async!==false);
            _requireJs(path, callback, loadAsync, compression);
        }else{
            o2.runCallback(callback, "success");
        }
    };
    var _requireApp = function(module, clazz, callback, async, sequence, compression){
        var type = typeOf(module);
        if (type==="array"){
            var sql = !!sequence;
            var thisLoaded = [];
            var thisErrorLoaded = [];
            if (sql){
                _requireSequence(_requireAppSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);

            }else{
                _requireDisarray(_requireAppSingle, module, thisLoaded, thisErrorLoaded, callback, async, compression);
            }
        }
        if (type==="string"){
            var modules = [module, clazz];
            _requireAppSingle(modules, callback, async, compression);
        }
    };

    JSON = window.JSON || {};
    var _json = JSON;
    _json.get = function(url, callback, async, nocache){
        var loadAsync = (async !== false);
        var noJsonCache = (nocache === true);

        url = (url.indexOf("?")!==-1) ? url+"&v="+o2.version.v : url+"?v="+o2.version.v;

        var json = null;
        var res = new Request.JSON({
            url: o2.filterUrl(url),
            secure: false,
            method: "get",
            noCache: noJsonCache,
            async: loadAsync,
            withCredentials: true,
            onSuccess: function(responseJSON, responseText){
                json = responseJSON;
                if (typeOf(callback).toLowerCase() === 'function'){
                    callback(responseJSON, responseText);
                }else{
                    o2.runCallback(callback, "success", [responseJSON, responseText]);
                }
            }.bind(this),
            onFailure: function(xhr){
                o2.runCallback(callback, "requestFailure", [xhr]);
            }.bind(this),
            onError: function(text, error){
                o2.runCallback(callback, "error", [text, error]);
            }.bind(this)
        });
        res.send();
        return json;
    };
    _json.getJsonp = function(url, callback, async, callbackKey){
        var loadAsync = (async !== false);

        var callbackKeyWord = callbackKey || "callback";

        url = (url.indexOf("?")!==-1) ? url+"&v="+o2.version.v : url+"?v="+o2.version.v;
        var res = new Request.JSONP({
            url: o2.filterUrl(url),
            secure: false,
            method: "get",
            noCache: true,
            async: loadAsync,
            callbackKey: callbackKeyWord,
            onSuccess: function(responseJSON, responseText){
                o2.runCallback(callback, "success",[responseJSON, responseText]);
            }.bind(this),
            onFailure: function(xhr){
                o2.runCallback(callback, "requestFailure",[xhr]);
            }.bind(this),
            onError: function(text, error){
                o2.runCallback(callback, "error",[text, error]);
            }.bind(this)
        });
        res.send();
    };


    var _loadLP = function(name){
        var jsPath = o2.session.path;
        jsPath = jsPath+"/lp/"+name+".js";
        var r = new Request({
            url: o2.filterUrl(jsPath),
            async: false,
            method: "get",
            onSuccess: function(responseText){
                try{
                    Browser.exec(responseText);
                }catch (e){}
            },
            onFailure: function(xhr){
1263 1264 1265 1266 1267
                if (name!="zh-cn"){
                    _loadLP("zh-cn");
                }else{
                    throw "loadLP Error: "+xhr.responseText;
                }
1268 1269 1270 1271 1272 1273 1274
            }
        });
        r.send();
    };

    var _cacheUrls = [
        /jaxrs\/form\/workorworkcompleted\/.+/ig,
NoSubject's avatar
NoSubject 已提交
1275
        /jaxrs\/form\/.+/ig,
1276 1277 1278 1279
        //    /jaxrs\/script/ig,
        /jaxrs\/script\/.+\/app\/.+\/imported/ig,
        /jaxrs\/script\/portal\/.+\/name\/.+\/imported/ig,
        /jaxrs\/script\/.+\/application\/.+\/imported/ig,
NoSubject's avatar
NoSubject 已提交
1280 1281 1282
        /jaxrs\/page\/.+\/portal\/.+/ig,
        /jaxrs\/document\/.+/ig,
        /jaxrs\/applicationdict\/.+/ig,
NoSubject's avatar
NoSubject 已提交
1283
        /jaxrs\/custom\/.+/ig,
NoSubject's avatar
NoSubject 已提交
1284 1285
        /jaxrs\/definition\/idea.+/ig,
        /jaxrs\/distribute\/assemble\/source\/.+/ig,
NoSubject's avatar
NoSubject 已提交
1286 1287 1288 1289 1290 1291 1292

        ///jaxrs\/form\/workorworkcompleted\/.+/ig,
        //    /jaxrs\/script/ig,
        // /jaxrs\/script\/.+\/app\/.+\/imported/ig,
        // /jaxrs\/script\/portal\/.+\/name\/.+\/imported/ig,
        // /jaxrs\/script\/.+\/application\/.+\/imported/ig,
        // /jaxrs\/page\/.+\/portal\/.+/ig
1293 1294 1295
        // /jaxrs\/authentication/ig
        // /jaxrs\/statement\/.*\/execute\/page\/.*\/size\/.*/ig
    ];
NoSubject's avatar
NoSubject 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    // _restful_bak = function(method, address, data, callback, async, withCredentials, cache){
    //     var loadAsync = (async !== false);
    //     var credentials = (withCredentials !== false);
    //     address = (address.indexOf("?")!==-1) ? address+"&v="+o2.version.v : address+"?v="+o2.version.v;
    //     //var noCache = cache===false;
    //     var noCache = !cache;
    //
    //
    //     //if (Browser.name == "ie")
    //     if (_cacheUrls.length){
    //         for (var i=0; i<_cacheUrls.length; i++){
    //             _cacheUrls[i].lastIndex = 0;
    //             if (_cacheUrls[i].test(address)){
    //                 noCache = false;
    //                 break;
    //             }
    //         }
    //     }
    //     //var noCache = false;
    //     var res = new Request.JSON({
    //         url: o2.filterUrl(address),
    //         secure: false,
    //         method: method,
    //         emulation: false,
    //         noCache: noCache,
    //         async: loadAsync,
    //         withCredentials: credentials,
    //         onSuccess: function(responseJSON, responseText){
    //             // var xToken = this.getHeader("authorization");
    //             // if (!xToken) xToken = this.getHeader("x-token");
    //             var xToken = this.getHeader("x-token");
    //             if (xToken){
    //                 if (window.layout){
    //                     if (!layout.session) layout.session = {};
    //                     layout.session.token = xToken;
    //                 }
    //             }
    //             o2.runCallback(callback, "success", [responseJSON]);
    //         },
    //         onFailure: function(xhr){
    //             o2.runCallback(callback, "requestFailure", [xhr]);
    //         }.bind(this),
    //         onError: function(text, error){
    //             o2.runCallback(callback, "error", [text, error]);
    //         }.bind(this)
    //     });
    //
    //     res.setHeader("Content-Type", "application/json; charset=utf-8");
    //     res.setHeader("Accept", "text/html,application/json,*/*");
    //     if (window.layout) {
    //         if (layout["debugger"]){
    //             res.setHeader("x-debugger", "true");
    //         }
    //         if (layout.session && layout.session.user){
    //             if (layout.session.user.token) {
    //                 res.setHeader("x-token", layout.session.user.token);
    //                 res.setHeader("authorization", layout.session.user.token);
    //             }
    //         }
    //     }
    //     //Content-Type	application/x-www-form-urlencoded; charset=utf-8
    //     res.send(data);
    //     return res;
    // };

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    _restful = function(method, address, data, callback, async, withCredentials, cache){
        var loadAsync = (async !== false);
        var credentials = (withCredentials !== false);
        address = (address.indexOf("?")!==-1) ? address+"&v="+o2.version.v : address+"?v="+o2.version.v;
        //var noCache = cache===false;
        var noCache = !cache;

        //if (Browser.name == "ie")
        if (_cacheUrls.length){
            for (var i=0; i<_cacheUrls.length; i++){
1371
                _cacheUrls[i].lastIndex = 0;
1372 1373 1374 1375 1376 1377
                if (_cacheUrls[i].test(address)){
                    noCache = false;
                    break;
                }
            }
        }
NoSubject's avatar
NoSubject 已提交
1378

1379
        var useWebWorker = (window.layout && layout.config && layout.config.useWebWorker);
1380
        //var noCache = false;
NoSubject's avatar
NoSubject 已提交
1381
        if (!loadAsync || !useWebWorker){
NoSubject's avatar
NoSubject 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
            var res;
            var p = new Promise(function(s,f){
                res = new Request.JSON({
                    url: o2.filterUrl(address),
                    secure: false,
                    method: method,
                    emulation: false,
                    noCache: noCache,
                    async: loadAsync,
                    withCredentials: credentials,
                    onSuccess: function(responseJSON, responseText){
                        // var xToken = this.getHeader("authorization");
                        // if (!xToken) xToken = this.getHeader("x-token");
                        var xToken = this.getHeader("x-token");
                        if (xToken){
                            if (window.layout){
                                if (!layout.session) layout.session = {};
                                layout.session.token = xToken;
                            }
NoSubject's avatar
NoSubject 已提交
1401
                        }
NoSubject's avatar
NoSubject 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
                        o2.runCallback(callback, "success", [responseJSON]);
                    },
                    onFailure: function(xhr){
                        o2.runCallback(callback, "requestFailure", [xhr]);
                    }.bind(this),
                    onError: function(text, error){
                        o2.runCallback(callback, "error", [text, error]);
                    }.bind(this)
                });

                res.setHeader("Content-Type", "application/json; charset=utf-8");
                res.setHeader("Accept", "text/html,application/json,*/*");
                if (window.layout) {
                    if (layout["debugger"]){
                        res.setHeader("x-debugger", "true");
1417
                    }
NoSubject's avatar
NoSubject 已提交
1418 1419 1420 1421 1422
                    if (layout.session && layout.session.user){
                        if (layout.session.user.token) {
                            res.setHeader("x-token", layout.session.user.token);
                            res.setHeader("authorization", layout.session.user.token);
                        }
NoSubject's avatar
NoSubject 已提交
1423 1424
                    }
                }
NoSubject's avatar
NoSubject 已提交
1425 1426 1427 1428
                //Content-Type	application/x-www-form-urlencoded; charset=utf-8
                res.send(data);
            }.bind(this));

NoSubject's avatar
NoSubject 已提交
1429
            var oReturn = (callback.success && callback.success.isAG) ? callback.success : callback;
NoSubject's avatar
NoSubject 已提交
1430
            var oReturn = p;
1431 1432
            oReturn.res = res;
            return oReturn;
NoSubject's avatar
NoSubject 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
        }else{
            var workerMessage = {
                method: method,
                noCache: noCache,
                loadAsync: loadAsync,
                credentials: credentials,
                address: o2.filterUrl(address),
                body: data,
                debug: (window.layout && layout["debugger"]),
                token: (window.layout && layout.session && layout.session.user) ? layout.session.user.token : ""
1443
            }
NoSubject's avatar
NoSubject 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
            var actionWorker = new Worker("../o2_core/o2/actionWorker.js");
            actionWorker.onmessage = function(e) {
                result = e.data;
                if (result.type==="done"){
                    var xToken = result.data.xToken;
                    if (xToken){
                        if (window.layout){
                            if (!layout.session) layout.session = {};
                            layout.session.token = xToken;
                        }
                    }
                    o2.runCallback(callback, "success", [result.data]);
                }else{
                    o2.runCallback(callback, "failure", [result.data]);
1458
                }
1459
                actionWorker.terminate();
1460
            }
NoSubject's avatar
NoSubject 已提交
1461
            actionWorker.postMessage(workerMessage);
1462 1463 1464 1465
            var oReturn = (callback.success && callback.success.addResolve) ? callback.success : callback;
            oReturn.actionWorker = actionWorker;
            return oReturn;
            //return callback;
1466
        }
NoSubject's avatar
NoSubject 已提交
1467
        //return res;
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    };

    var _release = function(o){
        var type = typeOf(o);
        switch (type){
            case "object":
                for (var k in o){
                    //if (o[k] && o[k].destroy) o[k].destroy();
                    o[k] = null;
                }
                break;
            case "array":
                for (var i=0; i< o.length; i++){
                    _release(o[i]);
                    if (o[i]) o[i] = null;
                }
                break;
        }
    };

    var _defineProperties = Object.defineProperties || function (obj, properties) {
        function convertToDescriptor(desc) {
            function hasProperty(obj, prop) {
                return Object.prototype.hasOwnProperty.call(obj, prop);
            }
            function isCallable(v) {
                // NB: modify as necessary if other values than functions are callable.
                return typeof v === "function";
            }
            if (typeof desc !== "object" || desc === null)
                throw new TypeError("bad desc");
            var d = {};
            if (hasProperty(desc, "enumerable"))
                d.enumerable = !!desc.enumerable;
            if (hasProperty(desc, "configurable"))
                d.configurable = !!desc.configurable;
            if (hasProperty(desc, "value"))
                d.value = desc.value;
            if (hasProperty(desc, "writable"))
                d.writable = !!desc.writable;
            if (hasProperty(desc, "get")) {
                var g = desc.get;
                if (!isCallable(g) && typeof g !== "undefined")
                    throw new TypeError("bad get");
                d.get = g;
            }
            if (hasProperty(desc, "set")) {
                var s = desc.set;
                if (!isCallable(s) && typeof s !== "undefined")
                    throw new TypeError("bad set");
                d.set = s;
            }
            if (("get" in d || "set" in d) && ("value" in d || "writable" in d))
                throw new TypeError("identity-confused descriptor");
            return d;
        }
        if (typeof obj !== "object" || obj === null)
            throw new TypeError("bad obj");
        properties = Object(properties);
        var keys = Object.keys(properties);
        var descs = [];
        for (var j = 0; j < keys.length; j++)
            descs.push([keys[j], convertToDescriptor(properties[keys[j]])]);
        for (var i = 0; i < descs.length; i++){
            if (Object.defineProperty && (Browser.name=="ie" && Browser.version!=8)){
                Object.defineProperty(obj, descs[i][0], descs[i][1]);
            }else{
                if (descs[i][1].value) obj[descs[i][0]] = descs[i][1].value;
                if (descs[i][1].get) obj["get"+descs[i][0].capitalize()] = descs[i][1].get;
                if (descs[i][1].set) obj["set"+descs[i][0].capitalize()] = descs[i][1].set;
            }
        }
        return obj;
    };
    if (!Array.prototype.findIndex) {
        Object.defineProperty(Array.prototype, 'findIndex', {
            value: function(predicate) {
                if (this == null) {
                    throw new TypeError('"this" is null or not defined');
                }
                var o = Object(this);
                var len = o.length >>> 0;
                if (typeof predicate !== 'function') {
                    throw new TypeError('predicate must be a function');
                }
                var thisArg = arguments[1];
                var k = 0;
                while (k < len) {
                    var kValue = o[k];
                    if (predicate.call(thisArg, kValue, k, o)) {
                        return k;
                    }
                    k++;
                }
                return -1;
            }
        });
    }
    if (!Array.prototype.find) {
        Object.defineProperty(Array.prototype, 'find', {
            value: function(predicate) {
                if (this == null) {
                    throw new TypeError('"this" is null or not defined');
                }
                var o = Object(this);
                var len = o.length >>> 0;
                if (typeof predicate !== 'function') {
                    throw new TypeError('predicate must be a function');
                }
                var thisArg = arguments[1];
                var k = 0;
                while (k < len) {
                    var kValue = o[k];
                    if (predicate.call(thisArg, kValue, k, o)) {
                        return kValue;
                    }
                    k++;
                }
                return undefined;
            }
        });
    }

    var _txt = function(v){
        var t = v.replace(/\</g, "&lt;");
        t = t.replace(/\</g, "&gt;");
        return t;
    };

    this.o2.Class = _Class;
    this.o2.require = _require;
    this.o2.requireApp = _requireApp;
    this.o2.JSON = _json;
    this.o2.loadLP = _loadLP;
    this.o2.restful = _restful;
    this.o2.release = _release;
    this.o2.defineProperties = _defineProperties;
    this.o2.txt = _txt;

    Object.repeatArray = function(o, count){
        var arr = [];
        for (var i=0; i<count; i++){
            arr.push(o)
        }
        return arr;
    }
NoSubject's avatar
NoSubject 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    // Date.implement({
    //     "getFromServer": function(callback){
    //         if (callback){
    //             o2.Actions.get("x_program_center").echo(function(json){
    //                 d = Date.parse(json.data.serverTime);
    //                 callback(d);
    //             });
    //         }else{
    //             var d;
    //             o2.Actions.get("x_program_center").echo(function(json){
    //                 d = Date.parse(json.data.serverTime);
    //             }, null, false);
    //             return d;
    //         }
    //     }
    // });
1630 1631
    Date.getFromServer = function(async){
        var d;
NoSubject's avatar
NoSubject 已提交
1632 1633
        var cb = ((async && o2.typeOf(async)=="function") ? (async.isAG ? async : async.ag()) : null) || function(json){
        //var cb = function(json){
1634 1635 1636 1637 1638 1639
            d = Date.parse(json.data.serverTime);
            return d;
        }.ag().catch(function(json){ return d; });

        o2.Actions.get("x_program_center").echo(cb, null, !!async);

NoSubject's avatar
NoSubject 已提交
1640
        return (!!async) ? cb : d;
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653

            // if (callback){
            //     o2.Actions.get("x_program_center").echo(function(json){
            //         d = Date.parse(json.data.serverTime);
            //         o2.runCallback(callback, "success", [d]);
            //     });
            // }else{
            //     var d;
            //     o2.Actions.get("x_program_center").echo(function(json){
            //         d = Date.parse(json.data.serverTime);
            //     }, null, false);
            //     return d;
            // }
NoSubject's avatar
NoSubject 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
    };

    Object.appendChain = function(oChain, oProto) {
        if (arguments.length < 2) {
            throw new TypeError('Object.appendChain - Not enough arguments');
        }
        if (typeof oProto === 'number' || typeof oProto === 'boolean') {
            throw new TypeError('second argument to Object.appendChain must be an object or a string');
        }

        var oNewProto = oProto,
            oReturn,
            o2nd,
            oLast;

        oReturn = o2nd = oLast = oChain instanceof this ? oChain : new oChain.constructor(oChain);

        for (var o1st = this.getPrototypeOf(o2nd);
             o1st !== Object.prototype && o1st !== Function.prototype;
             o1st = this.getPrototypeOf(o2nd)
        ) {
            o2nd = o1st;
        }

        if (oProto.constructor === String) {
            oNewProto = Function.prototype;
            oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1));
            oReturn = oReturn.bind(oLast);
            this.setPrototypeOf(oReturn, oLast);
        }

        this.setPrototypeOf(o2nd, oNewProto);
        return oReturn;
    }

    var _AsyncGeneratorPrototype = _Class.create({
        initialize: function(resolve, reject, name){
1691
            this.isAG = true;
NoSubject's avatar
NoSubject 已提交
1692 1693 1694 1695 1696 1697
            this.name = name || "";
            this._createSuccess();
            this._createFailure();
            if (resolve) this.success.resolve = resolve;
            if (reject) this.failure.reject = reject;
        },
1698
        //$family: function(){ return "o2_async_function"; },
NoSubject's avatar
NoSubject 已提交
1699 1700 1701 1702 1703 1704 1705
        _createSuccess: function(){
            var _self = this;
            this.success = function(){
                var result;
                if (_self.success.resolve) result = _self.success.resolve.apply(this, arguments);
                if (_self.success.resolveList){
                    _self.success.resolveList.each(function(r){
1706
                        result = r(result, arguments) || result;
NoSubject's avatar
NoSubject 已提交
1707 1708
                    });
                }
1709 1710 1711
                _self.isSuccess = true;
                _self.result = result;
                _self.arg = arguments;
NoSubject's avatar
NoSubject 已提交
1712
                return result;
NoSubject's avatar
NoSubject 已提交
1713 1714 1715 1716 1717 1718
            }
        },
        _createFailure: function(){
            var _self = this;
            this.failure = function(){
                var result;
NoSubject's avatar
NoSubject 已提交
1719
                if (_self.failure.reject) result = _self.failure.reject.apply(this, arguments);
NoSubject's avatar
NoSubject 已提交
1720 1721
                if (_self.failure.rejectList){
                    _self.failure.rejectList.each(function(r){
1722
                        result = r(result, arguments) || result;
NoSubject's avatar
NoSubject 已提交
1723 1724
                    });
                }
1725 1726 1727 1728
                _self.isFailure = true;
                _self.result = result;
                _self.arg = arguments;
                return result;
NoSubject's avatar
NoSubject 已提交
1729 1730 1731 1732 1733
            }
        },
        setResolve: function(resolve){
            if (!this.success) this._createSuccess();
            this.success.resolve = resolve;
1734
            return this;
NoSubject's avatar
NoSubject 已提交
1735 1736 1737
        },
        setReject: function(reject){
            if (!this.failure) this._createFailure();
1738 1739
            this.failure.reject = reject;
            return this;
NoSubject's avatar
NoSubject 已提交
1740 1741 1742 1743
        },
        addResolve: function(resolve){
            if (!this.success) this._createSuccess();
            if (resolve){
1744
                if (this.isSuccess){
1745
                    this.result = resolve(this.result, this.arg);
1746
                }else{
1747 1748 1749 1750 1751 1752
                    if (!this.success.resolve){
                        this.success.resolve = resolve;
                    }else{
                        if (!this.success.resolveList) this.success.resolveList = [];
                        this.success.resolveList.push(resolve);
                    }
1753
                }
NoSubject's avatar
NoSubject 已提交
1754
            }
1755
            return this;
NoSubject's avatar
NoSubject 已提交
1756 1757 1758 1759
        },
        addReject: function(reject){
            if (!this.failure) this._createFailure();
            if (reject){
1760
                if (this.isFailure){
1761
                    this.result = reject(this.result, this.arg);
1762
                }else{
1763 1764 1765 1766 1767 1768
                    if (!this.failure.reject){
                        this.failure.reject = reject;
                    }else{
                        if (!this.failure.rejectList) this.failure.rejectList = [];
                        this.failure.rejectList.push(reject);
                    }
1769
                }
NoSubject's avatar
NoSubject 已提交
1770
            }
1771 1772 1773 1774 1775 1776 1777 1778
            return this;
        },
        then: function(resolve){
            return this.addResolve(resolve);
        },
        "catch": function(reject){
            return this.addReject(reject);
        },
1779
    });
NoSubject's avatar
NoSubject 已提交
1780 1781 1782 1783
    var _AsyncGenerator = function(resolve, reject, name){
        var asyncGeneratorPrototype = new _AsyncGeneratorPrototype(resolve, reject, name);
        return Object.appendChain(asyncGeneratorPrototype, "if (this.success) this.success.apply(this, arguments);");
    }
NoSubject's avatar
NoSubject 已提交
1784 1785

    //@todo
NoSubject's avatar
NoSubject 已提交
1786 1787
    _AsyncGenerator.all = function(arr){
        var result = [];
NoSubject's avatar
NoSubject 已提交
1788 1789 1790
        var ag = function (){
            return result;
        }.ag();
NoSubject's avatar
NoSubject 已提交
1791

NoSubject's avatar
NoSubject 已提交
1792
        if (o2.typeOf(arr) !== "array") arr = [arr];
NoSubject's avatar
NoSubject 已提交
1793

NoSubject's avatar
NoSubject 已提交
1794 1795 1796 1797 1798 1799
        var count  = arr.length;
        var check = function(){
            count--;
            if (count<=0)ag();
        }

1800
        //window.setTimeout(function(){
NoSubject's avatar
NoSubject 已提交
1801 1802 1803 1804 1805 1806 1807
            arr.forEach(function(a){
                if (typeOf(a)=="array"){
                    o2.AG.all(a).then(function(v){
                        result = result.concat(v);
                        check();
                    });
                }else{
NoSubject's avatar
NoSubject 已提交
1808
                    if (a && a.isAG){
NoSubject's avatar
NoSubject 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
                        a.then(function(v){
                            o2.AG.all(v).then(function(r){
                                result = result.concat(r);
                                check();
                            });
                        });
                    }else{
                        result.push(a);
                        check();
                    }
                }
            });
1821
        //}, 0);
NoSubject's avatar
NoSubject 已提交
1822
        return ag;
NoSubject's avatar
NoSubject 已提交
1823
    }
NoSubject's avatar
NoSubject 已提交
1824 1825

    o2.AsyncGenerator = o2.AG = _AsyncGenerator;
1826

1827 1828 1829 1830
    Function.prototype.ag = function(){
        return o2.AG(this);
    }

1831 1832 1833 1834 1835 1836
})();
o2.core = true;


/** ***** BEGIN LICENSE BLOCK *****
 * |------------------------------------------------------------------------------|
NoSubject's avatar
NoSubject 已提交
1837
 * | O2OA 活力办公 创意无限    o2.more.js                                          |
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
 * |------------------------------------------------------------------------------|
 * | Distributed under the AGPL license:                                          |
 * |------------------------------------------------------------------------------|
 * | Copyright © 2018, o2oa.net, o2server.io O2 Team                              |
 * | All rights reserved.                                                         |
 * |------------------------------------------------------------------------------|
 *
 *  This file is part of O2OA.
 *
 *  O2OA is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  O2OA is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ***** END LICENSE BLOCK ******/
(function (){
    o2.getCenterPosition = function(el, width, height){
        var elPositon = $(el).getPosition();
        var elSize = $(el).getSize();
        var node = $("layout");
        var size = (node) ? $(node).getSize() : $(document.body).getSize();

        var top = (elPositon.y+elSize.y)/2 - (height/2);
        var left = (elPositon.x+elSize.x)/2-(width/2);
        if ((left+width)>size.x){
            left = size.x-width-10;
        }
        if ((top+height)>size.y){
            top = size.y-height-10;
        }

        return {"x": left, "y": top};
    };
    o2.getMarkSize = function(node){
        var size;
        if (!node){
            size = $(document.body).getSize();
            var winSize = $(window).getSize();

            var height = size.y;
            var width = size.x;

            if (height<winSize.y) height = winSize.y;
            if (width<winSize.x) width = winSize.x;

            return {x: size.x, y: height};
        }else{
            size = $(node).getSize();
            return {x: size.x, y: size.y};
        }
    };
    o2.json = function(jsonString, fun){
        var obj = JSON.decode(jsonString);
        var p = fun.split(".");
        var tmp = obj;
        p.each(function(item){
            if (item.indexOf("[")!==-1){
                var x = item.split("[");
                var i = parseInt(x[1].substr(0, x[1].indexOf("]")));
                tmp = tmp[x[0]][i];
            }else{
                tmp = tmp[item];
            }
        });
        return tmp;
    };
    o2.getHTMLTemplate = function(url, callback, async){
        var loadAsync = (async !== false);
        var res = new Request.HTML({
            url: url,
            async: loadAsync,
            method: "get",
            onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
                o2.runCallback(callback, "success", [responseTree, responseElements, responseHTML, responseJavaScript]);
            }.bind(this),
            onFailure: function(xhr){
                o2.runCallback(callback, "requestFailure", [xhr]);
            }
        });
        res.send();
    };

    o2.getRequestText = function(url, callback, async){
        var loadAsync = (async !== false);

        url = (url.indexOf("?")!==-1) ? url+"&v="+o2.version.v : url+"?v="+o2.version.v;
        var res = new Request({
            url: url,
            async: loadAsync,
            method: "get",
            onSuccess: function(responseText, responseXML){
                o2.runCallback(callback, "success",[responseText, responseXML]);
            }.bind(this),
            onFailure: function(xhr){
                o2.runCallback(callback, "requestFailure",[xhr]);
            }
        });
        res.send();
    };

    o2.encodeJsonString = function(str){
        var tmp = [str];
        var dataStr = (JSON.encode(tmp));
        return dataStr.substr(2, dataStr.length-4);
    };
    o2.decodeJsonString = function(str){
        var tmp = "[\""+str+"\"]";
        var dataObj = (JSON.decode(tmp));
        return dataObj[0];
    };

    o2.getTextSize = function(text, styles){
        var tmpSpan = new Element("span", {
            "text": text,
            "styles": styles
        }).inject($(document.body));
        var size = tmpSpan.getSize();
        tmpSpan.destroy();
        return size;
    };
    o2.getCenter = function(size, target, offset){
        if (!target) target = document.body;
        var targetSize = target.getSize();
        var targetPosition = target.getPosition(offset);
        var targetScroll = target.getScroll();

        var x = targetSize.x/2;
        var y = targetSize.y/2;

        x = x-(size.x/2);
        y = y-(size.y/2);
        x = x+targetPosition.x;
        y = y+targetPosition.y;
        x = x+targetScroll.x;
        y = y+targetScroll.y;

        return {"x": x, "y": y};
    };
    o2.getEPointer = function(e){
        var x = 0;
        var y = 0;
        if (typeOf(e)=="element"){
            var position = e.getPosition(this.content);
            x = position.x;
            y = position.y;
        }else{
            if (Browser.name=="firefox"){
                x = parseFloat(e.event.clientX || e.event.x);
                y = parseFloat(e.event.clientY || e.event.y);
            }else{
                x = parseFloat(e.event.x);
                y = parseFloat(e.event.y);
            }

            if (e.target){
                var position = e.target.getPosition(this.content);
                x = position.x;
                y = position.y;
            }
            //    }
        }
        return {"x": x, "y": y};
    };
    o2.getParent = function(node, tag){
        var pNode = node.parentElement;
        while(pNode && pNode.tagName.toString().toLowerCase() !== tag.toString().toLowerCase()){
            pNode = pNode.parentElement;
        }
        return pNode;
    };
    o2.getOffset = function(evt){
        if (Browser.name==="firefox"){
            return {
                "offsetX": evt.layerX,
                "offsetY": evt.layerY
            };
        }else{
            return {
                "offsetX": evt.offsetX,
                "offsetY": evt.offsetY
            }
        }
    };

    if (String.implement) String.implement({
        "getAllIndexOf": function(str){
            var idxs= [];
            var idx = this.indexOf(str);
            while (idx !== -1){
                idxs.push(idx);
                idx = this.indexOf(str, idx+1);
            }
            return idxs;
        }
    });
    if (Array.implement) Array.implement({
        "trim": function(){
            var arr = [];
            this.each(function(v){
                if (v) arr.push(v);
            });
            return arr;
        },
        "isIntersect": function(arr){
            return this.some(function(item){ return (arr.indexOf(item)!==-1); })
        }
    });
    if (window.Element && Element.implement) Element.implement({
        "isIntoView": function() {
            // var pNode = this.getParent();
            // while (pNode && ((pNode.getScrollSize().y-(pNode.getComputedSize().height+1)<=0) || pNode.getStyle("overflow")==="visible")) pNode = pNode.getParent();
            //
            var pNode = this.getParentSrcollNode();

            if (!pNode) pNode = document.body;
            var size = pNode.getSize();
            var srcoll = pNode.getScroll();
            var p = (pNode == window) ? {"x":0, "y": 0} : this.getPosition(pNode);
            var nodeSize = this.getSize();
            //return (p.x-srcoll.x>=0 && p.y-srcoll.y>=0) && (p.x+nodeSize.x<size.x+srcoll.x && p.y+nodeSize.y<size.y+srcoll.y);
            return (p.x-srcoll.x>=0 && p.y>=0) && (p.x+nodeSize.x<size.x+srcoll.x && p.y+nodeSize.y<size.y)
        },
        "appendHTML": function(html, where){
            if (this.insertAdjacentHTML){
                var whereText = "beforeEnd";
                if (where==="before") whereText = "beforeBegin";
                if (where==="after") whereText = "afterEnd";
                if (where==="bottom") whereText = "beforeEnd";
                if (where==="top") whereText = "afterBegin";
                this.insertAdjacentHTML(whereText, html);
            }else {
                if (where==="bottom") this.innerHTML = this.innerHTML+html;
                if (where==="top") this.innerHTML = html+this.innerHTML;
            }
        },
        "positionTo": function(x,y){
            var left = x.toFloat();
            var top = y.toFloat();
            var offsetNode = this.getOffsetParent();
            if (offsetNode){
                var offsetPosition = offsetNode.getPosition();
                left = left-offsetPosition.x;
                top = top-offsetPosition.y;
            }
            this.setStyles({"top": top, "left": left});
            return this;
        },
        "getBorder": function(){
            var positions = ["top", "left", "right", "bottom"];
            var styles = ["color", "style", "width"];

            var obj = {};
            positions.each(function (position){
                styles.each(function(style){
                    var key = "border-"+position+"-"+style;
                    obj[key] = this.getStyle(key);
                }.bind(this));
            }.bind(this));

            return obj;
        },
        "isOutside": function(e){
            var elementCoords = this.getCoordinates();
            var targetCoords  = this.getCoordinates();
            if(((e.page.x < elementCoords.left || e.page.x > (elementCoords.left + elementCoords.width)) ||
                (e.page.y < elementCoords.top || e.page.y > (elementCoords.top + elementCoords.height))) &&
                ((e.page.x < targetCoords.left || e.page.x > (targetCoords.left + targetCoords.width)) ||
                    (e.page.y < targetCoords.top || e.page.y > (targetCoords.top + targetCoords.height))) ) return true;

            return false;
        },
        "getAbsolutePosition":function(){
            var styleLeft = 0;
            var styleTop = 0;
            var node = this;

            styleLeft = node.offsetLeft;
            styleTop = node.offsetTop;

            node = node.parentElement;

            while (node && node.tagName.toString().toLowerCase()!=="body"){
                styleLeft += node.offsetLeft;
                styleTop += node.offsetTop;
                node = node.offsetParent;
            }
            return {x: styleLeft, y: styleTop};
        },
        "tweenScroll": function(to, time){
            if (!this.tweenScrollQueue){
                this.tweenScrollQueue = [];
            }
            if (this.tweenScrollQueue.length){
                this.tweenScrollQueue.push(to);
            }else{
                this.tweenScrollQueue.push(to);
                this.doTweenScrollQueue(time);
            }
        },
        "doTweenScrollQueue": function(time){
            if (this.tweenScrollQueue.length){
                var i = this.tweenScrollQueue.length;
                var to = this.tweenScrollQueue[this.tweenScrollQueue.length-1];

                var scroll = this.getScroll();
                var dy = to - scroll.y;
                var step = dy/time;
                var count = 0;
                var move = 0;

                var id = window.setInterval(function(){

                    this.scrollTo(0, scroll.y+count*step);
                    count++;
                    if (count>time){
                        window.clearInterval(id);
                        for (var x=1; x<=i; x++) this.tweenScrollQueue.shift();
                        if (this.tweenScrollQueue.length) this.doTweenScrollQueue(time);
                    }
                }.bind(this), 1);
            }
        },
        "isPointIn": function(px, py, offX, offY, el){
            if (!offX) offX = 0;
            if (!offY) offY = 0;
            var position = this.getPosition(el);
            var size = this.getSize();
            return (position.x-offX<=px && position.x+size.x+offX>=px && position.y-offY<=py && position.y+size.y+offY>=py);
        },
        "isInPointInRect": function(sx, sy, ex, ey){
            var position = this.getPosition();
            var size = this.getSize();

            var p1 = {"x": position.x, "y": position.y};
            var p2 = {"x": position.x+size.x, "y": position.y};
            var p3 = {"x": position.x+size.x, "y": position.y+size.y};
            var p4 = {"x": position.x, "y": position.y+size.y};

            var sp = {"x": Math.min(sx, ex), "y": Math.min(sy, ey)};
            var ep = {"x": Math.max(sx, ex), "y": Math.max(sy, ey)};

            if (p1.x>=sp.x && p1.y>=sp.y && p1.x<=ep.x && p1.y<=ep.y) return true;
            if (p2.x>=sp.x && p2.y>=sp.y && p2.x<=ep.x && p2.y<=ep.y) return true;
            if (p3.x>=sp.x && p3.y>=sp.y && p3.x<=ep.x && p3.y<=ep.y) return true;
            if (p4.x>=sp.x && p4.y>=sp.y && p4.x<=ep.x && p4.y<=ep.y) return true;
            if (p3.x>=sp.x && p3.y>=sp.y && p1.x<=sp.x && p1.y<=sp.y) return true;
            if (p3.x>=ep.x && p3.y>=ep.y && p1.x<=ep.x && p1.y<=ep.y) return true;
            if (p1.x<=sp.x && p2.x>=sp.x && p1.y>=sp.y && p4.y<=ep.y) return true;
            if (p1.y<=sp.y && p4.y>=sp.y && p1.x>=sp.x && p2.x<=ep.x) return true;

            return false;
        },
        "isOverlap": function(node){
            var p = node.getPosition();
            var s = node.getSize();
            return this.isInPointInRect(p.x, p.y, p.x+s.x, p.y+s.y);
        },

        "getUsefulSize": function(){
            var size = this.getSize();
            var borderLeft = this.getStyle("border-left").toInt();
            var borderBottom = this.getStyle("border-bottom").toInt();
            var borderTop = this.getStyle("border-top").toInt();
            var borderRight = this.getStyle("border-right").toInt();

            var paddingLeft = this.getStyle("padding-left").toInt();
            var paddingBottom = this.getStyle("padding-bottom").toInt();
            var paddingTop = this.getStyle("padding-top").toInt();
            var paddingRight = this.getStyle("padding-right").toInt();

            var x = size.x-paddingLeft-paddingRight;
            var y = size.y-paddingTop-paddingBottom;

            return {"x": x, "y": y};
        },
        "clearStyles": function(isChild){
            this.removeProperty("style");
            if (isChild){
                var subNode = this.getFirst();
                while (subNode){
                    subNode.clearStyles(isChild);
                    subNode = subNode.getNext();
                }
            }
        },
        "maskIf": function(styles, click){
            var style = {
                "background-color": "#666666",
                "opacity": 0.4,
                "z-index":100
            };
            if (styles){
                style = Object.merge(style, styles);
            }
            var position = this.getPosition(this.getOffsetParent());
            this.mask({
                "destroyOnHide": true,
                "style": style,
                "useIframeShim": true,
                "iframeShimOptions": {"browsers": true},
                "onShow": function(){
                    this.shim.shim.setStyles({
                        "opacity": 0,
                        "top": ""+position.y+"px",
                        "left": ""+position.x+"px"
                    });
                },
                "onClick": click
            });
        },
        "scrollIn": function(where){
            var wh = (where) ? where.toString().toLowerCase() : "center";

            if (Browser.name=="ie" || Browser.name=="safari"){
                var scrollNode = this.getParentSrcollNode();
                var scrollFx = new Fx.Scroll(scrollNode);
                var scroll = scrollNode.getScroll();
                var size = scrollNode.getSize();
                var thisSize = this.getComputedSize();
                var p = this.getPosition(scrollNode);

                if (wh=="start"){
                    var top = 0;
                    scrollFx.start(scroll.x, p.y-top+scroll.y);
                }else if (wh=="end"){
                    var bottom = size.y-thisSize.totalHeight;
                    scrollFx.start(scroll.x, p.y-bottom+scroll.y);
                }else{
                    var center = size.y/2-thisSize.totalHeight/2;
                    scrollFx.start(scroll.x, p.y-center+scroll.y);
                }
            }else{
                if (wh!=="start" && wh!=="end") wh = "center"
                this.scrollIntoView({"behavior": "smooth", "block": wh, "inline": "nearest"});
            }
        },
        scrollToNode: function(el, where){
            var scrollSize = this.getScrollSize();
            if (!scrollSize.y) return true;
            var wh = (where) ? where.toString().toLowerCase() : "bottom";
            var node = $(el);
            var size = node.getComputedSize();
            var p = node.getPosition(this);
            var thisSize = this.getComputedSize();
            var scroll = this.getScroll();
            if (wh==="top"){
                var n = (p.y-thisSize.computedTop);
                if (n<0) this.scrollTo(scroll.x, scroll.y+n);
                n = (size.totalHeight+p.y-thisSize.computedTop)-thisSize.height;
                if (n>0) this.scrollTo(scroll.x, scroll.y+n);

            }else{
                var n = (size.totalHeight+p.y-thisSize.computedTop)-thisSize.height;
                if (n>0) this.scrollTo(scroll.x, scroll.y+n);
                n = p.y-thisSize.computedTop;
                if (n<0) this.scrollTo(scroll.x, scroll.y+n);
            }
        },
        "getInnerStyles": function(){
            var styles = {};
            style = this.get("style");
            if (style){
                var styleArr = style.split(/\s*\;\s*/g);
                styleArr.each(function(s){
                    if (s){
                        var sarr = s.split(/\s*\:\s*/g);
                        styles[sarr[0]] = (sarr.length>1) ? sarr[1]: ""
                    }
                }.bind(this));
            }
            return styles;
        },
        "getInnerProperties": function(){
            var properties = {};
            if (this.attributes.length){
                for (var i=0; i<this.attributes.length; i++){
                    properties[this.attributes[i].nodeName] = this.attributes[i].nodeValue;
                }
            }
            return properties;
        },
        "getZIndex": function(){
            var n = this;
            var i=0;
            while (n){
                if (n.getStyle("position")==="absolute"){
                    var idx = n.getStyle("z-index");
                    i = (idx && idx.toFloat()>i) ? idx.toFloat()+1 : 0;
                    break;
                }
                n = n.getParent();
            }
            return i;
        },
        "getParentSrcollNode": function(){
            var node = this.getParent();
            while (node && (node.getScrollSize().y-2<=node.getSize().y || (node.getStyle("overflow")!=="auto" &&  node.getStyle("overflow-y")!=="auto"))){
                node = node.getParent();
            }
            return node || null;
        },
        "getEdgeHeight": function(notMargin){
            var h = 0;
            h += (this.getStyle("border-top-width").toFloat() || 0)+ (this.getStyle("border-bottom-width").toFloat() || 0);
            h += (this.getStyle("padding-top").toFloat() || 0)+ (this.getStyle("padding-bottom").toFloat() || 0);
            if (!notMargin) h += (this.getStyle("margin-top").toFloat() || 0)+ (this.getStyle("margin-bottom").toFloat() || 0);
            return h;
        },
        "getEdgeWidth": function(notMargin){
            var h = 0;
            h += (this.getStyle("border-left-width").toFloat() || 0)+ (this.getStyle("border-right-width").toFloat() || 0);
            h += (this.getStyle("padding-left").toFloat() || 0)+ (this.getStyle("padding-right").toFloat() || 0);
            if (!notMargin) h += (this.getStyle("margin-left").toFloat() || 0)+ (this.getStyle("margin-right").toFloat() || 0);
            return h;
        }
    });
    Object.copy = function(from, to){
        Object.each(from, function(value, key){
            switch (typeOf(value)){
                case "object":
                    if (!to[key]) to[key]={};
                    Object.copy(value, to[key]);
                    break;
                default:
                    to[key] = value;
            }
        });
    };

    if (window.JSON) JSON.format = JSON.encode;

    if (window.Slick) {
        Slick.definePseudo('src', function (value) {
            return Element.get(this, "src").indexOf(value) !== -1;
        });
        Slick.definePseudo('srcarr', function (value) {
            var vList = value.split(",");
            var src = Element.get(this, "src");
            var flag = false;
            for (var i = 0; i < vList.length; i++) {
                if (src.indexOf(vList[i]) !== -1) {
                    flag = true;
                    break;
                }
            }
            return flag;
        });
        Slick.definePseudo('ahref', function (value) {
            var href = Element.get(this, "href");
            if (!href) href = "";
            href = href.toString().toLowerCase();
            return (href.indexOf(value) !== -1);
        });

        Slick.definePseudo('rowspanBefore', function (line) {
            var tr = MWF.getParent(this, "tr");
            var rowspan = this.get("rowspan").toInt() || 1;
            var currentRowIndex = tr.rowIndex.toInt();

            return rowspan > 1 && currentRowIndex < line.toInt() && currentRowIndex + rowspan - 1 >= line;
        });
        Slick.definePseudo('rowspan', function () {
            var rowspan = this.get("rowspan").toInt() || 1;
            return rowspan > 1;
        });

        Slick.definePseudo('colspanBefore', function (col) {
            var tr = MWF.getParent(this, "tr");
            var colspan = this.get("colspan").toInt() || 1;
            var currentColIndex = this.cellIndex.toInt();

            return colspan > 1 && currentColIndex < col.toInt() && currentColIndex + colspan - 1 >= col.toInt();
        });

        Slick.definePseudo('colspan', function () {
            var colspan = this.get("colspan").toInt() || 1;
            return colspan > 1;
        });
    }

    o2.common = o2.common || {};

    o2.common.encodeHtml = function(str){
        str = str.toString();
        str = str.replace(/\&/g, "&amp;");
        str = str.replace(/>/g, "&gt;");
        str = str.replace(/</g, "&lt;");
        return str.replace(/\"/g, "&quot;");
    };

    o2.common.getResponseTextPost = function(path, body, contentType){
        var returnText = "";
        var options = {
            url: path,
            async: false,
            data: body,
            method: "post",
            onSuccess: function(esponseTree, responseElements, responseHTML, responseJavaScript){
                returnText = responseHTML;
            }
        };
        var r = new Request.HTML(options);
        r.send();
        return returnText;
    };
    o2.common.getResponseText = function(path){
        var returnText = "";
        var options = {
            url: path,
            async: false,
            method: "get",
            onSuccess: function(esponseTree, responseElements, responseHTML, responseJavaScript){
                returnText = responseHTML;
            }
        };
        var r = new Request.HTML(options);
        r.send();
        return returnText;
    };
    o2.common.toDate = function(str){
        var tmpArr = str.split(" ");
        if (!tmpArr[1]) tmpArr.push("0:0:0");
        var dateArr = tmpArr[0].split("-");
        var timeArr = tmpArr[1].split(":");
        return new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],timeArr[0],timeArr[1],timeArr[2]);
    };

    o2.common.toDate = function(str){
        var tmpArr = str.split(" ");
        if (!tmpArr[1]) tmpArr.push("0:0:0");
        var dateArr = tmpArr[0].split("-");
        var timeArr = tmpArr[1].split(":");
        return new Date(dateArr[0],parseInt(dateArr[1])-1,dateArr[2],timeArr[0],timeArr[1],timeArr[2]);
    };

    o2.grayscale = function(src, width, height, callback){
        try {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var imgObj = new Image();
            imgObj.src = src;
            canvas.width = width || imgObj.width;
            canvas.height = height || imgObj.height;
            ctx.drawImage(imgObj, 0, 0);

            var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
            for(var y = 0; y < imgPixels.height; y++){
                for(var x = 0; x < imgPixels.width; x++){
                    var i = (y * 4) * imgPixels.width + x * 4;
                    var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                    imgPixels.data[i] = avg;
                    imgPixels.data[i + 1] = avg;
                    imgPixels.data[i + 2] = avg;
                }
            }
            ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
            var src1 = canvas.toDataURL();
            //var blob = canvas.toBlob();
            canvas.destroy();
            return {"status": "success", "src": src1};
        }catch(e){
            return {"status": "error", "src": src}
        }
    };
    o2.eventPosition = function(e){
        var x = 0;
        var y = 0;
        if (Browser.name=="firefox"){
            x = parseFloat(e.event.clientX || e.event.x);
            y = parseFloat(e.event.clientY || e.event.y);
        }else{
            x = parseFloat(e.event.x);
            y = parseFloat(e.event.y);
        }
        return {"x": x, "y": y};
    };

    if (window.Browser){
        if (Browser.name==="ie" && Browser.version<9){
            Browser.ieuns = true;
        }else if(Browser.name==="ie" && Browser.version<10){
            Browser.iecomp = true;
        }
        if (Browser.iecomp){
            o2.load("ie_adapter", null, false);
            o2.session.isDebugger = true;
            //layout["debugger"] = true;
        }
        o2.session.isMobile = (["mac", "win", "linux"].indexOf(Browser.Platform.name)===-1);
    }
})();
o2.more = true;

//o2.addReady
(function(){
NoSubject's avatar
NoSubject 已提交
2541
    //dom ready
NoSubject's avatar
NoSubject 已提交
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
    var _dom = {
        ready: false,
        loaded: false,
        checks: [],
        shouldPoll: false,
        timer: null,
        testElement: document.createElement('div'),
        readys: [],

        domready: function(){
            clearTimeout(_dom.timer);
            if (_dom.ready) return;
            _dom.loaded = _dom.ready = true;
2555 2556
            o2.removeListener(document, 'DOMContentLoaded', _dom.checkReady);
            o2.removeListener(document, 'readystatechange', _dom.check);
NoSubject's avatar
NoSubject 已提交
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
            _dom.onReady();
        },
        check: function(){
            for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.MooTools && o2.core && o2.more){
                _dom.domready();
                return true;
            }
            return false;
        },
        poll: function(){
            clearTimeout(_dom.timer);
            if (!_dom.check()) _dom.timer = setTimeout(_dom.poll, 10);
        },

        /*<ltIE8>*/
        // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
        // testElement.doScroll() throws when the DOM is not ready, only in the top window
        doScrollWorks: function(){
            try {
                _dom.testElement.doScroll();
                return true;
            } catch (e){}
            return false;
        },
        /*</ltIE8>*/

        onReady: function(){
            for (var i=0; i<_dom.readys.length; i++){
                this.readys[i].apply(window);
            }
        },
        addReady: function(fn){
            if (_dom.loaded){
                if (fn) fn.apply(window);
            }else{
                if (fn) _dom.readys.push(fn);
            }
            return _dom;
        },
        checkReady: function(){
            _dom.checks.push(function(){return true});
            _dom.check();
        }
    };
    var _loadO2 = function(){
2602 2603
        (!o2.core) ? this.o2.load("o2.core", _dom.check) : _dom.check();
        (!o2.more) ? this.o2.load("o2.more", _dom.check) : _dom.check();
NoSubject's avatar
NoSubject 已提交
2604 2605
    };

2606
    o2.addListener(document, 'DOMContentLoaded', _dom.checkReady);
NoSubject's avatar
NoSubject 已提交
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621

    /*<ltIE8>*/
    // If doScroll works already, it can't be used to determine domready
    //   e.g. in an iframe
    if (_dom.testElement.doScroll && !_dom.doScrollWorks()){
        _dom.checks.push(_dom.doScrollWorks);
        _dom.shouldPoll = true;
    }
    /*</ltIE8>*/

    if (document.readyState) _dom.checks.push(function(){
        var state = document.readyState;
        return (state == 'loaded' || state == 'complete');
    });

2622
    if ('onreadystatechange' in document) o2.addListener(document, 'readystatechange', _dom.check);
NoSubject's avatar
NoSubject 已提交
2623 2624 2625 2626
    else _dom.shouldPoll = true;

    if (_dom.shouldPoll) _dom.poll();

NoSubject's avatar
NoSubject 已提交
2627 2628 2629 2630 2631
    if (!window.MooTools){
        this.o2.load("mootools", function(){ _loadO2(); _dom.check(); });
    }else{
        _loadO2();
    }
NoSubject's avatar
NoSubject 已提交
2632 2633
    this.o2.addReady = function(fn){ _dom.addReady.call(_dom, fn); };
})();
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

//compatible
COMMON = {
    "DOM":{},
    "setContentPath": function(path){
        COMMON.contentPath = path;
    },
    "JSON": o2.JSON,
    "Browser": Browser,
    "Class": o2.Class,
    "XML": o2.xml,
    "AjaxModule": {
        "load": function(urls, callback, async, reload){
            o2.load(urls, callback, reload, document);
        },
        "loadDom":  function(urls, callback, async, reload){
            o2.load(urls, callback, reload, document);
        },
        "loadCss":  function(urls, callback, async, reload, sourceDoc){
            o2.loadCss(urls, document.body, callback, reload, sourceDoc);
        }
    },
    "Request": Request,
    "typeOf": o2.typeOf
};
COMMON.Browser.Platform.isMobile = o2.session.isMobile;
COMMON.DOM.addReady = o2.addReady;
MWF = o2;
MWF.getJSON = o2.JSON.get;
MWF.getJSONP = o2.JSON.getJsonp;
NoSubject's avatar
NoSubject 已提交
2664
MWF.defaultPath = o2.session.path;