
var myinteger = (/^-?\d*(\.\d+)?$/);
var oBundle = "";
var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

var current_date = getCurrentDate();
var segmentedDate1 = new Date(current_date);
var segmentedDate2 = new Date(current_date);
var hvi_team_role = '1';
const allowedRoles = ["Administrator", "Account Payable Team", "Driver", "Maintenance Team","Quality Team"]; // Define allowed roles

// const messaging = firebase.messaging();
sap.ui.getCore().getConfiguration().setFormatLocale("en-US");

var dataRecordCount = 5;
var multiLocationDB = new sap.m.ComboBox({width:"10%"});
multiLocationDB.addEventDelegate({onAfterRendering: function(e) {multiLocationDB.$().find("input").attr("readonly", true);}});


// var oxmaint_subscription = "Yes";
var oxmaint_subscription = sessionStorage.getItem('subscription_type');
let oxmaint_demo_data = sessionStorage.getItem("oxmaint_demo_data");
let portal_type_flag = sessionStorage.getItem("portal_type");
	

var oxmaint_approval_level = sessionStorage.getItem("oxmaint_approval_level");
var oxmaint_approval_amount = sessionStorage.getItem("oxmaint_approval_amount");

var oxmaint_ws_group_name = sessionStorage.getItem("oxmaint_ws_group_name");
var oxmaint_ws_group_number = sessionStorage.getItem("oxmaint_ws_group_number");
var oxmaint_workshop_number = sessionStorage.getItem("oxmaint_workshop_number");
var oxmaint_workshop_name = sessionStorage.getItem("oxmaint_workshop_name");
var oxmaint_role = sessionStorage.getItem('oxmaint_role');
var oxmaint_wo_verification = sessionStorage.getItem('oxmaint_wo_verification');
var oxmaint_approval_array;

var reqLbl = new sap.m.Label({ required: true });
var oLbl = new sap.m.Label({ });




var hvi_location_id = sessionStorage.getItem('oxmaint_location_id');
if(hvi_location_id == null){
    hvi_location_id = "Default-001";
};



multiLocationDB.attachSelectionChange(function () {
    var loc = multiLocationDB.getSelectedKey();
    sessionStorage.setItem('oxmaint_location_id', loc);
    window.location.reload();
    hvi_location_id = loc;

    //onload(1);
});

var languageDB = new sap.m.ComboBox({layoutData: new sap.m.OverflowToolbarLayoutData({priority: "Low"})});
languageDB.setWidth("10%");
languageDB.addItem(new sap.ui.core.ListItem({text:"English"}));
languageDB.addEventDelegate({onAfterRendering: function(e) {languageDB.$().find("input").attr("readonly", true);}});

var languageCode = sessionStorage.getItem('languageCode');
if(languageCode == null){ languageCode = "EN";}

var vehicleArray;

if (languageCode == "EN") {
    oBundle = jQuery.sap.resources({ url: "i18n/i18n_en.properties" });
    languageDB.setValue("English");
} else{
    oBundle = jQuery.sap.resources({  url : "i18n/i18n_en.properties"}); 
    languageDB.setValue("English");
}

languageDB.attachSelectionChange(function () {

    var lang = languageDB.getSelectedItem().getText();

    if (lang == "English") {
        sessionStorage.setItem('languageCode', "EN");
    }
    window.location.reload();
});


var emailUser = sessionStorage.getItem('oxmaint_email');

var admin_name = sessionStorage.getItem('oxmaint_admin_name');
var hvi_login_type = sessionStorage.getItem('oxmaint_login_type');

var hvi_userid = sessionStorage.getItem('oxmaint_userid');
var employee_name = sessionStorage.getItem('oxmaint_employee_name');
var hvi_notification_email = sessionStorage.getItem('oxmaint_notification_email');
var hvi_account_access_value = sessionStorage.getItem('oxmaint_account_access');
var oxmaint_supplier_id = sessionStorage.getItem('oxmaint_supplier_id');


var hvi_user_access_value = sessionStorage.getItem('oxmaint_user_access');
var hvi_user_access = [];
if (hvi_user_access_value != null && hvi_user_access_value != "") {
    hvi_user_access = hvi_user_access_value.split(",");
}else{
    hvi_user_access = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18'];
}

var assign_vehicle_value = sessionStorage.getItem('oxmaint_assign_vehicle');
    
var hvi_assign_vehicle = [];
if (assign_vehicle_value != null && assign_vehicle_value != "") {
    hvi_assign_vehicle = assign_vehicle_value.split("^");
}

if(emailUser == null){
    sessionStorage.removeItem('oxmaint_email');
    window.open("login.html", "_self");
}

var hvi_remember = sessionStorage.getItem('oxmaint_remember');
if(hvi_remember){
        if(emailUser == null){
        sessionStorage.removeItem('oxmaint_email');
        window.open("login.html", "_self");
    }
}else{
    if(hvi_login_type=="1"){
        sessionStorage.removeItem('oxmaint_email');
        window.open("login.html", "_self");
    }
    
}

var operatedID = emailUser;
var operatedBy = emailUser;

if (hvi_userid != null) {
    if (employee_name != null) {
        operatedID = hvi_userid;
        operatedBy = employee_name;
    } else {
        if (admin_name != "" && admin_name != null) {
            operatedBy = admin_name;
        } 
    }
} else {
    if (admin_name != "" && admin_name != null) {
        operatedBy = admin_name;
    } 
}


//Single Tab Open Only
const channel = new BroadcastChannel('tab');
channel.postMessage('another-tab');
// note that listener is added after posting the message

channel.addEventListener('message', (msg) => {
  if (msg.data === 'another-tab') {
    // message received from 2nd tab
    alert('Cannot open multiple instances');
    window.open("about:blank", "_self");
    window.close();
  }
});



var hvi_approver = sessionStorage.getItem('oxmaint_approver');
var hvi_write_access = sessionStorage.getItem('oxmaint_write_access');

var subscription_status = sessionStorage.getItem('oxmaint_status');
var subscription_count = sessionStorage.getItem('oxmaint_count');
var plan_name = sessionStorage.getItem('oxmaint_plan');

var driverReminderDays = {
    9: "1 time in 28 calendar days",
    11: "1 time in 14 calendar days",
    12: "1 time in 14 calendar days",
    14: "5 times in a week",
    21: "1 time in 14 calendar days",
    24: "1 time in a week",
    25: "1 time in 28 calendar days",
    27: "1 time in a week",
    28: "5 times in a week",
    29: "1 time in 14 calendar days",
    30: "1 time in 14 calendar days",
    31: "1 time in 14 calendar days",
    32: "1 time in a week",
    33: "1 time in a week",
    34: "1 time in a week"
};

var driverTypeArray = {
    "9": "Gold",
    "11": "Greenline",
    "12": "Sahabat Rental",
    "14": "EV",
    "21": "Sahabat Sejati",
    "24": "Sahabat Rental HVR",
    "25": "Emoto",
    "27": "Premium EV",
    "28": "Premium Non EV",
    "29": "Sahabat Rental Airport",
    "30": "Sahabat Rental HVR ICE Airport",
    "31": "Sahabat Rental Plus",
    "32": "Sahabat Rental HVR EV",
    "33": "Sahabat Rental HVR EV Airport",
    "34": "Sahabat Rental HVR ICE"
  }
  
  
  

