VaKeR CYBER ARMY
Logo of a company Server : Apache/2.4.41 (Ubuntu)
System : Linux absol.cf 5.4.0-198-generic #218-Ubuntu SMP Fri Sep 27 20:18:53 UTC 2024 x86_64
User : www-data ( 33)
PHP Version : 7.4.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Directory :  /var/www/html/tech_preview/hr/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //var/www/html/tech_preview/hr/new_module.js
'use strict';

contentModule.getDateTimeExcelExport = function(timesend){
    if (!timesend) return "";
    var res = "";
    var month, day, year, hour, minute;
    month = timesend.getMonth() + 1;
    day = timesend.getDate();
    year = timesend.getFullYear();
    hour = timesend.getHours();
    minute = timesend.getMinutes();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minute < 10) {
        minute = "0" + minute;
    }
    res += year;
    res += month;
    res += day;
    res += "_" + hour;
    res += minute;
    return res;
};

function UnreadMessageLine() {
    this.$text = absol.$('.chat-unreadmessage-line-text', this);
    this.$leftLine = absol.$('.chat-unreadmessage-line-left', this);
    this.$rightLine = absol.$('.chat-unreadmessage-line-right', this);

    this.$attachhook = absol._('attachhook').addTo(this)
        .on('error', this.updateSize.bind(this));
};

UnreadMessageLine.render = function(){
    return absol._({
        class: 'chat-unreadmessage-line',
        child:[
            {
                tag:'span',
                class: 'chat-unreadmessage-line-text',
                child: { text: 'Unread messages'}
            },
            '.chat-unreadmessage-line-left',
            '.chat-unreadmessage-line-right'
        ]
    });
};

UnreadMessageLine.prototype.updateSize = function(){
    var textBound = this.$text.getBoundingClientRect();
    this.$leftLine.addStyle('right', 'calc(50% + '+ (textBound.width / 2 + 10)+'px)');
    this.$rightLine.addStyle('left', 'calc(50% + '+(textBound.width / 2 + 10)+'px)');
};

UnreadMessageLine.property = {};

UnreadMessageLine.property.text = {
    set: function(value){
        this._text = value + '';
        this.$text.clearChild().addChild(absol._({text: value}));
    },
    get: function(){
        return this._text;
    }
};

absol.coreDom.install('unreadmessageline',UnreadMessageLine);

theme.MesssageItem = function MesssageItem(){
    this.$avatar = absol.$('.chat-message-item-avatar', this);
    this.$name = absol.$('.chat-message-item-name', this);
    this.$time = absol.$('.chat-message-item-time', this);
    this.$messagetext = absol.$('.chat-message-item-message-text', this);
    this.$new_noseen = absol.$('.chat-message-item-new-noseen', this);
    this.$cmd_menu = absol.$('.chat-message-item-cmd-menu', this);
    this.on('click', this.eventHandler.click);//gắn hàm xử ló sự kiện vào bản thân nó
};


theme.MesssageItem.tag = 'messageitem';

theme.MesssageItem.render = function(){
    return absol._({
        extendEvent: ['pressopen'],
        class: 'chat-message-item',
        child:[
            {
                class: 'chat-message-item-avatar'
            },
            {
                class:'chat-message-item-content-ctn',
                child:[
                    {
                        class:'chat-message-item-title',
                        child:[
                            {
                                class:'chat-message-item-name'
                            },
                            {
                                class:'chat-message-item-time'
                            }
                        ]
                    },
                    {
                    class:'chat-message-item-message',
                    child:[
                        {
                            class:'chat-message-item-message-text'
                        },
                        {
                            class:'chat-message-item-cmd',
                            child: [
                                {
                                    class:'chat-message-item-new-noseen'
                                },
                                {
                                    class:'chat-message-item-cmd-menu'
                                }
                            ]
                        }
                    ]
                    }
                ]
            }
        ]
    });
};

theme.MesssageItem.property = {};

theme.MesssageItem.property.avatarSrc = {
    set: function(value){
        this.$avatar.style.backgroundImage = "url(" + value + ")";
    },
    get: function(){
        return this.$avatar.src;
    }
};

theme.MesssageItem.property.name = {
    set: function(value){
        this._name = value + '';
        this.$name.clearChild().addChild(absol._({text: value}));
    },
    get: function(){
        return this._name;
    }
};

theme.MesssageItem.property.isActive = {
    set: function(value){
        if (value){
            this.addClass("is-active");
        }
        else {
            this.removeClass("is-active");
        }
        this._active = value;
    },
    get: function(){
        return this._active;
    }
};

theme.MesssageItem.property.time = {
    set: function(value){
        this._time = value;
        if (value){
            this.$time.clearChild().addChild(absol._({text: contentModule.getTimeMessageList(value)}));
        }
        else {
            this.$time.clearChild();
        }
    },
    get: function(){
        return this._time;
    }
};

theme.MesssageItem.property.messagetext = {
    set: function(value){
        this._messagetext = value + '';
        this.$messagetext.clearChild().addChild(absol._({text: value}));
    },
    get: function(){
        return this._messagetext;
    }
};

theme.MesssageItem.property.new_noseen = {
    set: function(value){
        this._new_noseen = value;
        if (value > 0){
            if (value > 9) value = "9+";
            var elt = absol.buildDom({
                class: "chat-button-number",
                child: [absol._({text: value})]
            });
            this.$new_noseen.clearChild().addChild(elt);
        }
        else {
            this.$new_noseen.clearChild();
        }
    },
    get: function(){
        return this._new_noseen;
    }
};

absol.coreDom.install( theme.MesssageItem);


theme.MesssageItem.eventHandler = {};

theme.MesssageItem.eventHandler.click = function(event){
    if (!absol.EventEmitter.hitElement(this.$cmd, event)){//không phải click vào cmd
        this.emit('pressopen', {target: this, type: 'pressopen'}, this);
    }
};



contentModule.MessageReceiver = (function () {
    function MessageReceiver() {
        absol.EventEmitter.call(this);
    }

    absol.OOP.mixClass(MessageReceiver, absol.EventEmitter);

    MessageReceiver.prototype.handleMessage = function (message) {
        switch (message.content.messageType) {
            case "comment":
                this.emit('comment', message.content);
                break;
            case "chat":
                this.emit('chat', message.content);
                break;
            case "change_data_module":
                if (!data_module.listMessRandomCreate[message.content.randomId]){
                    switch (message.content.table){
                        case "employees":
                            data_module.loadAllEmployeesList();
                            break;
                        case "partner":
                            data_module.loadDataPartnerGlobal();
                            break;
                        case "partner_class":
                            data_module.loadDataPartnerClassGlobal();
                            break;
                        case "contact":
                            data_module.loadDataContactGlobal();
                            break;
                    }
                }
                break;
            case "change_data_type_flex":
                if (!data_module.listMessRandomCreate[message.content.randomId]){
                    ModalElement.alert({
                        title: LanguageModule.text("txt_maintenance_and_upgrade"),
                        message: LanguageModule.text2("war_txt_maintenance_and_upgrade", [1])
                    });
                    setTimeout(function(){
                        window.location.reload();
                    }, 60000);
                }
                break;
            default:

        }
    }


    return MessageReceiver;
})();


contentModule.shareMessageReceiver = new contentModule.MessageReceiver();

contentModule.reactionComment = function (host, localid, icon) {
    return new Promise(function (resolve, reject) {
        var data = {
            commentid: host.commentid,
            localid: localid
        };
        if (icon === "REMOVE") {
            data.type = "remove";
        }
        else {
            data.type = "add";
            data.emoji = icon.text;
        }
        FormClass.api_call({
            url: "hr_reaction_comment.php",
            params: [{ name: "data", value: EncodingClass.string.fromVariable(data) }],
            func: function (success, message) {
                if (success) {
                    if (message.substr(0, 2) == "ok") {
                        var extra = EncodingClass.string.toVariable(message.substr(2));
                        resolve(extra);
                        var randomId = contentModule.generateRandom();
                        host.listMessRandomCreate[randomId] = true;
                        hr.sendMessageFunc({
                            messageType: "comment",
                            type: "reaction",
                            id: host.commentid,
                            localid: localid,
                            commentid: host.commentid,
                            taskid: host.comment_taskid,
                            tablename: host.comment_tablename,
                            randomId: randomId,
                            extra: extra
                        });
                    }
                    else {
                        console.log(message);
                    }
                }
                else {
                    console.log(message);
                }
            }
        })
    });
};

contentModule.deleteComment = function (host, localid) {
    return new Promise(function (resolve, reject) {
        var data = {
            localid: localid,
            commentid: host.commentid
        };
        FormClass.api_call({
            url: "hr_delete_comment.php",
            params: [{ name: "data", value: EncodingClass.string.fromVariable(data) }],
            func: function (success, message) {
                if (success) {
                    if (message.substr(0, 2) == "ok") {
                        resolve();
                        var randomId = contentModule.generateRandom();
                        host.listMessRandomCreate[randomId] = true;
                        hr.sendMessageFunc({
                            messageType: "comment",
                            type: "delete",
                            localid: localid,
                            id: host.commentid,
                            taskid: host.comment_taskid,
                            tablename: host.comment_tablename,
                            randomId: randomId
                        });
                    }
                    else {
                        // console.log(message);
                    }
                }
                else {
                    // console.log(message);;
                }
            }
        });
    });
};

contentModule.editComment = function (host, localid, content, quote) {
    return new Promise(function (resolve, reject) {
        var data = {
            localid: localid,
            commentid: host.commentid,
            content: content,
            quote: quote
        };
        FormClass.api_call({
            url: "hr_edit_comment.php",
            params: [{ name: "data", value: EncodingClass.string.fromVariable(data) }],
            func: function (success, message) {
                if (success) {
                    if (message.substr(0, 2) == "ok") {
                        var randomId = contentModule.generateRandom();
                        host.listMessRandomCreate[randomId] = true;
                        var dataDraw = {
                            messageType: "comment",
                            type: "edit",
                            localid: localid,
                            content: content,
                            quote: quote,
                            id: host.commentid,
                            taskid: host.comment_taskid,
                            tablename: host.comment_tablename,
                            randomId: randomId
                        };
                        resolve(dataDraw);
                        hr.sendMessageFunc(dataDraw);
                    }
                    else {
                        ModalElement.alert({ message: message });
                    }
                }
                else {
                    var dataDraw = {
                        type: "edit",
                        localid: localid,
                        content: content,
                        id: host.commentid,
                        randomId: randomId,
                        failed: true
                    };
                    resolve(dataDraw);
                }
            }
        });
    });
};

contentModule.seenComment = function (host, localid) {
    return new Promise(function (resolve, reject) {
        if (host.commentid == 0) return;
        FormClass.api_call({
            url: "hr_seen_comment.php",
            params: [
                { name: "commentid", value: host.commentid},
                { name: "comment_seenid", value: localid }
            ],
            func: function (success, message) {
                if (success) {
                    if (message.substr(0, 2) == "ok") {
                        resolve();
                    }
                    else {
                        ModalElement.alert({ message: message });
                    }
                }
                else {
                    ModalElement.alert({ message: message });
                }
            }
        });
    });
};

contentModule.saveComment = function (host, taskid, tablename, text, files, images, quote, listIdLocal, tagList) {
    return new Promise(function (resolveMessage, rejectMessage) {
        var listFile = files.concat(images);
        var allUploadFiles = [];
        listFile.forEach(function (file, index) {
            allUploadFiles.push(new Promise(function (rs, rj) {
                function saveFile() {
                    var typeFile;
                    if (file.type.startsWith('image/')) {
                        typeFile = "img";
                    }
                    else {
                        typeFile = "file";
                    }
                    var path = ["hr", "files"];
                    systemconfig.connectorFile.upload({
                        index: 0,
                        path: path,
                        filehandle: file,
                        filename: listIdLocal[index] + "_" + file.name + ".upload",
                        onsuccess: function (content) {
                            rs({
                                type: typeFile,
                                name: file.name
                            });
                        },
                        onfailed: function (content) {
                            ModalElement.alert({ message: LanguageModule.text("war_txt_no_upload_file") });
                            console.log(message);
                        }
                    });
                };
                systemconfig.loadFolderFunc().then(function (value) {
                    if (value) saveFile();
                    else {
                        systemconfig.reconnectFile().then(function () {
                            saveFile();
                        });
                    }
                });
            }));
        });
        Promise.all(allUploadFiles).then(function (listMessageFile) {
            var dataDraw = [];
            dataDraw.id = host.commentid;
            var paramsUrl = [
                {
                    name: "id",
                    value: host.commentid
                },
                {
                    name: "fullname",
                    value: systemconfig.fullname
                },
                {
                    name: "text",
                    value: text
                },
                { name: "listIdLocal", value: EncodingClass.string.fromVariable(listIdLocal) },
                { name: "tagList", value: EncodingClass.string.fromVariable(tagList) },
                { name: "listMessageFile", value: EncodingClass.string.fromVariable(listMessageFile) },
                { name: "tablename", value: tablename },
                { name: "taskid", value: taskid },
                { name: "userSendNotiList", value: EncodingClass.string.fromVariable(host.userSendNotiList) }
            ];
            if (quote) {
                paramsUrl.push({
                    name: "quote",
                    value: EncodingClass.string.fromVariable(quote)
                });
            }
            FormClass.api_call({
                url: "hr_save_comment.php",
                params: paramsUrl,
                func: function (success, message) {
                    var drawMessage = function (failed) {
                        for (var i = 0; i < listMessageFile.length; i++) {
                            if (listMessageFile[i].type == "img") {
                                dataDraw.push({
                                    localid: listIdLocal[i],
                                    content: listMessageFile[i].name,
                                    userid: systemconfig.userid,
                                    fullname: systemconfig.fullname,
                                    content_type: "img",
                                    m_time: new Date(),
                                    failed: failed
                                });
                            }
                            else {
                                dataDraw.push({
                                    localid: listIdLocal[i],
                                    content: listMessageFile[i].name,
                                    userid: systemconfig.userid,
                                    fullname: systemconfig.fullname,
                                    content_type: "file",
                                    m_time: new Date(),
                                    failed: failed
                                });
                            }
                        }
                        if (text != "" || quote) {
                            dataDraw.push({
                                localid: listIdLocal[listIdLocal.length - 1],
                                content: text,
                                userid: systemconfig.userid,
                                fullname: systemconfig.fullname,
                                content_type: "text",
                                m_time: new Date(),
                                failed: failed,
                                extra: {
                                    quote: quote
                                }
                            });
                        }
                        resolveMessage(dataDraw);
                        if (!failed) {
                            var randomId = contentModule.generateRandom();
                            host.listMessRandomCreate[randomId] = true;
                            hr.sendMessageFunc({
                                messageType: "comment",
                                type: "add",
                                dataDraw: dataDraw,
                                id: host.commentid,
                                taskid: host.comment_taskid,
                                tablename: host.comment_tablename,
                                randomId: randomId,
                                userReceiveNotiList: host.userReceiveNotiList
                            });
                            if (host.usertagList.length > 0) hr.sendMessageFunc({
                                messageType: "comment",
                                type: "tag",
                                dataDraw: dataDraw,
                                id: host.commentid,
                                taskid: host.comment_taskid,
                                tablename: host.comment_tablename,
                                randomId: randomId,
                                usertagList: host.usertagList
                            });
                        }
                    };
                    if (success) {
                        if (message.substr(0, 2) == "ok") {
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            host.commentid = st.commentid;
                            host.userReceiveNotiList = st.userReceiveNotiList;
                            host.usertagList = st.usertagList;
                            for (var i = 0; i < st.newLogs.length; i++){
                                host.database.user_tag_employee_logs.items.push(st.newLogs[i]);
                            }
                            drawMessage();
                        }
                        else {
                            ModalElement.alert({ message: message });
                        }
                    }
                    else {
                        drawMessage(true);
                    }
                }.bind(this)
            });
        }.bind(this));
    });
};

contentModule.drawCommentInside = function(params){
    return new Promise(function(resolve, reject){
        var chatBox;
        var loadData = function(){
            return new Promise(function(rs, rj){
                FormClass.api_call({
                    url: "database_load.php",
                    params: [
                        { name: "task", value: "load_comment_single"},
                        { name: "tablename", value: params.tablename },
                        { name: "taskid", value: params.taskid }
                    ],
                    func: function (success, message) {
                        if (success) {
                            if (message.substr(0, 2) == "ok") {
                                var st = EncodingClass.string.toVariable(message.substr(2));
                                console.log(st);
                                rs(st);
                            }
                            else {
                                ModalElement.alert({ message: message });
                            }
                        }
                        else {
                            ModalElement.alert({ message: message });
                        }
                    }
                });
            });
        };
        Promise.all([loadData(), data_module.loadEmployeeItemsPrivView(), data_module.loadUserTagEmployeeLogs()]).then(function(values){
            var host = values[1];
            host.userSendNotiList = params.userSendNotiList? params.userSendNotiList : [];
            host.listMessRandomCreate = {};
            contentModule.makeDatabaseContent(host, values[0]);
            contentModule.makeDatabaseContent(host, values[2]);
            var content = [], mess_seen_id = 0;
            host.commentid = 0;
            host.comment_taskid = params.taskid;
            host.comment_tablename = params.tablename;
            if (values[0].comments.length > 0) {
                content = EncodingClass.string.toVariable(values[0].comments[0].content);
                host.commentid = values[0].comments[0].id;
            }
            chatBox = new ChatBox({
                disabled: params.disabled,
                database: host.database,
                isComment: true,
                data: {
                    content: content,
                    mess_seen_id: values[0].comment_seenid,
                    id: host.commentid,
                    sendFunc: function (text, files, images, quote, listIdLocal, tagList) {
                        return contentModule.saveComment(host, params.taskid, params.tablename, text, files, images, quote, listIdLocal, tagList);
                    },
                    seenFunc: function (localid) {
                        return contentModule.seenComment(host, localid);
                    },
                    editMessageFunc: function (localid, content, quote) {
                        return contentModule.editComment(host, localid, content, quote);
                    },
                    reactionMessageFunc: function (localid, icon) {
                        return contentModule.reactionComment(host, localid, icon);
                    },
                    deleteMessageFunc: function (localid) {
                        return new Promise(function (rs, rj) {
                            contentModule.deleteComment(host, localid).then(function (value) {
                                for (var j = 0; j < chatBox.content.length; j++) {
                                    if (chatBox.content[j].localid == localid && (chatBox.content[j].content_type == "img" || chatBox.content[j].content_type == "file")) {
                                        var filename = localid + "_" + chatBox.content[j].content + ".upload";
                                        var path;
                                        path = ["hr", "files"];

                                        function deleteFile() {
                                            systemconfig.connectorFile.delete({
                                                index: 0,
                                                path: path,
                                                files: [filename],
                                                onsuccess: function () {
                                                    console.log("success");
                                                },
                                                onfailed: function (content) {
                                                    console.log(content);
                                                }
                                            });
                                        };
                                        systemconfig.loadFolderFunc().then(function (value) {
                                            if (value) deleteFile();
                                            else {
                                                systemconfig.reconnectFile().then(function () {
                                                    deleteFile();
                                                });
                                            }
                                        });
                                        break;
                                    }
                                }
                                rs(value);
                            });
                        });
                    }
                }
            });
            contentModule.shareMessageReceiver.on('comment', function (messageContent) {
                if (!host.listMessRandomCreate[messageContent.randomId] && messageContent.tablename == host.comment_tablename && messageContent.taskid == host.comment_taskid) {
                    host.commentid = messageContent.id;
                    switch (messageContent.type){
                        case "add":
                            chatBox.content = chatBox.content.concat(messageContent.dataDraw);
                            for (var i = 0; i < messageContent.dataDraw.length; i++){
                                chatBox.addMessage(messageContent.dataDraw[i]);
                            }
                            break;
                        case "edit":
                            chatBox.editMessageRedraw(messageContent.localid, messageContent.content, messageContent.quote);
                            break;
                        case "delete":
                            for (var i = 0; i < chatBox.content.length; i++) {
                                if (chatBox.content[i].localid == messageContent.localid) {
                                    chatBox.content.splice(i, 1);
                                    break;
                                }
                            }
                            chatBox.deleteMessageRedraw(messageContent.localid);
                            break;
                        case "reaction":
                            chatBox.reactionMessageRedraw(messageContent.localid, messageContent.extra.emoji);
                            break;
                        default:

                    }
                }
            });
            resolve(chatBox);
        })
    });
};

contentModule.getTimeMessage = function (timeview) {
    var now = new Date();
    var res = "";
    var seenHours = timeview.getHours();
    if (seenHours < 10) {
        seenHours = "0" + seenHours;
    }
    var seenMinutes = timeview.getMinutes();
    if (seenMinutes < 10) {
        seenMinutes = "0" + seenMinutes;
    }
    return seenHours + ":" + seenMinutes;
};

function MKNav() {
    this._items = [];
    this._value = null;
    this._value2Idx = {};
    this.$lastItem = null;
}

MKNav.tag = 'mknav';

MKNav.render = function () {
    return absol._({
        extendEvent: ['clickitem'],
        class: 'mk-nav'
    })
};

MKNav.property = {};

MKNav.property.value = {
    set: function (val) {
        this._value = val;
        var idx = this._value2Idx[val];
        if (idx !== undefined) {
            this.addStyle('--mk-nav-line-top', 40 * idx + 'px');
            if (this.$lastItem) {
                this.$lastItem.removeClass('mk-current');
            }

            this.$lastItem = this.childNodes[idx];
            this.$lastItem.addClass('mk-current');
        }

    },
    get: function () {
        return this._value;
    }
};

MKNav.property.items = {
    set: function (items) {
        items = items || [];
        this._items = items;
        this.clearChild();
        var self = this;
        this._value2Idx = {};
        items.forEach(function (item, idx) {
            var itemElt = absol._({
                class: 'mk-nav-item',
                child: { text: item.text },
                on: {
                    click: function () {
                        self.value = item.value;
                        self.emit('clickitem', { typel: 'clickitem', item: item }, this);
                    }
                }
            });
            self._value2Idx[item.value] = idx;
            self.addChild(itemElt);
        });

        this.value = this._value;//update

    },
    get: function () {
        return this._items;
    }
}
absol.coreDom.install(MKNav);

var ChatBox = function (params) {
    this.database = params.database;
    this.content = params.data.content;
    this.name = params.data.name;
    this.sendFunc = params.data.sendFunc;
    this.mess_seen_id = params.data.mess_seen_id;
    this.seenFunc = params.data.seenFunc;
    this.loadOldMessFunc = params.data.loadOldMessFunc;
    this.editMessageFunc = params.data.editMessageFunc;
    this.deleteMessageFunc = params.data.deleteMessageFunc;
    this.reactionMessageFunc = params.data.reactionMessageFunc;
    this.isNotiCenter = params.isNotiCenter;
    this.viewNameChat = params.viewNameChat;
    this.disabled = params.disabled;
    this.isComment = params.isComment;
};

ChatBox.prototype.setDisabled = function(status){
    this.disabled = status;
    if (status){
        this.vInputContainer.style.display = "none";
    }
    else {
        this.vInputContainer.style.display = "";

    }
};

ChatBox.prototype.getCounters = function (emoji) {
    var counters = {};
    var userIndex;
    for (var i = 0; i < emoji.length; i++) {
        if (counters[emoji[i].text] === undefined) {
            counters[emoji[i].text] = {
                count: 0,
                users: []
            };
        }
        userIndex = this.database.users.getByhomeid(emoji[i].userid);
        if (userIndex < 0) continue;
        counters[emoji[i].text].count++;
        if (counters[emoji[i].text][emoji[i].userid]) continue;
        counters[emoji[i].text].users.push({
            name: (emoji[i].userid == systemconfig.userid) ? LanguageModule.text("txt_you") : this.database.users.items[userIndex].fullname,
            avatar: this.database.users.items[userIndex].avatarSrc
        });
        counters[emoji[i].text][emoji[i].userid] = true;
    }
    return counters;
};

ChatBox.prototype.reactionMessageRedraw = function (localid, emoji) {
    var self = this;
    var elt, type;
    for (var i = 0; i < self.listMessLocalid.length; i++) {
        if (self.listMessLocalid[i].localid == localid) {
            elt = self.listMessLocalid[i].elt;
        }
    }
    if (!elt) return;
    var messelt = absol.$("div", elt, function (e) {
        return e.classList.contains("card-chatbox-message-me") || e.classList.contains("card-chatbox-message-other")
            || e.classList.contains("card-chatbox-message-other-img") || e.classList.contains("card-chatbox-message-me-img");
    });
    if (!messelt) return;
    var emojielt = absol.$(".chats-message-emoji-list-ctn", messelt);
    if (!emojielt) return;
    if (emoji.length == 0) {
        messelt.style.marginBottom = 0;
        emojielt.style.display = "none";
    }
    else {
        emojielt.style.display = "";
        if (!emojielt.firstChild) {
            var emojiCounterList = absol.buildDom({
                tag: 'emojicounterlist'
            }).addTo(emojielt);
        }
        emojielt.firstChild.counters = self.getCounters(emoji);
        messelt.style.marginBottom = emojielt.clientHeight - 10 + "px";
    }
};

ChatBox.prototype.reactionMessage = function (id, icon) {
    var self = this;
    self.reactionMessageFunc(id, icon).then(function (values) {
        for (var j = 0; j < self.content.length; j++) {
            if (self.content[j].localid == id) {
                self.content[j].extra = values;
                break;
            }
        }
        self.reactionMessageRedraw(id, values.emoji);
    });
};

ChatBox.prototype.addGallery = function(data){
    var self = this;
    var res;
    if (!contentModule.compareDate(data.m_time, self.lastTimeGallery)){
        res = DOMElement.div({
            attrs: {
                className: "chats-theme-gallery-time-separate"
            },
            text: contentModule.getTimeGallerySeparate(data.m_time)
        });
        self.information_content.appendChild(res);
    }
    var fullname = "";
    if (data.userid == systemconfig.userid){
        fullname = LanguageModule.text("txt_you");
    }
    else {
        var uIndex = self.database.users.getByhomeid(data.userid);
        if (uIndex >= 0){
            fullname = self.database.users.items[uIndex].fullname;
        }
    }
    var item;
    switch (data.content_type) {
        case "text":
            var aobjs = absol.parseMessage(data.content, {tagMap: self.tagMap});
            aobjs.forEach(function(aobj){
                if (aobj.tag == 'a'){
                    aobj.attr = aobj.attr || {};
                    aobj.attr.target = '_blank';// mở tab mới
                    aobj.style = aobj.style ||{};
                    aobj.style.cursor =  "pointer";
                    aobj.style.textDecoration =  "underline";
                }
            });
            var texts = aobjs.map(function(aobj){
                return absol._(aobj);// chuyển qua dom object cho giống code cũ
            });
            item = DOMElement.div({
                attrs: {
                    style: {
                        padding: "10px"
                    }
                },
                children: texts
            });
            break;
        case "file":
            var suffFile = data.content.split('.').pop();
            var fileIcon;
            if (contentModule.listSuffFiles.indexOf(suffFile) >= 0) {
                fileIcon = suffFile + ".svg";
            }
            else {
                fileIcon = "default.svg";
            }
            var fileHref;
            if (data.old_cd) fileHref = window.domainFilesCD + data.localid + "_"  + data.content + ".upload";
            else fileHref = window.domainFilesNew + data.localid + "_"  + data.content + ".upload";
            item = DOMElement.div({
                attrs: {
                    style: {
                        padding: "10px"
                    }
                },
                children: [DOMElement.a({
                    attrs:{
                        onclick: function(){
                            absol.FileSaver.saveAs(fileHref, data.content);
                        },
                        style:{
                            cursor: "pointer",
                            color: "black",
                            textDecoration: "none"
                        }
                    },
                    children: [DOMElement.table({
                        data: [[
                            DOMElement.div({
                                attrs: {
                                    style: {
                                        height: "50px",
                                        width: "50px",
                                        textAlign: "center",
                                        verticalAlign: "middle",
                                        display: "table-cell"
                                    }
                                },
                                children: [DOMElement.img({
                                    attrs: {
                                        src:  window.originHost + "/vivid_exticons/" + fileIcon,
                                        style: {
                                            maxHeight: "50px",
                                            maxWidth: "50px"
                                        }
                                    }
                                })]
                            }),
                            { attrs: { style: { width: "20px" } } },
                            { text: data.content }
                        ]]
                    })]
                })]
            });
            break;
        case "img":
            var srcimg;
            if (data.old_cd) srcimg = window.domainImagesCD + data.localid + "_" + data.content + ".upload";
            else srcimg = window.domainFilesNew + data.localid + "_" + data.content + ".upload";
            if (data.loading !== undefined){
                srcimg = URL.createObjectURL(data.object)
            }
            item = DOMElement.div({
                attrs: {
                    style: {
                        maxWidth: "100%"
                    }
                },
                children: [DOMElement.img({
                    attrs: {
                        src: srcimg,
                        style: {
                            maxHeight: "100%",
                            maxWidth: "100%"
                        },
                        onclick: function(id){
                            return function(event, me){
                                document.body.appendChild(descViewImagePreview(self.dataImageListView, id));
                            }
                        }(data.localid)
                    }
                })]
            });
            break;

    }
    res = DOMElement.div({
        children: [
            DOMElement.div({
                attrs: {
                    className: "chats-theme-gallery-time"
                },
                text: fullname + ", " + absol.datetime .formatDateTime(data.m_time, 'HH:mm')
            }),
            DOMElement.div({
                attrs: {
                    className: "chats-theme-gallery-content-ctn"
                },
                children: [item]
            })
        ]
    });
    self.information_content.appendChild(res);
    self.lastTimeGallery = data.m_time;
};

ChatBox.prototype.changeTypeGallery = function(type){
    var self = this;
    var list = [];
    switch (type) {
        case "all":
            list = self.dataImageList.concat(self.dataLinkList);
            list = list.concat(self.dataFileList);
            break;
        case "files":
            list = self.dataFileList;
            break;
        case "links":
            list = self.dataLinkList;
            break;
        case "image":
            list = self.dataImageList;
            break;
    }
    list.sort(function(a, b){
        return b.m_time.getTime() - a.m_time.getTime();
    });
    self.lastTimeGallery = new Date(0);
    DOMElement.removeAllChildren(self.information_content);
    self.information_content.appendChild(DOMElement.textNode(""));
    for (var i = 0; i < list.length; i++){
        self.addGallery(list[i]);
    }
};

ChatBox.prototype.toggleGallery = function(){
    if (this.chats_gallery.style.display == "inline-block"){
        this.chats_gallery.style.display = "none";
        this.icon_gallery.style.color = "#929292";
        this.chatBodyContent.style.width = "100%";
    }
    else {
        this.chats_gallery.style.display = "inline-block";
        this.icon_gallery.style.color = "#0068ff";
        this.chatBodyContent.style.width = "calc(100% - var(--chat-desktop-gallery))";
    }
    if (this.openToggle) return;
    this.changeTypeGallery("all");
    this.openToggle = true;
};

ChatBox.prototype.galleryHeader = function(){
    var self = this;
    return DOMElement.div({
        attrs: {className: "chats-theme-desktop-information-name-container"},
        children: [
            DOMElement.div({
                attrs: {
                    className: "card-icon-cover"
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "material-icons bsc-icon-hover-black",
                        onclick: function(){
                            self.toggleGallery();
                        }
                    },
                    text: "clear"
                })]
            }),
            DOMElement.span({
                attrs: {
                    className: "chats-theme-desktop-gallery-title"
                },
                text: LanguageModule.text("txt_gallery")
            }),
            absol.buildDom({
                tag: "selectmenu",
                style: {
                    position: "absolute",
                    top: "10px",
                    right: "0"
                },
                props: {
                    items: [
                        {value: "all", text: LanguageModule.text("txt_all")},
                        {value: "image", text: LanguageModule.text("txt_images")},
                        {value: "files", text: LanguageModule.text("txt_files")},
                        {value: "links", text: LanguageModule.text("txt_links")}
                    ]
                },
                on: {
                    change: function(){
                        self.changeTypeGallery(this.value);
                    }
                }
            })
        ]
    });
};

