
var formSelectSource = "inspection";

var inspectionField1 = new sap.m.Input({});
var inspectionField2 = new sap.m.Input({});
var inspectionField3 = new sap.m.Input({});

function getInspectionIndex(){

     var itemList = accountList1.getItems();
    inspectionField2.setValue(operatedBy);
    inspectionField3.setValue(operatedBy);
    busyDialog.open();
    HVI_Index.where({ id: emailUser }).read().done(function (results) {

            var newReportNo = Number(sessionStorage.getItem('report_start_no')) + Number(results[0]['inspection']) + 1;
            inspectionField1.setValue(sessionStorage.getItem('report_prefix') + newReportNo);
            inspectionField1.setEnabled(false);
            busyDialog.close();
        });
}

var inspectionTypeRB1 = new sap.m.RadioButton({text:oBundle.getText("Quick_Inspection")});
var inspectionTypeRB2 = new sap.m.RadioButton({text:oBundle.getText("Detailed_Inspection")});		
var inspectionTypeRG = new sap.m.RadioButtonGroup({columns : 2,
        selectedIndex:1,
        buttons:[inspectionTypeRB1,inspectionTypeRB2],
        select: function (e) {
      
        }
});

var inspectionField4 = new sap.m.Input({
    showValueHelp: true,
    valueHelpOnly: true,
    placeholder: oBundle.getText("Select_inspection_form_from_list"),
    valueHelpRequest: function () {
        selectFormDialog();
        //formSelectSource = "inspection";
    }
});
 
 
 function selectFormDialog() {

    var oSelectDialog = new sap.m.SelectDialog({ contentWidth: "50%", draggable: true, rememberSelections: false, multiSelect: false,
        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 selectedItem = oEvent.getParameter("selectedItem");
            inspectionField4.setValue(selectedItem.getTitle());
            funGetInspectionForm(selectedItem.getCustomData()[0].getKey());
           
        }
    });

	var oItemTemplate = new sap.m.StandardListItem({
		title: "{group_name}",
		description: "{description}",
		type: "Active",
        customData: new sap.ui.core.CustomData({key:"{id}"})
	})


    var reverseForm = [...inspectionFormJSON];
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: reverseForm.reverse() });
    oSelectDialog.setModel(oModel); 
    oSelectDialog.bindAggregation("items", "/modelData", oItemTemplate);
    oSelectDialog.open();    
    
    oSelectDialog._getCancelButton().setText(oBundle.getText("Cancel"));
}
   
var inspectionFieldV1 = new sap.m.Input({
        showValueHelp: true,
        valueHelpOnly: true,
        placeholder:oBundle.getText("Select_vehicle_from_inventry_list"),
        valueHelpRequest: function () {
             selectVehiclArea = "inspection";
             pickVehicle();
        }
    });

var inspectionFieldV2 = new sap.m.Input({enabled:false});
var inspectionFieldV3 = new sap.m.Input({enabled:false});
var inspectionFieldV4 = new sap.m.Input({type:"Number"});

 var inspectionMeterDB = new sap.m.ComboBox();
        inspectionMeterDB.addItem(new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Miles")}));
        inspectionMeterDB.addItem(new sap.ui.core.ListItem({key:"2",text:oBundle.getText("KM")}));
        // inspectionMeterDB.addItem(new sap.ui.core.ListItem({key:"3",text:oBundle.getText("Hours")}));
        inspectionMeterDB.setSelectedKey("2");
 inspectionMeterDB.addEventDelegate({
         onAfterRendering: function(e) {
              inspectionMeterDB.$().find("input").attr("readonly", true);
         }
        });


 var inspectionForm1 = new sap.ui.layout.form.Form({
				editable: true,
				layout: new sap.ui.layout.form.ResponsiveGridLayout(),
				formContainers: [
					new sap.ui.layout.form.FormContainer({
						formElements: [
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true, text: oBundle.getText("Report")+" #"}),
								fields: [inspectionField1]
							}),
							new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true, text: oBundle.getText("Location")}),
								fields: [inspectionField2]
							}),
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true,text: oBundle.getText("Inspector_Name")}),
								fields: [inspectionField3]
							}),
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true,text: oBundle.getText("Select_Inspection_Form")}),
								fields: [inspectionField4]
							}),
						   ]
						}),
                    new sap.ui.layout.form.FormContainer({
						formElements: [
                         new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true,text: oBundle.getText("License_Number")}),
								fields: [inspectionFieldV1]
							}),
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true,text: oBundle.getText("Vehicle_Name")}),
								fields: [inspectionFieldV2]
							}),
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: false,text: oBundle.getText("VIN_Number")}),
								fields: [inspectionFieldV3]
							}),
                            new sap.ui.layout.form.FormElement({
								label: new sap.m.Label({required: true,text: oBundle.getText("Meter_Reading")}),
								fields: [inspectionFieldV4,inspectionMeterDB]
							})
                        ]
                        })
				]
			});


var overAllConditionDB = new sap.m.ComboBox();
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"1",text:oBundle.getText("overAllCondition1")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"2",text:oBundle.getText("overAllCondition2")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"3",text:oBundle.getText("overAllCondition3")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"4",text:oBundle.getText("overAllCondition4")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"5",text:oBundle.getText("overAllCondition5")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"6",text:oBundle.getText("overAllCondition6")}));
        overAllConditionDB.addItem(new sap.ui.core.ListItem({key:"7",text:oBundle.getText("overAllCondition7")}));
        overAllConditionDB.setSelectedKey("1");
 overAllConditionDB.addEventDelegate({
         onAfterRendering: function(e) {
              overAllConditionDB.$().find("input").attr("readonly", true);
         }});

 var safeToUseCB1 = new sap.m.CheckBox({
        width:"50px",
        text: oBundle.getText("Yes"),
        valueState: "Success",
        select: function (e) {
            safeToUseCB1.setSelected(true);
            safeToUseCB2.setSelected(false);
            //safeToUseCB3.setSelected(false);
        }
    });
var safeToUseCB2 = new sap.m.CheckBox({
        width:"50px",
        text: oBundle.getText("No"),
        valueState: "Error",
        select: function (e) {
            safeToUseCB1.setSelected(false);
            safeToUseCB2.setSelected(true);
            //safeToUseCB3.setSelected(false);
        }
    });


var maintenanceCB1 = new sap.m.CheckBox({
        width:"50px",
        text: oBundle.getText("Yes"),
        valueState: "Error",
        select: function (e) {
            maintenanceCB1.setSelected(true);
            maintenanceCB2.setSelected(false);
            VStatusElement.setVisible(true);
            maintenancePriorityElement.setVisible(true);
        }
    });

