

var addNewSection = new sap.m.Button({text:oBundle.getText("Add_Section"),type:sap.m.ButtonType.Emphasized,
    icon: sap.ui.core.IconPool.getIconURI("add"),press:addSection }).addStyleClass("left_margin");
var updateSecName = new sap.m.Button({text:oBundle.getText("Update_Section_Name"),type:sap.m.ButtonType.Emphasized,
    icon: sap.ui.core.IconPool.getIconURI("add"),press:updateSectionName }).addStyleClass("left_margin");


var oTableTree = new sap.ui.table.TreeTable({
    selectionMode: sap.ui.table.SelectionMode.Single,
    useGroupMode:true,
    visibleRowCount: 14,
    toolbar: new sap.m.Toolbar({ content: [addNewSection,updateSecName,
        new sap.m.ToolbarSpacer(),treeTableTitle]}),
    toggleOpenState: function(oEvent) {
        //alert("enter")
    }
});

oTableTree.setSelectionMode(sap.ui.table.SelectionMode.Single);
oTableTree.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);
oTableTree.addColumn(new sap.ui.table.Column({hAlign: "Center",width: "60px",label: oBundle.getText("Sort"), template: "sort_order"}));
oTableTree.addColumn(new sap.ui.table.Column({label: oBundle.getText("Inspection_Item"), template: "name"}));

oTableTree.addColumn(new sap.ui.table.Column({
    label: oBundle.getText("Type"),
    template: new sap.ui.commons.Image({ height: "25px" }).bindProperty("src", {
        parts: [{ path: "type", type: new sap.ui.model.type.String()}],
        formatter: function (type) {
            if (type != null) {
                if (type == "1") {
                    return "Images/icons/check11.png";
                    this.setWidth("120px");
                } else if (type == "2") {
                    return "Images/icons/check22.png";
                    this.setWidth("50px");
                } else if (type == "3") {
                    return "Images/icons/check3.png";
                    this.setWidth("50px");
                } else if (type == "4") {
                    return "Images/icons/check4.png";
                    this.setWidth("50px");
                }else if (type == "5") {
                    return "Images/icons/check22.png";
                    this.setWidth("50px");
                }else if (type == "6") {
                    return "Images/icons/check22.png";
                    this.setWidth("50px");
                }
            }
        }
    }),
    width: "120px",
    hAlign: "Center"
}));

oTableTree.addColumn(new sap.ui.table.Column({
        label: oBundle.getText("Required"),
        template: new sap.ui.commons.Image({width:"25px",height:"25px"}).bindProperty("src", {
            parts: [{ path: "required", type: new sap.ui.model.type.String()}],
            formatter: function (required) {
                if (required != null) {  
                    if(required=="1"){
                    return "Images/icons/yes.png";
                    }else if(required=="0"){
                        //return "Images/icons/no.png";
                    }
                }
            }
        }),
        width: "80px",
        hAlign: "Center"
}));

oTableTree.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({ text: oBundle.getText("Action")}),
    template: new sap.m.Button({
        type: "Transparent",
        icon: "sap-icon://edit",
        press: function (e) {

            var model = this.getModel();
            var path = e.getSource().getBindingContext().getPath();
            var obj = model.getProperty(path);

            var type = obj['type'];
            var name = obj['name'];
            var source = obj['source'];

            if (source == "0") {
                displayMenuChecklist2(e, obj);
            } else {
                displayMenuChecklist3(e, obj); 
            }
        }
    }),
    width: "70px",
    hAlign: "Center"
}));


var TreeLayoutMatrix = new sap.ui.commons.layout.MatrixLayout({
        columns: 2,
        width: "100%",
        widths: ["70%", "30%"]
    });

var TreeLayout = new sap.m.Page("tree_checklist",{
            title:oBundle.getText("Inspection_Items"),
            showNavButton:true,
            navButtonText:oBundle.getText("Back"),
            showHeader:true,
            enableScrolling:true,
            content : [TreeLayoutMatrix],
            navButtonPress: function (e) {oLayoutCheckList.back();}
        }); 

oLayoutCheckList.addPage(checklistPage1).addPage(TreeLayout).addPage(checklistPage4);