ChatBox.prototype.createMessage = function (data) {
    var self = this;
    var className, classNameImg;
    if (data.userid == systemconfig.userid) {
        className = "card-chatbox-message-me";
        classNameImg = "card-chatbox-message-me-img";
    }
    else {
        className = "card-chatbox-message-other";
        classNameImg = "card-chatbox-message-other-img";
    }
    var res, messelt;
    if (data.extra === undefined) data.extra = {};
    if (data.extra.emoji === undefined) data.extra.emoji = [];
    switch (data.content_type) {
        case "text":
            var texts;
            var aobjs = absol.parseMessage(data.content, {tagMap: self.tagMap});// trả về một array theo cú pháp absol
            // thêm vài thuộc tính cho thẻ a
            aobjs.forEach(function (aobj) {
                if (aobj.tag == 'a') {
                    aobj.attr = aobj.attr || {};
                    aobj.attr.target = '_blank';// mở tab mới
                    aobj.style = aobj.style || {};
                    aobj.style.cursor = "pointer";
                    aobj.style.textDecoration = "underline";
                }
            });
            for (var i = 0; i < aobjs.length; i++) {
                if (aobjs[i].tag == "a") {
                    self.dataLinkList.push(data);
                    break;
                }
            }
            res = DOMElement.div({
                attrs: {
                    className: "card-chatbox-message-line"
                }
            });
            var extra = DOMElement.div({
                attrs: { className: "card-chatbox-extra-ctn" }
            });
            if (data.userid == systemconfig.userid) {
                res.appendChild(extra);
            }
            var emoji_icon = DOMElement.div({
                attrs: {
                    className: "card-icon-emoji-message-cover"
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "mdi mdi-emoticon-happy-outline card-icon-emoji-message"
                    }
                })]
            });
            var EmojiPickerTooltip = absol.require('emojipickertooltip');
            EmojiPickerTooltip.toggleWhenClick(emoji_icon, {
                onSelect: function (icon) {
                    self.reactionMessage(data.localid, icon);
                }, orientation: 'top'
            });
            extra.appendChild(emoji_icon);
            var xextra = [];
            if (data.loading !== undefined) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.img({
                        attrs: {
                            className: "material-icons card-icon-loading-message",
                            src: window.domain + "./loading.gif"
                        }
                    })]
                }))
            }
            else if (data.failed !== undefined && data.failed) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-failed-message"
                        },
                        text: "error_outline"
                    })]
                }));
            }
            if (data.userid == systemconfig.userid && data.isEdit !== undefined) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-edit-message"
                        },
                        text: "create"
                    })]
                }));
            }
            if (xextra.length > 0) {
                extra.appendChild(DOMElement.div({
                    children: xextra
                }));
            }
            texts = aobjs.map(function (aobj) {
                return absol._(aobj);// chuyển qua dom object cho giống code cũ
            });
            if (data.extra.quote) {
                var childrenText = [
                    absol.buildDom({
                        tag: "messagequote",
                        style: {
                            cursor: "pointer",
                            marginBottom: "5px"
                        },
                        props: {
                            data: data.extra.quote,
                            tagMap: self.tagMap
                        },
                        on: {
                            click: function () {
                                self.scrollIntoViewMessage(data.extra.quote.localid);
                            }
                        }
                    })
                ];
                if (data.content.length > 0) {
                    childrenText.push(
                        DOMElement.div({
                            attrs: {
                                style: {
                                    height: "10px",
                                    borderTop: "1px solid #a9a9ac"
                                }
                            }
                        }),
                        DOMElement.div({
                            children: texts
                        })
                    );
                }
                messelt = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: childrenText
                });
            }
            else {
                messelt = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: texts
                });
            }
            var emojielt = DOMElement.div({
                attrs: {
                    className: "chats-message-emoji-list-ctn",
                    style: {
                        display: (data.extra.emoji.length > 0) ? "" : "none"
                    }
                }
            });
            if (data.extra.emoji.length > 0) {
                var emojiCounterList = absol.buildDom({
                    tag: 'emojicounterlist'
                }).addTo(emojielt);
                emojielt.firstChild.counters = self.getCounters(data.extra.emoji);
                absol._('attachhook').on('attached', function () {
                    this.remove();
                    messelt.style.marginBottom = emojielt.clientHeight - 10 + "px";
                }).addTo(emojiCounterList);

            }
            messelt.appendChild(emojielt);
            res.appendChild(messelt);
            if (data.userid != systemconfig.userid) {
                res.appendChild(extra);
            }
            if (data.userid != systemconfig.userid && data.isEdit !== undefined) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-edit-message"
                        },
                        text: "create"
                    })]
                }));
            }
            if (xextra.length > 0) extra.appendChild(DOMElement.div({
                children: xextra
            }));
            break;
        case "img":
            var srcimg;
            if (data.old_cd) srcimg = window.domainImagesCD + data.localid + "_" + data.content + ".upload";
            else srcimg = window.domainFilesNew + data.localid + "_" + data.content + ".upload";
            if (data.loading !== undefined) {
                srcimg = URL.createObjectURL(data.object)
            }
            messelt = DOMElement.div({
                attrs: {
                    className: classNameImg
                },
                children: [DOMElement.img({
                    attrs: {
                        style: {
                            maxHeight: "100%",
                            maxWidth: "100%",
                            display: "block"
                        },
                        src: srcimg,
                        onclick: function (id) {
                            return function (event, me) {
                                document.body.appendChild(descViewImagePreview(self.dataImageListView, id));
                                // console.log(self.dataImageListView, id);
                            }
                        }(data.localid)
                    }
                })]
            });
            var emojielt = DOMElement.div({
                attrs: {
                    className: "chats-message-emoji-list-ctn",
                    style: {
                        display: (data.extra.emoji.length > 0) ? "" : "none"
                    }
                }
            });
            if (data.extra.emoji.length > 0) {
                var emojiCounterList = absol.buildDom({
                    tag: 'emojicounterlist'
                }).addTo(emojielt);
                emojielt.firstChild.counters = self.getCounters(data.extra.emoji);
                absol._('attachhook').on('attached', function () {
                    this.remove();
                    messelt.style.marginBottom = emojielt.clientHeight - 10 + "px";
                }).addTo(emojiCounterList);
            }
            messelt.appendChild(emojielt);
            res = DOMElement.div({
                attrs: {
                    className: "card-chatbox-message-line"
                }
            });
            var extra = DOMElement.div({
                attrs: { className: "card-chatbox-extra-ctn" }
            });
            var emoji_icon = DOMElement.div({
                attrs: {
                    className: "card-icon-emoji-message-cover"
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "mdi mdi-emoticon-happy-outline card-icon-emoji-message"
                    }
                })]
            });
            var EmojiPickerTooltip = absol.require('emojipickertooltip');
            EmojiPickerTooltip.toggleWhenClick(emoji_icon, {
                onSelect: function (icon) {
                    self.reactionMessage(data.localid, icon);
                }, orientation: 'top'
            });
            extra.appendChild(emoji_icon);
            if (data.userid == systemconfig.userid) {
                res.appendChild(extra);
            }
            var xextra = [];
            if (data.loading !== undefined) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.img({
                        attrs: {
                            className: "material-icons card-icon-loading-message",
                            src: window.domain + "./loading.gif"
                        }
                    })]
                }));
            }
            else if (data.failed !== undefined && data.failed) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-failed-message"
                        },
                        text: "error_outline"
                    })]
                }));
            }
            if (xextra.length > 0) {
                extra.appendChild(DOMElement.div({
                    children: xextra
                }));
            }
            res.appendChild(messelt);
            if (data.userid != systemconfig.userid) {
                res.appendChild(extra);
            }
            self.dataImageList.push(data);
            var uIndex = self.database.users.getByhomeid(data.userid);
            var srcImgAvatar = "", fullname = "";
            if (uIndex >= 0) {
                srcImgAvatar = self.database.users.items[uIndex].avatarSrc;
                fullname = self.database.users.items[uIndex].fullname;
            }
            self.dataImageListView.unshift({
                id: data.localid,
                avatar: srcImgAvatar,
                userName: fullname,
                src: srcimg,
                date: data.m_time,
                m_time: data.m_time,
                downloadName: data.content,
                note: ""
            });
            break;
        case "file":
            self.dataFileList.push(data);
            var suffFile = data.content.split('.').pop();
            var fileIcon;
            if (contentModule.listSuffFiles.indexOf(suffFile) >= 0) {
                fileIcon = suffFile + ".svg";
            }
            else {
                fileIcon = "default.svg";
            }
            var fileHref;
            if (data.old_cd) fileHref = window.domainFilesCD + data.localid + "_" + data.content + ".upload";
            else fileHref = window.domainFilesNew + data.localid + "_" + data.content + ".upload";
            messelt = DOMElement.div({
                attrs: {
                    className: className
                },
                children: [
                    DOMElement.a({
                        attrs: {
                            onclick: function () {
                                absol.FileSaver.saveAs(fileHref, data.content);
                            },
                            style: {
                                cursor: "pointer",
                                color: "black",
                                textDecoration: "none"
                            }
                        },
                        children: [DOMElement.table({
                            data: [[
                                DOMElement.div({
                                    attrs: {
                                        style: {
                                            height: "50px",
                                            width: "50px",
                                            textAlign: "center",
                                            verticalAlign: "middle",
                                            display: "table-cell"
                                        }
                                    },
                                    children: [DOMElement.img({
                                        attrs: {
                                            src: window.originHost + "/vivid_exticons/" + fileIcon,
                                            style: {
                                                maxHeight: "50px",
                                                maxWidth: "50px"
                                            }
                                        }
                                    })]
                                }),
                                {
                                    attrs: { style: { overflowWrap: "anywhere" } },
                                    text: data.content
                                }
                            ]]
                        })]
                    })
                ]
            });
            var emojielt = DOMElement.div({
                attrs: {
                    className: "chats-message-emoji-list-ctn",
                    style: {
                        display: (data.extra.emoji.length > 0) ? "" : "none"
                    }
                }
            });
            if (data.extra.emoji.length > 0) {
                var emojiCounterList = absol.buildDom({
                    tag: 'emojicounterlist'
                }).addTo(emojielt);
                emojielt.firstChild.counters = self.getCounters(data.extra.emoji);
                absol._('attachhook').on('attached', function () {
                    this.remove();
                    messelt.style.marginBottom = emojielt.clientHeight - 10 + "px";
                }).addTo(emojiCounterList);
            }
            messelt.appendChild(emojielt);
            res = DOMElement.div({
                attrs: {
                    className: "card-chatbox-message-line"
                }
            });
            var extra = DOMElement.div({
                attrs: { className: "card-chatbox-extra-ctn" }
            });
            if (data.userid == systemconfig.userid) {
                res.appendChild(extra);
            }
            var emoji_icon = DOMElement.div({
                attrs: {
                    className: "card-icon-emoji-message-cover"
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "mdi mdi-emoticon-happy-outline card-icon-emoji-message"
                    }
                })]
            });
            var EmojiPickerTooltip = absol.require('emojipickertooltip');
            EmojiPickerTooltip.toggleWhenClick(emoji_icon, {
                onSelect: function (icon) {
                    self.reactionMessage(data.localid, icon);
                }, orientation: 'top'
            });
            extra.appendChild(emoji_icon);
            var xextra = [];
            if (data.loading !== undefined) {
                xextra.push(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.img({
                        attrs: {
                            className: "material-icons card-icon-loading-message",
                            src: window.domain + "./loading.gif"
                        }
                    })]
                }));
            }
            else if (data.failed !== undefined && data.failed) {
                xextra.appendChild(DOMElement.div({
                    attrs: {
                        className: "card-icon-edit-message-cover"
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-failed-message"
                        },
                        text: "error_outline"
                    })]
                }));
            }
            if (xextra.length > 0) {
                extra.appendChild(DOMElement.div({
                    children: xextra
                }));
            }
            res.appendChild(messelt);
            if (data.userid != systemconfig.userid) {
                res.appendChild(extra);
            }
            break;
        case "add_member":
            var listMemberText = "";
            var userIndex;
            for (var i = 0; i < data.content.length; i++) {
                userIndex = self.database.users.getByhomeid(data.content[i]);
                if (userIndex >= 0){
                    if (i > 0) listMemberText += ", ";
                    listMemberText += self.database.users.items[userIndex].fullname;
                }
            }
            var fullname = "***";
            var uIndex = self.database.users.getByhomeid(data.userid);
            if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            res = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: contentModule.getTimeMessage(data.m_time) + ", " + fullname + " đã thêm " + listMemberText
                    }
                })]
            });
            break;
        case "create":
            var fullname = "***";
            var uIndex = self.database.users.getByhomeid(data.userid);
            if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            res = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: contentModule.getTimeMessage(data.m_time) + ", " + fullname + " đã tạo nhóm."
                    }
                })]
            });
            break;
        case "join":
            var fullname = "***";
            var uIndex = self.database.users.getByhomeid(data.userid);
            if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            res = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: contentModule.getTimeMessage(data.m_time) + ", " + fullname + " đã tham gia nhóm."
                    }
                })]
            });
            break;
        case "remove_member":
            var userIndex = self.database.users.getByhomeid(data.content);
            var fullname = "***";
            var uIndex = self.database.users.getByhomeid(data.userid);
            if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            res = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: contentModule.getTimeMessage(data.m_time) + ", " + fullname + " đã xóa " + self.database.users.items[userIndex].fullname + " khỏi cuộc trò chuyện."
                    }
                })]
            });
            break;
        case "leave_group":
            var userIndex = self.database.users.getByhomeid(data.content.leave);
            if (userIndex < 0) {
                res = DOMElement.div({});
                break;
            }
            var messText = contentModule.getTimeMessage(data.m_time) + ", " + self.database.users.items[userIndex].fullname + " đã rời khỏi cuộc trò chuyện";
            if (data.content.admin > 0) {
                userIndex = self.database.users.getByhomeid(data.content.admin);
                if (userIndex >= 0) {
                    messText += ", và " + self.database.users.items[userIndex].fullname + " đã được chọn làm trưởng nhóm."
                }
            }
            res = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: messText
                    }
                })]
            });
            break;
        default:
            res = DOMElement.div({});
            break;
    }
    if (data.content_type == "file" || data.content_type == "text" || data.content_type == "img") {
        if (data.loading === undefined && data.failed === undefined) {
            absol.$(messelt).defineEvent('contextmenu');
            messelt.on('contextmenu', function (event) {
                var selectedText = event.selectedText;
                var items = [];
                if (!self.disabled && data.content_type == "text" && data.userid == systemconfig.userid) {
                    items.push({
                        text: LanguageModule.text("txt_edit"),
                        extendClasses: "bsc-quickmenu",
                        icon: {
                            tag: "i",
                            class: "material-icons",
                            child: { text: "mode_edit" }
                        },
                        cmd: function (data, elt) {
                            return function (event, me) {
                                self.editMessage(data.localid, data.content, data.extra, elt);
                            }
                        }(data, res)
                    });
                }
                if (data.content_type == "text") {
                    items.push({
                        text: LanguageModule.text("txt_copy"),
                        extendClasses: "bsc-quickmenu",
                        icon: {
                            tag: "i",
                            class: "material-icons",
                            child: { text: "file_copy" }
                        },
                        cmd: function (data) {
                            return function (event, me) {
                                contentModule.copyToClipboard(data.content);
                            }
                        }(data)
                    });
                }
                if (!self.disabled) items.push({
                    text: LanguageModule.text("txt_quote"),
                    extendClasses: "bsc-quickmenu",
                    icon: {
                        tag: "i",
                        class: "material-icons",
                        child: { text: "reply" }
                    },
                    cmd: function (data) {
                        return function (event, me) {
                            self.quoteMessage(data);
                        }
                    }(data)
                });
                if (!self.disabled && selectedText) {
                    items.push({
                        text: LanguageModule.text("txt_quote_selection"),
                        extendClasses: "bsc-quickmenu",
                        icon: {
                            tag: "i",
                            class: "material-icons",
                            child: { text: "reply" }
                        },
                        cmd: function (data, selectedText) {
                            return function (event, me) {
                                self.quoteMessage(data, selectedText);
                            }
                        }(data, selectedText)
                    });
                }
                if (data.content_type == "img") {
                    var imgHref;
                    if (data.old_cd) imgHref = window.domainImagesCD + data.localid + "_" + data.content + ".upload";
                    else imgHref = window.domainFilesNew + data.localid + "_" + data.content + ".upload";
                    items.push({
                        text: LanguageModule.text("txt_download"),
                        extendClasses: "bsc-quickmenu",
                        icon: {
                            tag: "i",
                            class: "material-icons",
                            child: { text: "file_download" }
                        },
                        cmd: function (data) {
                            return function (event, me) {
                                absol.FileSaver.saveAs(imgHref, data.content);
                            }
                        }(data)
                    });
                }
                if (!self.disabled && data.userid == systemconfig.userid) {
                    items.push({
                        text: LanguageModule.text("txt_delete"),
                        extendClasses: "bsc-quickmenu red",
                        icon: {
                            tag: "i",
                            class: "material-icons",
                            child: { text: "delete" }
                        },
                        cmd: function (data) {
                            return function (event, me) {
                                self.deleteMessageConfirm(data.localid);
                            }
                        }(data)
                    });
                }
                event.showContextMenu({
                    items: items
                }, function (event) {
                    var cmd = event.menuItem.cmd;
                    cmd();
                });
            });
        }
    }
    return res;
};
ChatBox.prototype.editMessage = function (localid, content, extra, elt) {
    var self = this;
    if (extra && extra.quote) self.vMediaInput.quote = extra.quote;
    self.vMediaInput.text = content;
    self.vMediaInput.mode = "edit";
    self.vMediaInput.focus();
    self.localidEdit = localid;
};

ChatBox.prototype.quoteMessage = function (data, selectedText) {
    var self = this;
    var fullname = "";
    var userIndex = self.database.users.getByhomeid(data.userid);
    if (userIndex >= 0) fullname = self.database.users.items[userIndex].fullname;
    switch (data.content_type) {
        case "text":
            self.vMediaInput.quote = {
                text: (selectedText) ? selectedText : data.content,
                desc: fullname + " - " + data.m_time.toLocaleString(),
                localid: data.localid
            };
            self.vMediaInput.focus();
            break;
        case "file":
            self.vMediaInput.quote = {
                file: data.content,
                text: "[File] " + data.content,
                desc: fullname + " - " + data.m_time.toLocaleString(),
                localid: data.localid
            };
            break;
        case "img":
            var imgSrc;
            if (data.old_cd) imgSrc = window.domainImagesCD + data.localid + "_" + data.content + ".upload";
            else imgSrc = window.domainFilesNew + data.localid + "_" + data.content + ".upload";
            self.vMediaInput.quote = {
                img: imgSrc,
                text: "[IMG] " + data.content,
                desc: fullname + " - " + data.m_time.toLocaleString(),
                localid: data.localid
            };
            break;
        default:

    }
};

ChatBox.prototype.deleteMessageRedraw = function (localid) {
    var self = this;
    var elt, userid;
    for (var i = 0; i < self.listMessLocalid.length; i++) {
        if (self.listMessLocalid[i].localid == localid) {
            elt = self.listMessLocalid[i].elt;
            userid = self.listMessLocalid[i].userid;
            if (i == self.listMessLocalid.length - 1) {
                if (self.listMessLocalid.length > 1){
                    self.lastUserid = self.listMessLocalid[self.listMessLocalid.length - 2].userid;
                    self.lastMessTime = self.listMessLocalid[self.listMessLocalid.length - 2].m_time;
                }
                else {
                    self.lastUserid = 0;
                    self.lastMessTime = new Date(0);
                }
            }
            self.listMessLocalid.splice(i, 1);
        }
    }
    if (elt !== undefined) {
        if (userid != systemconfig.userid) {
            if (elt.parentNode.childNodes.length == 2) {
                elt.parentNode.parentNode.parentNode.remove();
                return;
            }
        }
        else {
            if (elt.parentNode.childNodes.length == 2) {
                elt.parentNode.remove();
                return;
            }
        }
        elt.remove();
    }
};

ChatBox.prototype.deleteMessage = function (localid) {
    var self = this;
    self.deleteMessageFunc(localid).then(function (values){
        for (var i = self.content.length - 1; i >= 0 ; i--){
            if (self.content[i].localid == localid) {
                self.content.splice(i, 1);
                break;
            }
        }
        self.deleteMessageRedraw(localid);
        self.vMediaInput.mode = "new";
        self.vMediaInput.focus();
    });
};

ChatBox.prototype.deleteMessageConfirm = function (localid) {
    var self = this;
    if (self.isNotiCenter){
        hr.overviewWidget.showModal({
            title: LanguageModule.text("war_title_detele_message"),
            content: LanguageModule.text("war_txt_detele_message"),
            buttons: [
                {
                    text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                        modal.remove();
                        self.deleteMessage(localid);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"), onclick: function (event, modal, caller) {
                        modal.remove();
                    }
                }
            ]
        });
    }
    else {
        ModalElement.question({
            title: LanguageModule.text("war_title_detele_message"),
            message: LanguageModule.text("war_txt_detele_message"),
            onclick: function (sel) {
                if (sel == 0) {
                    self.deleteMessage(localid);
                }
            }
        });
    }
};

ChatBox.prototype.updateMessage = function (content) {
    var self = this;
    var messEltCmd;
    for (var i = self.listMessLocalid.length - 1; i >= 0; i--) {
        if (self.listMessLocalid[i].localid == content.localid) {
            messEltCmd = absol.$('.card-icon-loading-message', self.listMessLocalid[i].elt).parentNode;
            DOMElement.removeAllChildren(messEltCmd);
            if (content.failed) {
                messEltCmd.appendChild(DOMElement.i({
                    attrs: {
                        className: "material-icons card-icon-failed-message"
                    },
                    text: "error_outline"
                }));
            }
            else {
                absol.$(self.listMessLocalid[i].elt.childNodes[1]).defineEvent('contextmenu');
                self.listMessLocalid[i].elt.childNodes[1].on('contextmenu', function (event) {
                    var selectedText = event.selectedText;
                    var items = [];
                    if (!self.disabled && content.content_type == "text" && content.userid == systemconfig.userid) {
                        items.push({
                            text: LanguageModule.text("txt_edit"),
                            extendClasses: "bsc-quickmenu",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "mode_edit" }
                            },
                            cmd: function (content, elt) {
                                return function (event, me) {
                                    self.editMessage(content.localid, content.content, content.extra, elt);
                                }
                            }(content, self.listMessLocalid[i].elt)
                        });
                    }
                    if (content.content_type == "text") {
                        items.push({
                            text: LanguageModule.text("txt_copy"),
                            extendClasses: "bsc-quickmenu",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "file_copy" }
                            },
                            cmd: function (content) {
                                return function (event, me) {
                                    contentModule.copyToClipboard(content.content);
                                }
                            }(content)
                        });
                    }
                    if (!self.disabled){
                        items.push({
                            text: LanguageModule.text("txt_quote"),
                            extendClasses: "bsc-quickmenu",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "reply" }
                            },
                            cmd: function (content) {
                                return function (event, me) {
                                    self.quoteMessage(content);
                                }
                            }(content)
                        });
                    }
                    if (!self.disabled && selectedText) {
                        items.push({
                            text: LanguageModule.text("txt_quote_selection"),
                            extendClasses: "bsc-quickmenu",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "reply" }
                            },
                            cmd: function (content, selectedText) {
                                return function (event, me) {
                                    self.quoteMessage(content, selectedText);
                                }
                            }(content, selectedText)
                        });
                    }
                    if (content.content_type == "img") {
                        var imgHref;
                        if (content.old_cd) imgHref = window.domainImagesCD + content.localid + "_" + content.content + ".upload";
                        else imgHref = window.domainFilesNew + content.localid + "_" + content.content + ".upload";
                        items.push({
                            text: LanguageModule.text("txt_download"),
                            extendClasses: "bsc-quickmenu",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "file_download" }
                            },
                            cmd: function (content) {
                                return function (event, me) {
                                    absol.FileSaver.saveAs(imgHref, content.content);
                                }
                            }(content)
                        });
                    }
                    if (!self.disabled && content.userid == systemconfig.userid) {
                        items.push({
                            text: LanguageModule.text("txt_delete"),
                            extendClasses: "bsc-quickmenu red",
                            icon: {
                                tag: "i",
                                class: "material-icons",
                                child: { text: "delete" }
                            },
                            cmd: function (content) {
                                return function (event, me) {
                                    self.deleteMessageConfirm(content.localid);
                                }
                            }(content)
                        });
                    }
                    event.showContextMenu({
                        items: items
                    }, function (event) {
                        var cmd = event.menuItem.cmd;
                        cmd();
                    });
                });
                if (content.content_type == "img") {
                    if (content.old_cd) self.listMessLocalid[i].elt.childNodes[1].firstChild.src = window.domainImagesCD + content.localid + "_" + content.content + ".upload";
                    else self.listMessLocalid[i].elt.childNodes[1].firstChild.src = window.domainFilesNew + content.localid + "_" + content.content + ".upload";
                }
            }
            break;
        }
    }
};

ChatBox.prototype.sendAddMessage = function (text, files, images, tagList){
    var self = this;
    self.seenMessage();
    switch (self.vMediaInput.mode){
        case "new":
            var quote = self.vMediaInput.quote;
            var messList = [];
            for (var i = 0; i < files.length; i++) {
                messList.push({
                    content_type: "file",
                    content: files[i].name,
                    m_time: new Date(),
                    userid: systemconfig.userid,
                    loading: true
                });
            }
            for (var i = 0; i < images.length; i++) {
                messList.push({
                    content_type: "img",
                    content: images[i].name,
                    m_time: new Date(),
                    userid: systemconfig.userid,
                    object: images[i],
                    loading: true
                });
            }
            if (quote || text != "") {
                var messText = {
                    content_type: "text",
                    content: text,
                    m_time: new Date(),
                    userid: systemconfig.userid,
                    loading: true
                };
                if (quote) {
                    messText.extra = {
                        quote: quote
                    };
                }
                messList.push(messText);
            }
            var listIdLocal = [], localid;
            for (var i = 0; i < messList.length; i++) {
                localid = (new Date()).getTime() + i;
                listIdLocal.push(localid);
                messList[i].localid = localid;
                self.addMessage(messList[i]);
                self.vMessContainer.scrollTop = self.vMessContainer.scrollHeight;
            }
            setTimeout(function () {
                self.vMessContainer.scrollTop = self.vMessContainer.scrollHeight;
                self.vMediaInput.focus();
            }, 1000);
            self.sendFunc(text, files, images, quote, listIdLocal, tagList).then(function (values) {
                self.content = self.content.concat(values);
                for (var i = 0; i < values.length; i++) {
                    self.updateMessage(values[i]);
                }
                self.mess_seen_id = values[values.length - 1].localid;
            });
            break;
        case "edit":
            var quote = self.vMediaInput.quote;
            self.editMessageFunc(self.localidEdit, text, quote).then(function (values) {
                for (var i = 0; i < self.content.length; i++) {
                    if (self.content[i].localid == self.localidEdit) {
                        self.content[i].content = text;
                        break;
                    }
                }
                self.editMessageRedraw(self.localidEdit, text, quote, values.failed);
                self.vMediaInput.mode = "new";
                self.vMediaInput.focus();
            });
            break;
        default:

    }
};

ChatBox.prototype.scrollIntoViewMessage = function (localid) {
    var self = this;
    var elt;
    for (var i = 0; i < self.listMessLocalid.length; i++) {
        if (self.listMessLocalid[i].localid == localid) {
            elt = self.listMessLocalid[i].elt;
            break;
        }
    }
    if (elt) {
        elt.scrollIntoView();
        var messelt = absol.$("div", elt, function (e) {
            return e.classList.contains("card-chatbox-message-me") || e.classList.contains("card-chatbox-message-other")
                || e.classList.contains("card-chatbox-message-other-img") || e.classList.contains("card-chatbox-message-me-img");
        });
        if (!messelt) return;
        messelt.classList.add("card-anim-scale");
        setTimeout(function () {
            messelt.classList.remove("card-anim-scale");
        }, 1000);
    }
};

ChatBox.prototype.editMessageRedraw = function (localid, text, quote, failed) {
    var self = this;
    var elt, type, extra, m_time, userid
    for (var i = self.listMessLocalid.length - 1; i >= 0; i--) {
        if (self.listMessLocalid[i].localid == localid) {
            elt = self.listMessLocalid[i].elt;
            type = self.listMessLocalid[i].type;
            extra = self.listMessLocalid[i].extra;
            m_time = self.listMessLocalid[i].m_time;
            userid = self.listMessLocalid[i].userid;
            break;
        }
    }
    if (!extra) extra = {};
    extra.quote = quote;
    DOMElement.removeAllChildren(elt);
    elt.appendChild(self.createMessage({
        content_type: "text",
        localid: localid,
        content: text,
        isEdit: true,
        failed: failed,
        extra: extra,
        m_time: m_time,
        userid: userid
    }));
};

ChatBox.prototype.seenMessage = function () {
    var self = this;
    self.new_mess_in_chat_icon.style.display = "none";
    if (this.listMessLocalid.length == 0) return;
    if (this.mess_seen_id == this.listMessLocalid[0].localid) return;
    if (self.content.length == 0) return;
    self.seenFunc(self.content[self.content.length - 1].localid).then(function (values) {
        self.mess_seen_id = self.content[self.content.length - 1].localid;
    });
};

ChatBox.prototype.updateContentSize = function () {
    if (this.vMessContainer.clientHeight <= this.vMessContainer.scrollHeight){
        this.isLast = true;
        this.toggleLastMessage();
    }
};

ChatBox.prototype.addMessage = function (content) {
    var self = this;
    if (this.lastMessTime != 0) {
        var oldTime, oldMonth, oldDate, oldYear;
        oldTime = this.lastMessTime.getTime() / 86400000;
        oldDate = this.lastMessTime.getDate();
        oldMonth = this.lastMessTime.getMonth() + 1;
        oldYear = this.lastMessTime.getFullYear();
        var newTime = content.m_time.getTime() / 86400000;
        var newDate = content.m_time.getDate()
        var newMonth = content.m_time.getMonth() + 1;
        var newYear = content.m_time.getFullYear();
        if (oldYear != newYear || oldMonth != newMonth || oldDate != newDate) {
            var now = new Date();
            var nowTime = now.getTime() / 86400000;
            var nowDate = now.getDate()
            var nowMonth = now.getMonth() + 1;
            var nowYear = now.getFullYear();
            var res;
            if (nowYear == newYear) {
                if (nowMonth == newMonth && nowDate == newDate) {
                    res = "Today";
                }
                else if (nowTime - newTime < 7) {
                    var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
                    res = weekday[content.m_time.getDay()];
                }
                else {
                    res = contentModule.getDateView(content.m_time);
                }
            }
            else {
                res = contentModule.getDateView(content.m_time);
            }
            var singleMessage = absol.buildDom({
                class: "card-chatbox-line-seen",
                child: [absol.buildDom({
                    tag: "unreadmessageline",
                    props: {
                        text: res
                    }
                })]
            });
            this.vBoxMessage.appendChild(singleMessage);
        }
    }
    var singleMessage;
    if (content.content_type != "file" && content.content_type != "img" && content.content_type != "text") {
        singleMessage = this.createMessage(content);
        self.listMessLocalid.push({
            localid: content.localid,
            userid: content.userid,
            m_time: content.m_time,
            elt: singleMessage,
            extra: content.extra
        });
        this.vBoxMessage.appendChild(singleMessage);
        this.lastUserid = 0;
    }
    else {
        if (this.lastUserid !== content.userid || this.lastMessTime.getTime() + 60000 < content.m_time.getTime()) {
            var className;
            if (content.userid == systemconfig.userid) {
                className = "card-chatbox-groupmess-me";
                this._lastVMessageGroup = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                className: "card-chatbox-groupmess-me-note"
                            },
                            text: contentModule.getTimeMessage(content.m_time)
                        })
                    ]
                });
                this.vBoxMessage.appendChild(this._lastVMessageGroup);
            }
            else {
                className = "card-chatbox-groupmess-other";
                var uIndex = self.database.users.getByhomeid(content.userid);
                var srcImgAvatar = "", fullname = "";
                if (uIndex >= 0) {
                    srcImgAvatar = self.database.users.items[uIndex].avatarSrc;
                    fullname = self.database.users.items[uIndex].fullname;
                }
                this._lastVMessageGroup = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                className: "card-chatbox-groupmess-other-note"
                            },
                            text: fullname + ", " + contentModule.getTimeMessage(content.m_time)
                        })
                    ]
                });
                this.vBoxMessage.appendChild(DOMElement.div({
                    attrs: {
                        className: "card-chatbox-message-cover"
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                style: {
                                    marginLeft: "10px",
                                    display: "inline-block",
                                    verticalAlign: "top"
                                }
                            },
                            children: [
                                DOMElement.div({
                                    attrs: {
                                        className: "message-avatar-user",
                                        style: {
                                            backgroundImage: "url(" + srcImgAvatar + ")"
                                        }
                                    }
                                })
                            ]
                        }),
                        DOMElement.div({
                            attrs: {
                                style: {
                                    display: "inline-block"
                                }
                            },
                            children: [this._lastVMessageGroup]
                        })
                    ]
                }));
            }
        }
        this.lastUserid = content.userid;
        singleMessage = this.createMessage(content);
        self.listMessLocalid.push({
            localid: content.localid,
            userid: content.userid,
            m_time: content.m_time,
            elt: singleMessage,
            extra: content.extra
        });
        this._lastVMessageGroup.appendChild(singleMessage);
    }
    this.lastMessTime = content.m_time;
    var self = this;
    if (this.reload === undefined) {
        if (content.localid <= this.mess_seen_id) {
            setTimeout(function () {
                absol.require('bscroller').prototype.scrollInto.call(self.vMessContainer, singleMessage);
            }, 500);
        }
    }
};

