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/keeview_app/html/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/html/keeview_app/html/orgs.js
hr.orgs.addTimekeepingCodeSave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTimekeepingCodeForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["code", "machineid"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
            data.employeeid = host.employeeid;
        }
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_timekeeping_code.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        if (id > 0){
                            var index = host.database.timekeeping_code.getIndex(id);
                            if (index < 0){
                                ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                                return;
                            }
                            host.database.timekeeping_code.items[index] = content;
                        }
                        else {
                            host.database.timekeeping_code.items.push(content);
                        }
                        ModalElement.close();
                        resolve(content);
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addTimekeepingCodeClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTimekeepingCodeForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["code", "machineid"]
                );
            }
            else {
                var oldData = {
                    code: "",
                    machineid: 0
                };
                var ischange = contentModule.isChanged(oldData, data,
                    ["code", "machineid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addTimekeepingCodeSave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editTimekeepingCode = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        function redraw(value){
            host.editTimekeepingCodeForm = DOMElement.div({});
            var  title;
            if (id == 0) title = LanguageModule.text("txt_add_timekeeping_code");
            else title = LanguageModule.text("txt_edit_timekeeping_code");
            ModalElement.showWindow({
                title: title,
                bodycontent: host.editTimekeepingCodeForm,
                buttonlist: [
                    {
                        text: LanguageModule.text("txt_save"),
                        onclick: function(){
                            hr.orgs.addTimekeepingCodeSave(host, id, dataEdit).then(function(value){
                                resolve(value)
                            });
                        }
                    },
                    {
                        text: LanguageModule.text("txt_cancel"),
                        onclick: function(){
                            hr.orgs.addTimekeepingCodeClose(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                    }
                ]
            });
            contentModule.makeFormData({
                typeid: host.form_config.checkin_employee_ident.typeid,
                formid: host.form_config.checkin_employee_ident.input_form,
                initialValue: value,
                formContainer: host.editTimekeepingCodeForm,
                typelists: host.database.typelists.items,
                variableType: "system"
            }).then(function(getValue){
                getValueFunction = getValue;
                absol.form.traversal(host.editTimekeepingCodeForm.formFragment.view, function(item){
                    if (item.node.tag === "TextInput") {
                        item.node.domElt.focus();
                        item.stop();
                        return;
                    }
                });
            });
            host.editTimekeepingCodeForm.getValue = function(){
                var data = getValueFunction();
                if (!data) return false;
                return data;
            };
        };
        if (id > 0){
            redraw(dataEdit);
        }
        else redraw({employeeid: host.employeeid});
    });
};

hr.orgs.deleteTimekeepingCode = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_delete_timekeeping_code.php",
            params: [{name: "id", value: id}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var index = host.database.timekeeping_code.getIndex(id);
                        host.database.timekeeping_code.items.splice(index, 1);
                        resolve();
                    }
                    else if (message == "failed_used"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_can_not_delete")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteTimekeepingCodeConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.timekeeping_code.getIndex(id);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_timekeeping_code"),
            message: LanguageModule.text2("war_txt_detele", [host.database.timekeeping_code.items[index].code]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteTimekeepingCode(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.editTimekeepingCodePre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "timekeeping_code_load_by_id"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        hr.orgs.editTimekeepingCode(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else if (message == "war_txt_failed_data"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_failed_data"),
                            func: function(){
                                host.frameList.removeLast();
                                hr.orgs.showEmployeePre(host, host.employeeid);
                            }
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({
                        message: message
                    });
                }
            }
        });
    });
};

hr.orgs.employeeTimekeepingCode = function(host){
    var displayDic = {
        machineid: true,
        code: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "checkin_employee_ident", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "timekeeping_code_list").then(function(value){
            var configColumnTimekeepingCode = value;
            var data = [];
            for (var i = 0; i < host.database.timekeeping_code.items.length; i++){
                data.push(hr.orgs.getRowTimekeepingCode(host, host.database.timekeeping_code.items[i]));
            }
            var params = {
                configColumnTimekeepingCode: configColumnTimekeepingCode,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "timekeeping_code_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["timekeeping_code_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editTimekeepingCode(host, 0).then(function(value){
                        rs(hr.orgs.getRowTimekeepingCode(host, value));
                    });
                };
            }
            timekeeping_codePage.redrawTable(params);
        });
    };
    var timekeeping_codePage = theme.employeeTimekeepingCodeForm();
    redrawTableFunc();
    return timekeeping_codePage;
};

hr.orgs.makeAllIndex = function(host){
    contentModule.makeOrgsIndex(host);
    contentModule.makePositionsIndex(host);
    contentModule.makeEmployeesIndex(host);
};

hr.orgs.orgChart = function(host){
    var t = contentModule.getOrgsAndEmployeesListSelectTreeMenu(host);
    var orgItems = {
        text: "Root",
        items: t.splice(1)
    };
    var singlePage = theme.orgChart({
        orgItems: orgItems,
        backFunc: function(){
            host.frameList.removeLast();
        }
    });
    host.frameList.addChild(singlePage);
    singlePage.requestActive();
};

hr.orgs.importUpdateFunc = function(host){
    var uploadwindow = DOMElement.input({
        attrs: {
            type: "file",
            style: {display: "none"}
        }
    });
    uploadwindow.onchange = function (){
        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: "orgs_import_update_employee.php",
                        params: [
                            {
                                name: "filedata",
                                value: EncodingClass.string.fromVariable(rs)
                            }
                        ],
                        func: function( success, message) {
                            ModalElement.close(-1);
                            if (success){
                                if (message.substr(0, 2) == "ok"){
                                    var content = EncodingClass.string.toVariable(message.substr(2));
                                    ModalElement.alert({
                                        message: LanguageModule.text("txt_import_success"),
                                        func: function(){
                                            hr.menu.tabPanel.removeTab(host.holder.id);
                                            hr.menu.loadPage(11);
                                        }
                                    });
                                }
                                else if (message.substr(0, 6) == "failed"){
                                    var content = EncodingClass.string.toVariable(message.substr(6));
                                    if (!content || !content.errorcode) {
                                        ModalElement.alert({
                                            message: "Lỗi không xác định"
                                        });
                                        console.log(message);
                                        return;
                                    }
                                    switch (content.errorcode) {
                                        case "id_not_exist":
                                            message = "Sheet Employee: Id nhân viên không tồn tại hoặc đã cũ (Mã: " + content.value + ", Dòng: " + content.row + ")";
                                            break;
                                        case "hr_support_employee_not_exist":
                                            message = "Sheet Employee: Hr hỗ trợ nhân viên không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")";
                                            break;
                                        case "direct_manager_not_exist":
                                            message = "Sheet Employee: Quản lý trực tiếp không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")";
                                            break;
                                        case "indirect_manager_not_exist":
                                            message = "Sheet Employee: Quản lý gián tiếp không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")";
                                            break;
                                        case "same_code":
                                            message = "Sheet Employee: Trùng mã nhân viên (Mã: " + content.value + ", Dòng 1: " + content.row + ", Dòng 2: " + content.same_row + ")";
                                            break;
                                        case "miss_code":
                                            message = "Sheet Employee: Chưa nhập mã nhân viên (Dòng: " + content.row + ")";
                                            break;
                                        case "miss_fullname":
                                            message = "Sheet Employee: Chưa nhập tên nhân viên (Dòng: " + content.row + ")";
                                            break;
                                        case "same_user":
                                            message = "Sheet Employee: Trùng user liên kết (username: " + content.value + ", Dòng 1: " + content.row + ", Dòng 2: " + content.same_row + ")";
                                            break;
                                        case "user_not_exist":
                                            message = "Sheet Employee: Username không tồn tại (username: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "org_not_exist":
                                            message = "Sheet Employee: Phòng ban không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "miss_org":
                                            message = "Sheet Employee: Chưa nhập mã phòng ban (Dòng: " + content.row + ")";
                                            break;
                                        case "miss_dayofbirth":
                                            message = "Sheet Employee: Chưa nhập ngày sinh (Dòng: " + content.row + ")";
                                            break;
                                        case "miss_nationalidno":
                                            message = "Sheet Employee: Chưa nhập số CMND (Dòng: " + content.row + ")";
                                            break;
                                        case "miss_nationality":
                                            message = "Sheet Employee: Chưa nhập quốc tịch (Dòng: " + content.row + ")";
                                            break;
                                        case "nationality_not_exist":
                                            message = "Sheet Employee: Quốc gia không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "miss_nationality":
                                            message = "Sheet Employee: Chưa nhập quốc tịch (Dòng: " + content.row + ")";
                                            break;
                                        case "riligion_not_exist":
                                            message = "Sheet Employee: Tôn giáo không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "ethnic_not_exist":
                                            message = "Sheet Employee: Dân tộc không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "permanent_nation_not_exist":
                                            message = "Sheet Employee: Quốc gia thường trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "permanent_city_not_exist":
                                            message = "Sheet Employee: Thành phố thường trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "temporary_nation_not_exist":
                                            message = "Sheet Employee: Quốc gia tạm trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "temporary_city_not_exist":
                                            message = "Sheet Employee: Thành phố tạm trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "position_not_exist":
                                            message = "Sheet Employee: Chức danh không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "concurrent_position_not_exist":
                                            message = "Sheet Employee: Chức danh kiêm nhiệm không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;

                                        case "emp_code_not_exist":
                                            message = "Sheet " + content.sheet + ": Mã nhân viên không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "miss_emp_code":
                                            message = "Sheet " + content.sheet + ": Chưa nhập mã nhân viên (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_contract_number":
                                            message = "Sheet " + content.sheet + ": Chưa nhập mã hợp đồng lao động (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_signing_date":
                                            message = "Sheet " + content.sheet + ": Chưa nhập ngày ký hợp đồng lao động (Dòng : " + content.row + ")";
                                            break;
                                        case "contract_type_not_exist":
                                            message = "Sheet " + content.sheet + ": ID loại hợp đồng lao động không tồn tại (ID: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "miss_contract_type":
                                            message = "Sheet " + content.sheet + ": Chưa nhập loại hợp đồng lao động (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_effective_date_from":
                                            message = "Sheet " + content.sheet + ": Chưa nhập thời gian hiệu lực Từ ngày (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_effective_date_to":
                                            message = "Sheet " + content.sheet + ": Chưa nhập thời gian hiệu lực Đến ngày (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_salary_grade":
                                            message = "Sheet " + content.sheet + ": Chưa nhập bậc lương (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_basic_salary_amount":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Mức lương cơ bản (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_gross_salary_amount":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Mức lương chính (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_calculated_on":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Tính trên (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_effective_date":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Ngày hiệu lực (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_decision_date":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Ngày quyết định (Dòng : " + content.row + ")";
                                            break;
                                        case "machine_code_not_exist":
                                            message = "Sheet " + content.sheet + ": Mã máy chấm công tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")";
                                            break;
                                        case "miss_machine_code":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Mã máy chấm công (Dòng : " + content.row + ")";
                                            break;
                                        case "miss_code_timekeeping":
                                            message = "Sheet " + content.sheet + ": Chưa nhập Mã chấm công (Dòng : " + content.row + ")";
                                            break;
                                        case "same_employee_same_machine":
                                            message = "Sheet TimekeepingCode : Trùng nhân viên và máy chấm công (Dòng 1: " + content.same_row + ", Dòng 2 : " + content.row + ")";
                                            break;
                                        case "same_contract_number":
                                            message = "Sheet " + content.sheet + ": Trùng số hợp đồng lao động (Số : " + content.value + ", Dòng 1: " + content.same_row + ", Dòng 2 : " + content.row + ")";
                                            break;
                                        case "same_timekeeping_code":
                                            message = "Sheet " + content.sheet + ": Trùng mã chấm công trên cùng 1 máy chấm công (Mã: " + content.value + ", Dòng 1: " + content.same_row + ", Dòng 2 : " + content.row + ")";
                                            break;
                                        default:
                                            message = "Lỗi không xác định";
                                    }
                                    ModalElement.alert({
                                        message: message
                                    });
                                    return;
                                }
                                else {
                                    console.log(message);
                                    ModalElement.alert({
                                        message: "Lỗi không xác định"
                                    });
                                    return;
                                }
                            }
                            else {
                                console.log(message);
                                ModalElement.alert({
                                    message: "Lỗi không xác định"
                                });
                                return;
                            }
                        }
                    });
                });
            }
        }(this.value));
        f.readAsArrayBuffer(this.files[0]);
    };
    uploadwindow.click();
};

hr.orgs.importFunc = function(host){
    var uploadwindow = DOMElement.input({
        attrs: {
            type: "file",
            style: {display: "none"}
        }
    });
    uploadwindow.onchange = function (){
        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: "orgs_import_employee.php",
                        // fileuploads: [
                        //     {
                        //         name: "excelFile",
                        //         filename: "excel.xlsx",
                        //         content: rs
                        //     }
                        // ],
                        params: [
                            {
                                name: "filedata",
                                value: EncodingClass.string.fromVariable(rs)
                            }
                        ],
                        func: function( success, message) {
                            ModalElement.close(-1);
                            if (success){
                                if (message.substr(0, 2) == "ok"){
                                    var content = EncodingClass.string.toVariable(message.substr(2));
                                    ModalElement.alert({
                                        message: LanguageModule.text("txt_import_success"),
                                        func: function(){
                                            hr.menu.tabPanel.removeTab(host.holder.id);
                                            hr.menu.loadPage(11);
                                        }
                                    });
                                }
                                else if (message.substr(0, 6) == "failed"){
                                    var content = EncodingClass.string.toVariable(message.substr(6));
                                    if (!content || !content.errorcode) {
                                        ModalElement.alert({
                                            message: "Lỗi không xác định"
                                        });
                                        console.log(message);
                                        return;
                                    }
                                    switch (content.errorcode) {
                                        case "hr_support_employee_not_exist":
                                            message = "Hr hỗ trợ nhân viên không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")"
                                            break;
                                        case "direct_manager_not_exist":
                                            message = "Quản lý trực tiếp không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")"
                                            break;
                                        case "indirect_manager_not_exist":
                                            message = "Quản lý gián tiếp không tồn tại (Mã: " + content.value + ", Dòng: " + content.row + ")"
                                            break;
                                        case "same_code":
                                            message = "Trùng mã nhân viên (Mã: " + content.value + ", Dòng 1: " + content.row + ", Dòng 2: " + content.same_row + ")"
                                            break;
                                        case "miss_code":
                                            message = "Chưa nhập mã nhân viên (Dòng: " + content.row + ")"
                                            break;
                                        case "miss_fullname":
                                            message = "Chưa nhập tên nhân viên (Dòng: " + content.row + ")"
                                            break;
                                        case "same_user":
                                            message = "Trùng user liên kết (username: " + content.value + ", Dòng 1: " + content.row + ", Dòng 2: " + content.same_row + ")"
                                            break;
                                        case "user_not_exist":
                                            message = "Username không tồn tại (username: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "org_not_exist":
                                            message = "Phòng ban không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "miss_org":
                                            message = "Chưa nhập mã phòng ban (Dòng: " + content.row + ")"
                                            break;
                                        case "miss_dayofbirth":
                                            message = "Chưa nhập ngày sinh (Dòng: " + content.row + ")"
                                            break;
                                        case "miss_nationalidno":
                                            message = "Chưa nhập số CMND (Dòng: " + content.row + ")"
                                            break;
                                        case "miss_nationality":
                                            message = "Chưa nhập quốc tịch (Dòng: " + content.row + ")"
                                            break;
                                        case "nationality_not_exist":
                                            message = "Quốc gia không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "miss_nationality":
                                            message = "Chưa nhập quốc tịch (Dòng: " + content.row + ")"
                                            break;
                                        case "riligion_not_exist":
                                            message = "Tôn giáo không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "thnic_not_exist":
                                            message = "Dân tộc không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "permanent_nation_not_exist":
                                            message = "Quốc gia thường trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "permanent_city_not_exist":
                                            message = "Thành phố thường trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "temporary_nation_not_exist":
                                            message = "Quốc gia tạm trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "temporary_city_not_exist":
                                            message = "Thành phố tạm trú không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "position_not_exist":
                                            message = "Chức danh không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        case "concurrent_position_not_exist":
                                            message = "Chức danh kiêm nhiệm không tồn tại (Mã: " + content.value + ", Dòng : " + content.row + ")"
                                            break;
                                        default:
                                            message = "Lỗi không xác định";
                                    }
                                    ModalElement.alert({
                                        message: message
                                    });
                                    return;
                                }
                                else {
                                    console.log(message);
                                    ModalElement.alert({
                                        message: "Lỗi không xác định"
                                    });
                                    return;
                                }
                            }
                            else {
                                console.log(message);
                                ModalElement.alert({
                                    message: "Lỗi không xác định"
                                });
                                return;
                            }
                        }
                    });
                });
            }
        }(this.value));
        f.readAsArrayBuffer(this.files[0]);
    };
    uploadwindow.click();
};

hr.orgs.exportFunc = function(host){
    ModalElement.show_loading();
    var excelData = [];
    var promiseList = [];
    var getType = function(id){
        var index = data_module.typelists.getIndex(id);
        var type = data_module.typelists.items[index].type;
        if (form_module.primitiveTypeList.indexOf(type) != -1){
            type = data_module.typelists.items[index].type2;
        }
        return type;
    }
    var typeid = host.form_config.employee.typeid;
    var content = [];
    while (typeid != -27) {
        var idx = data_module.typelists.getIndex(typeid);
        for (var i = data_module.typelists.items[idx].content.details.length - 1; i >= 0; i--) {
            content.unshift(EncodingClass.string.duplicate(data_module.typelists.items[idx].content.details[i]));
        }
        typeid = data_module.typelists.items[idx].content.typeof;
    }
    var extrainfo = [];
    var type;
    var noExportArray = [
        "structure", "extends_structure", "array", "image_file", "any_file", "color_picker", "enum_multi", "extends_enum_multi", "nation_city",
        "userlist", "select_department_employee", "position_list", "employee_list", "multiselect_offboarding_reasons", "members_of_shifts", "members_of_partner_class",
        "members_of_locations"
    ];
    var noneSheetData = [
        "string", "phonenumber", "website", "performance_chart", "gps", "variable_input", "variable_textarea", "number",
        "currency", "note", "html", "date", "datetime", "month", "week", "datemonth", "time", "hour_period",
        "boolean", "email_address"
    ];
    for (var i = 0; i < content.length; i++){
        if (content[i].type == "union") {
            var t_type = getType(content[i].typeOfUnion);
            content[i].sheetName = "data_of_" + content[i].localid;
            excelData.push({name: content[i].sheetName});
            promiseList.push(data_module.exportData[t_type](content[i].typeOfUnion));
            content[i].type = t_type;
            var detailUnion = content[i].detailUnion;
            delete content[i].detailUnion;
            extrainfo.push(content[i]);
            var lcid = {};
            var values = Object.values(detailUnion);
            values.forEach((item, idx) => {
                item.forEach((item2, idx2) => {
                    if (!lcid[item2.localid]) {
                        var type = getType(item2.type);
                        if (noExportArray.indexOf(type) == -1){
                            if(noneSheetData.indexOf(type) == -1) {
                                item2.sheetName = "data_of_" + item2.localid;
                                excelData.push({name: item2.sheetName});
                                promiseList.push(data_module.exportData[type](item2.type));
                            }
                            item2.type = type;
                            extrainfo.push(item2);
                            lcid[item2.localid] = 1;
                        }
                    }
                });
            });
        }
        else {
            type = getType(content[i].type);
            if (noExportArray.indexOf(type) == -1){
                if(noneSheetData.indexOf(type) == -1) {
                    content[i].sheetName = "data_of_" + content[i].localid;
                    excelData.push({name: content[i].sheetName});
                    promiseList.push(data_module.exportData[type](content[i].type));
                }
                content[i].type = type;
                extrainfo.push(content[i]);
            }
        }
    }
    console.log(extrainfo);
    FormClass.api_call({
        url: "orgs_export.php",
        params: [{name: "extrainfo", value: EncodingClass.string.fromVariable(extrainfo)}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success) {
                if (message.substr(0, 2) == "ok"){
                    var content = EncodingClass.string.toVariable(message.substr(2));
                    var x = contentModule.getDateTimeExcelExport(new Date());
                    Promise.all(promiseList).then(function(data){
                        excelData.forEach((item, i) => {
                            item.data = data[i];
                            content.sheets.unshift(item);
                        });
                        excel_module.writerWorkbook(content, "org_ "+x+".xlsx");
                    })
                }
                else {
                    console.log(message);
                }
            }
            else {
                console.log(message);
            }
        }
    })
};