function nullCheck(value){
    return (value != null && value != "");
}

function nullCheckAll(value){
    return (value !=null && value !="null" && value != ""  && value!="undefined");
}

function getHourMinutes(value) {
    if (nullCheck(value)) {
        var hours = Math.floor(value / 60);
        var minutes = value % 60;
        return hours + "H " + minutes + "M";
    }else{
        return "0H 0M";
    }
}

function dateDiffInDays(a, b) {

    if (nullCheck(a) && nullCheck(b)) {

        var MS_PER_DAY = 1000 * 60 * 60 * 24;
        var date1 = new Date(a);
        var date2 = new Date(b);
        var diff = new Date(date2.getTime() - date1.getTime());
        return Math.floor(diff / MS_PER_DAY);
    }else{
        return 0;
    }
}

function minusCheck(value){
    if(value != null && value != ""){
         var numberValue = parseFloat(value);
         if(numberValue<0){
             return true;
         }
    }
    return false;
}

function twoDecimal(value){
    
    return Math.round(parseFloat(value) * 100) / 100; 
}

function getStatusText(status){
    
      var statusArray = [oBundle.getText("Requested"),//0
                        oBundle.getText("Initiated"),//1
                        oBundle.getText("In_Progress"),//2
                        oBundle.getText("On_Hold"),//3
                        oBundle.getText("Complete"),//4
                        oBundle.getText("Rework"),//5
                        oBundle.getText("Postponed"),//6
                        oBundle.getText("Closed"),//7
                        oBundle.getText("Rejected"),//8
                        oBundle.getText("Inspected"),//9
                        oBundle.getText("Approved"),//10
                        oBundle.getText("Scheduled"),//11
                        oBundle.getText("Waiting_for_Approval")];//12 

      return statusArray[Number(status)];
}
function getWOStatusText(status){
    
      var statusArray = [oBundle.getText("Pending_Approval"),//0
                        oBundle.getText("Open"),//1
                        oBundle.getText("Complete"),//2
                        oBundle.getText("Closed"),//3
                        oBundle.getText("GRM"),//4
                        oBundle.getText("Reject"),//5
                        oBundle.getText("Cancelled"),//6
                        oBundle.getText("Approved"),//7
                       ]; 

      return statusArray[Number(status)];
}
function getPOStatusText(status){
    
    var statusArray = ["",
                      oBundle.getText("Open"),//1
                      oBundle.getText("Waiting_for_Approval"), //Request-2
                      oBundle.getText("Approved"), //Accepted - 3
                      oBundle.getText("Rejected"), //4
                      oBundle.getText("Ordered"), //Release - 5
                      oBundle.getText("Received"), //Completed - 6
                      oBundle.getText("Partial_Received"),  //7
                      oBundle.getText("Closed"), //8
                    ];
                      //Open, Waiting for Approval, Rejected, Approved ,Ordered, Received , Close
    return statusArray[Number(status)];
}

function getPOItemStatusText(status){
    
    var statusArray = ["",
                      oBundle.getText("Demand"),
                      oBundle.getText("Return"), 
                      oBundle.getText("Replace"), 
                      
                    ];
                      
    return statusArray[Number(status)];
}
function getDemandStatusText(status){
    
    var statusArray = ["",
                      oBundle.getText("Open"),//1
                      oBundle.getText("PO_Generated"), 
                      oBundle.getText("Received"),
                    ];
                     
    return statusArray[Number(status)];
}
function getTyreStatusText(status){
    
    var statusArray = ["",
                      oBundle.getText("New"),//1
                      oBundle.getText("Retreaded"), 
                      oBundle.getText("Retired"),
                      oBundle.getText("Old"),
                    ];
                     
    return statusArray[Number(status)];
}

function getTaskStatusText(status){
    
    var statusArray = [oBundle.getText("Inspected"),
                      oBundle.getText("Initiated"),
                      oBundle.getText("In_Progress"),
                      oBundle.getText("On_Hold"),
                      oBundle.getText("Complete"),
                      oBundle.getText("Rework"),
                      oBundle.getText("Postponed"),
                      oBundle.getText("No_Need"),
                      oBundle.getText("Initiated")
                      ];

    return statusArray[Number(status)];
}

function getPriorityText(priority){
    
      var priorityArray = ["",
                            oBundle.getText("Low"),
                            oBundle.getText("Medium"),
                            oBundle.getText("High"),
                            oBundle.getText("Emergency")];

    return priorityArray[Number(priority)]
}
function getToolStatus(status){
    
    var oArray = ["",
                oBundle.getText("Available"),
                oBundle.getText("Not_Available"),
                oBundle.getText("In_Maintenance"),
                oBundle.getText("Out_of_Service")];
  return oArray[Number(status)]
}
function getRootCauseText(root){
    
    var oArray = ["",
                oBundle.getText("Driver/Employee_Negligence"),
                oBundle.getText("Lack_of_Maintenance"),
                oBundle.getText("Run_to_Failure"),
                oBundle.getText("Part_Damaged")];
  return oArray[Number(root)]
}
function getIncidentStatusText(status){
    
    var oArray = ["",
                oBundle.getText("Open"),
                oBundle.getText("Processing"),
                oBundle.getText("Claimed"),
                oBundle.getText("Closed")];
  return oArray[Number(status)]
}

function getVehicleStatus(status){
    
    if(isNaN(status)){status = "1";}

    var oArray = ["",
                oBundle.getText("Available"),
                oBundle.getText("In_Maintenance"),
                oBundle.getText("Maintenance_Required"),
                oBundle.getText("Breakdown"),
                oBundle.getText("Discontinue"),
                oBundle.getText("Deployed"),
                oBundle.getText("Idle")
            ];
  return oArray[Number(status)]
}
function getVehicleHistorySource(source){
    
    var oArray = ["",
                oBundle.getText("vehicle insert entry"),
                oBundle.getText("vehicle update entry"),
                oBundle.getText("Inspection_Entry"),
                oBundle.getText("Workorder_complete_entry"),
                oBundle.getText("Service_schedule_complete_entry"),
                oBundle.getText("Fuel_entry"),
                oBundle.getText("Corrective_Action"),
                oBundle.getText("GPS")
            ];
  return oArray[Number(source)]
}
function getVehicleHistoryType(type){
    
    var oArray = ["",
                oBundle.getText("Odometer_Updated"),
                oBundle.getText("Status_Updated")];
  return oArray[Number(type)]
}