ChatBox.prototype.addOldMessage = function (content) {
    var self = this;
    var oldTime, oldMonth, oldDate, oldYear;
    if (this.firstMessTime.getTime() != 0) {
        oldTime = this.firstMessTime.getTime() / 86400000;
        oldDate = this.firstMessTime.getDate();
        oldMonth = this.firstMessTime.getMonth() + 1;
        oldYear = this.firstMessTime.getFullYear();
    }
    var newTime = content.m_time.getTime() / 86400000;
    var newDate = content.m_time.getDate()
    var newMonth = content.m_time.getMonth() + 1;
    var newYear = content.m_time.getFullYear();
    if (oldYear != newYear || oldMonth != newMonth || oldDate != newDate) {
        var now = new Date();
        var nowTime = now.getTime() / 86400000;
        var nowDate = now.getDate()
        var nowMonth = now.getMonth() + 1;
        var nowYear = now.getFullYear();
        var res;
        if (nowYear == newYear) {
            if (nowMonth == newMonth && nowDate == newDate) {
                res = "Today";
            }
            else if (nowTime - oldTime < 7) {
                var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
                res = weekday[this.firstMessTime.getDay()];
            }
            else {
                res = contentModule.getDateView(this.firstMessTime);
            }
        }
        else {
            res = contentModule.getDateView(this.firstMessTime);
        }
        var singleMessage = absol.buildDom({
            class: "card-chatbox-line-seen",
            child: [absol.buildDom({
                tag: "unreadmessageline",
                props: {
                    text: res
                }
            })]
        });
        this.vBoxMessage.insertBefore(singleMessage, this.vBoxMessage.firstChild);
        this.firstUserid = 0;
        this.firstMessTime = new Date(0);
    }
    if (content.content_type == "file" || content.content_type == "img" || content.content_type == "text") {
        if (this.firstUserid !== content.userid || this.firstMessTime.getTime() + 60000 < content.m_time.getTime()) {
            var className;
            if (content.userid == systemconfig.userid) {
                className = "card-chatbox-groupmess-me";
                this._firstVMessageGroup = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                className: "card-chatbox-groupmess-me-note"
                            },
                            text: contentModule.getTimeMessage(content.m_time)
                        })
                    ]
                });
                this.vBoxMessage.insertBefore(this._firstVMessageGroup, this.vBoxMessage.firstChild);
            }
            else {
                className = "card-chatbox-groupmess-other";
                var srcImgAvatar = "", fullname = "";
                var uIndex = self.database.users.getByhomeid(content.userid);
                if (uIndex >= 0) {
                    srcImgAvatar = self.database.users.items[uIndex].avatarSrc;
                    fullname = self.database.users.items[uIndex].fullname;
                }
                this._firstVMessageGroup = DOMElement.div({
                    attrs: {
                        className: className
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                className: "card-chatbox-groupmess-other-note"
                            },
                            text: fullname + ", " + contentModule.getTimeMessage(content.m_time)
                        })
                    ]
                });
                var groupCoverElt = DOMElement.div({
                    attrs: {
                        className: "card-chatbox-message-cover"
                    },
                    children: [
                        DOMElement.div({
                            attrs: {
                                style: {
                                    marginLeft: "10px",
                                    display: "inline-block",
                                    verticalAlign: "top"
                                }
                            },
                            children: [
                                DOMElement.div({
                                    attrs: {
                                        className: "message-avatar-user",
                                        style: {
                                            backgroundImage: "url(" + srcImgAvatar + ")"
                                        }
                                    }
                                })
                            ]
                        }),
                        DOMElement.div({
                            attrs: {
                                style: {
                                    display: "inline-block"
                                }
                            },
                            children: [this._firstVMessageGroup]
                        })
                    ]
                });
                this.vBoxMessage.insertBefore(groupCoverElt, this.vBoxMessage.firstChild);
            }
            this.firstUserid = content.userid;
            this.firstMessTime = content.m_time;
        }
    }
    else {
        this._firstVMessageGroup = DOMElement.div({});
        this.vBoxMessage.insertBefore(this._firstVMessageGroup, this.vBoxMessage.firstChild);
        this.firstUserid = 0;
    }
    var singleMessage = this.createMessage(content);
    self.listMessLocalid.push({
        localid: content.localid,
        userid: content.userid,
        m_time: content.m_time,
        elt: singleMessage,
        extra: content.extra
    });
    this._firstVMessageGroup.insertBefore(singleMessage, this._firstVMessageGroup.childNodes[1]);
};

ChatBox.prototype.toggleLastMessage = function () {
    if (this.isLast) {
        this.seenMessage();
        this.scroll_last_ctn.style.visibility = "hidden";
    }
    else {
        this.scroll_last_ctn.style.visibility = "visible";
    }
};

ChatBox.prototype.loadOldMess = function(){
    var self = this;
    self.vMessContainer.addEventListener("scroll", function(){
        if (self.vMessContainer.scrollTop == 0){
            var x = self.vBoxMessage.firstChild;
            if (self.content.length > 0){
                self.firstUserid = 0;
                self.firstMessTime = self.content[0].m_time;
            }
            else {
                self.firstUserid = 0;
                self.firstMessTime = new Date(0);
            }
            if (self.loadOldMessFunc){
                self.loadOldMessFunc().then(function(values){
                    // console.log(values);
                    for (var i = values.length -1; i >= 0; i--){
                        self.addOldMessage(values[i]);
                    }
                    if (values.length > 0) x.scrollIntoView();
                });
            }
        }
    });
};

ChatBox.prototype.nameChat = function(){
    var self = this;
    this.icon_gallery = DOMElement.i({
        attrs: {
            className: "material-icons bsc-icon-hover-blue",
            style: {
                verticalAlign: "middle"
            },
            onclick: function(){
                this.toggleGallery();
            }.bind(this)
        },
        text: "burst_mode"
    });
    this.titleChat = DOMElement.div({
        attrs: {
            className: "chats-theme-desktop-title"
        },
        text: this.name
    });
    this.nameChat = DOMElement.div({
        attrs: {
            className: "chats-theme-desktop-name-chat-container"
        },
        children: [
            this.titleChat,
            DOMElement.div({
                attrs: {
                    className: "chats-theme-desktop-content-icon"
                },
                children: [
                    DOMElement.table({
                        data: [[
                            DOMElement.i({
                                attrs: {
                                    className:"material-icons bsc-icon-hover-black",
                                    style: {
                                        marginRight: "5px",
                                        verticalAlign: "middle"
                                    }
                                },
                                text: "search"
                            }),
                            this.icon_gallery
                        ]]
                    })
                ]
            })
        ]
    });
    return this.nameChat;
};

ChatBox.prototype.getView = function () {
    var self = this;
    this.information_content = DOMElement.div({
        attrs: {className: "chats-theme-desktop-information-body-container"}
    });
    this.chats_gallery = DOMElement.div({
        attrs: {
            className: "chats-theme-desktop-information-content"
        },
        children: [
            this.galleryHeader(),
            this.information_content
        ]
    });
    this.vBoxMessage = absol.buildDom({
        class: "card-chat-box-messages"
    });
    var xdisplay = "none", xnew_no_seen = "";
    this.new_mess_in_chat_icon = DOMElement.div({
        attrs: {
            className: "chat-button-number-in-chatbox",
            style: {
                display: xdisplay
            }
        },
        text: xnew_no_seen
    });
    this.scroll_last_ctn = DOMElement.button({
        attrs: {
            className: "card-chat-box-scroll-last-ctn"
        },
        children: [
            DOMElement.i({
                attrs: {
                    className: "material-icons card-chat-box-scroll-last-icon",
                    onclick: function () {
                        self.vMessContainer.scrollTop = self.vMessContainer.scrollHeight - self.vMessContainer.clientHeight;
                    }
                },
                text: "keyboard_arrow_down"
            }),
            this.new_mess_in_chat_icon
        ]
    });
    this.vMessContainer = DOMElement.div({
        attrs: {
            className: "card-chat-box-messages-container"
        },
        children: [
            this.vBoxMessage
        ]
    });
    this.vMessContainer.addEventListener("scroll", function () {
        var isLast = absol.$.isScrolledToBottom(this);
        if (isLast == self.isLast) return;
        self.isLast = isLast;
        self.toggleLastMessage();
    });
    this.vInputContainer = DOMElement.div({
        attrs: {
            className: "card-chat-box-text-input-container"
        }
    });
    var self = this;
    var text = "", files = [], images = [], mode = "new";
    this.vMediaInput = absol.buildDom({
        tag: 'messageinput',
        data: {
            v2: true
        },
        props: {
            mode: mode,
            text: text,
            images: images,
            files: files
        },
        on: {
            sizechange: function (event) {
                this.updateContentSize();
            }.bind(this),
            send: function () {
                if (this.text !== "" || this.files.length > 0 || this.images.length > 0 || this.quote) {
                    self.sendAddMessage(this.text, this.files, this.images, this.tagList);
                    this.clearAllContent();
                }
            },
            cancel: function () {
                this.mode = "new";
                this.clearAllContent();
                self.localidEdit = 0;
            },
            useraddfile: function (event) {
                var files = event.files;
                var bigFiles = files.filter(function (file) {
                    return file.size > hr.fileLimit * 1024 * 1000;
                });
                var smallFiles = files.filter(function (file) {
                    return file.size <= hr.fileLimit * 1024 * 1000;
                });
                if (bigFiles.length > 0) {
                    event.resolve(new Promise(function (resolve) {
                        if (self.isNotiCenter){
                            hr.overviewWidget.showModal({
                                title: LanguageModule.text("txt_warning"),
                                content: DOMElement.div({
                                    children: [
                                        DOMElement.div({
                                            text: LanguageModule.text2("war_txt_file_over_size", ["", hr.fileLimit])
                                        }),
                                        absol.buildDom({
                                            child: bigFiles.map(function (file) {
                                                return {
                                                    child: [
                                                        { tag: 'span', child: { text: file.name + ": " } },
                                                        { tag: 'span', text: file.size + 'B' },
                                                    ]
                                                };
                                            })
                                        })
                                    ]
                                }),
                                buttons: [
                                    {
                                        text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                                            modal.remove();
                                            resolve(smallFiles);
                                        }
                                    }
                                ]
                            });
                        }
                        else {
                            ModalElement.showWindow({
                                title: LanguageModule.text("txt_warning"),
                                bodycontent: DOMElement.div({
                                    children: [
                                        DOMElement.div({
                                            text: LanguageModule.text2("war_txt_file_over_size", ["", hr.fileLimit])
                                        }),
                                        absol.buildDom({
                                            child: bigFiles.map(function (file) {
                                                return {
                                                    child: [
                                                        { tag: 'span', child: { text: file.name + ": " } },
                                                        { tag: 'span', text: file.size + 'B' },
                                                    ]
                                                };
                                            })
                                        })
                                    ]
                                }),
                                buttonlist: [
                                    {
                                        text: LanguageModule.text("txt_ok"),
                                        onclick: function(){
                                            ModalElement.close();
                                            resolve(smallFiles);
                                        }
                                    }
                                ]
                            });
                        }
                    }));
                }
            }
        }
    });
    self.tagMap = {};
    for (var i = 0; i < self.database.users.items.length; i++){
        self.tagMap[self.database.users.items[i].homeid] = self.database.users.items[i].fullname;
    }
    if (self.isComment){
        var employeesUserDic = {};
        for (var i = 0; i < self.database.employees.items.length; i++){
            employeesUserDic[self.database.employees.items[i].userid] = self.database.employees.items[i];
        }
        this.vMediaInput.tagMap = self.tagMap;
        var employeesDic = contentModule.makeDictionaryIndex(self.database.employees.items);
        this.vMediaInput.addPlugin({
            icon: '<span>@</span>',
            id: 'tag_employee',
            autoClose: false,
            order: 0,
            onOpen: function(){
                var contentElt = this.contentElt;
                contentElt.clearChild();
                var drawLogs = function(){
                    var oIndex, uIndex;
                    var k;
                    for (var i = 0; i < self.database.user_tag_employee_logs.items.length; i++){
                        k = employeesUserDic[self.database.user_tag_employee_logs.items[i].user_tagid];
                        uIndex = self.database.users.getByhomeid(self.database.user_tag_employee_logs.items[i].user_tagid);
                        if (k && uIndex >= 0){
                            oIndex = self.database.orgs.getIndex(k.orgid);
                            logs_elt.appendChild(DOMElement.div({
                                attrs: {
                                    className: "hr-employee-tag-logs-ctn",
                                    onclick: function(k){
                                        return function(){
                                            var values = employee_select.values;
                                            values = values.slice();
                                            if (values.indexOf(k.id) < 0){
                                                values.push(k.id);
                                            }
                                            employee_select.values = values;
                                        }
                                    }(k)
                                },
                                children: [
                                    DOMElement.div({
                                        attrs: {
                                            className: "hr-employee-tag-logs-avatar",
                                            style: {
                                                backgroundImage: "url(" + self.database.users.items[uIndex].avatarSrc + ")"
                                            }
                                        }
                                    }),
                                    DOMElement.div({
                                        attrs: {
                                            className: "hr-employee-tag-logs-text"
                                        },
                                        text: k.fullname + " (" + self.database.orgs.items[oIndex].name +")"
                                    })
                                ]
                            }));
                        }
                    }
                };
                var thisPlugin = this;
                var userNone = {};
                userNone[systemconfig.userid] = true;
                var employee_select = absol.buildDom({
                    tag: "multichecktreeleafmenu",
                    style: {
                        display: "block",
                        width: "100%"
                    },
                    props: {
                        items: contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(self, userNone),
                        enableSearch: true
                    }
                });
                var logs_elt = DOMElement.div({
                    attrs: {
                        style: {
                            maxHeight: "400px",
                            overflow: "auto"
                        }
                    }
                });
                drawLogs();
                contentElt.appendChild(DOMElement.div({
                    attrs: {
                        style: {
                            border: "var(--control-border)",
                            borderRadius: "5px",
                            padding: "var(--control-verticle-distance-2)"
                        }
                    },
                    children: [DOMElement.table({
                        data: [
                            [employee_select],
                            [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
                            [logs_elt],
                            [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
                            [{
                                attrs: {align: "right"},
                                children: [
                                    DOMElement.span({
                                        attrs: {
                                            style: {lineHeight: "30px", height: "30px", color: "var(--a-color)", cursor: "pointer"},
                                            onclick: function(){
                                                var values = employee_select.values;
                                                var k;
                                                for (var i = 0; i < values.length; i++){
                                                    k = employeesDic[values[i]];
                                                    if (k >= 0){
                                                        if (self.vMediaInput.text.length > 0) thisPlugin.appendText(" ");
                                                        thisPlugin.appendText('@[id:' + self.database.employees.items[k].userid + ']');
                                                    }
                                                }
                                                thisPlugin.closePopup();
                                            }
                                        },
                                        text: LanguageModule.text("txt_ok")
                                    }),
                                    DOMElement.span({
                                        attrs: {
                                            style: {lineHeight: "30px", height: "30px", cursor: "pointer", marginLeft: "var(--control-verticle-distance-2)"},
                                            onclick: function(){
                                                thisPlugin.closePopup();
                                            }
                                        },
                                        text: LanguageModule.text("txt_cancel")
                                    })
                                ]
                            }]
                        ]
                    })]
                }));
            }
        });
    }
    this.vMediaInput.$preInput.on('focus', function () {
        self.seenMessage();
    });
    this.vInputContainer.appendChild(this.vMediaInput);
    this.vInputContainer.appendChild(this.scroll_last_ctn);
    this.vMessCtn = DOMElement.div({
        attrs: {
            className: "card-chat-box-messages-ctn"
        },
        children: [this.vMessContainer]
    });
    this.chatBodyContent = DOMElement.div({
        attrs: {
            className: "card-chat-box-content"
        }
    });
    if (this.viewNameChat){
        this.chatBodyContent.appendChild(this.nameChat());
    }
    this.chatBodyContent.appendChild(this.vMessCtn);
    if (!this.disabled) this.chatBodyContent.appendChild(this.vInputContainer);

    this.view = DOMElement.div({
        attrs: {
            className: "card-chat-box",
            onclick: function (event) {
                var targetClassList = event.target.classList;
                if (targetClassList.contains('card-chatbox-message-cover')
                    || targetClassList.contains('card-chatbox-message-line')
                    || targetClassList.contains('card-chat-box-messages-container')
                ) {
                    this.vMediaInput.focus();
                }
            }.bind(this)
        },
        children: [
            DOMElement.div({
                attrs: {
                    className: "card-chat-box-body"
                },
                children: [
                    this.chatBodyContent,
                    this.chats_gallery
                ]
            })
        ]
    });
    this.listMessLocalid = [];
    this.lastUserid = 0;
    this.lastMessTime = new Date(0);
    this.dataImageList = [];
    this.dataImageListView = [];
    this.dataFileList = [];
    this.dataLinkList = [];
    for (var i = 0; i < this.content.length; i++) {
        this.addMessage(this.content[i]);
    }
    this.$attachhook = absol._('attachhook').addTo(this.view);
    this.$attachhook.requestUpdateSize = this.updateContentSize.bind(this);
    this.$attachhook.on('attached', function(){
        absol.ResizeSystem.add(this);
        this.requestUpdateSize();
    });
    this.loadOldMess();
    return this.view;
};

contentModule.makeChat_session_membersIndex = function(host){
    for (var i = 0; i < host.database.chat_sessions.items.length; i++){
        host.database.chat_sessions.items[i].chat_session_membersIndexList = [];
        host.database.chat_sessions.items[i].membersIdList = [];
        host.database.chat_sessions.items[i].mess_seen_id = 0;
        host.database.chat_sessions.items[i].start_mess_id = 0;
    }
    var k;
    var chat_sessionsDic = contentModule.makeDictionaryIndex(host.database.chat_sessions.items);
    for (var i = 0; i < host.database.chat_session_members.items.length; i++){
        host.database.chat_session_members.items[i].chatIndex = k = chat_sessionsDic[host.database.chat_session_members.items[i].chatid];
        if (k !== undefined){
            if (host.database.chat_session_members.items[i].userid == systemconfig.userid){
                if (host.database.chat_session_members.items[i].mess_seen_id != "") host.database.chat_sessions.items[k].mess_seen_id = parseInt(host.database.chat_session_members.items[i].mess_seen_id, 10);
                if (host.database.chat_session_members.items[i].start_mess_id != "") host.database.chat_sessions.items[k].start_mess_id = parseInt(host.database.chat_session_members.items[i].start_mess_id, 10);
                host.database.chat_sessions.items[k].privilege = host.database.chat_session_members.items[i].privilege;
            }
            host.database.chat_sessions.items[k].chat_session_membersIndexList.push(i);
            host.database.chat_sessions.items[k].membersIdList.push({
                userid: host.database.chat_session_members.items[i].userid,
                privilege: host.database.chat_session_members.items[i].privilege
            });
        }
    }
};

var ChatBar = function(params){
    this.database = params.database;
    this.orgViewDic = params.orgViewDic;
    this.orgEditDic = params.orgEditDic;
    this.employeeEditDic = params.employeeEditDic;
    this.data = params.data;
    this.func = params.func;
    this.isNotiCenter = params.isNotiCenter;
    this.frameView = params.frameView;
};

ChatBar.prototype.getMessageText = function(data){
    var self = this;
    switch (data.content_type) {
        case "file":
        case "text":
            return data.content;
        case "img":
            return "[photo]";
        case "join":
            var fullname = "***", uIndex;
            if (data.userid == systemconfig.userid){
                fullname = LanguageModule.text("txt_you");
            }
            else {
                uIndex = self.database.users.getByhomeid(data.userid);
                if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            }
            return fullname + " đã tham gia nhóm."
        case "create":
            var fullname = "***", uIndex;
            if (data.userid == systemconfig.userid){
                fullname = LanguageModule.text("txt_you");
            }
            else {
                uIndex = self.database.users.getByhomeid(data.userid);
                if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            }
            return fullname + " đã tạo nhóm."
        case "add_member":
            var fullname = "***", uIndex;
            if (data.userid == systemconfig.userid){
                fullname = LanguageModule.text("txt_you");
            }
            else {
                uIndex = self.database.users.getByhomeid(data.userid);
                if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            }
            var listMemberName = "";
            for (var i = 0; i < data.content.length; i++){
                if (listMemberName.length > 0) listMemberName += ", ";
                uIndex = self.database.users.getByhomeid(data.content[i]);
                if (uIndex >= 0) listMemberName += self.database.users.items[uIndex].fullname;
            }
            return fullname + " đã thêm " + listMemberName;
        case "remove_member":
            var fullname = "***", uIndex;
            if (data.userid == systemconfig.userid){
                fullname = LanguageModule.text("txt_you");
            }
            else {
                uIndex = self.database.users.getByhomeid(data.userid);
                if (uIndex >= 0) fullname = self.database.users.items[uIndex].fullname;
            }
            var member = "***";
            uIndex = self.database.users.getByhomeid(data.content);
            if (uIndex >= 0) member = self.database.users.items[uIndex].fullname;
            return fullname + " đã xóa " + member + " khỏi cuộc trò chuyện."
        case "leave_group":
            var messText = "";
            var uIndex = self.database.users.getByhomeid(data.content.leave);
            if (uIndex >= 0) messText += self.database.users.items[uIndex].fullname + " đã rời khỏi cuộc trò chuyện, và ";
            else messText = "...";
            return messText;

    }
    return "";
};

ChatBar.prototype.dissolveGroup = function(item){
    var self = this;
    item.dissolveFunc(item.id).then(function(value){
        if (self.manageModal !== undefined) self.manageModal.selfRemove();
        else if (self.frameView && self.frameView.length > 1) self.frameView.removeLast();
        self.dropGroup(item.id);
    });
};

ChatBar.prototype.dissolveGroupConfirm = function(item){
    var self = this;
    if (self.isNotiCenter){
        hr.overviewWidget.showModal({
            title: LanguageModule.text("txt_dissolve_group"),
            content: LanguageModule.text2("war_txt_dissolve_group", item.name),
            buttons: [
                {
                    text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                        modal.remove();
                        self.dissolveGroup(item);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"), onclick: function (event, modal, caller) {
                        modal.remove();
                    }
                }
            ]
        });
    }
    else {
        ModalElement.question2({
            title: LanguageModule.text("txt_dissolve_group"),
            message: LanguageModule.text2("war_txt_dissolve_group", item.name),
            onclick: function(sel){
                if (sel == 0){
                    self.dissolveGroup(item);
                }
            }
        });
    }
};

ChatBar.prototype.deleteGroup = function(item){
    var self = this;
    item.deleteFunc(item.id).then(function(value){
        if (self.manageModal !== undefined) self.manageModal.selfRemove();
        else if (self.frameView && self.frameView.length > 1) self.frameView.removeLast();
        self.dropGroup(item.id);
    });
};

ChatBar.prototype.deleteGroupConfirm = function(item){
    var self = this;
    if (self.isNotiCenter){
        hr.overviewWidget.showModal({
            title: LanguageModule.text("txt_delete_conversation"),
            content: LanguageModule.text("war_txt_delete_conversation"),
            buttons: [
                {
                    text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                        modal.remove();
                        self.deleteGroup(item);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"), onclick: function (event, modal, caller) {
                        modal.remove();
                    }
                }
            ]
        });
    }
    else {
        ModalElement.question2({
            title: LanguageModule.text("txt_delete_conversation"),
            message: LanguageModule.text("war_txt_delete_conversation"),
            onclick: function(sel){
                if (sel == 0){
                    self.deleteGroup(item);
                }
            }
        });
    }
};

ChatBar.prototype.leaveGroup = function(item){
    var self = this;
    item.leaveFunc(item.id).then(function(value){
        if (self.manageModal !== undefined) self.manageModal.selfRemove();
        else if (self.frameView && self.frameView.length > 1) self.frameView.removeLast();
        self.dropGroup(item.id);
    });
};

ChatBar.prototype.leaveGroupConfirm = function(item){
    var self = this;
    if (self.isNotiCenter){
        hr.overviewWidget.showModal({
            title: LanguageModule.text("txt_leave_group"),
            content: LanguageModule.text2("war_txt_leave_group", item.name),
            buttons: [
                {
                    text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                        modal.remove();
                        self.leaveGroup(item);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"), onclick: function (event, modal, caller) {
                        modal.remove();
                    }
                }
            ]
        });
    }
    else {
        ModalElement.question2({
            title: LanguageModule.text("txt_leave_group"),
            message: LanguageModule.text2("war_txt_leave_group", item.name),
            onclick: function(sel){
                if (sel == 0){
                    self.leaveGroup(item);
                }
            }
        });
    }
};

ChatBar.prototype.editNameGroup = function(item){
    var self = this;
    var nameElt = absol.$('.card-manage-group-name', self.manageGroupDiv);
    DOMElement.removeAllChildren(nameElt);
    var name_inputtext = DOMElement.input({
        attrs: {
            className: "card-manage-group-name-input",
            onkeydown: function(event){
                if (event.keyCode == 13) saveFunc();
            },
            value: item.name
        }
    });
    nameElt.appendChild(name_inputtext);
    name_inputtext.focus();
    var editElt = absol.$('.card-manage-group-edit-btn-ctn', self.manageGroupDiv);
    DOMElement.removeAllChildren(editElt);
    var saveNameBtn = absol.buildDom({
        tag: 'button',
        class:['card-transparent-btn', 'card-manage-group-edit-btn'],
        child: 'span.mdi.mdi-check'
    });
    editElt.appendChild(saveNameBtn);
    var saveFunc = function(){
        var name =  name_inputtext.value.trim();
        if (name == ""){
            if (self.isNotiCenter){
                hr.overviewWidget.showModal({
                    title: "",
                    content: LanguageModule.text("war_txt_no_name"),
                    buttons: [
                        {
                            text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                                modal.remove();
                            }
                        }
                    ]
                });
            }
            else {
                ModalElement.alert({message: LanguageModule.text("war_txt_no_name")});
            }
            return;
        }
        item.changeNameGroupFunc(name).then(function(value){
            item.name = name;
            DOMElement.removeAllChildren(nameElt);
            nameElt.appendChild(DOMElement.textNode(name));
            DOMElement.removeAllChildren(editElt);
            editElt.appendChild(absol.buildDom({
                tag: 'button',
                class:['card-transparent-btn', 'card-manage-group-edit-btn'],
                child: 'span.mdi.mdi-pencil-outline',
                on: {
                    click: function(){
                        self.editNameGroup(item);
                    }
                }
            }));
            for (var i = 0; i < self.listMessItemView.length; i++){
                if (self.listMessItemView[i].id == item.id){
                    self.listMessItemView[i].elt.name = name;
                }
            }
        });
    };
    saveNameBtn.on('click', function(){
        saveFunc();
    });
};

ChatBar.prototype.manageGroup = function(item){
    var self = this;
    item.memberList.getIndex = function(id){
        for (var i = 0; i < item.memberList.length; i++){
            if (item.memberList[i].id == id) return i;
        }
        return -1;
    };
    var addMemberSubmit = function(members_group_select){
        var listEmpAdd = members_group_select.values;
        var listMemberAdd = [];
        var k;
        for (var i = 0; i < listEmpAdd.length; i++){
            k = self.database.employees.getIndex(listEmpAdd[i]);
            if (k >= 0) listMemberAdd.push(self.database.employees.items[k].userid);
        }
        if (listMemberAdd.length == 0){
            if (self.isNotiCenter){
                hr.overviewWidget.showModal({
                    title: "",
                    content: LanguageModule.text("war_txt_no_member"),
                    buttons: [
                        {
                            text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                                modal.remove();
                            }
                        }
                    ]
                });
            }
            else {
                ModalElement.alert({
                    message: LanguageModule.text("war_txt_no_member")
                });
            }
            return;
        }
        frameView.removeLast();
        item.addMemberGroupFunc(listMemberAdd).then(function(value){
            var userIndex, fullname = "";
            for (var i = 0; i < listMemberAdd.length; i++){
                userIndex = self.database.users.getByhomeid(listMemberAdd[i]);
                if (userIndex >= 0){
                    if (i > 0) fullname += ", ";
                    fullname += self.database.users.items[userIndex].fullname;
                    item.memberList.push({
                        id: listMemberAdd[i],
                        fullname: self.database.users.items[userIndex].fullname,
                        avatarSrc: self.database.users.items[userIndex].avatarSrc,
                        privilege: (systemconfig.userid == listMemberAdd[i])? 2 : 0
                    });
                }
            }
            drawListMember();
            for (var i = 0; i < self.listMessItemView.length; i++){
                if (self.listMessItemView[i].id == item.id){
                    self.listMessItemView[i].elt.messagetext = "Bạn vừa thêm "+ fullname + " vào cuộc trò chuyện.";
                    self.listMessItemView[i].elt.time = value.m_time;
                    self.listChatContent.insertBefore(self.listMessItemView[i].elt, self.listChatContent.firstChild);
                    if (self.listMessItemView[i].elt.new_noseen > 0){
                        if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                        else if (self.isNotiCenter && hr.mChatPage) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                    }
                    self.listMessItemView[i].elt.new_noseen = 0;
                }
            }
        });
    };
    var addMember = function(){
        var userNone = {};
        for (var i = 0; i < item.memberList.length; i++){
            userNone[item.memberList[i].id] = true;
        }
        var items = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(self, userNone);
        var members_group_select = absol.buildDom({
            tag: 'multichecktreemenu',
            class: "card-chat-members-group-select",
            props: {
                items: items,
                enableSearch: true,
                leafOnly: true
            }
        });
        var addMemberElt;
        if (self.isNotiCenter || hr.isMobile){
            var commands = [{
                icon:  DOMElement.i({
                    attrs: {
                        className: "material-icons"
                    },
                    text: "save"
                }),
                cmd: function(){
                    addMemberSubmit(members_group_select);
                }
            }];
            var header = absol.buildDom({
                tag: 'mheaderbar',
                props: {
                    actionIcon: DOMElement.i({
                        attrs: {
                            className: "material-icons"
                        },
                        text: "arrow_back_ios"
                    }),
                    title: LanguageModule.text("txt_add_to_group"),
                    commands: commands
                },
                on: {
                    action: function(){
                        frameView.removeLast();
                    },
                    command: function(event){
                        event.commandItem.cmd();
                    }
                }
            });
            var addMemberElt = absol.buildDom({
                tag: 'tabframe',
                child: [
                    header,
                    DOMElement.div({
                        attrs: {
                            className: "card-mobile-content"
                        },
                        children: [members_group_select]
                    })
                ]
            });
        }
        else {
            addMemberElt = absol.buildDom({
                tag: "tabframe",
                class: "card-chat-member",
                child: [
                    {
                        class: "card-chat-member-header",
                        child: [
                            {
                                class: 'card-chat-member-title-ctn',
                                child: [
                                    DOMElement.span({
                                        attrs: {
                                            className: 'card-chat-member-title'
                                        },
                                        text: LanguageModule.text("txt_add_to_group")
                                    })
                                ]
                            },
                            {
                                class:'card-chat-member-close-btn-ctn',
                                child: {
                                    tag: 'button',
                                    class:['card-transparent-btn', 'card-chat-member-close-btn'],
                                    child: 'span.mdi.mdi-close',
                                    on: {
                                        click: function(){
                                            frameView.removeLast();
                                        }
                                    }
                                }
                            }
                        ]
                    },
                    {
                        class: 'card-chat-member-body',
                        child: [members_group_select]
                    },
                    DOMElement.div({
                        attrs: {
                            align: "center"
                        },
                        children: [DOMElement.table({
                            data: [[
                                {
                                    children: [theme.noneIconButton({
                                        onclick: function(){
                                            addMemberSubmit(members_group_select);
                                        },
                                        text: LanguageModule.text("txt_save")
                                    })]
                                },
                                {
                                    attrs: {style: {width: hr.menu.distanceButtonForm}}
                                },
                                {
                                    children: [theme.noneIconButton({
                                        onclick: function (event, me) {
                                            frameView.removeLast();
                                        },
                                        text: LanguageModule.text("txt_cancel")
                                    })]
                                }
                            ]]
                        })]
                    })
                ]
            });
        }
        frameView.addChild(addMemberElt);
        addMemberElt.requestActive();
    };

    var removeMember = function(userid){
        item.removeMemberFunc(userid).then(function(value){
            var uIndex = item.memberList.getIndex(userid);
            var fullname = item.memberList[uIndex].fullname;
            item.memberList.splice(uIndex, 1);
            drawListMember();
            for (var i = 0; i < self.listMessItemView.length; i++){
                if (self.listMessItemView[i].id == item.id){
                    self.listMessItemView[i].elt.messagetext = "Bạn vừa xoá "+ fullname + " khỏi cuộc trò chuyện.";
                    self.listMessItemView[i].elt.time = value.m_time;
                    self.listChatContent.insertBefore(self.listMessItemView[i].elt, self.listChatContent.firstChild);
                    if (self.listMessItemView[i].elt.new_noseen > 0){
                        if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                        else if (hr.mChatPage && self.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                    }
                    self.listMessItemView[i].elt.new_noseen = 0;
                    break;
                }
            }
        });
    };

    var removeMemberConfirm = function(userid){
        var uIndex = item.memberList.getIndex(userid);
        if (self.isNotiCenter){
            hr.overviewWidget.showModal({
                title: LanguageModule.text("txt_remove_member"),
                content: LanguageModule.text2("war_txt_remove_member", [item.memberList[uIndex].fullname]),
                buttons: [
                    {
                        text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                            modal.remove();
                            removeMember(userid);
                        }
                    },
                    {
                        text: LanguageModule.text("txt_cancel"), onclick: function (event, modal, caller) {
                            modal.remove();
                        }
                    }
                ]
            });
        }
        else {
            ModalElement.question2({
                title: LanguageModule.text('txt_remove_member'),
                message: LanguageModule.text2("war_txt_remove_member", [item.memberList[uIndex].fullname]),
                onclick: function(sel){
                    if (sel == 0){
                        removeMember(userid);
                    }
                }
            });
        }
    };
    var listMemberElt = absol.buildDom({
        class: 'card-manage-group-participants-ctn',
        child: [
            DOMElement.div({
                attrs: {
                    className: "card-manage-group-participants-title"
                },
                text: LanguageModule.text2("txt_participants", [item.memberList.length])
            }),
            DOMElement.div({
                attrs: {
                    className: "card-manage-group-participants-content"
                }
            })
        ]
    });
    var drawListMember = function(){
        item.memberList.sort(function(a, b){
            if (a.id == systemconfig.userid) return 1;
            if (absol.string.nonAccentVietnamese(a.fullname.toLowerCase()) > absol.string.nonAccentVietnamese(b.fullname.toLowerCase())) return 1;
            if (absol.string.nonAccentVietnamese(a.fullname.toLowerCase()) < absol.string.nonAccentVietnamese(b.fullname.toLowerCase())) return -1;
            return 0;
        });
        DOMElement.removeAllChildren(listMemberElt);
        var listMemberEltTemp = DOMElement.div({
            attrs: {
                className: "card-manage-group-participants-content"
            }
        });
        listMemberEltTemp.appendChild(DOMElement.div({
            attrs: {
                className: "card-manage-group-participants-member",
                onclick: function(){
                    addMember();
                }
            },
            children: [
                DOMElement.div({
                    attrs: {
                        className: "card-manage-group-participants-member-avatar-ctn"
                    },
                    children: [DOMElement.div({
                        attrs: {
                            className: "card-manage-group-participants-member-avatar",
                            style: {
                                backgroundImage: "url(add_member.png)"
                            }
                        }
                    })]
                }),
                DOMElement.div({
                    attrs: {
                        className: "card-manage-group-participants-member-name"
                    },
                    text: LanguageModule.text("txt_add_member")
                })
            ]
        }));
        var manageMemberElt, quickMenuItems;
        for (var i = 0; i < item.memberList.length; i++){
            manageMemberElt = DOMElement.div({});
            quickMenuItems = [];
            if (item.privilege >= 2 && systemconfig.userid != item.memberList[i].id){
                quickMenuItems.push({
                    text: LanguageModule.text("txt_remove_member"),
                    extendClasses: "bsc-quickmenu",
                    icon: {
                        tag: "i",
                        class: "material-icons",
                        child: { text: "delete" }
                    },
                    cmd: function(userid){
                        return function(){
                            removeMemberConfirm(userid);
                        }
                    }(item.memberList[i].id)
                });
            }
            if (quickMenuItems.length > 0){
                manageMemberElt = DOMElement.div({
                    attrs: {
                        className: "card-manage-group-participants-member-remove",
                        style: {
                            visibility: "hidden"
                        }
                    },
                    children: [DOMElement.i({
                        attrs: {
                            className: "material-icons card-icon-manage-member-chat"
                        },
                        text: "more_horiz"
                    })]
                });
                absol.QuickMenu.showWhenClick(manageMemberElt, {items: quickMenuItems}, [3, 4], function (menuItem) {
                    if (menuItem.cmd) menuItem.cmd();
                });
            }
            listMemberEltTemp.appendChild(DOMElement.div({
                attrs: {
                    className: "card-manage-group-participants-member",
                    onmouseout: function(manageMemberElt){
                        return function(){
                            manageMemberElt.style.visibility = "hidden";
                        }
                    }(manageMemberElt),
                    onmouseover: function(manageMemberElt){
                        return function(){
                            manageMemberElt.style.visibility = "visible";
                        }
                    }(manageMemberElt)
                },
                children: [
                    DOMElement.div({
                        attrs: {
                            className: "card-manage-group-participants-member-avatar-ctn"
                        },
                        children: [DOMElement.div({
                            attrs: {
                                className: "card-manage-group-participants-member-avatar",
                                style: {
                                    backgroundImage: "url(" + item.memberList[i].avatarSrc + ")"
                                }
                            }
                        })]
                    }),
                    DOMElement.div({
                        attrs: {
                            className: "card-manage-group-participants-member-name"
                        },
                        text: item.memberList[i].fullname
                    }),
                    manageMemberElt
                ]
            }));
        }
        listMemberElt.appendChild(DOMElement.div({
            attrs: {
                className: "card-manage-group-participants-title"
            },
            text: LanguageModule.text2("txt_participants", [item.memberList.length])
        }));
        listMemberElt.appendChild(listMemberEltTemp);
    };
    drawListMember();
    var bodyManager = absol.buildDom({
        class: 'card-manage-group-body',
        child:[
            {
                class: 'card-manage-group-name-ctn',
                child:[
                {
                    class: 'card-manage-group-name',
                    child: {text: item.name}
                },
                {
                    class: 'card-manage-group-desc',
                    // child: {text: 'Active now'}
                },
                {
                    class: 'card-manage-group-edit-btn-ctn',
                    child:{
                    tag: 'button',
                    class:['card-transparent-btn', 'card-manage-group-edit-btn'],
                    child: 'span.mdi.mdi-pencil-outline'
                    }
                }
                ]
            },
            {
                class: 'card-manage-group-demarcation-line'
            },
            listMemberElt
        ]
    });
    bodyManager.appendChild(absol.buildDom({
        class: 'card-manage-group-demarcation-line'
    }));
    bodyManager.appendChild(absol.buildDom({
        class: 'card-manage-group-body-delete-leave',
        on: {
            click: function(){
                self.deleteGroupConfirm(item);
            }
        },
        child: DOMElement.span({
            text: LanguageModule.text("txt_delete_conversation")
        })
    }));
    bodyManager.appendChild(absol.buildDom({
        class: 'card-manage-group-demarcation-line'
    }));
    bodyManager.appendChild(absol.buildDom({
        class: 'card-manage-group-body-delete-leave',
        style: {
            color: "red"
        },
        on: {
            click: function(){
                self.leaveGroupConfirm(item);
            }
        },
        child: DOMElement.span({
            text: LanguageModule.text("txt_leave_group")
        })
    }));
    if (item.privilege >= 2){
        bodyManager.appendChild(absol.buildDom({
            class: 'card-manage-group-demarcation-line'
        }));
        bodyManager.appendChild(absol.buildDom({
            class: 'card-manage-group-body-delete-leave',
            style: {
                color: "red"
            },
            on: {
                click: function(){
                    self.dissolveGroupConfirm(item);
                }
            },
            child: DOMElement.span({
                text: LanguageModule.text("txt_dissolve_group")
            })
        }));
    }
    self.manageGroupDiv = absol.buildDom({
        tag: "tabframe",
        class: "card-manage-group",
        child: [
            {
                class: "card-manage-group-header",
                child: [
                    {
                        class: 'card-manage-group-avatar-block',
                        child: [
                            {
                                class: 'card-manage-group-avatar-image',
                                style:{
                                    'background-image': 'url(' + item.avatarSrc + ')'
                                }
                            },
                            {
                                class: ['card-manage-group-avatar-status-dot']
                            }
                        ]
                    },
                    {
                        class:'card-manage-group-close-btn-ctn',
                        child: {
                            tag: 'button',
                            class:['card-transparent-btn', 'card-manage-group-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    if (self.isNotiCenter || hr.isMobile) self.frameView.removeLast();
                                    else self.manageModal.selfRemove();
                                    if (hr.isMobile) hr.menu.showMobileTabbar(true);
                                }
                            }
                        }
                    }
                ]
            },
            bodyManager
        ]
    });
    var frameView;
    if (self.isNotiCenter || hr.isMobile){
        frameView = self.frameView;
        if (hr.isMobile) hr.menu.showMobileTabbar(false);
    }
    else {
        frameView = absol.buildDom({
            tag:'frameview',
            class: 'card-manage-group-frameview'
        });
        self.manageModal = absol.buildDom({
            tag: "modal",
            child: [frameView]
        });
        document.body.appendChild(self.manageModal);
    }
    frameView.addChild(self.manageGroupDiv);
    self.manageGroupDiv.requestActive();
    var editNameBtn = absol.$('.card-manage-group-edit-btn', self.manageGroupDiv);
    editNameBtn.on('click', function(){
        self.editNameGroup(item);
    });
    var saveAvatarFunc = function(src){
        item.changeAvatarGroupFunc(src).then(function(value){
            for (var i = 0; i < self.listMessItemView.length; i++){
                if (self.listMessItemView[i].id == item.id){
                    self.listMessItemView[i].elt.avatarSrc = src;
                }
            }
            item.avatarSrc = src;
            avtElt.style.backgroundImage = "url("+src+")";
        });
    };
    var avtElt = absol.$('.card-manage-group-avatar-image', self.manageGroupDiv);
    avtElt.on('click', function(){
        pizo.xmlModalDragImage.createModal(document.body,function(){
            var src = pizo.xmlModalDragImage.imgUrl.src;
            saveAvatarFunc(src);
        });
    });
};