hr.orgs.deleteOrg = function(host, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_delete.php",
        params: [{name: "id", value: id}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var index = host.database.orgs.getIndex(id);
                    host.database.orgs.items.splice(index, 1);
                    contentModule.makeOrgsIndex(host);
                    hr.orgs.redraw(host);
                }
                else if (message == "failed_org") {
                    ModalElement.alert({message: LanguageModule.text("war_txt_can_not_delete_org_has_org")});
                }
                else if (message == "failed_emp") {
                    ModalElement.alert({message: LanguageModule.text("war_txt_can_not_delete_org_has_emp")});
                }
                else if (message == "failed_used") {
                    ModalElement.alert({message: LanguageModule.text("war_txt_can_not_delete")});
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.deleteOrgConfirm = function(host, id){
    var index = host.database.orgs.getIndex(id);
    ModalElement.question({
        title: LanguageModule.text("war_title_department"),
        message: LanguageModule.text2("war_txt_detele", [host.database.orgs.items[index].name]),
        onclick: function(sel){
            if (sel == 0){
                hr.orgs.deleteOrg(host, id);
            }
        }
    });
};

hr.orgs.deleteEmployee = function(host, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_delete_employee.php",
        params: [{name: "id", value: id}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var index = host.database.employees.getIndex(id);
                    host.database.employees.items.splice(index, 1);
                    contentModule.makeEmployeesIndex(host);
                    hr.orgs.redrawEmployee2(host);
                }
                else if (message == "failed_used") {
                    ModalElement.alert({message: LanguageModule.text("war_txt_can_not_delete")});
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.deleteEmployeeConfirm = function(host, id){
    var index = host.database.employees.getIndex(id);
    ModalElement.question({
        title: LanguageModule.text("war_title_delete_employee"),
        message: LanguageModule.text2("war_txt_detele", [host.database.employees.items[index].fullname]),
        onclick: function(sel){
            if (sel == 0){
                hr.orgs.deleteEmployee(host, id);
            }
        }
    });
};

hr.orgs.save_emp_extradata = function(host, data, content, type){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_emp_extradata.php",
            params: [
                {name: "data", value: EncodingClass.string.fromVariable(data)},
                {name: "employeeid", value: host.employeeid},
                {name: "type", value: type}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        resolve(content);
                        ModalElement.close();
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.saveEmployeePolicy = function(host, data, id){
    return new Promise(function(resolve, reject){
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        data.files = [];
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_employee_policies.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        content.description = data.description;
                        if (content.type == "insurance"){
                            content.calculated_on = data.calculated_on;
                        }
                        else if (content.type == "tax"){
                            content.tax_type = data.tax_type;
                        }
                        else if (content.type == "other_liability"){
                            content.tax_relief = data.tax_relief;
                            content.insurance_contribution_relief = data.insurance_contribution_relief;
                            content.other_liability_type = data.other_liability_type;
                            content.frequency = data.frequency;
                        }
                        var listTypeActiveGroupUnique = ["insurance", "tax", "trade_union", "benefit", "allowance", "other_liability"];
                        if (listTypeActiveGroupUnique.indexOf(content.type) >= 0 && content.available){
                            var pIndex = host.database[content.type + "_policies"].getIndex(content.policyid);
                            if (pIndex >= 0){
                                var groupid = host.database[content.type + "_policies"].items[pIndex].groupid;
                                var pIDList = {};
                                host.database[content.type + "_policies"].items.forEach(function(item){
                                    if (item.groupid == groupid) pIDList[item.id] = true;
                                });
                                host.database.employee_policies.items.forEach(function(item){
                                    if (item.type == content.type && pIDList[item.policyid]) item.available = 0;
                                });
                            }
                        }
                        if (id > 0){
                            var index = host.database.employee_policies.getIndex(id);
                            if (index < 0){
                                ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                                return;
                            }
                            host.database.employee_policies.items[index] = content;
                        }
                        else {
                            host.database.employee_policies.items.push(content);
                        }
                        ModalElement.close();
                        resolve(content);
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteEmployeePolicies = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_delete_employee_policies.php",
            params: [{name: "id", value: id}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var index = host.database.employee_policies.getIndex(id);
                        host.database.employee_policies.items.splice(index, 1);
                        resolve();
                    }
                    else if (message == "failed_used"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_can_not_delete")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteEmployeeSalaryDecision = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_delete_employee_salary_decisions.php",
            params: [{name: "id", value: id}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var index = host.database.employee_salary_decisions.getIndex(id);
                        host.database.employee_salary_decisions.items.splice(index, 1);
                        resolve();
                    }
                    else if (message == "failed_used"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_can_not_delete")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteEmploymentContract = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_delete_employee_employment_contract.php",
            params: [{name: "id", value: id}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var index = host.database.employment_contracts.getIndex(id);
                        host.database.employment_contracts.items.splice(index, 1);
                        resolve();
                    }
                    else if (message == "failed_used"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_can_not_delete")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.replaceDataOrg = function(host, oldid, content){
    var index = host.database.orgs.getIndex(oldid);
    var ni;
    for (var i = 0; i < host.database.orgs.items[index].childIndexList.length; i++){
        ni = host.database.orgs.items[index].childIndexList[i];
        host.database.orgs.items[ni].parentid = content.id;
    }
    for (var i = 0; i < host.database.orgs.items[index].positionIndexList.length; i++){
        ni = host.database.orgs.items[index].positionIndexList[i];
        host.database.positions.items[ni].orgid = content.id;
    }
    for (var i = 0; i < host.database.orgs.items[index].employeeIndexList.length; i++){
        ni = host.database.orgs.items[index].employeeIndexList[i];
        host.database.employees.items[ni].orgid = content.id;
    }
    host.database.orgs.items[index] = content;
};

hr.orgs.addDepartmentSave = function(host, id, getValueFunction){
    return new Promise(function(rs, rj){
        var data = getValueFunction();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var index = host.database.orgs.getIndex(id);
            var ischange = contentModule.isChanged(host.database.orgs.items[index], data, ["name", "code", "fullname", "geopos", "extrainfo"]);
            if (!ischange){
                hr.orgs.preRedraw(host);
                hr.menu.changeCurrentUrlTab(host, "orgs");
                rs();
                return;
            }
            data.ver = host.database.orgs.items[index].ver;
        }
        else {
            data.ver = 0;
        }
        for (var i = 0; i < host.database.orgs.items.length; i++){
            if (host.database.orgs.items[i].id != id && host.database.orgs.items[i].code.toLowerCase() == data.code.toLowerCase()){
                ModalElement.alert({
                    message: LanguageModule.text("war_txt_code_was_used")
                });
                return;
            }
        }
        if (!data.parentid) data.parentid = 0;
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_department.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        host.id = content.id;
                        host.orgid = content.id;
                        content.geopos = data.geopos;
                        if (content.parentid == 0) host.companyid = content.id;
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        if (id > 0){
                            hr.orgs.replaceDataOrg(host, id, content);
                        }
                        else {
                            host.database.orgs.items.push(content);
                        }
                        hr.orgs.preRedraw(host);
                        rs();
                        hr.menu.changeCurrentUrlTab(host, "orgs");
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addEmployeeSave = function(host, id, getValueFunction){
    return new Promise(function(resolve, reject){
        var saveFunc = function(){
            data.orgid = host.orgid;
            data.available = data.available? 1: 0;
            data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
            data.social_network = EncodingClass.string.fromVariable(data.social_network);
            data.content = EncodingClass.string.fromVariable(data.content);
            ModalElement.show_loading();
            FormClass.api_call({
                url: "orgs_save_employee.php",
                params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
                func: function(success, message){
                    if (id > 0) ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            data_module.loadAllEmployeesList();
                            var randomId = contentModule.generateRandom();
                            data_module.listMessRandomCreate[randomId] = true;
                            hr.sendMessageFunc({
                                messageType: "change_data_module",
                                randomId: randomId
                            });
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            var dataEmp = st.dataEmployee;
                            var pIndex;
                            pIndex = host.database.positions.getIndex(dataEmp.position);
                            if (pIndex >= 0) dataEmp.positionName = host.database.positions.items[pIndex].name;
                            pIndex = host.database.positions.getIndex(dataEmp.concurrent_position);
                            if (pIndex >= 0) dataEmp.concurrent_positionName = host.database.positions.items[pIndex].name;
                            // var positionName = "", pIndex;
                            // for (var i = 0; i < dataEmp.positions.length; i++){
                            //     pIndex = host.database.positions.getIndex(dataEmp.positions[i]);
                            //     if (pIndex >= 0) positionName += ", " + host.database.positions.items[pIndex].name;
                            // }
                            // dataEmp.positionName = positionName.substr(2);
                            dataEmp.content = EncodingClass.string.toVariable(dataEmp.content);
                            for (var i = 0; i < contentModule.getPeopleContentField.length; i++){
                                dataEmp[contentModule.getPeopleContentField[i]] = dataEmp.content[contentModule.getPeopleContentField[i]];
                            }
                            host.orgid = dataEmp.orgid;
                            host.employeeid = dataEmp.id;
                            //=====update people=====//
                            var dataPeo = st.dataPeople;
                            dataPeo.extrainfo = EncodingClass.string.toVariable(dataPeo.extrainfo);
                            if (st.newpeople == 1){
                                host.database.peoples.items.push(dataPeo);
                            }
                            else {
                                var x = host.database.peoples.getIndex(dataPeo.id);
                                if (x < 0) {
                                    console.log(x);
                                    return;
                                }
                                host.database.peoples.items[x] = dataPeo;
                            }
                            //=======//
                            if (id > 0){
                                var index = host.database.employees.getIndex(id);
                                host.database.employees.items.splice(index, 1);
                            }
                            host.database.employees.items.push(dataEmp);
                            contentModule.makeEmployeesIndex(host);
                            contentModule.makeEmployeeAllData(host);
                            contentModule.makePrivilegeOrgConfigs(host);
                            resolve();
                            hr.orgs.redrawEmployee2(host);
                            if (id > 0){
                                if (host.peopleid != dataEmp.peopleid){
                                    for (var i = 0; i < host.database.employee_policies.items.length; i++){
                                        host.database.employee_policies.items[i].employee_peopleid = dataEmp.peopleid;
                                    }
                                }
                                host.peopleid = dataEmp.peopleid;
                                host.drawGeneralInforFunc();
                                if (st.dataUser && st.dataUser.id > 0){
                                    setTimeout(function(){
                                        var statusName;
                                        if (dataEmp.available) statusName = LanguageModule.text("txt_yes");
                                        else statusName = LanguageModule.text("txt_no");
                                        var userFullname = "";
                                        var uIndex = host.database.users.getIndex(st.dataUser.id);
                                        if (uIndex >= 0) userFullname = host.database.users.items[uIndex].fullname;
                                        st.dataUser.available = dataEmp.available;
                                        ModalElement.showWindow({
                                            bodycontent: DOMElement.div({
                                                innerHTML: LanguageModule.text2("war_title_warning_change_active_user", [dataPeo.fullname, userFullname, statusName])
                                            }),
                                            buttonlist: [
                                                {
                                                    text: LanguageModule.text("txt_yes"),
                                                    onclick: function(){
                                                        ModalElement.show_loading();
                                                        FormClass.api_call({
                                                            url: "orgs_change_active_user.php",
                                                            params: [{name: "data", value: EncodingClass.string.fromVariable(st.dataUser)}],
                                                            func: function(success, message){
                                                                ModalElement.close(-1);
                                                                if (success){
                                                                    if (message.substr(0, 2) == "ok"){
                                                                        ModalElement.close();
                                                                    }
                                                                    else {
                                                                        ModalElement.alert({message: message});
                                                                    }
                                                                }
                                                                else {
                                                                    ModalElement.alert({message: message});
                                                                }
                                                            }
                                                        });
                                                    }
                                                },
                                                {
                                                    text: LanguageModule.text("txt_no"),
                                                    onclick: function(){
                                                        ModalElement.close();
                                                    }
                                                }
                                            ]
                                        });
                                    }, 100);
                                }
                            }
                            else {
                                hr.orgs.showEmployeePre(host, host.employeeid);
                            }
                        }
                        else if (message == "failed_userid") {
                            ModalElement.alert({message: LanguageModule.text("war_txt_this_user_has_linked_to_another_employee")});
                        }
                        else if (message == "failed_nationalidno") {
                            ModalElement.alert({message: LanguageModule.text("war_txt_nationalidno_was_used")});
                        }
                        else if (message == "war_txt_code_was_used"){
                            ModalElement.alert({
                                message: LanguageModule.text(message)
                            });
                        }
                        else if (message == "lock_system"){
                            ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                        }
                        else if (message.startsWith("edited") || message.startsWith("deleted")){
                            console.log(message);
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        };
        var data = getValueFunction();
        if (!data){
            return;
        }
        data.id = id;
        data.content = {};
        for (var i = 0; i < contentModule.getPeopleContentField.length; i++){
            data.content[contentModule.getPeopleContentField[i]] = data[contentModule.getPeopleContentField[i]];
        }
        if (id > 0){
            var index = host.database.employees.getIndex(id);
            var peopleField = ["fullname", "nationality", "nationalidno", "dayofbirth", "extrainfo", "available", "content", "userid", "available"];
            var employeeField = ["code", "position", "concurrent_position", "direct_manager", "indirect_manager"];
            var ischange = contentModule.isChanged(host.database.employees.items[index], data,
                employeeField
            );
            data.ischangeEmp = ischange;
            if (!ischange){
                ischange = contentModule.isChanged(host.database.employees.items[index], data,
                    peopleField
                );
            }
            if (!ischange){
                resolve();
                return;
            }
            data.peopleid = host.database.employees.items[index].peopleid;
            if (data.nationalidno != host.database.employees.items[index].nationalidno){
                ModalElement.showWindow({
                    bodycontent: DOMElement.div({
                        text: "Bạn sửa lại số CMND của nhân viên, thay đổi này là sửa lại dữ liệu nhập sai hay số CMND của nhân viên thay đổi?"
                    }),
                    buttonlist: [
                        {
                            text: "Sửa lỗi nhập sai",
                            onclick: function(){
                                ModalElement.close();
                                data.typeChangeNationalidno = "fixed";
                                saveFunc();
                            }
                        },
                        {
                            text: "Nhân viên đổi số CMND",
                            onclick: function(){
                                ModalElement.close();
                                data.typeChangeNationalidno = "change";
                                saveFunc();
                            }
                        }
                    ]
                });
                return;
            }
        }
        saveFunc();
    });
};

hr.orgs.addEmployeeClose = function(host, id, getValueFunction){
    return new Promise(function(resolve, reject){
        var data = getValueFunction("no_alert");
        if (!data) {
            resolve();
            return;
        }
        function closeFunc(){
            resolve();
        };
        if (id > 0){
            var index = host.database.employees.getIndex(id);
            data.content = {};
            for (var i = 0; i < contentModule.getPeopleContentField.length; i++){
                data.content[contentModule.getPeopleContentField[i]] = data[contentModule.getPeopleContentField[i]];
            }
            var ischange = contentModule.isChanged(host.database.employees.items[index], data,
                ["code", "extrainfo", "userid", "fullname", "nationality", "nationalidno", "dayofbirth", "content", "userid", "available"]
            );
        }
        else {
            var ischange = contentModule.isChanged({code: "", fullname: ""}, data, ["code", "fullname"]);
        }
        if (!ischange){
            closeFunc();
        }
        else {
            contentModule.questionChange({
                onclick: function(sel){
                    if (sel == 0){
                        hr.orgs.addEmployeeSave(host, id, getValueFunction).then(function(){
                            resolve();
                        });
                    }
                    else if (sel == 1){
                        closeFunc();
                    }
                }
            });
        }
    });
};

hr.orgs.addEmployee = function(host, orgid, id){
    host.employeeid = id;
    host.orgid = orgid;
    function redraw(value){
        var formContainer = DOMElement.div({});
        var  title;
        if (id == 0) title = LanguageModule.text("txt_add_employee");
        else title = LanguageModule.text("txt_edit_employee");
        theme.addEmployeeForm({
            title: title,
            formContainer: formContainer,
            frameList: host.frameList,
            func: {
                save: function(){
                    return hr.orgs.addEmployeeSave(host, id, getValueFunction);
                },
                close: function(){
                    return hr.orgs.addEmployeeClose(host, id, getValueFunction);
                }
            }
        });
        var getValueFunction;
        contentModule.makeFormData({
            typeid: host.form_config.employee.typeid,
            formid: host.form_config.employee.input_form,
            initialValue: value,
            formContainer: formContainer,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            var shareData = {};
            Object.defineProperty(shareData, "orgid", {
                get: function(){
                    return orgid;
                }
            });
            formContainer.formFragment.setContext("shareData", shareData);
            var userElt = absol.form.findComponent(formContainer.formFragment.view, {
                name: 'type_employee_userid',
                depth: false
            });
            if (userElt){
                var usersDic = {};
                for (var i = 0; i < host.database.employees.items.length; i++){
                    if (host.database.employees.items[i].id == id) continue;
                    usersDic[host.database.employees.items[i].userid] = true;
                }
                var userItems = [{value: 0, text: LanguageModule.text("txt_select_value")}];
                for (var i = 0; i < host.database.users.items.length; i++){
                    if (usersDic[host.database.users.items[i].homeid]) continue;
                    userItems.push({
                        value: host.database.users.items[i].homeid,
                        text: host.database.users.items[i].username + " - " + host.database.users.items[i].fullname
                    });
                }
                setTimeout(function(){
                    userElt.domElt.items = userItems;
                }, 500);
            }
            if (id > 0 && !host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                var content = [];
                contentModule.getDetailsExtends(host, content, host.form_config.employee.typeid);
                for (var i = 0; i < content.length; i++){
                    if (!host.organizational_employee_configs[content[i].localid]){
                        var elt = absol.form.findComponent(formContainer.formFragment.view, {
                            name: content[i].localid,
                            depth: false
                        });
                        if (elt){
                            elt.attributes.disabled = true;
                        }
                    }
                }
            }
        });
    };
    if (id > 0){
        var index = host.database.employees.getIndex(id);
        var dataEmp = EncodingClass.string.duplicate(host.database.employees.items[index]);
        host.peopleid = host.database.employees.items[index].peopleid;
        redraw(dataEmp);
    }
    else redraw();
};

hr.orgs.addEmployeePre = function(host, orgid, id){
    var loadData = function(){
        return new Promise(function(resolve, reject){
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "employee_load_by_id"},
                    {name: "orgid", value: orgid},
                    {name: "id", value: id}
                ],
                func: function(success, message){
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            var content = st.content;
                            if (id > 0){
                                var index = host.database.employees.getIndex(id);
                                // var positions = [];
                                content.concurrent_position = 0;
                                content.position = 0;
                                for (var i = 0; i < st.employee_positions.length; i++){
                                    if (st.employee_positions[i].type == "concurrent_position") {
                                        content.concurrent_position = st.employee_positions[i].positionid;
                                    }
                                    else {
                                        content.position = st.employee_positions[i].positionid;
                                    }
                                    // positions.push(st.employee_positions[i].positionid);
                                }
                                // content.positions = positions;
                                var direct_manager = 0, indirect_manager = 0;
                                for (var i = 0; i < st.employee_managers.length; i++){
                                    if (st.employee_managers[i].type == "direct") direct_manager = st.employee_managers[i].managerid;
                                    if (st.employee_managers[i].type == "indirect") indirect_manager = st.employee_managers[i].managerid;
                                }
                                content.direct_manager = direct_manager;
                                content.indirect_manager = indirect_manager;
                                host.database.employees.items[index] = content;
                                contentModule.makeEmployeeAllData(host);
                                if (st.peopleData[0].content == "") st.peopleData[0].content = {};
                                else st.peopleData[0].content = EncodingClass.string.toVariable(st.peopleData[0].content);
                                for (var i = 0; i < contentModule.getPeopleContentField.length; i++){
                                    st.peopleData[0][contentModule.getPeopleContentField[i]] = st.peopleData[0].content[contentModule.getPeopleContentField[i]];
                                }
                                var x = host.database.peoples.getIndex(st.peopleData[0].id);
                                if (x < 0) host.database.peoples.items.push(st.peopleData[0]);
                                else host.database.peoples.items[x] = st.peopleData[0];
                                for (var param in st.peopleData[0]) {
                                    if (param != "id" && param != "userid" && param != "available"){
                                        host.database.employees.items[index][param] = st.peopleData[0][param];
                                    }
                                }
                                if (host.database.employees.items[index].extrainfo == "") host.database.employees.items[index].extrainfo = {};
                                else host.database.employees.items[index].extrainfo = EncodingClass.string.toVariable(host.database.employees.items[index].extrainfo);
                            }
                            resolve(content);
                        }
                        else if (message == "war_txt_failed_data"){
                            ModalElement.alert({message: LanguageModule.text(message)});
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        });
    };
    var loadConfig = function(){
        return new Promise(function(resolve, reject){
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation || host.configEmployeeLoaded){
                resolve();
            }
            else {
                FormClass.api_call({
                    url: "database_load.php",
                    params: [{name: "task", value: "orgs_load_config_employee"}],
                    func: function(success, message){
                        if (success){
                            if (message.substr(0, 2) == "ok"){
                                var st = EncodingClass.string.toVariable(message.substr(2));
                                if (st.length > 0){
                                    host.organizational_employee_configs = EncodingClass.string.toVariable(st[0]["content"]);
                                }
                                else {
                                    host.organizational_employee_configs = systemconfig.organizational_employee_configs;
                                }
                                resolve();
                            }
                            else {
                                ModalElement.alert({message: message});
                            }
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                });
            }
        });
    };
    ModalElement.show_loading();
    Promise.all([loadData(), loadConfig()]).then(function(values){
        ModalElement.close(-1);
        hr.orgs.addEmployee(host, values[0].orgid, values[0].id);
    });
};

hr.orgs.deleteFamilyMember = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_delete_family_member.php",
            params: [{name: "id", value: id}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var index = host.database.employee_family_members.getIndex(id);
                        host.database.employee_family_members.items.splice(index, 1);
                        resolve();
                    }
                    else if (message == "failed_used"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_can_not_delete")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteFamilyMemberConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_family_members.getIndex(id);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_family_member"),
            message: LanguageModule.text2("war_txt_detele", [host.database.employee_family_members.items[index].fullname]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteFamilyMember(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addFamilyMemberSave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editFamilyMemberForm.getValue();
        if (!data) return;
        data.dayofbirth = EncodingClass.string.fromVariable(data.dayofbirth);
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["fullname", "dayofbirth", "sex", "relation", "comment", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
            data.employeeid = host.employeeid;
        }
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_family_member.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        content.dayofbirth = EncodingClass.string.toVariable(content.dayofbirth);
                        if (id > 0){
                            var index = host.database.employee_family_members.getIndex(id);
                            if (index < 0){
                                ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                                return;
                            }
                            host.database.employee_family_members.items[index] = content;
                        }
                        else {
                            host.database.employee_family_members.items.push(content);
                        }
                        ModalElement.close();
                        resolve(content);
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addFamilyMemberClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editFamilyMemberForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["fullname", "dayofbirth", "sex", "relation", "extrainfo"]
                );
            }
            else {
                var oldData = {
                    fullname: "",
                    relation: ""
                };
                var ischange = contentModule.isChanged(oldData, data,
                    ["fullname", "relation"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addFamilyMemberSave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editFamilyMember = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        function redraw(value){
            host.editFamilyMemberForm = DOMElement.div({});
            var  title;
            if (id == 0) title = LanguageModule.text("txt_add_family_member");
            else title = LanguageModule.text("txt_edit_family_member");
            ModalElement.showWindow({
                title: title,
                bodycontent: host.editFamilyMemberForm,
                buttonlist: [
                    {
                        text: LanguageModule.text("txt_save"),
                        onclick: function(){
                            hr.orgs.addFamilyMemberSave(host, id, dataEdit).then(function(value){
                                resolve(value)
                            });
                        }
                    },
                    {
                        text: LanguageModule.text("txt_cancel"),
                        onclick: function(){
                            hr.orgs.addFamilyMemberClose(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                    }
                ]
            });
            contentModule.makeFormData({
                typeid: host.form_config.family_members.typeid,
                formid: host.form_config.family_members.input_form,
                initialValue: value,
                formContainer: host.editFamilyMemberForm,
                typelists: host.database.typelists.items,
                variableType: "system"
            }).then(function(getValue){
                getValueFunction = getValue;
                absol.form.traversal(host.editFamilyMemberForm.formFragment.view, function(item){
                    if (item.node.tag === "TextInput") {
                        item.node.domElt.focus();
                        item.stop();
                        return;
                    }
                });
            });
            host.editFamilyMemberForm.getValue = function(){
                var data = getValueFunction();
                if (!data) return false;
                return data;
            };
        };
        if (id > 0){
            redraw(dataEdit);
        }
        else redraw();
    });
};

hr.orgs.editFamilyMemberPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "family_member_load_by_id"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        if (dataEdit.dayofbirth == "") dataEdit.dayofbirth = {level: null, value: null};
                        else dataEdit.dayofbirth = EncodingClass.string.toVariable(dataEdit.dayofbirth);
                        hr.orgs.editFamilyMember(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else if (message == "war_txt_failed_data"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_failed_data"),
                            func: function(){
                                host.frameList.removeLast();
                                hr.orgs.showEmployeePre(host, host.employeeid);
                            }
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({
                        message: message
                    });
                }
            }
        });
    });
};

hr.orgs.employeeGeneralInformation = function(host){
    host.drawGeneralInforFunc = function(){
        var index = host.database.employees.getIndex(host.employeeid);
        var dataEmp = EncodingClass.string.duplicate(host.database.employees.items[index]);
        contentModule.makeOutputFormData({
            typeid: host.form_config.employee.typeid,
            formid: host.form_config.employee.output_form,
            initialValue: dataEmp,
            formContainer: viewGeneralInformation,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){});
    };
    var params = {};
    var index = host.database.employees.getIndex(host.employeeid);
    var orgid = host.database.employees.items[index].orgid;
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation || systemconfig.userid == host.database.employees.items[index].userid){
        params.editFunc = function(){
            hr.orgs.addEmployeePre(host, orgid, host.employeeid);
        };
    }
    var res = theme.employeeGeneralInformationForm(params);
    var viewGeneralInformation = res.viewGeneralInformation;
    host.drawGeneralInforFunc();
    return res;
};

hr.orgs.getRowFamilyMember = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editFamilyMemberPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowFamilyMember(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteFamilyMemberConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.getRowTimekeepingCode = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editTimekeepingCodePre(host, content.id).then(function(value){
                rs(hr.orgs.getRowTimekeepingCode(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteTimekeepingCodeConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeFamilyMembers = function(host){
    var displayDic = {
        fullname: true,
        sex: true,
        relation: true,
        dayofbirth: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "family_members", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "family_member_list").then(function(value){
            var configColumnFamilyMembers = value;
            var data = [];
            for (var i = 0; i < host.database.employee_family_members.items.length; i++){
                data.push(hr.orgs.getRowFamilyMember(host, host.database.employee_family_members.items[i]));
            }
            var params = {
                configColumnFamilyMembers: configColumnFamilyMembers,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "family_member_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["family_member_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editFamilyMember(host, 0).then(function(value){
                        rs(hr.orgs.getRowFamilyMember(host, value));
                    });
                };
            }
            family_membersPage.redrawTable(params);
        });
    };
    var family_membersPage = theme.employeeFamilyMembersForm();
    redrawTableFunc();
    return family_membersPage;
};

hr.orgs.addWorkHistorySave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editWorkHistoryForm.getValue();
        if (!data) return;
        var dataWork_history = EncodingClass.string.duplicate(host.emp_work_history);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["position", "organization", "from_month", "to_month", "comment", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataWork_history.length; i++){
                if (dataWork_history[i].id == content.id){
                    dataWork_history[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataWork_history.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataWork_history.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataWork_history, data, "work_history").then(function(value){
            host.emp_work_history = dataWork_history;
            resolve(value);
        });
    });
};

hr.orgs.addWorkHistoryClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editWorkHistoryForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["position", "organization", "from_month", "to_month", "comment", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({position: "", organization: ""}, data,
                    ["position", "organization"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addWorkHistorySave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editWorkHistory = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editWorkHistoryForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_work_history"),
            bodycontent: host.editWorkHistoryForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addWorkHistorySave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addWorkHistoryClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.work_history.typeid,
            formid: host.form_config.work_history.input_form,
            initialValue: content,
            formContainer: host.editWorkHistoryForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(host.editWorkHistoryForm.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        host.editWorkHistoryForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteWorkHistory = function(host, content){
    return new Promise(function(resolve, reject){
        var dataWork_history = EncodingClass.string.duplicate(host.emp_work_history);
        for (var i = 0; i < dataWork_history.length; i++){
            if (dataWork_history[i].id == content.id){
                dataWork_history.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataWork_history, content, "work_history").then(function(value){
            host.emp_work_history = dataWork_history;
            resolve(value);
        });
    });
};

hr.orgs.deleteWorkHistoryConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_work_history"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteWorkHistory(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowWorkHistory = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editWorkHistory(host, content).then(function(value){
                rs(hr.orgs.getRowWorkHistory(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteWorkHistoryConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeWorkHistory = function(host){
    var displayDic = {
        position: true,
        organization: true,
        from_month: true,
        to_month: true,
        comment: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "work_history", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "work_history_list").then(function(value){
            var configColumnWork_history = value;
            var data = [];
            for (var i = 0; i < host.emp_work_history.length; i++){
                data.push(hr.orgs.getRowWorkHistory(host, host.emp_work_history[i]));
            }
            var params = {
                configColumnWork_history: configColumnWork_history,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "work_history_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["work_history_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editWorkHistory(host).then(function(value){
                        rs(hr.orgs.getRowWorkHistory(host, value));
                    });
                };
            }
            workHistoryPage.redrawTable(params);
        });
    };
    var workHistoryPage = theme.employeeWorkHistoryForm();
    redrawTableFunc();
    return workHistoryPage;
};

hr.orgs.addEducationHistorySave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editEducationHistoryForm.getValue();
        if (!data) return;
        var dataEducation_history = EncodingClass.string.duplicate(host.emp_education_history);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["major", "school", "degree", "from_month", "to_month", "comment", "top_level", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataEducation_history.length; i++){
                if (dataEducation_history[i].id == content.id){
                    dataEducation_history[i] = data;
                    x = 1;
                    if (!data.top_level) continue;
                }
                else {
                    if (data.top_level) dataEducation_history[i].top_level = false;
                }
            }
            if (!x){
                if (data.top_level){
                    for (var i = 0; i < dataEducation_history.length; i++){
                        dataEducation_history[i].top_level = false;
                    }
                }
                data.id = (new Date()).getTime();
                dataEducation_history.push(data);
            }
        }
        else {
            if (data.top_level){
                for (var i = 0; i < dataEducation_history.length; i++){
                    dataEducation_history[i].top_level = false;
                }
            }
            data.id = (new Date()).getTime();
            dataEducation_history.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataEducation_history, data, "education_history").then(function(value){
            host.emp_education_history = dataEducation_history;
            resolve(value);
        });
    });
};

hr.orgs.addEducationHistoryClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editEducationHistoryForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["major", "school", "degree", "from_month", "to_month", "comment", "top_level", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({major: "", school: "", degree: ""}, data,
                    ["major", "school", "degree"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addEducationHistorySave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editEducationHistory = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editEducationHistoryForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_education_history"),
            bodycontent: host.editEducationHistoryForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addEducationHistorySave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addEducationHistoryClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.education_history.typeid,
            formid: host.form_config.education_history.input_form,
            initialValue: content,
            formContainer: host.editEducationHistoryForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(host.editEducationHistoryForm.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        host.editEducationHistoryForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteEducationHistory = function(host, content){
    return new Promise(function(resolve, reject){
        var dataEducation_history = EncodingClass.string.duplicate(host.emp_education_history);
        for (var i = 0; i < dataEducation_history.length; i++){
            if (dataEducation_history[i].id == content.id){
                dataEducation_history.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataEducation_history, content, "education_history").then(function(value){
            host.emp_education_history = dataEducation_history;
            resolve(value);
        });
    });
};

hr.orgs.deleteEducationHistoryConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_education_history"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEducationHistory(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowEducationHistory = function(host, content, redrawTableFunc){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(){
            hr.orgs.editEducationHistory(host, content).then(function(value){
                redrawTableFunc();
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteEducationHistoryConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeEducationHistory = function(host){
    var displayDic = {
        major: true,
        school: true,
        degree: true,
        from_month: true,
        to_month: true,
        comment: true,
        top_level: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "education_history", displayDic);
    var redrawTableFunc = function(){
        host.emp_education_history.sort(function(a, b){
            return a.from_month.getTime() - b.from_month.getTime();
        });
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "education_history_list").then(function(value){
            var configColumnEducation_history = value;
            var data = [];
            for (var i = 0; i < host.emp_education_history.length; i++){
                data.push(hr.orgs.getRowEducationHistory(host, host.emp_education_history[i], redrawTableFunc));
            }
            var params = {
                configColumnEducation_history: configColumnEducation_history,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "education_history_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["education_history_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(){
                    hr.orgs.editEducationHistory(host).then(function(value){
                        redrawTableFunc();
                    });
                };
            }
            educationHistoryPage.redrawTable(params);
        });
    };
    var educationHistoryPage = theme.employeeEducationHistoryForm();
    redrawTableFunc();
    return educationHistoryPage;
};

hr.orgs.addSkillSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editSkillForm.getValue();
        if (!data) return;
        var dataSkill = EncodingClass.string.duplicate(host.emp_skill);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["skill", "level", "comment", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataSkill.length; i++){
                if (dataSkill[i].id == content.id){
                    dataSkill[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataSkill.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataSkill.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataSkill, data, "skill").then(function(value){
            host.emp_skill = dataSkill;
            resolve(value);
        });
    });
};

hr.orgs.addSkillClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editSkillForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["skill", "level", "comment", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({skill: "", level: 0}, data,
                    ["skill", "level", "comment"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addSkillSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editSkill = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editSkillForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_skill"),
            bodycontent: host.editSkillForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addSkillSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addSkillClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.skill.typeid,
            formid: host.form_config.skill.input_form,
            initialValue: content,
            formContainer: host.editSkillForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(host.editSkillForm.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        host.editSkillForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteSkill = function(host, content){
    return new Promise(function(resolve, reject){
        var dataSkill = EncodingClass.string.duplicate(host.emp_skill);
        for (var i = 0; i < dataSkill.length; i++){
            if (dataSkill[i].id == content.id){
                dataSkill.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataSkill, content, "skill").then(function(value){
            host.emp_skill = dataSkill;
            resolve(value);
        });
    });
};

hr.orgs.deleteSkillConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_skill"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteSkill(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowSkill = function(host, content){
    console.log(content);
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editSkill(host, content).then(function(value){
                rs(hr.orgs.getRowSkill(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteSkillConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeSkill = function(host){
    var displayDic = {
        skill: true,
        level: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "skill", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "skill_list").then(function(value){
            var configColumnSkill = value;
            var data = [];
            for (var i = 0; i < host.emp_skill.length; i++){
                data.push(hr.orgs.getRowSkill(host, host.emp_skill[i]));
            }
            var params = {
                configColumnSkill: configColumnSkill,
                data: data,
                filterColumnFunc: function(){
                    console.log(3454);
                    contentModule.userColumnConfigForm({
                        type: "skill_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["skill_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editSkill(host).then(function(value){
                        rs(hr.orgs.getRowSkill(host, value));
                    });
                };
            }
            skillPage.redrawTable(params);
        });
    };
    var skillPage = theme.employeeSkillForm();
    redrawTableFunc();
    return skillPage;
};

hr.orgs.addSocialNetworkSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editSocialNetworkForm.getValue();
        if (!data) return;
        var dataSocialNetwork = EncodingClass.string.duplicate(host.emp_social_network);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["name", "account", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataSocialNetwork.length; i++){
                if (dataSocialNetwork[i].id == content.id){
                    dataSocialNetwork[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataSocialNetwork.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataSocialNetwork.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataSocialNetwork, data, "social_network").then(function(value){
            host.emp_social_network = dataSocialNetwork;
            resolve(value);
        });
    });
};

hr.orgs.addSocialNetworkClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editSocialNetworkForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["type", "account", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({type: "", account: ""}, data,
                    ["type", "account"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addSocialNetworkSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editSocialNetwork = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editSocialNetworkForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_social_network"),
            bodycontent: host.editSocialNetworkForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addSocialNetworkSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addSocialNetworkClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.social_network.typeid,
            formid: host.form_config.social_network.input_form,
            initialValue: content,
            formContainer: host.editSocialNetworkForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(host.editSocialNetworkForm.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        host.editSocialNetworkForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteSocialNetwork = function(host, content){
    return new Promise(function(resolve, reject){
        var dataSocialNetwork = EncodingClass.string.duplicate(host.emp_social_network);
        for (var i = 0; i < dataSocialNetwork.length; i++){
            if (dataSocialNetwork[i].id == content.id){
                dataSocialNetwork.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataSocialNetwork, content, "social_network").then(function(value){
            host.emp_social_network = dataSocialNetwork;
            resolve(value);
        });
    });
};

hr.orgs.deleteSocialNetworkConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_social_network"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteSocialNetwork(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowSocialNetwork = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editSocialNetwork(host, content).then(function(value){
                rs(hr.orgs.getRowSocialNetwork(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteSocialNetworkConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeSocialNetwork = function(host){
    var displayDic = {
        name: true,
        account: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "social_network", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "social_network_list").then(function(value){
            var configColumnSocialNetwork = value;
            var data = [];
            for (var i = 0; i < host.emp_social_network.length; i++){
                data.push(hr.orgs.getRowSocialNetwork(host, host.emp_social_network[i]));
            }
            var params = {
                configColumnSocialNetwork: configColumnSocialNetwork,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "social_network_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["social_network_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editSocialNetwork(host).then(function(value){
                        rs(hr.orgs.getRowSocialNetwork(host, value));
                    });
                };
            }
            socialNetworkPage.redrawTable(params);
        });
    };
    var socialNetworkPage = theme.employeeSocialNetworkForm();
    redrawTableFunc();
    return socialNetworkPage;
};

hr.orgs.addPhoneSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editPhoneForm.getValue();
        if (!data) return;
        var dataPhone = EncodingClass.string.duplicate(host.emp_phone);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["type", "number", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataPhone.length; i++){
                if (dataPhone[i].id == content.id){
                    dataPhone[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataPhone.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataPhone.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataPhone, data, "phone").then(function(value){
            host.emp_phone = dataPhone;
            resolve(value);
        });
    });
};

hr.orgs.addPhoneClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editPhoneForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["type", "number", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({type: 0, number: 0}, data,
                    ["type", "number"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addPhoneSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editPhone = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editPhoneForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_phone"),
            bodycontent: host.editPhoneForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addPhoneSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addPhoneClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.phone.typeid,
            formid: host.form_config.phone.input_form,
            initialValue: content,
            formContainer: host.editPhoneForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
        });
        host.editPhoneForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deletePhone = function(host, content){
    return new Promise(function(resolve, reject){
        var dataPhone = EncodingClass.string.duplicate(host.emp_phone);
        for (var i = 0; i < dataPhone.length; i++){
            if (dataPhone[i].id == content.id){
                dataPhone.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataPhone, content, "phone").then(function(value){
            host.emp_phone = dataPhone;
            resolve(value);
        });
    });
};

hr.orgs.deletePhoneConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_phone"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deletePhone(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowPhone = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editPhone(host, content).then(function(value){
                rs(hr.orgs.getRowPhone(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deletePhoneConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeePhone = function(host){
    var displayDic = {
        type: true,
        number: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "phone", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "phone_list").then(function(value){
            var configColumnPhone = value;
            var data = [];
            for (var i = 0; i < host.emp_phone.length; i++){
                data.push(hr.orgs.getRowPhone(host, host.emp_phone[i]))
            }
            var params = {
                data: data,
                configColumnPhone: configColumnPhone,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "phone_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["phone_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation) params.addFunc = function(rs){
                hr.orgs.editPhone(host, 0).then(function(value){
                    rs(hr.orgs.getRowPhone(host, value));
                });
            };
            phonePage.redrawTable(params);
        });
    };
    var phonePage = theme.employeePhoneForm();
    redrawTableFunc();
    return phonePage;
};

hr.orgs.addEmailSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editEmailForm.getValue();
        if (!data) return;
        var dataEmail = EncodingClass.string.duplicate(host.emp_email);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["type", "address", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataEmail.length; i++){
                if (dataEmail[i].id == content.id){
                    dataEmail[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataEmail.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataEmail.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataEmail, data, "email").then(function(value){
            host.emp_email = dataEmail;
            resolve(value);
        });
    });
};

hr.orgs.addEmailClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editEmailForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["type", "address", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({type: 0, address: ""}, data,
                    ["type", "address"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addEmailSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editEmail = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editEmailForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_email"),
            bodycontent: host.editEmailForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addEmailSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addEmailClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.email.typeid,
            formid: host.form_config.email.input_form,
            initialValue: content,
            formContainer: host.editEmailForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
        });
        host.editEmailForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteEmail = function(host, content){
    return new Promise(function(resolve, reject){
        var dataEmail = EncodingClass.string.duplicate(host.emp_email);
        for (var i = 0; i < dataEmail.length; i++){
            if (dataEmail[i].id == content.id){
                dataEmail.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataEmail, content, "email").then(function(value){
            host.emp_email = dataEmail;
            resolve(value);
        });
    });
};

hr.orgs.deleteEmailConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_email"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmail(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowEmail = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editEmail(host, content).then(function(value){
                rs(hr.orgs.getRowEmail(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteEmailConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeEmail = function(host){
    var displayDic = {
        type: true,
        address: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "email", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "email_list").then(function(value){
            var configColumnEmail = value;
            var data = [];
            for (var i = 0; i < host.emp_email.length; i++){
                data.push(hr.orgs.getRowEmail(host, host.emp_email[i]))
            }
            var params = {
                data: data,
                configColumnEmail: configColumnEmail,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "email_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["email_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation) params.addFunc = function(rs){
                hr.orgs.editEmail(host, 0).then(function(value){
                    rs(hr.orgs.getRowEmail(host, value));
                });
            };
            emailPage.redrawTable(params);
        });
    };
    var emailPage = theme.employeeEmailForm();
    redrawTableFunc();
    return emailPage;
};

hr.orgs.addAdditionalPersonalDocumentSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editAdditionalPersonalDocumentForm.getValue();
        if (!data) return;
        var dataAdditionalPersonalDocument = EncodingClass.string.duplicate(host.emp_additional_personal_document);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["type", "number", "place_of_issue", "date_of_issue", "expire_time", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataAdditionalPersonalDocument.length; i++){
                if (dataAdditionalPersonalDocument[i].id == content.id){
                    dataAdditionalPersonalDocument[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataAdditionalPersonalDocument.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataAdditionalPersonalDocument.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataAdditionalPersonalDocument, data, "additional_personal_document").then(function(value){
            host.emp_additional_personal_document = dataAdditionalPersonalDocument;
            resolve(value);
        });
    });
};

hr.orgs.addAdditionalPersonalDocumentClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editAdditionalPersonalDocumentForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["type", "number", "place_of_issue", "date_of_issue", "expire_time", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({type: 0, number: ""}, data,
                    ["type", "number"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addAdditionalPersonalDocumentSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editAdditionalPersonalDocument = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editAdditionalPersonalDocumentForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_additional_personal_document"),
            bodycontent: host.editAdditionalPersonalDocumentForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addAdditionalPersonalDocumentSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addAdditionalPersonalDocumentClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.personal_document.typeid,
            formid: host.form_config.personal_document.input_form,
            initialValue: content,
            formContainer: host.editAdditionalPersonalDocumentForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
        });
        host.editAdditionalPersonalDocumentForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteAdditionalPersonalDocument = function(host, content){
    return new Promise(function(resolve, reject){
        var dataAdditionalPersonalDocument = EncodingClass.string.duplicate(host.emp_additional_personal_document);
        for (var i = 0; i < dataAdditionalPersonalDocument.length; i++){
            if (dataAdditionalPersonalDocument[i].id == content.id){
                dataAdditionalPersonalDocument.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataAdditionalPersonalDocument, content, "additional_personal_document").then(function(value){
            host.emp_additional_personal_document = dataAdditionalPersonalDocument;
            resolve(value);
        });
    });
};

hr.orgs.deleteAdditionalPersonalDocumentConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_additional_personal_document"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteAdditionalPersonalDocument(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowAdditionalPersonalDocument = function(host, content){
    var func = {};
    if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        func.edit = function(rs){
            hr.orgs.editAdditionalPersonalDocument(host, content).then(function(value){
                rs(hr.orgs.getRowAdditionalPersonalDocument(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteAdditionalPersonalDocumentConfirm(host, content).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeAdditionalPersonalDocument = function(host){
    var displayDic = {
        type: true,
        number: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "personal_document", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "additional_personal_document_list").then(function(value){
            var configColumnAdditionalPersonalDocument = value;
            var data = [];
            for (var i = 0; i < host.emp_additional_personal_document.length; i++){
                data.push(hr.orgs.getRowAdditionalPersonalDocument(host, host.emp_additional_personal_document[i]));
            }
            var params = {
                configColumnAdditionalPersonalDocument: configColumnAdditionalPersonalDocument,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "additional_personal_document_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["additional_personal_document_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_general_information_abilities_contact_communications_other_infomation){
                params.addFunc = function(rs){
                    hr.orgs.editAdditionalPersonalDocument(host).then(function(value){
                        rs(hr.orgs.getRowAdditionalPersonalDocument(host, value));
                    });
                };
            }
            additionalPersonalDocumentPage.redrawTable(params);
        });
    };
    var additionalPersonalDocumentPage = theme.employeeAdditionalPersonalDocumentForm();
    redrawTableFunc();
    return additionalPersonalDocumentPage;
};

hr.orgs.addBankAccountSave = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editBankAccountForm.getValue();
        if (!data) return;
        var dataBankAccount = EncodingClass.string.duplicate(host.emp_bank_account);
        if (content){
            var ischange = contentModule.isChanged(content, data,
                ["account_number", "account_holder_name", "bank_name", "agency", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.id = content.id;
            var x = 0;
            for (var i = 0; i < dataBankAccount.length; i++){
                if (dataBankAccount[i].id == content.id){
                    dataBankAccount[i] = data;
                    x = 1;
                    break;
                }
            }
            if (!x){
                data.id = (new Date()).getTime();
                dataBankAccount.push(data);
            }
        }
        else {
            data.id = (new Date()).getTime();
            dataBankAccount.push(data);
        }
        hr.orgs.save_emp_extradata(host, dataBankAccount, data, "bank_account").then(function(value){
            host.emp_bank_account = dataBankAccount;
            resolve(value);
        });
    });
};

hr.orgs.addBankAccountClose = function(host, content){
    return new Promise(function(resolve, reject){
        var data = host.editBankAccountForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (content){
                var ischange = contentModule.isChanged(content, data,
                    ["account_number", "account_holder_name", "bank_name", "agency", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({
                        account_number: "",
                        account_holder_name: "",
                        bank_name: "",
                        agency: ""
                    },
                    data,
                    ["account_number", "account_holder_name", "bank_name", "agency"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addBankAccountSave(host, content).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editBankAccount = function(host, content){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editBankAccountForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_bank_account"),
            bodycontent: host.editBankAccountForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addBankAccountSave(host, content).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addBankAccountClose(host, content).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.bank_account.typeid,
            formid: host.form_config.bank_account.input_form,
            initialValue: content,
            formContainer: host.editBankAccountForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            absol.form.traversal(host.editBankAccountForm.formFragment.view, function(item){
                if (item.node.tag === "TextInput") {
                    item.node.domElt.focus();
                    item.stop();
                    return;
                }
            });
        });
        host.editBankAccountForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.deleteBankAccount = function(host, content){
    return new Promise(function(resolve, reject){
        var dataBankAccount = EncodingClass.string.duplicate(host.emp_bank_account);
        for (var i = 0; i < dataBankAccount.length; i++){
            if (dataBankAccount[i].id == content.id){
                dataBankAccount.splice(i, 1);
                break;
            }
        }
        hr.orgs.save_emp_extradata(host, dataBankAccount, content, "bank_account").then(function(value){
            host.emp_bank_account = dataBankAccount;
            resolve(value);
        });
    });
};

hr.orgs.deleteBankAccountConfirm = function(host, content){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_bank_account"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteBankAccount(host, content).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowBankAccount = function(host, content){
    var func = {};
    if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        func.edit = function(rs){
            hr.orgs.editBankAccount(host, content).then(function(value){
                rs(hr.orgs.getRowBankAccount(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteBankAccountConfirm(host, content).then(function(value){
                rs(value);
            });
        }
    };
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeBankAccount = function(host){
    var displayDic = {
        account_number: true,
        account_holder_name: true,
        bank_name: true,
        agency: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "bank_account", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "bank_account_list").then(function(value){
            var configColumnBank_account = value;
            var data = [];
            for (var i = 0; i < host.emp_bank_account.length; i++){
                data.push(hr.orgs.getRowBankAccount(host, host.emp_bank_account[i]));
            }
            var params = {
                configColumnBank_account: configColumnBank_account,
                data: data,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "bank_account_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["bank_account_list"] = value;
                        redrawTableFunc();
                    });
                }
            };
            if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
                params.addFunc = function(rs){
                    hr.orgs.editBankAccount(host, 0).then(function(value){
                        rs(hr.orgs.getRowBankAccount(host, value));
                    });
                }
            }
            bankAccountPage.redrawTable(params);
        });
    };
    var bankAccountPage = theme.employeeBankAccountForm({});
    redrawTableFunc();
    return bankAccountPage;
};

hr.orgs.employeeAbility = function(host){
    return theme.employeeAbilityForm({
        work_history: hr.orgs.employeeWorkHistory(host),
        education_history: hr.orgs.employeeEducationHistory(host),
        skill: hr.orgs.employeeSkill(host)
    });
};

hr.orgs.addEmploymentContractSave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editEmploymentContractForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["contractid", "effective_date_from", "effective_date_to", "attachments", "available", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.available = data.available? 1: 0;
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        data.attachments = EncodingClass.string.fromVariable(data.attachments);
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_employee_employment_contracts.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        content.attachments = EncodingClass.string.toVariable(content.attachments);
                        if (content.available){
                            host.database.employment_contracts.items.forEach(function(item){
                                item.available = 0;
                            });
                        }
                        host.dataEmployment_contractEdit = content;
                        if (id > 0){
                            var index = host.database.employment_contracts.getIndex(id);
                            if (index < 0){
                                ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                                return;
                            }
                            host.database.employment_contracts.items[index] = content;
                            host.drawEmployment_contractGeneralInforFunc();
                        }
                        else {
                            host.database.employment_contracts.items.push(content);
                        }
                        ModalElement.close();
                        host.drawEmploymentContractTableFunc();
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else if (message == "contract_number_was_exist"){
                        ModalElement.alert({
                            message: LanguageModule.text("txt_contract_number_was_exist")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addEmploymentContractClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editEmploymentContractForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["contractid", "effective_date_from", "attachments", "extrainfo", "available"]
                );
            }
            else {
                var ischange = contentModule.isChanged({contractid: 0, effective_date_from: new Date()}, data,
                    ["contractid", "effective_date_from"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addEmploymentContractSave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editEmploymentContract = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editEmploymentContractForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_employment_contract"),
            bodycontent: host.editEmploymentContractForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addEmploymentContractSave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addEmploymentContractClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.employment_contracts.typeid,
            formid: host.form_config.employment_contracts.input_form,
            initialValue: dataEdit,
            formContainer: host.editEmploymentContractForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editEmploymentContractForm.formFragment.setContext('host', host);
            host.editEmploymentContractForm.formFragment.setContext('id', id);
            host.editEmploymentContractForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editEmploymentContractForm.formFragment.view, {
                    name: 'type_employee_employment_contract_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editEmploymentContractForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editEmploymentContractPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_employment_contracts"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var cIndex = host.database.employment_contract_types.getIndex(dataEdit.contractid);
                        if (cIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        if (dataEdit.attachments === "") dataEdit.attachments = [];
                        else if (EncodingClass.type.isString(dataEdit.attachments)){
                            dataEdit.attachments = EncodingClass.string.toVariable(dataEdit.attachments);
                        }
                        dataEdit.description = host.database.employment_contract_types.items[cIndex].description;
                        hr.orgs.editEmploymentContract(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.showEmploymentContract = function(host, id){
    var params = {
        id: id,
        closeFunc: function(){
            host.frameList.removeLast();
        }
    };
    if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        params.editFunc = function(){
            hr.orgs.editEmploymentContractPre(host, id);
        };
    }
    hr.employment_contract.showEmployment_contractFunc(host, params);
};

hr.orgs.showEmploymentContractPre = function(host, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "employee_load_employment_contracts"},
            {name: "id", value: id}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    host.dataEmployment_contractEdit = EncodingClass.string.toVariable(message.substr(2));
                    if (host.dataEmployment_contractEdit.extrainfo == "") host.dataEmployment_contractEdit.extrainfo = {};
                    else host.dataEmployment_contractEdit.extrainfo = EncodingClass.string.toVariable(host.dataEmployment_contractEdit.extrainfo);
                    var cIndex = host.database.employment_contract_types.getIndex(host.dataEmployment_contractEdit.contractid);
                    if (cIndex < 0){
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                        return;
                    }
                    if (host.dataEmployment_contractEdit.attachments === "") host.dataEmployment_contractEdit.attachments = [];
                    else if (EncodingClass.type.isString(host.dataEmployment_contractEdit.attachments)){
                        host.dataEmployment_contractEdit.attachments = EncodingClass.string.toVariable(host.dataEmployment_contractEdit.attachments);
                    }
                    host.dataEmployment_contractEdit.description = host.database.employment_contract_types.items[cIndex].description;
                    hr.orgs.showEmploymentContract(host, id);
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.deleteEmploymentContractConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employment_contracts.getIndex(id);
        var pIndex = host.database.employment_contract_types.getIndex(host.database.employment_contracts.items[index].contractid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_employment_contract"),
            message: LanguageModule.text2("war_txt_detele", [host.database.employment_contract_types.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmploymentContract(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowEmploymentContract = function(host, content){
    var func = {
        view: function(){
            hr.orgs.showEmploymentContractPre(host, content.id);
        }
    };
    if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        func.delete = function(rs){
            hr.orgs.deleteEmploymentContractConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employmentContracts = function(host){
    var displayDic = {
        contractid: true,
        effective_date_from: true,
        effective_date_to: true,
        available: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "employment_contracts", displayDic);
    host.drawEmploymentContractTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "org_employment_contract_list").then(function(value){
            var configColumnEmployment_contract = value;
            var data = [];
            for (var i = 0; i < host.database.employment_contracts.items.length; i++){
                data.push(hr.orgs.getRowEmploymentContract(host, host.database.employment_contracts.items[i]));
            }
            var params = {
                data: data,
                configColumnEmployment_contract: configColumnEmployment_contract,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "org_employment_contract_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["org_employment_contract_list"] = value;
                        host.drawEmploymentContractTableFunc();
                    });
                }
            };
            if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
                params.addFunc = function(){
                    hr.orgs.editEmploymentContract(host, 0);
                }
            }
            employmentContractPage.redrawTable(params);
        });
    };
    var employmentContractPage = theme.employmentContractsForm({});
    host.drawEmploymentContractTableFunc();
    return employmentContractPage;
};

hr.orgs.employeeSalaryInformationAndAccount = function(host){
    return theme.employeeSalaryInformationAndAccountForm({
        employment_contracts: hr.orgs.employmentContracts(host),
        salary_decisions: hr.orgs.employeeSalaryDecision(host)
        // bank_account: hr.orgs.employeeBankAccount(host)
    });
};

hr.orgs.employeeCommunication = function(host){
    return theme.employeeCommunicationForm({
        phone: hr.orgs.employeePhone(host),
        email: hr.orgs.employeeEmail(host)
    });
};

hr.orgs.employeeOtherInformation = function(host){
    return theme.employeeOtherInformationForm({
        additional_personal_document: hr.orgs.employeeAdditionalPersonalDocument(host),
        family_members: hr.orgs.employeeFamilyMembers(host),
        timekeeping_code: hr.orgs.employeeTimekeepingCode(host)
    });
};

hr.orgs.addSalaryDecisionSave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editSalaryDecisionForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["effective_date", "position", "salary_grade", "salary_amount", "calculated_on", "reference_number", "decision_date", "attachments", "extrainfo", "available"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.available = data.available? 1: 0;
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        data.attachments = EncodingClass.string.fromVariable(data.attachments);
        data.files = [];
        ModalElement.show_loading();
        FormClass.api_call({
            url: "orgs_save_employee_salary_decisions.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        content.attachments = EncodingClass.string.toVariable(content.attachments);
                        if (content.available){
                            host.database.employee_salary_decisions.items.forEach(function(item){
                                if (item.policyid == data.policyid) item.available = 0;
                            });
                        }
                        host.dataSalary_decisionsEdit = content;
                        if (id > 0){
                            var index = host.database.employee_salary_decisions.getIndex(id);
                            if (index < 0){
                                ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                                return;
                            }
                            host.database.employee_salary_decisions.items[index] = content;
                            host.drawSalaryDecisionGeneralInforFunc();
                        }
                        else {
                            host.database.employee_salary_decisions.items.push(content);
                        }
                        host.drawSalaryDecisionTableFunc();
                        ModalElement.close();
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message.startsWith("edited") || message.startsWith("deleted")){
                        console.log(message);
                        ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                    }
                    else if (message == "war_txt_code_was_used"){
                        ModalElement.alert({
                            message: LanguageModule.text(message)
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addSalaryDecisionClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editSalaryDecisionForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["effective_date", "position", "salary_grade", "salary_amount", "calculated_on", "reference_number", "decision_date", "attachments", "extrainfo", "available"]
                );
            }
            else {
                var ischange = contentModule.isChanged({effective_date: new Date()}, data,
                    ["effective_date"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addSalaryDecisionSave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editSalaryDecision = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editSalaryDecisionForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_salary_decision"),
            bodycontent: host.editSalaryDecisionForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addSalaryDecisionSave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addSalaryDecisionClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.salary_decisions_applied_to_employee.typeid,
            formid: host.form_config.salary_decisions_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editSalaryDecisionForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editSalaryDecisionForm.formFragment.setContext('host', host);
            host.editSalaryDecisionForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editSalaryDecisionForm.formFragment.view, {
                    name: 'type_salary_decisions_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editSalaryDecisionForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editSalaryDecisionPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_salary_decisions"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        if (dataEdit.attachments === "") dataEdit.attachments = [];
                        else if (EncodingClass.type.isString(dataEdit.attachments)){
                            dataEdit.attachments = EncodingClass.string.toVariable(dataEdit.attachments);
                        }
                        hr.orgs.editSalaryDecision(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteSalaryDecisionConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_salary_decision"),
            message: LanguageModule.text2("war_txt_detele", [""]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeeSalaryDecision(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.salary_decisions.showSalaryDecision = function(host, id){
    var params = {
        id: id,
        closeFunc: function(){
            host.frameList.removeLast();
        }
    };
    if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        params.editFunc = function(){
            hr.orgs.editSalaryDecisionPre(host, id);
        };
    }
    hr.salary_decisions.showSalary_decisionsFunc(host, params);
};

hr.orgs.showSalaryDecisionPre = function(host, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "employee_load_salary_decisions"},
            {name: "id", value: id}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    host.dataSalary_decisionsEdit = EncodingClass.string.toVariable(message.substr(2));
                    if (host.dataSalary_decisionsEdit.extrainfo == "") host.dataSalary_decisionsEdit.extrainfo = {};
                    else host.dataSalary_decisionsEdit.extrainfo = EncodingClass.string.toVariable(host.dataSalary_decisionsEdit.extrainfo);
                    if (host.dataSalary_decisionsEdit.attachments === "") host.dataSalary_decisionsEdit.attachments = [];
                    else if (EncodingClass.type.isString(host.dataSalary_decisionsEdit.attachments)){
                        host.dataSalary_decisionsEdit.attachments = EncodingClass.string.toVariable(host.dataSalary_decisionsEdit.attachments);
                    }
                    hr.salary_decisions.showSalaryDecision(host, id);
                }
                else if (message == "war_txt_failed_data"){
                    ModalElement.alert({
                        message: LanguageModule.text("war_txt_failed_data")
                    });
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.getRowSalaryDecision = function(host, content){
    var func = {
        view: function(){
            hr.orgs.showSalaryDecisionPre(host, content.id);
        }
    };
    if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        func.delete = function(rs){
            hr.orgs.deleteSalaryDecisionConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeSalaryDecision = function(host){
    var displayDic = {
        effective_date: true,
        position: true,
        salary_grade: true,
        basic_salary_amount: true,
        gross_salary_amount: true,
        calculated_on: true,
        available: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "salary_decisions_applied_to_employee", displayDic);
    host.drawSalaryDecisionTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "org_salary_decision_list").then(function(value){
            var configColumnSalary_decision = value;
            var data = [];
            for (var i = 0; i < host.database.employee_salary_decisions.items.length; i++){
                data.push(hr.orgs.getRowSalaryDecision(host, host.database.employee_salary_decisions.items[i]));
            }
            var params = {
                data: data,
                configColumnSalary_decision: configColumnSalary_decision,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "org_salary_decision_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["org_salary_decision_list"] = value;
                        host.drawSalaryDecisionTableFunc();
                    });
                }
            };
            if (host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
                params.addFunc = function(){
                    hr.orgs.editSalaryDecision(host, 0);
                }
            }
            salaryDecisionPage.redrawTable(params);
        });
    };
    var salaryDecisionPage = theme.employeeSalaryDecisionForm({});
    host.drawSalaryDecisionTableFunc();
    return salaryDecisionPage;
};

hr.orgs.addAdvancePaymentPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editAdvancePaymentPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "advance_payment";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableAdvancePaymentPoliciesFunc();
            }
        });
    });
};

hr.orgs.addAdvancePaymentPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editAdvancePaymentPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addAdvancePaymentPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editAdvancePaymentPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editAdvancePaymentPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_advance_payment_policy"),
            bodycontent: host.editAdvancePaymentPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addAdvancePaymentPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addAdvancePaymentPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.advance_payment_policies_applied_to_employee.typeid,
            formid: host.form_config.advance_payment_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editAdvancePaymentPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editAdvancePaymentPolicyForm.formFragment.setContext('host', host);
            host.editAdvancePaymentPolicyForm.formFragment.setContext('id', id);
            host.editAdvancePaymentPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editAdvancePaymentPolicyForm.formFragment.view, {
                    name: 'type_advance_payment_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editAdvancePaymentPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editAdvancePaymentPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.advance_payment_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.advance_payment_policies.items[pIndex].description;
                        hr.orgs.editAdvancePaymentPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteAdvancePaymentPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.advance_payment_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_advance_payment_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.advance_payment_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowAdvancePaymentPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editAdvancePaymentPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowAdvancePaymentPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteAdvancePaymentPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.advance_payment_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "advance_payment", host.database.advance_payment_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeAdvancePaymentPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "advance_payment_policies_applied_to_employee", displayDic);
    host.redrawTableAdvancePaymentPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "advance_payment_policies_applied_to_employee_list").then(function(value){
            var configColumnAdvancePaymentPolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "advance_payment") continue;
                row = hr.orgs.getRowAdvancePaymentPolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnAdvancePaymentPolicies: configColumnAdvancePaymentPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "advance_payment_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["advance_payment_policies_applied_to_employee_list"] = value;
                        host.redrawTableAdvancePaymentPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editAdvancePaymentPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowAdvancePaymentPolicy(host, value));
                    });
                };
            }
            advance_payment_policiesPage.redrawTable(params);
        });
    };
    var advance_payment_policiesPage = theme.employeeAdvancePaymentPoliciesForm({});
    host.redrawTableAdvancePaymentPoliciesFunc();
    return advance_payment_policiesPage;
};

hr.orgs.addBonusPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editBonusPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "bonus";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableBonusPoliciesFunc();
            }
        });
    });
};

hr.orgs.addBonusPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editBonusPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addBonusPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editBonusPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editBonusPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_bonus_policy"),
            bodycontent: host.editBonusPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addBonusPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addBonusPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.bonus_policies_applied_to_employee.typeid,
            formid: host.form_config.bonus_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editBonusPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editBonusPolicyForm.formFragment.setContext('host', host);
            host.editBonusPolicyForm.formFragment.setContext('id', id);
            host.editBonusPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editBonusPolicyForm.formFragment.view, {
                    name: 'type_bonus_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editBonusPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editBonusPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.bonus_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.bonus_policies.items[pIndex].description;
                        hr.orgs.editBonusPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteBonusPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.bonus_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_bonus_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.bonus_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowBonusPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editBonusPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowBonusPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteBonusPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeBonusPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "bonus_policies_applied_to_employee", displayDic);
    host.redrawTableBonusPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "bonus_policies_applied_to_employee_list").then(function(value){
            var configColumnBonusPolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "bonus") continue;
                data.push(hr.orgs.getRowBonusPolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnBonusPolicies: configColumnBonusPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "bonus_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["bonus_policies_applied_to_employee_list"] = value;
                        host.redrawTableBonusPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editBonusPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowBonusPolicy(host, value));
                    });
                };
            }
            bonus_policiesPage.redrawTable(params);
        });
    };
    var bonus_policiesPage = theme.employeeBonusPoliciesForm({});
    host.redrawTableBonusPoliciesFunc();
    return bonus_policiesPage;
};

hr.orgs.addPunishmentPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editPunishmentPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "punishment";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTablePunishmentPoliciesFunc();
            }
        });
    });
};

hr.orgs.addPunishmentPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editPunishmentPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addPunishmentPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editPunishmentPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editPunishmentPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_punishment_policy"),
            bodycontent: host.editPunishmentPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addPunishmentPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addPunishmentPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.punishment_policies_applied_to_employee.typeid,
            formid: host.form_config.punishment_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editPunishmentPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editPunishmentPolicyForm.formFragment.setContext('host', host);
            host.editPunishmentPolicyForm.formFragment.setContext('id', id);
            host.editPunishmentPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editPunishmentPolicyForm.formFragment.view, {
                    name: 'type_punishment_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editPunishmentPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editPunishmentPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.punishment_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.punishment_policies.items[pIndex].description;
                        hr.orgs.editPunishmentPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deletePunishmentPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.punishment_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_punishment_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.punishment_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowPunishmentPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editPunishmentPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowPunishmentPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deletePunishmentPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeePunishmentPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "punishment_policies_applied_to_employee", displayDic);
    host.redrawTablePunishmentPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "punishment_policies_applied_to_employee_list").then(function(value){
            var configColumnPunishmentPolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "punishment") continue;
                data.push(hr.orgs.getRowPunishmentPolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnPunishmentPolicies: configColumnPunishmentPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "punishment_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["punishment_policies_applied_to_employee_list"] = value;
                        host.redrawTablePunishmentPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editPunishmentPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowPunishmentPolicy(host, value));
                    });
                };
            }
            punishment_policiesPage.redrawTable(params);
        });
    };
    var punishment_policiesPage = theme.employeePunishmentPoliciesForm({});
    host.redrawTablePunishmentPoliciesFunc();
    return punishment_policiesPage;
};

hr.orgs.employeeBonusPunishmentAdvancePaymentPolicies = function(host){
    return theme.employeeBonusPunishmentAdvancePaymentPoliciesFrom({
        bonus: hr.orgs.employeeBonusPolicies(host),
        punishment: hr.orgs.employeePunishmentPolicies(host),
        advance_payment: hr.orgs.employeeAdvancePaymentPolicies(host)
    });
};

hr.orgs.addBenefitPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editBenefitPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "benefit";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableBenefitPoliciesFunc();
            }
        });
    });
};

hr.orgs.addBenefitPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editBenefitPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addBenefitPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editBenefitPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editBenefitPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_benefit_policy"),
            bodycontent: host.editBenefitPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addBenefitPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addBenefitPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.benefit_policies_applied_to_employee.typeid,
            formid: host.form_config.benefit_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editBenefitPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editBenefitPolicyForm.formFragment.setContext('host', host);
            host.editBenefitPolicyForm.formFragment.setContext('id', id);
            host.editBenefitPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editBenefitPolicyForm.formFragment.view, {
                    name: 'type_benefit_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editBenefitPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editBenefitPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.benefit_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.benefit_policies.items[pIndex].description;
                        hr.orgs.editBenefitPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteBenefitPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.benefit_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_benefit_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.benefit_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowBenefitPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editBenefitPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowBenefitPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteBenefitPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.benefit_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "benefit", host.database.benefit_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeBenefitPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "benefit_policies_applied_to_employee", displayDic);
    host.redrawTableBenefitPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "benefit_policies_applied_to_employee_list").then(function(value){
            var configColumnBenefitPolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "benefit") continue;
                row = hr.orgs.getRowBenefitPolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnBenefitPolicies: configColumnBenefitPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "benefit_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["benefit_policies_applied_to_employee_list"] = value;
                        host.redrawTableBenefitPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editBenefitPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowBenefitPolicy(host, value));
                    });
                };
            }
            benefit_policiesPage.redrawTable(params);
        });
    };
    var benefit_policiesPage = theme.employeeBenefitPoliciesForm({});
    host.redrawTableBenefitPoliciesFunc();
    return benefit_policiesPage;
};

hr.orgs.addAllowancePolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editAllowancePolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "allowance";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableAllowancePoliciesFunc();
            }
        });
    });
};

