
var hvi_default_type = sessionStorage.getItem('oxmaint_default_type');
var oTableTeam = new sap.m.Table({growing: true,mode: "SingleSelectMaster",noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),growingThreshold: 25,mode:"None",growingScrollToLoad: false,
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    columns: [
        new sap.m.Column({ width: "100px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }) }),
        new sap.m.Column({ width: "80px",hAlign: "Center",header: new sap.m.Label({ text: "", design: sap.m.LabelDesign.Bold}) }),
        new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Name"), design: sap.m.LabelDesign.Bold }) }),
        new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("User_ID"), design: sap.m.LabelDesign.Bold }) }),
        new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("notification_email"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true
        }),
        new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Assigned_Vehicle"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true, hAlign: "Center",width: "150px"
        }),
        new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("User_Access_Area"), design: sap.m.LabelDesign.Bold }),
            minScreenWidth: "1500px", popinDisplay: "Inline", demandPopin: true, hAlign: "Left"
        }),
        new sap.m.Column({width: "100px", header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }) })
]});

var teamTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({type: "Emphasized",icon: "sap-icon://action",text: oBundle.getText("Action"),
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj1 = model.getProperty(path);
                displayMenuTeamMember(event, obj1);
            }
        }),
        new sap.f.Avatar({ src: "{image}",displaySize: "S",displayShape: "Circle",imageFitType: "Cover",
        initials: { path: "name",
            formatter: function (value) {
                if(value!=null){
                    var arr = value.split(" ");
                    var secW = "";
                    if(arr[1]!=null){
                        secW = arr[1].charAt(0);
                    }
                    return arr[0].charAt(0)+secW;
                }
            }}}),
        new sap.m.VBox({
            items:[ new sap.tnt.InfoLabel({colorScheme:6,
                text: { path: "role",
                    formatter: function (role) {
                        if(role=="1"||role==oBundle.getText("Operator")){
                            return oBundle.getText("Operator");
                        }else if(role=="2"||role==oBundle.getText("Technician")){
                            return oBundle.getText("Technician");
                        }else if(role=="3"||role==oBundle.getText("Employee")){
                            return oBundle.getText("Employee");
                        }else if(role=="4"){
                            return oBundle.getText("Sub_Admin");
                        }  
                    }
                }}),
                new sap.m.Label({wrapping:true,text: "{name}"}).addStyleClass("sapUiTinyMarginTop"),
            ]}).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({ text: "{emailid}"}),
        new sap.m.Label({ text: "{notification_email}"}),
        new sap.m.Button({icon: "sap-icon://inventory",type: sap.m.ButtonType.Accept,
            text: {path: "assign_vehicle",
                formatter: function (value) {
                    
                    if (value != null && value != "") {
                            var oArray = value.split("^"); 
                            if (oArray.length > 0) {
                            this.setType(sap.m.ButtonType.Accept);
                            if (oArray[0] == "1") {
                                return oBundle.getText("All");
                            } else {
                                return (oArray.length);
                            }
                        } else {
                            this.setType(sap.m.ButtonType.Reject);
                            return "0";
                        }
                    }else{
                        this.setType(sap.m.ButtonType.Reject);
                        return "0";
                    }
                }
            },
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                viewAssignedVehicle(obj['assign_vehicle']);
            }
        }),
        new sap.m.Label({ wrapping: true,
            text: {path: "user_access",
                formatter: function (value) {
                    if (value != null) {
                        var oValue = "";
                        var splitArray = value.split(",");
                        if (splitArray.indexOf("1") > -1 || splitArray.indexOf("Inspection") > -1) {
                            oValue = oValue + oBundle.getText("Inspection") + ",";
                        }
                        // if (splitArray.indexOf("2") > -1 || splitArray.indexOf("Daily") > -1) {
                        //     oValue = oValue + oBundle.getText("Daily_Inspection") + ",";
                        // }
                        if (splitArray.indexOf("3") > -1 || splitArray.indexOf("Inventory") > -1) {
                            oValue = oValue + oBundle.getText("Vehicles") + ",";
                        }
                        if (splitArray.indexOf("4") > -1 || splitArray.indexOf("Checklist") > -1) {
                            oValue = oValue + oBundle.getText("Forms") + ",";
                        }
                        if (splitArray.indexOf("5") > -1 || splitArray.indexOf("Workorder") > -1) {
                            oValue = oValue + oBundle.getText("Workorder") + ",";
                        }
                        if (splitArray.indexOf("6") > -1 || splitArray.indexOf("Scheduler") > -1) {
                            oValue = oValue + oBundle.getText("Service_Schedule") + ",";
                        }
                        if (splitArray.indexOf("7") > -1 || splitArray.indexOf("Incident Report") > -1) {
                            oValue = oValue + oBundle.getText("Incident_Report") + ",";
                        }
                        // if (splitArray.indexOf("8") > -1 || splitArray.indexOf("Fuel Log") > -1) {
                        //     oValue = oValue + oBundle.getText("Fuel_Management") + ",";
                        // }
                        if (splitArray.indexOf("9") > -1 || splitArray.indexOf("Summary") > -1) {
                            oValue = oValue + oBundle.getText("Report") + ", ";
                        }
                        if (splitArray.indexOf("10") > -1 || splitArray.indexOf("User") > -1) {
                            oValue = oValue + oBundle.getText("Team_Management") + ", ";
                        }
                        if (splitArray.indexOf("11") > -1 || splitArray.indexOf("Account") > -1) {
                            oValue = oValue + oBundle.getText("Account")+ ", ";
                        }
                        if (splitArray.indexOf("12") > -1 || splitArray.indexOf("Reminder") > -1) {
                            oValue = oValue + oBundle.getText("Reminder")+ ", ";
                        }
                        if (splitArray.indexOf("13") > -1 || splitArray.indexOf("Parts Inventory") > -1) {
                            oValue = oValue + oBundle.getText("Parts_Inventory")+ ", ";
                        }
                        if (splitArray.indexOf("14") > -1) {
                            oValue = oValue + oBundle.getText("Request")+ ", ";
                        }
                        if (splitArray.indexOf("15") > -1) {
                            oValue = oValue + oBundle.getText("Labor_Code")+ ", ";
                        }
                        if (splitArray.indexOf("16") > -1) {
                            oValue = oValue + oBundle.getText("Fault_List")+ ", ";
                        }
                        // if (splitArray.indexOf("17") > -1) {
                        //     oValue = oValue + oBundle.getText("Tool_Management")+ ", ";
                        // }
                        if (splitArray.indexOf("18") > -1) {
                            oValue = oValue + oBundle.getText("Site")+ ", ";;
                        }
                        if (splitArray.indexOf("19") > -1) {
                            oValue = oValue + oBundle.getText("Purchase_Order")+ ", ";
                        }
                        if (splitArray.indexOf("20") > -1) {
                            oValue = oValue + oBundle.getText("PO_Approval")+ ", ";
                        }
                        if (splitArray.indexOf("21") > -1) {
                            oValue = oValue + oBundle.getText("Demand_Parts")+ ", ";
                        }
                        if (splitArray.indexOf("22") > -1) {
                            oValue = oValue + oBundle.getText("Vendors")+ ", ";
                        }
                        if (splitArray.indexOf("27") > -1) {
                            oValue = oValue + oBundle.getText("Documents")+ ", ";
                        }
                        // if (splitArray.indexOf("23") > -1) {
                        //     oValue = oValue + oBundle.getText("Tyre_Inventory")+ ", ";
                        // }
                        // if (splitArray.indexOf("24") > -1) {
                        //     oValue = oValue + oBundle.getText("Logbook")+ ", ";

                        // }if (splitArray.indexOf("26") > -1) {
                        //     oValue = oValue + oBundle.getText("Task_Master")+ ", ";
                        // }
                        // if (splitArray.indexOf("25") > -1) {
                        //     oValue = oValue + oBundle.getText("Bunker");
                        // }
                        return oValue;
                    }
                }
            }
        }),
        new sap.tnt.InfoLabel({colorScheme:6,
            text: { path: "active",
                formatter: function (active) {
                    if(active=="1"){
                        this.setColorScheme(3);
                        return oBundle.getText("Inactive");
                    }else {
                        this.setColorScheme(8);
                        return oBundle.getText("Active");
                    }
                }
            }}),
    ],
    highlight: {
        path: "user_block",
        formatter: function (block) {
            if (block != null) {
                if (block == "Yes" || block == "2") {
                    return "Error";
                } else {
                    return "Success";
                }
            }
            return "None";
        }
    }
});