function getZeroOne(value) {

    if (value) { 
        return "1"; 
    }else{
        return "0";
    }
}
function getTrueFalse(value) {

    if (value=="1") { 
        return true; 
    }else{
        return false;
    }
}
function getTrueFalseIcon(value) {

    if (value=="1") { 
        return "sap-icon://accept"; 
    }else{
        return "sap-icon://decline"; 
    }
}
function getNotificationIconEmail(value) {

    if (value=="1") { 
        return "sap-icon://email"; 
    }else{
        return null; 
    }
}
function getNotificationIconMobile(value) {

    if (value=="1") { 
        return "sap-icon://iphone"; 
    }else{
        return null; 
    }
}
function secondsToHms(d) {

     if (d < 60) { return "0h0m"; }

    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? "h" : "h") : "0h";
    var mDisplay = m > 0 ? m + (m == 1 ? "m" : "m") : "0m";
    var sDisplay = s > 0 ? s + (s == 1 ? "s" : "s") : "";
    return hDisplay + mDisplay + sDisplay; 
}

function getCurrentDate(){
     
    var date = new Date();
    var yyyy = date.getFullYear().toString();
    var mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based
    var dd = date.getDate().toString();
    if(dd.length==1){
        dd = "0" + dd;
    }
    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    return dd + "-" + monthNames[date.getMonth()] + "-" + yyyy;
}

function getTime( ) {

var d = new Date( ); 
d.setHours( d.getHours() ); // offset from local time
var h = (d.getHours() % 12) || 12; // show midnight & noon as 12
return (
    ( h < 10 ? '0' : '') + h +
    ( d.getMinutes() < 10 ? ':0' : ':') + d.getMinutes() +
            // optional seconds display
    // ( d.getSeconds() < 10 ? ':0' : ':') + d.getSeconds() + 
    ( d.getHours() < 12 ? ' AM' : ' PM' )
);
}

function getTimeWithSec( ) {

    var d = new Date( ); 
    d.setHours( d.getHours() ); // offset from local time
    var h = (d.getHours() % 12) || 12; // show midnight & noon as 12
    return (
        ( h < 10 ? '0' : '') + h +
        ( d.getMinutes() < 10 ? ':0' : ':') + d.getMinutes() +
                // optional seconds display
         ( d.getSeconds() < 10 ? ':0' : ':') + d.getSeconds() + 
        ( d.getHours() < 12 ? ' AM' : ' PM' )
    );
    }

function getUTC_Time(oTime,src){

    var d = new Date(getCurrentDate()+ " "+oTime);
    var h = addZero(d.getUTCHours());
    var m = addZero(d.getUTCMinutes());
   
   var in_min = (parseInt(h)*60)+parseInt(m);
   if(src==2){
      
    return in_min
   }else{
       return h + ":" + m;
   }
}
function addZero(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  }
  
function getTimeZone() {
    var offset = new Date().getTimezoneOffset(),
        o = Math.abs(offset);
    return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
}

function validateEmail(email) { 
    if (email.trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
        return true;
    }else{
        return false;
    }
}

function timeConverter(UNIX_timestamp){

    var a = new Date(UNIX_timestamp * 1000);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + '-' + month + '-' + year;// + '-' + hour + ':' + min + ':' + sec ;
    return time;
}

function getDeleteMenu(oMenu,oKey){

    // if(hvi_login_type=="1" ||(hvi_login_type == "2" && hvi_team_role == "4")){
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://delete",
        text: oBundle.getText("Delete"),key: oKey,startsSection: true}));
    // }
}
function getApprovalMenu(oMenu){

    if (hvi_login_type == "1" || (hvi_login_type == "2" && (hvi_approver == "1" || hvi_team_role == "4"))) {
        oMenu.insertItem(new sap.m.MenuItem({icon: "sap-icon://show",
        text: oBundle.getText("View_and_Approve"),key: "1"
        }), 0);
    }
}


function getTrialAlert(){
    var pay_flag = sessionStorage.getItem("oxmaint_pay_flag"); 
    // var subscription_type = sessionStorage.getItem("subscription_type");

    if(nullCheckAll(pay_flag) && pay_flag == "1" && subscription_status != "Active"){
        return true;
    }else{
        return false;
    }
};


function getTrialAlertDialogue(){
    var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Trial_Expired"),
        content: [new sap.m.Label({textAlign:"Center" , width:"100%",text: oBundle.getText("pay_subscription_alert")})],
        buttons: [
            new sap.m.Button({
                text: oBundle.getText("Subscription"),
                icon: "sap-icon://payment-approval",
                press: function () {
                    navContainer.to("p14");
                    navigationItemMaster.setExpanded(true)
                    sideNavigation.setSelectedKey("p14");
                    oDialog.close();
                }
            }),
                new sap.m.Button({
                    text: oBundle.getText("Contact"),
                    icon: "sap-icon://customer-and-contacts",
                    press: function () {
                        navContainer.to("p11");
                        navigationItemMaster.setExpanded(true)
                        sideNavigation.setSelectedKey("p11");
                        
                        var oObjectPageLayout = sap.ui.getCore().byId("accountPageLayout");
                        var oSection = sap.ui.getCore().byId("AD5"); 
                        oObjectPageLayout.setSelectedSection(oSection);
                        oDialog.close();

                    }
                })
            ]
    }).open();
};


function getLocationName(locationId){
    var filter_location = emailJSONLocation.filter(function(value,index){
        return value.location_id == locationId;
    })

    if(filter_location.length > 0){
        return filter_location[0]['location_name'];
    }else{
        return locationId
    }
}
function filterQueryTaskInspection(emailUser) {
         return this.master_email === emailUser && this.source === "1" && this.added_flag === "1";
    }

function filterQueryTask(emailUser,inspection_id) {
        return this.master_email === emailUser && this.inspection_id === inspection_id && this.source === "1";
 }

 function filterQueryFaultList(emailUser,vehicle_number) {
    return this.master_email === emailUser && this.vehicle_number === vehicle_number && this.task_status !="4" && this.source === "1";
}


function filterQuerySchedule1(emailUser) {
        return this.master_email === emailUser && this.status !="2";
}
function filterQuerySchedule2(emailUser,hvi_location_id) {
    return this.master_email === emailUser && this.status !="2" && this.location_id === hvi_location_id;
}

function filterQueryScheduleComplete1(emailUser) {
        return this.master_email === emailUser && this.status =="2";
}

function filterQueryScheduleComplete2(emailUser,hvi_location_id) {
    return this.master_email === emailUser && this.status =="2" && this.location_id === hvi_location_id;
}


function queryFault() { 

    if(hvi_location_id=="Default-001"){
        return  { master_email: emailUser, source: "1", added_flag: "1" };
    }else{
        return  { master_email: emailUser, source: "1", added_flag: "1",location_id : hvi_location_id};
    }    
}

function queryInspection(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return  {user_name:emailUser, archive : "0"};
        }else if(src==2){ 
            return  {user_name:emailUser, archive : "1"};
        }else if(src==3){ 
            return  { user_name: emailUser};
        }
    }else{
        if(src==1){ 
            return  {user_name:emailUser, archive : "0",location_id : hvi_location_id};
        }else if(src==2){ 
            return  {user_name:emailUser, archive : "1",location_id : hvi_location_id};
        }else if(src==3){ 
            return  { user_name: emailUser,location_id : hvi_location_id};
        }
    }    
}