hr.orgs.addAllowancePolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editAllowancePolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addAllowancePolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editAllowancePolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editAllowancePolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_allowance_policy"),
            bodycontent: host.editAllowancePolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addAllowancePolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addAllowancePolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.allowance_policies_applied_to_employee.typeid,
            formid: host.form_config.allowance_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editAllowancePolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editAllowancePolicyForm.formFragment.setContext('host', host);
            host.editAllowancePolicyForm.formFragment.setContext('id', id);
            host.editAllowancePolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editAllowancePolicyForm.formFragment.view, {
                    name: 'type_allowance_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editAllowancePolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editAllowancePolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.allowance_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.allowance_policies.items[pIndex].description;
                        hr.orgs.editAllowancePolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteAllowancePolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.allowance_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_allowance_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.allowance_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowAllowancePolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editAllowancePolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowAllowancePolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteAllowancePolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.allowance_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "allowance", host.database.allowance_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeAllowancePolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "allowance_policies_applied_to_employee", displayDic);
    host.redrawTableAllowancePoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "allowance_policies_applied_to_employee_list").then(function(value){
            var configColumnAllowancePolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "allowance") continue;
                row = hr.orgs.getRowAllowancePolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnAllowancePolicies: configColumnAllowancePolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "allowance_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["allowance_policies_applied_to_employee_list"] = value;
                        host.redrawTableAllowancePoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editAllowancePolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowAllowancePolicy(host, value));
                    });
                };
            }
            allowance_policiesPage.redrawTable(params);
        });
    };
    var allowance_policiesPage = theme.employeeAllowancePoliciesForm({});
    host.redrawTableAllowancePoliciesFunc();
    return allowance_policiesPage;
};