var maintenanceCB2 = new sap.m.CheckBox({
        width:"50px",
        text: oBundle.getText("No"),
        valueState: "Success",
        select: function (e) {
            maintenanceCB1.setSelected(false);
            maintenanceCB2.setSelected(true);
            VStatusElement.setVisible(false);
            maintenancePriorityElement.setVisible(false);
        }
    });

var inspectionVehicleStatusDB = 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")})
]}).addEventDelegate({onAfterRendering: function(e) {inspectionVehicleStatusDB.$().find("input").attr("readonly", true);}});

var maintenancePriorityInspectionDB = new sap.m.ComboBox();
       // maintenancePriorityInspectionDB.addItem(new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Normal")}));
        maintenancePriorityInspectionDB.addItem(new sap.ui.core.ListItem({key:"2",text:oBundle.getText("Low")}));
        maintenancePriorityInspectionDB.addItem(new sap.ui.core.ListItem({key:"3",text:oBundle.getText("Medium")}));
        maintenancePriorityInspectionDB.addItem(new sap.ui.core.ListItem({key:"4",text:oBundle.getText("High")}));
        maintenancePriorityInspectionDB.addItem(new sap.ui.core.ListItem({key:"5",text:oBundle.getText("Emergency")}));
        maintenancePriorityInspectionDB.setSelectedKey("2");
 maintenancePriorityInspectionDB.addEventDelegate({
         onAfterRendering: function(e) {
              maintenancePriorityInspectionDB.$().find("input").attr("readonly", true);
         }});

var VStatusElement = new sap.ui.layout.form.FormElement({
    label: new sap.m.Label({required: true, text: oBundle.getText("Vehicle_Status")}),
    fields: [inspectionVehicleStatusDB]
});

var maintenancePriorityElement = new sap.ui.layout.form.FormElement({
	label: new sap.m.Label({required: true,text: oBundle.getText("Maintenance_Priority")}),
	fields: [maintenancePriorityInspectionDB]
});

var inspectionSummaryNote = new sap.m.TextArea({width:"100%", height:"100px",rows : 5, wrapping : sap.ui.core.Wrapping.on
	        }).addStyleClass("field");