var VSDTeam = new sap.m.ViewSettingsDialog({
        confirm: function (oEvent) {
            var p = oEvent.getParameters(),
                oSorter = null;
            if (p.sortItem) {
                oSorter = p.sortItem.getCustomData()[0].getValue();
                var key = p.sortItem.getCustomData()[0].getKey();

                var sortType = sap.ui.core.SortOrder.Descending;
                if (this.getSortDescending()) {
                    sortType = sap.ui.core.SortOrder.Descending;
                } else {
                    sortType = sap.ui.core.SortOrder.Ascending;
                }

                oTableTeam.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);
                oTableTeam.getColumns()[3].setSortIndicator(sap.ui.core.SortOrder.None);
                oTableTeam.getColumns()[4].setSortIndicator(sap.ui.core.SortOrder.None);
            
                if (key == "1") {
                    oTableTeam.getColumns()[2].setSortIndicator(sortType);
                } else if (key == "2") {
                    oTableTeam.getColumns()[3].setSortIndicator(sortType);
                } else if (key == "3") {
                    oTableTeam.getColumns()[4].setSortIndicator(sortType);
                } 
                if (oSorter) {
                    oSorter.bDescending = p.sortDescending;
                    oTableTeam.getBinding("items").sort(oSorter);
                }
            }
        }
    });
oTableTeam.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.Descending);

VSDTeam.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("Name"),
    selected: true,
    customData: new sap.ui.core.CustomData({
        key:"1",
        value: new sap.ui.model.Sorter("name", false)
    })
}));
VSDTeam.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("User_ID" ),
    customData: new sap.ui.core.CustomData({
        key:"2",
        value: new sap.ui.model.Sorter("emailid", false)
    })
}));
VSDTeam.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("notification_email"),
    customData: new sap.ui.core.CustomData({
        key:"3",
        value: new sap.ui.model.Sorter("notification_email", false)
    })
}));



oTableTeam.setHeaderToolbar(new sap.m.Toolbar({
content: [
    new sap.m.Button({ 
        text: oBundle.getText("Add_Team_Member"), 
        type:sap.m.ButtonType.Emphasized,
        icon: sap.ui.core.IconPool.getIconURI("add"), 
        press: function(){
                
            AddUpdateDialog(1);
                
        } 
    }),
    new sap.m.Button({ 
        text: oBundle.getText("Add_New_WO"), 
        type:sap.m.ButtonType.Emphasized,
        icon: sap.ui.core.IconPool.getIconURI("add"), 
        press: function(){
            workorderViewNew();
        }
    }),
    new sap.m.ToolbarSpacer(),
    // new sap.m.Button({ 
    //     text: oBundle.getText("Add_Documents"), 
    //     type:sap.m.ButtonType.Emphasized,
    //     icon: sap.ui.core.IconPool.getIconURI("add"), 
    //     press: function(){
    //         addTeamDocDialog(1);
    //     } 
    // }),
    new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
            var oBinding = oTableTeam.getBinding("items");
            var searchStr = this.getValue();
            if (oBinding) {
                var oFilters = [
                new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("emailid", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("password", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("notification_email", sap.ui.model.FilterOperator.Contains, searchStr),
                //new sap.ui.model.Filter("user_block", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("user_access", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                new sap.ui.model.Filter("mobile", sap.ui.model.FilterOperator.Contains, searchStr),
                ];
                var filterObj = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObj);
            } else {
                oBinding.filter([]);
            }
        }

    }),
    new sap.m.Button({icon: "sap-icon://sort",press: function () {
            VSDTeam.open();
    }}),
    new sap.m.MenuButton({
        icon: "sap-icon://menu",
        menu: new sap.m.Menu({
            itemSelected: function(oEvent) {
                var key = oEvent.getParameter("item").getKey();
                if(key == "1"){
                
                    if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                        teamExcelExport();
                    }else{
                        sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
                        return;
                    }
                }
            },
            items: [
                new sap.m.MenuItem({key: "1",text: oBundle.getText("Excel_Export"),
                icon: "sap-icon://excel-attachment",
                })         
            ]
        })
    })
    ]
    }));

function teamExcelExport(){

    var xlsHeader = [oBundle.getText("Role"),
                        oBundle.getText("Name"), 
                        oBundle.getText("User_ID"),
                        oBundle.getText("Email"),
                        oBundle.getText("Blocked"),
                        oBundle.getText("User_Access_Area"),
                        oBundle.getText("Assigned_Vehicle")
                ];

    var dataObject = [];
    var tableItem = oTableTeam.getItems();
    for(var i=0;i<tableItem.length;i++){

        var item = tableItem[i].getBindingContext().getObject();

        var user_access = tableItem[i].getCells()[6].getText();
        //var assign_vehicle = tableItem[i].getCells()[6].getText();

        var assign_vehicle = item.assign_vehicle;
        var assignVehicle = "";
        if (assign_vehicle != null) {
            if(assign_vehicle=="1"){
                assignVehicle = "All";
            }else{
                assignVehicle = assign_vehicle.replace(/\^/g, ", ");
            }  
        }

        dataObject.push({"1":item.role,
                        "2":item.name,
                        "3":item.emailid,
                        "4":item.notification_email,
                        "5":item.user_block,
                        "6":user_access,
                        "7":assignVehicle
                        
            });
    }

    var createXLSLFormatObj = [];

    createXLSLFormatObj.push(xlsHeader);
    $.each(dataObject, function(index, value) {
        var innerRowData = [];
        $.each(value, function(ind, val) {
            innerRowData.push(val);
        });
        createXLSLFormatObj.push(innerRowData);
    });

    var filename = "TeamExport.xlsx";
    var sheet_name = "Data";

    var wb = XLSX.utils.book_new();
    var ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, sheet_name);
    XLSX.writeFile(wb, filename);
}

function displayMenuTeamMember(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://employee-pane",text: oBundle.getText("Overview"),key: "0"}),
            new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Edit"),key: "1"}),
            new sap.m.MenuItem({icon: "sap-icon://inventory",text: oBundle.getText("Assign_Vehicle"),key: "2"}),
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View_Password"),key: "3"}),
            new sap.m.MenuItem({icon: "sap-icon://employee",text: oBundle.getText("Block_Team_Member"),key: "4"}),
            // new sap.m.MenuItem({icon: "sap-icon://employee",text: oBundle.getText("Block_Team_Member"),key: "4"}),
            new sap.m.MenuItem({icon: "sap-icon://share-2",text: oBundle.getText("Share"),key: "6"}), 
            new sap.m.MenuItem({icon: "sap-icon://sys-cancel",text: oBundle.getText("Mark_Inactive"),key: "7"}), 
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { employeeOverView(obj);
            } else if (oItem == "1") {AddUpdateDialog(2, obj);
            } else if (oItem == "2") {assignVehicle(obj);
            } else if (oItem == "3") {viewPassword(obj['password']);
            } else if (oItem == "4") {blockTeamMember(obj);
            }else if (oItem == "7") {inactiveTeamMember(obj);
            } else if (oItem == "5") {deleteTeamMember(obj['id']);
            }else if (oItem == "6") {
                
                var name = obj['name'];
                var userID = obj['emailid'];
                var password = obj['password'];

                var androidLink = "https://play.google.com/store/apps/details?id=com.jrs.oxmaint";
                var iosLink = "https://apps.apple.com/us/app/maintenance-workorder-oxmaint/id1568268027";
                var portalLink = "https://oxmaint.com/portal/employee.html";

                var subject = oBundle.getText("Credentials_of_Heavy_Vehicle_Inspection");
                var message = oBundle.getText("Dear")+" "+name+", <br><br>"+
                              oBundle.getText("Below_is_your_Credentials")+"- <br>"+
                              oBundle.getText("User_ID")+" : "+userID+" <br>"+
                              oBundle.getText("Password")+" : "+password+" <br><br><br>"+
                              oBundle.getText("Android_App_Link")+" : "+androidLink+" <br>"+
                              oBundle.getText("iOS_App_Link")+" : "+iosLink+" <br>"+
                              oBundle.getText("Web_Portal_Link")+" : "+portalLink;
                var dialogTitle = oBundle.getText("Share_Credentials_with_Team_Member");
                var layoutHeader = oBundle.getText("User")+" : "+name;
                shareDialog(subject, message,dialogTitle,layoutHeader);
            }
        }
    });
    if(hvi_default_type == '2'){
        oMenu.getItems()[2].setVisible(false)
    }
    getDeleteMenu(oMenu,"5");
    oMenu.openBy(event.getSource());
}

// var oTableTeamDoc = new sap.m.Table({growing: true,mode: "SingleSelectMaster",noDataText: oBundle.getText("No_Data"),
//     growingTriggerText: oBundle.getText("More"),growingThreshold: 25,mode:"None",growingScrollToLoad: false,
//     sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
//     columns: [
//         // new sap.m.Column({ width: "100px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }) }),
//         // new sap.m.Column({ width: "80px",hAlign: "Center",header: new sap.m.Label({ text: "", design: sap.m.LabelDesign.Bold}) }),
//         new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Type"), design: sap.m.LabelDesign.Bold }) }),
//         new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Description"), design: sap.m.LabelDesign.Bold }) }),
//         new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Created_Date"), design: sap.m.LabelDesign.Bold }),
//         minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true
//     }),
//     new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Added_By"), design: sap.m.LabelDesign.Bold }),
//         minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true, hAlign: "Center"
//     }),
//     new sap.m.Column({width:'100px', header: new sap.m.Label({ text: oBundle.getText("Attachment"), design: sap.m.LabelDesign.Bold }) }),
// ]});

