
var hvi_default_type = sessionStorage.getItem('oxmaint_default_type');


// 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 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 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 hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