hr.orgs.employeeBenefitAllowancePolicies = function(host){
    return theme.employeeBenefitAllowancePoliciesForm({
        benefit: hr.orgs.employeeBenefitPolicies(host),
        allowance: hr.orgs.employeeAllowancePolicies(host)
    });
};

hr.orgs.deleteInsurancePolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.insurance_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_insurance_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.insurance_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addInsurancePolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editInsurancePolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            if (data.value === undefined) dataEdit.value = undefined;
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "value", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "insurance";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableInsurancePoliciesFunc();
            }
        });
    });
};

hr.orgs.addInsurancePolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editInsurancePolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                if (data.value === undefined) dataEdit.value = undefined;
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "value", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addInsurancePolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editInsurancePolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editInsurancePolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_insurance_policy"),
            bodycontent: host.editInsurancePolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addInsurancePolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addInsurancePolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.insurance_policies_applied_to_employee.typeid,
            formid: host.form_config.insurance_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editInsurancePolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editInsurancePolicyForm.formFragment.setContext('host', host);
            host.editInsurancePolicyForm.formFragment.setContext('id', id);
            host.editInsurancePolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editInsurancePolicyForm.formFragment.view, {
                    name: 'type_insurance_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editInsurancePolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editInsurancePolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.insurance_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.insurance_policies.items[pIndex].description;
                        dataEdit.calculated_on = host.database.insurance_policies.items[pIndex].calculated_on;
                        hr.orgs.editInsurancePolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.getRowInsurancePolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editInsurancePolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowInsurancePolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteInsurancePolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.insurance_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "insurance", host.database.insurance_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeInsurancePolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "insurance_policies_applied_to_employee", displayDic);
    host.redrawTableInsurancePoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "insurance_policies_applied_to_employee_list").then(function(value){
            var configColumnInsurancePolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "insurance") continue;
                row = hr.orgs.getRowInsurancePolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnInsurancePolicies: configColumnInsurancePolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "insurance_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["insurance_policies_applied_to_employee_list"] = value;
                        host.redrawTableInsurancePoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editInsurancePolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowInsurancePolicy(host, value));
                    });
                };
            }
            insurance_policiesPage.redrawTable(params);
        });
    };
    var insurance_policiesPage = theme.employeeInsurancePoliciesForm({});
    host.redrawTableInsurancePoliciesFunc();
    return insurance_policiesPage;
};