// var teamDocTemplate = new sap.m.ColumnListItem({
//     cells: [
//         new sap.m.Label({ text: "{attachment_type}"}),
//         new sap.m.Label({ text: "{attachment_name}"}),
//         new sap.m.Label({ text: "{attached_date}"}),
//         new sap.m.Label({ text: "{attached_by}"}),
//         new sap.m.Button({
//             icon: "sap-icon://pdf-attachment",
//             type: sap.m.ButtonType.Transparent,
//             text: { path: "attachment_url",
//                 formatter: function (attachment_url) {
//                     if (attachment_url != null && attachment_url =="") {
//                         this.setVisible(false);
//                     } else {
//                         this.setVisible(true);
//                     }
//             }},
//             press: function (e) {
//                 var model = this.getModel();
//                 var path = e.getSource().getBindingContext().getPath();
//                 var obj = model.getProperty(path);
//                 var blob_path = obj['attachment_url'];

//                 window.open(blob_path, "_blank");
//             }
//         })
        
//     ],
// });
function employeeOverView(obj){

    



    var SegmentedGroup1 = new sap.m.SegmentedButton({ width: "100%",
        items: [new sap.m.SegmentedButtonItem({ key: "1", text: oBundle.getText("Today") }),
                new sap.m.SegmentedButtonItem({width:"90px", key: "2", text: oBundle.getText("This_Week") }),
                new sap.m.SegmentedButtonItem({width:"90px", key: "3", text: oBundle.getText("This_Month") }),
                new sap.m.SegmentedButtonItem({ key: "4", text: oBundle.getText("This_Year") })
            ],
        selectedKey: "1",
        selectionChange: function (oEvent) {

            var btnId = oEvent.getParameter('item').getKey();
            var current_date = getCurrentDate();
            var oDateSplit = current_date.split("-");
            var current = new Date(current_date);

            if (btnId == "1") {
                teamOverViewData(oTableTimeLog, oTemplateTimeLog, oTableLaborView, oTemplateLaborView, obj, current, current);
            } else if (btnId == "2") {

                var weekstart = current.getDate() - current.getDay() + 1;
                var weekend = weekstart + 6;       // end day is the first day + 6 
                var monday = new Date(current.setDate(weekstart));
                var sunday = new Date(current.setDate(weekend));

                teamOverViewData(oTableTimeLog, oTemplateTimeLog, oTableLaborView, oTemplateLaborView, obj, monday, sunday);
            } else if (btnId == "3") {

                var firstDay = new Date(current.getFullYear(), current.getMonth(), 1);
                var lastDay = new Date(current.getFullYear(), current.getMonth() + 1, 0);
                teamOverViewData(oTableTimeLog, oTemplateTimeLog, oTableLaborView, oTemplateLaborView, obj, firstDay, lastDay);

            } else if (btnId == "4") {

                var yearFirstDate = new Date("01-Jan-" + oDateSplit[2]);
                var yearLastDate = new Date("31-Dec-" + oDateSplit[2]);
                teamOverViewData(oTableTimeLog, oTemplateTimeLog, oTableLaborView, oTemplateLaborView, obj, yearFirstDate, yearLastDate);
            }
        }
    });


    var oTableTimeLog = oTableWOTimeLog.clone();
    oTableTimeLog.destroyInfoToolbar();
    oTableTimeLog.setMode("None");

    var oTemplateTimeLog = oTableWOTimeLogTemplate.clone();
    oTemplateTimeLog.setType("Inactive");

    oTableTimeLog.insertColumn(new sap.m.Column({header: TableHeader.clone().setText(oBundle.getText("Workorder_Number"))}),0);
    oTableTimeLog.insertColumn(new sap.m.Column({header: TableHeader.clone().setText(oBundle.getText("Vehicle_Number"))}),1);

    oTemplateTimeLog.insertCell(new sap.m.Label({wrapping:true,text: "{wo_number}"}),0);
    oTemplateTimeLog.insertCell(new sap.m.Label({wrapping:true,text: "{vehicle_number}"}),1);

    var oTableLaborView = oTableLaborItemWO.clone();
    oTableLaborView.destroyInfoToolbar();
    oTableLaborView.setMode("None");
 

    var oTemplateLaborView = oTableLaborItemWOTemplate.clone();
    oTemplateLaborView.setType("Inactive");


    oTableLaborView.removeColumn(0);
    oTemplateLaborView.removeCell(0);

    oTableLaborView.removeColumn(4);
    oTemplateLaborView.removeCell(4);

    oTableLaborView.insertColumn(new sap.m.Column({header: TableHeader.clone().setText(oBundle.getText("Workorder_Number"))}),0);
    oTableLaborView.insertColumn(new sap.m.Column({header: TableHeader.clone().setText(oBundle.getText("Vehicle_Number"))}),1);
    oTableLaborView.insertColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_Date"))}),6);
    oTableLaborView.insertColumn(new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Added_By"))}),7);


    oTemplateLaborView.insertCell(new sap.m.Label({wrapping:true,text: "{wo_number}"}),0);
    oTemplateLaborView.insertCell(new sap.m.Label({wrapping:true,text: "{vehicle_number}"}),1);
    oTemplateLaborView.insertCell(new sap.m.Label({wrapping:true,text: "{added_date}"}),6);
    oTemplateLaborView.insertCell(new sap.m.Label({wrapping:true,text: "{added_by}"}),7);



    var ot1 = TableHeader.clone().setText(oBundle.getText("Not_yet_customize"));
    var ot2 = TableHeader.clone().setText(oBundle.getText("Not_yet_customize"));

    var oLayoutTeamOverView = new sap.uxap.ObjectPageLayout({ headerContentPinnable: false, preserveHeaderStateOnScroll: true,
        useIconTabBar: true,toggleHeaderOnTitleClick: true,
        headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
            heading: [new sap.m.Title({ text: obj['name'] +"("+obj['emailid']+")", level: "H1", titleStyle: "H2" })],
            actions: [SegmentedGroup1]
        }),
        sections: [
            new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Time_Card"),
                subSections: new sap.uxap.ObjectPageSubSection({
                    blocks: [oTableTimeLog]
            })}),
            new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Pay_Details"),
                subSections: new sap.uxap.ObjectPageSubSection({
                    blocks: [oTableLaborView]
            })}),
            // new sap.uxap.ObjectPageSection({ showTitle: true, title: oBundle.getText("Documents"),
            //     subSections: new sap.uxap.ObjectPageSubSection({
            //         blocks: [oTableTeamDoc]
            // })}),
        ]
    });


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

    var current_date = getCurrentDate();
    var current = new Date(current_date); 
            
    teamOverViewData(oTableTimeLog,oTemplateTimeLog,oTableLaborView,oTemplateLaborView, obj,current,current);
    // funGetTeamDoc(obj['emailid']);
}

function teamOverViewData(oTableTimeLog,oTemplateTimeLog,oTableLaborView,oTemplateLaborView,obj,start_date,end_date){
    
    oTableTimeLog.setBusy(true);
    HVI_WO_TimeLog.where({ master_email: emailUser, user_id: obj['emailid'] }).take(100).orderByDescending("__createdAt").read().done(function (results) {

        var getFilterJson = results.filter(function (item, index) {

            var oDate = new Date(item.added_date.split(" ")[0]);
            if (start_date <= oDate && oDate <= end_date) {

                var getWorkorder = workorderJSONArray.filter(function (obj, index) { return (obj.id === item.wo_id); });
                if (getWorkorder.length > 0) {
                    item.wo_number = getWorkorder[0]['wo_number'];
                    item.vehicle_number = getWorkorder[0]['vehicle_number'];
                }
                return true;
            } else {
                return false;
            }
        });
      
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: getFilterJson });

        oTableTimeLog.setModel(oModel);
        oTableTimeLog.bindItems({ path: "/modelData",
            template: oTemplateTimeLog
        });
        oTableTimeLog.setBusy(false);
    });


oTableLaborView.setBusy(true);
HVI_WO_Labor.where({ master_email: emailUser, user_id: obj['emailid'] }).read().done(function (results) {
        
     var getFilterJson = results.filter(function (item, index) {

            var oDate = new Date(item.added_date.split(" ")[0]);
            if (start_date <= oDate && oDate <= end_date) {

                var getWorkorder = workorderJSONArray.filter(function (obj, index) { return (obj.id === item.wo_id); });
                if (getWorkorder.length > 0) {
                    item.wo_number = getWorkorder[0]['wo_number'];
                    item.vehicle_number = getWorkorder[0]['vehicle_number'];
                }
                return true;
            } else {
                return false;
            }
        });

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: getFilterJson });
        oTableLaborView.setModel(oModel);
        oTableLaborView.bindItems({ path: "/modelData",template: oTemplateLaborView});

        oTableLaborView.setBusy(false);
    });
}