function filterQueryWorkorderOpen1(emailUser) {
    return this.master_email === emailUser && this.archive ==="0"&& this.approved =="1" && this.wo_status !="4" && this.wo_status !="7";
}

function filterQueryWorkorderOpen2(emailUser,hvi_location_id) {
    return this.master_email === emailUser && this.archive === "0" && this.approved =="1" && this.wo_status !="4" && this.wo_status !="7" && this.location_id === hvi_location_id;
}

function filterQueryWorkorderCompleted1(emailUser) {
    return this.master_email === emailUser && this.archive ==="0"&& this.approved =="1" && (this.wo_status ==="4" || this.wo_status ==="7");
}

function filterQueryWorkorderCompleted2(emailUser,hvi_location_id) {
    return this.master_email === emailUser && this.archive ==="0"&& this.approved =="1" && (this.wo_status ==="4" || this.wo_status ==="7") && this.location_id === hvi_location_id;
}

function queryWorkorder(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { master_email: emailUser, approved:"1"}; //archive:"0",
        }else if(src==2){ 
            return { master_email: emailUser,archive:"1", approved:"1"};
        }else if(src==3){
            return { master_email: emailUser,archive:"0", approval_request:"1", approved:"0"};
        }else if(src==4){
            return { master_email: emailUser};
        }else if(src==5){ 
            return { master_email: emailUser,archive:"0", approved:"1" , wo_status:"4"};
        }
    }else{
        if(src==1){ 
            return { master_email: emailUser, approved:"1",location_id : hvi_location_id}; //archive:"0", 
        }else if(src==2){ 
            return { master_email: emailUser,archive:"1", approved:"1",location_id : hvi_location_id};
        }else if(src==3){
            return { master_email: emailUser,archive:"0", approval_request:"1", approved:"0",location_id : hvi_location_id};
        }else if(src==4){
            return { master_email: emailUser,location_id : hvi_location_id};
        }else if(src==5){ 
            return { master_email: emailUser,archive:"0", approved:"1", wo_status:"4", location_id : hvi_location_id};
        }
    }    
}

function queryPO(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { master_email: emailUser,archive:"0", approved:"1"};
        }else if(src==2){ 
            return { master_email: emailUser,archive:"1", approved:"1"};
        }else if(src==3){
            return { master_email: emailUser,archive:"0", approval_request:"1", approved:"0"};
        }else if(src==4){
            return { master_email: emailUser};
        }
    }else{
        if(src==1){ 
            return { master_email: emailUser,archive:"0", approved:"1",location_id : hvi_location_id};
        }else if(src==2){ 
            return { master_email: emailUser,archive:"1", approved:"1",location_id : hvi_location_id};
        }else if(src==3){
            return { master_email: emailUser,archive:"0", approval_request:"1", approved:"0",location_id : hvi_location_id};
        }else if(src==4){
            return { master_email: emailUser,location_id : hvi_location_id};
        }
    }    
}

function queryUserEmail(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { user_email: emailUser };
        }
    }else{
        if(src==1){ 
            return { user_email: emailUser,location_id : hvi_location_id};
        }
    }    
}

function queryPartsInventory(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { user_email: emailUser};
        }else if(src==2){ 
           // return { user_email: emailUser,scrap_flag:"1" };
        }else if(src==3){ 
           // return { user_email: emailUser,float_flag:"1" };
        }
    }else{
       
        if(src==1){ 
            return { user_email: emailUser,location_id : hvi_location_id };
        }else if(src==2){ 
           // return { user_email: emailUser,location_id : hvi_location_id,scrap_flag:"1" };
        }else if(src==3){ 
           // return { user_email: emailUser,location_id : hvi_location_id,float_flag:"1" };
        }
    }    
}

function queryMasterEmail(src) {

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { master_email: emailUser };
        }
    }else{
        if(src==1){ 
            return { master_email: emailUser,location_id : hvi_location_id};
        }
    }    
}

function queryUserEmailBunker(src) {


   // alert(hvi_location_id);

    if(hvi_location_id=="Default-001"){
        if(src==1){ 
            return { master_email: emailUser,source:"1" };
        }else if(src==2){ 
            return { master_email: emailUser,source:"2" };
        }
    }else{
        if(src==1){ 
            return {  master_email: emailUser,source:"1",location_id : hvi_location_id};
        }else if(src==2){ 
            return {  master_email: emailUser,source:"2",location_id : hvi_location_id};
        }
    }    
}