var inspectionMeterReadingLayout = new sap.ui.layout.HorizontalLayout({content:[]});

 var inspectionForm2 = new sap.ui.layout.form.Form({
		editable: true,
		layout: new sap.ui.layout.form.ResponsiveGridLayout(),
		formContainers: [
			new sap.ui.layout.form.FormContainer({
				formElements: [
                    new sap.ui.layout.form.FormElement({
						label: new sap.m.Label({required: true, text: oBundle.getText("Overall_Condition")}),
						fields: [overAllConditionDB]
					}),
					new sap.ui.layout.form.FormElement({
						label: new sap.m.Label({required: true, text: oBundle.getText("Vehicle_Safe_to_Use")}),
						fields: [new sap.ui.layout.HorizontalLayout({content:[safeToUseCB1,safeToUseCB2]})]
					}),
                    new sap.ui.layout.form.FormElement({
						label: new sap.m.Label({required: true,text: oBundle.getText("Maintenance_Required")}),
						fields: [new sap.ui.layout.HorizontalLayout({content:[maintenanceCB1,maintenanceCB2]})]
					}),
                    VStatusElement,maintenancePriorityElement,
                    new sap.ui.layout.form.FormElement({
						label: new sap.m.Label({text: oBundle.getText("Additional_Note")}),
						fields: [inspectionSummaryNote]
					})
                ]
            })
		]
	});


		var oTableInspectionTree = new sap.ui.table.TreeTable({
			selectionMode: sap.ui.table.SelectionMode.Single,
			//useGroupMode:true,
			visibleRowCount: 14,
			toggleOpenState: function(oEvent) {
			}
		});

        oTableInspectionTree.setSelectionMode(sap.ui.table.SelectionMode.Single);
        oTableInspectionTree.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);
      
        oTableInspectionTree.addColumn(new sap.ui.table.Column({label: oBundle.getText("Inspection_Item"), template: "name"}));
        //oTableInspectionTree.addColumn(new sap.ui.table.Column({width:"100px",label: "Data Type", template: "type"}));

        oTableInspectionTree.addColumn(new sap.ui.table.Column({
            label: new sap.ui.commons.Label({ text: oBundle.getText("Action")}),
            template: new sap.m.Button({
                type: "Emphasized",
                icon: "sap-icon://inspection",
                text: oBundle.getText("Inspection"),
                text: {
                    parts: [{ path: "source", type: new sap.ui.model.type.String()}],
                    formatter: function (source) {
                        if (source == "0") {
                            this.setVisible(false);
                        } else {
                            this.setVisible(true);
                        }
                        return oBundle.getText("Inspection");
                    }
                },
                press: function (e) {

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

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

                    if (source == "0") {
                        this.setVisible(false);
                    } else {
                        this.setVisible(true);
                    }

                    doInspection(obj);
                }
            }),
            width: "150px",
            hAlign: "Center"
        }));

        oTableInspectionTree.addColumn(new sap.ui.table.Column({
            label: new sap.ui.commons.Label({ textAlign: "Center", text: oBundle.getText("Result")}),
            template: new sap.m.GenericTag({
                status: "None",
                text: { 
                    parts: [{ path: "condition", type: new sap.ui.model.type.String() },
                            { path: "type", type: new sap.ui.model.type.String() },
                            { path: "range", type: new sap.ui.model.type.String()},
                            { path: "inspected", type: new sap.ui.model.type.String()}],
                    formatter: function (condition, data_type, range,inspected) {

                        if (inspected == "1") {
                            this.setVisible(true);
                            if (data_type == "1") {
                                if (condition == "1") {
                                    this.setStatus("Success");
                                    return oBundle.getText("Good");
                                } else if (condition == "2") {
                                    this.setStatus("Warning");
                                    return oBundle.getText("Repair");
                                } else if (condition == "3") {
                                    this.setStatus("Error");
                                    return oBundle.getText("Replace");
                                } else if (condition == "4") {
                                    this.setStatus("None");
                                    return oBundle.getText("NA");
                                }
                            } else if (data_type == "2") {
                                if (condition == "1") {
                                    this.setStatus("Success");
                                    return oBundle.getText("Yes"); 
                                } else if (condition == "2") {
                                    this.setStatus("Error");
                                    return oBundle.getText("No");
                                } else if (condition == "3") {
                                    this.setStatus("None");
                                    return oBundle.getText("NA");
                                }
                            } else if (data_type == "3") {
                                this.setStatus("None");
                                return condition;
                            } else if (data_type == "4") {
                                if (range != null) {
                                    var rangeArray = range.split("-");
                                    if (parseFloat(rangeArray[0]) <= parseFloat(condition) && parseFloat(rangeArray[1]) >= parseFloat(condition)) {
                                        this.setStatus("Success");
                                        return condition;
                                    } else {
                                        this.setStatus("Error");
                                        return condition;
                                    }
                                }
                            } else if (data_type == "5") {
                                if (condition == "1") {
                                    this.setStatus("Success");
                                    return oBundle.getText("Pass"); 
                                } else if (condition == "2") {
                                    this.setStatus("Error");
                                    return oBundle.getText("Fail");
                                }else if (condition == "3") {
                                    this.setStatus("None");
                                    return oBundle.getText("NA");
                                }
                            }  else if (data_type == "6") {
                                if (condition == "1") {
                                    this.setStatus("Success");
                                    return oBundle.getText("Ok"); 
                                } else if (condition == "2") {
                                    this.setStatus("Error");
                                    return oBundle.getText("Faulty");
                                }else if (condition == "3") {
                                    this.setStatus("None");
                                    return oBundle.getText("NA");
                                }
                            } 
                        }else {
                            this.setVisible(false);
                        }
                    }
                }
            }),
            width: "150px",
            hAlign: "Center"
        }));
        
         oTableInspectionTree.addColumn(new sap.ui.table.Column({
            label: new sap.ui.commons.Label({textAlign:"Center", text: oBundle.getText("Note")}),
            template: new sap.m.Button({
                    icon: "sap-icon://notes",
                    text: { 
                        parts: [{ path: "noteAvailable", type: new sap.ui.model.type.String()}],
                        formatter: function (noteAvailable) {
                            if (noteAvailable == "1"){
                                this.setType("Emphasized");
                            }else{
                                this.setType("Default");
                            }
                        }
                }
            }),
            width: "70px",
            hAlign: "Center"
        }));
         oTableInspectionTree.addColumn(new sap.ui.table.Column({
            label: new sap.ui.commons.Label({textAlign:"Center", text: oBundle.getText("Image")}),
            template: new sap.m.Button({
                    icon: "sap-icon://picture",
                    text: { 
                    parts: [{ path: "imageAvailable", type: new sap.ui.model.type.String()}],
                    formatter: function (imageAvailable) {
                        if (imageAvailable == "1"){
                            this.setType("Emphasized");
                        }else{
                              this.setType("Default");
                        }
                    }
                }
            }),
            width: "70px",
            hAlign: "Center"
        }));

        var breakNext = 0;
        var InspectionStepBtn1 = new sap.m.Button({
            text: oBundle.getText("Next"),
            type: sap.m.ButtonType.Emphasized,
            icon: "sap-icon://open-command-field",
            press: function (oEvent) {

                var value1 = inspectionField1.getValue();
                var value2 = inspectionField2.getValue();
                var value3 = inspectionField3.getValue();
                var value4 = inspectionField4.getValue();

                var valueV1 = inspectionFieldV1.getValue();
                var valueV2 = inspectionFieldV2.getValue();
                var valueV4 = inspectionFieldV4.getValue();

                if (value1.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Report_Number_Empty"));
                    return;
                }
                if (value2.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Location_Empty"));
                    return;
                }
                if (value3.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Inspector_Name_Empty"));
                    return;
                }
                if (value4.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Please_select_inspection_form"));
                    return;
                }
                if (valueV1.trim() == "" || valueV2.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
                    return;
                }
                if (valueV4.trim() == "") {
                    sap.m.MessageBox.error(oBundle.getText("Meter_Reading_Empty"));
                    return;
                }
                if (breakNext == 0) {
                    inspectionStep1.setValidated(true);
                    inspectionWizard.nextStep();
                }
                breakNext = 1;
            } 
        });

        var InspectionStepBtn2 = new sap.m.Button({
            text: oBundle.getText("Inspection_Completed"),
            type: sap.m.ButtonType.Emphasized,
            icon: "sap-icon://complete",
            press: function (oEvent) {

                var requiredCount = 0;
                var passCount = 0;
                var failCount = 0;
                var naCount = 0;
                var inspectedChk = 0;
                var noteImageFlag = 0;

                var noteFlag = sessionStorage.getItem('oxmaint_note_flag');
                var imageFlag = sessionStorage.getItem('oxmaint_image_flag');

                if (inspectionListJSONArray.length !== 0) {
                    inspectionListJSONArray.forEach(function (obj, i) {
                        var count = Object.keys(obj).length - 3;
                        for (var j = 0; j < count; j++) {

                            if (obj["" + j].required == "1" && obj["" + j].inspected == "0" && requiredCount == 0) {
                                requiredCount = requiredCount + 1;
                                sap.m.MessageBox.error(obj["" + j].name + " " + oBundle.getText("is_not_inspected_it_is_required"));
                                break;
                            }

                            if (obj["" + j].inspected === "1") {
                                inspectedChk = inspectedChk + 1;
                                if (obj["" + j].type === "1" || obj["" + j].type === "2") {
                                   
                                    
                                    if (obj["" + j].condition === "1") {
                                        passCount = passCount + 1;
                                    } else if (obj["" + j].condition === "4" || (obj["" + j].type == '2' && obj["" + j].condition == '3')) {
                                        naCount = naCount + 1;
                                    } else {
                                        failCount = failCount + 1;


                                        if (noteFlag == "1" && obj["" + j].note == "") {
                                            noteImageFlag = noteImageFlag + 1;
                                            sap.m.MessageBox.error(oBundle.getText("Note_required_for_fault") + " " + obj["" + j].name);
                                            break;
                                        }
                                        if (imageFlag == "1" && obj["" + j].image == "") {
                                            noteImageFlag = noteImageFlag + 1;
                                            sap.m.MessageBox.error(oBundle.getText("Image_required_for_fault") + " " + obj["" + j].name);
                                            break;
                                        }


                                    }
                                } else if (obj["" + j].type === "4") {
                                    if (obj["" + j].range != null) {
                                        var rangeArray = obj["" + j].range.split("-");
                                        if (parseFloat(rangeArray[0]) <= parseFloat(obj["" + j].condition) && parseFloat(rangeArray[1]) >= parseFloat(obj["" + j].condition)) {
                                        } else {
                                            failCount = failCount + 1;
                                        }
                                    }
                                }else if (obj["" + j].type === "5" || obj["" + j].type === "6") {
                                    if (obj["" + j].condition === "1") {
                                        passCount = passCount + 1;
                                    } else if (obj["" + j].condition == '3') {
                                        naCount = naCount + 1;
                                    } else {
                                        failCount = failCount + 1;


                                        if (noteFlag == "1" && obj["" + j].note == "") {
                                            noteImageFlag = noteImageFlag + 1;
                                            sap.m.MessageBox.error(oBundle.getText("Note_required_for_fault") + " " + obj["" + j].name);
                                            break;
                                        }
                                        if (imageFlag == "1" && obj["" + j].image == "") {
                                            noteImageFlag = noteImageFlag + 1;
                                            sap.m.MessageBox.error(oBundle.getText("Image_required_for_fault") + " " + obj["" + j].name);
                                            break;
                                        }


                                    }
                                }

                            }
                        }
                    });
                } else {
                    sap.m.MessageBox.error(oBundle.getText("There_is_no_inspection_item_in_form"));
                    return;
                }

                if (inspectedChk == 0) {
                    sap.m.MessageBox.error(oBundle.getText("Please_do_at_least_one_inspection"));
                    return;
                }

                if (requiredCount > 0) {
                    return;
                }
                if (noteImageFlag > 0) {
                    return;
                }

                if (failCount > 0) {

                    overAllConditionDB.setSelectedKey("3");
                    safeToUseCB2.setSelected(true);
                    maintenanceCB1.setSelected(true);
                    inspectionVehicleStatusDB.setSelectedKey("3");

                    VStatusElement.setVisible(true);
                    maintenancePriorityElement.setVisible(true);

                } else {
                    overAllConditionDB.setSelectedKey("1");
                    inspectionVehicleStatusDB.setSelectedKey("1");
                    safeToUseCB1.setSelected(true);
                    maintenanceCB2.setSelected(true);

                    VStatusElement.setVisible(false);
                    maintenancePriorityElement.setVisible(false);
                }

                inspectionStep2.setValidated(true);
                inspectionWizard.nextStep();
            }
        });

        var InspectionStepBtn3 = new sap.m.Button({
                text: oBundle.getText("Generate_Report"),
                type: sap.m.ButtonType.Emphasized,
                icon: "sap-icon://inspection",
                press: function (oEvent) {
                    generateInspectionReport();
                } 
            });