function assignVehicle(obj) {

    aDataAssignVehicle = [];
    var assign_vehicle = obj['assign_vehicle'];
    if (assign_vehicle == null) { assign_vehicle = ""; }
    var assign_vehicle = assign_vehicle.split("^");

    if (assign_vehicle != "") {
        for (var i = 0; i < assign_vehicle.length; i++) {
            if (assign_vehicle[i] == "1") {
                for(var j=0;j< vehicleArray.length; j++){
                    if (vehicleArray.indexOf(vehicleArray[j]) > -1) {
                        aDataAssignVehicle.push({ Vehicle_Number: vehicleArray[j] });
                    }
                }
            } else {
                aDataAssignVehicle.push({ Vehicle_Number: assign_vehicle[i] });
            }
        }
        }

	oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
	oTableAssignVehicle.setModel(oModelAssignVehicle);
	oTableAssignVehicle.bindRows("/modelData");

	var oDialog = new sap.m.Dialog({
	    title: oBundle.getText("Assign_Vehicle"),
	    state: sap.ui.core.ValueState.Success,
	    content: [oTableAssignVehicle],
	    buttons: [
            new sap.m.Button({text: oBundle.getText("Assign"),icon: "sap-icon://accept",
                press: function () {
                    var assignVehicle = "";
                    var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
                    var assignVehicleCount = oTableAssignVehicle.getBinding("rows").getLength();

                    if (assignVehicleCount == vehicleJSONArray.length) {
                        assignVehicle = "1";
                    } else {
                        for (var i = 0; i < assignVehicleCount; i++) {
                            assignVehicle = assignVehicle + objAssignVehicle[i]['Vehicle_Number'] + "^";
                        }
                        assignVehicle = assignVehicle.slice(0, -1);
                    }
                    busyDialog.open();
                    HVI_AccessControl.update({ id: obj['id'], assign_vehicle: assignVehicle
                    }).done(function () {
                        funGetTeam();
                        oDialog.close();
                        busyDialog.close();
                    }, failureUser);
                }
            }),
            new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}})
        ]
	}).open();

}

function blockTeamMember(obj) {

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Block_Team_Member"),
        state: sap.ui.core.ValueState.Error,
        content: [userBlockDB],
        buttons: [
            new sap.m.Button({text: oBundle.getText("Done"),icon: "sap-icon://accept",
                press: function () {
                        busyDialog.open();
                        HVI_AccessControl.update({ id: obj['id'],user_block: userBlockDB.getValue()      
                    }).done(function () {
                        funGetTeam();
                        oDialog.close();
                        busyDialog.close();
                    }, failureUser);
                }
            }),
            new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}
            })
		]
    }).open();
}
function inactiveTeamMember(obj) {

    var userInactiveDB = new sap.m.ComboBox({ width:"100%"});
    userInactiveDB.addItem(new sap.ui.core.ListItem({key:"0",text:oBundle.getText("No")}));
    userInactiveDB.addItem(new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Yes")}));
    userInactiveDB.addEventDelegate({onAfterRendering: function(e) {
        userInactiveDB.$().find("input").attr("readonly", true);
     }});

     userInactiveDB.setSelectedKey(obj['active']);

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Inactive Team Member"),
        state: sap.ui.core.ValueState.Error,
        content: [userInactiveDB],
        buttons: [
            new sap.m.Button({text: oBundle.getText("Done"),icon: "sap-icon://accept",
                press: function () {
                        busyDialog.open();
                        HVI_AccessControl.update({ id: obj['id'],active: userInactiveDB.getSelectedKey()  
                    }).done(function () {
                        funGetTeam();
                        oDialog.close();
                        busyDialog.close();
                    }, failureUser);
                }
            }),
        new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}})
	]}).open();
}
function viewPassword(password) {

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Password"),
        state: sap.ui.core.ValueState.Success,
        content: [new sap.m.Label({ text: oBundle.getText("Password") +" - "+password })],
        buttons: [
			new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",press: function () {oDialog.close();}})
		]
    }).open();

}

function viewAssignedVehicle(assigned){
    
    var oTableAssignedView = new sap.ui.table.Table({editable : false, width : "100%",visibleRowCount :5});
        
        oTableAssignedView.setSelectionMode(sap.ui.table.SelectionMode.Single);
        oTableAssignedView.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);

        oTableAssignedView.addColumn(new sap.ui.table.Column({
            label: new sap.ui.commons.Label({text:oBundle.getText("Assigned_Vehicle")}),
            template: new sap.ui.commons.TextView().bindProperty("text", "assign"),
            width:"100%"
        }));
         
        var assignedArray = [];
        if (assigned != null && assigned != "") {
            assignedArray = assigned.split("^");
        } 

        var aDataAssigned =[];
         
        if (assignedArray.length > 0) {

            for (var i = 0; i < assignedArray.length; i++) {
                if (assignedArray[i] == "1") {
                    for(var j=0;j< vehicleArray.length; j++){
                    aDataAssigned.push({ assign: vehicleArray[j]});
                }
                } else {
                    aDataAssigned.push({ assign: assignedArray[i] });
                }
            }

            var oModelAssign = new sap.ui.model.json.JSONModel();
            oModelAssign.setData({ modelData: aDataAssigned });
            oTableAssignedView.setModel(oModelAssign);
            oTableAssignedView.bindRows("/modelData");

            var oDialog = new sap.m.Dialog({draggable: true,
                icon: "sap-icon://inventory",title: oBundle.getText("Assigned_Vehicle"),
                state: sap.ui.core.ValueState.Success,
                content: [oTableAssignedView],
                buttons: [
                    new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
                    press: function () {oDialog.close();}})
                ]
            }).open();
        } else { 
        sap.m.MessageBox.error(oBundle.getText("No_Vehicle_Assigned"),{title: oBundle.getText("Alert")});
        }
}


var oTableTeamSelect = new sap.m.Table({growing: false,mode: "SingleSelectMaster",noDataText: oBundle.getText("No_Data"),
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    growingThreshold: 12,mode:"None",growingScrollToLoad: false,
    columns: [
                new sap.m.Column({ width: "80px",hAlign: "Center",header: new sap.m.Label({ text: "", design: sap.m.LabelDesign.Bold}) }),
                new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Name"), design: sap.m.LabelDesign.Bold }) }),
                new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("User_ID"), design: sap.m.LabelDesign.Bold }) }),
                new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("notification_email"), design: sap.m.LabelDesign.Bold }),
                    minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true
                }),
               new sap.m.Column({ width: "100px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }) }),
          ]
});

var oTableTeamSelectTemplate = new sap.m.ColumnListItem({
    cells: [
            new sap.f.Avatar({src: "{image}",displaySize: "S",displayShape: "Circle",imageFitType: "Cover"}),
            new sap.m.Label({ text: "{user_name}" }),
            new sap.m.Label({ text: "{user_id}" }),
            new sap.m.Label({ text: "{email}" }),
            new sap.m.Button({type: "Emphasized",icon: "sap-icon://action",text: oBundle.getText("Select"),
                press: function (event) {
                    var model = this.getModel();
                    var path = event.getSource().getBindingContext().getPath();
                    var obj = model.getProperty(path);
                    var notification_email = obj['email'];
                    if (notification_email != null && notification_email != "") {

                        if(selectTeamArea=="share_email"){
                            toEmailField.setValue(notification_email);
                        }else if(selectTeamArea=="cc_email"){
                                bccEmailField.setValue(notification_email);
                        }
                        oDialogTeamSelect.close();
                    } else {
                        sap.m.MessageBox.error(oBundle.getText("Email_not_available_for_selected_team_member"));
                    }
                }
        })]
});

var VSDoTableTeamSelect = new sap.m.ViewSettingsDialog({
        confirm: function (oEvent) {
            var p = oEvent.getParameters(),
                oSorter = null;
            if (p.sortItem) {
                oSorter = p.sortItem.getCustomData()[0].getValue();
                if (oSorter) {
                    oSorter.bDescending = p.sortDescending;
                    oTableTeamSelect.getBinding("items").sort(oSorter);
                }
            }
        }
});

VSDoTableTeamSelect.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("Name" ),
    selected: true,
    customData: new sap.ui.core.CustomData({
        value: new sap.ui.model.Sorter("user_name", false)
    })
}));
VSDoTableTeamSelect.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("User_ID" ),
    customData: new sap.ui.core.CustomData({
        value: new sap.ui.model.Sorter("user_id", false)
    })
}));
VSDoTableTeamSelect.addSortItem(new sap.m.ViewSettingsItem({
    text: oBundle.getText("notification_email"),
    customData: new sap.ui.core.CustomData({
        value: new sap.ui.model.Sorter("email", false)
    })
}));
    
oTableTeamSelect.setInfoToolbar(new sap.m.Toolbar({
    content: [
        new sap.m.Label({text: oBundle.getText("USER_MANAGEMENT_LIST")}),
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = oTableTeamSelect.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                    new sap.ui.model.Filter("user_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("user_id", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("email", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
        }),
        new sap.m.Button({text:oBundle.getText("sorting"),icon: "sap-icon://sort",
            press: function () {VSDoTableTeamSelect.open();}
        })
    ]
    }));
    