ChatBar.prototype.getMessItem = function(item){
    var self = this;
    var mItemsNew = absol.buildDom({
        tag: "messageitem",
        props: {
            avatarSrc: item.avatarSrc,
            name: item.name,
            time: item.lasttime
        },
        on:{
            pressopen: function(event){
                self.func.openChatBoxFunc(item);
            }
        }
    });
    absol.$(mItemsNew).defineEvent('contextmenu');
    mItemsNew.on('contextmenu', function(event){
        var items = [];
        if (item.isGroup){
            items.push({
                text: LanguageModule.text("txt_manage_group"),
                extendClasses: "bsc-quickmenu",
                cmd: function(){
                    self.manageGroup(item);
                }
            });
        }
        items.push({
            text: LanguageModule.text("txt_delete_conversation"),
            extendClasses: "bsc-quickmenu",
            cmd: function(){
                self.deleteGroupConfirm(item);
            }
        });
        if (item.isGroup){
            items.push({
                text: LanguageModule.text("txt_leave_group"),
                extendClasses: "bsc-quickmenu",
                cmd: function(){
                    self.leaveGroupConfirm(item);
                }
            });
        }
        event.showContextMenu({
            items: items
        }, function(event){
            var cmd = event.menuItem.cmd;
            cmd();
        });
    });
    var new_noseen = 0;
    for (var j = 0; j < item.content.length; j++){
        if (item.content[j].localid > item.mess_seen_id){
            new_noseen++;
        }
    }
    mItemsNew.new_noseen = new_noseen;
    if (item.content.length > 0){
        var lastMess = item.content[item.content.length - 1];
        mItemsNew.messagetext = self.getMessageText(lastMess);
    }
    return mItemsNew;
};

ChatBar.prototype.drawListMessage = function(data){
    var self = this;
    var mItemsNew;
    for (var i = 0; i < data.length; i++){
        if (data[i].isdelete) continue;
        mItemsNew = this.getMessItem(data[i]);
        self.listChatContent.appendChild(mItemsNew);
        self.listMessItemView.push({
            id: data[i].id,
            elt: mItemsNew
        });
    }
};

ChatBar.prototype.loadOldChat_session = function(){
    var self = this;
    self.listChatContainer.addEventListener("scroll", function(){
        if (self.listChatContainer.scrollTop + self.listChatContainer.offsetHeight >= self.listChatContainer.scrollHeight){
            self.func.loadChat_sessionsOldFunc().then(function(values){
                self.drawListMessage(values);
            });
        }
    });
};

ChatBar.prototype.getView = function(){
    var self = this;
    var addGroupFunc = function(){
        var ex = false;
        self.func.addgroupFunc().then(function(value){
            for (var i = 0; i < self.listMessItemView.length; i++){
                if (self.listMessItemView[i].id == value.id){
                    ex = true;
                    self.listMessItemView[i].elt.emit("click");
                    break;
                }
            }
            if (!ex){
                var mItemsNew = self.getMessItem(value);
                self.listChatContent.insertBefore(mItemsNew, self.listChatContent.firstChild);
                self.listMessItemView.unshift({
                    id: value.id,
                    elt: mItemsNew
                });
                mItemsNew.emit("click");
            }
        });
    };
    this.listChatContent = absol._({
        class: "chats-theme-desktop-list-message-content"
    });
    this.listChatContainer = DOMElement.div({
        attrs: {
            className: "chats-theme-desktop-list-message-container"
        },
        children: [this.listChatContent]
    });
    this.listMessItemView = [];
    if (hr.isMobile){
        var commands = [];
        commands.push({
            icon:  DOMElement.i({
                attrs: {
                    className: "material-icons"
                },
                text: "group_add"
            }),
            cmd: function(){
                addGroupFunc();
            }
        });
        var header = absol.buildDom({
            tag: 'mheaderbar',
            props: {
                actionIcon: DOMElement.i({
                    attrs: {
                        className: "material-icons"
                    },
                    text: "arrow_back_ios"
                }),
                title: LanguageModule.text("txt_chat"),
                commands: commands
            },
            data: {
                searchInput: this.inputsearchbox
            },
            on: {
                action: function(){
                    hr.menu.loadPage(1000);
                },
                command: function(event){
                    event.commandItem.cmd();
                }
            }
        });
        this.listChatContainer.classList.add("mobile");
        this.view = absol.buildDom({
            tag: 'tabframe',
            child:[
                header,
                DOMElement.div({
                    attrs: {className: "card-mobile-content-no-padding"},
                    children: [this.listChatContainer]
                })
            ]
        });
    }
    else {
        this.addgroupIcon = DOMElement.i({
            attrs: {
                className: "material-icons bsc-icon-hover-black",
                style: {
                    margin: "5px"
                },
                onclick: function(){
                    addGroupFunc();
                }
            },
            text: "group_add"
        });
        this.view = DOMElement.div({
            attrs: {className: "chats-theme-desktop-container"},
            children: [
                DOMElement.div({
                    attrs: {className: "chats-theme-desktop-list-message"},
                    children: [
                        DOMElement.div({
                            attrs: {className: "chats-theme-desktop-searchbox-add-group"},
                            children: [
                                DOMElement.div({
                                    attrs: {
                                        className: "chats-theme-desktop-searchbox-container"
                                    },
                                    // children: [this.inputsearchbox]
                                }),
                                DOMElement.div({
                                    attrs: {
                                        className: "chats-theme-desktop-add-group-container"
                                    },
                                    children: [this.addgroupIcon]
                                })
                            ]
                        }),
                        this.listChatContainer
                    ]
                })
            ]
        });
    }
    this.drawListMessage(this.data);
    this.loadOldChat_session();
    return this.view;
};

ChatBar.prototype.dropGroup = function(id){
    var self = this;
    for (var i = 0; i < self.listMessItemView.length; i++){
        if (self.listMessItemView[i].id == id){
            self.listMessItemView[i].elt.remove();
            self.listMessItemView.splice(i, 1);
            break;
        }
    }
};

contentModule.generateDataChat = function(host, item){
    if (!item.pinid_list) item.pinid_list = [];
    else item.pinid_list = EncodingClass.string.toVariable(item.pinid_list);
    item.memberList = [];
    for (var i = 0; i < item.membersIdList.length; i++){
        var uIndex = host.database.users.getByhomeid(item.membersIdList[i].userid);
        if (uIndex < 0) continue;
        item.memberList.push({
            id: item.membersIdList[i].userid,
            fullname: host.database.users.items[uIndex].fullname,
            avatarSrc: host.database.users.items[uIndex].avatarSrc,
            privilege: item.membersIdList[i].privilege
        });
    }
    item.isGroup = false;
    if (item.memberList.length > 2) item.isGroup = true;
    else {
        for (var x = 0; x < item.memberList.length; x++){
            if (item.memberList[x].privilege >= 2){
                item.isGroup = true;
                break;
            }
        }
    }
    if (item.isGroup) {
        if (item.avatar !== "" && item.avatar !== undefined){
            item.avatarSrc = window.domainGroup_avatars + item.id + "_" + item.avatar;
        }
        else {
            item.avatarSrc = window.domainGroup_avatars + "default.svg";
        }
    }
    else {
        for (var j = 0; j < item.membersIdList.length; j++){
            if (item.membersIdList[j].userid !== systemconfig.userid){
                var userIndex = host.database.users.getByhomeid(item.membersIdList[j].userid);
                if (userIndex >= 0){
                    item.avatarSrc = host.database.users.items[userIndex].avatarSrc;
                    item.name = host.database.users.items[userIndex].fullname;
                }
                break;
            }
        }
    }

    item.sendFunc = function(host, item){
        return function(text, files, images, quote, listIdLocal){
            return new Promise(function(resolve, reject){
                hr.chats.sendMessage(host, item.id, text, files, images, quote, listIdLocal).then(function(value){
                    item.content = item.content.concat(value);
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == item.id){
                            if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                            var lastMess = value[value.length - 1];
                            host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(lastMess);
                            host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, host.chatBar.listChatContent.firstChild);
                            host.chatBar.listMessItemView[i].elt.time = lastMess.m_time;
                        }
                    }
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.seenFunc = function(host, item){
        return function(messid){
            return new Promise(function(resolve, reject){
                hr.chats.seenMess(host, item.id, messid).then(function(value){
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == item.id){
                            if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                        }
                    }
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.loadOldMessFunc = function(host, item){
        return function(){
            return new Promise(function(resolve, reject){
                hr.chats.loadOldMess(host, item.id).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.editMessageFunc = function(host, item){
        return function(localid, content, quote){
            return new Promise(function(resolve, reject){
                hr.chats.editMessage(host, item.id, localid, content, quote).then(function(value){
                    if (item.content.length > 0 && localid == item.content[item.content.length - 1].localid){
                        for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                            if (host.chatBar.listMessItemView[i].id == item.id){
                                host.chatBar.listMessItemView[i].elt.messagetext = content;
                            }
                        }
                    }
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.deleteMessageFunc = function(host, item){
        return function(localid, content){
            return new Promise(function(resolve, reject){
                hr.chats.deleteMessage(host, item.id, localid).then(function(value){
                    if (item.content.length > 0 && localid == item.content[item.content.length - 1].localid){
                        for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                            if (host.chatBar.listMessItemView[i].id == item.id){
                                if (item.content.length > 1){
                                    var lastMess = item.content[item.content.length - 2];
                                    host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(lastMess);
                                    host.chatBar.listMessItemView[i].elt.time = lastMess.m_time;
                                    var temp = host.chatBar.listChatContent.getElementsByClassName("chat-message-item");
                                    var ex;
                                    for (var j = 0; j < temp.length; j++){
                                        if (temp[j].time && temp[j].time.getTime() < lastMess.m_time.getTime()){
                                            host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, temp[j]);
                                            ex = true;
                                            break;
                                        }
                                    }
                                    if (!ex) host.chatBar.listChatContent.appendChild(host.chatBar.listMessItemView[i].elt);
                                }
                                else {
                                    host.chatBar.listMessItemView[i].elt.messagetext = "";
                                    host.chatBar.listMessItemView[i].elt.time = item.lasttime;
                                    var temp = host.chatBar.listChatContent.getElementsByClassName("chat-message-item");
                                    var ex;
                                    for (var j = 0; j < temp.length; j++){
                                        if (temp[j].time && temp[j].time.getTime() < item.lasttime.getTime()){
                                            host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, temp[j]);
                                            ex = true;
                                            break;
                                        }
                                    }
                                    if (!ex) host.chatBar.listChatContent.appendChild(host.chatBar.listMessItemView[i].elt);
                                }
                                break;
                            }
                        }
                    }
                    resolve(value);
                    for (var i = item.content.length - 1; i >= 0; i--){
                        if (item.content[i].localid == localid){
                            item.content.splice(i, 1);
                            break;
                        }
                    }
                });
            });
        }
    }(host, item);
    item.changeAvatarGroupFunc = function(host, item){
        return function(src){
            return hr.chats.changeAvatarGroup(host, item.id, src);
        }
    }(host, item);
    item.changeNameGroupFunc = function(host, item){
        return function(name){
            return new Promise(function(resolve, reject){
                hr.chats.changeNameGroup(host, item.id, name).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.addMemberGroupFunc = function(host, item){
        return function(listMember){
            return new Promise(function(resolve, reject){
                hr.chats.addMemberGroup(host, item.id, listMember).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.removeMemberFunc = function(host, item){
        return function(userid){
            return new Promise(function(resolve, reject){
                hr.chats.removeMemberGroup(host, item.id, userid).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.deleteFunc = function(host, item){
        return function(){
            return new Promise(function(resolve, reject){
                hr.chats.deleteGroup(host, item.id).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.leaveFunc = function(host, item){
        return function(){
            return new Promise(function(resolve, reject){
                hr.chats.leaveGroup(host, item.id).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.dissolveFunc = function(host, item){
        return function(){
            return new Promise(function(resolve, reject){
                hr.chats.dissolveGroup(host, item.id).then(function(value){
                    resolve(value);
                });
            });
        }
    }(host, item);
    item.reactionMessageFunc = function(host, item){
        return function(localid, icon){
            return hr.chats.reactionMessage(host, item.id, localid, icon);
        }
    }(host, item);
};

contentModule.getAddGroupChatView = function(host){
    var name_group_inputtext = theme.input({
        style: {
            width: "100%",
            marginTop: "var(--control-horizontal-distance-1)",
            marginBottom: "var(--control-horizontal-distance-2)"
        }
    });
    var userNone = {};
    userNone[systemconfig.userid] = true;
    var listUserAdd = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host, userNone);
    var members_group_select = absol.buildDom({
        tag: 'multichecktreemenu',
        class: "card-chat-members-group-select",
        style: {
            maxWidth: "100%"
        },
        props: {
            items: listUserAdd,
            leafOnly: true,
            enableSearch: true
        }
    });
    var view = DOMElement.div({
        children: [
            DOMElement.div({text: LanguageModule.text("txt_group_name")}),
            name_group_inputtext,
            DOMElement.div({text: LanguageModule.text("txt_add_members_into_group")}),
            members_group_select
        ]
    });
    view.getValue = function(){
        var x = members_group_select.values;
        var listMember = [];
        var employeesDic = contentModule.makeDictionaryIndex(host.database.employees.items);
        var k;
        for (var i = 0; i < x.length; i++){
            k = employeesDic[x[i]];
            if (k >= 0){
                listMember.push(host.database.employees.items[k].userid);
            }
        }
        var data = {
            name: name_group_inputtext.value.trim(),
            listMember: listMember
        };
        if (data.listMember.length < 1) {
            if (host.isNotiCenter){
                hr.overviewWidget.showModal({
                    title: "",
                    content: LanguageModule.text("war_txt_member_is_null"),
                    buttons: [
                        {
                            text: LanguageModule.text("txt_ok"), onclick: function (event, modal, caller) {
                                modal.remove();
                            }
                        }
                    ]
                });
            }
            else {
                ModalElement.alert({
                    message: LanguageModule.text("war_txt_member_is_null")
                });
            }
            return;
        }
        return data;
    };
    name_group_inputtext.focus();
    return view;
};

contentModule.addGroupChatFunc = function(host){
    return new Promise(function(resolve, reject){
        var res = contentModule.getAddGroupChatView(host);
        var commands = [{
            icon:  DOMElement.i({
                attrs: {
                    className: "material-icons"
                },
                text: "save"
            }),
            cmd: function(){
                var data = res.getValue();
                if (!data) return;
                hr.chats.addGroupChatFuncSubmit(host, data).then(function(value){
                    host.frameList.removeLast();
                    resolve(value);
                    if (hr.isMobile) hr.menu.showMobileTabbar(true);
                });
            }
        }];
        var header = absol.buildDom({
            tag: 'mheaderbar',
            class: hr.isMobile? "" : "am-light-weight",
            props: {
                actionIcon: DOMElement.i({
                    attrs: {
                        className: "material-icons"
                    },
                    text: "arrow_back_ios"
                }),
                title: LanguageModule.text("txt_add_group"),
                commands: commands
            },
            on: {
                action: function(){
                    host.frameList.removeLast();
                    if (hr.isMobile) hr.menu.showMobileTabbar(true);
                },
                command: function(event){
                    event.commandItem.cmd();
                }
            }
        });
        var view = absol.buildDom({
            tag: 'tabframe',
            child:[
                header,
                DOMElement.div({
                    attrs: {
                        className: "card-mobile-content"
                    },
                    children: [res]
                })
            ]
        });
        host.frameList.addChild(view);
        view.requestActive();
        if (hr.isMobile) hr.menu.showMobileTabbar(false);
    });
};

contentModule.newMessFunc = function(host){
    contentModule.shareMessageReceiver.on('chat', function (messageContent) {
        if (host.listMessRandomCreate[messageContent.randomId]) return;
        if (messageContent.membersIdList.indexOf(systemconfig.userid) < 0) return;
        switch (messageContent.type) {
            case "add":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    host.database.chat_sessions.items[sIndex].content = host.database.chat_sessions.items[sIndex].content.concat(messageContent.dataDraw);
                }
                var ex;
                for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                    if (host.chatBar.listMessItemView[i].id == messageContent.id){
                        ex = true;
                        if (messageContent.userid == systemconfig.userid){
                            if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                        }
                        else {
                            if (host.chatBar.listMessItemView[i].elt.new_noseen == 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter + 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter + 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = host.chatBar.listMessItemView[i].elt.new_noseen + messageContent.dataDraw.length;
                        }
                        var lastMess = messageContent.dataDraw[messageContent.dataDraw.length - 1];
                        host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(lastMess);
                        host.chatBar.listMessItemView[i].elt.time = lastMess.m_time;
                        host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, host.chatBar.listChatContent.firstChild);
                    }
                }
                if (!ex){
                    hr.chats.loadSessionNew(host, messageContent.id).then(function(value){
                        console.log(value);
                        var mItemsNew = host.chatBar.getMessItem(value);
                        host.chatBar.listChatContent.insertBefore(mItemsNew, host.chatBar.listChatContent.firstChild);
                        host.chatBar.listMessItemView.unshift({
                            id: value.id,
                            elt: mItemsNew
                        });
                    });
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        for (var i = 0; i < messageContent.dataDraw.length; i++){
                            host.chatActive.chatBox.addMessage(messageContent.dataDraw[i]);
                        }
                    }
                }
                break;
            case "editmessage":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    var item = host.database.chat_sessions.items[sIndex];
                    for (var i = 0; i < item.content.length; i++){
                        if (item.content[i].localid == messageContent.localid){
                            item.content[i].content = messageContent.content;
                        }
                    }
                    if (item.content.length > 0 && messageContent.localid == item.content[item.content.length - 1].localid){
                        for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                            if (host.chatBar.listMessItemView[i].id == messageContent.id){
                                host.chatBar.listMessItemView[i].elt.messagetext = messageContent.content;
                            }
                        }
                    }
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.chatActive.chatBox.editMessageRedraw(messageContent.localid, messageContent.content, messageContent.quote);
                    }
                }
                break;
            case "dissolve_group":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    host.database.chat_sessions.items.splice(sIndex, 1);
                }
                for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                    if (host.chatBar.listMessItemView[i].id == messageContent.id){
                        host.chatBar.dropGroup(messageContent.id);
                    }
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.dropChatActive();
                        host.chatActive = null;
                    }
                }
                break;
            case "add_member_group":
                console.log(messageContent);
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    host.database.chat_sessions.items[sIndex].content.push(messageContent.newMess);
                    host.database.chat_sessions.items[sIndex].membersIdList = host.database.chat_sessions.items[sIndex].membersIdList.concat(messageContent.listMemberAdd);
                }
                var ex;
                for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                    if (host.chatBar.listMessItemView[i].id == messageContent.id){
                        ex = true;
                        if (messageContent.userid == systemconfig.userid){
                            if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                        }
                        else {
                            if (host.chatBar.listMessItemView[i].elt.new_noseen == 0){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter + 1);
                                else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter + 1;
                            }
                            host.chatBar.listMessItemView[i].elt.new_noseen = host.chatBar.listMessItemView[i].elt.new_noseen + 1;
                        }
                        host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(messageContent.newMess);
                        host.chatBar.listMessItemView[i].elt.time = messageContent.newMess.m_time;
                        host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, host.chatBar.listChatContent.firstChild);
                    }
                }
                if (!ex){
                    hr.chats.loadSessionNew(host, messageContent.id).then(function(value){
                        var mItemsNew = host.chatBar.getMessItem(value);
                        host.chatBar.listChatContent.insertBefore(mItemsNew, host.chatBar.listChatContent.firstChild);
                        host.chatBar.listMessItemView.unshift({
                            id: value.id,
                            elt: mItemsNew
                        });
                    });
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.chatActive.chatBox.addMessage(messageContent.newMess);
                    }
                }
                break;
            case "leave_group":
                if (messageContent.userLeave == systemconfig.userid){
                    var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                    if (sIndex >= 0){
                        host.database.chat_sessions.items.splice(sIndex, 1);
                    }
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == messageContent.id){
                            host.chatBar.dropGroup(messageContent.id);
                        }
                    }
                    if (host.chatActive){
                        if (host.chatActive.id == messageContent.id){
                            host.dropChatActive();
                            host.chatActive = null;
                        }
                    }
                }
                else {
                    var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                    if (sIndex >= 0){
                        host.database.chat_sessions.items[sIndex].content.push(messageContent.newMess);
                        for (var i = 0; i < host.database.chat_sessions.items[sIndex].membersIdList.length; i++){
                            if (host.database.chat_sessions.items[sIndex].membersIdList[i].userid == messageContent.userLeave){
                                host.database.chat_sessions.items[sIndex].membersIdList.splice(i, 1);
                            }
                        }
                    }
                    var ex;
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == messageContent.id){
                            ex = true;
                            if (messageContent.userid == systemconfig.userid){
                                if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                    if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                    else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                                }
                                host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                            }
                            else {
                                if (host.chatBar.listMessItemView[i].elt.new_noseen == 0){
                                    if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter + 1);
                                    else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter + 1;
                                }
                                host.chatBar.listMessItemView[i].elt.new_noseen = host.chatBar.listMessItemView[i].elt.new_noseen + 1;
                            }
                            host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(messageContent.newMess);
                            host.chatBar.listMessItemView[i].elt.time = messageContent.newMess.m_time;
                            host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, host.chatBar.listChatContent.firstChild);
                        }
                    }
                    if (!ex){
                        hr.chats.loadSessionNew(host, messageContent.id).then(function(value){
                            var mItemsNew = host.chatBar.getMessItem(value);
                            host.chatBar.listChatContent.insertBefore(mItemsNew, host.chatBar.listChatContent.firstChild);
                            host.chatBar.listMessItemView.unshift({
                                id: value.id,
                                elt: mItemsNew
                            });
                        });
                    }
                    if (host.chatActive){
                        if (host.chatActive.id == messageContent.id){
                            host.chatActive.chatBox.addMessage(messageContent.newMess);
                        }
                    }
                }
                break;
            case "add_session":
                hr.chats.loadSessionNew(host, messageContent.id).then(function(value){
                    var mItemsNew = host.chatBar.getMessItem(value);
                    host.chatBar.listChatContent.insertBefore(mItemsNew, host.chatBar.listChatContent.firstChild);
                    host.chatBar.listMessItemView.unshift({
                        id: value.id,
                        elt: mItemsNew
                    });
                });
                break;
            case "change_group_name":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    host.database.chat_sessions.items[sIndex].name = messageContent.name;
                }
                for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                    if (host.chatBar.listMessItemView[i].id == messageContent.id){
                        host.chatBar.listMessItemView[i].elt.name = messageContent.name;
                    }
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.chatActive.chatBox.titleChat.innerText = messageContent.name;
                    }
                }
                break;
            case "remove_member_group":
                if (messageContent.userRemove == systemconfig.userid){
                    var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                    if (sIndex >= 0){
                        host.database.chat_sessions.items.splice(sIndex, 1);
                    }
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == messageContent.id){
                            host.chatBar.dropGroup(messageContent.id);
                        }
                    }
                    if (host.chatActive){
                        if (host.chatActive.id == messageContent.id){
                            host.dropChatActive();
                            host.chatActive = null;
                        }
                    }
                }
                else {
                    var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                    if (sIndex >= 0){
                        host.database.chat_sessions.items[sIndex].content.push(messageContent.newMess);
                        for (var i = 0; i < host.database.chat_sessions.items[sIndex].membersIdList.length; i++){
                            if (host.database.chat_sessions.items[sIndex].membersIdList[i].userid == messageContent.userRemove){
                                host.database.chat_sessions.items[sIndex].membersIdList.splice(i, 1);
                            }
                        }
                    }
                    var ex;
                    for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                        if (host.chatBar.listMessItemView[i].id == messageContent.id){
                            ex = true;
                            if (messageContent.userid == systemconfig.userid){
                                if (host.chatBar.listMessItemView[i].elt.new_noseen > 0){
                                    if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter - 1);
                                    else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter - 1;
                                }
                                host.chatBar.listMessItemView[i].elt.new_noseen = 0;
                            }
                            else {
                                if (host.chatBar.listMessItemView[i].elt.new_noseen == 0){
                                    if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(86, 'counter', hr.menu.mobileTabbar.getItem(86).counter + 1);
                                    else if (hr.mChatPage && host.isNotiCenter) hr.mChatPage.counter = hr.mChatPage.counter + 1;
                                }
                                host.chatBar.listMessItemView[i].elt.new_noseen = host.chatBar.listMessItemView[i].elt.new_noseen + 1;
                            }
                            host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(messageContent.newMess);
                            host.chatBar.listMessItemView[i].elt.time = messageContent.newMess.m_time;
                            host.chatBar.listChatContent.insertBefore(host.chatBar.listMessItemView[i].elt, host.chatBar.listChatContent.firstChild);
                        }
                    }
                    if (!ex){
                        hr.chats.loadSessionNew(host, messageContent.id).then(function(value){
                            var mItemsNew = host.chatBar.getMessItem(value);
                            host.chatBar.listChatContent.insertBefore(mItemsNew, host.chatBar.listChatContent.firstChild);
                            host.chatBar.listMessItemView.unshift({
                                id: value.id,
                                elt: mItemsNew
                            });
                        });
                    }
                    if (host.chatActive){
                        if (host.chatActive.id == messageContent.id){
                            host.chatActive.chatBox.addMessage(messageContent.newMess);
                        }
                    }
                }
                break;
            case "change_group_avatar":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    host.database.chat_sessions.items[sIndex].avatarSrc = messageContent.avatarSrc;
                }
                for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                    if (host.chatBar.listMessItemView[i].id == messageContent.id){
                        ex = true;
                        host.chatBar.listMessItemView[i].elt.avatarSrc = messageContent.avatarSrc;
                    }
                }
                break;
            case "reactionmessage":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    var item = host.database.chat_sessions.items[sIndex];
                    for (var i = 0; i < item.content.length; i++){
                        if (item.content[i].localid == messageContent.localid){
                            item.content[i].extra = messageContent.extra;
                        }
                    }
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.chatActive.chatBox.reactionMessageRedraw(messageContent.localid, messageContent.extra.emoji);
                    }
                }
                break;
            case "deletemessage":
                var sIndex = host.database.chat_sessions.getIndex(messageContent.id);
                if (sIndex >= 0){
                    var item = host.database.chat_sessions.items[sIndex];
                    if (item.content.length > 0 && messageContent.localid == item.content[item.content.length - 1].localid){
                        for (var i = 0; i < host.chatBar.listMessItemView.length; i++){
                            if (host.chatBar.listMessItemView[i].id == messageContent.id){
                                if (item.content.length > 1){
                                    host.chatBar.listMessItemView[i].elt.messagetext = host.chatBar.getMessageText(item.content[item.content.length - 2]);
                                    host.chatBar.listMessItemView[i].elt.time = item.content[item.content.length - 2].m_time;
                                }
                                else {
                                    host.chatBar.listMessItemView[i].elt.messagetext = "";
                                    host.chatBar.listMessItemView[i].elt.time = "";
                                }
                            }
                        }
                    }
                    for (var i = 0; i < item.content.length; i++){
                        if (item.content[i].localid == messageContent.localid){
                            item.content.splice(i, 1);
                        }
                    }
                }
                if (host.chatActive){
                    if (host.chatActive.id == messageContent.id){
                        host.chatActive.chatBox.deleteMessageRedraw(messageContent.localid);
                    }
                }
                break;
            default:

        }
    });
};