var oBusyDialogInspection = new sap.m.BusyDialog({ text: oBundle.getText("Inspection_Generating")});

function generateInspectionReport(){
    
    var inspectionID = new Date().getTime() + "";

    var value1 = inspectionField1.getValue();
    var value2 = inspectionField2.getValue();
    var value3 = inspectionField3.getValue();
    var value4 = inspectionField4.getValue();

    var valueV1 = inspectionFieldV1.getValue();
    var valueV2 = inspectionFieldV2.getValue();
    var valueV3 = inspectionFieldV3.getValue();
    var valueV4 = inspectionFieldV4.getValue();
  
    if (value1.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Report_Number_Empty"));
        return;
    }
    if (value2.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Location_Empty"));
        return;
    }
    if (value3.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Inspector_Name_Empty"));
        return;
    }
    if (value4.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Please_select_inspection_form"));
        return;
    }
    if (valueV1.trim() == "" || valueV2.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Please_select_vehicle"));
        return;
    }
    if (valueV4.trim() == "") {
        sap.m.MessageBox.error(oBundle.getText("Meter_Reading_Empty"));
        return;
    }
            
    var overAllCondition = overAllConditionDB.getValue();
    var safeToUse = "1";
    if(safeToUseCB1.getSelected()){
        safeToUse = "1";
    }
    if(safeToUseCB2.getSelected()){
        safeToUse = "2";
    }
    

    var inMaintenence = "1";
    if(maintenanceCB1.getSelected()){
        inMaintenence = "1";
    }
    if(maintenanceCB2.getSelected()){
        inMaintenence = "2";
    }

    var mainteNancePriority = maintenancePriorityInspectionDB.getValue();
    var vehicleStatus =  inspectionVehicleStatusDB.getValue();
    var vehicleStatusKey =  inspectionVehicleStatusDB.getSelectedKey();
    var summaryNote = inspectionSummaryNote.getValue();

    var getVehicle = vehicleJSONArray.filter(function (obj, index) {
        return (obj.vehicle_serial === valueV1);
    });

    var created_date = getIndonesianTime();
    
    // if (maintenanceCB1.getSelected()) {

    //     HVI_VehiclesInv.update({ id: getVehicle[0]['id'], status: vehicleStatusKey, odometer:valueV4
    //     }).done(function () { funGetVehicle(); });

    //     HVI_VehiclesHistory.insert({ master_email: emailUser, vehicle_number: getVehicle[0]['vehicle_serial'], 
    //         vehicle_name: getVehicle[0]['vehicle_name'], odometer: getVehicle[0]['odometer'],
    //         odometer_unit: getVehicle[0]['odometer_unit'], status: "1", type: "2", source: "3", 
    //         created_date: created_date, created_by: operatedBy
    //     }).done(function () {});

    //     HVI_VehiclesHistory.insert({ master_email: emailUser, vehicle_number: getVehicle[0]['vehicle_serial'], 
    //         vehicle_name: getVehicle[0]['vehicle_name'], odometer: valueV4,
    //         odometer_unit: getVehicle[0]['odometer_unit'], status: "1", type: "1", source: "3", 
    //         created_date: created_date, created_by: operatedBy
    //     }).done(function () {});

    // }else{

    //     HVI_VehiclesInv.update({ id: getVehicle[0]['id'], odometer:valueV4 }).done(function () { funGetVehicle(); });

    //     HVI_VehiclesHistory.insert({ master_email: emailUser, vehicle_number: getVehicle[0]['vehicle_serial'], 
    //         vehicle_name: getVehicle[0]['vehicle_name'], odometer: valueV4,
    //         odometer_unit: getVehicle[0]['odometer_unit'], status: getVehicle[0]['status'], type: "1", source: "3", 
    //         created_date: created_date, created_by: operatedBy
    //     }).done(function () {});
    // }
                

    var checklistGroup = "";
    var checklistName = "";
    var checklistStatus = "";
    var checklistNote = "";
    var checklistUrl = "";
    var checklistType = "";
    var checklistRange = "";

    var faultRepair = "";
    var faultReplace = "";

    if (inspectionListJSONArray.length !== 0) {
        inspectionListJSONArray.forEach(function (obj, i) {
            var count = Object.keys(obj).length - 3;
            for (var j = 0; j < count; j++) {

                if (obj["" + j].inspected == "1") {

                    checklistGroup = checklistGroup + obj["" + j].sub_group_name + "^";
                    checklistName = checklistName + obj["" + j].name + "^";
                    checklistStatus = checklistStatus + obj["" + j].condition + "^";

                    checklistNote = checklistNote + obj["" + j].note + "^";
                    checklistUrl = checklistUrl + obj["" + j].image + "^";
                    checklistType = checklistType + obj["" + j].type + "^";
                    checklistRange = checklistRange + obj["" + j].range + "^";

                    if (obj["" + j].type === "1") {
                        if (obj["" + j].condition === "2") {
                            faultRepair = faultRepair + "^" + obj["" + j].name;
                            insertInspectionFault(valueV1, valueV2, inspectionID, value1, obj[""+j].name, oBundle.getText("Repair"), obj[""+j].note);
                        } else if (obj["" + j].condition === "3") {
                            faultReplace = faultReplace + "^" + obj["" + j].name;
                            insertInspectionFault(valueV1, valueV2, inspectionID, value1, obj[""+j].name, oBundle.getText("Replace"), obj[""+j].note);
                        }
                    } else if (obj["" + j].type === "2") {
                        if (obj["" + j].condition === "2") {
                            faultRepair = faultRepair + "^" + obj["" + j].name;
                            insertInspectionFault(valueV1, valueV2, inspectionID, value1, obj[""+j].name, oBundle.getText("Repair"), obj[""+j].note);
                        }
                    } else if (obj["" + j].type === "4") {
                        if (obj["" + j].range != null) {
                            var rangeArray = obj["" + j].range.split("-");
                            if (parseFloat(rangeArray[0]) <= parseFloat(obj["" + j].condition) && parseFloat(rangeArray[1]) >= parseFloat(obj["" + j].condition)) {
                            } else {
                                faultRepair = faultRepair + "^" + obj["" + j].name;
                                insertInspectionFault(valueV1, valueV2, inspectionID, value1, obj[""+j].name, oBundle.getText("Repair"), obj[""+j].note);
                            }
                        }
                    } else { // for 5 and 6 
                        if (obj["" + j].condition === "2") {
                            faultRepair = faultRepair + "^" + obj["" + j].name;
                            insertInspectionFault(valueV1, valueV2, inspectionID, value1, obj[""+j].name, oBundle.getText("Repair"), obj[""+j].note);
                        }
                    }
                }
            }
        });
    }

    checklistGroup = checklistGroup.slice(0, -1);
    checklistName = checklistName.slice(0, -1);
    checklistStatus = checklistStatus.slice(0, -1);
    checklistNote = checklistNote.slice(0, -1);
    checklistUrl = checklistUrl.slice(0, -1);
    checklistType = checklistType.slice(0, -1);
    checklistRange = checklistRange.slice(0, -1);

var meterReadingInspection = valueV4+" "+inspectionMeterDB.getValue();

var current_date = getIndonesianTime();
 
var tsLong = new Date().getTime();
var reportno = value1.replace(/[^.,a-zA-Z0-9]/g,"");
var	blob_name  = reportno+"_"+tsLong+"";           
var userFolder = emailUser.replace(/[@.]/g,"");
var inspectionPdfURL = "https://oxmaint.com/pdf/inspection/"+userFolder+"/"+blob_name+".pdf";

 oBusyDialogInspection.open();


 if (faultRepair!="" || faultReplace !="") {

        for (var i = 0; i < notificationEmailArray.length; i++) {
            if (notificationEmailArray[i].inspection_fault_email == "1") {
                sendMailInspection(notificationEmailArray[i].notification_email,value1,faultRepair,faultReplace,summaryNote,inspectionPdfURL,
                valueV1,valueV2,getVehicle[0]['vehicle_categoty']);
            }
        }
    }

 var item = {master_email:emailUser, id:inspectionID, report_no: value1, location: value2, inspection_date: current_date,inspector: value3,
             license_number: valueV1, chassis_number: valueV2, engine_number: valueV3, 
             vehicle_status: vehicleStatus,maintenance_required: inMaintenence, maintenance_priority: mainteNancePriority,  
             meter_reading: meterReadingInspection,overall_condition: overAllCondition, safe_to_use: safeToUse, remark: summaryNote,
             repair: faultRepair, replace: faultReplace, uploaded: "1",
             pdf_file_path: "",custom1: inspectionPdfURL,custom2: blob_name,app_version: "Web11.0",archive:"0", form_name:value4
         }

         Car_Inspection.insert(item).done(function () {
            
             funGetInspection();
             getFaultList();
             if(oxmaint_demo_data != "1"){
                updateLoginData();
            }
         }, failure);


    var insp_url = "https://oxmaint.com/pdf/pdf2_en/inspection_portal_new.php";
    if(languageCode == 'PT' || languageCode == 'pt'){
        insp_url = "https://oxmaint.com/pdf/pdf2_pt/inspection_portal_new.php";
    }else if(languageCode == 'ES' || languageCode == 'es'){
        insp_url = "https://oxmaint.com/pdf/pdf2_es/inspection_portal_new.php";
    }else if(languageCode == 'JA' || languageCode == 'ja'){
        insp_url = "https://oxmaint.com/pdf/pdf2_ja/inspection_portal.php";
    }else{
        insp_url = "https://oxmaint.com/pdf/pdf2_en/inspection_portal_new.php";
    }

    $.ajax({
        type: "POST",
        url: insp_url,
        data: {
            "email": emailUser,
            "logoUrl": sessionStorage.getItem('oxmaint_logo'),

            "report": value1,
            "location": value2,
            "date": current_date,
            "inspector": value3,

            "cetegory": getVehicle[0]['vehicle_categoty'],
            "number": valueV1,
            "name": valueV2,
            "vin": valueV3,
            "meter": valueV4 + " " + inspectionMeterDB.getValue(),
            "model": getVehicle[0]['vehicle_model'],
            "operator": getVehicle[0]['vehicle_operator'],

            "condition": overAllCondition,
            "safe": safeToUse,
            "maintenance": inMaintenence,
            "status": vehicleStatus,
            "priority": mainteNancePriority,
            "remark": summaryNote,
            "blob": blob_name + ".pdf",

            "group_name": value4, //Group Name

            "checklistGroup": checklistGroup,
            "checklistName": checklistName,
            "checklistStatus": checklistStatus,
            "checklistNote": checklistNote,
            "checklistUrl": checklistUrl,

            "checklistType": checklistType,
            "checklistRange": checklistRange,

            "signature": operatedBy,

            "customFeildFlag1": "0",
            "customFeildFlag2": "0",
            "customFeildFlag3": "0",
            "customFeildFlag4": "0",
            "customFeildFlag5": "0",

            "customFeildName1": "",
            "customFeildName2": "",
            "customFeildName3": "",
            "customFeildName4": "",
            "customFeildName5": "",

            "customFeildValue1": "",
            "customFeildValue2": "",
            "customFeildValue3": "",
            "customFeildValue4": "",
            "customFeildValue5": "",

            "inspection_sign_flag1": "0",
            "inspection_sign_flag2": "0",

            "inspection_sign1": "",
            "inspection_sign2": "",

            "inspection_sign_id1": "",
            "inspection_sign_id1": "",

            "inspectorSignatureLabel": "Inspector",
            "subscription":oxmaint_subscription

        },
        success: function (data) {

            oBusyDialogInspection.close();
            sap.m.MessageBox.success(oBundle.getText("Report_Generated"));

            clearInspectioField();
            breakNext = 0;

        }
    });


    HVI_Index.where({ id: emailUser }).read().done(function (results) {

        HVI_Index.update({ id: emailUser, inspection: (Number(results[0]['inspection']) + 1) }).done(function () { });
    });
}