var oTextFieldUserAccess1 = new sap.m.Input({ id: "userAccess_et1", value: "", width: "100%" });
var oTextFieldUserAccess2 = new sap.m.Input({
    required:true,
    id: "userAccess_et2",
    value: "", 
    width: "100%",
    liveChange : function(event) {
        if (oTextFieldUserAccess2.getValue().length < 6) {
            this.setValueStateText(oBundle.getText("User_ID_characters"));
            this.setValueState(sap.ui.core.ValueState.Error);  // if the field is empty after change, it will go red
        }else {
            this.setValueState(sap.ui.core.ValueState.None); }
    }});
var oTextFieldUserAccess3 = new sap.m.Input({ type:"Password",id: "userAccess_et23", value: "", width: "100%",
    liveChange : function(event) {
        if (oTextFieldUserAccess3.getValue().length < 6) {
            this.setValueStateText(oBundle.getText("Password_characters"));
            this.setValueState(sap.ui.core.ValueState.Error);  // if the field is empty after change, it will go red
        }else {
            this.setValueState(sap.ui.core.ValueState.None); }
    } });
var oTextFieldUserAccess4 = new sap.m.Input({ value: "", width: "100%" });
var oTextFieldUserAccessMobile = new sap.m.Input({ type:"Number", width: "100%" });

var teamRoleDB = new sap.m.ComboBox({
    width:"100%",
    items:[new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Operator")}),
        new sap.ui.core.ListItem({key:"2",text:oBundle.getText("Technician")}),
        new sap.ui.core.ListItem({key:"3",text:oBundle.getText("Employee")}),
        new sap.ui.core.ListItem({key:"4",text:oBundle.getText("Sub_Admin")})
]});
teamRoleDB.setSelectedKey("1");

var userBlockDB = new sap.m.ComboBox();
    userBlockDB.setWidth("100%");
    userBlockDB.addItem(new sap.ui.core.ListItem({text:oBundle.getText("No")}));
    userBlockDB.addItem(new sap.ui.core.ListItem({text:oBundle.getText("Yes")}));
    userBlockDB.setValue(oBundle.getText("No"));
    userBlockDB.addEventDelegate({
        onAfterRendering: function(e) {
            userBlockDB.$().find("input").attr("readonly", true);
        }
    });

    var data = [];
    if(hvi_default_type == "2"){
        data  = {
            shift: [
                   
                    {key: "5",Description: oBundle.getText("Workorder")},
                    {key: "14",Description: oBundle.getText("Request")}, 
                    {key: "10",Description: oBundle.getText("Users_Management")},
                    {key: "18",Description: oBundle.getText("Site_Project")},
                    {key: "9",Description: oBundle.getText("Report")},  
                ]
            };
    }else{
        data  = {
            shift: [
                    {key: "000",Description: oBundle.getText("Remove_All")},  
                    {key: "00",Description: oBundle.getText("Select_All")},  
                    {key: "1",Description: oBundle.getText("Inspection")},
                    // {key: "2",Description: oBundle.getText("Daily_Reporting")},
                    {key: "7",Description: oBundle.getText("Incident_Report")},
                    {key: "4",Description: oBundle.getText("Forms")},
                    {key: "12",Description: oBundle.getText("Reminder")},
    
                    {key: "5",Description: oBundle.getText("Workorder")},
                    {key: "14",Description: oBundle.getText("Request")}, 
                    {key: "6",Description: oBundle.getText("Service_Schedule")},
                    {key: "13",Description: oBundle.getText("Parts_Inventory")},
                    {key: "15",Description: oBundle.getText("Labor_Code")},
                    // {key: "26",Description: oBundle.getText("Task_Master")},
    
                    {key: "19",Description: oBundle.getText("Purchase_Order")},
                    {key: "20",Description: oBundle.getText("PO_Approval")},
                    {key: "21",Description: oBundle.getText("Demand_Parts")},
                    {key: "22",Description: oBundle.getText("Vendors")},
    
                   // {key: "16",Description: oBundle.getText("Fault_List")},
    
                    // {key: "8",Description: oBundle.getText("Fuel_Management")},
                    // {key: "25",Description: oBundle.getText("Fuel_Bunker")},
                    // {key: "23",Description: oBundle.getText("Tyre_Inventory")},
                    // {key: "17",Description: oBundle.getText("Tool_Management")},
                    {key: "3",Description: oBundle.getText("Vehicles")},
                    
                    // {key: "24",Description: oBundle.getText("Logbook")},
    
                    {key: "10",Description: oBundle.getText("Users_Management")},
                    {key: "18",Description: oBundle.getText("Site_Project")},
    
                    {key: "9",Description: oBundle.getText("Report")},
                    {key: "11",Description: oBundle.getText("Account")},  
                    {key: "27",Description: oBundle.getText("Documents")},  
                ]
            };
    }
    

    var oModelData = new sap.ui.model.json.JSONModel();
    oModelData.setData(data);

    var userSccessDB = new sap.m.MultiComboBox({  
        width:"100%",
        items : {  
            path : "/shift",  
            template : new sap.ui.core.ListItem({ 
                key  : "{key}",   
                text : "{Description}"  
            })
        },
        selectionChange: function(event) {
    
    
        
            var selectedItems = event.getSource().getSelectedItems();
            var selectAllItem = selectedItems.find(function(item) {
                return item.getKey() === "00";
            });
            var removeAllItem = selectedItems.find(function(item) {
                return item.getKey() === "000";
            });
            // console.log(selectAllItem)
            if (selectAllItem) {
                event.getSource().setSelectedItems(
                    event.getSource().getItems().filter(function(item) {
                        return item.getKey() !== "00" && item.getKey() !== "000";
                    })
                );
            }
    
            if(removeAllItem){
                // Deselect all items if no "select all" item is selected
                event.getSource().removeAllSelectedItems();
            }
        }
    });
    userSccessDB.setModel(oModelData);

    var locationDB = new sap.m.ComboBox({width:"100%",
        items : {  
        path : "/modelData",  
        template : new sap.ui.core.ListItem({ 
            key  : "{location_id}",   
            text : "{location_name}"  
        })
    }
    });
    locationDB.addEventDelegate({ onAfterRendering: function(e) {
        locationDB.$().find("input").attr("readonly", true);
    }});

    var secondryLocationDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        valueHelpRequest: function () { selectMultiLocation(secondryLocationDB); }
    });

  
    var approver = new sap.m.CheckBox({text: oBundle.getText("Yes")});


function selectMultiLocation(input) {

    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true,
        resizable: true, rememberSelections: true, multiSelect: true,
        title: oBundle.getText("Select_Site/Project"),
        noDataText: oBundle.getText("No_Data"),
        liveChange: function (oEvent) {
            sSearchValue = oEvent.getParameter("value"),
            oBinding = oEvent.getParameter("itemsBinding");
            if (oBinding) {
                var oFilters = [
                    new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, sSearchValue),
                    new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, sSearchValue),                    
                ];
                var filterObj = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObj);
            } else {
                oBinding.filter([]);
            }
        },
        confirm: function (oEvent) {
            var tokenList = input.getTokens();
            var aContexts = oEvent.getParameter("selectedContexts");
            if (aContexts && aContexts.length) {
               aContexts.map(function (oContext) { 
                    var location_name =  oContext.getObject()['location_name'];
                    var location_id =  oContext.getObject()['location_id'];

                    var insertFlag = true;
                    for (var j = 0; j < tokenList.length; j++) {
                        if (tokenList[j].getKey() == location_id) { insertFlag = false; }
                    }
                    if (tokenList.length == 0 || insertFlag) {
                        input.addToken(new sap.m.Token({ key: location_id, text: location_name }));
                    }

                });
            }
           
            // var tokenList = input.getTokens();
            // var selectedItems = oEvent.getParameter("selectedItems");
            // if (selectedItems) {
            //     for (var i = 0; i < selectedItems.length; i++) {
            //         var insertFlag = true;
            //         for (var j = 0; j < tokenList.length; j++) {
            //             if (tokenList[j].getKey() == selectedItems[i].getTitle()) {insertFlag = false;}
            //         }
            //         if (tokenList.length == 0 || insertFlag) {
            //             input.addToken(new sap.m.Token({ key: selectedItems[i].getTitle(), text: selectedItems[i].getDescription() }));
            //         }
            //     }
            // }
        }
    });

	var oItemTemplate = new sap.m.StandardListItem({title: "{location_id}",
		description: "{location_name}",type: "Active"
	})

    var tokenList = input.getTokens();
    var result = emailJSONLocation.filter(function (obj, index) {
        for (var j = 0; j < tokenList.length; j++) {
            if (tokenList[j].getKey() == obj.location_id) { return false; }
        }
        return true;
    });


    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: result });
    oSelectDialog.setModel(oModel); 
    oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
    oSelectDialog.open();    
    
    oSelectDialog._getOkButton().setText(oBundle.getText("Select"));
    oSelectDialog._getCancelButton().setText(oBundle.getText("Cancel"));
}

var aDataAssignVehicle =[];
var oModelAssignVehicle = new sap.ui.model.json.JSONModel();