hr.orgs.deleteOvertimePolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.overtime_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_overtime_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.overtime_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addOvertimePolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editOvertimePolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            if (data.value === undefined) dataEdit.value = undefined;
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "overtime";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableOvertimePoliciesFunc();
            }
        });
    });
};

hr.orgs.addOvertimePolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editOvertimePolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                if (data.value === undefined) dataEdit.value = undefined;
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addOvertimePolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editOvertimePolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editOvertimePolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_overtime_policy"),
            bodycontent: host.editOvertimePolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addOvertimePolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addOvertimePolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.overtime_policies_applied_to_employee.typeid,
            formid: host.form_config.overtime_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editOvertimePolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editOvertimePolicyForm.formFragment.setContext('host', host);
            host.editOvertimePolicyForm.formFragment.setContext('id', id);
            host.editOvertimePolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editOvertimePolicyForm.formFragment.view, {
                    name: 'type_overtime_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editOvertimePolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editOvertimePolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.overtime_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.overtime_policies.items[pIndex].description;
                        dataEdit.calculated_on = host.database.overtime_policies.items[pIndex].calculated_on;
                        hr.orgs.editOvertimePolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.getRowOvertimePolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editOvertimePolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowOvertimePolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteOvertimePolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.overtime_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "overtime", host.database.overtime_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeOvertimePolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "overtime_policies_applied_to_employee", displayDic);
    host.redrawTableOvertimePoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "overtime_policies_applied_to_employee_list").then(function(value){
            var configColumnOvertimePolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "overtime") continue;
                row = hr.orgs.getRowOvertimePolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnOvertimePolicies: configColumnOvertimePolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "overtime_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["overtime_policies_applied_to_employee_list"] = value;
                        host.redrawTableOvertimePoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editOvertimePolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowOvertimePolicy(host, value));
                    });
                };
            }
            overtime_policiesPage.redrawTable(params);
        });
    };
    var overtime_policiesPage = theme.employeeOvertimePoliciesForm({});
    host.redrawTableOvertimePoliciesFunc();
    return overtime_policiesPage;
};
//

hr.orgs.deleteTaxPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.tax_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_tax_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.tax_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addTaxPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTaxPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "tax";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableTaxPoliciesFunc();
            }
        });
    });
};

hr.orgs.addTaxPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTaxPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addTaxPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editTaxPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        if (id == 0){
            var x = false;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "tax") continue;
                x = true;
                break;
            }
            if (x){
                ModalElement.alert({message: LanguageModule.text("war_txt_employee_has_only_one_tax_policy")});
                return;
            }
        }
        var getValueFunction;
        host.editTaxPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_tax_policy"),
            bodycontent: host.editTaxPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addTaxPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addTaxPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.tax_policies_applied_to_employee.typeid,
            formid: host.form_config.tax_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editTaxPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editTaxPolicyForm.formFragment.setContext('host', host);
            host.editTaxPolicyForm.formFragment.setContext('id', id);
            host.editTaxPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editTaxPolicyForm.formFragment.view, {
                    name: 'type_tax_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editTaxPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editTaxPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.tax_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.tax_policies.items[pIndex].description;
                        dataEdit.tax_type = host.database.tax_policies.items[pIndex].tax_type;
                        hr.orgs.editTaxPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.getRowTaxPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editTaxPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowTaxPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteTaxPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeTaxPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true,
        tax_type: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "tax_policies_applied_to_employee", displayDic);
    host.redrawTableTaxPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "tax_policies_applied_to_employee_list").then(function(value){
            var configColumnTaxPolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "tax") continue;
                data.push(hr.orgs.getRowTaxPolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnTaxPolicies: configColumnTaxPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "tax_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["tax_policies_applied_to_employee_list"] = value;
                        host.redrawTableTaxPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editTaxPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowTaxPolicy(host, value));
                    });
                };
            }
            tax_policiesPage.redrawTable(params);
        });
    };
    var tax_policiesPage = theme.employeeTaxPoliciesForm({});
    host.redrawTableTaxPoliciesFunc();
    return tax_policiesPage;
};

hr.orgs.deleteTradeUnionPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.trade_union_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_trade_union_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.trade_union_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addTradeUnionPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTradeUnionPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "trade_union";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableTradeUnionPoliciesFunc();
            }
        });
    });
};

hr.orgs.addTradeUnionPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editTradeUnionPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addTradeUnionPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editTradeUnionPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editTradeUnionPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_trade_union_policy"),
            bodycontent: host.editTradeUnionPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addTradeUnionPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addTradeUnionPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.trade_union_policies_applied_to_employee.typeid,
            formid: host.form_config.trade_union_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editTradeUnionPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editTradeUnionPolicyForm.formFragment.setContext('host', host);
            host.editTradeUnionPolicyForm.formFragment.setContext('id', id);
            host.editTradeUnionPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editTradeUnionPolicyForm.formFragment.view, {
                    name: 'type_trade_union_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editTradeUnionPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editTradeUnionPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.trade_union_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.trade_union_policies.items[pIndex].description;
                        dataEdit.calculated_on = host.database.trade_union_policies.items[pIndex].calculated_on;
                        hr.orgs.editTradeUnionPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.getRowTradeUnionPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editTradeUnionPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowTradeUnionPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteTradeUnionPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.trade_union_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "trade_union", host.database.trade_union_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeTradeUnionPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "trade_union_policies_applied_to_employee", displayDic);
    host.redrawTableTradeUnionPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "trade_union_policies_applied_to_employee_list").then(function(value){
            var configColumnTradeUnionPolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "trade_union") continue;
                row = hr.orgs.getRowTradeUnionPolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnTradeUnionPolicies: configColumnTradeUnionPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "trade_union_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["trade_union_policies_applied_to_employee_list"] = value;
                        host.redrawTableTradeUnionPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editTradeUnionPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowTradeUnionPolicy(host, value));
                    });
                };
            }
            trade_union_policiesPage.redrawTable(params);
        });
    };
    var trade_union_policiesPage = theme.employeeTradeUnionPoliciesForm({});
    host.redrawTableTradeUnionPoliciesFunc();
    return trade_union_policiesPage;
};

hr.orgs.deleteOtherLiabilityPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.other_liability_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_other_liability_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.other_liability_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.addOtherLiabilityPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editOtherLiabilityPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "other_liability";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableOtherLiabilityPoliciesFunc();
            }
        });
    });
};

hr.orgs.addOtherLiabilityPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editOtherLiabilityPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addOtherLiabilityPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editOtherLiabilityPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editOtherLiabilityPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_other_liability_policy"),
            bodycontent: host.editOtherLiabilityPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addOtherLiabilityPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addOtherLiabilityPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.other_liability_policies_applied_to_employee.typeid,
            formid: host.form_config.other_liability_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editOtherLiabilityPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editOtherLiabilityPolicyForm.formFragment.setContext('host', host);
            host.editOtherLiabilityPolicyForm.formFragment.setContext('id', id);
            host.editOtherLiabilityPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editOtherLiabilityPolicyForm.formFragment.view, {
                    name: 'type_other_liability_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editOtherLiabilityPolicyForm.getValue = function(){
            var data = getValueFunction();
            console.log(data);
            return data;
        };
    });
};

hr.orgs.editOtherLiabilityPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.other_liability_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.other_liability_policies.items[pIndex].description;
                        dataEdit.tax_relief = host.database.other_liability_policies.items[pIndex].tax_relief;
                        dataEdit.insurance_contribution_relief = host.database.other_liability_policies.items[pIndex].insurance_contribution_relief;
                        dataEdit.calculated_on = host.database.other_liability_policies.items[pIndex].calculated_on;
                        dataEdit.contributed_by_company = host.database.other_liability_policies.items[pIndex].contributed_by_company;
                        dataEdit.contributed_by_employee = host.database.other_liability_policies.items[pIndex].contributed_by_employee;
                        dataEdit.frequency = host.database.other_liability_policies.items[pIndex].frequency;
                        hr.orgs.editOtherLiabilityPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.getRowOtherLiabilityPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editOtherLiabilityPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowOtherLiabilityPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteOtherLiabilityPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.other_liability_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "other_liability", host.database.other_liability_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeOtherLiabilityPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "other_liability_policies_applied_to_employee", displayDic);
    host.redrawTableOtherLiabilityPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "other_liability_policies_applied_to_employee_list").then(function(value){
            var configColumnOtherLiabilityPolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "other_liability") continue;
                row = hr.orgs.getRowOtherLiabilityPolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnOtherLiabilityPolicies: configColumnOtherLiabilityPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "other_liability_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["other_liability_policies_applied_to_employee_list"] = value;
                        host.redrawTableOtherLiabilityPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editOtherLiabilityPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowOtherLiabilityPolicy(host, value));
                    });
                };
            }
            other_liability_policiesPage.redrawTable(params);
        });
    };
    var other_liability_policiesPage = theme.employeeOtherLiabilityPoliciesForm({});
    host.redrawTableOtherLiabilityPoliciesFunc();
    return other_liability_policiesPage;
};

hr.orgs.employeeLiabilityPolicies = function(host){
    return theme.employeeLiabilityPoliciesForm({
        insurance: hr.orgs.employeeInsurancePolicies(host),
        tax: hr.orgs.employeeTaxPolicies(host),
        trade_union: hr.orgs.employeeTradeUnionPolicies(host),
        other_liability: hr.orgs.employeeOtherLiabilityPolicies(host)
    });
};

hr.orgs.addLeavePolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editLeavePolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "leave";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableLeavePoliciesFunc();
            }
        });
    });
};

hr.orgs.addLeavePolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editLeavePolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addLeavePolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editLeavePolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editLeavePolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_leave_policy"),
            bodycontent: host.editLeavePolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addLeavePolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addLeavePolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.leave_policies_applied_to_employee.typeid,
            formid: host.form_config.leave_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editLeavePolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editLeavePolicyForm.formFragment.setContext('host', host);
            host.editLeavePolicyForm.formFragment.setContext('id', id);
            host.editLeavePolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editLeavePolicyForm.formFragment.view, {
                    name: 'type_leave_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editLeavePolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editLeavePolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.leave_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.leave_policies.items[pIndex].description;
                        hr.orgs.editLeavePolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteLeavePolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.leave_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_leave_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.leave_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowLeavePolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editLeavePolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowLeavePolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteLeavePolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.leave_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "leave", host.database.leave_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeLeavePolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "leave_policies_applied_to_employee", displayDic);
    host.redrawTableLeavePoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "leave_policies_applied_to_employee_list").then(function(value){
            var configColumnLeavePolicies = value;
            var data = [], row;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "leave") continue;
                row = hr.orgs.getRowLeavePolicy(host, host.database.employee_policies.items[i]);
                if (!row) continue;
                data.push(row);
            }
            var params = {
                data: data,
                configColumnLeavePolicies: configColumnLeavePolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "leave_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["leave_policies_applied_to_employee_list"] = value;
                        host.redrawTableLeavePoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editLeavePolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowLeavePolicy(host, value));
                    });
                };
            }
            leave_policiesPage.redrawTable(params);
        });
    };
    var leave_policiesPage = theme.employeeLeavePoliciesForm({});
    host.redrawTableLeavePoliciesFunc();
    return leave_policiesPage;
};

hr.orgs.addLateEarlyCheckinPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editLateEarlyCheckinPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "late_early_checkin";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableLateEarlyCheckinPoliciesFunc();
            }
        });
    });
};

hr.orgs.addLateEarlyCheckinPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editLateEarlyCheckinPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addLateEarlyCheckinPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editLateEarlyCheckinPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var getValueFunction;
        host.editLateEarlyCheckinPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_late_early_checkin_policy"),
            bodycontent: host.editLateEarlyCheckinPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addLateEarlyCheckinPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addLateEarlyCheckinPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.late_early_checkin_policies_applied_to_employee.typeid,
            formid: host.form_config.late_early_checkin_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editLateEarlyCheckinPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editLateEarlyCheckinPolicyForm.formFragment.setContext('host', host);
            host.editLateEarlyCheckinPolicyForm.formFragment.setContext('id', id);
            host.editLateEarlyCheckinPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editLateEarlyCheckinPolicyForm.formFragment.view, {
                    name: 'type_late_early_checkin_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editLateEarlyCheckinPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editLateEarlyCheckinPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.late_early_checkin_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.late_early_checkin_policies.items[pIndex].description;
                        hr.orgs.editLateEarlyCheckinPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteLateEarlyCheckinPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.late_early_checkin_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_late_early_checkin_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.late_early_checkin_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowLateEarlyCheckinPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editLateEarlyCheckinPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowLateEarlyCheckinPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteLateEarlyCheckinPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    // var pIndex = host.database.late_early_checkin_policies.getIndex(res.policyid);
    // if (pIndex < 0) return null;
    // res.variables = contentModule.getPolicyVariables(host.database.typelists, "late_early_checkin", host.database.late_early_checkin_policies.items[pIndex]);
    res.func = func;
    return res;
};

hr.orgs.employeeLateEarlyCheckinPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "late_early_checkin_policies_applied_to_employee", displayDic);
    host.redrawTableLateEarlyCheckinPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "late_early_checkin_policies_applied_to_employee_list").then(function(value){
            var configColumnLateEarlyCheckinPolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "late_early_checkin") continue;
                data.push(hr.orgs.getRowLateEarlyCheckinPolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnLateEarlyCheckinPolicies: configColumnLateEarlyCheckinPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "late_early_checkin_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["late_early_checkin_policies_applied_to_employee_list"] = value;
                        host.redrawTableLateEarlyCheckinPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editLateEarlyCheckinPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowLateEarlyCheckinPolicy(host, value));
                    });
                };
            }
            late_early_checkin_policiesPage.redrawTable(params);
        });
    };
    var late_early_checkin_policiesPage = theme.employeeLateEarlyCheckinPoliciesForm({});
    host.redrawTableLateEarlyCheckinPoliciesFunc();
    return late_early_checkin_policiesPage;
};

hr.orgs.addStandardWorkdayPolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editStandardWorkdayPolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "standard_workday";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTableStandardWorkdayPoliciesFunc();
            }
        });
    });
};

hr.orgs.addStandardWorkdayPolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editStandardWorkdayPolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addStandardWorkdayPolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editStandardWorkdayPolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        if (id == 0){
            var x = false;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "standard_workday") continue;
                x = true;
                break;
            }
            if (x){
                ModalElement.alert({message: LanguageModule.text("war_txt_employee_has_only_one_standard_workday_policy")});
                return;
            }
        }
        var getValueFunction;
        host.editStandardWorkdayPolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_standard_workday_policy"),
            bodycontent: host.editStandardWorkdayPolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addStandardWorkdayPolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addStandardWorkdayPolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.standard_workday_policies_applied_to_employee.typeid,
            formid: host.form_config.standard_workday_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editStandardWorkdayPolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editStandardWorkdayPolicyForm.formFragment.setContext('host', host);
            host.editStandardWorkdayPolicyForm.formFragment.setContext('id', id);
            host.editStandardWorkdayPolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editStandardWorkdayPolicyForm.formFragment.view, {
                    name: 'type_standard_workday_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editStandardWorkdayPolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editStandardWorkdayPolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.standard_workday_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.standard_workday_policies.items[pIndex].description;
                        hr.orgs.editStandardWorkdayPolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deleteStandardWorkdayPolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.standard_workday_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_standard_workday_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.standard_workday_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowStandardWorkdayPolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editStandardWorkdayPolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowStandardWorkdayPolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deleteStandardWorkdayPolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeeStandardWorkdayPolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "standard_workday_policies_applied_to_employee", displayDic);
    host.redrawTableStandardWorkdayPoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "standard_workday_policies_applied_to_employee_list").then(function(value){
            var configColumnStandardWorkdayPolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "standard_workday") continue;
                data.push(hr.orgs.getRowStandardWorkdayPolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnStandardWorkdayPolicies: configColumnStandardWorkdayPolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "standard_workday_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["standard_workday_policies_applied_to_employee_list"] = value;
                        host.redrawTableStandardWorkdayPoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editStandardWorkdayPolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowStandardWorkdayPolicy(host, value));
                    });
                };
            }
            standard_workday_policiesPage.redrawTable(params);
        });
    };
    var standard_workday_policiesPage = theme.employeeStandardWorkdayPoliciesForm({});
    host.redrawTableStandardWorkdayPoliciesFunc();
    return standard_workday_policiesPage;
};