function insertInspectionFault(vehicle_number, vehicle_name, inspection_id, inspection_number, task_name, task_type, inspection_note) {

    // var reported_date = getIndonesianTime();
    // var reported_by = operatedBy;

    // var added_date = getIndonesianTime();
    // var added_by = operatedBy;

    // Car_Workorder_Task.insert({
    //     master_email:emailUser,
    //     license_number: vehicle_number, source: "1",
    //     task_name: task_name, task_type: task_type, task_status: "0", added_flag: "1",
    //     inspection_id: inspection_id, inspection_number: inspection_number, inspection_note: inspection_note,
    //     reported_date: reported_date, reported_by: reported_by,
    //     added_date:added_date,added_by:added_by
    // }).done(function () {

    // });
}

function sendMailInspection(notifyEmail,reportNo,faultRepair,faultReplace,summaryNote,inspectionPdfURL,vehicleNo,vehicleName,category){
   
    var defectiveItem = faultRepair.replace(/\^/g, ", ") + faultReplace.replace(/\^/g, ", ");


     $.ajax({
         type: "POST",
         url: "https://oxmaint.com/notification/defect_alert.php",
         data: {
             "email": notifyEmail,
             "report": reportNo,
             "vehicle": vehicleNo,
             "item": defectiveItem,
             "note": summaryNote,
             "pdf_url": inspectionPdfURL,
             "category": category,
             "name": vehicleName 
         },
         success: function (data) {
          
         }
     });
}
           