function assignRemove(){
    
    var allVehicledata = oTableAssignVehicle.getModel().getData();
    var vehicleArray = allVehicledata['modelData']
    var indexes = oTableAssignVehicle.getSelectedIndices();
    
    var sIndex = [];
    for(i=0;i<indexes.length;i++){
         var test = oTableAssignVehicle.getContextByIndex(indexes[i]).getObject();
         var vehicleNumberSelected = test['Vehicle_Number'];
         vehicleArray.findIndex(function (entry, j) {
         if (entry.Vehicle_Number == vehicleNumberSelected) {
             sIndex = sIndex.concat(j);
             return true;
         }
         });
    }
    
    //  console.log(sIndex)
    //  console.log(indexes)

   if(sIndex.length>0){

        sap.m.MessageBox.show(oBundle.getText("Do_you_want_to_remove_item"),
		sap.m.MessageBox.Icon.ERROR,
		oBundle.getText("Alert"),
		[sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
		function (bConfirmed) {
            if (bConfirmed == "YES") {
                busyDialog.open(); 
                 for (var i = sIndex.length -1; i >= 0; i--){		          
		            aDataAssignVehicle.splice(sIndex[i],1);
                    oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
		            oTableAssignVehicle.setModel(oModelAssignVehicle);
		            oTableAssignVehicle.bindRows("/modelData");
                    if (i === 0) {
                        busyDialog.close(); 
                    }
		        }
		    }
		});
     }else{
         sap.m.MessageBox.error(oBundle.getText("Select_at_least_one_row"));
     }
}

var avatarTeam = new sap.f.Avatar({displaySize: "L",displayShape: "Circle",imageFitType: "Cover"});

var btnAssignVehicle = new sap.m.Button({ icon: "sap-icon://action", text: oBundle.getText("Click_here_to_select_vehicle"), //width: "100%",
    layoutData: new sap.ui.layout.GridData({ span: "L2 M4 S6" }),
    type: sap.m.ButtonType.Emphasized,
    press: function () {
        if(!vehicleTemp){
            selectVehiclArea = "assign_vehicle";
            pickVehicle();
        }else{
            sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
            get4WVehicle();
            vehicleTemp = false;
            return;
        }
            
       
    } 
});
 
var oTableAssignVehicle = new sap.ui.table.Table({ width : "100%",
    noData : oBundle.getText("Not_Assign"),
    selectionMode: sap.ui.table.SelectionMode.None,
    visibleRowCount :9
});
  
oTableAssignVehicle.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: oBundle.getText("Assigned_Vehicle")}),
    template: new sap.ui.commons.TextView().bindProperty("text", "Vehicle_Number"),
    filterProperty: "Vehicle_Number"
}));


oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
oTableAssignVehicle.setModel(oModelAssignVehicle);
oTableAssignVehicle.bindRows("/modelData");

var newToolbarAssign = new sap.m.Toolbar({
    content: [new sap.m.Button({ text: oBundle.getText("Remove_selected"),
        icon: "sap-icon://delete",
        visible:false,
        press: function () {
            assignRemove();
        }
    }),
    new sap.m.ToolbarSpacer(),btnRemoveAssignVehicle, btnAssignVehicle
]});

oTableAssignVehicle.addExtension(newToolbarAssign);

var avatarblobPath = "";
function uploadTeamAvatarDialog(){

        standartBusyDialog.setText("");

        var tsLong = new Date().getTime();
		var userFolder = emailUser.replace(/[@.]/g,"");
        var filenale = emailUser.replace(/[^.,a-zA-Z0-9]/g,"")+"_"+tsLong;

        var oFileUploaderTeam = new sap.ui.unified.FileUploader({
            name: "file",
            uploadUrl: "https://oxmaint.com/upload/avatar.php",
            sendXHR: true,
            maximumFileSize: 1.0,
            fileType: ['jpeg', 'jpg', 'JPG', 'JPEG', "PNG", 'png'],
            width: "400px",
            placeholder: oBundle.getText("Choose_a_photo_for_uploading"),
            parameters: [
					new sap.ui.unified.FileUploaderParameter({ name: "name", value: filenale }),
                    new sap.ui.unified.FileUploaderParameter({ name: "email", value: userFolder })
				],
            uploadProgress: function (oEvent) {
                var nLoaded, nTotal;
                if (oEvent.getParameter("lengthComputable")) {
                    nLoaded = oEvent.getParameter("loaded");
                    nTotal = oEvent.getParameter("total");

                    console.log("Upload Progress in Bytes: " +
								nLoaded + " of " + nTotal + " loaded (" +
								(nLoaded / nTotal * 100) + "%)"
						);
                    standartBusyDialog.setText(Math.floor((nLoaded / nTotal) * 100) + "%");
                }
            },
            fileSizeExceed: function (oEvent) {
                standartBusyDialog.close();
                sap.m.MessageBox.error(oBundle.getText("avatar_image_size"));
            },
            typeMissmatch: function (oEvent) {
                standartBusyDialog.close();
                sap.m.MessageBox.error(oBundle.getText("This_is_not_valid_file_type"));
            },
            uploadAborted: function (oEvent) {  standartBusyDialog.close();},
            uploadComplete: function (oEvent) {
                var ext = oEvent.getParameter("responseRaw").replace(/"/g, "");
                oDialog.close();
                standartBusyDialog.close();
                avatarblobPath = "https://oxmaint.com/upload/avatar/" + userFolder + "/" + filenale + "." + ext;
                avatarTeam.setSrc(avatarblobPath);
            }
        });

        var oDialog = new sap.m.Dialog({
            title: oBundle.getText("Upload_Photo"),
            content: [oFileUploaderTeam],
            buttons: [
                  new sap.m.Button({
                      text: oBundle.getText("Upload"),
                      icon: "sap-icon://upload",
                      press: function () {
                          if(oFileUploaderTeam.getValue()!=""){
                               standartBusyDialog.open();
                              oFileUploaderTeam.upload();
                          }else{
                              sap.m.MessageBox.error(oBundle.getText("Select_image_for_upload"));
                          }
                      }
                  }),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
        }).open();
}





let oTeamField1 = new  sap.m.ComboBox({
    // layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
    value:oBundle.getText("Active"),
    items:[    
        new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Active")}),
        new sap.ui.core.ListItem({key:"2",text:oBundle.getText("Inactive")}),
    ]
}).addEventDelegate({onAfterRendering: function(e) {oTeamField1.$().find("input").attr("readonly", true);}});


let oTeamField2 = new  sap.m.ComboBox({
    // layoutData: new sap.ui.layout.GridData({span: "L3 M6 S12"}),
    value:oBundle.getText("G1"),
    items:[    
        new sap.ui.core.ListItem({key:"1",text:oBundle.getText("G1")}),
        new sap.ui.core.ListItem({key:"2",text:oBundle.getText("G2")}),
        new sap.ui.core.ListItem({key:"3",text:oBundle.getText("G3")}),
        new sap.ui.core.ListItem({key:"4",text:oBundle.getText("G4")}),
        new sap.ui.core.ListItem({key:"5",text:oBundle.getText("G5")}),
        new sap.ui.core.ListItem({key:"6",text:oBundle.getText("G6")}),
        new sap.ui.core.ListItem({key:"7",text:oBundle.getText("G7")}),
    ]
}).addEventDelegate({onAfterRendering: function(e) {oTeamField2.$().find("input").attr("readonly", true);}});


function AddUpdateDialog(type,obj){

    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: emailJSONLocation });
    locationDB.setModel(oModel);

    var userAccessForm1 = 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("Workshop Group") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Workshop Number") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Workshop") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("User_ID") }),
                        fields: [oTextFieldUserAccess2]
                    }),
                    
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Password") }),
                        fields: [oTextFieldUserAccess3]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Role") }),
                        fields: [teamRoleDB]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({  required: true, text: oBundle.getText("notification_email") }),
                        fields: [oTextFieldUserAccess4]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Branch") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Status") }),
                        fields: [oTeamField1]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Position") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Approval Amount") }),
                        fields: [new sap.m.Input({})]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ required: true, text: oBundle.getText("Approval Level ID") }),
                        fields: [oTeamField2]
                    }),
                    // new sap.ui.layout.form.FormElement({
                    //     label: new sap.m.Label({ required: true, text: oBundle.getText("Name") }),
                    //     fields: [oTextFieldUserAccess1]
                    // }),
                    
                    //     new sap.ui.layout.form.FormElement({
                    //         label: new sap.m.Label({ required: true, text: oBundle.getText("User_Access_Area") }),
                    //         fields: [userSccessDB]
                    //     }),
                    //     new sap.ui.layout.form.FormElement({
                    //         label: new sap.m.Label({ required: true, text: oBundle.getText("Primary_Site/Project") }),
                    //         fields: [locationDB]
                    //     }),
                    //     new sap.ui.layout.form.FormElement({
                    //         label: new sap.m.Label({ text: oBundle.getText("Secondry_Site/Project") }),
                    //         fields: [secondryLocationDB]
                    //     }),
                        // new sap.ui.layout.form.FormElement({
                        //     label: new sap.m.Label({ text: oBundle.getText("Mobile") }),
                        //     fields: [oTextFieldUserAccessMobile]
                        // }),
                            
                        // new sap.ui.layout.form.FormElement({
                        //     label: new sap.m.Label({ text: oBundle.getText("Make_Approver") }),
                        //     fields: [approver]
                        // }),
                        new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: ""}),
                        fields: [new sap.m.Button({
                            text: oBundle.getText("Upload_Photo"),
                            type:sap.m.ButtonType.Emphasized,
                            icon: "sap-icon://add-photo",
                            width:"80%",
                            press: function () {
                                uploadTeamAvatarDialog();
                            }
                        }), avatarTeam,
                    ]
                })
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        // fields: [oTableAssignVehicle]
                    }),
                ]
            })
        ]});
        if(hvi_default_type == '2'){
            userAccessForm1.getFormContainers()[1].setVisible(false);
        }
    if (type === 2) {
        displayFormDataUserAccess(obj);
    } else {
        dataClearUserAccess();
    }

    var addBtn = new sap.m.Button({ text: oBundle.getText("Add_Team_Member"), icon: "sap-icon://add",
        press: function(){
            insertUserAccess(oDialog);
        }});

    var updateBtn = new sap.m.Button({text: oBundle.getText("Update"),icon: "sap-icon://edit",
        press: function () {
            updateUserAccess(oDialog,obj);
        }
    });

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

     if (type == 2) {
        addBtn.setVisible(false);
        updateBtn.setVisible(true);
        oDialog.setTitle(oBundle.getText("Update_Team_Member"));
    }else{
        addBtn.setVisible(true);
        updateBtn.setVisible(false);
        oDialog.setTitle(oBundle.getText("Add_Team_Member"));
    }
}