var sectionDB = new  sap.m.ComboBox({layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
selectionChange:function(){
    var subGroupID =  sectionDB.getSelectedKey();
    var getItemAreay = checklistJSONArray3.filter(function (obj, index) {
        return (obj.subgroup_id === subGroupID);
    });
    treeFieldOrder.setValue((getItemAreay.length+1)); 
}

});
sectionDB.addEventDelegate({onAfterRendering: function(e) {sectionDB.$().find("input").attr("readonly", true);}});

var dataTypeRB1 = new sap.m.RadioButton({text:oBundle.getText("Good_Reapir_Replace_NA")});
var dataTypeRB2 = new sap.m.RadioButton({text:oBundle.getText("Yes_No_NA")});
var dataTypeRB3 = new sap.m.RadioButton({text:oBundle.getText("Text_Field")});
var dataTypeRB4 = new sap.m.RadioButton({text:oBundle.getText("Number")});
			
var dataTypeRB5 = new sap.m.RadioButton({text:oBundle.getText("Pass_Fail_NA")});
var dataTypeRB6 = new sap.m.RadioButton({text:oBundle.getText("Ok_Faulty_NA")});
				
var dataTypeRG = new sap.m.RadioButtonGroup({columns : 6,
        buttons:[dataTypeRB1,dataTypeRB2,dataTypeRB3,dataTypeRB4,dataTypeRB5,dataTypeRB6],
        select: function (e) {
            if (dataTypeRB4.getSelected()) {
                sap.ui.getCore().getElementById('rangeSection').setVisible(true);
            }else{
                sap.ui.getCore().getElementById('rangeSection').setVisible(false);
            }
        }
});

 var treeField1 = new sap.m.Input({});
 var treeFieldRange1 = new sap.m.Input({width:"80%",type:"Number"});
 var treeFieldRange2 = new sap.m.Input({width:"70%",type:"Number"});

 var rangeLayout = new sap.ui.layout.HorizontalLayout({content:[treeFieldRange1,treeFieldRange2]});

 var requiredCB = new sap.m.CheckBox({
        text: oBundle.getText("Required"),
        valueState: "Success",
        select: function (e) {}
    });
 var procedureNote = new sap.m.TextArea({width:"100%",rows : 3, wrapping : sap.ui.core.Wrapping.on}).addStyleClass("field");
 var treeFieldOrder = new sap.m.Input({value:"1",width:"100px",type:"Number"});

 var treeForm1 = new sap.ui.layout.form.Form({
    editable: true,
    title:oBundle.getText("Add_Inspection_Item"),
    layout: new sap.ui.layout.form.ResponsiveGridLayout(),
    formContainers: [
        new sap.ui.layout.form.FormContainer({
            formElements: [
                new sap.ui.layout.form.FormElement({
                    label: new sap.m.Label({required: true, text: oBundle.getText("Add_under_Section")}),
                    fields: [sectionDB]
                }),
                new sap.ui.layout.form.FormElement({
                    label: new sap.m.Label({required: true, text: oBundle.getText("Inspection_Item")}),
                    fields: [treeField1]
                }),
                new sap.ui.layout.form.FormElement({
                    label: new sap.m.Label({text: oBundle.getText("Type")}),
                    fields: [dataTypeRG]
                }),
                new sap.ui.layout.form.FormElement({
                    id:"rangeSection",
                    visible:false,
                    label: new sap.m.Label({required: true, text: oBundle.getText("Range")}),
                    fields: [rangeLayout]
                }),
                new sap.ui.layout.form.FormElement({
                    fields: [requiredCB
                        ]
                }),
                new sap.ui.layout.form.FormElement({
                    fields: [
                        new sap.ui.layout.HorizontalLayout({content:[
                            new sap.m.Label({required: true, text: oBundle.getText("Sort_Order")}).addStyleClass("sapUiTinyMarginTop"),treeFieldOrder]})]
                }),
                    new sap.ui.layout.form.FormElement({
                    label: new sap.m.Label({ text: oBundle.getText("Instructions")}),
                    fields: [procedureNote]
                }),
                
                new sap.ui.layout.form.FormElement({
                    fields: [new sap.m.Button({text:oBundle.getText("Save"),type:sap.m.ButtonType.Emphasized,
                        icon: sap.ui.core.IconPool.getIconURI("save"),press:addChecklistItem })]
                }),
                ]
            }),
    ]
});