function funFilterJsonByVehicle(result){

    var results=[];
    if(hvi_login_type=="2"){
       results = result.filter(function(obj, index){
           if (hvi_assign_vehicle.length > 0) {
                   if (hvi_assign_vehicle[0] == "1") {
                       return true;
                   } else {
                       return (hvi_assign_vehicle.indexOf(obj.vehicle_serial) > -1 );
                   }
                }else{
                    return false;
                }
           });
       }else{
           results = result;
       }
       return results;
}
function funFilterJsonByVehicleNumber(result){

    var results=[];
    if(hvi_login_type=="2"){
       results = result.filter(function(obj, index){
           if (hvi_assign_vehicle.length > 0) {
                   if (hvi_assign_vehicle[0] == "1") {
                       return true;
                   } else {
                       return (hvi_assign_vehicle.indexOf(obj.vehicle_number) > -1 );
                   }
                }else{
                    return false;
                }
           });
       }else{
           results = result;
       }
       return results;
}
function funFilterJsonByVehicleNo(result){

    var results=[];
    if(hvi_login_type=="2"){
       results = result.filter(function(obj, index){
           if (hvi_assign_vehicle.length > 0) {
                   if (hvi_assign_vehicle[0] == "1") {
                       return true;
                   } else {
                       return (hvi_assign_vehicle.indexOf(obj.vehicle_no) > -1 );
                   }
                }else{
                    return false;
                }
           });
       }else{
           results = result;
       }
       return results;
}
function funFilterJsonByVehicleAnsUser(result){

    var results=[];
    if(hvi_login_type=="2"){
    results = result.filter(function(obj, index){
        if (hvi_assign_vehicle.length > 0) {
            if (hvi_assign_vehicle[0] == "1") {return true;
            } else {
                return (hvi_assign_vehicle.indexOf(obj.vehicle_number) > -1 || hvi_userid  === obj.assign);
            }
            }else{return false; }
        });
    }else{
        results = result;
    }
    return results;
}
function filterQueryVehicleMeterHistory(emailUser,startDate,endDate) {
    return this.master_email === emailUser  && this.type === "1" &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewMeterHistory(emailUser,vehicleNumber,startDate,endDate) {
    return this.master_email === emailUser && this.vehicle_number === vehicleNumber &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewInspection(emailUser,vehicleNumber,startDate,endDate) {
    return this.master_email === emailUser && this.license_number === vehicleNumber && this.archive != "1" &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewWorkorder(emailUser,vehicleNumber,startDate,endDate) {
    return this.master_email === emailUser  && this.license_number === vehicleNumber && //&& this.archive === "0"
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewDaily(emailUser,vehicleNumber,startDate,endDate) {
    return this.user_email === emailUser && this.vehicle_number === vehicleNumber &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewIncident(emailUser,vehicleNumber,startDate,endDate) {
    return this.user_email === emailUser && this.vehicle_number === vehicleNumber &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}
function filterQueryVehicleViewFuel(emailUser,vehicleNumber,startDate,endDate) {
    return this.user_email === emailUser && this.vehicle_number === vehicleNumber &&
    (this.createdAt >= new Date(startDate) && this.createdAt <= new Date(endDate));
}

//reports query



//----------------------Filter Queries------------------------------------
//function for filter queries.
function filterQueryFuelLog1(email, startDate, endDate) {
    return this.user_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryTankHistory1(email, startDate, endDate) {
    return this.master_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryTankAdjustment1(email, startDate, endDate) {
    return this.master_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};

function filterQueryFuelLog2(email,site_id, startDate, endDate) {
    return this.user_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};
function filterQueryTankHistory2(email,site_id, startDate, endDate) {
    return this.master_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};
function filterQueryTankAdjustment2(email,site_id, startDate, endDate) {
    return this.master_email == email && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};


function filterQueryFuelBunkerHistoryReport1(mail, startDate, endDate){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryFuelBunkerHistoryReport2(mail, startDate, endDate, site_id){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryPartsReport1(mail, startDate, endDate){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryPartsReport2(mail, startDate, endDate, site_id){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryToolReport1(mail, startDate, endDate){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryToolReport2(mail, startDate, endDate, site_id){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryInspectionReport1(mail, startDate, endDate){
    return this.user_name == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryInspectionReport2(mail, startDate, endDate, site_id){
    return this.user_name == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryDailyReport1(mail, startDate, endDate){
    return this.user_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryDailyReport2(mail, startDate, endDate, site_id){
    return this.user_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryWorkorderReport1(mail, startDate, endDate){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryWorkorderReport2(mail, startDate, endDate, site_id){
    return this.master_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQueryIncidentReport1(mail, startDate, endDate){
    return this.user_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};


function filterQueryFuelLogReport1(mail, startDate, endDate){
    return this.user_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryFuelLogReport2(mail, startDate, endDate, site_id){
    return this.user_email == mail && this.createdAt <= endDate && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

function filterQuerySchedule3(mail) {
    return this.master_email == mail && this.deleted == 0 && this.location_id == hvi_location_id && this.status == '2';
};

//filter query
function filterQueryWorkorderDashboardReport1(mail, startDate){
    return this.master_email == mail && this.createdAt >= startDate && this.deleted == 0;
};

function filterQueryWorkorderDashboardReport2(mail, startDate,  site_id){
    return this.master_email == mail && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};


function filterQueryFuelDashboardReport1(email, startDate){
    return this.user_email == email && this.createdAt >= startDate && this.deleted == 0;
};
function filterQueryFuelDashboardReport2(email, startDate, site_id){
    return this.user_email == email &&  this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};
//filter query
function filterQueryIDReport1(mail, startDate){
    return this.user_name == mail && this.__createdAt >= startDate && this.deleted == 0;
};
function filterQueryIDReport2(mail, startDate, site_id){
    return this.user_name == mail && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};

//filter query
function filterQueryInspectionDashboard1(mail, startDate){
    return this.user_name == mail && this.__createdAt >= startDate && this.deleted == 0;
};
function filterQueryInspectionDashboard2(mail, startDate, site_id){
    return this.user_name == mail && this.createdAt >= startDate && this.deleted == 0 && this.location_id == site_id;
};




function isDecimal(value) {
    // Check if the value is of type 'number' and is finite
    if (typeof value === 'number' && isFinite(value)) {
        return true;
    }

    // If the value is a string, try to parse it as a number and check if it's finite
    if (typeof value === 'string') {
        const parsedValue = parseFloat(value);
        return !isNaN(parsedValue) && isFinite(parsedValue);
    }

    // For other types, return false
    return false;
}

function checkVehicleAlreadyExist(vehicleNumber){
    var existVehicleFilter = vehicleJSONArray.filter(item => item.vehicle_serial == vehicleNumber);
    if(existVehicleFilter.length > 0){
        return true;
    }else{
        return false;
    }
}




// //Notification permission
// let permission = Notification.permission;

// if(permission === "granted") {
//
//     showNotification();
// } else {
//     
//     requestAndShowPermission();
// } 
// function showNotification() {

//     var title = "JavaScript Jeep";
//     icon = "https://oxmaint.com/portal/Images/logo.png"
//     var body = "Message to be displayed";
//     var notification = new Notification('Title', { body, icon });
//     notification.onclick = () => { 
//         notification.close();
//         window.parent.focus();
//     }
// }
// function requestAndShowPermission() {
//     Notification.requestPermission(function (permission) {
//     if (permission === "granted") {
//             showNotification();
//     }
//     });
// }






//Sample Data


function getDate(){
    
    var date = new Date();
    var yyyy = date.getFullYear().toString();
    var mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based
    var dd  = date.getDate().toString();
        if(dd.length==1){
            dd = "0" + dd;
        }
    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    return curDate = dd+"-"+monthNames[date.getMonth()]+"-"+yyyy;

    }

// function addDaysToDate(daysToAdd) {
//     let dateString = getIndonesianTime();
//     // Convert the input date string into a Date object
//     let date = new Date(dateString);
    
//     // Add the number of days to the date
//     date.setDate(date.getDate() + daysToAdd);
    
//     // Format the result in the desired format (e.g., "dd-MMM-yyyy hh:mm tt")
//     let options = { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: true };
//     return date.toLocaleString('en-GB', options).replace(',', '');
// }


// Date Format LIKE DD-MMM-yyyy HH:mm tt
function addDaysToDate(daysToAdd) {
    let dateString = getIndonesianTime();
    // Convert the input date string into a Date object
    let date = new Date(dateString);
    
    // Add the number of days to the date
    date.setDate(date.getDate() + daysToAdd);
    
    // Extract day, month, and year
    const day = date.getDate().toString().padStart(2, '0'); // Ensure day is 2 digits
    const month = date.toLocaleString('en-GB', { month: 'short' }); // Short month like 'Oct'
    const year = date.getFullYear();
    
    // Extract hours and minutes, adjust for 12-hour format with AM/PM
    let hours = date.getHours();
    const minutes = date.getMinutes().toString().padStart(2, '0'); // Ensure minutes are 2 digits
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12 || 12; // Convert 24-hour format to 12-hour

    // Ensure hours are 2 digits
    const formattedHours = hours.toString().padStart(2, '0');
    
    // Return formatted date and time
    return `${day}-${month}-${year} ${formattedHours}:${minutes} ${ampm}`;
};

// Date Format LIKE DD-MMM-yyyy
function addDaysToDate1(daysToAdd) {
    let dateString = getIndonesianTime();
    // Convert the input date string into a Date object
    let date = new Date(dateString);
    
    // Add the number of days to the date
    date.setDate(date.getDate() + daysToAdd);
    
    // Get day, month, and year in the desired format
    const day = date.getDate().toString().padStart(2, '0');
    const month = date.toLocaleString('en-GB', { month: 'short' });
    const year = date.getFullYear();

    // Return the formatted string
    return `${day}-${month}-${year}`;
};

function formatDateToDDMMMYYYY(inputDate) {
    // Ensure inputDate is a Date object
    const date = new Date(inputDate);

    if (isNaN(date.getTime())) {
        throw new Error("Invalid date provided.");
    }

    // Extract year, month, and day
    const year = date.getFullYear();
    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const month = monthNames[date.getMonth()];
    const day = String(date.getDate()).padStart(2, '0');

    // Return formatted date
    return `${day}-${month}-${year}`;
};

function formatDateToYYYYMMDD(inputDate) {
    if(!nullCheckAll(inputDate)){
        return
    }
    // Ensure inputDate is a Date object
    const date = new Date(inputDate);

    if (isNaN(date.getTime())) {
        throw new Error("Invalid date provided.");
    }

    // Extract year, month, and day
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
    const day = String(date.getDate()).padStart(2, '0');

    // Return formatted date
    return `${year}-${month}-${day}`;
};




var cityCB = new sap.m.ComboBox({width:"100%",
    value:oBundle.getText("Select_City"),
    items:[
        new sap.ui.core.ListItem({text: oBundle.getText("Select_City")}),
        new sap.ui.core.ListItem({text: oBundle.getText("BANDUNG")}),
        new sap.ui.core.ListItem({text: oBundle.getText("BALI")}),
        new sap.ui.core.ListItem({text: oBundle.getText("JAKARTA")}),
        new sap.ui.core.ListItem({text: oBundle.getText("MAKASSAR")}),
        new sap.ui.core.ListItem({text: oBundle.getText("MALANG")}),
        new sap.ui.core.ListItem({text: oBundle.getText("MEDAN")}),
        new sap.ui.core.ListItem({text: oBundle.getText("MANADO")}),
        new sap.ui.core.ListItem({text: oBundle.getText("PALEMBANG")}),
        new sap.ui.core.ListItem({text: oBundle.getText("SEMARANG")}),
        new sap.ui.core.ListItem({text: oBundle.getText("SOLO")}),
        new sap.ui.core.ListItem({text: oBundle.getText("SURABAYA")}),
        new sap.ui.core.ListItem({text: oBundle.getText("YOGYAKARTA")}),
        // // new sap.ui.core.ListItem({text: oBundle.getText("HEAD OFFICE AND ACCOUNTING OFFICE")}),
        // new sap.ui.core.ListItem({text: oBundle.getText("STI jakarta")}),
]}).addEventDelegate({onAfterRendering: function(e) {cityCB.$().find("input").attr("readonly", true);}});




function formatToIDR(amount) {
    // Format as integer without decimal places
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0, // Avoid showing decimals
        maximumFractionDigits: 0  // Avoid showing decimals
    }).format(amount);
};
// function formatIDRWithoutSymbol(amount) {
//     const formatted = new Intl.NumberFormat('id-ID', {
//         style: 'currency',
//         currency: 'IDR',
//         minimumFractionDigits: 2,
//         maximumFractionDigits: 2
//     }).format(amount);
    
//     // Remove "Rp" and any whitespace
//     return formatted.replace(/[Rp\s]/g, '').trim();
// }
function formatIDRWithoutSymbol(amount) {
    const formatted = new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(amount);

    // Remove "Rp" and whitespace
    let result = formatted.replace(/[Rp\s]/g, '').trim();

    // Remove ",00" if present at the end
    if (result.endsWith(',00')) {
        result = result.slice(0, -3);
    }

    return result;
}



function getIndonesianTime() {
    // Specify the desired time zone for Indonesia (e.g., Asia/Jakarta)
    const indonesianTimeZone = "Asia/Jakarta";

    // Get the current time in the specified time zone
    const now = new Date();
    const options = { timeZone: indonesianTimeZone };

    // Create a formatter for date and time
    const formatter = new Intl.DateTimeFormat("en-US", {
        ...options,
        day: "2-digit",
        month: "short", // Short month name
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        hour12: true, // For AM/PM format
    });

    // Format the date-time
    const parts = formatter.formatToParts(now);
    const dateParts = {
        day: "",
        month: "",
        year: "",
        hour: "",
        minute: "",
        dayPeriod: "",
    };

    // Map parts to build the formatted string
    parts.forEach(part => {
        if (part.type in dateParts) {
            dateParts[part.type] = part.value;
        }
    });

    // Construct the date-time string in the required format
    const formattedTime = `${dateParts.day}-${dateParts.month}-${dateParts.year} ${dateParts.hour}:${dateParts.minute} ${dateParts.dayPeriod}`;

    // console.log(`Indonesian Time (${indonesianTimeZone}): ${formattedTime}`);
    return formattedTime;
}



//Schedule
function filterQueryGrabSchedule() {
    return (
        this.master_email === emailUser && this.status !="2" 
        // && (allowedRoles.includes(oxmaint_role)  || this.workshop_number == oxmaint_workshop_number)
    );
}

//Inspection
function filterQueryGrabInspection(src) {

    if(src==1){ 
        return  {master_email:emailUser, archive : "0"};//,workshop_number:oxmaint_workshop_number};
    }else if(src==2){ 
        return  {master_email:emailUser, archive : "1"};//,workshop_number:oxmaint_workshop_number};
    }

}



//Workorder
function filterQueryGrabWorkorder(status) {
    return (
        this.master_email == emailUser && this.wo_status == status && this.archive != "1" &&
        (allowedRoles.includes(oxmaint_role)  || this.workshop_number == oxmaint_workshop_number)
    );
};
//Supplier Wo Pick
function filterQueryGrabSuppInvWO(status) {
    return (
        this.master_email == emailUser && this.wo_status == status && this.archive != "1" &&
        this.supplier_wo_flag == 'Supplier' && this.supplier_id == oxmaint_supplier_id //&& (this.supplier_inv_pick != 'Done')
    );
};

function filterQueryGrabAllWorkorder() {
    return (
        this.master_email == emailUser && this.archive != "1" &&
        (allowedRoles.includes(oxmaint_role)  || this.workshop_number == oxmaint_workshop_number)
    );
};

function filterQueryGrabArchiveWorkorder() {
    return (
        this.master_email == emailUser && this.archive == "1" &&
        (allowedRoles.includes(oxmaint_role)  || this.workshop_number == oxmaint_workshop_number)
    );
};



//Vehicle Duplicate Check
function filterQueryVehicleCheck(license_number,vehicle_id){
    return this.master_email == emailUser && this.license_number == license_number  && this.id != vehicle_id && this.deleted == 0;
};

//Parts Duplicate Check
function filterQueryPartCheck(part_name,workshop,part_id,make,model,transmission){
    return this.master_email == emailUser && this.part_name == part_name && this.workshop_number == workshop  
    && this.make == make && this.model == model && this.transmission == transmission 
    && this.id != part_id && this.deleted == 0;
};


// function filterQueryWOReport1(startDate, endDate){
//     return this.master_email == emailUser && this.createdAt >= startDate &&  this.createdAt <= endDate;
// };
// function filterQueryWOReport2(startDate, endDate){
//     return this.master_email == emailUser && this.workshop_number == oxmaint_workshop_number && this.createdAt >= startDate &&  this.createdAt <= endDate;
// };




function roundToInt(value) {
    return Math.round(Math.abs(value));
}

function filterGrabVehicle(result){
    return result;
    // // if (oxmaint_role == 'Administrator' || hvi_assign_vehicle[0] == '1') {
    // if (allowedRoles.includes(oxmaint_role) || hvi_assign_vehicle[0] == '1') {
    //     return result; 
    // }else{
    //     return result.filter((a) => hvi_assign_vehicle.includes(a.license_number));
    // };
    
}


function validateNumber(value, field) {
    // console.log(value)
    if (
        value === null || 
        value === undefined || 
        value === '' || 
        isNaN(value) 
        
    ) {
        sap.m.MessageBox.error(field + " " + oBundle.getText("is_Empty"));
        return true;
    }else if (
        /\s/.test(value.toString()) ||  // Check for spaces
        /[.,-]/.test(value.toString())  // Check for ',', '.', and '-'
        ){
             sap.m.MessageBox.error(field + " " + oBundle.getText("is_not_a_valid_number"));
        return true;
        }
    return false;
}


function getIndexDate(){
     
    var date = new Date();
    var yyyy = date.getFullYear().toString().substr(-2);
    var mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based
    var dd = date.getDate().toString();
    if(dd.length==1){
        dd = "0" + dd;
    }
    if(mm.length==1){
        mm = "0" + mm;
    }
 
    return yyyy + "" + mm + "" + dd;
}





//Disable right click and ctrl + shift + I on the web portal
// document.addEventListener('keydown', function(event) {
//     if (event.ctrlKey && event.shiftKey && event.key === 'I') {
//         event.preventDefault(); // Prevent the default action (opening dev tools)
//         // alert('Developer tools are disabled on this page.');
//     }
//     if (e.key === "F12") {
//         e.preventDefault();
//     }
// });

document.addEventListener("keydown", function (e) {
    if (e.ctrlKey && (e.key === "U" || e.key === "I" || e.key === "J" || e.key === "C")) {
        e.preventDefault();
    }
    if (e.key === "F12") {
        e.preventDefault();
    }
});
//Prevent Rifght click 
document.addEventListener('contextmenu', function(event) {
    event.preventDefault(); // Prevent the right-click context menu
    // alert('Right-click is disabled on this page.');
});
//Disable Mouse Scroll
document.addEventListener("wheel", function(event) {
    if (document.activeElement.type === "number") {
        event.preventDefault();
    }
}, { passive: false });
//Session Timeout
(function () {
    let inactivityTime = 1800000; // 30 minutes (in milliseconds)
    let warningTime = 1200000; // Show warning at 20 minutes
    let timeout, warningTimeout;

    function logoutUser() {
        const vehicleType = localStorage.getItem("vehicleType")
        sessionStorage.clear();
        localStorage.clear();
        localStorage.setItem("vehicleType", vehicleType)
        alert("Session expired due to inactivity.");
        window.location.href = "login.html"; // Redirect to logout page
    }

    function showWarning() {
        sap.m.MessageBox.error("You will be logged out soon due to inactivity!");
    }

    function resetTimer() {
        clearTimeout(timeout);
        clearTimeout(warningTimeout);
        warningTimeout = setTimeout(showWarning, warningTime);
        timeout = setTimeout(logoutUser, inactivityTime);
    }

    // Reset timer on user activity
    document.addEventListener("mousemove", resetTimer);
    document.addEventListener("keypress", resetTimer);
    document.addEventListener("click", resetTimer);
    document.addEventListener("scroll", resetTimer);

    // Initialize the timer
    resetTimer();
})();

// setInterval(function () {
//     var before = new Date().getTime();
//     debugger;  // Forces a pause when DevTools is open
//     var after = new Date().getTime();
//     if (after - before > 100) {
//         alert("Developer Tools detected! Closing the page.");
//         window.location.href = "about:blank"; // Redirect to blank page
//     }
// }, 1000);




// async function uploadFile() {
//     const fileInput = document.getElementById('fileInput');
//     const file = fileInput.files[0];

//     const containerUrl = "https://<your-storage-account>.blob.core.windows.net/<your-container>?<sas-token>";

//     const blobName = file.name;
//     const blockBlobClient = new azureStorageBlob.BlockBlobClient(`${containerUrl}/${blobName}`);

//     try {
//       await blockBlobClient.uploadBrowserData(file);
//       alert('Upload successful!');
//     } catch (err) {
//       console.error('Upload failed:', err.message);
//     }
// }

// const { BlobServiceClient } = Azure.Storage.Blobs;
// var selectedFileWO = null;
// function uploadToBlobStorage(){
//     var oFileUploaderAttachment = new sap.ui.unified.FileUploader({
//         name: "attachment",
//         uploadUrl: "", // leave empty
//         sendXHR: true,
//         maximumFileSize: 5,
//         fileType: [
//           "jpeg", "jpg", "png", "pdf", "ppt", "xls", "xlsx", "doc"
//         ],
//         width: "100%",
//         placeholder: oBundle.getText("Choose_a_file_for_uploading"),
      
//         change: function (oEvent) {
//             selectedFile = oEvent.getParameter("files")[0];
//             if (selectedFile) {
//               sap.m.MessageToast.show("File selected: " + selectedFile.name);
//             }
//           },
      
//         fileSizeExceed: function (oEvent) {
//           sap.m.MessageBox.error(oBundle.getText("file_size_warning"));
//         },
//         typeMissmatch: function (oEvent) {
//           sap.m.MessageBox.error(oBundle.getText("This_is_not_valid_file_type"));
//         }
//       });
 
//       var oDialog = new sap.m.Dialog({
//         contentWidth: "50%",
//         draggable: true,
//         resizable: true,
//         title: oBundle.getText("Upload_Work_Order_Attachment"),
//         state: sap.ui.core.ValueState.Success,
//         content: [oFileUploaderAttachment],
//         buttons: [
//           new sap.m.Button({
//             text: oBundle.getText("Upload"),
//             icon: "sap-icon://upload",
//             press: function () {
//             //   var attachName = attachmentName.getValue();
//             //   var attachment_type = attachedTypeDB.getValue();
//             //   var attachment_typeKey = attachedTypeDB.getSelectedKey();
//             //   if (attachment_typeKey == "1") {
//             //     sap.m.MessageBox.error(oBundle.getText("Select_attachment_type"));
//             //     return;
//             //   }
    
//               if (!selectedFile) {
//                 sap.m.MessageBox.warning("Please select a file first.");
//                 return;
//               }

//               try {
//                 uploadToAzure(selectedFile);
               
//               } catch (err) {
//                 sap.m.MessageBox.error("Upload failed: " + err.message);
//               } finally {
//                 standartBusyDialog.close();
//               }

//             //   var file = oEvent.getParameter("files")[0];
//             //   if (!file) {
//             //     return;
//             //   }
          
//             //   oDialogAttachment.setText("Uploading...");
//             //   standartBusyDialog.open();
          
//             //   try {
//             //     await uploadToAzure(file);
//             //   } catch (err) {
//             //     sap.m.MessageBox.error("Upload failed: " + err.message);
//             //   } finally {
//             //     standartBusyDialog.close();
//             //   }
              
//             //   if (oFileUploaderAttachment.getValue() != "") {
//             //     oDialogAttachment.open();
//             //     oFileUploaderAttachment.upload();
//             //   } else {
//             //     sap.m.MessageBox.error(oBundle.getText("Select_file_for_upload"));
//             //   }
//               // }
//             },
//           }),
//           new sap.m.Button({
//             text: oBundle.getText("Cancel"),
//             icon: "sap-icon://decline",
//             press: function () {
//               oDialog.close();
//             },
//           }),
//         ],
//       }).open();

// }

// async function uploadToAzure1(file) {
//     const sasToken = "sp=racwli&st=2025-03-01T10:32:43Z&se=2030-03-01T18:32:43Z&spr=https&sv=2022-11-02&sr=c&sig=7AvtxmEhIGbwqkVM6JE8wn6KWcHHBPGFWipqNMB2vZk%3D";
//     const storageAccount = "https://primerentalstg.blob.core.windows.net";
//     const containerName = "prime";
  
//     // const blobName = Date.now() + "_" + file.name;
//     // const blobUrl = `https://${storageAccount}.blob.core.windows.net/${containerName}/${blobName}`;
//     const containerUrlWithSAS = `https://${storageAccount}.blob.core.windows.net/${containerName}?${sasToken}`;

//   // Create a BlobServiceClient
//   const blobServiceClient = BlobServiceClient.fromConnectionString(containerUrlWithSAS);

//   // Get the container client
//   const containerClient = blobServiceClient.getContainerClient(containerName);

//   // Generate a unique blob name
//   const blobName = Date.now() + "_" + file.name;

//   // Get a BlockBlobClient for the selected blob
//   const blockBlobClient = containerClient.getBlockBlobClient(blobName);

//   try {
//     // Upload the file to Azure Blob Storage
//     await blockBlobClient.uploadBrowserData(file, {
//       blobHTTPHeaders: { blobContentType: file.type }
//     });

//     // Generate the URL for the uploaded file
//     const blobUrl = `https://${storageAccount}.blob.core.windows.net/${containerName}/${blobName}`;
//   }catch{
//     console.log("error")
//   }
    
    
    
    
//     // const containerUrlWithSAS = `https://${storageAccount}.blob.core.windows.net/${containerName}?${sasToken}`;
  
//     // const blockBlobClient = new azureStorageBlob.BlockBlobClient(`${containerUrlWithSAS}/${blobName}`);
  
//     // await blockBlobClient.uploadBrowserData(file, {
//     //   blobHTTPHeaders: { blobContentType: file.type }
//     // });
//     // sap.m.MessageToast.show("Upload successful!");
//     // // After upload, you can save the URL to your DB
//     // const attachment_url = blobUrl;
//     // const created_date = getIndonesianTime();
//     // const attachName = attachmentName.getValue();
//     // const attachment_type = attachedTypeDB.getValue();
  
//     // return Car_Workorder_Attachment.insert({
//     //   master_email: emailUser,
//     //   wo_id: workorderID,
//     //   wo_number: workorderID,
//     //   attachment_name: attachName,
//     //   attached_by: operatedBy,
//     //   attached_date: created_date,
//     //   attachment_url: attachment_url,
//     //   attachment_type: attachment_type
//     // }).done(function () {
//     // sap.m.MessageToast.show("Upload successful!");
//     //   funWorkorderAttachment();
//     //   oDialogAttachment.close();
//     //   oDialog.close();
//     // });
//   }
  


//   async function uploadToAzure(file) {
//     const sasToken = "sp=racwli&st=2025-03-01T10:32:43Z&se=2030-03-01T18:32:43Z&spr=https&sv=2022-11-02&sr=c&sig=7AvtxmEhIGbwqkVM6JE8wn6KWcHHBPGFWipqNMB2vZk%3D";
//     const storageAccount = "primerentalstg.blob.core.windows.net";
//     const containerName = "prime";
    
//     // Container URL with SAS token
//     const containerUrlWithSAS = `https://${storageAccount}/${containerName}?${sasToken}`;

//     // try {
//         // Create a BlobServiceClient using the SAS URL
//         const blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(containerUrlWithSAS);

//         // Get a container client
//         const containerClient = blobServiceClient.getContainerClient(containerName);

//         // Generate a unique blob name
//         const blobName = Date.now() + "_" + file.name;

//         // Get a BlockBlobClient for the selected blob
//         const blockBlobClient = containerClient.getBlockBlobClient(blobName);

//         // Upload the file to Azure Blob Storage
//         await blockBlobClient.uploadBrowserData(file, {
//             blobHTTPHeaders: { blobContentType: file.type }
//         });

//         const blobUrl = `https://${storageAccount}/${containerName}/${blobName}`;
//         sap.m.MessageToast.show("Upload successful!");

//         // You can save the `blobUrl` for later use (e.g., store it in your DB)
//     // } catch (err) {
//     //     sap.m.MessageBox.error("Upload failed: " + err.message);
//     // }
// }







// function bookignSch(){
//     console.log("sachin")
//     $.ajax({
//         type: "POST",
//         url: `https://grab-api-stg.azurewebsites.net/V01/Grab_Inspection.asmx/create_booking`,
//         data: {     
//             "id":"391",
//             "status":"Scheduled",
//             "location_id":"433",
//             "location_name":"Pool BSD",
//             "booking_flag":"1",
//             "booking_id":"BKID12345",
//             "booking_date":"2025-06-02",
//             "booking_slot":"slot10_11",
//             "master_email":"demo@oxmaint.com"
//         },
//         success: function (data) {
//             console.log("Done AJAX 1" + data)
//         },
//         error: function(xhr, status, error) {
//             console.log(xhr)
//         }
//     });
//     $.ajax({
//         type: "POST",
//         url: `${api_url_name}/Grab_Inspection.asmx/create_booking`,
//         data: {
//            "id":"391",
//             "status":"Scheduled",
//             "location_id":"433",
//             "location_name":"Pool BSD",
//             "booking_flag":"1",
//             "booking_id":"BKID1212",
//             "booking_date":"2025-06-02",
//             "booking_slot":"slot10_11",
//             "master_email":"demo@oxmaint.com",
//         },
//         success: function (data) {

//             console.log("Done AJAX 2" + data)
//         },
//         error: function(xhr, status, error) {
//             console.log(xhr)
//         }
//     });

// }