hr.orgs.employeeWorkingTimePolicies = function(host){
    return theme.employeeWorkingTimePoliciesForm({
        leave: hr.orgs.employeeLeavePolicies(host),
        late_early_checkin: hr.orgs.employeeLateEarlyCheckinPolicies(host),
        overtime: hr.orgs.employeeOvertimePolicies(host),
        standard_workday: hr.orgs.employeeStandardWorkdayPolicies(host),
        piece_wage: hr.orgs.employeePieceWagePolicies(host)
    });
};

hr.orgs.addPieceWagePolicySave = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editPieceWagePolicyForm.getValue();
        if (!data) return;
        data.id = id;
        if (id > 0){
            var ischange = contentModule.isChanged(dataEdit, data,
                ["policyid", "extrainfo"]
            );
            if (!ischange){
                ModalElement.close();
                return;
            }
            data.ver = dataEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.employeeid = host.employeeid;
        data.type = "piece_wage";
        data.available = data.available? 1: 0;
        hr.orgs.saveEmployeePolicy(host, data, id).then(function(value){
            var updateAll = false;
            if (id > 0){
                if (data.available && !dataEdit.available) updateAll = true;
            }
            else {
                if (data.available) updateAll = true;
            }
            if (!updateAll) resolve(value);
            else {
                host.redrawTablePieceWagePoliciesFunc();
            }
        });
    });
};

hr.orgs.addPieceWagePolicyClose = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        var data = host.editPieceWagePolicyForm.getValue();
        var closeFunc = function(){
            ModalElement.close();
        };
        if (!data) {
            ModalElement.close();
            closeFunc();
        }
        else {
            if (id > 0){
                var ischange = contentModule.isChanged(dataEdit, data,
                    ["policyid", "extrainfo"]
                );
            }
            else {
                var ischange = contentModule.isChanged({policyid: 0}, data,
                    ["policyid"]
                );
            }
            if (!ischange){
                closeFunc();
            }
            else {
                contentModule.questionChange({
                    onclick: function(sel){
                        if (sel == 0){
                            hr.orgs.addPieceWagePolicySave(host, id, dataEdit).then(function(value){
                                resolve(value);
                            });
                        }
                        else if (sel == 1){
                            closeFunc();
                        }
                    }
                });
            }
        }
    });
};

hr.orgs.editPieceWagePolicy = function(host, id, dataEdit){
    return new Promise(function(resolve, reject){
        if (id == 0){
            var x = false;
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "piece_wage") continue;
                x = true;
                break;
            }
            if (x){
                ModalElement.alert({message: LanguageModule.text("war_txt_employee_has_only_one_piece_wage_policy")});
                return;
            }
        }
        var getValueFunction;
        host.editPieceWagePolicyForm = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_piece_wage_policy"),
            bodycontent: host.editPieceWagePolicyForm,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addPieceWagePolicySave(host, id, dataEdit).then(function(value){
                            resolve(value)
                        });
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addPieceWagePolicyClose(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                }
            ]
        });
        contentModule.makeFormData({
            typeid: host.form_config.piece_wage_policies_applied_to_employee.typeid,
            formid: host.form_config.piece_wage_policies_applied_to_employee.input_form,
            initialValue: dataEdit,
            formContainer: host.editPieceWagePolicyForm,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            host.editPieceWagePolicyForm.formFragment.setContext('host', host);
            host.editPieceWagePolicyForm.formFragment.setContext('id', id);
            host.editPieceWagePolicyForm.formFragment.afterEntryCompleted().then(function(){
                var elt = absol.form.findComponent(host.editPieceWagePolicyForm.formFragment.view, {
                    name: 'type_piece_wage_policies_applied_to_employee_employeeid',
                    depth: false
                });
                if (elt){
                    elt.attributes.value = host.employeeid;
                    elt.attributes.disabled = true;
                }
            });
        });
        host.editPieceWagePolicyForm.getValue = function(){
            var data = getValueFunction();
            if (!data) return false;
            return data;
        };
    });
};

hr.orgs.editPieceWagePolicyPre = function(host, id){
    return new Promise(function(resolve, reject){
        ModalElement.show_loading();
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "employee_load_policies"},
                {name: "id", value: id}
            ],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var dataEdit = EncodingClass.string.toVariable(message.substr(2));
                        if (dataEdit.extrainfo == "") dataEdit.extrainfo = {};
                        else dataEdit.extrainfo = EncodingClass.string.toVariable(dataEdit.extrainfo);
                        var pIndex = host.database.piece_wage_policies.getIndex(dataEdit.policyid);
                        if (pIndex < 0){
                            ModalElement.alert({message: LanguageModule.text("war_txt_failed_data")});
                            return;
                        }
                        dataEdit.description = host.database.piece_wage_policies.items[pIndex].description;
                        hr.orgs.editPieceWagePolicy(host, id, dataEdit).then(function(value){
                            resolve(value);
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.deletePieceWagePolicyConfirm = function(host, id){
    return new Promise(function(resolve, reject){
        var index = host.database.employee_policies.getIndex(id);
        var pIndex = host.database.piece_wage_policies.getIndex(host.database.employee_policies.items[index].policyid);
        ModalElement.question({
            title: LanguageModule.text("war_title_delete_piece_wage_policy"),
            message: LanguageModule.text2("war_txt_detele", [host.database.piece_wage_policies.items[pIndex].name]),
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.deleteEmployeePolicies(host, id).then(function(value){
                        resolve(value);
                    });
                }
            }
        });
    });
};

hr.orgs.getRowPieceWagePolicy = function(host, content){
    var func = {};
    if (host.priv_edit_hr_policies){
        func.edit = function(rs){
            hr.orgs.editPieceWagePolicyPre(host, content.id).then(function(value){
                rs(hr.orgs.getRowPieceWagePolicy(host, value));
            });
        };
        func.delete = function(rs){
            hr.orgs.deletePieceWagePolicyConfirm(host, content.id).then(function(value){
                rs(value);
            });
        };
    }
    var res = EncodingClass.string.duplicate(content);
    res.func = func;
    return res;
};

hr.orgs.employeePieceWagePolicies = function(host){
    var displayDic = {
        policyid: true,
        description: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "piece_wage_policies_applied_to_employee", displayDic);
    host.redrawTablePieceWagePoliciesFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "piece_wage_policies_applied_to_employee_list").then(function(value){
            var configColumnPieceWagePolicies = value;
            var data = [];
            for (var i = 0; i < host.database.employee_policies.items.length; i++){
                if (host.database.employee_policies.items[i].type != "piece_wage") continue;
                data.push(hr.orgs.getRowPieceWagePolicy(host, host.database.employee_policies.items[i]));
            }
            var params = {
                data: data,
                configColumnPieceWagePolicies: configColumnPieceWagePolicies,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "piece_wage_policies_applied_to_employee_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["piece_wage_policies_applied_to_employee_list"] = value;
                        host.redrawTablePieceWagePoliciesFunc();
                    });
                }
            };
            if (host.priv_edit_hr_policies){
                params.addFunc = function(rs){
                    hr.orgs.editPieceWagePolicy(host, 0).then(function(value){
                        rs(hr.orgs.getRowPieceWagePolicy(host, value));
                    });
                };
            }
            piece_wage_policiesPage.redrawTable(params);
        });
    };
    var piece_wage_policiesPage = theme.employeePieceWagePoliciesForm({});
    host.redrawTablePieceWagePoliciesFunc();
    return piece_wage_policiesPage;
};

hr.orgs.editAnnualLeaveSubmit = function(host, employeeid, data){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "employee_save_annual_leave_save.php",
        params: [
            {name: "employeeid", value: employeeid},
            {name: "year", value: new Date().getFullYear()},
            {name: "content", value: EncodingClass.string.fromVariable(data)}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    ModalElement.close();
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    })
};

hr.orgs.editAnnualLeave = function(host, id){
    var redraw = function(content){
        var last_year_remain_input = theme.input({
            type: "number",
            style: {
                width: "50px"
            },
            value: content.last_year_remain
        });
        var leave_day_use_last_year_input = theme.input({
            type: "number",
            style: {
                width: "50px"
            },
            value: content.leave_day_use_last_year
        });
        var leave_day_use_this_year_input = theme.input({
            type: "number",
            style: {
                width: "50px"
            },
            value: content.leave_day_use_this_year
        });
        ModalElement.showWindow({
            title: "Sửa ngày nghỉ phép",
            bodycontent: DOMElement.table({
                data: [
                    [
                        {text: "Số ngày phép năm ngoái còn lại (Tại thời điểm cuối năm)"},
                        {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                        last_year_remain_input
                    ],
                    [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
                    [
                        {text: "Số ngày phép dùng của năm ngoái"},
                        {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                        leave_day_use_last_year_input
                    ],
                    [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
                    [
                        {text: "Số ngày phép dùng của năm nay"},
                        {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                        leave_day_use_this_year_input
                    ]
                ]
            }),
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        var data = {
                            last_year_remain: parseFloat(last_year_remain_input.value),
                            leave_day_use_last_year: parseFloat(leave_day_use_last_year_input.value),
                            leave_day_use_this_year: parseFloat(leave_day_use_this_year_input.value)
                        };
                        hr.orgs.editAnnualLeaveSubmit(host, id, data);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        ModalElement.close();
                    }
                }
            ]
        });
    };
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "load_config_employee_annual_leave"},
            {name: "employeeid", value: id},
            {name: "year", value: new Date().getFullYear()}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var st = EncodingClass.string.toVariable(message.substr(2));
                    var content = {
                        last_year_remain: 0,
                        leave_day_use_last_year: 0,
                        leave_day_use_this_year: 0
                    };
                    if (st.length > 0){
                        content = EncodingClass.string.toVariable(st[0].content);
                    }
                    redraw(content);
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.showEmployee = function(host, id){
    hr.menu.changeCurrentUrlTab(host, "view_employee/" + id);
    host.employeeid = id;
    var index = host.database.employees.getIndex(host.employeeid);
    var dataEmp = host.database.employees.items[index];
    host.emp_work_history = (dataEmp.work_history == "")? [] : EncodingClass.string.toVariable(dataEmp.work_history);
    host.emp_education_history = (dataEmp.education_history == "")? [] : EncodingClass.string.toVariable(dataEmp.education_history);
    host.emp_skill = (dataEmp.skill == "")? [] : EncodingClass.string.toVariable(dataEmp.skill);
    host.emp_social_network = (!dataEmp.social_network)? [] : EncodingClass.string.toVariable(dataEmp.social_network);
    host.emp_phone = (!dataEmp.phone)? [] : EncodingClass.string.toVariable(dataEmp.phone);
    host.emp_email = (!dataEmp.email)? [] : EncodingClass.string.toVariable(dataEmp.email);
    host.emp_additional_personal_document = (dataEmp.additional_personal_document == "")? [] : EncodingClass.string.toVariable(dataEmp.additional_personal_document);
    host.emp_bank_account = (dataEmp.bank_account == "")? [] : EncodingClass.string.toVariable(dataEmp.bank_account);
    var orgid = dataEmp.orgid;
    if (systemconfig.privSystem >= 2){
        host.priv_edit_general_information_abilities_contact_communications_other_infomation = true;
        host.priv_view_employee_profiles = true;
        host.priv_edit_employment_contracts_salary_decisions_bank_accounts = true;
        host.priv_edit_hr_policies = true;
        host.priv_edit_organization_and_employee = true;
    }
    else {
        for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
            if (host.listConfigPrivilegeOfMe[i].departmentList.indexOf(orgid) < 0) continue;
            if (host.listConfigPrivilegeOfMe[i].content.edit_general_information_abilities_contact_communications_other_infomation){
                host.priv_edit_general_information_abilities_contact_communications_other_infomation = true;
            }
            if (host.listConfigPrivilegeOfMe[i].content.view_employee_profiles){
                host.priv_view_employee_profiles = true;
            }
            if (host.listConfigPrivilegeOfMe[i].content.priv_edit_employment_contracts_salary_decisions_bank_accounts){
                host.priv_edit_employment_contracts_salary_decisions_bank_accounts = true;
            }
            if (host.listConfigPrivilegeOfMe[i].content.edit_hr_policies){
                host.priv_edit_hr_policies = true;
            }
            if (host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee){
                host.edit_organization_and_employee = true;
                host.priv_edit_general_information_abilities_contact_communications_other_infomation = true;
                host.priv_view_employee_profiles = true;
                host.priv_edit_employment_contracts_salary_decisions_bank_accounts = true;
                host.priv_edit_hr_policies = true;
            }
        }
    }
    var viewDic = {};
    if (dataEmp.userid == systemconfig.userid) host.priv_view_employee_profiles = true;
    viewDic.general_information = function(){
        return hr.orgs.employeeGeneralInformation(host);
    };
    if (host.priv_view_employee_profiles || host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        viewDic.ability = function(){
            return hr.orgs.employeeAbility(host);
        };
        // viewDic.communication = function(){
        //     return hr.orgs.employeeCommunication(host);
        // };
    }
    if (host.priv_view_employee_profiles || host.priv_edit_employment_contracts_salary_decisions_bank_accounts){
        viewDic.employment_contract_salary_account = function(){
            return hr.orgs.employeeSalaryInformationAndAccount(host);
        };
    }
    if (host.priv_view_employee_profiles || host.priv_edit_general_information_abilities_contact_communications_other_infomation){
        viewDic.other_information = function(){
            return hr.orgs.employeeOtherInformation(host);
        }
    }
    if (host.priv_view_employee_profiles || host.priv_edit_hr_policies){
        viewDic.bonus_punishment_advance_payment_policies = function(){
            return hr.orgs.employeeBonusPunishmentAdvancePaymentPolicies(host);
        };
        viewDic.benefit_allowance_policies = function(){
            return hr.orgs.employeeBenefitAllowancePolicies(host);
        };
        viewDic.liability_policies = function(){
            return hr.orgs.employeeLiabilityPolicies(host);
        };
        viewDic.working_time_policies = function(){
            return hr.orgs.employeeWorkingTimePolicies(host);
        };
    }
    viewDic.comment = function(){
        return contentModule.drawComment({taskid: host.employeeid, tablename: "employees"});
    };
    theme.showEmployeeView({
        holder: host.holder,
        frameList: host.frameList,
        edit_annual_leave: function(){
            hr.orgs.editAnnualLeave(host, id);
        },
        viewDic: viewDic
    });
};

hr.orgs.showEmployeePre = function(host, id){
    var index = host.database.employees.getIndex(id);
    var orgid = host.database.employees.items[index].orgid;
    ModalElement.show_loading();
    var loadData = function(){
        return new Promise(function(rs, rj){
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "employee_general_load_by_id"},
                    {name: "orgid", value: orgid},
                    {name: "id", value: id}
                ],
                func: function(success, message){
                    ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            var content = st.content;
                            var index = host.database.employees.getIndex(id);
                            host.database.employees.items[index] = content;
                            contentModule.makeEmployeeAllData(host);
                            if (st.peopleData[0].content == "") st.peopleData[0].content = {};
                            else st.peopleData[0].content = EncodingClass.string.toVariable(st.peopleData[0].content);
                            for (var i = 0; i < contentModule.getPeopleContentField.length; i++){
                                st.peopleData[0][contentModule.getPeopleContentField[i]] = st.peopleData[0].content[contentModule.getPeopleContentField[i]];
                            }
                            var x = host.database.peoples.getIndex(st.peopleData[0].id);
                            if (x < 0) host.database.peoples.items.push(st.peopleData[0]);
                            else host.database.peoples.items[x] = st.peopleData[0];
                            for (var param in st.peopleData[0]) {
                                if (param != "id" && param != "available" && param != "userid"){
                                    host.database.employees.items[index][param] = st.peopleData[0][param];
                                }
                            }
                            if (host.database.employees.items[index].extrainfo == "") host.database.employees.items[index].extrainfo = {};
                            else host.database.employees.items[index].extrainfo = EncodingClass.string.toVariable(host.database.employees.items[index].extrainfo);
                            // var positions = [], positionName = "", pIndex;
                            var position = 0, positionName = "";
                            var concurrent_position = 0, concurrent_positionName = "";
                            var pIndex;
                            for (var i = 0; i < st.employee_positions.length; i++){
                                if (st.employee_positions[i].type == "concurrent_position"){
                                    concurrent_position = st.employee_positions[i].positionid;
                                    pIndex = host.database.positions.getIndex(st.employee_positions[i].positionid);
                                    if (pIndex >= 0) concurrent_positionName = host.database.positions.items[pIndex].name;
                                }
                                else {
                                    position = st.employee_positions[i].positionid;
                                    pIndex = host.database.positions.getIndex(st.employee_positions[i].positionid);
                                    if (pIndex >= 0) positionName = host.database.positions.items[pIndex].name;
                                }
                                // positions.push(st.employee_positions[i].positionid);
                            }
                            host.database.employees.items[index].position = position;
                            host.database.employees.items[index].positionName = positionName;
                            host.database.employees.items[index].concurrent_position = concurrent_position;
                            host.database.employees.items[index].concurrent_positionName = concurrent_positionName;
                            delete st.employee_positions;
                            var direct_manager = 0, indirect_manager = 0;
                            for (var i = 0; i < st.employee_managers.length; i++){
                                if (st.employee_managers[i].type == "direct") direct_manager = st.employee_managers[i].managerid;
                                if (st.employee_managers[i].type == "indirect") indirect_manager = st.employee_managers[i].managerid;
                            }
                            host.database.employees.items[index].direct_manager = direct_manager;
                            host.database.employees.items[index].indirect_manager = indirect_manager;
                            delete st.employee_managers;
                            delete st.content;
                            delete st.peopleData;
                            contentModule.makeDatabaseContent(host, st);
                            rs(content.id);
                        }
                        else if (message == "war_txt_failed_data"){
                            ModalElement.alert({message: LanguageModule.text(message)});
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        });
    }
    var loadPolicies = function(){
        return new Promise(function(rs, rj){
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "orgs_load_policies"}
                ],
                func: function(success, message){
                    ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            contentModule.makeDatabaseContent(host, st);
                            for (var x in st){
                                var index = x.indexOf("_policies");
                                if (index > 0){
                                    var type = x.substr(0, index);
                                }
                                contentModule.makeVariablesForPolicy(host, type);
                            }
                            rs();
                        }
                        else if (message == "war_txt_failed_data"){
                            ModalElement.alert({message: LanguageModule.text(message)});
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        });
    };
    var promiseList = [loadData()];
    if (!host.policies) promiseList.push(loadPolicies());
    Promise.all(promiseList).then(function(values){
        contentModule.makeEmployeePoliciesData(host);
        hr.orgs.showEmployee(host, values[0]);
    });
};

hr.orgs.addPositionSave = function(host, id, getValueFunction){
    var data = getValueFunction();
    if (!data) return;
    data.id = id;
    if (id > 0){
        var index = host.database.positions.getIndex(id);
        var ischange = contentModule.isChanged(host.database.positions.items[index], data,
            ["name", "code", "benefits", "liability_and_authority", "prefered_ability", "report_to", "working_condition", "job_description", "extrainfo"]
        );
        if (!ischange){
            ModalElement.close();
            hr.orgs.redrawPosition(host);
            hr.menu.changeCurrentUrlTab(host, "orgs");
            return;
        }
    }
    if (data.name == ""){
        ModalElement.alert({
            message: LanguageModule.text("war_txt_no_name")
        });
        return;
    }
    if (data.code == ""){
        ModalElement.alert({
            message: LanguageModule.text("war_txt_no_code")
        });
        return;
    }
    for (var i = 0; i < host.database.positions.items.length; i++){
        if (host.database.positions.items[i].id != id && host.database.positions.items[i].code.toLowerCase() == data.code.toLowerCase()){
            ModalElement.alert({
                message: LanguageModule.text("war_txt_code_was_used")
            });
            return;
        }
    }
    data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_save_position.php",
        params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var content = EncodingClass.string.toVariable(message.substr(2));
                    content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                    host.id = content.id;
                    host.orgid = content.orgid;
                    if (id > 0){
                        var index = host.database.positions.getIndex(id);
                        host.database.positions.items.splice(index, 1);
                    }
                    host.database.positions.items.push(content);
                    ModalElement.close();
                    contentModule.makePositionsIndex(host);
                    hr.orgs.redrawPosition(host);
                    hr.menu.changeCurrentUrlTab(host, "orgs");
                }
                else if (message == "lock_system"){
                    ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                }
                else if (message.startsWith("edited") || message.startsWith("deleted")){
                    console.log(message);
                    ModalElement.alert({message: LanguageModule.text("war_txt_failed_ver_reload_data")});
                }
                else if (message == "war_txt_code_was_used"){
                    ModalElement.alert({
                        message: LanguageModule.text(message)
                    });
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.addPositionClose = function(host, id, getValueFunction){
    function closeFunc(){
        ModalElement.close();
        hr.menu.changeCurrentUrlTab(host, "orgs");
    };
    var data = getValueFunction();
    if (!data) {
        ModalElement.close();
        ModalElement.close();
        hr.menu.changeCurrentUrlTab(host, "orgs");
        return;
    }
    var oldData;
    if (id > 0){
        var index = host.database.positions.getIndex(id);
        oldData = host.database.positions.items[index];
    }
    else {
        oldData = {
            name: "",
            code: "",
            benefits: "",
            working_condition: "",
            job_description: "",
            report_to: "",
            liability_and_authority: "",
            prefered_ability: "",
            extrainfo: {}
        };
    }
    var ischange = contentModule.isChanged(oldData, data,
        ["name", "code", "benefits", "liability_and_authority", "prefered_ability", "report_to", "working_condition", "job_description", "extrainfo"]
    );
    if (!ischange){
        closeFunc();
    }
    else {
        contentModule.questionChange({
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.addPositionSave(host, id, getValueFunction, 1);
                }
                else if (sel == 1){
                    closeFunc();
                }
            }
        });
    }
};