var sectionDBUpdate = new  sap.m.ComboBox({layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
});
function updateSectionName(){
    sectionDBUpdate.addEventDelegate({onAfterRendering: function(e) {sectionDBUpdate.$().find("input").attr("readonly", true);}});
    var newSectionName = new sap.m.Input({value:""});
    var FormName1 = new sap.ui.layout.form.Form({
        editable: true,
   
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("Section_Name")}),
                        fields: [sectionDBUpdate]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("New_Section_Name")}),
                        fields: [newSectionName]
                    }),
                    ]
                }),
        ]
    });

    var updateBtn = new sap.m.Button({
        text:"Update",
        icon:"",
        press:function(){
            let sectionID = sectionDBUpdate.getSelectedKey();
            let sectionNewName = newSectionName.getValue();
            if (validation(sectionID, oBundle.getText("Old_Section_Name"))) { return; }
            if (validation(sectionNewName, oBundle.getText("New_Section_Name"))) { return; }
            busyDialog.open();

            Grab_Checklist2.update({id:sectionID, master_email: emailUser, sub_group: sectionNewName }).done(function () {

                funGetTreeChecklist("form_page");
                addHistoryTableData(sectionNewName,"Update","Checklist2",{"sub_group":sectionDBUpdate.getValue()},{"sub_group":sectionNewName});
                busyDialog.close();
                funGetChecklist();
                oDialog.close();
                sap.m.MessageBox.success(oBundle.getText("Done"));
            }, failure);
        }
    })

    var oDialog = new sap.m.Dialog({ contentWidth: "50%", draggable: true, resizable: true,
        title: oBundle.getText("Update_Section_Name"),
        content: [
            FormName1
        ],
        buttons: [updateBtn,
            new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
        ]
    }).open();
}

 //TreeLayoutMatrix.createRow(addNewSection);
TreeLayoutMatrix.createRow(oTableTree,treeForm1);