var inspectionStep1 = new sap.m.WizardStep({
				validated : true,
				title : oBundle.getText("Inspection_Info"),
				icon: "sap-icon://message-information",
				content: [

					//wizard.validateStep(step1);
								
					//wizard.invalidateStep(step1);
					//oStep.setValidated(bSelected);				
                    //wizard.discardProgress(oStep);
                    inspectionForm1,InspectionStepBtn1
					
				]
			});
var inspectionStep2 = new sap.m.WizardStep({
				validated : true,
				title : oBundle.getText("Do_Inspection"),
				icon: "sap-icon://inspection",
				content: [oTableInspectionTree,InspectionStepBtn2]
			});
var inspectionStep3 = new sap.m.WizardStep({
				validated : true,
				title : oBundle.getText("Inspection_Summary"),
				icon: "sap-icon://order-status",
				content: [inspectionForm2,InspectionStepBtn3]
			});

var inspectionWizard = new sap.m.Wizard({
				width:"100%",
				showNextButton: false,
				complete : function() {},
				steps: [inspectionStep1, inspectionStep2, inspectionStep3]
			});
			
 var createInspectionPage = new sap.m.Page("create_inspection", {
        showNavButton: true,
        headerContent:[],
        navButtonPress: function(){ oAppInspection.backToTop(); },
        content : [inspectionWizard]
    }).addEventDelegate({});

    

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

    oAppInspection.addPage(inspection_history_page).addPage(createInspectionPage).addPage(inspectionArchivePage);


var inspectionImageUploadedURL = "0";