contentModule.makeArchivedChat = function(host, item){
    item.archivedIdList = [];
    var k;
    for (var i = 0; i < host.database.archived_chats.items.length; i++){
        if (host.database.archived_chats.items[i].chatid != item.id) continue;
        if (host.database.archived_chats.items[i].content !== undefined){
            host.database.archived_chats.items[i].content = EncodingClass.string.toVariable(host.database.archived_chats.items[i].content);
            item.content = host.database.archived_chats.items[i].content.concat(item.content);
        }
        else {
            item.archivedIdList.push(host.database.archived_chats.items[i].id);
        }
    }
};

contentModule.createChatPage = function(host){
    contentModule.newMessFunc(host);
    host.listMessRandomCreate = {};
    host.frameList = absol.buildDom({
        tag: "frameview",
        class: "main-frame-view",
        style: {
            width: "100%",
            height: "100%"
        }
    });
    host.dropChatActive = function(){
        host.frameList.removeLast();
    };
    DOMElement.removeAllChildren(host.holder);
    host.holder.appendChild(host.frameList);
    contentModule.makeChat_session_membersIndex(host);
    for (var i = 0; i < host.database.chat_sessions.items.length; i++){
        contentModule.makeArchivedChat(host, host.database.chat_sessions.items[i]);
        contentModule.generateDataChat(host, host.database.chat_sessions.items[i]);
    }
    host.historyOpenChat = {};
    host.chatBar = new ChatBar({
        database: host.database,
        orgViewDic: host.orgViewDic,
        orgEditDic: host.orgEditDic,
        employeeEditDic: host.employeeEditDic,
        data: host.database.chat_sessions.items,
        isNotiCenter: host.isNotiCenter,
        frameView: host.frameList,
        func: {
            addgroupFunc: function(){
                return contentModule.addGroupChatFunc(host);
            },
            loadChat_sessionsOldFunc: function(){
                return new Promise(function(resolve, reject){
                    hr.chats.loadChat_sessionsOld(host).then(function(value){
                        resolve(value);
                    });
                });
            },
            openChatBoxFunc: function(data){
                if (hr.isMobile) hr.menu.showMobileTabbar(false);
                host.nameChat = DOMElement.span({
                    text: data.name
                });
                var chatBox = new ChatBox({
                    database: host.database,
                    data: data,
                    isNotiCenter: true,
                });
                var chatBoxView = chatBox.getView();
                var commands = [];
                if (!hr.isMobile){
                    commands.push({
                        icon:  DOMElement.i({
                            attrs: {
                                className: "mdi mdi-window-maximize"
                            }
                        }),
                        cmd: function(){
                            hr.overviewWidget.minimize();
                            hr.menu.loadPage(86, data.id);
                        }
                    });
                }
                var header = absol.buildDom({
                    tag: 'mheaderbar',
                    class: hr.isMobile? "" : "am-light-weight",
                    props: {
                        actionIcon: DOMElement.i({
                            attrs: {
                                className: "material-icons"
                            },
                            text: "arrow_back_ios"
                        }),
                        title: host.nameChat,
                        commands: commands
                    },
                    on: {
                        action: function(){
                            host.frameList.removeLast();
                            host.historyOpenChat[data.id] = {
                                vMediaInput: chatBox.vMediaInput,
                                localidEdit: chatBox.localidEdit
                            };
                            host.chatActive = null;
                            if (hr.isMobile) hr.menu.showMobileTabbar(true);
                        },
                        command: function(event){
                            event.commandItem.cmd();
                        }
                    }
                });
                var view = absol.buildDom({
                    tag: 'tabframe',
                    child:[
                        header,
                        DOMElement.div({
                            attrs: {
                                className: "card-mobile-content-no-padding"
                            },
                            children: [chatBoxView]
                        })
                    ]
                });
                chatBox.titleChat = host.nameChat;
                host.chatActive = {
                    id: data.id,
                    chatBox: chatBox
                };
                setTimeout(function () {
                    chatBox.vMediaInput.focus();
                    if (host.historyOpenChat[data.id]){
                        chatBox.vMediaInput.mode = host.historyOpenChat[data.id].vMediaInput.mode;
                        chatBox.vMediaInput.text = host.historyOpenChat[data.id].vMediaInput.text;
                        chatBox.vMediaInput.files = host.historyOpenChat[data.id].vMediaInput.files;
                        chatBox.vMediaInput.images = host.historyOpenChat[data.id].vMediaInput.images;
                        chatBox.localidEdit = host.historyOpenChat[data.id].localidEdit;
                    }
                }, 100);
                host.frameList.addChild(view);
                view.requestActive();
            }
        }
    });
    if (hr.isMobile){
        var singlePage = host.chatBar.getView();
    }
    else {
        var singlePage = absol.buildDom({
            tag: "frame",
            child: [host.chatBar.getView()]
        });
    }
    host.frameList.addChild(singlePage);
    singlePage.requestActive();
};

contentModule.makePrivilegesEmployment_contracts_salary_decisionsConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeViewDic[host.database.employees.items[i].id] = true;
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            host.listConfigPrivilegeOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        host.listConfigPrivilegeOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        if (!host.listConfigPrivilegeOfMe[i].content.edit_employment_contracts_salary_decisions_bank_accounts && !host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee) continue;
        host.privAdd = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeViewDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesActivitiesConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (!item.content.edit_activities) return;
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            host.listConfigPrivilegeOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        host.listConfigPrivilegeOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.privAdd = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeEditDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesFunctionalMatrixsConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (!item.content.edit_functional_matrix) return;
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            host.listConfigPrivilegeOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        host.listConfigPrivilegeOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.privAdd = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeEditDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesPoliciesConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2 || data_module.admin_rights_of_me.human_resource_policy) {
        host.privApply = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            host.listConfigPrivilegeOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        host.listConfigPrivilegeOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        if (!host.listConfigPrivilegeOfMe[i].content.edit_hr_policies && !host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee) continue;
        host.privApply = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                host.employeeEditDic[eid] = true;
            });
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesListsConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeViewDic[host.database.employees.items[i].id] = true;
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            host.listConfigPrivilegeOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        host.listConfigPrivilegeOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        if (!host.listConfigPrivilegeOfMe[i].content.edit_list && !host.listConfigPrivilegeOfMe[i].content.view_list && !host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee) continue;
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                });
            }
        }
        if (host.listConfigPrivilegeOfMe[i].content.edit_list || host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee){
            host.privAdd = true;
            for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
                k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
                if (k >= 0){
                    host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                        host.employeeEditDic[eid] = true;
                    });
                }
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeViewDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesWarehousesConfigs = function(host, priv){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeEditDic = {};
    host.listWarehousePriv = [];
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        for (var i = 0; i < host.database.warehouses.items.length; i++){
            host.listWarehousePriv.push(host.database.warehouses.items[i].id);
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content[priv]){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].content.level == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].content.orgid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].content.orgid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listWarehousePriv.push(host.listConfigPrivilegeOfMe[i].taskid);
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                host.employeeEditDic[eid] = true;
            });
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].content.orgid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
        host.privAdd = true;
    }
    if (host.employeeOfMe.length > 0){
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.getDepartmentListSelectTreeMenuFilterHasView = function(host, companyId){
    function getOrgItem(index){
        var items = [], ni;
        for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
            ni = host.database.orgs.items[index].childIndexList[i];
            if (!host.orgViewDic[host.database.orgs.items[ni].id]) continue;
            items.push(getOrgItem(ni));
        }
        var res = {
            value: host.database.orgs.items[index].id,
            text: host.database.orgs.items[index].name,
            items: items
        };
        return res;
    };
    var items = [{value: 0, text: LanguageModule.text("txt_all_department")}];
    for (var i = 0; i < host.database.orgs.items.length; i++){
        if (host.database.orgs.items[i].parentid != companyId) continue;
        if (!host.orgViewDic[host.database.orgs.items[i].id]) continue;
        items.push(getOrgItem(i));
    }
    return items;
};

contentModule.getDepartmentIDListPrivView = function(host, index){
    if (index < 0) return [];
    var list = [host.database.orgs.items[index].id];
    var ni;
    for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
        ni = host.database.orgs.items[index].childIndexList[i];
        if (host.orgViewDic && !host.orgViewDic[host.database.orgs.items[ni].id]) continue;
        list = list.concat(contentModule.getDepartmentIDListPrivView(host, ni));
    }
    return list;
};

contentModule.formApplyToPolicies = function(params){
    return new Promise(function(resolve, reject){
        var f = function(){
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "load_employee_policies_active_by_policy"},
                    {name: "type", value: params.type},
                    {name: "policyid", value: params.policyid}
                ],
                func: function(success, message){
                    ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            var values = [];
                            for (var i = 0; i < st.length; i++){
                                if (values.indexOf(st[i].employeeid) >= 0) continue;
                                values.push(st[i].employeeid);
                            }
                            var saveEmployeePolicies = function(){
                                var employeeIdList = department_employee_select.values;
                                employeeIdList.sort(function(a, b){
                                    return a - b;
                                });
                                if (employeeIdList.length == 0){
                                    ModalElement.alert({message: LanguageModule.text("war_txt_department_employee_is_null")});
                                    return;
                                }
                                var data = {
                                    policyid: params.policyid,
                                    type: params.type,
                                    employeeIdList: employeeIdList,
                                    extrainfo: EncodingClass.string.fromVariable({})
                                };
                                if (params.type == "insurance" && params.calculated_on == "option"){
                                    value = value_input.value.trim();
                                    if (value == ""){
                                        ModalElement.alert({message: LanguageModule.text("war_txt_value_in_null")});
                                        return;
                                    }
                                    data.value = parseFloat(value);
                                }
                                else {
                                    data.value = 0;
                                }
                                ModalElement.show_loading();
                                FormClass.api_call({
                                    url: "policies_apply_to_employee.php",
                                    params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
                                    func: function(success, message){
                                        ModalElement.close(-1);
                                        if (success){
                                            if (message.substr(0, 2) == "ok"){
                                                ModalElement.close();
                                                resolve();
                                            }
                                            else {
                                                ModalElement.alert({message: message});
                                            }
                                        }
                                        else {
                                            ModalElement.alert({message: message});
                                        }
                                    }
                                });
                            };
                            var department_employee_select = absol.buildDom({
                                tag: "multichecktreemenu",
                                style: {
                                    width: "100%"
                                },
                                props: {
                                    items: orgEmpItems,
                                    leafOnly: true,
                                    enableSearch: true,
                                    values: values
                                }
                            });
                            var data = [
                                [
                                    {
                                        attrs: {style: {whiteSpace: "nowrap"}},
                                        text: LanguageModule.text("txt_department_employee")
                                    },
                                    {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                                    department_employee_select
                                ]
                            ];
                            if (params.type == "insurance"){
                                if (params.calculated_on == "option"){
                                    var value_input = theme.input({
                                        style: {
                                            width: "100%",
                                            minWidth: "300px"
                                        },
                                        type: "number"
                                    });
                                    data.push(
                                        [{attrs: {style: {height: "var(--control-horizontal-distance-2)"}}}],
                                        [
                                            {
                                                attrs: {style: {whiteSpace: "nowrap"}},
                                                text: LanguageModule.text("txt_value")
                                            },
                                            {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                                            value_input
                                        ]
                                    );
                                }
                            }
                            ModalElement.showWindow({
                                title: LanguageModule.text("txt_apply_to"),
                                bodycontent: DOMElement.table({
                                    data: data
                                }),
                                buttonlist: [
                                    {
                                        text: LanguageModule.text("txt_ok"),
                                        onclick: function(){
                                            saveEmployeePolicies();
                                        }
                                    },
                                    {
                                        text: LanguageModule.text("txt_cancel"),
                                        onclick: function(){
                                            ModalElement.close();
                                        }
                                    }
                                ]
                            });
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        };
        var employeeHasPolicyGroup;
        var loadEmployeeHasPolicyGroup = function(){
            return new Promise(function(resolve, reject){
                FormClass.api_call({
                    url: "database_load.php",
                    params: [
                        {name: "task", value: "load_employee_has_leave_policy_group_by_policyid"},
                        {name: "policyid", value: params.policyid}
                    ],
                    func: function(success, message){
                        if (success){
                            if (message.substr(0, 2) == "ok"){
                                var st = EncodingClass.string.toVariable(message.substr(2));
                                employeeHasPolicyGroup = st;
                                resolve();
                            }
                            else {
                                ModalElement.alert({message: message});
                            }
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                });
            });
        };
        var orgEmpItems;
        var promiseList = [
            data_module.loadOrgsList(),
            data_module.loadEmployeesList(),
            data_module.loadPeoplesList()
        ];
        if (params.type == "leave"){
            promiseList.push(loadEmployeeHasPolicyGroup());
        }
        ModalElement.show_loading();
        Promise.all(promiseList).then(function(value){
            var temp = {database: {}};
            contentModule.makeDatabaseContent(temp, {orgs: value[0], employees: value[1], peoples: value[2]});
            var pDict = {};
            temp.database.peoples.items.forEach(function(elt){
                pDict[elt.id] = elt;
            });
            temp.database.employees.items.forEach(function(elt){
                elt.fullname = pDict[elt.peopleid].fullname;
            });
            contentModule.makeOrgsIndex(temp);
            contentModule.makeEmployeesIndex(temp);
            if (params.type == "leave"){
                temp.employeeNotViewDic = {};
                for (var i = 0; i < employeeHasPolicyGroup.length; i++){
                    temp.employeeNotViewDic[employeeHasPolicyGroup[i]] = true;
                }
            }
            orgEmpItems = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(temp);
            f();
        });
    });
};

contentModule.getOrgsAndEmployeesListSelectTreeMenuLeafPriv = function(host){
    function getOrgItem(index){
        var items = [], ni;
        for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
            ni = host.database.orgs.items[index].childIndexList[i];
            if (!host.orgViewDic[host.database.orgs.items[ni].id]) continue;
            items.push(getOrgItem(ni));
        }
        items.sort(function(a, b){
            if (a.sortText > b.sortText) return 1;
            if (a.sortText < b.sortText) return -1;
            return 0;
        });
        var e_items = [], ni;
        for (var i = 0; i < host.database.orgs.items[index].employeeIndexList.length; i++){
            ni = host.database.orgs.items[index].employeeIndexList[i];
            if (!host.employeeEditDic[host.database.employees.items[ni].id]) continue;
            e_items.push({
                value: host.database.employees.items[ni].id,
                text: host.database.employees.items[ni].fullname,
                icon: {tag:'span', class:['mdi', 'mdi-account']},
                sortText: absol.string.nonAccentVietnamese(host.database.employees.items[ni].fullname).toLowerCase(),
                isLeaf: true
            });
        }
        e_items.sort(function(a, b){
            if (a.sortText > b.sortText) return 1;
            if (a.sortText < b.sortText) return -1;
            return 0;
        });
        console.log(e_items);
        var res = {
            value: -host.database.orgs.items[index].id,
            text: host.database.orgs.items[index].name,
            icon: {tag:'span', class:['mdi', 'mdi-folder-account']},
            items: items.concat(e_items),
            sortText: absol.string.nonAccentVietnamese(host.database.orgs.items[index].name).toLowerCase()
        };
        return res;
    };
    var items = [];
    for (var i = 0; i < host.database.orgs.items.length; i++){
        if (host.database.orgs.items[i].parentid != 0) continue;
        if (!host.orgViewDic[host.database.orgs.items[i].id]) continue;
        items.push(getOrgItem(i));
    }
    items.sort(function(a, b){
        if (a.sortText > b.sortText) return 1;
        if (a.sortText < b.sortText) return -1;
        return 0;
    });
    return items;
};

contentModule.getOrgsListSelectTreeMenuNotRoot = function(host){
    function getOrgItem(index){
        var items = [];
        for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
            items.push(getOrgItem(host.database.orgs.items[index].childIndexList[i]));
        }
        var res = {
            value: host.database.orgs.items[index].id,
            text: host.database.orgs.items[index].name,
            items: items
        };
        return res;
    };
    var items = [{value: 0, text: LanguageModule.text("txt_select_value")}];
    for (var i = 0; i < host.database.orgs.items.length; i++){
        if (host.database.orgs.items[i].parentid != 0) continue;
        items.push(getOrgItem(i));
    }
    return items;
};

contentModule.makePrivilegeAsset_transaction = function(host){
    var k, orgid, warehouseid;
    if (systemconfig.privSystem >= 2){
        for (var i = 0; i < host.database.asset_transactions.items.length; i++){
            host.database.asset_transactions.items[i].privView = true;
            host.database.asset_transactions.items[i].privEdit = true;
        }
        return;
    }
    for (var i = 0; i < host.database.asset_transactions.items.length; i++){
        k = host.employeesDic[host.database.asset_transactions.items[i].employeeid];
        if (k >= 0){
            orgid = host.database.employees.items[k].orgid;
            warehouseid = host.database.asset_transactions.items[i].warehouseid;
            for (var j = 0; j < host.listConfigPrivilegeOfMe.length; j++){
                if (host.listConfigPrivilegeOfMe[j].taskid != warehouseid) continue;
                if (host.listConfigPrivilegeOfMe[j].departmentList.indexOf(orgid) >= 0){
                    host.database.asset_transactions.items[i].privView = true;
                    host.database.asset_transactions.items[i].privEdit = true;
                    break;
                }
            }
        }
        if (!host.database.asset_transactions.items[i].privView){
             if (host.database.asset_transactions.items[i].employeeid == host.employeeOfMe[0]){
                 host.database.asset_transactions.items[i].privView = true;
             }
        }
    }
};

contentModule.changeEmployeeWarehousesPrivileges = function(host, employeeElt, warehouseElt){
    employeeElt.domElt.on("change", function(){
        if (systemconfig.privSystem >= 2) return;
        var employeeid = employeeElt.domElt.value;
        if (employeeid > 0){
            var k = host.employeesDic[employeeid];
            if (k >= 0){
                var orgid = host.database.employees.items[k].orgid;
                var x = {
                    database: {
                        warehouses: host.database.warehouses
                    }
                };
                x.listWarehousePriv = [];
                for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
                    if (host.listConfigPrivilegeOfMe[i].departmentList.indexOf(orgid) < 0) continue;
                    x.listWarehousePriv.push(host.listConfigPrivilegeOfMe[i].taskid);
                }
                var items = contentModule.getWarehousesListSelectMenu(x);
                warehouseElt.domElt.items = items;
            }
        }
        else {
            warehouseElt.domElt.items = contentModule.getWarehousesListSelectMenu(host);
        }
    });
    warehouseElt.domElt.on("change", function(){
        if (systemconfig.privSystem >= 2) return;
        var warehouseid = warehouseElt.domElt.value;
        if (warehouseid > 0){
            var x = {
                database: {
                    orgs: host.database.orgs,
                    employees: host.database.employees
                }
            };
            x.orgViewDic = {};
            x.employeeEditDic = {};
            var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
            var k;
            for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
                if (host.listConfigPrivilegeOfMe[i].taskid != warehouseid) continue;
                for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
                    x.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
                    k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
                    host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                        x.employeeEditDic[eid] = true;
                    });
                }
                k = orgsDic[host.listConfigPrivilegeOfMe[i].content.orgid];
                if (k >= 0){
                    while (host.database.orgs.items[k].parentid > 0){
                        x.orgViewDic[host.database.orgs.items[k].parentid] = true;
                        k = orgsDic[host.database.orgs.items[k].parentid];
                    }
                }
            }
            console.log(x.orgViewDic, x.employeeEditDic);
            employeeElt.domElt.items = contentModule.getMemberOfEmployeeSelectMenu(x);
        }
        else {
            employeeElt.domElt.items = contentModule.getMemberOfEmployeeSelectMenu(host);
        }
    });
};

contentModule.makePrivilegesProjectsConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeEditDic = {};
    host.employeeViewDic = {};
    if (systemconfig.privSystem >= 2) {
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
            host.employeeViewDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.employeeViewDic[host.employeeOfMe[0]] = true;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.project_setting){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
};

contentModule.makePrivilegesViewRequest = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.employeeViewDic = {};
    if (systemconfig.privSystem >= 2) {
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeViewDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.view_request){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                });
            }
        }
    }
};

contentModule.makePrivilegesContactConfigs = function(host){
    host.employeeEditContactDic = {};
    if (systemconfig.privSystem >= 2){
        return;
    };
    host.employeeEditContactDic = {};
    if (host.employeeOfMe.length == 0) return;
    host.employeeEditContactDic[host.employeeOfMe[0]] = true;
    host.listConfigPrivilegeOfMe = [];
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.edit_employees_contacts){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeEditContactDic[eid] = true;
                });
            }
        }
    }
};

contentModule.makePrivilegesViewEditOrgEmployee = function(host){
    host.employeeEditDic = {};
    host.employeeViewDic = {};
    host.orgViewDic = {};
    host.orgEditDic = {};
    if (systemconfig.privSystem >= 2) {
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeEditDic[host.database.employees.items[i].id] = true;
            host.employeeViewDic[host.database.employees.items[i].id] = true;
        }
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
            host.orgEditDic[host.database.orgs.items[i].id] = true;
        }
        return;
    };
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var listAuthorityOrg = hr.orgs.getAuthorityList();
    var listAuthorityWarehouse = hr.warehouses.getAuthorityList();
    if (host.employeeOfMe.length == 0) return;
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    var listConfigPrivilegeOrgOfMe = [];
    host.database.config_orgs_privileges.items.forEach(function(item){
        for (var i = 0; i < listAuthorityOrg.length; i++){
            if (item.content[listAuthorityOrg[i].priv]){
                if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                    listConfigPrivilegeOrgOfMe.push(item);
                }
                else {
                    if (item.content.employee_groups.indexOf(0) >= 0){
                        if (host.groupOfMe.length > 0) listConfigPrivilegeOrgOfMe.push(item);
                    }
                    else {
                        for (var i = 0; i < item.content.employee_groups.length; i++){
                            if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                                listConfigPrivilegeOrgOfMe.push(item);
                                break;
                            }
                        }
                    }
                }
                break;
            }
        }
    });
    for (var i = 0; i < listConfigPrivilegeOrgOfMe.length; i++){
        listConfigPrivilegeOrgOfMe[i].departmentList = [];
        if (listConfigPrivilegeOrgOfMe[i].taskdetails == 1){
            listConfigPrivilegeOrgOfMe[i].departmentList.push(listConfigPrivilegeOrgOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(listConfigPrivilegeOrgOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(listConfigPrivilegeOrgOfMe[i].departmentList, dIndex);
        }
    }
    var k;
    for (var i = 0; i < listConfigPrivilegeOrgOfMe.length; i++){
        k = orgsDic[listConfigPrivilegeOrgOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
        for (var j = 0; j < listConfigPrivilegeOrgOfMe[i].departmentList.length; j++){
            host.orgViewDic[listConfigPrivilegeOrgOfMe[i].departmentList[j]] = true;
            host.orgEditDic[listConfigPrivilegeOrgOfMe[i].departmentList[j]] = true;
            k = orgsDic[listConfigPrivilegeOrgOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeEditDic[eid] = true;
                    host.employeeViewDic[eid] = true;
                });
            }
        }
    }
    var listConfigPrivilegeWarehouseOfMe = [];
    host.database.config_warehouses_privileges.items.forEach(function(item){
        for (var i = 0; i < listAuthorityWarehouse.length; i++){
            if (item.content[listAuthorityWarehouse[i].priv]){
                if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                    listConfigPrivilegeWarehouseOfMe.push(item);
                }
                else {
                    if (item.content.employee_groups.indexOf(0) >= 0){
                        if (host.groupOfMe.length > 0) listConfigPrivilegeWarehouseOfMe.push(item);
                    }
                    else {
                        for (var i = 0; i < item.content.employee_groups.length; i++){
                            if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                                listConfigPrivilegeWarehouseOfMe.push(item);
                                break;
                            }
                        }
                    }
                }
                break;
            }
        }
    });
    for (var i = 0; i < listConfigPrivilegeWarehouseOfMe.length; i++){
        listConfigPrivilegeWarehouseOfMe[i].departmentList = [];
        if (listConfigPrivilegeWarehouseOfMe[i].content.level == 1){
            listConfigPrivilegeWarehouseOfMe[i].departmentList.push(listConfigPrivilegeWarehouseOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(listConfigPrivilegeWarehouseOfMe[i].content.orgid);
            if (dIndex >= 0) getDepartmentList(listConfigPrivilegeWarehouseOfMe[i].departmentList, dIndex);
        }
    }
    for (var i = 0; i < listConfigPrivilegeWarehouseOfMe.length; i++){
        k = orgsDic[listConfigPrivilegeWarehouseOfMe[i].content.orgid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
        for (var j = 0; j < listConfigPrivilegeWarehouseOfMe[i].departmentList.length; j++){
            host.orgViewDic[listConfigPrivilegeWarehouseOfMe[i].departmentList[j]] = true;
            host.orgEditDic[listConfigPrivilegeWarehouseOfMe[i].departmentList[j]] = true;
            k = orgsDic[listConfigPrivilegeWarehouseOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeEditDic[eid] = true;
                    host.employeeViewDic[eid] = true;
                });
            }
        }
    }
    host.employeeEditDic[host.employeeOfMe[0]] = true;
    host.employeeViewDic[host.employeeOfMe[0]] = true;
    var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
    var pid = host.database.employees.items[eIndex].orgid;
    host.orgViewDic[pid] = true;
    var oIndex = host.database.orgs.getIndex(pid);
    while (host.database.orgs.items[oIndex].parentid > 0) {
        pid = host.database.orgs.items[oIndex].parentid;
        host.orgViewDic[pid] = true;
        oIndex = host.database.orgs.getIndex(pid);
    }
};

