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


function addUpdateVehicle(src,obj){
    
    var oField21 = new  sap.m.ComboBox({
        value:oBundle.getText("Priority1"),
        items:[
            new sap.ui.core.ListItem({text: oBundle.getText("Priority1")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Priority2")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Priority3")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Priority4")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Priority5")}),
    ]}).addEventDelegate({onAfterRendering: function(e) {oField21.$().find("input").attr("readonly", true);}});

    var oField7 = new sap.m.ComboBox({
        selectedKey:"1",
        items:[
            new sap.ui.core.ListItem({key:"1",text: oBundle.getText("Available")}), 
            new sap.ui.core.ListItem({key:"2",text: oBundle.getText("In_Maintenance")}),
            new sap.ui.core.ListItem({key:"3",text: oBundle.getText("Maintenance_Required")}),
            new sap.ui.core.ListItem({key:"4",text: oBundle.getText("Breakdown")}),
            new sap.ui.core.ListItem({key:"5",text: oBundle.getText("Discontinue")}),
            new sap.ui.core.ListItem({key:"6",text: oBundle.getText("Deployed")}),
            new sap.ui.core.ListItem({key:"7",text: oBundle.getText("Idle")})
            
    ]}).addEventDelegate({onAfterRendering: function(e) {oField7.$().find("input").attr("readonly", true);}});

    var oField22 = new  sap.m.ComboBox({
        items:[
            new sap.ui.core.ListItem({text: oBundle.getText("Owned_Asset")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Leased_Asset")}),
            new sap.ui.core.ListItem({text: oBundle.getText("Rental_Asset")})
        ]
    }).addEventDelegate({onAfterRendering: function(e) {oField22.$().find("input").attr("readonly", true);}});
    
    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 oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: emailJSONLocation });
    locationDB.setModel(oModel);

    var oField0 = new sap.m.ComboBox({
        selectedKey:oBundle.getText("Select_Asset_Type"),
        items:[
            new sap.ui.core.ListItem({key: oBundle.getText("Select_Asset_Type"), text: oBundle.getText("Select_Asset_Type")}),
            new sap.ui.core.ListItem({key: "1", text: oBundle.getText("Asset")}),
            new sap.ui.core.ListItem({key: "2", text: oBundle.getText("Vehicle")}),
        ],
        change:function(){
            // console.log(oField0.getSelectedKey())
            if(oField0.getSelectedKey() == '1'){
                oForm1.getFormContainers()[1].getFormElements()[4].setVisible(false);
                oForm1.getFormContainers()[1].getFormElements()[5].setVisible(false);
                oForm1.getFormContainers()[1].getFormElements()[6].setVisible(false);
                oForm1.getFormContainers()[1].getFormElements()[7].setVisible(false);
                oForm1.getFormContainers()[3].getFormElements()[5].getLabel().setText(oBundle.getText("Sensor_Enabled"));
                oForm1.getFormContainers()[3].getFormElements()[7].getLabel().setText(oBundle.getText("Sensor_Vehicle_ID"));
                
            }else{
                oForm1.getFormContainers()[1].getFormElements()[4].setVisible(true);
                oForm1.getFormContainers()[1].getFormElements()[5].setVisible(true);
                oForm1.getFormContainers()[1].getFormElements()[6].setVisible(true);
                oForm1.getFormContainers()[1].getFormElements()[7].setVisible(true);
                
                oForm1.getFormContainers()[3].getFormElements()[5].getLabel().setText(oBundle.getText("GPS_Enabled"));
                oForm1.getFormContainers()[3].getFormElements()[7].getLabel().setText(oBundle.getText("GPS_Vehicle_ID"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {oField0.$().find("input").attr("readonly", true);}});
    var oField1 = new sap.m.Input({});
    var oField2 = new sap.m.Input({});
    var oField3 = new sap.m.Input({});
    var oField4 = new sap.m.Input({});
    var oField5 = new sap.m.Input({});
    var oField6 = new sap.m.Input({type:"Number",value:0});
   
    var oField8 = new sap.m.Input({type:"Number"});
    var oField9 = new sap.m.Input({});
    var oField10 = new sap.m.Input({});

    var oField11 = new sap.m.Input({});
    var oField12 = new sap.m.Input({type:"Number"});
    var oField13 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy"});
    var oField14 = new sap.m.Input({});
    var oField15 = new sap.m.Input({});
    var oField16 = new sap.m.Input({});
    var oField17 = new sap.m.Input({type:"Number"});
    var oField18 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy"});
    var oField19 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy"});
    var oField20 = new sap.m.Input({});

    var oField23 = new sap.m.TextArea({width:"100%",height:"50px",rows : 2, wrapping : sap.ui.core.Wrapping.on});
    var avatarVehicle = new sap.f.Avatar({src:"sap-icon://product",displaySize: "L",displayShape: "Square",imageFitType: "Cover"});
    
    var assignList = new sap.m.List({mode: "Delete",
        "delete": function (oEvent) {
            var olist = oEvent.getParameter("listItem");
            var oContext = oEvent.getParameter("listItem").getBindingContext();
            var mid;
            try {
                mid = oContext.getObject().id;
                if(nullCheckAll(mid)) {
                    console.log("Value exists in mid");
                }
            } catch (error) {
                console.log("Error occurred:", error.message);
            }
            // var mid = oContext.getObject().id;
      
            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") {
		            assignList.removeItem(olist);
                    HVI_Assign_Form.del({ id: mid}).done(function () { });

		        }
		    });
        },
        headerToolbar: new sap.m.Toolbar({
            content: [new sap.m.Label({ text: oBundle.getText("Assign_Inspection_Form"),design: sap.m.LabelDesign.Bold }), new sap.m.ToolbarSpacer(),
                        new sap.m.Button({ text: oBundle.getText("Forms"), type: sap.m.ButtonType.Accept,
                        icon: "sap-icon://survey", press: function () { assignFormDialog(assignList,1); }
            })]
        })
    });

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

    //var oField24 = new sap.m.Input({type:"Number"});
    var oField25 = new sap.m.Input({});
    var oField26 = new sap.m.Input({});

    var oField27 = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy"});
    var oField28 = new sap.m.Input({type:"Number"});

    var oFieldChk1 = new sap.m.CheckBox({selected: false});
    var oFieldChk2 = new sap.m.CheckBox({selected: false});
    //var oFieldChk3 = new sap.m.CheckBox({selected: true});

     var oForm1 = 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: reqLbl.clone().setText(oBundle.getText("Asset_Type")),fields: [oField0]}),
	            new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Vehicle_Number")),fields: [oField1]}),
                new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Vehicle_Name")),fields: [oField2]}),
                new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Vehicle_Category")),fields: [oField3]}),
                new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Model_Make")),fields: [oField5]}),
                new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Meter_Reading")),fields: [oField6,meterUnit]}),
                new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Status")),fields: [oField7]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("VIN_Number")),fields: [oField4]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Vehicle_Utilization_Goal")),fields: [oField28]}),
		]}),
        new sap.ui.layout.form.FormContainer({
	        formElements: [
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Year")),fields: [oField8]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Manufacture")),fields: [oField10]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Last_Maintenance_Reading")),fields: [oField12]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Last_Maintenance_Date")),fields: [oField13]}),
	            new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Chassis_Number")),fields: [oField9]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("License_Plate")),fields: [oField11]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Registration_State")),fields: [oField14]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Registration_Exp_Date")),fields: [oField27]}),
		    ]}),
        new sap.ui.layout.form.FormContainer({
	        formElements: [
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Site_Project")),fields: [locationDB]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Business_Unit")),fields: [oField15]}),
	            new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Asset_Value")),fields: [oField17]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Purchase_Date")),fields: [oField18]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Warranty_Date")),fields: [oField19]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Required_Geo_Location_while_Inspection")),fields: [oFieldChk1]}),
               new sap.ui.layout.form.FormElement({fields: [assignList]}),
		    ]}),
        new sap.ui.layout.form.FormContainer({formElements: [
        
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Operator_Name")),fields: [oField20]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Maintenance_Priority")),fields: [oField21]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Ownership_Mode")),fields: [oField22]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Vehicle_Note")),fields: [oField23]}),
                new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Vehicle_Image")),
                        fields: [
                                    new sap.ui.layout.HorizontalLayout({content: [
                                        avatarVehicle,new sap.m.Button({
                                            text: oBundle.getText("Upload_Photo"),
                                            type:sap.m.ButtonType.Emphasized,
                                            icon: "sap-icon://add-photo",
                                            press: function () {
                                                uploadVehicleAvatarDialog(avatarVehicle);
                                            }
                                        }).addStyleClass("sapUiSmallMarginBeginEnd")
                                    ]}),
                ]}),

                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("GPS_Enabled")),fields: [oFieldChk2]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Device_ID")),fields: [oField25]}),
                new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("GPS_Vehicle_ID")),fields: [oField26]}),
                
        ]})
	]});

    oForm1.getFormContainers()[1].getFormElements()[4].setVisible(false);
    oForm1.getFormContainers()[1].getFormElements()[5].setVisible(false);
    oForm1.getFormContainers()[1].getFormElements()[6].setVisible(false);
    oForm1.getFormContainers()[1].getFormElements()[7].setVisible(false);
    oForm1.getFormContainers()[3].getFormElements()[5].getLabel().setText(oBundle.getText("Sensor_Enabled"));
    oForm1.getFormContainers()[3].getFormElements()[7].getLabel().setText(oBundle.getText("Sensor_Vehicle_ID"));
    
    var addVehicle = new sap.m.Button({ visible: true, icon: "sap-icon://add",
        text: oBundle.getText("Add_Vehicle"),
        press: function () {

            var value0 = oField0.getSelectedKey();
            // console.log(value0)
            // console.log(typeof(value0))
            if(value0 != "1" && value0 != "2"){
                sap.m.MessageBox.error(oBundle.getText("Select_Asset_Type"));
                return;
            }
            var value1 = oField1.getValue();
            var value2 = oField2.getValue();
            var value3 = oField3.getValue();
            var value4 = oField4.getValue();
            var value5 = oField5.getValue();
            var value6 = oField6.getValue();
            var value7 = oField7.getSelectedKey();

            var value8 = oField8.getValue();
            var value9 = oField9.getValue();
            var value10 = oField10.getValue();
            var value11 = oField11.getValue();

            var value12 = oField12.getValue();
            var value13 = oField13.getValue();

            var value14 = oField14.getValue();
            var value15 = oField15.getValue();
            
            
            var value17 = oField17.getValue();
            var value18 = oField18.getValue();
            var value19 = oField19.getValue();
            var value20 = oField20.getValue();
            var value21 = oField21.getValue();
            var value22 = oField22.getValue();
            var value23 = oField23.getValue();

            // var value24 = oField24.getValue();
            var value25 = oField25.getValue();
            var value26 = oField26.getValue();
            var value27 = oField27.getValue();
            var value28 = oField28.getValue();

            
            var value16 = "Default";
            var location_id = "Default-001";
            if(locationDB.getSelectedItem()!=null){
                value16 = locationDB.getSelectedItem().getText(); 
                location_id = locationDB.getSelectedKey();
            }
            
            var gps_inspection_flag = "1";
            var gps_enabled = "1";

            if (oFieldChk1.getSelected()) {
                gps_inspection_flag = "1";
            }else {
                gps_inspection_flag = "0";
            }
            if (oFieldChk2.getSelected()) {
                gps_enabled = "1";
            }else {
                gps_enabled = "0";
            }


            if (validation(value1, oBundle.getText("Vehicle_Number"))) { return; }
            if (validation(value2, oBundle.getText("Vehicle_Name"))) { return; }
            if (validation(value3, oBundle.getText("Vehicle_Category"))) { return; }
            // if (validation(value4, oBundle.getText("Vehicle_VIN"))) { return; }
            if (validation(value5, oBundle.getText("Vehicle_Model"))) { return; }
            if (validation(value6, oBundle.getText("Meter_Reading"))) { return; }

            if(checkVehicleAlreadyExist(value1)){
                sap.m.MessageBox.error(oBundle.getText("Vehicle_Number_already_exist"));
                return;
            }
            if (vehicleArray.indexOf(value1) > -1) {
                sap.m.MessageBox.error(oBundle.getText("Vehicle_Number_already_exist"));
                return;
            }

            var avatarBlobPath = avatarVehicle.getSrc();
            var created_date = getCurrentDate() + " " + getTime();
            var roundvehicle_meter = twoDecimal(value6);
            var meter_unit = meterUnit.getValue();

            var assignItem = assignList.getItems();
            for (var j = 0; j < assignItem.length; j++) {

                var form_id = assignItem[j].getCustomData()[0].getKey();;
                var form_name = assignItem[j].getTitle();

                HVI_Assign_Form.insert({ master_email: emailUser, form_id: form_id,form_name:form_name,
                    vehicle_number:value1,vehicle_name:value2}).done(function () {});
            }

            /*  if (oFieldChk3.getSelected()) {

                if (validation(value12, oBundle.getText("Last_Service_Reading"))) { return; }
                if (validation(value13, oBundle.getText("Last_Service_Date"))) { return; }

                setAutomaticSchedule(value3,value1,value2,meter_unit,value12,value13);
            }else{
                
            }*/

            busyDialog.open();
            HVI_VehiclesInv.insert({ user_email: emailUser, vehicle_serial: value1, vehicle_name: value2, vehicle_categoty: value3,
                vehicle_vin: value4, vehicle_model: value5, odometer: roundvehicle_meter, odometer_unit: meter_unit, status: value7,

                year: value8, chassis_number: value9, manufacture: value10, license_plate: value11, last_service_reading: value12,
                last_service_date: value13, registration_state: value14,
                location_id:location_id,
                business_unit: value15, location: value16, asset_value: value17, purchase_date: value18, warrantyexpdate: value19,
                vehicle_operator: value20, maintenancepriority: value21, mode: value22, vehicle_note: value23,
                //assign_form_id: assign_form_id, assign_form_name: assign_form_name,
                imgurl: avatarBlobPath, createddate: created_date, createdby: operatedBy,
                gps_inspection_range:"",device_id:value25,gps_vehicle_id:value26,
                gps_inspection_flag: gps_inspection_flag, gps_enabled: gps_enabled,
                registration_exp_date:value27 ,utilization_goal:value28,archive: '0',vehicle_category:value0
            }).done(function () {
                funGetVehicle();
                if(oxmaint_demo_data != "1"){
                    updateLoginData();
                }
                busyDialog.close();
                oDialog.close();
            }, failure);

        }
    });
    var updateVehicle = new sap.m.Button({ visible: false, icon: "sap-icon://edit",
        text: oBundle.getText("Update_Vehicle"),
        press: function () {
            var value0 = oField0.getSelectedKey();
            if(value0 != "1" && value0 != "2"){
                sap.m.MessageBox.error(oBundle.getText("Select_Asset_Type"));
                return;
            }

            var value1 = oField1.getValue();
            var value2 = oField2.getValue();
            var value3 = oField3.getValue();
            var value4 = oField4.getValue();
            var value5 = oField5.getValue();
            var value6 = oField6.getValue();
            var value7 = oField7.getSelectedKey();

            var value8 = oField8.getValue();
            var value9 = oField9.getValue();
            var value10 = oField10.getValue();
            var value11 = oField11.getValue();
            var value12 = oField12.getValue();
            var value13 = oField13.getValue();
            var value14 = oField14.getValue();
            var value15 = oField15.getValue();
        
            var value17 = oField17.getValue();
            var value18 = oField18.getValue();
            var value19 = oField19.getValue();
            var value20 = oField20.getValue();
            var value21 = oField21.getValue();
            var value22 = oField22.getValue();
            var value23 = oField23.getValue();

            // var value24 = oField24.getValue();
            var value25 = oField25.getValue();
            var value26 = oField26.getValue();

            var value27 = oField27.getValue();
            var value28 = oField28.getValue();

            var value16 = "Default";
            var location_id = "Default-001";
            if(locationDB.getSelectedItem()!=null){
                value16 = locationDB.getSelectedItem().getText(); 
                location_id = locationDB.getSelectedKey();
            }

            var gps_inspection_flag = "1";
            var gps_enabled = "1";

            if (oFieldChk1.getSelected()) {
                gps_inspection_flag = "1";
                //if (validation(value24, oBundle.getText("GPS Inspection Range"))) { return; }
            }else {
                gps_inspection_flag = "0";
            }
            if (oFieldChk2.getSelected()) {
                gps_enabled = "1";
                //if (validation(value25, oBundle.getText("Device ID"))) { return; }
                //if (validation(value26, oBundle.getText("GPS Vehicle ID"))) { return; }
            }else {
                gps_enabled = "0";
            }

            if (validation(value1, oBundle.getText("Vehicle_Number"))) { return; }
            if (validation(value2, oBundle.getText("Vehicle_Name"))) { return; }
            if (validation(value3, oBundle.getText("Vehicle_Category"))) { return; }
            // if (validation(value4, oBundle.getText("Vehicle_VIN"))) { return; }
            if (validation(value5, oBundle.getText("Vehicle_Model"))) { return; }
            if (validation(value6, oBundle.getText("Meter_Reading"))) { return; }

            var avatarBlobPath = avatarVehicle.getSrc();
            var modifieddate = getCurrentDate() + " " + getTime();
            var roundvehicle_meter = twoDecimal(value6);
            var meter_unit = meterUnit.getValue();

            var assignItem = assignList.getItems();
            for (var j = 0; j < assignItem.length; j++) {

                var form_id = assignItem[j].getCustomData()[0].getKey();;
                var form_name = assignItem[j].getTitle();

                if(assignFormArray.indexOf(form_id) == -1){
                    HVI_Assign_Form.insert({ master_email: emailUser, form_id: form_id,form_name:form_name,
                        vehicle_number:value1,vehicle_name:value2}).done(function () {});
                }
            }

            busyDialog.open();
            HVI_VehiclesInv.update({ id: obj['id'], user_email: emailUser, vehicle_serial: value1, vehicle_name: value2, vehicle_categoty: value3,
                vehicle_vin: value4, vehicle_model: value5, odometer: roundvehicle_meter, odometer_unit:meter_unit, status: value7,

                year: value8, chassis_number: value9, manufacture: value10, license_plate: value11, last_service_reading: value12,
                last_service_date: value13, registration_state: value14,
                location_id:location_id,
                business_unit: value15, location: value16, asset_value: value17, purchase_date: value18, warrantyexpdate: value19,
                vehicle_operator: value20, maintenancepriority: value21, mode: value22, vehicle_note: value23,
                //assign_form_id: assign_form_id, assign_form_name: assign_form_name,
                imgurl: avatarBlobPath, modifieddate: modifieddate, modifiedby: operatedBy,
                gps_inspection_range:"",device_id:value25,gps_vehicle_id:value26,
                gps_inspection_flag: gps_inspection_flag, gps_enabled: gps_enabled,
                registration_exp_date:value27 ,utilization_goal:value28,vehicle_category:value0
            }).done(function () {
                funGetVehicle()
                busyDialog.close();
                oDialog.close();
            }, failure);

        } 
    });

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


    if(src==2){

        oDialog.setTitle(oBundle.getText("Update_Vehicle"));
        addVehicle.setVisible(false);
        updateVehicle.setVisible(true);
        oField1.setEnabled(false);
        if(!nullCheckAll(obj['vehicle_category'])){
            oField0.setSelectedKey("2");  
            oForm1.getFormContainers()[1].getFormElements()[4].setVisible(true);
            oForm1.getFormContainers()[1].getFormElements()[5].setVisible(true);
            oForm1.getFormContainers()[1].getFormElements()[6].setVisible(true);
            oForm1.getFormContainers()[1].getFormElements()[7].setVisible(true);
            oForm1.getFormContainers()[3].getFormElements()[5].getLabel().setText(oBundle.getText("GPS_Enabled"));
            oForm1.getFormContainers()[3].getFormElements()[7].getLabel().setText(oBundle.getText("GPS_Vehicle_ID")); 
        }else{
            oField0.setSelectedKey("1");
            oForm1.getFormContainers()[1].getFormElements()[4].setVisible(false);
            oForm1.getFormContainers()[1].getFormElements()[5].setVisible(false);
            oForm1.getFormContainers()[1].getFormElements()[6].setVisible(false);
            oForm1.getFormContainers()[1].getFormElements()[7].setVisible(false);
            oForm1.getFormContainers()[3].getFormElements()[5].getLabel().setText(oBundle.getText("Sensor_Enabled"));
            oForm1.getFormContainers()[3].getFormElements()[7].getLabel().setText(oBundle.getText("Sensor_Vehicle_ID"));
        }
        oField1.setValue(obj['vehicle_serial']);
        oField2.setValue(obj['vehicle_name']);
        oField3.setValue(obj['vehicle_categoty']);
        oField4.setValue(obj['vehicle_vin']);
        oField5.setValue(obj['vehicle_model']);

        oField6.setValue(obj['odometer']);
        meterUnit.setValue(obj['odometer_unit']);
        oField7.setSelectedKey(obj['status']);

        oField8.setValue(obj['year']);
        oField9.setValue(obj['chassis_number']);
        oField10.setValue(obj['manufacture']);
        oField11.setValue(obj['license_plate']);
        oField12.setValue(obj['last_service_reading']);
        oField13.setValue(obj['last_service_date']);
        oField14.setValue(obj['registration_state']);

        oField15.setValue(obj['business_unit']);
        oField16.setValue(obj['location']);
        oField17.setValue(obj['asset_value']);
        oField18.setValue(obj['purchase_date']);
        oField19.setValue(obj['warrantyexpdate']);
        oField20.setValue(obj['vehicle_operator']);
        oField21.setValue(obj['maintenancepriority']);

        oField22.setValue(obj['mode']);
        oField23.setValue(obj['vehicle_note']);

      // oField24.setValue(obj['gps_inspection_range']);
        oField25.setValue(obj['device_id']);
        oField26.setValue(obj['gps_vehicle_id']);
        oField27.setValue(obj['registration_exp_date']);
        oField28.setValue(obj['utilization_goal']);

        if(obj['location_id']==null){
            locationDB.setSelectedKey('Default-001');
        }else{
            locationDB.setSelectedKey(obj['location_id']);
        }

        if(obj['gps_inspection_flag'] != null && obj['gps_inspection_flag'] =="1"){
            oFieldChk1.setSelected(true);
        }
        if(obj['gps_enabled'] != null && obj['gps_enabled'] =="1"){
            oFieldChk2.setSelected(true);
        }
        
        if(obj['imgurl']){
            avatarVehicle.setSrc(obj['imgurl']);
        }
        var assignFormArray = [];
        assignList.setBusy(true);
        HVI_Assign_Form.where({ master_email: emailUser,vehicle_number : obj['vehicle_serial']}).take(100).orderByDescending("createdAt").read().done(function (results) {

            for (var i = 0; i < results.length; i++) {
                var form_id = results[i]['form_id'];
                assignFormArray.push(form_id);
            }

            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({ modelData: results });
            assignList.setModel(oModel);
    
            var oItemItem = new sap.m.StandardListItem({
                title: "{form_name}",
                customData: new sap.ui.core.CustomData({key:"{form_id}"})
            });
            assignList.bindAggregation("items", "/modelData", oItemItem);
            assignList.setBusy(false);
        });
    }else{
        
        addVehicle.setVisible(true);
        updateVehicle.setVisible(false);
        oField1.setEnabled(true);
    }
}