function doInspection(obj){

    inspectionImageUploadedURL = "0";

    var mid = obj['id'];
    var checklist_name = obj['name'];
    var sub_group_id = obj['sub_group'];
    var type = obj['type'];
    var required =  obj['required'];
    var instruction =  obj['instruction'];
    var range =  obj['range'];

    var condition =  obj['condition'];
    var note =  obj['note'];
    var image =  obj['image'];

    var typeValue1 = "";
    var typeValue2 = "";

    var conditionCB1 = new sap.m.CheckBox({
            text:  oBundle.getText("Good"),
            width:"70px",
            valueState: "Success",
            select: function (e) {
                typeValue1 = "1";
                conditionCB1.setSelected(true);
                conditionCB2.setSelected(false);
                conditionCB3.setSelected(false);
                conditionCB4.setSelected(false);
            }
        });   
    var conditionCB2 = new sap.m.CheckBox({
            text:  oBundle.getText("Repair"),
            width:"70px",
            valueState: "Warning",
            select: function (e) {
                typeValue1 = "2";
                conditionCB1.setSelected(false);
                conditionCB2.setSelected(true);
                conditionCB3.setSelected(false);
                conditionCB4.setSelected(false);
            }
        }); 
    var conditionCB3 = new sap.m.CheckBox({
            text:  oBundle.getText("Replace"),
            width:"70px",
            valueState: "Error",
            select: function (e) {
                typeValue1 = "3";
                conditionCB1.setSelected(false);
                conditionCB2.setSelected(false);
                conditionCB3.setSelected(true);
                conditionCB4.setSelected(false);
            }
        });
    var conditionCB4 = new sap.m.CheckBox({
            text:  oBundle.getText("NA"),
            select: function (e) {
                typeValue1 = "4";
                conditionCB1.setSelected(false);
                conditionCB2.setSelected(false);
                conditionCB3.setSelected(false);
                conditionCB4.setSelected(true);
            }
        });

    var yesCB = new sap.m.CheckBox({
            text:  oBundle.getText("Yes"),
            width:"50px",
            valueState: "Success",
            select: function (e) {
                typeValue2 = "1";
                yesCB.setSelected(true);
                noCB.setSelected(false);
                naCB.setSelected(false);
            }
        });  
    var noCB = new sap.m.CheckBox({
            text:  oBundle.getText("No"),
            width:"50px",
            valueState: "Error",
            select: function (e) {
                typeValue2 = "2";
                yesCB.setSelected(false);
                noCB.setSelected(true);
                naCB.setSelected(false);
            }
        });
    var naCB = new sap.m.CheckBox({
        text:  oBundle.getText("NA"),
        width:"50px",
        select: function (e) {
                typeValue2 = "3";
                yesCB.setSelected(false);
                noCB.setSelected(false);
                naCB.setSelected(true);
            }
        });
var textField = new sap.m.Input({placeholder:"ABC123"});
var numberField = new sap.m.Input({type:"Number",placeholder:"123456"});

  var conditionElement1 = new sap.ui.layout.form.FormElement({
		label: new sap.m.Label({required: true, text:  oBundle.getText("Condition")}),
		fields: [new sap.ui.layout.HorizontalLayout({content:[conditionCB1,conditionCB2,conditionCB3,conditionCB4]})]
	});
  var conditionElement2 = new sap.ui.layout.form.FormElement({
		label: new sap.m.Label({required: true, text:  oBundle.getText("Condition")}),
		fields: [new sap.ui.layout.HorizontalLayout({content:[yesCB,noCB,naCB]})]
	});
  var conditionElement3 = new sap.ui.layout.form.FormElement({
		label: new sap.m.Label({text:  oBundle.getText("Readings")}),
		fields: [textField]
	});
  var conditionElement4 = new sap.ui.layout.form.FormElement({
	    label: new sap.m.Label({ text:  oBundle.getText("Readings")}),
	    fields: [numberField]
	});

	if (type == "1") {
	    typeValue1 = condition;
	    if (condition == "1") {
	        conditionCB1.setSelected(true);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(false);
	    }else if (condition == "2") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(true);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(false);
	    }else if (condition == "3") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(true);
	        conditionCB4.setSelected(false);
	    }else if (condition == "4") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(true);
	    }

	    conditionElement1.setVisible(true);
	    conditionElement2.setVisible(false);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(false);
	} else if (type == "2") { 
        typeValue2 = condition;
        if (condition == "1") { 
            yesCB.setSelected(true);
            noCB.setSelected(false);
            naCB.setSelected(false);
        }else if (condition == "2"){
            yesCB.setSelected(false);
            noCB.setSelected(true);
            naCB.setSelected(false);
        }else if (condition == "3"){
            yesCB.setSelected(false);
            noCB.setSelected(false);
            naCB.setSelected(true);
        }
        conditionElement1.setVisible(false);
	    conditionElement2.setVisible(true);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(false);
    }else if (type == "3") {
        textField.setValue(condition);
        conditionElement1.setVisible(false);
	    conditionElement2.setVisible(false);
	    conditionElement3.setVisible(true);
	    conditionElement4.setVisible(false);
    }else if (type == "4") {
        numberField.setValue(condition);
        conditionElement1.setVisible(false);
	    conditionElement2.setVisible(false);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(true);
    }else if (type == "5") { 
        yesCB.setText(oBundle.getText("Pass"));
        noCB.setText(oBundle.getText("Fail"));
        typeValue2 = condition;
        if (condition == "1") { 
            yesCB.setSelected(true);
            noCB.setSelected(false);
            naCB.setSelected(false);
        }else if (condition == "2"){
            yesCB.setSelected(false);
            noCB.setSelected(true);
            naCB.setSelected(false);
        }else if (condition == "3"){
            yesCB.setSelected(false);
            noCB.setSelected(false);
            naCB.setSelected(true);
        }
        conditionElement1.setVisible(false);
	    conditionElement2.setVisible(true);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(false);
    }else if (type == "6") { 
        yesCB.setText(oBundle.getText("OK"));
        noCB.setText(oBundle.getText("Faulty"));
        typeValue2 = condition;
        if (condition == "1") { 
            yesCB.setSelected(true);
            noCB.setSelected(false);
            naCB.setSelected(false);
        }else if (condition == "2"){
            yesCB.setSelected(false);
            noCB.setSelected(true);
            naCB.setSelected(false);
        }else if (condition == "3"){
            yesCB.setSelected(false);
            noCB.setSelected(false);
            naCB.setSelected(true);
        }

        conditionElement1.setVisible(false);
	    conditionElement2.setVisible(true);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(false);
    }else {
        typeValue1 = condition;
        if (condition == "1") {
	        conditionCB1.setSelected(true);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(false);
	    }else if (condition == "2") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(true);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(false);
	    }else if (condition == "3") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(true);
	        conditionCB4.setSelected(false);
	    }else if (condition == "4") {
	        conditionCB1.setSelected(false);
	        conditionCB2.setSelected(false);
	        conditionCB3.setSelected(false);
	        conditionCB4.setSelected(true);
	    }
        conditionElement1.setVisible(true);
	    conditionElement2.setVisible(false);
	    conditionElement3.setVisible(false);
	    conditionElement4.setVisible(false);
    }

 var inspectionNote = new sap.m.TextArea({width:"100%", value:note,height:"60px",rows : 3, wrapping : sap.ui.core.Wrapping.on
	        }).addStyleClass("field");

var oImageInspection = new sap.m.Image({width:"200px",height:"100px"});