var oAppUserAccess  = new sap.m.App({height:"100%",initialPage:"team_page"});

 var teamPage = new sap.m.Page("team_page",{ title:oBundle.getText("USER_MANAGEMENT_LIST"),showHeader:true,enableScrolling:true,
        content : [oTableTeam]  
    });

 oAppUserAccess.addPage(teamPage);

var emailJSON = "";

function insertUserAccess(oDialog) {

    var name1 = sap.ui.getCore().getElementById('userAccess_et1').getValue();
    var email1 = sap.ui.getCore().getElementById('userAccess_et2').getValue();
    var password1 = sap.ui.getCore().getElementById('userAccess_et3').getValue();
    var notification_email = oTextFieldUserAccess4.getValue();
    var mobile = oTextFieldUserAccessMobile.getValue();
    var role  = teamRoleDB.getSelectedKey();

   var assignVehicle = "";
   var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
   var assignVehicleCount = oTableAssignVehicle.getBinding("rows").getLength();

   if (assignVehicleCount == vehicleJSONArray.length) {
       assignVehicle = "1";
   } else {
       for (var i = 0; i < assignVehicleCount; i++) {
           if (vehicleArray.indexOf(objAssignVehicle[i]['Vehicle_Number']) > -1) {
               assignVehicle = assignVehicle + objAssignVehicle[i]['Vehicle_Number'] + "^";
           }
       }
       assignVehicle = assignVehicle.slice(0, -1);
   }

    var userArea = "";
    for(var i=0;i<userSccessDB.getSelectedItems().length;i++){
        if(i==0){
            userArea = userArea + userSccessDB.getSelectedItems()[i].getKey();
        }else{
            userArea = userArea +","+ userSccessDB.getSelectedItems()[i].getKey();
        }
    }

    if (validation(name1, oBundle.getText("Name"))) {  return; }
    if (validation(email1, oBundle.getText("User_ID"))) { return; }

    if(hasWhiteSpace(email1)){
         sap.m.MessageBox.error(oBundle.getText("User_ID")+" "+oBundle.getText("contain_space"));
         return;
    }

    if (validation(password1, oBundle.getText("Password"))) { return; }
    if (validation(userArea+"", oBundle.getText("User_Access_Area"))) { return; }
   
    if(notification_email!=""){
        if (regEmail.test(notification_email) == false) {
            sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
            return ;
        }
      }

    if (email1.length < 6) {
        sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
        return;
    }
     if (password1.length < 6) { 
        sap.m.MessageBox.error(oBundle.getText("Select_Primary_site"));
        return;
    }

    for (var i = 0; i < emailJSON.length; i++) {
        var email = emailJSON[i];
        if (email.emailid == sap.ui.getCore().getElementById('userAccess_et2').getValue()) {
            sap.m.MessageBox.error(oBundle.getText("User_already_exist"));
             return;
        }
    }

    var approverFlag = approver.getSelected();
    var location_id = locationDB.getSelectedKey();
    if (!nullCheckAll(location_id)) { 
        sap.m.MessageBox.error(oBundle.getText("Select_Primary_site"));
        return;
    }
    var secondry_site_id = "";
    var secondry_site_name = "";
    var oTokenList = secondryLocationDB.getTokens();
    for (var j = 0; j < oTokenList.length; j++) {
        if (secondry_site_id == "") {
            secondry_site_id = oTokenList[j].getKey();
            secondry_site_name = oTokenList[j].getText();
        } else {
            secondry_site_id = secondry_site_id + "^" + oTokenList[j].getKey();
            secondry_site_name = secondry_site_name + "^" + oTokenList[j].getText();
        }
    }


    
 
    busyDialog.open();
    HVI_AccessControl.insert({ master_email: emailUser, name: name1, emailid: email1, password: password1, notification_email: notification_email,
        user_block: "No", user_access: userArea, assign_vehicle: assignVehicle,role:role,image:avatarblobPath,approver:approverFlag,
        read_write_access:"0",location_id:location_id,mobile:mobile,
        secondry_site_id:secondry_site_id,secondry_site_name:secondry_site_name,
        active:"0"
    }).done(function () {
        funGetTeam();
        dataClearUserAccess();
        oDialog.close();
        busyDialog.close();
    }, failureUser);

}

function updateUserAccess(oDialog,obj) {

        if(avatarblobPath==""){
            avatarblobPath = obj['image'];
        }

        var id1 = obj['id'];
        var name1 = sap.ui.getCore().getElementById('userAccess_et1').getValue();
        var email1 = sap.ui.getCore().getElementById('userAccess_et2').getValue();
        var password1 = sap.ui.getCore().getElementById('userAccess_et3').getValue();
        var notification_email = oTextFieldUserAccess4.getValue();
        var mobile = oTextFieldUserAccessMobile.getValue();
        var role  = teamRoleDB.getSelectedKey();

       var assignVehicle = "";
       var objAssignVehicle = oModelAssignVehicle.getProperty("/modelData");
       var assignVehicleCount = oTableAssignVehicle.getBinding("rows").getLength();

       if (assignVehicleCount == vehicleJSONArray.length) {
           assignVehicle = "1";
       } else {
           for (var i = 0; i < assignVehicleCount; i++) {
               if (vehicleArray.indexOf(objAssignVehicle[i]['Vehicle_Number']) > -1) {
                   assignVehicle = assignVehicle + objAssignVehicle[i]['Vehicle_Number'] + "^";
               }
           }
           assignVehicle = assignVehicle.slice(0, -1);
       }

        var userArea = "";
        for(var i=0;i<userSccessDB.getSelectedItems().length;i++){
            if(i==0){
                userArea = userArea + userSccessDB.getSelectedItems()[i].getKey();
            }else{
                userArea = userArea +","+ userSccessDB.getSelectedItems()[i].getKey();
            }
        }
   
        if (validation(name1, oBundle.getText("Name"))) { return; }
        if (validation(email1, oBundle.getText("User_ID"))) { return; }

        if(hasWhiteSpace(email1)){
             sap.m.MessageBox.error(oBundle.getText("User_ID")+" "+oBundle.getText("contain_space"));
             return;
        }

        if (validation(password1, oBundle.getText("Password"))) { return; }
        if (validation(userArea+"", oBundle.getText("User_Access_Area"))) { return; }
        if(notification_email!=""){
        if (regEmail.test(notification_email) == false) {
            sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
            return ;
            }
      }
    
    if (email1.length < 6) {
        sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
        return;
    }
     if (password1.length < 6) { 
        sap.m.MessageBox.error(oBundle.getText("Password_characters"));
        return;
    }

   var approverFlag = approver.getSelected();
   var location_id = locationDB.getSelectedKey();

   var secondry_site_id = "";
   var secondry_site_name = "";
   var oTokenList = secondryLocationDB.getTokens();
   for (var j = 0; j < oTokenList.length; j++) {
   if (secondry_site_id == "") {
       secondry_site_id = oTokenList[j].getKey();
       secondry_site_name = oTokenList[j].getText();
   } else {
       secondry_site_id = secondry_site_id + "^" + oTokenList[j].getKey();
       secondry_site_name = secondry_site_name + "^" + oTokenList[j].getText();
   }
   }
    

   busyDialog.open();
    HVI_AccessControl.update({ id: id1, master_email: emailUser, name: name1, emailid: email1, password: password1,role:role,
            image:avatarblobPath,user_access: userArea, assign_vehicle: assignVehicle, notification_email: notification_email,
            approver:approverFlag,read_write_access:"0",location_id:location_id,mobile:mobile,
            secondry_site_id:secondry_site_id,secondry_site_name:secondry_site_name,
    }).done(function () {
        funGetTeam();
        dataClearUserAccess();
        oDialog.close();
         busyDialog.close();
    }, failureUser);

}