contentModule.makePrivilegeViewPolicy = function(host, type){
    var listConfigPrivilegeOfMe = [];
    var policyHasList = {
        bonus: true,
        benefit: true,
        allowance: true,
        punishment: true,
        other_liability: true
    };
    host.database.config_orgs_privileges.items.forEach(function(item){
        if (item.content.human_resource_policy || (policyHasList[type] && (item.content.view_list || item.edit_list))){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    host.privViewAll = false;
    if (listConfigPrivilegeOfMe.length > 0) host.privViewAll = true;
};

contentModule.getPrivViewPolicy = function(host, type, id){
    for (var i = 0; i < host.database.employee_policies.items.length; i++){
        if (host.database.employee_policies.items[i].type != type) continue;
        if (host.database.employee_policies.items[i].employeeid != host.employeeOfMe[0]) continue;
        if (host.database.employee_policies.items[i].policyid != id) continue;
        return true;
    }
    var listPolicyApprover = {
        advance_payment: true,
        late_early_checkin: true,
        leave: true
    };
    if (listPolicyApprover[type]){
        for (var i = 0; i < host.database.policies_approvers.items.length; i++){
            if (host.database.policies_approvers.items[i].type != type) continue;
            if (host.database.policies_approvers.items[i].employeeid != host.employeeOfMe[0]) continue;
            if (host.database.policies_approvers.items[i].policyid != id) continue;
            return true;
        }
        if (host.directSubOfMe.length > 0){
            var pIndex = host.database[type + "_policies"].getIndex(id);
            if (pIndex >= 0 && host.database[type + "_policies"].items[pIndex].direct_manager_approves_first){
                for (var i = 0; i < host.database.employee_policies.items.length; i++){
                    if (host.database.employee_policies.items[i].type != type) continue;
                    if (host.database.employee_policies.items[i].policyid != id) continue;
                    if (host.directSubOfMe.indexOf(host.database.employee_policies.items[i].employeeid) < 0) continue;
                    return true;
                }
            }
        }
    }
    return false;
};

contentModule.makePrivilegesOnboardingConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeViewDic[host.database.employees.items[i].id] = true;
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.handle_onboarding){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.privAdd = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeViewDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.makePrivilegesOffboardingConfigs = function(host){
    host.listConfigPrivilegeOfMe = [];
    host.orgViewDic = {};
    host.employeeViewDic = {};
    host.employeeEditDic = {};
    if (systemconfig.privSystem >= 2) {
        host.privAdd = true;
        for (var i = 0; i < host.database.orgs.items.length; i++){
            host.orgViewDic[host.database.orgs.items[i].id] = true;
        }
        for (var i = 0; i < host.database.employees.items.length; i++){
            host.employeeViewDic[host.database.employees.items[i].id] = true;
            host.employeeEditDic[host.database.employees.items[i].id] = true;
        }
        return;
    };
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.handle_offboarding){
            if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
                host.listConfigPrivilegeOfMe.push(item);
            }
            else {
                if (item.content.employee_groups.indexOf(0) >= 0){
                    if (host.groupOfMe.length > 0) host.listConfigPrivilegeOfMe.push(item);
                }
                else {
                    for (var i = 0; i < item.content.employee_groups.length; i++){
                        if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                            host.listConfigPrivilegeOfMe.push(item);
                            break;
                        }
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.listConfigPrivilegeOfMe[i].departmentList = [];
        if (host.listConfigPrivilegeOfMe[i].taskdetails == 1){
            host.listConfigPrivilegeOfMe[i].departmentList.push(host.listConfigPrivilegeOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(host.listConfigPrivilegeOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(host.listConfigPrivilegeOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var k;
    for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
        host.privAdd = true;
        for (var j = 0; j < host.listConfigPrivilegeOfMe[i].departmentList.length; j++){
            host.orgViewDic[host.listConfigPrivilegeOfMe[i].departmentList[j]] = true;
            k = orgsDic[host.listConfigPrivilegeOfMe[i].departmentList[j]];
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    host.employeeViewDic[eid] = true;
                    host.employeeEditDic[eid] = true;
                });
            }
        }
        k = orgsDic[host.listConfigPrivilegeOfMe[i].taskid];
        if (k >= 0){
            while (host.database.orgs.items[k].parentid > 0){
                host.orgViewDic[host.database.orgs.items[k].parentid] = true;
                k = orgsDic[host.database.orgs.items[k].parentid];
            }
        }
    }
    if (host.employeeOfMe.length > 0){
        host.employeeViewDic[host.employeeOfMe[0]] = true;
        var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
        var pid = host.database.employees.items[eIndex].orgid;
        host.orgViewDic[pid] = true;
        var oIndex = host.database.orgs.getIndex(pid);
        while (host.database.orgs.items[oIndex].parentid > 0) {
            pid = host.database.orgs.items[oIndex].parentid;
            host.orgViewDic[pid] = true;
            oIndex = host.database.orgs.getIndex(pid);
        }
    }
};

contentModule.expToTokenArray = function(exp){
    var res = [], l = 0;
    for (var i = 0; i < exp.length; i++){
        res.push({
            type: exp[i].type,
            content: exp[i].value
        });
        l = exp[i].value.length + 1;
    }
};

contentModule.makePrivilegeViewWorkFlow = function(host){
    if (systemconfig.privSystem >= 2 || data_module.admin_rights_of_me.work_flows){
        for (var i = 0; i < host.database.work_flows.items.length; i++){
            host.database.work_flows.items[i].privView = true;
        }
        return;
    }
    if (host.employeeOfMe.length == 0) return;
    contentModule.makeOrgsIndex(host);
    contentModule.makeEmployeeData(host);
    contentModule.makeEmployeesIndex(host);
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var empOrgMeDic = {};
    empOrgMeDic[host.employeeOfMe[0]];
    var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
    var orgid = host.database.employees.items[eIndex].orgid;
    while (orgid > 0) {
        empOrgMeDic[orgid] = true;
        var oIndex = orgsDic[orgid];
        if (oIndex >= 0){
            orgid = host.database.orgs.items[oIndex].parentid;
        }
        else {
            break;
        }
    }
    var work_flowsDic = contentModule.makeDictionaryIndex(host.database.work_flows.items);
    var k;
    for (var i = 0; i < host.database.work_flow_members.items.length; i++){
        if (host.database.work_flow_members.items[i].orgid > 0){
            if (empOrgMeDic[host.database.work_flow_members.items[i].orgid]){
                k = work_flowsDic[host.database.work_flow_members.items[i].work_flowid];
                if (k >= 0) host.database.work_flows.items[k].privView = true;
            }
        }
        else {
            if (-host.database.work_flow_members.items[i].orgid == host.employeeOfMe[0]){
                k = work_flowsDic[host.database.work_flow_members.items[i].work_flowid];
                if (k >= 0) host.database.work_flows.items[k].privView = true;
            }
        }
    }
    for (var i = 0; i < host.database.work_flow_admin_privileges.items.length; i++){
        if (host.database.work_flow_admin_privileges.items[i].employeeid == host.employeeOfMe[0]){
            k = work_flowsDic[host.database.work_flow_admin_privileges.items[i].work_flowid];
            if (k >= 0) host.database.work_flows.items[k].privView = true;
        }
    }
};

contentModule.makePrivilegeObjects = function(host){
    if (host.employeeOfMe.length == 0) return;
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    host.empOrgMeDic = {};
    var eIndex = host.database.employees.getIndex(host.employeeOfMe[0]);
    var orgid = host.database.employees.items[eIndex].orgid;
    while (orgid > 0) {
        host.empOrgMeDic[orgid] = true;
        var oIndex = orgsDic[orgid];
        if (oIndex >= 0){
            orgid = host.database.orgs.items[oIndex].parentid;
        }
        else {
            break;
        }
    }
    if (systemconfig.privSystem >= 2){
        for (var j = 0; j < host.database.objects.items.length; j++){
            host.database.objects.items[j].privEdit = true;
            host.database.objects.items[j].privView = true;
        }
        return;
    }
    for (var i = 0; i < host.database.work_flow_admin_privileges.items.length; i++){
        if (host.database.work_flow_admin_privileges.items[i].employeeid == host.employeeOfMe[0]){
            for (var j = 0; j < host.database.objects.items.length; j++){
                if (!host.database.objects.items[j].closed) host.database.objects.items[j].privEdit = true;
                host.database.objects.items[j].privView = true;
            }
            return;
        }
    }
    for (var i = 0; i < host.database.objects.items.length; i++){
        if (host.database.objects.items[i].assign_to == host.employeeOfMe[0]){
            if (!host.database.objects.items[i].closed) host.database.objects.items[i].privEdit = true;
            host.database.objects.items[i].privView = true;
        }
        else {
            host.database.objects.items[i].privEdit = false;
            host.database.objects.items[i].privView = false;
        }
    }
    var objectsDic = contentModule.makeDictionaryIndex(host.database.objects.items);
    var k;
    for (var i = 0; i < host.database.object_permissions.items.length; i++){
        if (host.database.object_permissions.items[i].orgid > 0){
            if (host.empOrgMeDic[host.database.object_permissions.items[i].orgid]){
                k = objectsDic[host.database.object_permissions.items[i].objectid];
                if (k >= 0){
                    if (host.database.object_permissions.items[i].priv == "edit"){
                        if (!host.database.objects.items[k].closed) host.database.objects.items[k].privEdit = true;
                    }
                    host.database.objects.items[k].privView = true;
                }
            }
        }
        else {
            if (-host.database.object_permissions.items[i].orgid == host.employeeOfMe[0]){
                k = objectsDic[host.database.object_permissions.items[i].objectid];
                if (k >= 0){
                    if (host.database.object_permissions.items[i].priv == "edit"){
                        if (!host.database.objects.items[k].closed) host.database.objects.items[k].privEdit = true;
                    }
                    host.database.objects.items[k].privView = true;
                }
            }
        }
    }
};

contentModule.makeUserEmployeeName = function(host){
    var usersDic = {};
    for (var i = 0; i < host.database.users.items.length; i++){
        usersDic[host.database.users.items[i].homeid] = i;
    }
    var k;
    for (var i = 0; i < host.database.employees.items.length; i++){
        k = usersDic[host.database.employees.items[i].userid];
        if (k >= 0){
            host.database.users.items[k].fullname = host.database.employees.items[i].fullname;
        }
    }
};

contentModule.createCommentPage = function(host){
    host.tagMap = {};
    for (var i = 0; i < host.database.users.items.length; i++){
        host.tagMap[host.database.users.items[i].homeid] = host.database.users.items[i].fullname;
    }
    var readComment = function(id){
        if (id > 0){
            var index = host.database.comment_notifications.getIndex(id);
            if (host.database.comment_notifications.items[index].seen) return;
        }
        FormClass.api_call({
            url: "hr_seen_comment_notification.php",
            params: [
                {name: "id", value: id}
            ],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        if (id > 0){
                            var index = host.database.comment_notifications.getIndex(id);
                            host.database.comment_notifications.items[index].seen = 1;
                            inputidboxes[id].unread = false;
                            inputidboxes[id].quickmenu.props.items = getQuickmenuItemsList(host.database.comment_notifications.items[index]);
                        }
                        else {
                            host.database.comment_notifications.items.forEach(function(item){
                                item.seen = 1;
                                inputidboxes[item.id].unread = false;
                                inputidboxes[item.id].quickmenu.props.items = getQuickmenuItemsList(item);
                            });
                        }
                        if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(1001, 'counter', 0);
                        else hr.mCommentPage.counter = 0;
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    };
    var unReadComment = function(id){
        if (id > 0){
            var index = host.database.comment_notifications.getIndex(id);
            if (!host.database.comment_notifications.items[index].seen) return;
        }
        FormClass.api_call({
            url: "hr_unread_comment_notification.php",
            params: [
                {name: "id", value: id}
            ],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        if (id > 0){
                            var index = host.database.comment_notifications.getIndex(id);
                            host.database.comment_notifications.items[index].seen = 0;
                            inputidboxes[id].unread = true;
                            inputidboxes[id].quickmenu.props.items = getQuickmenuItemsList(host.database.comment_notifications.items[index]);
                        }
                        else {
                            // TODO:
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    };
    var removeComment = function(id){
        var index = host.database.comment_notifications.getIndex(id);
        if (index < 0){
            inputidboxes[id].selfRemove();
            return;
        }
        FormClass.api_call({
            url: "hr_remove_comment_notification.php",
            params: [
                {name: "id", value: id}
            ],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        if (id > 0){
                            var index = host.database.comment_notifications.getIndex(id);
                            if (!host.database.comment_notifications.items[index].seen){
                                if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(1001, 'counter', hr.menu.mobileTabbar.getItem(1001).counter - 1);
                                else hr.mCommentPage.counter = hr.mCommentPage.counter - 1;
                            }
                            host.database.comment_notifications.items.splice(index, 1);
                            inputidboxes[id].selfRemove();
                        }
                        else {
                            // TODO:
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    };
    var turnOffComment = function(item){
        FormClass.api_call({
            url: "hr_turn_off_comment_notifications.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(item)}],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        //// TODO:
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    };
    var makeData = function(items){
        return new Promise(function(resolve, reject){
            var listPromise = [];
            items.forEach(function(item){
                if (commentInfoByTablename[item.tablename] && !commentInfoByTablename[item.tablename].itemsList){
                    commentInfoByTablename[item.tablename].itemsList = [];
                    listPromise.push(new Promise(function(rs, rj){
                        contentModule.loadListPrimaryTypeEnum(commentInfoByTablename[item.tablename].datatype).then(function(list){
                            if (list.length > 0) list[0].text = "";
                            commentInfoByTablename[item.tablename].itemsList = list;
                            rs();
                        });
                    }));
                }
            });
            if (listPromise.length > 0){
                Promise.all(listPromise).then(function(){
                    resolve();
                });
            }
            else {
                resolve();
            }
        });
    };
    var getQuickmenuItemsList = function(item){
        var res = [];
        if (item.seen){
            res.push({
                text: LanguageModule.text("txt_mark_as_unread"),
                extendClasses: "bsc-quickmenu",
                icon: {
                    tag: "i",
                    class: ["mdi", "mdi-check"]
                },
                cmd: function(){
                    unReadComment(item.id);
                }
            });
        }
        else {
            res.push({
                text: LanguageModule.text("txt_mark_as_read"),
                extendClasses: "bsc-quickmenu",
                icon: {
                    tag: "i",
                    class: ["mdi", "mdi-check"]
                },
                cmd: function(){
                    readComment(item.id);
                }
            });
        }
        res.push({
            text: LanguageModule.text("txt_remove_this_notification"),
            extendClasses: "bsc-quickmenu red",
            icon: {
                tag: "i",
                class: ["mdi", "mdi-delete"]
            },
            cmd: function(){
                removeComment(item.id);
            }
        });
        res.push({
            text: LanguageModule.text("txt_turn_off_notifications"),
            extendClasses: "bsc-quickmenu",
            icon: {
                tag: "i",
                class: ["mdi", "mdi-message-off-outline"]
            },
            cmd: function(){
                turnOffComment(item);
            }
        });
        return res;
    };
    var getCommentItem = function(item){
        if (!commentInfoByTablename[item.tablename]) return;
        item.content = EncodingClass.string.toVariable(item.content);
        var avatarSrc = "", textT = DOMElement.div({});
        var uIndex = host.database.users.getByhomeid(item.content[0].userid);
        if (uIndex >= 0){
            textT.appendChild(DOMElement.span({text: host.database.users.items[uIndex].fullname}));
            avatarSrc = host.database.users.items[uIndex].avatarSrc;
        }
        if (item.tag){
            textT.appendChild(DOMElement.span({text: " đã nhắc đến bạn trong một phản hồi"}));
        }
        else {
            var commentText = "";
            if (item.content[item.content.length - 1].content_type == "text"){
                commentText = item.content[item.content.length - 1].content;
            }
            if ((commentText != "" && item.content.length > 2) || (commentText == "" && item.content.length > 1)){
                var xx;
                if (commentText != ""){
                    xx = item.content.length - 1;
                }
                else {
                    xx = item.content.length;
                }
                textT.appendChild(DOMElement.span({text: " đính kèm "}));
                textT.appendChild(DOMElement.span({
                    attrs: {style: {color: "var(--a-color)"}},
                    text: xx
                }));
                textT.appendChild(DOMElement.span({text: " file"}));
                if (commentText != "") textT.appendChild(DOMElement.span({text: " và"}));
            }
            else if (item.content[0].content_type != "text"){
                textT.appendChild(DOMElement.span({text: " đính kèm file " + '"'}));
                textT.appendChild(DOMElement.span({
                    attrs: {style: {color: "var(--a-color)"}},
                    text: item.content[0].content
                }));
                textT.appendChild(DOMElement.span({text: '"'}));
            }
            if (commentText.length > 0){
                textT.appendChild(DOMElement.span({text: " phản hồi " + '"'}));
                var aobjs = absol.parseMessage(commentText.trim(), {tagMap: host.tagMap, lengthLimit: 100, inline: true});
                aobjs.forEach(function(aobj){
                    if (aobj.tag == 'a'){
                        aobj.attr = aobj.attr || {};
                        aobj.attr.target = '_blank';// mở tab mới
                        aobj.style = aobj.style ||{};
                        aobj.style.cursor =  "pointer";
                        aobj.style.textDecoration =  "underline";
                    }
                });
                var texts = aobjs.map(function(aobj){
                    return absol._(aobj);// chuyển qua dom object cho giống code cũ
                });
                texts.forEach(function(textss){
                    textT.appendChild(DOMElement.span({
                        attrs: {style: {color: "var(--a-color)"}},
                        children: [textss]
                    }));
                });
                textT.appendChild(DOMElement.span({text: '"'}));
            }
        }
        textT.appendChild(DOMElement.span({text: " ở "}));
        var ld = new absol.ListDictionary(commentInfoByTablename[item.tablename].itemsList);
        var x = ld.getItemByValue(item.taskid);
        if (!x) return;
        textT.appendChild(DOMElement.span({text: commentInfoByTablename[item.tablename].name.toLowerCase() + " " + '"'}));
        textT.appendChild(DOMElement.span({
            attrs: {style: {color: "var(--a-color)"}},
            text: x.text
        }));
        textT.appendChild(DOMElement.span({text: '"'}));
        var itemsList = getQuickmenuItemsList(item);
        inputidboxes[item.id] = absol._({
            tag: 'kvcommentitem',
            style: {
                paddingTop: "var(--control-verticle-distance-1)",
                paddingBottom: "var(--control-verticle-distance-1)"
            },
            props: {
                text: textT,
                unread: !item.seen,
                time: item.createdtime,
                avatar: avatarSrc,
                quickmenu: {
                    props: {
                        items: itemsList
                    },
                    onSelect: function (item) {
                        item.cmd();
                    }
                }
            },
            on: {
                click: function(){
                    if (this.unread) readComment(item.id);
                    commentInfoByTablename[item.tablename].open(item.taskid);
                }
            }
        });
        return inputidboxes[item.id];
    };
    contentModule.makeEmployeeData(host);
    contentModule.makeUserEmployeeName(host);
    var commentInfoByTablename = contentModule.getCommentInfoByTablename();
    var comment_items_list = DOMElement.div({
        attrs: {
            style: {
                overflowX: "hidden",
                width: "100%"
            }
        }
    });
    var comment_ctn, comment_items_list_ctn;
    if (hr.isMobile){
        comment_items_list_ctn = DOMElement.div({
            attrs: {
                className: "hr-comment-items-list-ctn mobile"
            },
            children: [comment_items_list]
        });
        var header = absol.buildDom({
            tag: 'mheaderbar',
            props: {
                actionIcon: DOMElement.i({
                    attrs: {
                        className: "material-icons"
                    },
                    text: "arrow_back_ios"
                }),
                title: LanguageModule.text("txt_comment"),
                commands: [{
                    icon:  DOMElement.i({
                        attrs: {
                            className: "material-icons"
                        },
                        text: "done_all"
                    }),
                    cmd: function(){
                        readComment(0);
                    }
                }]
            },
            on: {
                action: function(){
                    hr.menu.loadPage(1000);
                },
                command: function(event){
                    event.commandItem.cmd();
                }
            }
        });
        comment_ctn = absol.buildDom({
            tag: 'tabframe',
            style: {
                height: "100%"
            },
            child:[
                header,
                DOMElement.div({
                    attrs: {
                        className: "card-mobile-content-no-padding"
                    },
                    children: [
                        comment_items_list_ctn
                    ]
                })
            ]
        });
    }
    else {
        comment_items_list_ctn = DOMElement.div({
            attrs: {
                className: "hr-comment-items-list-ctn"
            },
            children: [comment_items_list]
        });
        var readAllElt = DOMElement.div({
            attrs: {
                className: "hr_noti-center-read-all"
            },
            children: [DOMElement.span({
                attrs: {
                    style: {
                        cursor: "pointer"
                    },
                    onclick: function(){
                        readComment(0);
                    }
                },
                text: LanguageModule.text("txt_read_all")
            })]
        });
        comment_ctn = DOMElement.div({
            attrs: {
                style: {
                    height: "100%",
                    width: "100%"
                }
            },
            children: [
                readAllElt,
                comment_items_list_ctn
            ]
        });
    }
    var inputidboxes = {};
    makeData(host.database.comment_notifications.items).then(function(){
        host.database.comment_notifications.items.forEach(function(item){
            var x = getCommentItem(item);
            if (x) comment_items_list.appendChild(x);
        });
    });
    comment_items_list_ctn.addEventListener("scroll", function(){
        if (comment_items_list_ctn.scrollTop + comment_items_list_ctn.offsetHeight >= comment_items_list_ctn.scrollHeight){
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "load_old_comment_notifications"},
                    {name: "startIndex", value: host.database.comment_notifications.items.length}
                ],
                func: function(success, message){
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            makeData(st.comment_notifications).then(function(){
                                st.comment_notifications.forEach(function(item){
                                    var x = getCommentItem(item);
                                    if (x) comment_items_list.appendChild(x);
                                });
                            });
                            host.database.comment_notifications.items = host.database.comment_notifications.items.concat(st.comment_notifications);
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        }
    });
    DOMElement.removeAllChildren(host.holder);
    host.holder.appendChild(comment_ctn);
    contentModule.shareMessageReceiver.on('comment', function (messageContent){
        if (messageContent.userid == systemconfig.userid) return;
        if (messageContent.type == "add"){
            messageContent.userReceiveNotiList.forEach(function(item){
                if (item.userid == systemconfig.userid){
                    makeData([item]).then(function(){
                        item.unread = true;
                        var x = getCommentItem(item);
                        if (x){
                            if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(1001, 'counter', hr.menu.mobileTabbar.getItem(1001).counter + 1);
                            else hr.mCommentPage.counter = hr.mCommentPage.counter + 1;
                            comment_items_list.insertBefore(x, comment_items_list.firstChild);
                        }
                    });
                }
            });
        }
        else if (messageContent.type == "tag"){
            messageContent.usertagList.forEach(function(item){
                if (item.userid == systemconfig.userid){
                    makeData([item]).then(function(){
                        item.unread = true;
                        var x = getCommentItem(item);
                        if (x){
                            if (hr.isMobile) hr.menu.mobileTabbar.modifyItem(1001, 'counter', hr.menu.mobileTabbar.getItem(1001).counter + 1);
                            else hr.mCommentPage.counter = hr.mCommentPage.counter + 1;
                            comment_items_list.insertBefore(x, comment_items_list.firstChild);
                        }
                    });
                }
            });
        }
    });
};

contentModule.getCommentInfoByTablename = function(){
    return {
        objects: {
            name: LanguageModule.text("txt_object"),
            datatype: "member_of_objects",
            open: function(taskid){
                hr.menu.openObjectById(taskid, {scroll: "comments"});
            }
        },
        task: {
            name: LanguageModule.text("txt_task"),
            datatype: "member_of_task",
            open: function(taskid){
                hr.menu.openTaskById(taskid, {scroll: "comments"});
            }
        },
        meeting: {
            name: LanguageModule.text("txt_meeting"),
            datatype: "member_of_meeting",
            open: function(taskid){
                hr.menu.openMeetingById(taskid, {scroll: "comments"});
            }
        }
    };
};

contentModule.makeUserMarkerData = function(host, task, tablename){
    if (!tablename) tablename = task;
    for (var i = 0; i < host.database[task].items.length; i++){
        host.database[task].items[i].marked = false;
    }
    var dic = contentModule.makeDictionaryIndex(host.database[task].items);
    var k;
    for (var i = 0; i < host.database.user_marked.items.length; i++){
        if (host.database.user_marked.items[i].tablename != tablename) continue;
        k = dic[host.database.user_marked.items[i].taskid];
        if (k >= 0) host.database[task].items[k].marked = true;
    }
    var holderForSort = host.database[task].items.map(function(item){
        return {
            item: item,
            val: absol.string.nonAccentVietnamese(item.name.toLowerCase()),
            marked: item.marked
        }
    });
    holderForSort.sort(function(a, b){
        if (a.marked > b.marked) return -1;
        if (a.marked < b.marked) return 1;
        if (a.val < b.val) return -1;
        if (a.val > b.val) return 1;
        return 0;
    });
    host.database[task].items = holderForSort.map(function(holder){
        return holder.item;
    });
};

contentModule.markedFunc = function(host, params){
    return new Promise(function(resolve, reject){
        FormClass.api_call({
            url: "user_marked.php",
            params: [
                {name: "tablename", value: params.tablename},
                {name: "taskid", value: params.id},
                {name: "marked", value: params.marked? 1 : 0}
            ],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var id = parseInt(message.substr(2), 10);
                        if (params.marked){
                            host.database.user_marked.items.push({
                                id: id,
                                tablename: params.tablename,
                                taskid: params.id,
                                userid: systemconfig.userid
                            });
                        }
                        else {
                            for (var i = 0; i < host.database.user_marked.items.length; i++){
                                if (host.database.user_marked.items[i].tablename == params.tablename && host.database.user_marked.items[i].taskid == params.id){
                                    host.database.user_marked.items.splice(i, 1);
                                }
                            }
                        }
                        var index = host.database[params.task].getIndex(params.id);
                        host.database[params.task].items[index].marked = params.marked;
                        resolve();
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};


contentModule.makeUser_workflow_type_viewsDefault = function(host){
    for (var i = 0; i < host.database.work_flows.items.length; i++){
        if (hr.isMobile) host.database.work_flows.items[i].default_open = "table";
        else host.database.work_flows.items[i].default_open = "kanban";
    }
    var work_flowsDic = contentModule.makeDictionaryIndex(host.database.work_flows.items);
    var k;
    for (var i = 0; i < host.database.user_workflow_type_views.items.length; i++){
        k = work_flowsDic[host.database.user_workflow_type_views.items[i].work_flowid];
        if (k >= 0) host.database.work_flows.items[k].default_open = host.database.user_workflow_type_views.items[i].type_view;
    }
};

contentModule.makeAllEmployeesDic = function(){
    data_module.all_employeesDic = {};
    data_module.all_employees.items.sort(function(a, b){
        return b.id - a.id;
    });
    var dics = contentModule.makeDictionaryIndex(data_module.all_employees.items);
    var k;
    data_module.all_employees.items.forEach(function(item){
        if (item.obsoletedby != 0){
            k = dics[item.obsoletedby];
            if (k >= 0){
                if (data_module.all_employees.items[k].obsoletedby > 0){
                    item.obsoletedby = data_module.all_employees.items[k].obsoletedby;
                }
                data_module.all_employeesDic[item.id] = item.obsoletedby;
            }
        }
        else {
            data_module.all_employeesDic[item.id] = item.id;
        }
    });
};

contentModule.getGPSByString = function(str){
    var x = str.indexOf(",");
    var lat, lng;
    if (x > 0){
        lat = parseFloat(str.substr(0, x));
        lng = parseFloat(str.substr(x + 1));
        if (!lat || !lng) return null;
        return {
            lat: lat,
            lng: lng
        }
    }
    else {
        return null;
    }
};

contentModule.selectPartnerForm = function(host, params){
    return new Promise(function(resolve, reject){
        var redraw = function(){
            var ps = {
                database: host.database,
                data_container: host.data_container,
                form_config: host.form_config,
                user_column_configsDic: host.user_column_configsDic,
                func: {
                    ok: function(data){
                        console.log(data);
                        resolve(data);
                    }
                }
            };
            for (var x in params){
                ps[x] = params[x];
            };
            theme.formSelectPartner(ps);
        };
        if (host.database) {
            redraw();
        }
        else {
            host.database = {};
            var loadPartner = !data_module.partnerReady;
            ModalElement.show_loading();
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    //{name: "task", value: loadPartner? "partner_load_init": "partner_load_init_no_load_partner"}
                    {name: "task", value: "partner_load_init"}
                ],
                func: function(success, message){
                    ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var content = EncodingClass.string.toVariable(message.substr(2));
                            host.done = content.done;
                            delete content.done;
                            host.employeeOfMe = content.employeeOfMe;
                            delete content.employeeOfMe;
                            contentModule.makeDatabaseContent(host, content);
                            if (!loadPartner){
                                contentModule.makeDatabaseContent(host, {
                                    partner: EncodingClass.string.duplicate(data_module.partner.items),
                                    partner_class_links: EncodingClass.string.duplicate(data_module.partner_class_links.items),
                                    partner_class: EncodingClass.string.duplicate(data_module.partner_class.items)
                                });
                            }
                            contentModule.makeCitiesIndex(host);
                            contentModule.makePartnerData(host);
                            contentModule.makePartnerClassLinksData(host);
                            contentModule.makeUserMarkerData(host, "partner");
                            if (!loadPartner){
                                host.database.partner.items.sort(function(a, b) {
                                    if (b.marked > a.marked) return 1;
                                    if (b.marked < a.marked) return -1;
                                    return a.name - b.name;
                                });
                            }
                            host.form_config = contentModule.configVariable(host);
                            host.user_column_configsDic = contentModule.getUser_column_configsDic(host);
                            host.data_container = DOMElement.div({});
                            redraw();
                            data_module.loadPartnerFunc({
                                process: function (host) {
                                    return function (content) {
                                        var st = {
                                            partner: content.partner,
                                            partner_class_links: content.partner_class_links,
                                            done: (content.finished) ? 1 : 0
                                        };
                                        host.done = st.done;
                                        var x = {
                                            database: {}
                                        };
                                        contentModule.makeDatabaseContent(x, st);
                                        contentModule.makePartnerData(x);
                                        contentModule.makePartnerClassLinksData(x);
                                        host.data_container.insertData(x.database.partner.items);
                                        host.database.partner.items = host.database.partner.items.concat(x.database.partner.items);
                                        host.database.partner_class_links.items = host.database.partner.items.concat(x.database.partner_class_links.items);
                                    }
                                } (host),
                                sort: true
                            });
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        }
    });
};

contentModule.makeObjectPermissionData = function(host){
    if (!host.generalEmpForOrg){
        var getEmployeeDicForOrg = function(index){
            host.database.orgs.items[index].employeeDic = {};
            for (var i = 0; i < host.database.orgs.items[index].employeeIdList.length; i++){
                host.database.orgs.items[index].employeeDic[host.database.orgs.items[index].employeeIdList[i]] = true;
            }
            var k;
            for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
                k = getEmployeeDicForOrg(host.database.orgs.items[index].childIndexList[i]);
                for (var x in k){
                    host.database.orgs.items[index].employeeDic[x] = k[x];
                }
            }
            return host.database.orgs.items[index].employeeDic;
        };
        for (var i = 0; i < host.database.orgs.items.length; i++){
            if (host.database.orgs.items[i].parentid == 0){
                getEmployeeDicForOrg(i);
            }
        }
        host.generalEmpForOrg = true;
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var objectsDic = contentModule.makeDictionaryIndex(host.database.objects.items);
    for (var i = 0; i < host.database.objects.items.length; i++){
        host.database.objects.items[i].employeeRelatedDic = {};
        host.database.objects.items[i].employeeRelatedDic[host.database.objects.items[i].assign_to] = true;
    }
    var k;
    for (var i = 0; i < host.database.object_permissions.items.length; i++){
        if (host.database.object_permissions.items[i].orgid > 0){
            k = orgsDic[host.database.object_permissions.items[i].orgid];
            if (k >= 0){
                host.database.object_permissions.items[i].employeeDic = host.database.orgs.items[k].employeeDic;
            }
            else {
                host.database.object_permissions.items[i].employeeDic = {};
            }
        }
        else {
            host.database.object_permissions.items[i].employeeDic = {};
            host.database.object_permissions.items[i].employeeDic[-host.database.object_permissions.items[i].orgid] = true;
        }
        k = objectsDic[host.database.object_permissions.items[i].objectid];
        if (k >= 0){
            for (var x in host.database.object_permissions.items[i].employeeDic){
                host.database.objects.items[k].employeeRelatedDic[x] = host.database.object_permissions.items[i].employeeDic[x];
            }
        }
    }
};

contentModule.makeDocumentTemplatesProperties = function(host){
    var documentDic = contentModule.makeDictionaryIndex(host.database.document_templates.items);
    for (var i = 0; i < host.database.document_templates.items.length; i++){
        host.database.document_templates.items[i].properties = {};
    }
    var k, item;
    for (var i = 0; i < host.database.document_template_properties_links.items.length; i++){
        item = host.database.document_template_properties_links.items[i];
        k = documentDic[item.documentid];
        if (k !== undefined){
            host.database.document_templates.items[k].properties[item.property_groupid] = item.propertyid;
        }
    }
};

contentModule.getTypeList = function(){
    return new Promise(function(resolve, reject){
        if (data_module.pendingData.status == "success") {
            var res = [];
            for (var i = 0; i < data_module.typelists.items.length; i++){
                res.push(data_module.typelists.items[i].id);
            }
            resolve(res);
        }
        else {
            data_module.loadType_listsList().then(function(st){
                var host = {database: {}};
                contentModule.makeDatabaseContent(host, {typelists: st});
                var res = [];
                for (var i = 0; i < host.database.typelists.items.length; i++){
                    res.push(host.database.typelists.items[i].id);
                }
                resolve(res);
            });
        }
    });
};

contentModule.getTypeDescriptor = function(typeid){
    return new Promise(function(resolve, reject){
        var f1 = function(){
            var dic = contentModule.makeDictionaryIndex(host.database.typelists.items);
            var k = dic[typeid];
            if (k >= 0){
                var type = host.database.typelists.items[k].type;
                var type2 = host.database.typelists.items[k].type2;
                switch (type){
                    case "string":
                    case "note":
                    case "email_address":
                    case "phonenumber":
                    case "website":
                    case "gps":
                        resolve({type: 'string', displayName: host.database.typelists.items[k].name});
                        break;
                    case "number":
                    case "currency":
                        resolve({type: "number", displayName: host.database.typelists.items[k].name});
                        break;
                    case "date":
                        resolve({type: "date", displayName: host.database.typelists.items[k].name});
                        break;
                    case "datetime":
                        resolve({type: "datetime", displayName: host.database.typelists.items[k].name});
                        break;
                    case "boolean":
                        resolve({type: "bool", displayName: host.database.typelists.items[k].name});
                        break;
                    case "html":
                        resolve({type: "html", displayName: host.database.typelists.items[k].name});
                        break;
                    case "color_picker":
                        resolve({type: "color", displayName: host.database.typelists.items[k].name});
                        break;
                    case "any_file":
                        resolve({type: "file", displayName: host.database.typelists.items[k].name});
                        break;
                    case "image_file":
                        resolve({type: "image", displayName: host.database.typelists.items[k].name});
                        break;
                    case "files":
                        resolve({type: "file[]", displayName: host.database.typelists.items[k].name});
                        break;
                    case "array":
                        resolve({type: "array", of: host.database.typelists.items[k].content.typeof, displayName: host.database.typelists.items[k].name});
                        break;
                    case "treetable":
                        resolve({type: "treetable", of: host.database.typelists.items[k].content.typeof, displayName: host.database.typelists.items[k].name});
                        break;
                    default:
                        if (contentModule.listTypeSelectmenu.indexOf(type) >= 0){
                            if (type == "nation_city"){
                                resolve({type: "enum<pair>", displayName: host.database.typelists.items[k].name});
                            }
                            else {
                                resolve({type: "enum", displayName: host.database.typelists.items[k].name});
                            }
                        }
                        else if (contentModule.listTypeSelectbox.indexOf(type) >= 0){
                            resolve({type: "{enum}", displayName: host.database.typelists.items[k].name});
                        }
                        else if (type == "enum" || type == "extends_enum" || type2 == "enum"){
                            resolve({type: "enum", displayName: host.database.typelists.items[k].name});
                        }
                        else if (type == "enum_multi" || type == "extends_enum_multi" || type2 == "enum_multi"){
                            resolve({type: "{enum}", displayName: host.database.typelists.items[k].name});
                        }
                        else if (type == "structure" || type == "extends_structure" || type2 == "structure"){
                            var detailsList = [];
                            contentModule.getDetailsExtends(host, detailsList, typeid);
                            var properties = [];
                            for (var i = 0; i < detailsList.length; i++){
                                properties.push({
                                    type: detailsList[i].type,
                                    name: detailsList[i].localid,
                                    displayName: detailsList[i].name
                                });
                            }
                            resolve({type: "struct", properties: properties, displayName: host.database.typelists.items[k].name});
                        }
                        else {
                            resolve({type: "string", displayName: host.database.typelists.items[k].name});
                        }
                }
            }
            else {
                resolve(null);
            }
        };
        var host = {database: {}};
        if (data_module.pendingData.status == "success") {
            host.database.typelists = data_module.typelists;
            f1();
        }
        else {
            data_module.loadType_listsList().then(function(st){
                contentModule.makeDatabaseContent(host, {typelists: st});
                f1();
            });
        }
    });
};

contentModule.getEnumMembers = function(typeid){
    return new Promise(function(resolve, reject){

    });
};

contentModule.makeFunctionalMatrixsData = function(host){
    for (var i = 0; i < host.database.functional_matrixs.items.length; i++){
        host.database.functional_matrixs.items[i].listSub = [];
        host.database.functional_matrixs.items[i].listKpi = [];
    }
    var dic = contentModule.makeDictionaryIndex(host.database.functional_matrixs.items);
    var k;
    for (var i = 0; i < host.database.functional_matrix_subs.items.length; i++){
        k = dic[host.database.functional_matrix_subs.items[i].functionid];
        if (k >= 0){
            host.database.functional_matrixs.items[k].listSub.push(i);
        }
    }
    for (var i = 0; i < host.database.functional_matrix_kpis.items.length; i++){
        k = dic[host.database.functional_matrix_kpis.items[i].functionid];
        if (k >= 0){
            host.database.functional_matrixs.items[k].listKpi.push(i);
        }
    }
    for (var i = 0; i < host.database.functional_matrix_kpis.items.length; i++){
        host.database.functional_matrix_kpis.items[i].listSub = [];
    }
    dic = contentModule.makeDictionaryIndex(host.database.functional_matrix_kpis.items);
    for (var i = 0; i < host.database.functional_matrix_kpi_subs.items.length; i++){
        k = dic[host.database.functional_matrix_kpi_subs.items[i].kpiid];
        if (k >= 0){
            host.database.functional_matrix_kpis.items[k].listSub.push(i);
        }
    }
};

contentModule.makeDefaultData = function(host, typeid, typeContent, typeDict){
    var content;
    var dataType = typeDict[typeid].type;
    switch (dataType) {
        case 'structure':
            content = {}
            typeDict[typeid].content.details.forEach(function(elt){
                var t_data = contentModule.makeDefaultData(host, elt.type, elt, typeDict);
                content[elt.localid] = t_data;
            });
            break;
        case 'extends_structure':
            content = {}
            while (host.typeDict[typeid].type == "extends_structure"){
                typeDict[typeid].content.details.forEach(function(elt){
                    var t_data = contentModule.makeDefaultData(host, elt.type, elt, typeDict);
                    content[elt.localid] = t_data;
                });
                typeid = host.typeDict[typeid].content.typeof;
            }
            typeDict[typeid].content.details.forEach(function(elt){
                var t_data = contentModule.makeDefaultData(host, elt.type, elt, typeDict);
                content[elt.localid] = t_data;
            });
            break;
        case 'array':
            content = [];
            break;
        case 'string':
        case 'note':
        case 'email_address':
        case 'phonenumber':
        case 'website':
        case 'gps':
        case 'time':
            content = "";
            break;
        case 'nation_city':
            content = [0, 0];
            break;
        case 'currency':
        case 'number':
            content = 0;
            break;
        case 'datetime':
        case 'date':
        case 'month':
        case 'week':
            content = new Date(0);
            break;
        case 'boolean':
            content = false;
            break;
        case 'enum':
        case 'extends_enum':
            content = 0;
            break;
        case 'enum_multi':
        case 'extends_enum_multi':
            content = [];
            break;
        default:
            if (contentModule.listTypeSelectmenu.indexOf(dataType) >= 0){
                content = 0;
            }
            else if (contentModule.listTypeSelectbox.indexOf(dataType) >= 0) {
                content = [];
            }
            else {
                content = "";
            }
            break;
    }
    return content;
};

contentModule.makeAssign_employee_shiftsData = function(host){
    host.assign_employee_shiftsDic = {};
    host.database.assign_employee_shifts.items.forEach(function(item){
        if (!host.assign_employee_shiftsDic[item.employeeid]){
            host.assign_employee_shiftsDic[item.employeeid] = {};
            host.assign_employee_shiftsDic[item.employeeid][item.date_num] = [
                {
                    shiftid: item.shiftid,
                    time_in: item.time_in,
                    time_out: item.time_out
                }
            ];
        }
        else {
            if (host.assign_employee_shiftsDic[item.employeeid][item.date_num]){
                host.assign_employee_shiftsDic[item.employeeid][item.date_num].push({
                    shiftid: item.shiftid,
                    time_in: item.time_in,
                    time_out: item.time_out
                });
            }
            else {
                host.assign_employee_shiftsDic[item.employeeid][item.date_num] = [
                    {
                        shiftid: item.shiftid,
                        time_in: item.time_in,
                        time_out: item.time_out
                    }
                ];
            }
        }
    });
};

contentModule.getFontLevelList = function(){
    return [
        {value: 1, text: "1"},
        {value: 2, text: "2"},
        {value: 3, text: "3"},
        {value: 4, text: "4"}
    ]
};

contentModule.getPayRollCycleList = function(){
    return [
        {value: "month", text: LanguageModule.text("txt_month")},
        {value: "week", text: LanguageModule.text("txt_week")}
    ];
};

contentModule.getPayRollCycleText = function(cycle){
    var list = contentModule.getPayRollCycleList();
    for (var i = 0; i < list.length; i++){
        if (list[i].value == cycle) return list[i].text;
    }
    return "";
};

contentModule.getPayrollDateMonthList = function(){
    var list = [];
    for (var i = 1; i < 28; i++){
        list.push({value: i, text: i});
    }
    list.push({value: 0, text: LanguageModule.text("txt_last_date_of_month")});
    return list;
};

contentModule.getPayrollDateWeekList = function(){
    return [
        {value: 1, text: LanguageModule.text("txt_monday")},
        {value: 2, text: LanguageModule.text("txt_tuesday")},
        {value: 3, text: LanguageModule.text("txt_wednesday")},
        {value: 4, text: LanguageModule.text("txt_thursday")},
        {value: 5, text: LanguageModule.text("txt_friday")},
        {value: 6, text: LanguageModule.text("txt_saturday")},
        {value: 0, text: LanguageModule.text("txt_sunday")}
    ];
};

contentModule.getConfigBscDateWeekList = function(){
    return [
        {value: 0, text: LanguageModule.text("txt_monday")},
        {value: 1, text: LanguageModule.text("txt_tuesday")},
        {value: 2, text: LanguageModule.text("txt_wednesday")},
        {value: 3, text: LanguageModule.text("txt_thursday")},
        {value: 4, text: LanguageModule.text("txt_friday")},
        {value: 5, text: LanguageModule.text("txt_saturday")},
        {value: 6, text: LanguageModule.text("txt_sunday")}
    ];
};

contentModule.getPayrollDateViewMonth = function(payroll_date){
    var res = "";
    var list = contentModule.getPayrollDateMonthList();
    for (var i = 0; i < list.length; i++){
        if (list[i].value == payroll_date){
            res = list[i].text;
            break;
        }
    }
    if (payroll_date > 0) res = LanguageModule.text("txt_day") + " " + res;
    return res;
};

contentModule.getPayrollDateViewWeek = function(payroll_date){
    var res = "";
    var list = contentModule.getPayrollDateWeekList();
    for (var i = 0; i < list.length; i++){
        if (list[i].value == payroll_date){
            res = list[i].text;
            break;
        }
    }
    return res;
};

contentModule.getPayRollCycleView = function(host, cycleid){
    var res = "";
    var index = host.database.payroll_cycle.getIndex(cycleid);
    if (index < 0) return res;
    res += host.database.payroll_cycle.items[index].name;
    res += " (" + contentModule.getPayRollCycleText(host.database.payroll_cycle.items[index].cycle) + ", ";
    if (host.database.payroll_cycle.items[index].cycle == "month"){
        res += contentModule.getPayrollDateViewMonth(host.database.payroll_cycle.items[index].payroll_date);
    }
    else {
        res += contentModule.getPayrollDateViewWeek(host.database.payroll_cycle.items[index].payroll_date);
    }
    res += ")";
    return res;
};

contentModule.getApprovalPolicyNoDirect = function(host, params = {}, type = "edit"){
    var getApprovalMethod = function(value){
        var list = contentModule.getListApprovalMethod();
        for (var i = 0; i < list.length; i++){
            if (list[i].value == value) return list[i].text;
        }
        return "";
    };
    var orgEmpItems = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host);
    var getRowApprover = function(employeeid){
        var employee_select = absol.buildDom({
            tag: "selecttreeleafmenu",
            style: {
                display: "block",
                width: "100%"
            },
            props: {
                items: orgEmpItems,
                enableSearch: true,
                value: employeeid
            }
        });
        if (type == "view") employee_select.disabled = true;
        var cells = [];
        if (type == "edit") cells.push({
            style: {
                width: '30px',
                textAlign: 'center',
                fontSize: '25px'
            },
            class: 'as-drag-zone',
            child: 'span.mdi.mdi-drag'
        });
        cells.push({
            child: employee_select
        });
        if (type == "edit"){
            var deleteIcon = DOMElement.div({
                attrs: {
                    className: "card-icon-remove-cover",
                    onclick: function(){
                        var x = tableView.rowOf(row)
                        x.remove();
                    }
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "material-icons card-icon-remove"
                    },
                    text: "remove_circle"
                })]
            });
            cells.push({
                child: deleteIcon
            });
        }
        var row = {cells: cells};
        row.getValue = function(){
            var x = employee_select.value;
            if (x == 0){
                ModalElement.alert({
                    message: LanguageModule.text("txt_employee_is_null")
                });
                return;
            }
            return x;
        };
        return row;
    };
    var approval_method_select = absol.buildDom({
        tag: "selectmenu",
        style: {
            display: "block",
            width: "100%"
        },
        props: {
            items: contentModule.getListApprovalMethod(),
            disabled: type == "view"
        }
    });
    if (params.approval_method !== undefined) approval_method_select.value = params.approval_method;
    var data = [];
    if (params.approvers){
        for (var i = 0; i < params.approvers.length; i++){
            data.push(getRowApprover(params.approvers[i]));
        }
    }
    var header = [];
    if (type == "edit") header.push({});
    header.push({
        child:  absol.buildDom({text: LanguageModule.text("txt_employee")})
    });
    if (type == "edit") header.push({});
    var tableView = absol.buildDom({
        tag: "dynamictable",
        props: {
            adapter: {
               rowsPerPage: Infinity,
               data: {
                   head: {
                       rows: [
                           {
                               cells: header
                           }
                       ]
                   },
                   body: {
                       rows: data
                   }
               }
           }
        }
    });
    if (type == "view") tableView.classList.add("as-inline");
    var approvalElt = DOMElement.div({
        children: [
            DOMElement.table({
                data: [
                    [
                        {
                            attrs: {style: {lineHeight: "var(--control-height)"}},
                            text: LanguageModule.text("txt_approval_method")
                        },
                        {attrs: {style: {width: "var(--distance-between-title-value)"}}},
                        approval_method_select
                    ]
                ]
            }),
            DOMElement.div({attrs: {style: {height: "var(--control-verticle-distance-2)"}}}),
            DOMElement.div({
                children: [
                    DOMElement.span({text: LanguageModule.text("txt_approvers")}),
                    DOMElement.div({
                        attrs: {
                            className: "mk-table-wrapper-header-cmd",
                            style: {
                                visibility: (type == "view")? "hidden" : "visible"
                            },
                            onclick: function(){
                                tableView.addRow(getRowApprover(0));
                            }
                        },
                        text: LanguageModule.text("txt_add")
                    })
                ]
            }),
            DOMElement.div({attrs: {style: {height: "var(--control-verticle-distance-2)"}}}),
            DOMElement.div({
                attrs: {className: "cardsimpletableclass"},
                children: [tableView]
            })
        ]
    });
    approvalElt.getValue = function(){
        var approvers = [], value;
        var data = tableView.requireRows();
        var rowData;
        for (var i = 0; i < data.length; i++){
            rowData = data[i];
            value = rowData.data.getValue();
            if (!value) return;
            approvers.push(value);
        }
        if (approvers.length == 0){
            ModalElement.alert({
                message: LanguageModule.text("txt_approvers_is_null")
            });
            return;
        }
        var res = {
            approval_method: approval_method_select.value,
            approvers: approvers
        };
        return res;
    };
    return approvalElt;
};

contentModule.formAddPolicyHasApprovalNoDirect = function(host, params){
    var redraw = function(){
        var navItems = [
            {text: LanguageModule.text("txt_general_information")},
            {text: LanguageModule.text("txt_employee_apply")},
            {text: LanguageModule.text("txt_approval")}
        ];
        var vTimeline = absol.buildDom({
            tag: 'verticaltimeline',
            props: {
                items: navItems
            }
        });
        var formContainer = DOMElement.div({});
        var getValueFunction;
        contentModule.makeFormData({
            typeid: host.form_config[params.type + "_policies"].typeid,
            formid: host.form_config[params.type + "_policies"].input_form,
            formContainer: formContainer,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(formContainer.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        var generalInformationPageCtn = DOMElement.div({
            attrs: {
                className: 'kv-document-2-site-right kv-document-page'
            },
            children: [
                absol.buildDom({
                    class: 'kv-document-page-header',
                    child: [
                        {
                            tag: 'span',
                            class: 'kv-document-page-title',
                            child: { text: LanguageModule.text("txt_general_information") }
                        },

                        {
                            tag: 'button',
                            class: ['kv-document-transparent-btn', 'kv-document-page-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    ModalElement.close();
                                }
                            }
                        }
                    ]
                }),
                DOMElement.div({
                    attrs: {
                        className: 'kv-document-page-content'
                    },
                    children: [formContainer]
                }),
                absol.buildDom({
                    class: 'kv-document-page-footer',
                    child: [
                        DOMElement.div({attrs: {className: "kv-document-page-footer-left"}}),
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-right"},
                            children: [
                                theme.noneIconButton({
                                    className: "primary",
                                    text: LanguageModule.text("txt_next"),
                                    onclick: function(){
                                        var data = getValueFunction();
                                        console.log(data);
                                        if (!data) return;
                                        generalInformationPageCtn.style.display = "none";
                                        vTimeline.current = 1;
                                        employeeApplyPageCtn.style.display = "";
                                    }
                                }),
                                DOMElement.div({
                                    attrs: {
                                        className: "kv-document-link",
                                        onclick: function(){
                                            ModalElement.close();
                                        }
                                    },
                                    text: LanguageModule.text("txt_cancel")
                                })
                            ]
                        })
                    ]
                })
            ]
        });
        var orgEmpItems = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host);
        var department_employee_select = absol.buildDom({
            tag: "multichecktreemenu",
            style: {
                width: "100%"
            },
            props: {
                items: orgEmpItems,
                leafOnly: true,
                enableSearch: true
            }
        });
        var data = [
            [
                {
                    attrs: {style: {whiteSpace: "nowrap"}},
                    text: LanguageModule.text("txt_department_employee")
                },
                {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                department_employee_select
            ]
        ];
        var employeeApplyElt = DOMElement.table({
            data: data
        });
        employeeApplyElt.getValue = function(){
            return department_employee_select.values;
        };
        var employeeApplyPageCtn = DOMElement.div({
            attrs: {
                className: 'kv-document-2-site-right kv-document-page',
                style: {display: "none"}
            },
            children: [
                absol.buildDom({
                    class: 'kv-document-page-header',
                    child: [
                        {
                            tag: 'span',
                            class: 'kv-document-page-title',
                            child: { text: LanguageModule.text("txt_employee_apply") }
                        },
                        {
                            tag: 'button',
                            class: ['kv-document-transparent-btn', 'kv-document-page-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    ModalElement.close();
                                }
                            }
                        }
                    ]
                }),
                DOMElement.div({
                    attrs: {
                        className: 'kv-document-page-content'
                    },
                    children: [employeeApplyElt]
                }),
                absol.buildDom({
                    class: 'kv-document-page-footer',
                    child: [
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-left"},
                            children: [
                                theme.noneIconButton({
                                    text: LanguageModule.text("txt_back"),
                                    onclick: function(){
                                        employeeApplyPageCtn.style.display = "none";
                                        vTimeline.current = 0;
                                        generalInformationPageCtn.style.display = "";
                                    }
                                })
                            ]
                        }),
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-right"},
                            children: [
                                theme.noneIconButton({
                                    text: LanguageModule.text("txt_next"),
                                    onclick: function(){
                                        employeeApplyPageCtn.style.display = "none";
                                        vTimeline.current = 2;
                                        approvalPageCtn.style.display = "";
                                    }
                                })
                            ]
                        })
                    ]
                })
            ]
        });
        var approvalElt = contentModule.getApprovalPolicyNoDirect(host);
        var approvalPageCtn = DOMElement.div({
            attrs: {
                className: 'kv-document-2-site-right kv-document-page',
                style: {display: "none"}
            },
            children: [
                absol.buildDom({
                    class: 'kv-document-page-header',
                    child: [
                        {
                            tag: 'span',
                            class: 'kv-document-page-title',
                            child: { text: LanguageModule.text("txt_approval") }
                        },
                        {
                            tag: 'button',
                            class: ['kv-document-transparent-btn', 'kv-document-page-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    ModalElement.close();
                                }
                            }
                        }
                    ]
                }),
                DOMElement.div({
                    attrs: {
                        className: 'kv-document-page-content'
                    },
                    children: [approvalElt]
                }),
                absol.buildDom({
                    class: 'kv-document-page-footer',
                    child: [
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-left"},
                            children: [
                                theme.noneIconButton({
                                    text: LanguageModule.text("txt_back"),
                                    onclick: function(){
                                        approvalPageCtn.style.display = "none";
                                        vTimeline.current = 1;
                                        employeeApplyPageCtn.style.display = "";
                                    }
                                })
                            ]
                        }),
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-right"},
                            children: [
                                theme.noneIconButton({
                                    className: "primary",
                                    text: LanguageModule.text("txt_save"),
                                    onclick: function(){
                                        var approval = approvalElt.getValue();
                                        if (!approval) return;
                                        var data = {
                                            general_information: getValueFunction(),
                                            employee_apply: employeeApplyElt.getValue(),
                                            approval: approval
                                        };
                                        params.func.save(data).then(function(){
                                            ModalElement.close();
                                        });
                                    }
                                }),
                                DOMElement.div({
                                    attrs: {
                                        className: "kv-document-link",
                                        onclick: function(){
                                            ModalElement.close();
                                        }
                                    },
                                    text: LanguageModule.text("txt_cancel")
                                })
                            ]
                        })
                    ]
                })
            ]
        });
        ModalElement.show({
            bodycontent: absol.buildDom({
                class: 'kv-document-2-site',
                style: {
                    minWidth: "50vw",
                    height: "70vh"
                },
                child: [
                    {
                        class: 'kv-document-2-site-left',
                        child: [
                            {
                                class: 'kv-document-2-site-left-header',
                                child: [
                                    {
                                        tag: 'span',
                                        class: 'kv-document-2-site-left-header-text',
                                        child: { text: params.title }
                                    }
                                ]
                            },
                            vTimeline
                        ]
                    },
                    generalInformationPageCtn,
                    employeeApplyPageCtn,
                    approvalPageCtn
                ]
            })
        });
    };
    if (host.orgEmpLoaded){
        redraw();
    }
    else {
        data_module.loadEmployeeItemsPrivView().then(function(values){
            for (var x in values.database){
                host.database[x] = values.database[x];
            }
            delete  values.database;
            for (var x in values){
                host[x] = values[x];
            }
            host.orgEmpLoaded = true;
            redraw();
        });
    }
};

contentModule.formAddPolicyNoApproval = function(host, params){
    var redraw = function(){
        var navItems = [
            {text: LanguageModule.text("txt_general_information")},
            {text: LanguageModule.text("txt_employee_apply")}
        ];
        var vTimeline = absol.buildDom({
            tag: 'verticaltimeline',
            props: {
                items: navItems
            }
        });
        var formContainer = DOMElement.div({});
        var getValueFunction;
        contentModule.makeFormData({
            typeid: host.form_config[params.type + "_policies"].typeid,
            formid: host.form_config[params.type + "_policies"].input_form,
            formContainer: formContainer,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(formContainer.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        var generalInformationPageCtn = DOMElement.div({
            attrs: {
                className: 'kv-document-2-site-right kv-document-page'
            },
            children: [
                absol.buildDom({
                    class: 'kv-document-page-header',
                    child: [
                        {
                            tag: 'span',
                            class: 'kv-document-page-title',
                            child: { text: LanguageModule.text("txt_general_information") }
                        },

                        {
                            tag: 'button',
                            class: ['kv-document-transparent-btn', 'kv-document-page-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    ModalElement.close();
                                }
                            }
                        }
                    ]
                }),
                DOMElement.div({
                    attrs: {
                        className: 'kv-document-page-content'
                    },
                    children: [formContainer]
                }),
                absol.buildDom({
                    class: 'kv-document-page-footer',
                    child: [
                        DOMElement.div({attrs: {className: "kv-document-page-footer-left"}}),
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-right"},
                            children: [
                                theme.noneIconButton({
                                    className: "primary",
                                    text: LanguageModule.text("txt_next"),
                                    onclick: function(){
                                        var data = getValueFunction();
                                        if (!data) return;
                                        generalInformationPageCtn.style.display = "none";
                                        vTimeline.current = 1;
                                        employeeApplyPageCtn.style.display = "";
                                    }
                                }),
                                DOMElement.div({
                                    attrs: {
                                        className: "kv-document-link",
                                        onclick: function(){
                                            ModalElement.close();
                                        }
                                    },
                                    text: LanguageModule.text("txt_cancel")
                                })
                            ]
                        })
                    ]
                })
            ]
        });
        var orgEmpItems = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host);
        var department_employee_select = absol.buildDom({
            tag: "multichecktreemenu",
            style: {
                width: "100%"
            },
            props: {
                items: orgEmpItems,
                leafOnly: true,
                enableSearch: true
            }
        });
        var data = [
            [
                {
                    attrs: {style: {whiteSpace: "nowrap"}},
                    text: LanguageModule.text("txt_department_employee")
                },
                {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                department_employee_select
            ]
        ];
        var employeeApplyElt = DOMElement.table({
            data: data
        });
        employeeApplyElt.getValue = function(){
            return department_employee_select.values;
        };
        var employeeApplyPageCtn = DOMElement.div({
            attrs: {
                className: 'kv-document-2-site-right kv-document-page',
                style: {display: "none"}
            },
            children: [
                absol.buildDom({
                    class: 'kv-document-page-header',
                    child: [
                        {
                            tag: 'span',
                            class: 'kv-document-page-title',
                            child: { text: LanguageModule.text("txt_employee_apply") }
                        },
                        {
                            tag: 'button',
                            class: ['kv-document-transparent-btn', 'kv-document-page-close-btn'],
                            child: 'span.mdi.mdi-close',
                            on: {
                                click: function(){
                                    ModalElement.close();
                                }
                            }
                        }
                    ]
                }),
                DOMElement.div({
                    attrs: {
                        className: 'kv-document-page-content'
                    },
                    children: [employeeApplyElt]
                }),
                absol.buildDom({
                    class: 'kv-document-page-footer',
                    child: [
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-left"},
                            children: [
                                theme.noneIconButton({
                                    text: LanguageModule.text("txt_back"),
                                    onclick: function(){
                                        employeeApplyPageCtn.style.display = "none";
                                        vTimeline.current = 0;
                                        generalInformationPageCtn.style.display = "";
                                    }
                                })
                            ]
                        }),
                        DOMElement.div({
                            attrs: {className: "kv-document-page-footer-right"},
                            children: [
                                theme.noneIconButton({
                                    className: "primary",
                                    text: LanguageModule.text("txt_save"),
                                    onclick: function(){
                                        var data = {
                                            general_information: getValueFunction(),
                                            employee_apply: employeeApplyElt.getValue()
                                        };
                                        params.func.save(data).then(function(){
                                            ModalElement.close();
                                        });
                                    }
                                }),
                                DOMElement.div({
                                    attrs: {
                                        className: "kv-document-link",
                                        onclick: function(){
                                            ModalElement.close();
                                        }
                                    },
                                    text: LanguageModule.text("txt_cancel")
                                })
                            ]
                        })
                    ]
                })
            ]
        });
        ModalElement.show({
            bodycontent: absol.buildDom({
                class: 'kv-document-2-site',
                style: {
                    minWidth: "50vw",
                    height: "70vh"
                },
                child: [
                    {
                        class: 'kv-document-2-site-left',
                        child: [
                            {
                                class: 'kv-document-2-site-left-header',
                                child: [
                                    {
                                        tag: 'span',
                                        class: 'kv-document-2-site-left-header-text',
                                        child: { text: params.title }
                                    }
                                ]
                            },
                            vTimeline
                        ]
                    },
                    generalInformationPageCtn,
                    employeeApplyPageCtn
                ]
            })
        });
    };
    if (host.orgEmpLoaded){
        redraw();
    }
    else {
        data_module.loadEmployeeItemsPrivView().then(function(values){
            for (var x in values.database){
                host.database[x] = values.database[x];
            }
            delete  values.database;
            for (var x in values){
                host[x] = values[x];
            }
            host.orgEmpLoaded = true;
            redraw();
        });
    }
};

contentModule.getApprovalPayrollCycle = function(host, params = {}, type = "edit"){
    var getApprovalMethod = function(value){
        var list = contentModule.getListApprovalMethod();
        for (var i = 0; i < list.length; i++){
            if (list[i].value == value) return list[i].text;
        }
        return "";
    };
    var orgEmpItems = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host);
    var getRowApprover = function(employeeid){
        var employee_select = absol.buildDom({
            tag: "selecttreeleafmenu",
            style: {
                display: "block",
                width: "100%"
            },
            props: {
                items: orgEmpItems,
                enableSearch: true,
                value: employeeid
            }
        });
        if (type == "view") employee_select.disabled = true;
        var cells = [];
        if (type == "edit") cells.push({
            style: {
                width: '30px',
                textAlign: 'center',
                fontSize: '25px'
            },
            class: 'as-drag-zone',
            child: 'span.mdi.mdi-drag'
        });
        cells.push({
            child: employee_select
        });
        if (type == "edit"){
            var deleteIcon = DOMElement.div({
                attrs: {
                    className: "card-icon-remove-cover",
                    onclick: function(){
                        var x = tableView.rowOf(row)
                        x.remove();
                    }
                },
                children: [DOMElement.i({
                    attrs: {
                        className: "material-icons card-icon-remove"
                    },
                    text: "remove_circle"
                })]
            });
            cells.push({
                child: deleteIcon
            });
        }
        var row = {cells: cells};
        row.getValue = function(){
            var x = employee_select.value;
            if (x == 0){
                ModalElement.alert({
                    message: LanguageModule.text("txt_employee_is_null")
                });
                return;
            }
            return x;
        };
        return row;
    };
    var time_hours_needed_for_approval_input = theme.input({
        type: "number",
        min: 0,
        style: {
            textAlign: "right"
        },
        disabled: type == "view"
    });
    var approval_method_select = absol.buildDom({
        tag: "selectmenu",
        style: {
            display: "block",
            width: "100%"
        },
        props: {
            items: contentModule.getListApprovalMethod(),
            disabled: type == "view"
        }
    });
    if (params.time_hours_needed_for_approval !== undefined) time_hours_needed_for_approval_input.value = params.time_hours_needed_for_approval;
    if (params.approval_method !== undefined) approval_method_select.value = params.approval_method;
    var data = [];
    if (params.approvers){
        for (var i = 0; i < params.approvers.length; i++){
            data.push(getRowApprover(params.approvers[i]));
        }
    }
    var header = [];
    if (type == "edit") header.push({});
    header.push({
        child:  absol.buildDom({text: LanguageModule.text("txt_employee")})
    });
    if (type == "edit") header.push({});
    var tableView = absol.buildDom({
        tag: "dynamictable",
        props: {
            adapter: {
               rowsPerPage: Infinity,
               data: {
                   head: {
                       rows: [
                           {
                               cells: header
                           }
                       ]
                   },
                   body: {
                       rows: data
                   }
               }
           }
        }
    });
    if (type == "view") tableView.classList.add("as-inline");
    var approvalElt = DOMElement.div({
        children: [
            DOMElement.table({
                data: [
                    [
                        {
                            attrs: {style: {lineHeight: "var(--control-height)"}},
                            text: LanguageModule.text("txt_time_hours_needed_for_approval")
                        },
                        {attrs: {style: {width: "var(--distance-between-title-value)"}}},
                        time_hours_needed_for_approval_input
                    ],
                    [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
                    [
                        {
                            attrs: {style: {lineHeight: "var(--control-height)"}},
                            text: LanguageModule.text("txt_approval_method")
                        },
                        {attrs: {style: {width: "var(--distance-between-title-value)"}}},
                        approval_method_select
                    ]
                ]
            }),
            DOMElement.div({attrs: {style: {height: "var(--control-verticle-distance-2)"}}}),
            DOMElement.div({
                children: [
                    DOMElement.span({text: LanguageModule.text("txt_approvers")}),
                    DOMElement.div({
                        attrs: {
                            className: "mk-table-wrapper-header-cmd",
                            style: {
                                visibility: (type == "view")? "hidden" : "visible"
                            },
                            onclick: function(){
                                tableView.addRow(getRowApprover(0));
                            }
                        },
                        text: LanguageModule.text("txt_add")
                    })
                ]
            }),
            DOMElement.div({attrs: {style: {height: "var(--control-verticle-distance-2)"}}}),
            DOMElement.div({
                attrs: {className: "cardsimpletableclass"},
                children: [tableView]
            })
        ]
    });
    approvalElt.getValue = function(){
        var time_hours_needed_for_approval = parseFloat(time_hours_needed_for_approval_input.value);
        if (!time_hours_needed_for_approval){
            ModalElement.alert({
                message: LanguageModule.text("txt_time_hours_needed_for_approval_is_null"),
                func: function(){
                    time_hours_needed_for_approval_input.focus();
                }
            });
            return;
        }
        var approvers = [], value;
        var data = tableView.requireRows();
        var rowData;
        for (var i = 0; i < data.length; i++){
            rowData = data[i];
            value = rowData.data.getValue();
            if (!value) return;
            approvers.push(value);
        }
        if (approvers.length == 0){
            ModalElement.alert({
                message: LanguageModule.text("txt_approvers_is_null")
            });
            return;
        }
        var res = {
            time_hours_needed_for_approval: time_hours_needed_for_approval,
            approval_method: approval_method_select.value,
            approvers: approvers
        };
        return res;
    };
    return approvalElt;
};

contentModule.getViewPayrollDateMonthByCycleid = function(host, cycleid){
    var cycleIndex = host.database.payroll_cycle.getIndex(cycleid);
    if (cycleIndex < 0) return false;
    return host.database.payroll_cycle.items[cycleIndex].cycle == "month";
};

contentModule.getViewPayrollDateWeekByCycleid = function(host, cycleid){
    var cycleIndex = host.database.payroll_cycle.getIndex(cycleid);
    if (cycleIndex < 0) return false;
    return host.database.payroll_cycle.items[cycleIndex].cycle == "week";
};

contentModule.getNameListByCycleAndPayrollDate = function(host, cycleid, payroll_date_month, payroll_date_week){
    var cycleIndex = host.database.payroll_cycle.getIndex(cycleid);
    if (cycleid == 0) return;
    if (cycleIndex < 0) return;
    if (host.editedName) return;
    var cycleData = host.database.payroll_cycle.items[cycleIndex];
    if (cycleData.cycle == "month" && !payroll_date_month) return;
    if (cycleData.cycle == "week" && !payroll_date_week) return;
    var res = "";
    for (var i = 0; i < host.payroll_cycleItems.length; i++){
        if (host.payroll_cycleItems[i].value == cycleid){
            res += host.payroll_cycleItems[i].text;
            break;
        }
    }
    if (cycleData.cycle == "month"){
        var date = payroll_date_month;
        date = new Date(date.setDate(cycleData.payroll_date));
        res += " " + contentModule.getDateView(date);
    }
    else {
        var date = payroll_date_week;
        var x;
        if (cycleData.payroll_date == 0) x = 6;
        else x = cycleData.payroll_date - 1;
        date = new Date(date.getTime() + x*24*60*60*1000);
        res += " " + contentModule.getDateView(date);
    }
    return res;
};

contentModule.drawGeneralInformationEmployee_benefit_and_liability_list = function(host, params){
    var viewGeneralInformation = DOMElement.div({
        attrs: {
            style: {
                paddingLeft: "var(--control-verticle-distance-2)",
                paddingTop: "var(--control-verticle-distance-2)"
            }
        }
    });
    host.drawGeneralInforFunc = function(){
        contentModule.makeOutputFormData({
            typeid: host.form_config[params.type + "_list"].typeid,
            formid: host.form_config[params.type + "_list"].output_form,
            initialValue: host.dataListEdit,
            formContainer: viewGeneralInformation,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            viewGeneralInformation.formFragment.setContext('host', host);
        });
    };
    host.drawGeneralInforFunc();
    var childs = [
        {
            class: 'mk-section-header-name',
            child: { text: LanguageModule.text("txt_general_information") },
        }
    ];
    if (host.dataListEdit.status == 0 && (systemconfig.privSystem >= 2 || data_module.admin_rights_of_me.human_resource_list)) childs.push({
        class: 'mk-section-header-right',
        child: [
            DOMElement.a({
                attrs: {
                    onclick: function(){
                        params.editInforFunc();
                    }
                },
                text: LanguageModule.text("txt_edit")
            })
        ]
    });
    var res = absol.buildDom({
        attr: {
            "data-sectionid": "general_information"
        },
        child: [
            absol.buildDom({
                class: 'mk-section-header',
                child: childs
            }),
            viewGeneralInformation
        ]
    });
    return res;
};

contentModule.drawApprovalEmployee_benefit_and_liability_list = function(host, params){
    var data = [];
    var pIndex = host.database[params.type + "_policies"].getIndex(host.dataListEdit.policyid);
    var employeeDic = contentModule.makeDictionaryIndex(host.database.employees.items);
    var celldata, eIndex, ni, aItem, ex;
    for (var i = 0; i < host.database[params.type + "_policies"].items[pIndex].employee_approvers.length; i++){
        ni = host.database[params.type + "_policies"].items[pIndex].employee_approvers[i];
        eIndex = employeeDic[ni];
        if (eIndex === undefined) continue;
        celldata = [{
            text: host.database.employees.items[eIndex].fullname
        }];
        ex = 0;
        for (var j = 0; j < host.dataListEdit.employee_benefit_and_liability_list_approvers.length; j++){
            aItem = host.dataListEdit.employee_benefit_and_liability_list_approvers[j];
            if (host.database.employees.items[eIndex].peopleid == aItem.employee_peopleid){
                celldata.push({text: contentModule.getDateTimeView(aItem.time)});
                switch (aItem.status){
                    case 1:
                        celldata.push(DOMElement.div({
                            attrs: {
                                className: "table-view-status approved"
                            },
                            text: LanguageModule.text("txt_approved")
                        }));
                        break;
                    case 2:
                        celldata.push(DOMElement.div({
                            attrs: {
                                className: "table-view-status deny"
                            },
                            text: LanguageModule.text("txt_deny")
                        }));
                        break;
                    default:
                        celldata.push({});
                }
                celldata.push({text: aItem.comment});
                ex = 1;
                break;
            }
        }
        if (!ex) celldata.push({}, {}, {});
        data.push(celldata);
    }
    var viewApproval = DOMElement.div({
        attrs: {
            className: "cardsimpletableclass",
            style: {
                paddingTop: "var(--control-verticle-distance-2)",
                paddingLeft: "var(--control-horizontal-distance-2)"
            }
        },
        children: [DOMElement.table({
            data: data
        })]
    });
    var res = absol.buildDom({
        attr: {
            "data-sectionid": "approval"
        },
        child: [
            absol.buildDom({
                class: 'mk-section-header',
                child: [
                    {
                        class: 'mk-section-header-name',
                        child: { text: LanguageModule.text("txt_approval") },
                    }
                ]
            }),
            viewApproval
        ]
    });
    return res;
};

contentModule.formEmployee_benefit_and_liability_listView = function(host, params){
    hr.menu.changeCurrentUrlTab(host, params.type + "_list/" + params.listid);
    var navItems = [
        {text: LanguageModule.text("txt_general_information"), value: "general_information"},
        {text: LanguageModule.text("txt_list_details"), value: "list_details"}
    ];
    if (params.type != "salary_adjustment"){
        navItems.push({text: LanguageModule.text("txt_approval"), value: "approval"});
    }
    var nav = absol.buildDom({
        tag:'mknav',
        class: 'mk-nav',
        props: {
            items: navItems,
            value: "general_information"
        },
        on:{
            clickitem: function(event){
                rightCtn.off('scroll',scrollRightFunc);// prevent loop
                if (sectionList[this.value]) sectionList[this.value].scrollIntoView();
                setTimeout(function(){
                    rightCtn.on('scroll',scrollRightFunc );
                }, 10);
            }
        }
    });
    var scrollRightFunc = function(){
        var elt;
        var bound = rightCtn.getBoundingClientRect();
        var eltBound;
        var nearestEltId;
        var nearestDistance = 100000000;
        var distance;
        for (var i in sectionList){
            elt = sectionList[i];
            eltBound = elt.getBoundingClientRect();
            distance = 1000000;
            if (eltBound.top <= bound.top){
                if (eltBound.bottom >= bound.bottom){
                    distance = -1e6;
                }
                else if (bound.top - eltBound.top  < 30){
                    distance = eltBound.top - bound.bottom;//negative
                }
                else if (eltBound.bottom > bound.top){
                    distance = bound.top - eltBound.top;
                }
            }
            else if (eltBound.top < bound.bottom){
                distance = eltBound.top - bound.bottom;//negative
            }
            else {
                distance = Math.abs(bound.top - eltBound.top)
            }
            if (nearestDistance > distance){
                nearestDistance = distance;
                nearestEltId = i;
            }
        }
        nav.value = nearestEltId;
    };
    var rightCtn = absol.buildDom({
        class: 'mk-main-right',
        style: {
            paddingBottom: "var(--footer-margin)"
        },
        on: {
            scroll: scrollRightFunc
        }
    });
    var statusElt;
    switch (host.dataListEdit.status) {
        case 0:
            statusElt = DOMElement.div({
                attrs: {
                    className: "hr-status-view-btn waiting-approval"
                },
                text: LanguageModule.text("txt_waiting_approval")
            });
            break;
        case 1:
            statusElt = DOMElement.div({
                attrs: {
                    className: "hr-status-view-btn approved"
                },
                text: LanguageModule.text("txt_approved")
            });
            break;
        case 2:
            statusElt = DOMElement.div({
                attrs: {
                    className: "hr-status-view-btn deny"
                },
                text: LanguageModule.text("txt_deny")
            });
            break;

    }
    if (params.type != "salary_adjustment"){
        rightCtn.appendChild(DOMElement.div({
            attrs: {
                className: "hr-intro-view-form"
            },
            children: [DOMElement.table({
                data: [[
                    {text: LanguageModule.text("txt_approval_status")},
                    {attrs: {style: {width: "50px"}}},
                    statusElt
                ]]
            })]
        }));
    }
    rightCtn.appendChild(contentModule.drawGeneralInformationEmployee_benefit_and_liability_list(host, params));
    var childs = [
        {
            class: 'mk-section-header-name',
            child: { text: LanguageModule.text("txt_list_details") },
        }
    ];
    if (host.dataListEdit.status == 0 && (systemconfig.privSystem >= 2 || data_module.admin_rights_of_me.human_resource_list)){
        childs.push({
            class: 'mk-section-header-right',
            child: [
                DOMElement.a({
                    attrs: {
                        onclick: function(){
                            params.addDetailsFunc();
                        }
                    },
                    text: LanguageModule.text("txt_add")
                })
            ]
        });
    }
    childs.push({
        class: 'mk-section-header-right',
        child: [
            DOMElement.a({
                attrs: {
                    onclick: function(){
                        params.exportDetailsFunc();
                    }
                },
                text: LanguageModule.text("txt_export")
            })
        ]
    });
    if (host.dataListEdit.status == 0 && (systemconfig.privSystem >= 2 || data_module.admin_rights_of_me.human_resource_list)){
        childs.push({
            class: 'mk-section-header-right',
            child: [
                DOMElement.a({
                    attrs: {
                        onclick: function(){
                            params.importDetailsFunc();
                        }
                    },
                    text: LanguageModule.text("txt_import")
                })
            ]
        });
    }
    rightCtn.appendChild(absol.buildDom({
        attr: {
            "data-sectionid": "list_details"
        },
        child: [
            absol.buildDom({
                class: 'mk-section-header',
                child: childs
            }),
            params.list_detailsElt
        ]
    }));
    if (params.type != "salary_adjustment"){
        rightCtn.appendChild(contentModule.drawApprovalEmployee_benefit_and_liability_list(host, params));
    }
    var data_ctn = absol._({
        class: 'mk-main',
        style: {
            height: '100%'
        },
        child: [
            {
                class: 'mk-main-left-ctn',
                child: [nav]
            },
            rightCtn
        ]
    });
    var sectionList = {};
    absol.$("div", rightCtn, function(elt){
        var id = elt.getAttribute("data-sectionid");
        if (!id) return;
        sectionList[id] = elt;
    });
    var buttonlist = [
        DOMElement.div({
            attrs: {className: "single-button-header"},
            children: [theme.backButton({
                onclick: function(){
                    host.frameList.removeLast();
                    hr.menu.changeCurrentUrlTab(host, params.type + "_list");
                }
            })]
        })
    ];
    if (params.type != "salary_adjustment"){
        var privApproval = false;
        if (host.employeeOfMe.length > 0 && host.dataListEdit.status == 0){
            var pIndex = host.database[params.type + "_policies"].getIndex(host.dataListEdit.policyid);
            if (pIndex >= 0){
                var approval_method = host.database[params.type + "_policies"].items[pIndex].approval_method;
                switch (approval_method){
                    case "one_approver":
                        if (host.database[params.type + "_policies"].items[pIndex].employee_approvers.indexOf(host.employeeOfMe[0]) >= 0){
                            privApproval = true;
                        }
                        break;
                    case "parallel":
                        if (host.database[params.type + "_policies"].items[pIndex].employee_approvers.indexOf(host.employeeOfMe[0]) >= 0){
                            privApproval = true;
                            for (var i = 0; i < host.dataListEdit.employee_benefit_and_liability_list_approvers.length; i++){
                                if (host.dataListEdit.employee_benefit_and_liability_list_approvers[i].employeeid == host.employeeOfMe[0]){
                                    privApproval = false;
                                    break;
                                }
                            }
                        }
                        break;
                    case "sequence":
                        var k = host.database[params.type + "_policies"].items[pIndex].employee_approvers.indexOf(host.employeeOfMe[0]);
                        if (k > 0){
                            var eid = host.database[params.type + "_policies"].items[pIndex].employee_approvers[k -1];
                            var prev_done = false;
                            for (var i = 0; i < host.dataListEdit.employee_benefit_and_liability_list_approvers.length; i++){
                                if (host.dataListEdit.employee_benefit_and_liability_list_approvers[i].employeeid == eid){
                                    prev_done = true;
                                    break;
                                }
                            }
                            if (prev_done){
                                privApproval = true;
                                for (var i = 0; i < host.dataListEdit.employee_benefit_and_liability_list_approvers.length; i++){
                                    if (host.dataListEdit.employee_benefit_and_liability_list_approvers[i].employeeid == host.employeeOfMe[0]){
                                        privApproval = false;
                                        break;
                                    }
                                }
                            }
                        }
                        else if (k == 0) {
                            privApproval = true;
                        }
                        break;
                    default:

                }
            }
        }
        if (privApproval){
            buttonlist.push(DOMElement.div({
                attrs: {className: "single-button-header"},
                children: [theme.approvalButton({
                    onclick: function(){
                        params.approvalFunc();
                    }
                })]
            }));
            buttonlist.push(DOMElement.div({
                attrs: {className: "single-button-header"},
                children: [theme.denyButton({
                    onclick: function(){
                        params.denyFunc();
                    }
                })]
            }));
        }
    }
    if ((host.dataListEdit.status == 0 && data_module.admin_rights_of_me.human_resource_list) || systemconfig.privSystem){
        buttonlist.push(DOMElement.div({
            attrs: {className: "single-button-header"},
            children: [theme.deleteButton({
                onclick: function(){
                    params.deleteFunc().then(function(value){
                        host.frameList.removeLast();
                        hr.menu.changeCurrentUrlTab(host, params.type + "_list");
                    });
                }
            })]
        }));
    }
    var singlePage = absol.buildDom({
        tag: "singlepage",
        class: ["cd-page-not-padding-right", "as-viewport-full", "as-no-scroll"],
        child: [
            DOMElement.div({
                attrs: {className: 'button-panel-header absol-single-page-header'},
                children: buttonlist
            }),
            data_ctn
        ]
    });
    if (host.frameList.getLength() > 1) host.frameList.removeLast();
    host.frameList.addChild(singlePage);
    singlePage.requestActive();
};

contentModule.getWeekView = function(x){
    return absol.datetime.formatDateTime(x, LanguageModule.text("txt_week") + ' ww, yyyy');
};

contentModule.getMonthView = function(x){
    return absol.datetime.formatDateTime(x, LanguageModule.text("txt_month") + ' MM, yyyy');
};

contentModule.getWorkDayRatioListSystem = function(){
    return [
        {value: "r_week_day_work", text: LanguageModule.text("txt_r_week_day_work"), day_type: "weekday", ratio: 0},
        {value: "r_week_night_work", text: LanguageModule.text("txt_r_week_night_work"), day_type: "weekday", ratio: 0},
        {value: "r_week_night_work_1", text: LanguageModule.text("txt_r_week_night_work_1"), day_type: "weekday", ratio: 0},
        {value: "r_week_night_work_2", text: LanguageModule.text("txt_r_week_night_work_2"), day_type: "weekday", ratio: 0},
        {value: "r_week_day_ot", text: LanguageModule.text("txt_r_week_day_ot"), day_type: "weekday", ratio: 0},
        {value: "r_rest_day_ot", text: LanguageModule.text("txt_r_rest_day_ot"), day_type: "rest_day", ratio: 0},
        {value: "r_holiday_day_ot", text: LanguageModule.text("txt_r_holiday_day_ot"), day_type: "holiday", ratio: 0},
        {value: "r_week_night_ot", text: LanguageModule.text("txt_r_week_night_ot"), day_type: "weekday", ratio: 0},
        {value: "r_rest_night_ot", text: LanguageModule.text("txt_r_rest_night_ot"), day_type: "rest_day", ratio: 0},
        {value: "r_holiday_night_ot", text: LanguageModule.text("txt_r_holiday_night_ot"), day_type: "holiday", ratio: 0}
    ];
};
contentModule.getDayTypeList = function(){
    return [
        {value: "any_day", text: LanguageModule.text("txt_any_day")},
        {value: "weekday", text: LanguageModule.text("txt_weekday")},
        {value: "rest_day", text: LanguageModule.text("txt_rest_day")},
        {value: "holiday", text: LanguageModule.text("txt_holiday")},
        {value: "holiday_is_rest_day", text: LanguageModule.text("txt_holiday_is_rest_day")},
        {value: "double_holiday", text: LanguageModule.text("txt_double_holiday")},
        {value: "double_holiday_is_a_rest_day", text: LanguageModule.text("txt_double_holiday_is_a_rest_day")}
    ]
};
contentModule.getPaySheetColumnSystem = function(){
    return [
        {id: -1, name: LanguageModule.text("txt_employee_name"), code: "v_employee_name", cindex: 0},
        {id: -2, name: LanguageModule.text("txt_employee_code"), code: "v_employee_code", cindex: 1},
        {id: -3, name: LanguageModule.text("txt_department"), code: "v_employee_department", cindex: 2},
        {id: -4, name: LanguageModule.text("txt_position"), code: "v_employee_position", cindex: 3},
        {id: -5, name: LanguageModule.text("txt_basic_salary"), code: "v_basic_salary", cindex: 4}
    ];
};

contentModule.getExportContentEmployeeSimple = function(host, employeeViewDic){
    var exportContent = {
        row: 0,
        col: 0,
        data: [
            {
                row: 0,
                col: 0,
                colSpan: 5,
                value: LanguageModule.text("txt_employee"),
                bold: true,
                horizontal: "center",
                vertical: "middle"
            }
        ]
    };
    exportContent.row = 2;
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_index"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_code"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_name"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_department"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    var index = 0, oIndex;
    for (var i = 0; i < host.database.employees.items.length; i++){
        if (employeeViewDic && !employeeViewDic[host.database.employees.items[i].id]) continue;
        oIndex = orgsDic[host.database.employees.items[i].orgid];
        if (oIndex === undefined) continue;
        index++;
        exportContent.row++;
        exportContent.col = 0;
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: index
        });
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: host.database.employees.items[i].code
        });
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: host.database.employees.items[i].fullname
        });
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: host.database.orgs.items[oIndex].name
        });
    }
    for (var i = 1; i < exportContent.data.length; i++){
        exportContent.data[i].border = {
            top: {style: 'thin', color: {argb: 'FF000000'}},
            left: { style: 'thin', color: {argb: 'FF000000'}},
            bottom: { style: 'thin', color: {argb: 'FF000000'}},
            right: { style: 'thin', color: {argb: 'FF000000'}}
        };
    }
    return exportContent;
};