if(image!=""){
    oImageInspection.setSrc(image);
    inspectionImageUploadedURL = image;
    
}

 var inspectionImageUplaod = new sap.m.Button({
     text: oBundle.getText("Upload"),
     type: sap.m.ButtonType.Accept,
     width: "100%",
     icon: "sap-icon://upload",
     press: function () {
         uploadImageInspection(oImageInspection);
     }
 });

   
 var doInspectionForm = new sap.ui.layout.form.Form({
        editable: true,
        title:checklist_name,
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    conditionElement1,
                    conditionElement2,
                    conditionElement3,
                    conditionElement4,
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text: oBundle.getText("Inspection_Note")}),
                        fields: [inspectionNote]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: new sap.m.Label({ text:  oBundle.getText("Upload_image")}),
                        fields: [oImageInspection,inspectionImageUplaod]
                    }),
                    ]
                }),
        ]
    });

 var oDialogInspection = new sap.m.Dialog({
        modal: true,
        title:  oBundle.getText("Inspection_Item"),
        state: sap.ui.core.ValueState.Success,
        content: [doInspectionForm],
        buttons: [
            new sap.m.Button({
                text: oBundle.getText("Done"),
                icon: "sap-icon://accept",
                press: function () {

                    var textValue = textField.getValue();
                    var numberValue = numberField.getValue();
                    var condition = "";

                    if (type == "1") {
                        condition = typeValue1;
                        if (condition.trim() == "") {
                            sap.m.MessageBox.error( oBundle.getText("Please_select_condition"));
                            return;
                        }
                    } else if (type == "2") {
                        condition = typeValue2;
                        if (condition.trim() == "") {
                            sap.m.MessageBox.error( oBundle.getText("Please_select_condition"));
                            return;
                        }
                    } else if (type == "3") {
                        condition = textValue;
                        if (condition.trim() == "") {
                            sap.m.MessageBox.error( oBundle.getText("Please_provide_input"));
                            return;
                        }
                    } else if (type == "4") {
                        condition = numberValue;
                        if (condition.trim() == "") {
                            sap.m.MessageBox.error( oBundle.getText("Please_provide_readings"));
                            return;
                        }
                    } else {
                        condition = typeValue2;
                        if (condition.trim() == "") {
                            sap.m.MessageBox.error( oBundle.getText("Please_select_condition"));
                            return;
                        }
                    }

                    var imgUploadURL = "";
                    var imageAvailable = "0";
                    if (inspectionImageUploadedURL == "0") {
                        imgUploadURL = "";
                        imageAvailable = "0";
                    } else {
                        imgUploadURL = inspectionImageUploadedURL;
                        imageAvailable = "1";
                    }

                    var noteAvailable = "0";
                    if(inspectionNote.getValue().trim()!=""){
                        noteAvailable = "1";
                    }
                    
                    var updatedJson = {
                        "id": mid,
                        "condition": condition,
                        "note": inspectionNote.getValue(),
                        "image": imgUploadURL,
                        "inspected": "1",
                        "noteAvailable": noteAvailable,
                        "imageAvailable": imageAvailable
                    };

                    updateInspectionJSON(inspectionListJSONArray, updatedJson);

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

                    oTableInspectionTree.setModel(oModelInspection);
                    oTableInspectionTree.bindRows({
                        path: "/modelData",
                        parameters: {
                            numberOfExpandedLevels: 1
                        }
                    });

                    oTableInspectionTree.setGroupHeaderProperty("name");
                    oDialogInspection.close();

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

function updateInspectionJSON(jsonArray, updatedJson) {

  if (jsonArray.length !== 0) {
    jsonArray.forEach(function(obj,i) {
      var count = Object.keys(obj).length-3;
      for(var j=0;j<count;j++){
        if (obj[""+j].id === updatedJson.id) {
          obj[""+j].condition = updatedJson.condition;
          obj[""+j].note = updatedJson.note;
          obj[""+j].image = updatedJson.image;
          obj[""+j].inspected = updatedJson.inspected;
          obj[""+j].imageAvailable = updatedJson.imageAvailable;
          obj[""+j].noteAvailable = updatedJson.noteAvailable;
        } 
      }
    });
  }
};

function funGetInspectionForm(groupID) {

    busyDialog.open();

    Grab_Checklist2.where({group_id: groupID }).includeTotalCount().take(1000).read().done(function (results) {
        getInspectionFormTree(results,groupID);

    });

  }

var inspectionListJSONArray = [];

function getInspectionFormTree(sub_group,groupID) {

    inspectionListJSONArray = [];

    Grab_Checklist3.where({ group_id: groupID }).skip(skipValueHviChecklist3).
        take(1000).orderByDescending("sort_order").read().done(function (results) {
            results.reverse();
            var sub_group_array_Check = [];
            var sub_group_array = [];
            var checklist_array = {};

            for (var i = 0; i < results.length; i++) {

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

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

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

                    sub_group_array_Check.push(sub_group_name);
                    sub_group_array.push({ id: subgroup_id, name: sub_group_name, source: "0" });
                    checklist_array[sub_group_name] = [];
                }
                checklist_array[sub_group_name].push({ id: checklist_id, name: checklist, type: data_type,
                    range: range, instruction: instruction, required: required, source: "1", sub_group: subgroup_id,
                    condition: "", note: "", image: "",inspected: "0",imageAvailable:"0",noteAvailable:"0",
                    sub_group_name:sub_group_name
                });
            }
            
            sub_group_array.sort(function (a, b) {
                a = a.name.toLowerCase();
                b = b.name.toLowerCase();
                return a < b ? -1 : a > b ? 1 : 0;
            });

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

            inspectionListJSONArray = oInspectionData;

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

            oTableInspectionTree.setModel(oModel);
            oTableInspectionTree.bindRows({
                path: "/modelData",
                parameters: {
                    numberOfExpandedLevels: 1
                }
            });

            oTableInspectionTree.setGroupHeaderProperty("name");
            //oTableInspectionTree.expand(0);

            busyDialog.close();
        });
  }


function uploadImageInspection(oImageInspection){

        standartBusyDialog.setText("");

        var blob_name = new Date().getTime();
        var userFolder = emailUser.replace(/[@.]/g,"");
        var imgURL = "https://oxmaint.com/pdf/inspectionImage/"+userFolder+"/"+blob_name;

        var oFileUploader = new sap.ui.unified.FileUploader({
            name: "pdf",
            uploadUrl: "https://oxmaint.com/pdf/image.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: blob_name }),
                    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) { },
            change: function (oEvent) {

                var value = this.getValue();
                if(value.indexOf(".jpeg")>-1){
                    imgURL = imgURL + ".jpeg";
                }else if(value.indexOf(".JPG")>-1){
                    imgURL = imgURL + ".JPG";
                }else if(value.indexOf(".JPEG")>-1){
                    imgURL = imgURL + ".JPEG";
                }else if(value.indexOf(".png")>-1){
                    imgURL = imgURL + ".png";
                }else if(value.indexOf(".PNG")>-1){
                    imgURL = imgURL + ".PNG";
                }else if(value.indexOf(".jpg")>-1){
                    imgURL = imgURL + ".jpg";;
                }
                var localFile = oEvent.getParameter("files")[0];
                var localURL = window.URL || window.webkitURL;
                oImageInspection.setSrc(localURL.createObjectURL(localFile));

                inspectionImageUploadedURL = imgURL;
            },
            uploadComplete: function (oEvent) {
                oDialog.close();
                standartBusyDialog.close();
            }
        });


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

function clearInspectioField(){
    
    inspectionField1.setValue("");
    inspectionField2.setValue("");
    inspectionField3.setValue("");
    inspectionField4.setValue("");

    inspectionFieldV1.setValue("");
    inspectionFieldV2.setValue("");
    inspectionFieldV3.setValue("");
    inspectionFieldV4.setValue("");

    inspectionMeterDB.setValue(oBundle.getText("KM"));

    overAllConditionDB.setValue(oBundle.getText("Excellent_Condition"));

    safeToUseCB1.setSelected(false);
    safeToUseCB2.setSelected(false);
    //safeToUseCB3.setSelected(false);
    
    maintenanceCB1.setSelected(false);
    maintenanceCB2.setSelected(false);

    maintenancePriorityInspectionDB.setValue(oBundle.getText("Low"));
    inspectionVehicleStatusDB.setValue( oBundle.getText("Maintenance_Required"));
    inspectionSummaryNote.setValue("");


     inspectionListJSONArray = [];

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

        oTableInspectionTree.setModel(oModelTree);
        oTableInspectionTree.bindRows({
            path: "/modelData"
        });

    inspectionStep1.setValidated(false);
    inspectionStep2.setValidated(false);
    inspectionStep3.setValidated(false);

    inspectionWizard.previousStep();
    inspectionWizard.previousStep();
    oAppInspection.backToTop();
                
}