function addSection(){
    
    var textField = new sap.m.Input({value: "", width: "100%" });
    
     var oDialogChecklist2 = new sap.m.Dialog({
        modal : true,
        title: oBundle.getText("Add_Section"),
        state: sap.ui.core.ValueState.Success,
        content: [textField],
        buttons: [
                    new sap.m.Button({
					    text: oBundle.getText("Add"),
					    icon: "sap-icon://add",
					    press: function () {
                            var value = textField.getValue();
                            if (validation(value, oBundle.getText("Section"))) { return; }
                            busyDialog.open();
                             Grab_Checklist2.insert({ master_email: emailUser, group_id:group_id,sub_group: value }).done(function () {
                                funGetTreeChecklist("form_page");
                                addHistoryTableData(value,"Insert","Checklist2");
                                busyDialog.close();

                               }, failure);
					        oDialogChecklist2.close();
					    }
					}),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialogChecklist2.close();
					    }
					})
				]
    }).open();
}

 function updateSection(mid,subgroup_name){
      
    var new_subgroup_name = subgroup_name;
    var textField = new sap.m.Input({value:""+new_subgroup_name, width: "100%" });
    
     var oDialog = new sap.m.Dialog({
        modal : true,
        title: oBundle.getText("Update_Section"),
        state: sap.ui.core.ValueState.Success,
        content: [textField],
        buttons: [
                    new sap.m.Button({
					    text: oBundle.getText("Update"),
					    icon: "sap-icon://edit",
					    press: function () {
                             var value = textField.getValue();
                            if (validation(value, oBundle.getText("Section"))) { return; }
                            busyDialog.open();
                            Grab_Checklist2.update({id:mid, master_email: emailUser, sub_group: value }).done(function () {
                                addHistoryTableData(value,"Update","Checklist2",{"sub_group":subgroup_name},{"sub_group":value});
                                funGetTreeChecklist("form_page");
                                busyDialog.close();
                                funGetChecklist();
                                oDialog.close();
                                sap.m.MessageBox.success(oBundle.getText("Done"));
                            }, failure);
					    }
					}),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();

  }

var sectionDBEdit = new  sap.m.ComboBox({width:"100%",layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"})});
sectionDBEdit.addEventDelegate({
    onAfterRendering: function(e) {
        sectionDBEdit.$().find("input").attr("readonly", true);
    }
});

function updateChecklistTree(obj){

    var mid = obj['id'];
    var checklist_name = obj['name'];
    var sub_group_id = obj['sub_group'];
    var type = obj['type'];
    var required =  obj['required'];
    var instruction =  obj['instruction'];
    var range =  obj['range'];
    var sort_order =  obj['sort_order'];
    
    var dataTypeRB1 = new sap.m.RadioButton({text:oBundle.getText("Good_Reapir_Replace_NA")});
    var dataTypeRB2 = new sap.m.RadioButton({text:oBundle.getText("Yes_No_NA")});
    var dataTypeRB3 = new sap.m.RadioButton({text:oBundle.getText("Text_Field")});
    var dataTypeRB4 = new sap.m.RadioButton({text:oBundle.getText("Number")});
			
    var dataTypeRB5 = new sap.m.RadioButton({text:oBundle.getText("Pass_Fail_NA")});
    var dataTypeRB6 = new sap.m.RadioButton({text:oBundle.getText("Ok_Faulty_NA")});


    var dataTypeRG = new sap.m.RadioButtonGroup({columns : 6,
        buttons:[dataTypeRB1,dataTypeRB2,dataTypeRB3,dataTypeRB4,dataTypeRB5,dataTypeRB6],
        select: function (e) {
            if (dataTypeRB4.getSelected()) {
               rangeSectionFormElement.setVisible(true);
            }else{
                 rangeSectionFormElement.setVisible(false);
            }
        }
});

 var treeField1 = new sap.m.Input({});
 var treeFieldRange1 = new sap.m.Input({width:"80%",type:"Number"});
 var treeFieldRange2 = new sap.m.Input({width:"70%",type:"Number"});

 var rangeLayout = new sap.ui.layout.HorizontalLayout({content:[treeFieldRange1,treeFieldRange2]});

 var rangeSectionFormElement = new sap.ui.layout.form.FormElement({
     visible: false,
     label: new sap.m.Label({ required: true, text: oBundle.getText("Range")}),
     fields: [rangeLayout]
 });

 var requiredCB = new sap.m.CheckBox({
        text: oBundle.getText("Required"),
        selected: true,
        valueState: "Success",
        select: function (e) {}
    });
 var procedureNote = new sap.m.TextArea({width:"100%",height:"100px",rows : 3, wrapping : sap.ui.core.Wrapping.on}).addStyleClass("field");
 var treeFieldOrder = new sap.m.Input({width:"100px",type:"Number"});

 sectionDBEdit.setSelectedKey(sub_group_id);
 treeField1.setValue(checklist_name);
 dataTypeRG.setSelectedIndex((parseInt(type)-1));

 procedureNote.setValue(instruction);
 treeFieldOrder.setValue(sort_order);
 
 if(required=="1"){
     requiredCB.setSelected(true);
 }else{
     requiredCB.setSelected(false);
 }

 if(type=="4"){
     var rangeArray = range.split("-");
    treeFieldRange1.setValue(rangeArray[0]);
    treeFieldRange2.setValue(rangeArray[1]);
    rangeSectionFormElement.setVisible(true);
 }else{
     rangeSectionFormElement.setVisible(false);
 }

 var treeForm12 = new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("Add_under_Section")}),
                        fields: [sectionDBEdit]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("Inspection_Item")}),
                        fields: [treeField1]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({text: oBundle.getText("Type")}),
                        fields: [dataTypeRG]
                    }),
                    rangeSectionFormElement,
                    new sap.ui.layout.form.FormElement({
                        fields: [requiredCB]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({required: true, text: oBundle.getText("Sort_Order")}),
                        fields: [treeFieldOrder]
                    }),
                        new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: oBundle.getText("Instructions")}),
                        fields: [procedureNote]
                    }),
                    
                    ]
                }),
        ]
    });

 var oDialogChecklist2 = new sap.m.Dialog({contentWidth: "40%", contentHeight: "100%",draggable: true, resizable: true,
			    modal: true,
			    title: oBundle.getText("Update_Inspection_Item"),
			   // state: sap.ui.core.ValueState.Success,
			    content: [treeForm12],
			    buttons: [
                    new sap.m.Button({
                        text: oBundle.getText("Update"),
                        icon: "sap-icon://edit",
                        press: function () {

                            var sectionIndex = sectionDBEdit.indexOfItem(sectionDBEdit.getSelectedItem());
                            
                            var subGroupID = sectionDBEdit.getSelectedKey();
                            var checklistName = treeField1.getValue();
                            var data_type = dataTypeRG.getSelectedIndex() + 1;
                            var required = requiredCB.getSelected();
                            var instruction = procedureNote.getValue();
                            var sort_order = treeFieldOrder.getValue();

                            var range1 = treeFieldRange1.getValue();
                            var range2 = treeFieldRange2.getValue();

                            if (subGroupID == "select") {
                                sap.m.MessageBox.error(oBundle.getText("Select_Section_in_which_you_want_to_add_checklist_item"));
                                return;
                            }
                            if (validation(checklistName, oBundle.getText("Inspection_Item"))) { return; }
                            if (validation(sort_order, oBundle.getText("Sort_Order"))) { return; }

                            var rangeValue = "0-0";
                            if (data_type == 4) {
                                if (validation(range1, oBundle.getText("Range"))) { return; }
                                if (validation(range2, oBundle.getText("Range"))) { return; }
                                rangeValue = range1 + "-" + range2;
                            } else {
                                rangeValue = "0-0";
                            }

                            if (required) {
                                required = "1";
                            } else {
                                required = "0";
                            }

                            busyDialog.open();

                            var updateItems = { id: mid, 
                                checklist: checklistName, data_type: data_type, required: required, range: rangeValue, instruction: instruction,
                                sort_order:sort_order
                            };
                            Grab_Checklist3.update(updateItems).done(function () {
                                funGetTreeChecklist("",sectionIndex);
                                addHistoryTableData(updateItems['checklist'],"Update","Checklist3",
                                    {
                                        checklist:obj['name'],
                                        data_type:obj['type'],
                                        id:obj['id'],
                                        instruction:obj['instruction'],
                                        range:obj['range'],
                                        required:obj['required'],
                                        sort_order:obj['sort_order']
                                    },
                                    updateItems);
                                busyDialog.close();
                                oDialogChecklist2.close();
                            }, failure);
                        }
                    }),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialogChecklist2.close();
					    }
					})
				]
			}).open();
}