contentModule.intToExcelCol = function (number) {
    var colName = '', dividend = Math.floor(Math.abs(number)), rest;
    while (dividend > 0) {
        rest = (dividend - 1) % 26;
        colName = String.fromCharCode(65 + rest) + colName;
        dividend = parseInt((dividend - rest)/26);
    }
    return colName;
};
contentModule.excelColToInt = function (colName) {
    var digits = colName.toUpperCase().split(''), number = 0;
    for (var i = 0; i < digits.length; i++) {
        number += (digits[i].charCodeAt(0) - 64)*Math.pow(26, digits.length - i - 1);
    }
    return number;
};

contentModule.getExportContentListDetails = function(host, type){
    var columnList = contentModule.getColumnListFromDatatype(host, type + "_list_details", {});
    var exportContent = {
        row: 0,
        col: 0,
        data: [
            {
                row: 0,
                col: 2,
                colSpan: 10,
                value: "Chỉ nhập dữ liệu vào ô màu trắng, không nhập dữ liệu vào ô bôi màu",
                horizontal: "center",
                vertical: "middle",
                textcolor: "FFFF0000"
            },
            {
                row: 2,
                col: 2,
                colSpan: 10,
                value: LanguageModule.text("txt_" + type + "_list_details"),
                bold: true,
                horizontal: "center",
                vertical: "middle"
            }
        ]
    };
    exportContent.row += 4;
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_index"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    exportContent.data.push({
        row: exportContent.row,
        col: exportContent.col++,
        value: LanguageModule.text("txt_system_code"),
        bold: true,
        backgroundcolor: "FFEBEBEB",
        horizontal: "center",
        vertical: "middle"
    });
    for (var i = 0; i < columnList.length; i++){
        switch (columnList[i].value){
            case "employeeid":
                exportContent.data.push({
                    row: exportContent.row,
                    col: exportContent.col++,
                    value: LanguageModule.text("txt_employee_code"),
                    bold: true,
                    backgroundcolor: "FFEBEBEB",
                    horizontal: "center",
                    vertical: "middle"
                });
                exportContent.data.push({
                    row: exportContent.row,
                    col: exportContent.col++,
                    value: LanguageModule.text("txt_employee_name"),
                    bold: true,
                    backgroundcolor: "FFEBEBEB",
                    horizontal: "center",
                    vertical: "middle"
                });
                exportContent.data.push({
                    row: exportContent.row,
                    col: exportContent.col++,
                    value: LanguageModule.text("txt_department"),
                    bold: true,
                    backgroundcolor: "FFEBEBEB",
                    horizontal: "center",
                    vertical: "middle"
                });
                break;
            default:
                exportContent.data.push({
                    row: exportContent.row,
                    col: exportContent.col++,
                    value: columnList[i].text,
                    bold: true,
                    backgroundcolor: "FFEBEBEB",
                    horizontal: "center",
                    vertical: "middle"
                });
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    host.database.employee_benefit_and_liability_list_details.items.forEach(function(content){
        exportContent.row++;
        exportContent.col = 0;
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: exportContent.row - 4
        });
        exportContent.data.push({
            row: exportContent.row,
            col: exportContent.col++,
            value: content.id,
            backgroundcolor: "FFDDEBF7"
        });
        for (var i = 0; i < columnList.length; i++){
            switch (columnList[i].value){
                case "employeeid":
                    var eIndex = host.database.employees.getIndex(content.employeeid);
                    var oIndex = orgsDic[host.database.employees.items[eIndex].orgid];
                    exportContent.data.push({
                        row: exportContent.row,
                        col: exportContent.col++,
                        value: host.database.employees.items[eIndex].code
                    });
                    exportContent.data.push({
                        row: exportContent.row,
                        col: exportContent.col++,
                        value: {
                            formula: '=IF(' + contentModule.intToExcelCol(exportContent.col - 1) + (exportContent.row + 1) + '="","",VLOOKUP(' + contentModule.intToExcelCol(exportContent.col - 1) + (exportContent.row + 1) + ',Employee!$B:$C,2,FALSE))',
                            result: host.database.employees.items[eIndex].fullname
                        },
                        backgroundcolor: "FFDDEBF7"
                    });
                    exportContent.data.push({
                        row: exportContent.row,
                        col: exportContent.col++,
                        value: {
                            formula: '=IF(' + contentModule.intToExcelCol(exportContent.col - 2) + (exportContent.row + 1) + '="","",VLOOKUP(' + contentModule.intToExcelCol(exportContent.col - 2) + (exportContent.row + 1) + ',Employee!$B:$D,3,FALSE))',
                            result: host.database.orgs.items[oIndex].name
                        },
                        backgroundcolor: "FFDDEBF7"
                    });
                    break;
                default:
                    if (columnList[i].type == -1 || columnList[i].type == -118){
                        exportContent.data.push({
                            row: exportContent.row,
                            col: exportContent.col++,
                            value: content[columnList[i].value],
                            horizontal: "right"
                        });
                    }
                    else {
                        exportContent.data.push({
                            row: exportContent.row,
                            col: exportContent.col++,
                            value: content[columnList[i].value]
                        });
                    }
            }
        }
    });
    for (var i = 2; i < exportContent.data.length; i++){
        exportContent.data[i].border = {
            top: {style: 'thin', color: {argb: 'FF000000'}},
            left: { style: 'thin', color: {argb: 'FF000000'}},
            bottom: { style: 'thin', color: {argb: 'FF000000'}},
            right: { style: 'thin', color: {argb: 'FF000000'}}
        };
    }
    return exportContent;
};