// function setAutomaticSchedule(vehicle_category,vehicle_number,vehicle_name,odometer_unit,last_service_reading,last_service_date){

//     busyDialogSchedule.open();
//     $.ajax({
//         type: "POST",
//         url: "https://prod-251.westeurope.logic.azure.com:443/workflows/dbe4b2ff9cf84f1eb14492267b5a894f/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=1ahShmqtAoR8-r6MYqN7SXvSXmIGmnjWlssWNPvB26I",
//         contentType: 'application/json',
//         dataType: 'json',
//         data: JSON.stringify({
//             "master_email": emailUser,
//             "vehicle_category": vehicle_category,
//             "vehicle_number": vehicle_number,
//             "vehicle_name": vehicle_name,
//             "odometer_unit": odometer_unit,
//             "last_service_reading": last_service_reading,
//             "last_service_date": last_service_date
//         }),
//         success: function (data) {
//             getScheduleDetails();
//             busyDialogSchedule.close();
//          }
//     });

// }

function assignFormDialog(assignList,src,vehicle_number,vehicle_name) {

    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true,
        resizable: true, rememberSelections: false, multiSelect: true,
        title: oBundle.getText("Select_Inspection_Form"),
        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("group_name", sap.ui.model.FilterOperator.Contains, sSearchValue),
                    new sap.ui.model.Filter("description", 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 aContexts = oEvent.getParameter("selectedContexts");
            if (aContexts && aContexts.length) {
               aContexts.map(function (oContext) { 
                    var id =  oContext.getObject()['id'];
                    var group_name =  oContext.getObject()['group_name'];
                    if(src==2){
                        HVI_Assign_Form.insert({ master_email: emailUser, form_id: id,form_name:group_name,
                            vehicle_number:vehicle_number,vehicle_name:vehicle_name}).done(function () {});
                    }

                    assignList.addItem(new sap.m.StandardListItem({title: group_name,
                        customData: new sap.ui.core.CustomData({key:id})
                    }));   
                });
            }
        }
    });

    var oItemTemplate = new sap.m.StandardListItem({
        title: "{group_name}",
        type: "Active",
        customData: new sap.ui.core.CustomData({key:"{id}"})
    });
     var assignItem = assignList.getItems();
     var AssignKey = [];
     for (var j = 0; j < assignItem.length; j++) {
         AssignKey.push(assignItem[j].getCustomData()[0].getKey());    
      }

      var result = inspectionFormJSON.filter(function (obj, index) {
          return (AssignKey.indexOf(obj.id) < 0);
      });

    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"));
}