function addChecklistItem() {

   // oTableTree.expand(1);

    var sectionIndex = sectionDB.indexOfItem(sectionDB.getSelectedItem());
   
   var subGroupID =  sectionDB.getSelectedKey();
   var checklistName =  treeField1.getValue();
   var data_type = dataTypeRG.getSelectedIndex()+1;
   var required =  requiredCB.getSelected();
   var instruction = procedureNote.getValue();
   var sort_order = treeFieldOrder.getValue();

   var range1 = treeFieldRange1.getValue();
   var range2 = treeFieldRange2.getValue();

   if(subGroupID=="select"){
       sap.m.MessageBox.error(oBundle.getText("Select_Section_in_which_you_want_to_add_checklist_item"));
       return;
   }
    if (validation(checklistName, oBundle.getText("Inspection_Item"))) { return; }
    if (validation(sort_order, oBundle.getText("Sort_Order"))) { return; }

    var rangeValue = "0-0";
    if(data_type==4){
        if (validation(range1, oBundle.getText("Range"))) { return; }
        if (validation(range2, oBundle.getText("Range"))) { return; }
        rangeValue = range1 +"-"+ range2;
    }else{
        rangeValue = "0-0";
    }

    if(required){
        required = "1";
    }else{
        required = "0";
    }
    busyDialog.open();

    Grab_Checklist3.insert({ master_email: emailUser, group_id: group_id, subgroup_id: subGroupID, checklist: checklistName,
        data_type: data_type, required: required, range: rangeValue, instruction: instruction,sort_order:sort_order
    }).done(function () {

        funGetTreeChecklist("",sectionIndex);
        clearFieldChecklistItem();
        busyDialog.close();
        addHistoryTableData(checklistName,"Insert","Checklist3");
        var getItemAreay = checklistJSONArray3.filter(function (obj, index) {
            return (obj.subgroup_id === subGroupID);
        });
        treeFieldOrder.setValue((getItemAreay.length+2));  

    }, failure);



  }

function clearFieldChecklistItem(){
    
    treeField1.setValue("");
    procedureNote.setValue("");
    treeFieldRange1.setValue("");
    treeFieldRange2.setValue("");
     
}