contentModule.exportListDetails = function(host, type){
    ModalElement.alert({message: LanguageModule.text("txt_export_notification")});
    var employeeEditDic = {};
    var orgid, oIndex, orgIDList;
    var orgDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    for (var i = 0; i < host.dataListEdit.orgs.length; i++){
        orgid = host.dataListEdit.orgs[i];
        if (orgid > 0){
            oIndex = host.database.orgs.getIndex(orgid);
            orgIDList = contentModule.getDepartmentIDList(host, oIndex);
            for (var j = 0; j < orgIDList.length; j++){
                oIndex = orgDic[orgIDList[j]];
                host.database.orgs.items[oIndex].employeeIndexList.forEach(function(empIndex){
                    if (host.database.employees.items[empIndex].available){
                        if (type == "salary_adjustment"){
                            employeeEditDic[host.database.employees.items[empIndex].id] = true;
                        }
                        else if (host.dataListEdit.employee_apply_policies_dic[host.database.employees.items[empIndex].id]) employeeEditDic[host.database.employees.items[empIndex].id] = true;
                    }
                });
            }
        }
        else {
            if (type == "salary_adjustment"){
                employeeEditDic[-orgid] = true;
            }
            else if (host.dataListEdit.employee_apply_policies_dic[-orgid]) employeeEditDic[-orgid] = true;
        }
    }
    var exportContentEmployee = contentModule.getExportContentEmployeeSimple(host, employeeEditDic);
    var exportContentDetails = contentModule.getExportContentListDetails(host, type);
    var excelData = {
        sheets: [
            {
                name: "Employee",
                data: exportContentEmployee.data
            },
            {
                name: type + "_list_details",
                data: exportContentDetails.data
            }
        ]
    };
    var x = contentModule.getDateTimeExcelExport(new Date());
    var startWorker = function(result, fileName = type + "_list_"+x+".xlsx") {
        var w;
        if(typeof(Worker) !== "undefined") {
            if(typeof(w) == "undefined") {
                w = new Worker(window.domain + "exceljs.js");
                w.postMessage(result);
            }
            w.onmessage = function(event) {
                var data = event.data;
                if(data.name == "end")
                {
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(data.data);
                    link.download = fileName;
                    link.click();
                }
            }
        } else {
            console.log("Sorry, your browser does not support Web Workers...");
        }
    }
    startWorker(excelData);
};

contentModule.importListDetails = function(host, id, type, fi){
     return new Promise(function(resolve, reject){
         var columnList = contentModule.getColumnListFromDatatype(host, type + "_list_details", {});
         columnList.unshift(
             {value: "index"},
             {value: "id"}
         );
         var k;
         for (var i = 0; i < columnList.length; i++){
             if (columnList[i].value == "employeeid"){
                 k = i;
                 break;
             }
         }
         if (k){
             columnList.splice(k + 1, 0, {value: "employee_name", display: true, main: true, type: -1, text: LanguageModule.text("txt_employee_name")});
             k++;
             columnList.splice(k + 1, 0, {value: "department", display: true, main: true, type: -1, text: LanguageModule.text("txt_department")});
         }
         console.log(columnList);
         var typeDict = {};
         var dict2 = {};
         host.database.typelists.items.forEach(function(elt, index){
             typeDict[elt.id] = index;
             dict2[elt.id] = elt;
         });
         var mainData = contentModule.getMainData(host.form_config[type + "_list_details"].typeid, dict2);
         var f = new FileReader();
         f.onload = (function (fname) {
             return function (e) {
                 ModalElement.show_loading();
                 excel_module.load(f.result).then(function(rs){
                     console.log(rs);
                     FormClass.api_call({
                         url: "employee_benefit_and_liability_list_import.php",
                         params: [
                             {
                                 name: "exc_data",
                                 value: EncodingClass.string.fromVariable(rs)
                             },
                             {
                                 name: "listid",
                                 value: id
                             },
                             {
                                 name: "columnList",
                                 value: EncodingClass.string.fromVariable(columnList)
                             }
                         ],
                         func: function (success, message) {
                             if (success) {
                                 if (message.substr(0, 2) == "ok"){
                                     var listcount = EncodingClass.string.toVariable(message.substr(2));
                                     ModalElement.alert({message: "Đã thêm " + listcount.insert + " dòng và cập nhật " + listcount.update + " dòng."});
                                     resolve(listcount);
                                 }
                                 else {
                                     ModalElement.alert({
                                         message: message
                                     });
                                     return;
                                 }
                             }
                             else {
                                 ModalElement.alert({
                                     message: message
                                 });
                                 return;
                             }
                         }
                     });
                 });
             }
         }(fi.value));
         f.readAsArrayBuffer(fi.files[0]);
         setTimeout(function(){
             fi.value = "";
         }, 1000);
     });
};

contentModule.getMiliseconds = function(d){
    d = EncodingClass.string.duplicate(d);
    return d.getTime() - new Date(d.setHours(0, 0, 0, 0)).getTime();
};

contentModule.isValidExpression = function (s) {
    return MathClass.Expression.isvalid(s, function (varname) {
        if (varname == "G") return true;
        if (varname == "V") return true;
        if (varname == "L") return true;
        if (varname == "H") return true;
        return false;
    });
};

contentModule.isValidExpressionNoti = function (s) {
    return MathClass.Expression.isvalid(s, function (varname) {
        if (varname == "G") return true;
        if (varname == "L") return true;
        if (varname == "H") return true;
        return false;
    });
};

contentModule.getBscCriteriadefinitionsKpiType = function(){
    return [
        {value: "accumulate", text: LanguageModule.text("txt_accumulate")},
        {value: "average", text: LanguageModule.text("txt_average")},
        {value: "ratio", text: LanguageModule.text("txt_rate")},
        {value: "milestone", text: LanguageModule.text("txt_milestone")},
        // {value: "other", text: LanguageModule.text("txt_other")}
    ];
};

contentModule.getCriteriaKpiType = function(sumup_method, share_method, weight_requirement){
    var kpi_type;
    if (sumup_method == "accumulate" && share_method == "accumulate"){
        kpi_type = "accumulate";
    }
    else if (sumup_method == "average" && share_method == "average"){
        if (weight_requirement){
            kpi_type = "ratio";
        }
        else {
            kpi_type = "average";
        }
    }
    else if (sumup_method == "last" && share_method == "accumulate"){
        kpi_type = "milestone";
    }
    else kpi_type = "other";
    return kpi_type;
};

contentModule.makeBscCriteriaDefinitionData = function(host, item){
    item.kpi_type = contentModule.getCriteriaKpiType(item.sumup_method, item.share_method, item.weight_requirement);
};

contentModule.makeBscCriteriaDefinitionsData = function(host){
    for (var i = 0; i < host.database.bsc_criteriadefinitions.items.length; i++){
        contentModule.makeBscCriteriaDefinitionData(host, host.database.bsc_criteriadefinitions.items[i]);
    }
    var holderForSort = host.database.bsc_criteriadefinitions.items.map(function(item){
        return {
            item: item,
            val: absol.string.nonAccentVietnamese(item.name.toLowerCase())
        }
    });
    holderForSort.sort(function(a, b){
        if (a.val < b.val) return -1;
        if (a.val > b.val) return 1;
        return 0;
    });

    host.database.bsc_criteriadefinitions.items = holderForSort.map(function(holder){
        return holder.item;
    });
};

contentModule.getShare_methodItems = function(){
    return [
        {value: "accumulate", text: "accumulate"},
        {value: "average", text: "average"},
        {value: "min", text: "min"},
        {value: "max", text: "max"},
        {value: "first", text: "first"},
        {value: "last", text: "last"}
    ];
};

contentModule.getSumup_methodItems = function(){
    return [
        {value: "accumulate", text: "accumulate"},
        {value: "average", text: "average"},
        {value: "min", text: "min"},
        {value: "max", text: "max"},
        {value: "first", text: "first"},
        {value: "last", text: "last"}
    ];
};

contentModule.getDecpreItems = function(){
    return [
        {value: 0, text: "0"},
        {value: 1, text: "1 (0.1)"},
        {value: 2, text: "2 (0.12)"},
        {value: 3, text: "3 (0.123)"},
        {value: 4, text: "4 (0.1234)"}
    ];
};

contentModule.getDateFrom1970 = function(t){
    return Math.floor(absol.datetime.compareDate(t, new Date(0)));
};

contentModule.getDateTimeViewFromDate1970 = function(d){
    return contentModule.getDateView(new Date(d*86400000));
};

contentModule.getValueFromMoneyFormat = function(value) {
    if (value == "") value = "0";
    var s = value.split(systemconfig.separateSign).join("").split(systemconfig.commaSign).join(".");
    return parseFloat(s);
};

contentModule.moneyFormat2 = function(num, minF, decpre) {
    var number = absol.int.numberAutoFixed(num);
    var d, f, k, s;
    if (!EncodingClass.type.isNumber(number)) return "-";
    if (isNaN(number)) return "-";
	if (number < 0) return "-" + contentModule.fromDouble(-number, decpre);
    s = number.toFixed(decpre);
    k = s.indexOf(".");
    if (k != -1) {
        f = s.substr(k);
        s = s.substr(0, k);
    }
    else {
        f = "";
    }
    d = "";
    while (s.length > 3) {
        d = "," + s.substr(s.length - 3, 3) + d;
        s = s.substr(0, s.length - 3);
    }
    return s + d + f;
};

contentModule.fromDouble = function (number, decpre) {
    var d, f, k, s;
    if (!EncodingClass.type.isNumber(number)) return "-";
    if (isNaN(number)) return "-";
	if (number < 0) return "-" + contentModule.fromDouble(-number, decpre);
    s = number.toFixed(decpre);
    k = s.indexOf(".");
    if (k != -1) {
        f = s.substr(k);
        s = s.substr(0, k);
    }
    else {
        f = "";
    }
    d = "";
    while (s.length > 3) {
        d = "," + s.substr(s.length - 3, 3) + d;
        s = s.substr(0, s.length - 3);
    }
    return s + d + f;
};

contentModule.makeBscFormulaMessagesIndex = function(host){
    var i, k, t = [];
    for (i = 0; i < host.database.bsc_formulas.items.length; i++){
        host.database.bsc_formulas.items[i].messagesList = "0";
        host.database.bsc_formulas.items[i].messageIndexList = [];
    }
    for (i = 0; i < host.database.bsc_formula_messages.items.length; i++){
        host.database.bsc_formula_messages.items[i].formulaIndex = k = host.database.bsc_formulas.getIndex(host.database.bsc_formula_messages.items[i].formulaid);
        if (k >= 0){
            host.database.bsc_formulas.items[k].messageIndexList.push(t.length);
            host.database.bsc_formulas.items[k].messagesList = "if (" + host.database.bsc_formula_messages.items[i].cond + "," +  host.database.bsc_formula_messages.items[i].id + "," + host.database.bsc_formulas.items[k].messagesList + ")";
            t.push(host.database.bsc_formula_messages.items[i])
        }
    }
    for (i = 0; i < host.database.bsc_formulas.items.length; i++){
        host.database.bsc_formulas.items[i].parsedDataMess = MathClass.Expression.parse(host.database.bsc_formulas.items[i].messagesList);
        host.database.bsc_formulas.items[i].funcmess = host.database.bsc_formulas.items[i].parsedDataMess.calc;
    }
};

contentModule.makeConfigOrgsPrivileges = function(host){
    var listOfMe = [];
    if (host.employeeOfMe.length == 0) return;
    host.database.configs_privileges.items.forEach(function(item){
        if (item.content.employees.indexOf(0) >= 0 || item.content.employees.indexOf(host.employeeOfMe[0]) >= 0){
            listOfMe.push(item);
        }
        else {
            if (item.content.employee_groups.indexOf(0) >= 0){
                if (host.groupOfMe.length > 0) listOfMe.push(item);
            }
            else {
                for (var i = 0; i < item.content.employee_groups.length; i++){
                    if (host.groupOfMe.indexOf(item.content.employee_groups[i]) >= 0){
                        listOfMe.push(item);
                        break;
                    }
                }
            }
        }
    });
    var getDepartmentList = function(departmentList, dIndex){
        departmentList.push(host.database.orgs.items[dIndex].id);
        for (var i = 0; i < host.database.orgs.items[dIndex].childIndexList.length; i++){
            getDepartmentList(departmentList, host.database.orgs.items[dIndex].childIndexList[i]);
        }
    };
    for (var i = 0; i < listOfMe.length; i++){
        listOfMe[i].departmentList = [];
        if (listOfMe[i].taskdetails == 1){
            listOfMe[i].departmentList.push(listOfMe[i].taskid);
        }
        else {
            var dIndex = host.database.orgs.getIndex(listOfMe[i].taskid);
            if (dIndex >= 0) getDepartmentList(listOfMe[i].departmentList, dIndex);
        }
    }
    var orgsDic = contentModule.makeDictionaryIndex(host.database.orgs.items);
    host.privilegesDic = {};
    var k;
    for (var i = 0; i < listOfMe.length; i++){
        for (var j = 0; j < listOfMe[i].departmentList.length; j++){
            k = orgsDic[listOfMe[i].departmentList[j]];
            if (!host.privilegesDic[host.database.orgs.items[k].id]) host.privilegesDic[host.database.orgs.items[k].id] = {};
            for (var type in listOfMe[i].content){
                if (listOfMe[i].content[type]){
                    host.privilegesDic[host.database.orgs.items[k].id][type] = true;
                }
            }
            if (k >= 0){
                host.database.orgs.items[k].employeeIdList.forEach(function(eid){
                    if (!host.privilegesDic[-eid]) host.privilegesDic[-eid] = {};
                    for (var type in listOfMe[i].content){
                        if (listOfMe[i].content[type]){
                            host.privilegesDic[-eid][type] = true;
                        }
                    }
                });
            }
        }
    }
    console.log(host.privilegesDic);
};

contentModule.exportExcel = function(excelData, excelFileName){
    ModalElement.alert({message: LanguageModule.text("txt_export_notification")});
    var x = contentModule.getDateTimeExcelExport(new Date());
    var startWorker = function(result, fileName = excelFileName + x + ".xlsx") {
        var w;
        if(typeof(Worker) !== "undefined") {
            if(typeof(w) == "undefined") {
                w = new Worker(window.domain + "exceljs.js");
                w.postMessage(result);
            }
            w.onmessage = function(event) {
                var data = event.data;
                if(data.name == "end")
                {
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(data.data);
                    link.download = fileName;
                    link.click();
                }
            }
        } else {
            console.log("Sorry, your browser does not support Web Workers...");
        }
    }
    startWorker(excelData);
};

VaKeR 2022