function uploadVehicleAvatarDialog(avatarVehicle){

        standartBusyDialog.setText("");

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

        var oFileUploaderVehicle = new sap.ui.unified.FileUploader({
            name: "file",
            uploadUrl: "https://oxmaint.com/upload/avatar_vehicle.php",
            sendXHR: true,
            maximumFileSize: 5,
            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");
                    standartBusyDialog.setText(Math.floor((nLoaded / nTotal) * 100)+"%");
                }
            },
            fileSizeExceed: function (oEvent) {
                sap.m.MessageBox.error(oBundle.getText("avatar_image_size"));
            },
            typeMissmatch: function (oEvent) {
                sap.m.MessageBox.error(oBundle.getText("This_is_not_valid_file_type"));
            },
            uploadAborted: function (oEvent) { },
            uploadComplete: function (oEvent) { 
                var ext = oEvent.getParameter("responseRaw").replace(/"/g, "");
                oDialog.close();
                standartBusyDialog.close();
                var avatarSrc = "https://oxmaint.com/upload/avatarVehicle/" + userFolder + "/" + filenale + "." + ext;
                avatarVehicle.setSrc(avatarSrc);
            }
        });

	
     var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Upload_Photo"),
        content: [oFileUploaderVehicle],
        buttons: [
                  new sap.m.Button({
					    text: oBundle.getText("Upload"),
					    icon: "sap-icon://upload",
					    press: function () {
                           
                            if(oFileUploaderVehicle.getValue()!=""){
                                standartBusyDialog.open();
					            oFileUploaderVehicle.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();
}