hr.orgs.addPosition = function(host, orgid, id){
    host.id = id;
    if (id > 0) hr.menu.changeCurrentUrlTab(host, "edit_position/" + id);
    function redraw(value){
        var formContainer = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_position"),
            bodycontent: formContainer,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addPositionSave(host, host.id, getValueFunction);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addPositionClose(host, host.id, getValueFunction);
                    }
                }
            ]
        });
        var getValueFunction;
        contentModule.makeFormData({
            typeid: host.form_config.position.typeid,
            formid: host.form_config.position.input_form,
            initialValue: value,
            formContainer: formContainer,
            typelists: host.database.typelists.items,
            variableType: "system"
        }).then(function(getValue){
            getValueFunction = getValue;
            var orgElt = absol.form.findComponent(formContainer.formFragment.view, {
                name: 'type_position_orgid',
                depth: false
            });
            formContainer.formFragment.afterEntryCompleted().then(function(){
                if (orgElt) {
                    if (id == 0) orgElt.attributes.value = orgid;
                    orgElt.domElt.disabled = true;
                }
                absol.form.traversal(formContainer.formFragment.view, function(item){
                    if (item.node.tag === "TextInput") {
                        item.node.domElt.focus();
                        item.stop();
                        return;
                    }
                });
            });
        });
    };
    if (id > 0){
        var index = host.database.positions.getIndex(id);
        var x = EncodingClass.string.duplicate(host.database.positions.items[index]);
        redraw(x);
    }
    else redraw();
};

hr.orgs.addPositionPre = function(host, orgid, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "position_load_by_id"},
            {name: "orgid", value: orgid},
            {name: "id", value: id}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var content = EncodingClass.string.toVariable(message.substr(2));
                    if (id > 0){
                        var index = host.database.positions.getIndex(id);
                        if (content.extrainfo == "") content.extrainfo = {};
                        else content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        host.database.positions.items[index] = content;
                    }
                    hr.orgs.addPosition(host, content.orgid, content.id);
                }
                else if (message == "war_txt_failed_data"){
                    ModalElement.alert({message: LanguageModule.text(message)});
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.addDepartmentClose = function(host, id, getValueFunction){
    return new Promise(function(rs, rj){
        function closeFunc(){
            rs();
            hr.menu.changeCurrentUrlTab(host, "orgs");
        };
        var data = getValueFunction("no_alert");
        if (!data) {
            rs();
            hr.menu.changeCurrentUrlTab(host, "orgs");
            return;
        }
        var oldData;
        if (id > 0){
            var index = host.database.orgs.getIndex(id);
            oldData = host.database.orgs.items[index];
        }
        else {
            oldData = {
                name: "",
                code: "",
                geopos: [],
                extrainfo: {}
            };
        }
        var ischange = contentModule.isChanged(oldData, data, ["name", "code", "geopos", "extrainfo"]);
        if (!ischange){
            closeFunc();
        }
        else {
            contentModule.questionChange({
                onclick: function(sel){
                    if (sel == 0){
                        hr.orgs.addDepartmentSave(host, id, getValueFunction, 1).then(function(){
                            rs();
                        });
                    }
                    else if (sel == 1){
                        closeFunc();
                    }
                }
            });
        }
    });
};

hr.orgs.addDepartment = function(host, parentid, id){
    if (id > 0){
        hr.menu.changeCurrentUrlTab(host, "edit_department/" + id);
    }
    host.id = id;
    function redraw(value){
        var formContainer = DOMElement.div({});
        theme.addDepartmentForm({
            title: (parentid == 0)? LanguageModule.text("txt_company") : LanguageModule.text("txt_department"),
            formContainer: formContainer,
            frameList: host.frameList,
            func: {
                save: function(){
                    return hr.orgs.addDepartmentSave(host, host.id, getValueFunction);
                },
                close: function(){
                    return hr.orgs.addDepartmentClose(host, host.id, getValueFunction);
                }
            }
        });
        var getValueFunction;
        contentModule.makeFormData({
            typeid: (parentid == 0)? host.form_config.company.typeid : host.form_config.org.typeid,
            formid: (parentid == 0)? host.form_config.company.input_form : host.form_config.org.input_form,
            initialValue: value,
            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;
                }
            });
            formContainer.formFragment.afterEntryCompleted().then(function(){
                var parentElt = absol.form.findComponent(formContainer.formFragment.view, {
                    name: 'type_org_parentid',
                    depth: false
                });
                if (parentElt){
                    if (id == 0){
                        parentElt.attributes.value = parseInt(parentid, 10);
                    }
                    parentElt.domElt.disabled = true;
                }
            });
        });
    };
    if (id > 0){
        var index = host.database.orgs.getIndex(id);
        var x = EncodingClass.string.duplicate(host.database.orgs.items[index]);
        redraw(x);
    }
    else redraw();
};