function funGetTreeChecklist(source,sectionIndex) {

    busyDialog.open();
    Grab_Checklist2.where({ master_email: emailUser, group_id: group_id }).includeTotalCount().take(1000).read().done(function (results) {

        //results.splice(0, 0, { id: "select", sub_group:oBundle.getText("Select_Section")});

         results.sort(function (a, b) {
            a = a.sub_group.toLowerCase();
            b = b.sub_group.toLowerCase();
            return a < b ? -1 : a > b ? 1 : 0;
        }
       );


        var oModelSectionDB = new sap.ui.model.json.JSONModel();
        oModelSectionDB.setData({ modelData: results });

        var oItemTemplate1 = new sap.ui.core.ListItem();
        oItemTemplate1.bindProperty("key", "id");
        oItemTemplate1.bindProperty("text", "sub_group");
        
        
        sectionDBEdit.setModel(oModelSectionDB);
        sectionDBEdit.bindItems("/modelData", oItemTemplate1);
       
        if(source=="form_page"){
            sectionDB.setModel(oModelSectionDB);
            sectionDB.bindItems("/modelData", oItemTemplate1);
            sectionDBUpdate.setModel(oModelSectionDB);
            sectionDBUpdate.bindItems("/modelData", oItemTemplate1);
            
            sectionDB.setSelectedKey("select");
        }

        getTreeCheck(results,sectionIndex);

    });
  }

var checklistJSONArray3;

function getTreeCheck(sub_group,sectionIndex) {

    Grab_Checklist3.where({ master_email: emailUser, group_id: group_id }).take(1000).orderByDescending("checklist").read().done(function (results) {
    
        var sub_group_array_Check = [];
        var sub_group_array = [];
        var checklist_array = {};
        checklistJSONArray3 = results;
        for (var i = 0; i < results.length; i++) {

            var subgroup_id = results[i]['subgroup_id'];
            var checklist_id = results[i]['id'];
            var checklist = results[i]['checklist'];
            var data_type = results[i]['data_type'];
            var range = results[i]['range'];
            var required = results[i]['required'];
            var instruction = results[i]['instruction'];
            var sort_order = results[i]['sort_order'];
            var sub_group_name = "";

            for (var j = 0; j < sub_group.length; j++) {
                if (subgroup_id == sub_group[j]['id']) {
                    sub_group_name = sub_group[j]['sub_group'];
                }
            }

            if (sub_group_array_Check.indexOf(subgroup_id) === -1) {

                sub_group_array_Check.push(subgroup_id);
                sub_group_array.push({ id: subgroup_id, name: sub_group_name, source: "0" });
                checklist_array[sub_group_name] = [];
            }
            checklist_array[sub_group_name].push({ id: checklist_id, name: checklist, type: data_type, range: range, 
                instruction: instruction, required: required, source: "1", sub_group: subgroup_id,sort_order:sort_order });
        }

        for (var j = 0; j < sub_group.length; j++) {
            if (sub_group_array_Check.indexOf(sub_group[j]['id']) === -1 && sub_group[j]['id'] != "select") {
                sub_group_array.push({ id: sub_group[j]['id'], name: sub_group[j]['sub_group'], source: "0" });
                checklist_array[sub_group[j]['sub_group']] = [];
            }
        }

        sub_group_array.sort(function (a, b) {
            a = a.name.toLowerCase();
            b = b.name.toLowerCase();
            return a < b ? -1 : a > b ? 1 : 0;
        }
       );

        var oData = sub_group_array.map(function (name) {
            var o = name; //{ name: name.name };

           /* checklist_array[name.name].sort(function (a, b) {
                a = a.name.toLowerCase();
                b = b.name.toLowerCase();
                    return a < b ? -1 : a > b ? 1 : 0;
                }
            );*/
             checklist_array[name.name].sort(function (a, b) {
                a = parseInt(a.sort_order);
                b = parseInt(b.sort_order);
                return a < b ? -1 : a > b ? 1 : 0;
             });

            checklist_array[name.name].forEach(function (p, i) {
                o[i] = p; //{name: p};
            });
            return o;
        });

        var oModel = new sap.ui.model.json.JSONModel({modelData: oData});

        oTableTree.setModel(oModel);
        oTableTree.bindRows({path: "/modelData"});

        oTableTree.setGroupHeaderProperty("name");
        busyDialog.close();

        if(sectionIndex>-1){
            oTableTree.expand(sectionIndex);
        }
                
    });
  }