function deleteTeamMember(mid) {

    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Alert"),
        state: sap.ui.core.ValueState.Error,
        content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
        buttons: [
					new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
					    press: function () {
                            busyDialog.open();
					        HVI_AccessControl.del({ id: mid }).done(function () {
					            funGetTeam();
                                oDialog.close();
                                busyDialog.close();
					        });
					    }
					}),
					new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();

}

function dataClearUserAccess() {

    avatarblobPath = "";

    sap.ui.getCore().getElementById('userAccess_et1').setValue("");
    sap.ui.getCore().getElementById('userAccess_et2').setValue("");
    sap.ui.getCore().getElementById('userAccess_et3').setValue("");
    oTextFieldUserAccess4.setValue("");
    oTextFieldUserAccessMobile.setValue("");
    userBlockDB.setValue("No");
    userSccessDB.setSelectedKeys("");
    teamRoleDB.setSelectedKey("1");
    aDataAssignVehicle = [];
    oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
    oTableAssignVehicle.setModel(oModelAssignVehicle);
    oTableAssignVehicle.bindRows("/modelData");

    oTextFieldUserAccess2.setEnabled(true);
    avatarTeam.setSrc(null);
    approver.setSelected(false);
   
    secondryLocationDB.removeAllTokens();
            
}

var teamJSONArray = [];

function funGetTeam() {

    oTableTeam.setBusy(true);

    HVI_AccessControl.where(queryMasterEmail(1)).take(1000).orderByDescending("createdAt").read().done(function (results) {

        teamJSONArray =  results.filter(function (obj, index) {
            if (obj.active == "1") { return false; }
            return true;
        });

        emailJSON = results;

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableTeam.setModel(oModel);
        oTableTeam.bindItems({ path: "/modelData", template: teamTemplate});
        oTableTeam.setBusy(false);

        list23.setInfo(results.length);

        oTableTeamSelect.setModel(oModel);
        oTableTeamSelect.bindItems({ path: "/modelData", template: oTableTeamSelectTemplate });
     
        var oModelAssignDB = new sap.ui.model.json.JSONModel();
        oModelAssignDB.setData({ modelData: results });

        woAssignedInput.setModel(oModelAssignDB);
        woAssignedInput.bindAggregation("suggestionItems", "/modelData", new sap.ui.core.ListItem({
            key:"{emailid}",text: "{name}", additionalText:"{emailid}"}));

        taskAssignedInput.setModel(oModelAssignDB);
        taskAssignedInput.bindAggregation("suggestionItems", "/modelData", new sap.ui.core.ListItem({
            key:"{emailid}",text: "{name}", additionalText:"{emailid}"}));

        addLaborInput.setModel(oModelAssignDB);
        addLaborInput.bindAggregation("suggestionItems", "/modelData", new sap.ui.core.ListItem({
            key:"{emailid}",text: "{name}", additionalText:"{emailid}"}));

    });
}

function displayFormDataUserAccess(obj) {

        aDataAssignVehicle =[];
        oTextFieldUserAccess2.setEnabled(false);

        sap.ui.getCore().getElementById('userAccess_et1').setValue(obj['name']);
        sap.ui.getCore().getElementById('userAccess_et2').setValue(obj['emailid']);
        sap.ui.getCore().getElementById('userAccess_et3').setValue(obj['password']);
        oTextFieldUserAccess4.setValue(obj['notification_email']);
        oTextFieldUserAccessMobile.setValue(obj['mobile']);

        if(obj['approver']=="1"){
              approver.setSelected(true); 
        }else{
             approver.setSelected(false); 
        }
        if(obj['location_id']==null){
            locationDB.setSelectedKey('Default-001');
        }else{
            locationDB.setSelectedKey(obj['location_id']);
        }
        
        avatarTeam.setSrc(obj['image']);
        var mRole = obj['role'];

        if(mRole=="1"||mRole==oBundle.getText("Operator")){
            teamRoleDB.setSelectedKey("1");
        }else if(mRole=="2"||mRole==oBundle.getText("Technician")){
            teamRoleDB.setSelectedKey("2");
        }else if(mRole=="3"||mRole==oBundle.getText("Employee")){
            teamRoleDB.setSelectedKey("3");
        }else if(mRole=="4"){
            teamRoleDB.setSelectedKey("4");
        }  

        var userAcc = obj['user_access'];
        var array = userAcc.split(',');
        userSccessDB.setSelectedKeys(array);

        var assign_vehicle = obj['assign_vehicle'];
        if (assign_vehicle == null) { assign_vehicle = ""; }
        var assign_vehicle = assign_vehicle.split("^");

        if (assign_vehicle != "") {
        for (var i = 0; i < assign_vehicle.length; i++) {

            if (assign_vehicle[i] == "1") {
                for(var j=0;j< vehicleArray.length; j++){
                    aDataAssignVehicle.push({ Vehicle_Number: vehicleArray[j]});
                }
            } else {
                aDataAssignVehicle.push({ Vehicle_Number: assign_vehicle[i] });
            }
        }
        }

       
	    oModelAssignVehicle.setData({ modelData: aDataAssignVehicle });
	    oTableAssignVehicle.setModel(oModelAssignVehicle);
	    oTableAssignVehicle.bindRows("/modelData");

        if(nullCheckAll(obj['secondry_site_id'])){
            secondryLocationDB.removeAllTokens();
            var secondry_site_id = obj['secondry_site_id'].split("^");
            var secondry_site_name = obj['secondry_site_name'].split("^");
            for (var i = 0; i < secondry_site_id.length; i++) {
                secondryLocationDB.addToken(new sap.m.Token({ key: secondry_site_id[i], text: secondry_site_name[i] }));
            }
        }else{
            secondryLocationDB.removeAllTokens();
        }

}

function failureUser(){ alert(oBundle.getText("Failed")); return;}


var toEmailField;
var bccEmailField;
var oDialogTeamSelect;
var selectTeamArea = "";
function teamDialog(){
    
    oDialogTeamSelect = new sap.m.Dialog({
       title: oBundle.getText("Select_Team_Member"),
       state: sap.ui.core.ValueState.Success,
       content: [oTableTeamSelect],
       buttons: [
					new sap.m.Button({
                        type:"Accept",
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialogTeamSelect.close();
					    }
					})
				]
   }).open();
}

function shareDialog(subject,message,dialogTitle,layoutHeader){

    toEmailField = new sap.m.Input({ type: "Email",
        showValueHelp: true,
        placeholder:oBundle.getText("Write_email_or_pick_from_list"),
        //valueHelpOnly: true,
        valueHelpRequest: function () {
            selectTeamArea = "share_email",
            teamDialog();
        }
    });

    bccEmailField = new sap.m.Input({ type: "Email",
        showValueHelp: true,
        //valueHelpOnly: true,
        placeholder:oBundle.getText("Write_email_or_pick_from_list"),
        valueHelpRequest: function () {
            selectTeamArea = "cc_email",
            teamDialog();
        }
    });

   var oLayoutShare = new sap.ui.layout.form.Form({
        editable: true,
        title: layoutHeader,
        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("Share_Email") }),
                        fields: [toEmailField]
                    }),
                    /*new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: "CC"+oBundle.getText("Email") }),
                        fields: [bccEmailField]
                    }),*/
                ]
            })
        ]
    });

    var oDialog = new sap.m.Dialog({
        title: dialogTitle,
        state: sap.ui.core.ValueState.Success,
        content: [oLayoutShare],
        buttons: [
                new sap.m.Button({
                    text: oBundle.getText("Share"),
                    icon: "sap-icon://share-2",
                    press: function () {

                        var toEmail = toEmailField.getValue();
                        var bccEmail = bccEmailField.getValue();

                        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

                        if (reg.test(toEmail) == false) {
                            sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
                            return false;
                        }
                        if (bccEmail != "") {
                            if (reg.test(bccEmail) == false) {
                                sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
                                return false;
                            }
                        }

                        oDialog.close();
                        //sap.m.URLHelper.triggerEmail(toEmail, subject, message, bccEmail);
                        sendShareEmail(toEmail, subject, message, bccEmail);
                    }
                }),
                new sap.m.Button({
                    text: oBundle.getText("Cancel"),
                    icon: "sap-icon://decline",
                    press: function () {
                        oDialog.close();
                    }
                })
            ]
    }).open();
}

function sendShareEmail(toEmail, subject, message, bccEmail){
    // console.log("sachin")
    $.ajax({
        type: "POST",
        url: "https://oxmaint.com/notification/share_file.php",
        data: {
            "toEmail": toEmail,
            "bccEmail": bccEmail,
            "subject": subject,
            "message": message
        },
        success: function (data) {
            sap.m.MessageBox.success(oBundle.getText("Sent"));
        }
    });
}

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