hr.orgs.addDepartmentPre = function(host, parentid, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "department_load_by_id"},
            {name: "parentid", value: parentid},
            {name: "id", value: id}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var content = EncodingClass.string.toVariable(message.substr(2));
                    if (id > 0){
                        if (content.extrainfo == "") content.extrainfo = {};
                        else content.extrainfo = EncodingClass.string.toVariable(content.extrainfo);
                        var index = host.database.orgs.getIndex(id);
                        content.positionIndexList = host.database.orgs.items[index].positionIndexList;
                        content.childIndexList = host.database.orgs.items[index].childIndexList;
                        content.employeeIndexList = host.database.orgs.items[index].employeeIndexList;
                        hr.orgs.replaceDataOrg(host, id, content);
                    }
                    if (content.id > 0){
                        host.orgid = content.id;
                    }
                    else {
                        host.orgid = content.parentid;
                    }
                    hr.orgs.addDepartment(host, content.parentid, content.id);
                }
                else if (message == "war_txt_failed_data"){
                    ModalElement.alert({message: LanguageModule.text(message)});
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.deletePriv = function(host, configid){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_delete_privileges.php",
        params: [{name: "id", value: configid}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var index = host.database.configs.getIndex(configid);
                    host.database.configs.items.splice(index, 1);
                    var index = host.database.configs_org_privileges.getIndex(configid);
                    host.database.configs_org_privileges.items.splice(index, 1);
                    host.redrawPrivDetails();
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.deletePrivConfirm = function(host, configid){
    ModalElement.question({
        title: LanguageModule.text("war_title_delete_permission"),
        message: LanguageModule.text2("war_txt_detele", [""]),
        onclick: function(sel){
            if (sel == 0){
                hr.orgs.deletePriv(host, configid);
            }
        }
    });
};

hr.orgs.addPrivSubmit = function(host, id, data){
    if (id > 0){
        data.id = id;
        var index = host.database.configs.getIndex(id);
        data.ver = host.database.configs.items[index].ver;
    }
    else {
        data.id = 0;
        data.ver = 1;
    }
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_save_privileges.php",
        params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var st = EncodingClass.string.toVariable(message.substr(2));
                    st.content = EncodingClass.string.toVariable(st.content);
                    if (id > 0){
                        host.database.configs.items[index] = st;
                    }
                    else {
                        host.database.configs.items.push(st);
                    }
                    ModalElement.close();
                    host.redrawPrivDetails();
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.addPriv = function(host, orgid, id){
    if (id > 0) var index = host.database.configs.getIndex(id);
    var oIndex = host.database.orgs.getIndex(orgid);
    var departmentName = host.database.orgs.items[oIndex].name;
    var title;
    if (host.database.orgs.items[oIndex].parentid > 0){
        title = LanguageModule.text("txt_setting_permission_for_department") + " ";
    }
    else {
        title = LanguageModule.text("txt_setting_permission_for_company") + " ";
    }
    var isCompany = host.database.orgs.items[oIndex].parentid == 0;
    var level_select = absol.buildDom({
        tag: "selectmenu",
        style: {
            display: "block",
            width: "100%"
        },
        props: {
            items: [
                {value: 0, text: LanguageModule.text("txt_select_value")},
                {value: 1, text: isCompany? LanguageModule.text("txt_company") : LanguageModule.text("txt_department")},
                {value: 2, text: isCompany? LanguageModule.text("txt_company_and_sub_department") : LanguageModule.text("txt_department_and_sub_department")}
            ]
        }
    });
    if (id > 0) level_select.value = host.database.configs.items[index].taskdetails;
    var dataView = [
        [{
            attrs: {colSpan: 3, style: {lineHeight: "var(--control-height)"}},
            children: [
                DOMElement.span({text: title}),
                DOMElement.span({
                    attrs: {style: {fontWeight: "bold"}},
                    text: departmentName
                })
            ]
        }],
        [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
        [{
            attrs: {colSpan: 3, style: {fontWeight: "bold", lineHeight: "var(--control-height)"}},
            text: LanguageModule.text("txt_for_what_object")
        }],
        [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
        [
            {text: LanguageModule.text("txt_permission_level")},
            {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
            level_select
        ],
        [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}]
    ];
    dataView.push(
        [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
        [{
            attrs: {colSpan: 3, style: {fontWeight: "bold", lineHeight: "var(--control-height)"}},
            text: LanguageModule.text("txt_for_what_permission")
        }]
    );
    var listAuthority = hr.orgs.getAuthorityList();
    var checkbox = {};
    var dataAuthorityRow = {};
    for (var k = 0; k < 6; k++){
        dataAuthorityRow[k] = [];
    }
    var k;
    for (var i = 0; i < listAuthority.length; i++){
        checkbox[listAuthority[i].priv] = absol.buildDom({
            tag: "checkbox",
            class: "as-wrap-text",
            style: {
                margin: 0
            },
            props: {
                text: listAuthority[i].text
            }
        });
        k = i % 6;
        dataAuthorityRow[k].push(
            checkbox[listAuthority[i].priv]
        );
    }
    var dataAuthority = [];
    for (var k = 0; k < 6; k++){
        dataAuthority.push(
            dataAuthorityRow[k]
        );
    }
    dataView.push([{
        attrs: {colSpan: 3},
        children: [DOMElement.div({
            attrs: {className: "cardsimpletableclass"},
            children: [DOMElement.table({
                data: dataAuthority
            })]
        })]
    }]);
    var employeeGroupsItems = [{value: 0, text: LanguageModule.text("txt_all_employee_group")}];
    for (var i = 0; i < host.database.employee_groups.items.length; i++){
        if (!host.database.employee_groups.items[i].available) continue;
        employeeGroupsItems.push({
            value: host.database.employee_groups.items[i].id,
            text: host.database.employee_groups.items[i].name
        });
    }
    var employee_group_select = absol.buildDom({
        tag: "selectbox",
        style: {
            width: "100%",
            display: "block"
        },
        props: {
            items: employeeGroupsItems,
            enableSearch: true
        }
    });
    var items = contentModule.getOrgsAndEmployeesListSelectTreeMenuLeaf(host);
    items.unshift({value: 0, text: LanguageModule.text("txt_all_employee"), isLeaf: true});
    var employee_select = absol.buildDom({
        tag: "multichecktreemenu",
        style: {
            width: "100%",
            display: "block"
        },
        props: {
            items: items,
            leafOnly: true,
            enableSearch: true
        }
    });
    dataView.push(
        [{attrs: {style: {height: "20px"}}}],
        [{
            attrs: {colSpan: 3, style: {fontWeight: "bold", lineHeight: "var(--control-height)"}},
            text: LanguageModule.text("txt_for_whom")
        }],
        [
            {text: LanguageModule.text("txt_employee_group")},
            {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
            employee_group_select
        ],
        [{attrs: {style: {height: "var(--control-verticle-distance-2)"}}}],
        [
            {text: LanguageModule.text("txt_employee")},
            {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
            employee_select
        ]
    );
    if (id > 0){
        for (var i = 0; i < listAuthority.length; i++){
            checkbox[listAuthority[i].priv].checked = host.database.configs.items[index].content[listAuthority[i].priv];
        }
        employee_select.values = host.database.configs.items[index].content.employees;
        employee_group_select.values = host.database.configs.items[index].content.employee_groups;
    }

    var res = DOMElement.table({
        data: dataView
    });
    ModalElement.showWindow({
        title: id == 0? LanguageModule.text("txt_add") : LanguageModule.text("txt_edit"),
        bodycontent: res,
        buttonlist: [
            {
                text: LanguageModule.text("txt_save"),
                onclick: function(){
                    var data = res.getValue();
                    if (!data) return;
                    hr.orgs.addPrivSubmit(host, id, data);
                }
            },
            {
                text: LanguageModule.text("txt_cancel"),
                onclick: function(){
                    ModalElement.close();
                }
            }
        ]
    });
    res.getValue = function(){
        var values = {
            properties: {}
        };
        var level = level_select.value;
        if (level == 0){
            ModalElement.alert({message: LanguageModule.text("war_txt_level_is_null")});
            return;
        }
        for (var i = 0; i < listAuthority.length; i++){
            values[listAuthority[i].priv] = checkbox[listAuthority[i].priv].checked;
        }
        values.employee_groups = employee_group_select.values;
        values.employees = employee_select.values;
        return {
            taskid: orgid,
            taskdetails: level,
            content: EncodingClass.string.fromVariable(values)
        };
    };
};

hr.orgs.addPrivPre = function(host, orgid, id){
    ModalElement.show_loading();
    FormClass.api_call({
        url: "database_load.php",
        params: [
            {name: "task", value: "orgs_load_privileges_by_id"},
            {name: "id", value: id}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    var st = EncodingClass.string.toVariable(message.substr(2));
                    var index = host.database.configs.getIndex(id);
                    host.database.configs.items[index] = st;
                    hr.orgs.addPriv(host, orgid, id);
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.getAuthorityList = function(){
    var res = [
        {priv: "view_employee_profiles", text: LanguageModule.text("txt_view_employee_profiles")},
        {priv: "edit_general_information_abilities_contact_communications_other_infomation", text: LanguageModule.text("txt_edit_general_information_abilities_contact_communications_other_infomation")},
        {priv: "edit_employment_contracts_salary_decisions_bank_accounts", text: LanguageModule.text("txt_edit_employment_contracts_salary_decisions_bank_accounts")},
        {priv: "edit_hr_policies", text: LanguageModule.text("txt_edit_hr_policies")},
        {priv: "edit_organization_and_employee", text: LanguageModule.text("txt_edit_organization_and_employee")},
        {priv: "edit_activities", text: LanguageModule.text("txt_edit_activities")},
        // {priv: "view_list", text: LanguageModule.text("txt_view_list")},
        // {priv: "edit_list", text: LanguageModule.text("txt_edit_list")},
        {priv: "handle_onboarding", text: LanguageModule.text("txt_handle_onboarding")},
        {priv: "handle_offboarding", text: LanguageModule.text("txt_handle_offboarding")},
        {priv: "project_setting", text: LanguageModule.text("txt_project_setting")},
        // {priv: "view_request", text: LanguageModule.text("txt_view_request")},
        {priv: "edit_employees_contacts", text: LanguageModule.text("txt_edit_employees_contacts")},
        {priv: "view_scorecard", text: LanguageModule.text("txt_view_scorecard")},
        {priv: "edit_scorecard", text: LanguageModule.text("txt_edit_scorecard")},
        {priv: "input_values", text: LanguageModule.text("txt_input_values")},
        {priv: "approval_values_create_report", text: LanguageModule.text("txt_approval_values_create_report")},
        {priv: "accumulate_values", text: LanguageModule.text("txt_accumulate_values")},
        {priv: "lock_unlock_bsc", text: LanguageModule.text("txt_lock_unlock_bsc")}
    ];
    return res;
};

hr.orgs.viewPrivList = function(host, id){
    return new Promise(function(resolve, reject){
        var employeesDic = contentModule.makeDictionaryIndex(host.database.employees.items);
        var employee_groupsDic = contentModule.makeDictionaryIndex(host.database.employee_groups.items);
        var oIndex = host.database.orgs.getIndex(id);
        var isCompany = host.database.orgs.items[oIndex].parentid == 0;
        var getLevelText = function(level, taskid){
            var res;
            switch (level) {
                case 1:
                res = isCompany? LanguageModule.text("txt_company") : LanguageModule.text("txt_department");
                break;
                case 2:
                res = isCompany? LanguageModule.text("txt_company_and_sub_department") :  LanguageModule.text("txt_department_and_sub_department");
                break;
                default:
                res = "-";
                break;
            }
            if (taskid != id) {
                var oIndex = host.database.orgs.getIndex(taskid);
                if (oIndex >= 0) res += " (" + host.database.orgs.items[oIndex].name + ")";
                else res += " (-)";
            }
            return res;
        };
        var listAuthority = hr.orgs.getAuthorityList();
        host.redrawPrivDetails = function(){
            var employeeFvalue = employee_select.value;
            var employee_groupFvalue = employee_group_select.value;
            DOMElement.removeAllChildren(data_ctn);
            var data = [], row, objectElt, content;
            for (var i = 0; i < host.database.configs.items.length; i++){
                content = host.database.configs.items[i].content;
                if (employeeFvalue != 0){
                    var view = true;
                    if (content.employees.indexOf(0) < 0 && content.employees.indexOf(employeeFvalue) < 0){
                        view = false;
                        if (content.employee_groups.indexOf(0) >= 0){
                            for (j = 0; j < host.database.employee_groups.items.length; j++){
                                if (host.database.employee_groups.items[j].members.indexOf(employeeFvalue) >= 0){
                                    view = true;
                                    break
                                }
                            }
                        }
                        else {
                            for (var j = 0; j < content.employee_groups.length; j++){
                                var gIndex = employee_groupsDic[content.employee_groups[j]];
                                if (gIndex >= 0) if (host.database.employee_groups.items[gIndex].members.indexOf(employeeFvalue) >= 0){
                                    view = true;
                                    break
                                }
                            };
                        }
                    }
                    if (!view) continue;
                }
                if (employee_groupFvalue != 0 && content.employee_groups.indexOf(0) < 0){
                    if (content.employee_groups.indexOf(employee_groupFvalue) < 0) continue;
                }
                objectElt = DOMElement.div({
                    children: [
                        DOMElement.div({
                            text: getLevelText(host.database.configs.items[i].taskdetails, host.database.configs.items[i].taskid)
                        })
                    ]
                });
                var dataAuthority = [], dataAuthorityRow = {};
                for (var k = 0; k < 6; k++){
                    dataAuthorityRow[k] = [];
                }
                var k;
                listAuthority.forEach(function(itemAuthority, aIndex){
                    k = aIndex % 6;
                    dataAuthorityRow[k].push(
                        {
                            children: [absol.buildDom({
                                tag: "checkbox",
                                class: "as-wrap-text",
                                props: {
                                    checked: content[itemAuthority.priv],
                                    disabled: true,
                                    text: itemAuthority.text
                                }
                            })]
                        }
                    );
                });
                for (var k = 0; k < 6; k++){
                    dataAuthority.push(dataAuthorityRow[k]);
                }
                row = [
                    {style: {textAlign: "center"}},
                    {
                        element: objectElt
                    },
                    {
                        element: DOMElement.div({
                            attrs: {className: "cardsimpletableclass"},
                            children: [DOMElement.table({
                                data: dataAuthority
                            })]
                        })
                    }
                ];
                var whomElt = DOMElement.div({});
                var eIndex, eText = "";
                for (var j = 0; j < content.employees.length; j++){
                    if (content.employees[j] == 0){
                        eText += ", " + LanguageModule.text("txt_all_employee");
                    }
                    else {
                        eIndex = employeesDic[content.employees[j]];
                        if (eIndex >= 0) eText += "; " + host.database.employees.items[eIndex].fullname;
                    }
                }
                eText = eText.substr(2);
                whomElt.appendChild(DOMElement.div({
                    children: [
                        DOMElement.span({
                            text: LanguageModule.text("txt_employee") + ": "
                        }),
                        DOMElement.span({
                            attrs: {style: {fontWeight: "bold"}},
                            text: eText
                        })
                    ]
                }));
                var gIndex, gText = "";
                for (var j = 0; j < content.employee_groups.length; j++){
                    if (content.employee_groups[j] == 0){
                        gText += ", " + LanguageModule.text("txt_all_employee_group");
                    }
                    else {
                        gIndex = employee_groupsDic[content.employee_groups[j]];
                        if (gIndex >= 0) gText += "; " + host.database.employee_groups.items[gIndex].name;
                    }
                }
                gText = gText.substr(2);
                whomElt.appendChild(DOMElement.div({
                    children: [
                        DOMElement.span({
                            text: LanguageModule.text("txt_employee_group") + ": "
                        }),
                        DOMElement.span({
                            attrs: {style: {fontWeight: "bold"}},
                            text: gText
                        })
                    ]
                }));
                row.push({
                    element: whomElt
                });
                if (systemconfig.privSystem >= 2){
                    if (host.database.configs.items[i].taskid != id){
                        row.push({});
                    }
                    else {
                        var qmenuButton = DOMElement.div({
                            attrs: {
                                className: "card-icon-cover"
                            },
                            children: [DOMElement.i({
                                attrs: {
                                    className: "material-icons bsc-icon-hover-black"
                                },
                                text: "more_vert"
                            })]
                        });
                        var quickMenuItems = [
                            {
                                text: LanguageModule.text("txt_edit"),
                                icon: {tag: 'i', class: 'material-icons', child: {text: "create"}},
                                extendClasses: ['bsc-quickmenu'],
                                cmd: function (configid) {
                                    return function(){
                                        hr.orgs.addPrivPre(host, id, configid);
                                    }
                                }(host.database.configs.items[i].id)
                            }
                        ];
                        quickMenuItems.push({
                            text: LanguageModule.text("txt_delete"),
                            icon: {tag: 'i', class: 'material-icons', child: {text: "delete"}},
                            extendClasses: ['bsc-quickmenu', 'red'],
                            cmd: function (configid) {
                                return function(){
                                    hr.orgs.deletePrivConfirm(host, configid);
                                }
                            }(host.database.configs.items[i].id)
                        });
                        absol.QuickMenu.showWhenClick(qmenuButton, {items: quickMenuItems}, [3, 4], function (menuItem) {
                            if (menuItem.cmd) menuItem.cmd();
                        });
                        row.push({
                            element: qmenuButton
                        });
                    }
                }
                else {
                    row.push({});
                }
                data.push(row);
            }
            var header = [
                {value: LanguageModule.text("txt_index"), type: "increase"},
                {value: LanguageModule.text("txt_object")},
                {value: LanguageModule.text("txt_authority")},
                {value: LanguageModule.text("txt_employee") + "/ " + LanguageModule.text("txt_employee_group")},
                {}
            ];
            var tableView = pizo.tableView(
                header,
                data
            );
            data_ctn.appendChild(tableView);
        };
        var buttonlist = [
            DOMElement.div({
                attrs: {className: "single-button-header"},
                children: [theme.backButton({
                    onclick: function(){
                        host.frameList.removeLast();
                        resolve();
                    }
                })]
            })
        ];
        if (systemconfig.privSystem >= 2){
            buttonlist.push(DOMElement.div({
                attrs: {className: "single-button-header"},
                children: [theme.addButton({
                    onclick: function(){
                        hr.orgs.addPriv(host, id, 0);
                    }
                })]
            }));
        }
        var buttonPanel = DOMElement.div({
            attrs: {className: 'button-panel-header absol-single-page-header'},
            children: buttonlist
        });
        var employeeGroupsItems = [{value: 0, text: LanguageModule.text("txt_all_employee_group")}];
        for (var i = 0; i < host.database.employee_groups.items.length; i++){
            if (!host.database.employee_groups.items[i].available) continue;
            employeeGroupsItems.push({
                value: host.database.employee_groups.items[i].id,
                text: host.database.employee_groups.items[i].name
            });
        }
        var employee_group_select = absol.buildDom({
            tag: "selectmenu",
            props: {
                items: employeeGroupsItems,
                enableSearch: true
            },
            on: {
                change: function(){
                    host.redrawPrivDetails();
                }
            }
        });
        buttonPanel.appendChild(DOMElement.div({
            attrs: {className: "single-button-header"},
            children: [employee_group_select]
        }));
        var employeeItems = contentModule.getMemberOfEmployeeSelectMenu(host);
        employeeItems[0].text = LanguageModule.text("txt_all_employee");
        var employee_select = absol.buildDom({
            tag: "selecttreeleafmenu",
            props: {
                items: employeeItems,
                enableSearch: true
            },
            on: {
                change: function(){
                    host.redrawPrivDetails();
                }
            }
        });
        buttonPanel.appendChild(DOMElement.div({
            attrs: {className: "single-button-header"},
            children: [employee_select]
        }));
        var departmentName = "", title = LanguageModule.text("txt_permission_to_department");
        var oIndex = host.database.orgs.getIndex(id);
        if (oIndex >= 0){
            if (host.database.orgs.items[oIndex].parentid > 0) title = LanguageModule.text("txt_permission_to_department") + " ";
            else title = LanguageModule.text("txt_permission_to_company") + " ";
            departmentName = host.database.orgs.items[oIndex].name;
        }
        var data_ctn = DOMElement.div({attrs: {style: {paddingBottom: "var(--footer-margin)"}}});
        host.redrawPrivDetails();
        var singlePage = absol.buildDom({
            tag: "singlepage",
            child: [
                buttonPanel,
                DOMElement.div({
                    attrs: {
                        style: {
                            height: "var(--control-height)",
                            lineHeight: "var(--control-height)"
                        }
                    },
                    children: [
                        DOMElement.span({
                            text: title
                        }),
                        DOMElement.span({
                            attrs: {style: {fontWeight: "bold"}},
                            text: departmentName
                        })
                    ]
                }),
                data_ctn
            ]
        });
        host.frameList.addChild(singlePage);
        singlePage.requestActive();
    });
};

hr.orgs.viewPrivListPre = function(host, id){
    return new Promise(function(resolve, reject){
        var loadPriv = function(){
            var departmentparentlist = [], pid;
            var oIndex = host.database.orgs.getIndex(id);
            pid = host.database.orgs.items[oIndex].parentid;
            while (pid != 0){
                departmentparentlist.push(pid);
                oIndex = host.database.orgs.getIndex(pid);
                pid = host.database.orgs.items[oIndex].parentid;
            }
            ModalElement.show_loading();
            FormClass.api_call({
                url: "database_load.php",
                params: [
                    {name: "task", value: "orgs_load_privileges"},
                    {name: "orgid", value: id},
                    {name: "departmentparentlist", value: EncodingClass.string.fromVariable(departmentparentlist)}
                ],
                func: function(success, message){
                    ModalElement.close(-1);
                    if (success){
                        if (message.substr(0, 2) == "ok"){
                            var st = EncodingClass.string.toVariable(message.substr(2));
                            contentModule.makeDatabaseContent(host, st);
                            hr.orgs.viewPrivList(host, id).then(function(){
                                resolve();
                            });
                        }
                        else {
                            ModalElement.alert({message: message});
                        }
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
            });
        };
        loadPriv();
    });
};

hr.orgs.getRow = function(host, item){
    var edit_priv = false, add_priv = false;
    if (systemconfig.privSystem >= 2){
        edit_priv = true;
        add_priv = true;
    }
    else {
        for (var i = 0; i < host.listConfigPrivilegeOfMe.length; i++){
            if (!host.listConfigPrivilegeOfMe[i].content.edit_organization_and_employee) continue;
            if (host.listConfigPrivilegeOfMe[i].departmentList.indexOf(item.id) < 0) continue;
            edit_priv = true;
            if (host.listConfigPrivilegeOfMe[i].taskdetails == 2){
                add_priv = true;
                break;
            }
        }
    }
    var func = {
        clickRowFunc: function(){
            host.orgid = item.id;
        },
        redrawEmployee: function(){
            hr.orgs.redrawEmployee2(host);
        }
    };
    if (edit_priv){
        if (item.parentid > 0){
            func.edit = function(){
                hr.orgs.addDepartmentPre(host, item.parentid, item.id);
            };
            func.change_parent = function(){
                hr.orgs.changeParentForOrg(host, item.id);
            }
        }
        if (add_priv) func.add_department = function(){
            hr.orgs.addDepartmentPre(host, item.id, 0);
        };
        if (item.parentid > 0){
            func.add_position = function(){
                hr.orgs.addPositionPre(host, item.id, 0);
            };
            func.add_employee = function(){
                hr.orgs.addEmployeePre(host, item.id, 0);
            };
            func.delete = function(){
                hr.orgs.deleteOrgConfirm(host, item.id);
            };
        }
    }
    func.edit_priv = function(){
        hr.orgs.viewPrivListPre(host, item.id);
    };
    var res = EncodingClass.string.duplicate(item);
    res.func = func;
    res.child = [];
    var ni;
    for (var i = 0; i < res.childIndexList.length; i++){
        ni = res.childIndexList[i];
        if (!host.orgViewDic[host.database.orgs.items[ni].id]) continue;
        res.child.push(hr.orgs.getRow(host, host.database.orgs.items[ni]));
    }
    return res;
};

hr.orgs.getRowPosition = function(host, item){
    var res = EncodingClass.string.duplicate(item);
    var func = {
        edit: function(){
            hr.orgs.addPositionPre(host, item.orgid, item.id);
        }
    };
    res.func = func;
    return res;
};

hr.orgs.redrawPosition = function(host){
    if (host.orgid == 0){
        host.initPage.redrawPositionTable({});
        return;
    }
    var index = host.database.orgs.getIndex(host.orgid);
    if (index < 0) {
        host.initPage.redrawPositionTable({});
        console.log(host.database, host.orgid);
        return;
    }
    var displayDic = {
        name: true,
        code: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "position", displayDic);
    var redrawTableFunc = function(){
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "position_list").then(function(value){
            var configColumnPosition = value;
            var data = [];
            var pIndex;
            for (var i = 0; i < host.database.orgs.items[index].positionIndexList.length; i++){
                pIndex = host.database.orgs.items[index].positionIndexList[i];
                data.push(hr.orgs.getRowPosition(host, host.database.positions.items[pIndex]));
            }
            host.initPage.redrawPositionTable({
                data: data,
                configColumnPosition: configColumnPosition,
                filterColumnFunc: function(){
                    contentModule.userColumnConfigForm({
                        type: "position_list",
                        columnList: columnList
                    }).then(function(value){
                        host.user_column_configsDic["position_list"] = value;
                        redrawTableFunc();
                    });
                }
            });
        });
    };
    redrawTableFunc();
};

hr.orgs.changeOrgidForEmployeeSubmit = function(host, id, departmentid){
    var index = host.database.employees.getIndex(id);
    if (host.database.employees.items[index].orgid == departmentid){
        ModalElement.close();
        return;
    }
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_channe_orgid_for_employee.php",
        params: [
            {name: "id", value: id},
            {name: "orgid", value: departmentid}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    host.database.employees.items[index].orgid = departmentid;
                    host.database.employees.items[index].firstorgid = departmentid;
                    ModalElement.close();
                    contentModule.makeEmployeesIndex(host);
                    contentModule.makeEmployeeAllData(host);
                    contentModule.makePrivilegeOrgConfigs(host);
                    hr.orgs.redrawEmployee2(host);
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.changeOrgidForEmployee = function(host, id){
    var itemsList = contentModule.getOrgsListSelectTreeMenu(host, {disabledCompany: true});
    var department_select = absol.buildDom({
        tag: "selecttreemenu",
        props: {
            items: itemsList,
            enableSearch: true
        }
    });
    ModalElement.showWindow({
        title: LanguageModule.text("txt_move_department"),
        bodycontent: DOMElement.table({
            data: [[
                {text: LanguageModule.text("txt_move_to_department")},
                {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                department_select
            ]]
        }),
        buttonlist: [
            {
                text: LanguageModule.text("txt_ok"),
                onclick: function(){
                    var departmentid = department_select.value;
                    if (departmentid == 0){
                        ModalElement.alert({message: LanguageModule.text("war_txt_not_yet_select_department")});
                        return;
                    }
                    hr.orgs.changeOrgidForEmployeeSubmit(host, id, departmentid);
                }
            },
            {
                text: LanguageModule.text("txt_cancel"),
                onclick: function(){
                    ModalElement.close();
                }
            }
        ]
    });
};

hr.orgs.changeParentForOrgSubmit = function(host, id, parentid){
    var index = host.database.orgs.getIndex(id);
    if (host.database.orgs.items[index].parentid == parentid){
        ModalElement.close();
        return;
    }
    ModalElement.show_loading();
    FormClass.api_call({
        url: "orgs_change_parentid_for_org.php",
        params: [
            {name: "id", value: id},
            {name: "parentid", value: parentid}
        ],
        func: function(success, message){
            ModalElement.close(-1);
            if (success){
                if (message.substr(0, 2) == "ok"){
                    host.database.orgs.items[index].parentid = parentid;
                    host.database.orgs.items[index].firstparentid = parentid;
                    ModalElement.close();
                    hr.orgs.redraw(host);
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
            else {
                ModalElement.alert({message: message});
            }
        }
    });
};

hr.orgs.changeParentForOrg = function(host, id){
    var index = host.database.orgs.getIndex(id);
    var orgIDList = contentModule.getDepartmentIDList(host, index);
    var noSelectDic = {};
    for (var i = 0; i < orgIDList.length; i++){
        noSelectDic[orgIDList[i]] = true;
    }
    var itemsList = contentModule.getOrgsListSelectTreeMenu(host, {noSelectDic: noSelectDic});
    var department_select = absol.buildDom({
        tag: "selecttreemenu",
        props: {
            items: itemsList,
            enableSearch: true
        }
    });
    ModalElement.showWindow({
        title: LanguageModule.text("txt_move_department"),
        bodycontent: DOMElement.table({
            data: [[
                {text: LanguageModule.text("txt_move_to_department")},
                {attrs: {style: {width: "var(--control-horizontal-distance-2)"}}},
                department_select
            ]]
        }),
        buttonlist: [
            {
                text: LanguageModule.text("txt_ok"),
                onclick: function(){
                    var orgid = department_select.value;
                    if (orgid == 0){
                        ModalElement.alert({message: LanguageModule.text("war_txt_not_yet_select_department")});
                        return;
                    }
                    hr.orgs.changeParentForOrgSubmit(host, id, orgid);
                }
            },
            {
                text: LanguageModule.text("txt_cancel"),
                onclick: function(){
                    ModalElement.close();
                }
            }
        ]
    });
};

hr.orgs.getRowEmployee = function(host, item){
    var func = {};
    if (true){
        func.open = function(){
            hr.orgs.showEmployeePre(host, item.id);
        };
    }
    if (host.employeeEditDic[item.id]){
        func.move_department = function(){
            hr.orgs.changeOrgidForEmployee(host, item.id);
        };
        func.delete = function(){
            hr.orgs.deleteEmployeeConfirm(host, item.id);
        };
    }
    var res = EncodingClass.string.duplicate(item);
    res.func = func;
    return res;
};

hr.orgs.redrawEmployee2 = function(host){
    if (!host.configColumnEmployee){
        hr.orgs.redrawEmployee(host);
        return;
    }
    if (host.orgid == 0){
        if (!hr.isMobile) host.initPage.redrawEmployeeTable({});
        return;
    }
    var index = host.database.orgs.getIndex(host.orgid);
    if (host.database.orgs.items[index].parentid == 0){
        if (!hr.isMobile) host.initPage.redrawEmployeeTable({});
        return;
    }
    var data = [];
    var eIndex;
    for (var i = 0; i < host.database.orgs.items[index].employeeIndexList.length; i++){
        eIndex = host.database.orgs.items[index].employeeIndexList[i];
        if (host.employee_filter_status != -1 && host.database.employees.items[eIndex].available != host.employee_filter_status) continue;
        if (!host.employeeViewDic[host.database.employees.items[eIndex].id]) continue;
        data.push(hr.orgs.getRowEmployee(host, host.database.employees.items[eIndex]));
    }
    host.initPage.redrawEmployeeTable({
        data: data,
        configColumnEmployee: host.configColumnEmployee,
        filterColumnFunc: host.employeeFilterColumnFunc
    });
};

hr.orgs.redrawEmployee = function(host){
    if (host.orgid == 0){
        if (!hr.isMobile) host.initPage.redrawEmployeeTable({});
        return;
    }
    var index = host.database.orgs.getIndex(host.orgid);
    if (host.database.orgs.items[index].parentid == 0){
        if (!hr.isMobile){
            host.initPage.redrawEmployeeTable({});
        }
        return;
    }
    var displayDic = {
        fullname: true,
        code: true,
        userid: true,
        direct_manager: true,
        position: true
    };
    var columnList = contentModule.getColumnListFromDatatype(host, "employee", displayDic)
    var redrawTableFunc = function(){
        ModalElement.show_loading();
        contentModule.getColumnListConfig(host, host.user_column_configsDic, columnList, "employee_list").then(function(value){
            console.log(value);
            ModalElement.close(-1);
            host.configColumnEmployee = value;
            host.employeeFilterColumnFunc = function(){
                contentModule.userColumnConfigForm({
                    type: "employee_list",
                    columnList: columnList
                }).then(function(value){
                    host.user_column_configsDic["employee_list"] = value;
                    redrawTableFunc();
                });
            };
            hr.orgs.redrawEmployee2(host);
        });
    };
    redrawTableFunc();
};

hr.orgs.redraw = function(host){
    return new Promise(function(resolveMn, rejectMn){
        hr.orgs.makeAllIndex(host);
        host.initPage.redrawOrgTable({
            orgid: host.orgid,
            database: host.database,
            user_column_configsDic: host.user_column_configsDic,
            form_config: host.form_config,
            companyid: host.companyid,
            getRow: function(item){
                return hr.orgs.getRow(host, item);
            }
        });
        if (host.orgid === undefined) {
            host.orgid = host.companyid;
        }
        resolveMn(host);
        if (!hr.isMobile){
            hr.orgs.redrawEmployee(host);
        }
    });
};

hr.orgs.preRedraw = function(host){
    return new Promise(function(resolveMn, rejectMn){
        contentModule.makePrivilegeOrgConfigs(host);
        var listCompany = [];
        var ex;
        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;
            listCompany.push(host.database.orgs.items[i]);
        }
        if (!host.companyid && listCompany.length > 0) host.companyid = listCompany[0].id;
        host.initPage.updateSelectCompanyMenu(listCompany);
        hr.orgs.redraw(host).then(function(value){
            resolveMn(value);
        });
    });
};

hr.orgs.addCompanySubmit = function(host, id, getValueFunction){
    return new Promise(function(resolve,reject){
        var data = getValueFunction();
        if (!data) return;
        var oldData;
        if (id != 0){
            var ischange = contentModule.isChanged(host.dataCompanyEdit, data, ["name", "code", "geopos", "extrainfo"]);
            if (!ischange){
                ModalElement.close();
                return;
            }
        }
        data.id = id;
        if (id != 0){
            data.ver = host.dataCompanyEdit.ver;
        }
        else {
            data.ver = 1;
        }
        data.extrainfo = EncodingClass.string.fromVariable(data.extrainfo);
        ModalElement.show_loading();
        FormClass.api_call({
            url: "company_save.php",
            params: [{name: "data", value: EncodingClass.string.fromVariable(data)}],
            func: function(success, message){
                ModalElement.close(-1);
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var st = EncodingClass.string.toVariable(message.substr(2));
                        st.extrainfo = EncodingClass.string.toVariable(st.extrainfo);
                        if (id != 0){
                            var index = host.database.orgs.getIndex(id);
                            st.childIndexList = host.database.orgs.items[index].childIndexList;
                            st.employeeIndexList = host.database.orgs.items[index].employeeIndexList;
                            host.database.orgs.items[index] = st;
                            host.dataCompanyEdit = host.database.orgs.items[index];
                        }
                        else {
                            st.childIndexList = [];
                            st.employeeIndexList = [];
                            host.database.orgs.items.push(st);
                            host.dataCompanyEdit = st;
                        }
                        hr.orgs.preRedraw(host);
                        ModalElement.close();
                    }
                    else if (message == "lock_system"){
                        ModalElement.alert({message: LanguageModule.text("war_txt_system_lock")});
                    }
                    else if (message == "deleted" || message == "edited"){
                        ModalElement.alert({
                            message: LanguageModule.text("war_txt_failed_ver_reload_data")
                        });
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.addCompanyClose = function(host, id, getValueFunction){
    var data = getValueFunction();
    if (!data) {
        ModalElement.close();
        ModalElement.close();
        return;
    }
    if (id != 0){
        var oldData = host.dataCompanyEdit;
        var ischange = contentModule.isChanged(oldData, data, ["name", "code", "geopos", "extrainfo"]);
        if (!ischange){
            ModalElement.close();
            return;
        }
        contentModule.questionChange({
            onclick: function(sel){
                if (sel == 0){
                    hr.orgs.addCompanySubmit(host, id, getValueFunction);
                }
                else if (sel == 1){
                    ModalElement.close();
                }
            }
        });
    }
    else {
        ModalElement.close();
        return;
    }
};

hr.orgs.addCompany = function(host, id = 0){
    var redraw = function(value){
        var formContainer = DOMElement.div({});
        ModalElement.showWindow({
            title: LanguageModule.text("txt_company"),
            bodycontent: formContainer,
            buttonlist: [
                {
                    text: LanguageModule.text("txt_save"),
                    onclick: function(){
                        hr.orgs.addCompanySubmit(host, id, getValueFunction);
                    }
                },
                {
                    text: LanguageModule.text("txt_cancel"),
                    onclick: function(){
                        hr.orgs.addCompanyClose(host, id, getValueFunction);
                    }
                }
            ]
        });
        var getValueFunction;
        contentModule.makeFormData({
            typeid: host.form_config.company.typeid,
            formid: host.form_config.company.input_form,
            initialValue: value,
            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;
                }
            });
        });
    };
    if (id != 0){
        var index = host.database.orgs.getIndex(id);
        var x = EncodingClass.string.duplicate(host.database.orgs.items[index]);
        redraw(x);
    }
    else {
        redraw();
    }
};

hr.orgs.loadDBInit = function(host){
    return new Promise(function(resolve, reject){
        FormClass.api_call({
            url: "database_load.php",
            params: [
                {name: "task", value: "orgs_load_init"}
            ],
            func: function(success, message){
                if (success){
                    if (message.substr(0, 2) == "ok"){
                        var content = EncodingClass.string.toVariable(message.substr(2));
                        host.employeeOfMe = content.employeeOfMe;
                        delete content.employeeOfMe;
                        contentModule.makeDatabaseContent(host, content);
                        console.log(host.database);
                        host.form_config = contentModule.configVariable(host);
                        contentModule.makeEmployeeAllData(host);
                        contentModule.makeEmployeePosition2Data(host);
                        contentModule.makeGeoposOrgsData(host);
                        contentModule.makeEmployeeManagerData(host);
                        contentModule.makeEmployeeGroupMemberIndex(host);
                        hr.orgs.makeAllIndex(host);
                        host.user_column_configsDic = contentModule.getUser_column_configsDic(host);
                        resolve();
                    }
                    else {
                        ModalElement.alert({message: message});
                    }
                }
                else {
                    ModalElement.alert({message: message});
                }
            }
        });
    });
};

hr.orgs.init = function(host){
    return new Promise(function(resolveMn, rejectMn){
        ModalElement.show_loading();
        hr.menu.changeCurrentUrlTab(host, "orgs");
        host.database = {};
        var cmdbutton = {};
        host.employee_filter_status = 1;
        var params = {
            frameList: host.frameList,
            holder: host.holder,
            cmdbutton: cmdbutton,
            func: {
                change_company: function(id){
                    host.companyid = id;
                    host.orgid = undefined;
                    hr.orgs.redraw(host);
                },
                change_filter_employee: function(value){
                    host.employee_filter_status = value;
                    hr.orgs.redrawEmployee2(host);
                },
                export: function(){
                    hr.orgs.exportFunc(host);
                },
                import_update: function(){
                    hr.orgs.importUpdateFunc(host);
                },
                orgChart: function(){
                    hr.orgs.orgChart(host);
                },
                refresh_func: function(){
                    ModalElement.show_loading();
                    hr.orgs.loadDBInit(host).then(function(){
                        ModalElement.close(-1);
                        hr.orgs.preRedraw(host);
                    });
                },
                add_company: function(){
                    hr.orgs.addCompany(host);
                }
            }
        };
        host.initPage = host.funcs.formOrgsInit(params);
        ModalElement.show_loading();
        hr.orgs.loadDBInit(host).then(function(){
            if (params.qmenuButton) params.qmenuButton.style.display = "";
            ModalElement.close(-1);
            if (host.database.orgs.items.length == 0) return;
            hr.orgs.preRedraw(host).then(function(value){
                resolveMn(value);
            });
        });
    });
};
ModuleManagerClass.register({
    name: "Orgs",
    prerequisites: ["ModalElement", "FormClass"]
});

VaKeR 2022