var testMe8 = null;
var triggerBarcodeExistenceCheck = false;


function ConsumptionOnJob() {
    //Scanner variables
    var uo = null;
    var testSwitch = true;
    var moveToInfoPageRequested = false;
    var navigationAlreadyRequested = false;
    var incomingBarcode = null;
    //***************************************



    var self = {};
    self.currentJob = null;
    self.currentJobType = null;
    self.selectedSparepartNo = '';
    self.selectedSparepartId = '';
    self.selectedSparepartName = '';
    self.AvailableStockList = '';
    self.selectedStockId = null;
    self.selectedMachineId = null;
    self.selectedStockPredefined = false;
    self.predefinedConsumptionId = '-1';
    self.predefinedPlannedConsumption = '0';
    self.predefinedRealConsumption = '0';

    self.init = function () {
        c3('5');
        //initScanner(this);
        self.requestJobInfo();
    };

    self.requestJobInfo = function () {
        var requestingUser = $.cookie("username");


        var currentJobId = $.cookie("currently_selected_jobid");
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: { "userinitials": requestingUser, "job_id": currentJobId, "session_token": current_session_token },
            success: self.JobCardInfoRequestSuccess,
            error: self.JobCardInfoRequestError,
            url: "RequestExtendedJobInformation"
        });

        requester.ExecuteRequest();
    };

    self.JobCardInfoRequestSuccess = function (data, status, xhr) {

        if (data.d.SessionTokenValid == false) {
            //$.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });

            $("#consumption_on_job_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#consumption_on_job_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#consumption_on_job_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e5('consumptiononjob row 453');
            });

            $("#consumption_on_job_generic_popup_button").unbind("click").click(function () {
                $("#consumption_on_job_generic_popup").popup("close");
            });

            $("#consumption_on_job_generic_popup").popup().popup("open");
        }
        else {

            if (data.d.JobType == "Activity") {
                self.currentJob = data.d.ActivityInfo;
                self.updateJobInformationForActivity();
            }
            else if (data.d.JobType == "Fault") {
                self.currentJob = data.d.FaultInfo;
                self.updateJobInformationForFault();
            }
            self.currentJobType = data.d.JobType;
        }

    };

    self.JobCardInfoRequestError = function (request, status, error) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>
        c1('consumptiononjob row 485: Unable to retrieve fault information from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

  


    self.checkForSparepartExistence = function () {
        var consumption_on_job_search_param = '';
        var verificationService = '';
        self.clearErrorMsg();

        if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
            consumption_on_job_search_param = $("#consumption_on_job_sparepart_search_value").val();
            verificationService = 'CheckForSparepartPresence';
        }
        else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
            //MABE 20190921 - original code
            //consumption_on_job_search_param = consumeOnJobBarcodeHandler.lastResult;
            //verificationService = 'CheckForSparepartPresenceOnBarcode';
            c8('Consumptiononjob row 497 testMe8: ' + testMe8);
            consumption_on_job_search_param = testMe8;
            c8('Consumptiononjob row 498 consumption_on_job_search_param: ' + consumption_on_job_search_param);

            verificationService = 'CheckForSparepartPresenceOnBarcode';
            triggerBarcodeExistenceCheck = false;

        }

        var consumption_on_job_sp_group_param = ""; //for time being, this one is always a dummy
        var current_session_token = $.cookie("session_token");



        self.clearErrorMsg();

        if ($("#consumption_on_job_sparepart_errormessage").is(":visible")) {
            $("#consumption_on_job_sparepart_errormessage").text("");
            $("#consumption_on_job_sparepart_errormessage").hide();
        }


        //MABE - START HERE. CHECK EXACTLY WHAT'S THE VALUE OF consumption_on_job_search_param and why request contains positive flag for spare part existence

        if (((typeof consumption_on_job_search_param === 'undefined') && (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL)) ||
            ((CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) && ((typeof consumption_on_job_search_param !== 'undefined') && (consumption_on_job_search_param.length == 0)))) {
            self.setErrorMsg(ReturnPhraseOnKey('sparepartsearch_message_empty_searchparam_not_allowed'));
            return;
        }
        else if((typeof consumption_on_job_search_param !== 'undefined') && (consumption_on_job_search_param == null)){
            c1('consumptiononjob line 522: Sparepart search parameter is null. Ignoring request!');
            return;
        }
        else {
            c1('consumptiononjob line 526: Sparepart search parameter is ' + consumption_on_job_search_param + '. Requesting info about barcode.');
            var requester = new AjaxRequest({
                data: { "sparepart_search_param": consumption_on_job_search_param, "spareparttype_search_param": '0', "session_token": current_session_token },
                success: self.SparepartExistenceRequestComplete,
                error: self.SparepartExistenceRequestIncomplete,
                url: verificationService
            });
            requester.ExecuteRequest();
        }

    };

    self.SparepartExistenceRequestComplete = function (data, status, xhr) {

        var checkValidation = data.d.SessionTokenValid;
        var sparePartPresent = data.d.TrueOrFalse;

        console.log(data.d);


        if (checkValidation == false) {
            //$.mobile.navigate("#dialog_token_expired", { role: "dialog" });

            $("#consumption_on_job_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#consumption_on_job_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#consumption_on_job_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e5('consumptiononjob row 548');
            });

            $("#consumption_on_job_generic_popup_button").unbind("click").click(function () {
                $("#consumption_on_job_generic_popup").popup("close");
            });

            $("#consumption_on_job_generic_popup").popup().popup("open");
        }
        else if (sparePartPresent == false) {
            if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {

                $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
                $("#consumption_on_job_sparepart_errormessage").show();

                if (typeof ConsumeOnJobBarcodeReader !== 'undefined') {
                    ConsumeOnJobBarcodeReader.lastResult = '';
                }
            }
            else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                c5('consumptiononjob row 580: spare part is not found switching back to manual search until next press on scan button');
                $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
                $("#consumption_on_job_sparepart_errormessage").show();


                //Reseting incoming scan value and reverting to manual search until next press on scan barcode button.

                CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
                triggerBarcodeExistenceCheck = false;
                testMe8 = '';
            }
        }
        else if (data.d.ValueToPass > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {
            self.setErrorMsg(ReturnPhraseOnKey("sparepartselect_message_toomanyspareparts"));
        }

        else if (sparePartPresent == true) {

            if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                $.cookie("sparepartsearchparam", $("#sparepartselect_sparepart_id_input").val());
                $.cookie("spareparttypesearchparam", $("#sparepartsearch_sparepartgroups").val());
            }
            else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                $.cookie("sparepartsearchparam", data.d.StringToPass);
                $.cookie("spareparttypesearchparam", 0);
            }

            $("sparepartselect_sparepart_id_input").val("");

            //Set barcode reading from text fields to nothing - otherwise scanning will continue after each enter button entry
            initScanner(undefined);

            //$.mobile.navigate("#page_sparepartlist", { role: "page" });
            self.LookupSparePartList();
        }

    };

    self.SparepartExistenceRequestIncomplete = function (data, status, xhr) {
        c1('consumptiononjob row 615: Failed to confirm spare part search results. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

    self.LookupSparePartList = function () {

        var sparepart_search_param = '';

        $("#consumption_on_job_spare_part_search_box").hide();

        if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
            sparepart_search_param = $("#consumption_on_job_sparepart_search_value").val();

        }
        else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
            //sparepart_search_param = $.cookie('sparepartsearchparam');
            //$("#consumption_on_job_camera_section").css("display", "none");
            //$("#consumption_on_job_manual_search_switch").css("display", "none");
            //$('#consumption_on_job_scanagain').hide();
            //consumeOnJobBarcodeHandler.ShutdownCamera();

            //alert('implement spare part lookup here, based on scanned value in barcode scan page');
            sparepart_search_param = testMe8;

        }


        var sparepart_group_search_param = "0" //For the moment there is no spare part group parameter, so hardcoded to '0'
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: { "partial_sp_number": sparepart_search_param, "sparepart_group_id": sparepart_group_search_param, "session_token": current_session_token },
            success: self.LookupForSparepartsSuccess,
            error: self.LookupForSparepartsFailure,
            url: "RequestSparePartListOnPartialNumber"
        });
        requester.ExecuteRequest();
    };

    self.resetSearchResults = function () {

        $("#consumption_on_job_dynamic_content").hide();
        $("#consumption_on_job_new_search2").off();
        $("#consumption_on_job_dynamic_content").empty();
        $("#consumption_on_job_sparepart_search_value").val("");
        $("#consumption_on_job_spare_part_search_box").show();
        $("#consumption_on_job_sparepart_search_value").focus();
        //$("#consumption_on_job_camera").show();
    }

    self.attachEventToSparePartList = function () {


        $('#consumption_on_job_sparepart_list').on('click', 'li', function (e) {
            e.preventDefault();
            e.stopPropagation();

            self.selectedSparepartNo = $(this).data("sparepartnumber");
            self.selectedSparepartId = $(this).data("sparepartid");
            self.selectedSparepartName = $(this).data("sparepartname");
            if (self.selectedSparepartId !== undefined) {
                self.FindSparePartStores(self.selectedSparepartId);

            }
        });

    }

    self.LookupForSparepartsSuccess = function (data, status, xhr) {


        //$("#consumption_on_job_camera").hide();

        var listToShow = '<b>'
        listToShow += ReturnPhraseOnKey('consumption_on_job_search_results'); 
        listToShow += '</b><br><ul class="listview_default_class" id="consumption_on_job_sparepart_list" data-role="listview" data-inset="true" data-divider-theme="b">'

        var listData = data.d.SparePartList;
        var listDataLength = listData.length;


        if (listDataLength == 1) {
            self.selectedSparepartName = listData[0].SparePartName;
            self.selectedSparepartNo = listData[0].SparePartNumber;
            self.selectedSparepartId = listData[0].SparePartId;

            self.FindSparePartStores(self.selectedSparepartId);
        }
        else {



            jQuery.each(listData, function () {

                var sparepartLink = '<li role="heading" class="list-header-class" data-role="list-divider">';
                sparepartLink += this.SparePartNumber;
                sparepartLink += '</li>';
                //sparepartLink += '<li class="list-element-class" data-theme="c" data-icon="false" data-sparepartnumber="';
                sparepartLink += '<li class="list-element-class" data-icon="false" data-sparepartnumber="';

                sparepartLink += this.SparePartNumber;
                sparepartLink += '" data-sparepartid="';
                sparepartLink += this.SparePartId;
                sparepartLink += '" data-sparepartname="';
                sparepartLink += this.SparePartName;
                sparepartLink += '"><a href="#" data-transition="slide">';
                sparepartLink += this.SparePartName;
                sparepartLink += '</a></li>';
                listToShow += sparepartLink;
            });

            listToShow += '</ul>';
            listToShow += '<a class="default_button_class btn-mobile-pm5" id="consumption_on_job_new_search2"  href="#" data-role="button"  data-theme="b" data-translatetext="consumption_on_job_new_search_button">'
            listToShow += ReturnPhraseOnKey('consumption_on_job_new_search_button');
            listToShow += '</a>';

            $("#consumption_on_job_dynamic_content").html(listToShow);

            $("#consumption_on_job_new_search2").unbind().click(function (event) {
                
                self.resetSearchResults();
            });

            self.attachEventToSparePartList();

            $("#consumption_on_job_spare_part_search_box").hide();
            $("#consumption_on_job_dynamic_content").trigger("create");
            $("#consumption_on_job_dynamic_content").show();
        }

    };

    self.LookupForSparepartsFailure = function (request, status, error) {
        c1('consumptiononjob row 741: Failed to fetch spare part list');
    };

    self.FindSparePartStores = function (selectedSparepartId) {

        var currentJobId = $.cookie("currently_selected_jobid");
        var requestingUser = $.cookie("user_id");
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "sparepartid_param": selectedSparepartId.toString(), "jobid_param": currentJobId, "user_param": requestingUser, "session_token": current_session_token },
            success: self.FindSparePartStoresRequestComplete,
            error: self.FindSparePartStoresIncomplete,
            url: "GetSparePartStocksInfoOnJob"
        });
        requester.ExecuteRequest();
    }

    self.FindSparePartStoresRequestComplete = function (data, status, xhr) {

        self.AvailableStockList = data.d.StockElementList;

        var consumptionIdPredefined = data.d.StockPredefinedInJob;
        var consumptionId = data.d.PredefinedConsumptionId;
        var consumptionPredefinedToVoidStock = data.d.StockPredefinedToNone;
        var consumptionStockId = data.d.PredefinedStockId;
        var consumptionPlannedConsumption = data.d.PredefinedPlannedConsumption;
        var consumptionRealConsumption = data.d.PredefinedRealConsumption;
        var stockListLength = self.AvailableStockList.length;


        $("#consumption_on_job_dynamic_content").hide();
        $("#consumption_on_job_dynamic_content").empty();

        /* Update list of stocks valid for selection for the job */
        /*Case 1 - selected spare part is not predefined beforehand and spare part has no stocks available for location*/
        /*Creation of new consumption with no stock*/
        if ((consumptionPredefinedToVoidStock == false) && (stockListLength == 0)) {
            self.selectedStockPredefined = false;
            self.predefinedConsumptionId = -1;
            self.handleNewConsumptionWithoutNoAvailableStocks();
        }
            /*Case 2 - selected spare part has predefined consumption without a specific store*/
            /*Update of preexisting consumption with no stock */
        else if (consumptionPredefinedToVoidStock == true) {
            self.selectedStockPredefined = true;
            self.predefinedConsumptionId = consumptionId;
            self.predefinedPlannedConsumption = consumptionPlannedConsumption;
            self.predefinedRealConsumption = consumptionRealConsumption;
            self.handleExistingConsumptionWithoutStock(consumptionId);
        }
            /*Case 3 - selected spare part has no predefined consumption assigned to activity and one or more stocks available for location*/
            /*Present list of available stocks, including 'no stocks'*/
        else if ((consumptionPredefinedToVoidStock == false) && (consumptionIdPredefined == false) && (stockListLength > 0)) {
            self.selectedStockPredefined = false;
            self.predefinedConsumptionId = -1;


            var sparepartInfoSection = '<table id="stockdetails_table">';
            sparepartInfoSection += '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_sparepartinfo_label') + '</td></tr>';
            sparepartInfoSection += '<tr><td>' + self.selectedSparepartName + ' / ' + self.selectedSparepartNo + '</td></tr></table>';

            var stockListHTML = sparepartInfoSection + '<br/><br/><ul id="consumption_on_job_storelist" data-role="listview" data-divider-theme="b">'
            stockListHTML += '<li class="list-header-class" role="heading" data-role="list-divider">';
            stockListHTML += ReturnPhraseOnKey('sparepartdetail_stockheader');
            stockListHTML += '</li>';

            /* Add empty list element for scenario where spare part stock is NOT to be used */
            //stockListHTML += '<li class="list-element-class" data-theme="c" data-stockid = "0"><a href="#dummy" data-transition="slide">';
            stockListHTML += '<li class="list-element-class" data-stockid = "0"><a href="#dummy" data-transition="slide">';

            stockListHTML += ReturnPhraseOnKey('sparepartdetail_nostock');
            stockListHTML += '</a></li>';

            /* Create list of valid stocks for the job */

            jQuery.each(self.AvailableStockList, function () {
                //stockListHTML += '<li class="list-element-class" data-theme="c" data-stockid ="';
                stockListHTML += '<li class="list-element-class" data-stockid ="';
                stockListHTML += this.StockId;
                stockListHTML += '">';
                stockListHTML += '<a href="#">'
                stockListHTML += this.StockStore + ' (' + this.StockInStore + ')';
                stockListHTML += '</a></li>';
            });

            stockListHTML += '</ul>';


            $("#consumption_on_job_sp_info_section").html(sparepartInfoSection);
            $("#consumption_on_job_dynamic_content").html(stockListHTML);
            $("#consumption_on_job_dynamic_content").trigger("create");
            $("#consumption_on_job_dynamic_content").show();

            self.attachEventToSparePartStockList();

        }
            /*Case 4 - selected spare part has a predefined consumption with specified stock assigned to activity*/
            /*Handle consumption on specified stock*/
        else if ((consumptionPredefinedToVoidStock == false) && (consumptionIdPredefined = true)) {
            self.selectedStockPredefined = true;
            self.predefinedConsumptionId = consumptionId;
            self.predefinedPlannedConsumption = consumptionPlannedConsumption;
            self.predefinedRealConsumption = consumptionRealConsumption;
            self.handleExistingConsumptionWithStock(consumptionId);
        }
    }

    self.FindSparePartStoresIncomplete = function (request, status, error) {
        c1('consumptiononjob row 847: In FindSparePartStoresRequestIncomplete');
    };

    self.handleNewConsumptionWithoutNoAvailableStocks = function () {

        //Set 'global' stock id to be used for consumption to '0' - indicates no stock specified
        self.selectedStockId = 0;

        var htmlStockInformationDetails = '';

        var sparepartInfoSection = '<table id="stockdetails_table">';
        sparepartInfoSection += '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_sparepartinfo_label') + '</td></tr>';
        sparepartInfoSection += '<tr><td>' + self.selectedSparepartName + ' / ' + self.selectedSparepartNo + '</td></tr>';

        htmlStockInformationDetails = sparepartInfoSection + '<tr><td class="infotext">' + ReturnPhraseOnKey('consumption_on_job_consumption_with_no_stock_info') + '</td></tr></table>';
        $("#consumption_on_job_dynamic_content").empty();
        $("#consumption_on_job_dynamic_content").html(htmlStockInformationDetails);
        $("#consumption_on_job_dynamic_content").css("display", "block");

        $("#consumption_on_job_consumption_section").css("display", "block");
        $("#consumption_on_job_quantity").focus();

    };

    self.handleExistingConsumptionWithoutStock = function (consumptionToUpdate) {
        //Set 'global' stock id to be used for consumption to '0' - indicates no stock specified
        self.selectedStockId = 0;

        var sparepartInfoSection = '<table id="stockdetails_table">';
        sparepartInfoSection += '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_sparepartinfo_label') + '</td></tr>';
        sparepartInfoSection += '<tr><td>' + self.selectedSparepartName + ' / ' + self.selectedSparepartNo + '</td></tr>';

        var htmlStockInformationDetails = '';
        htmlStockInformationDetails += sparepartInfoSection + '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_consumption_with_no_stock_info') + '<br><b>';
        htmlStockInformationDetails += '<span style="font-weight: bold; text-shadow:none; color:khaki">' + ReturnPhraseOnKey('consumption_on_job_predefined_source_flag');
        htmlStockInformationDetails += ' (' + self.predefinedPlannedConsumption + '/' + self.predefinedRealConsumption + ')' + '</span></b></td></tr></table>';



        $("#consumption_on_job_dynamic_content").empty();
        $("#consumption_on_job_dynamic_content").html(htmlStockInformationDetails);
        $("#consumption_on_job_dynamic_content").css("display", "block");

        $("#consumption_on_job_consumption_section").css("display", "block");
        $("#consumption_on_job_quantity").focus();
    };

    self.handleExistingConsumptionWithStock = function (consumptionToUpdate) {
        self.RequestSelectedStockInfo(consumptionOnJob.AvailableStockList[0].StockId);
    };


    self.attachEventToSparePartStockList = function () {


        $('#consumption_on_job_storelist').on('click', 'li', function (e) {
            e.preventDefault();
            e.stopPropagation();

            self.selectedStockId = $(this).data("stockid");
            if (self.selectedStockId > 0) {
                self.RequestSelectedStockInfo(self.selectedStockId);
            }
            else {
                self.RequestSelectedStockInfo(self.selectedStockId);
            }
        });

    }


    self.updateJobInformationForActivity = function () {
        //Update activity header

        var activityBasicInfo = '<h3>' + ReturnPhraseOnKey('consumption_on_job_activityid_label') + self.currentJob.JobID + '<br>';
        activityBasicInfo += '<h3>' + ReturnPhraseOnKey('consumption_on_job_jobtype_label') + self.currentJob.TaskName + '</h3>';

        $("#consumption_on_job_job_basic_info").html(activityBasicInfo);

        //Update activity details
        var detailTable = '<table id="activitydetail_table">';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_machinename');
        detailTable += '</td><td>';
        detailTable += self.currentJob.MachineNumber;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_machinenumber');
        detailTable += '</td><td>';
        detailTable += self.currentJob.MachineName;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_task');
        detailTable += '</td><td>';
        detailTable += self.currentJob.TaskName;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_tasktype');
        detailTable += '</td><td>';
        detailTable += self.currentJob.TaskType;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_scheduleddate');
        detailTable += '</td><td>';
        detailTable += self.currentJob.ScheduledDate;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_completeddate');
        detailTable += '</td><td>';
        detailTable += self.currentJob.DoneDate;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('activitydetailhistorical_signedby');
        detailTable += '</td><td>';
        detailTable += self.currentJob.SignedBy;
        detailTable += '</td></tr>';
        detailTable += '</table>';

        $("#consumption_on_job_job_detailed_info").html(detailTable);



    };

    self.updateJobInformationForFault = function () {
        var faultBasicInfo = '<h3>' + ReturnPhraseOnKey('consumption_on_job_faultid_label') + self.currentJob.JobID + '<br>';
        faultBasicInfo += '<h3>' + ReturnPhraseOnKey('consumption_on_job_faulttype_label') + self.currentJob.FaultType + '</h3>';

        $("#consumption_on_job_job_basic_info").html(faultBasicInfo);

        var detailTable = '<table id="faultdetail_table">';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_machinename');
        detailTable += '</td><td>';
        detailTable += self.currentJob.MachineName;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_machinenumber');
        detailTable += '</td><td>';
        detailTable += self.currentJob.MachineNumber;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_discoveredon');
        detailTable += '</td><td>';
        detailTable += self.currentJob.DiscoveredOn;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_discoveredby');
        detailTable += '</td><td>';
        detailTable += self.currentJob.DiscoveredBy;
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_faultcause');
        detailTable += '</td><td>';
        if (self.currentJob.FaultCause == "Unspecified") {
            detailTable += ReturnPhraseOnKey('global_unspecified');
        }
        else {
            detailTable += self.currentJob.FaultCause;
        }
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_resolvedon');
        detailTable += '</td><td>';
        if (self.currentJob.ResolvedOn == "Unspecified") {
            detailTable += ReturnPhraseOnKey('global_unspecified');
        }
        else {
            detailTable += self.currentJob.ResolvedOn;
        }
        detailTable += '</td></tr>';
        detailTable += '<tr><td class="label">';
        detailTable += ReturnPhraseOnKey('faultdetailhistorical_signingperson');
        detailTable += '</td><td>';
        if (self.currentJob.SigningPerson == "Unspecified") {
            detailTable += ReturnPhraseOnKey('global_unspecified');
        }
        else {
            detailTable += self.currentJob.SigningPerson;
        }
        detailTable += '</td></tr>';
        detailTable += '</table>';

        $("#consumption_on_job_job_detailed_info").html(detailTable);
    };


    //Continue here - need to figure out a way to display warning about predefined stock when stock present
    //Next, implement update existing stock instead of adding new multiple times

    self.RequestSelectedStockInfo = function (stockIdToDisplay) {

        //$('#consumption_on_job_camera').hide();

        if (stockIdToDisplay > 0) {
            var requester = new AjaxRequest({
                data: { "stockid": stockIdToDisplay },
                success: self.SparePartStockInfoRequestSuccess,
                error: self.SparePartStockInfoRequestError,
                url: "RequestStockInformationOnStockId"
            });

            requester.ExecuteRequest();
        }
        else {
            self.handleNewConsumptionWithoutNoAvailableStocks();
        }
    }

    self.SparePartStockInfoRequestSuccess = function (data, status, xhr) {
        var incomingStoreName = data.d.StockStore;
        var incomingStockArea = data.d.StockPositionI;
        var incomingStockSection = data.d.StockPositionII;
        var incomingStockPostion = data.d.StockPositionIII;
        var incomingStockQtyInStock = data.d.StockInStore;



        var storeNameToPresent = ReturnPhraseOnKey('addconsumption_storenotselected');
        var storePositionsToPresent = ReturnPhraseOnKey('addconsumption_storenotselected');
        if (incomingStoreName != '') {
            storeNameToPresent = incomingStoreName;

            if (incomingStockArea != '') {
                storePositionsToPresent = incomingStockArea;

                if (incomingStockSection != '') {
                    storePositionsToPresent += ' -- ';
                    storePositionsToPresent += incomingStockSection;
                }
                if (incomingStockPostion != '') {
                    storePositionsToPresent += ' -- ';
                    storePositionsToPresent += incomingStockPostion;
                }
            }
        }

        var htmlStockInformationDetails = '';

        htmlStockInformationDetails = '<table id="stockdetails_table">';
        htmlStockInformationDetails += '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_sparepartinfo_label') + '</td></tr>';
        htmlStockInformationDetails += '<tr><td>' + self.selectedSparepartName + ' / ' + self.selectedSparepartNo + '</td></tr>';

        htmlStockInformationDetails += '<tr><td class="label" >' + ReturnPhraseOnKey('consumption_on_job_sparepartinfo_store');
        if (self.selectedStockPredefined) {
            htmlStockInformationDetails += '<span style="font-weight: bold; margin-left: 5%; text-shadow:none; color:khaki">';
            htmlStockInformationDetails += ReturnPhraseOnKey('consumption_on_job_predefined_source_flag');
            htmlStockInformationDetails += ' (' + self.predefinedPlannedConsumption + '/' + self.predefinedRealConsumption + ')</span></td></tr>';
        }
        else {
            htmlStockInformationDetails += '</td></tr>';
        }
        htmlStockInformationDetails += '<tr><td>' + storeNameToPresent + ' (' + incomingStockQtyInStock + ')' + '</td></tr>';
        htmlStockInformationDetails += '<tr><td class="label">' + ReturnPhraseOnKey('consumption_on_job_positionatstore') + '</td></tr>';
        htmlStockInformationDetails += '<tr><td>' + storePositionsToPresent + '</td></tr>';
        htmlStockInformationDetails += '</table>';

        $("#consumption_on_job_dynamic_content").empty();
        $("#consumption_on_job_dynamic_content").html(htmlStockInformationDetails);
        $("#consumption_on_job_dynamic_content").css("display", "block");

        $("#consumption_on_job_consumption_section").css("display", "block");
        $("#consumption_on_job_quantity").focus();
    };

    self.SparePartStockInfoRequestError = function (data, status, xhr) {
        c1('consumptiononjob row 1113: Unable to get spare part stock information.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

    self.commitConsumption = function (qtyToConsume) {
        var outgoingActivityId = 0;
        var outgoingFaultId = 0;
        var sparepartIdToConsume = self.selectedSparepartId;
        var consumptionTypeId = 1;
        var consumeAmount = qtyToConsume;
        var machineId = self.currentJob.MachineId;
        var consumeNote = '';
        var UserId = $.cookie("user_id");
        var SparePartStockId = self.selectedStockId;
        var ConsumeMachineID = self.selectedMachineId;
        var ConsumedOK = 1;
        var SubstractedFromStock = 0;
        var ConsumeAmountSubstracted = 0;
        var ConsumeAmountDirect = 0;
        var current_session_token = $.cookie("session_token");

        if (SparePartStockId == 0) {
            ConsumeAmountDirect = qtyToConsume;

        }
        else {
            SubstractedFromStock = 1;
            ConsumeAmountSubstracted = qtyToConsume;
        }

        if (self.currentJobType == "Activity") {
            outgoingActivityId = self.currentJob.ActivityID;
        }
        else if (self.currentJobType == "Fault") {
            outgoingFaultId = self.currentJob.FaultID;
        }

        //$("#consumption_on_job_consumption_section").css("display", "none");

        var requester = new AjaxRequest({

            data: {
                "activityid": outgoingActivityId, "faultid": outgoingFaultId, "sparepartid": sparepartIdToConsume, "consumptiontypeid": consumptionTypeId,
                "consumenote": consumeNote, "userid": UserId, "sparepartstockid": self.selectedStockId, "substractedfromstock": SubstractedFromStock,
                "ammountsubstracted": ConsumeAmountSubstracted, "consumedok": ConsumedOK, "machinenumber": self.currentJob.MachineName, "consumeddirect": ConsumeAmountDirect,
                "session_token": current_session_token
            },
            success: self.CreateNewConsumptionSuccess,
            error: self.CreateNewConsumptionFailure,
            url: "RegisterNewConsumption"
        });

        requester.ExecuteRequest();

    };

    self.CreateNewConsumptionSuccess = function (data, status, xhr) {

        console.clear();

        var currentJobId = $.cookie("currently_selected_jobid");
        var message = ReturnPhraseOnKey("consumption_on_job_dialogue_consumption_ok");
        var navigateToOnNewConsumption = 0;



        $("#consumption_on_job_consumption_on_job_consumption_finished_popup_header").html(message);
        $("#consumption_on_job_consumption_on_job_consumption_finished_popup_text").html(message);

        $("#consumption_on_job_consumption_finished_popup").off().on("popupafterclose", function (event, ui) {

            event.preventDefault();
            event.stopPropagation();

            triggerBarcodeExistenceCheck = false;
            testMe8 = '';

            self.sparepartCleanup();
            self.resetSearchInputElements();
            c5('consumptiononid row 1188, navigateToOnNewConsumption: ' + navigateToOnNewConsumption);

            if (navigateToOnNewConsumption == 1) {



                if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                    $.mobile.navigate("#page_consumption_on_job", { role: "page" });
                    e1('consumptiononjob row 819');
                }
                else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                    triggerBarcodeExistenceCheck = true;
                    SCAN_PAGE_TARGET = SCAN_SPAREPART_FOR_JOB;
                    testMe8 = '';
                    $.mobile.navigate("#page_scantest", { role: "page" });
                    e1('consumptiononjob row 826');
                }
                else {
                    c1("Could not decide about next navigation step, moving to job search on id page as final resort");
                    $.mobile.navigate("#page_consumption_on_job", { role: "page" });
                    e1('consumptiononjob row 831');
                }
            }
            else {

                $.cookie("currently_selected_jobid", '');

                detectedJobIDBarcode = '';
                detectedSparePartBarcode = '';

                if (CURRENT_JOBID_SEARCH_MODE == JOBID_SEARCH_INPUT_MANUAL) {
                    c2('consumptiononjob row 842 - NEW consumption for this job finished by user, switching to manual job search');
                    $.mobile.navigate("#page_jobsearch_onid", { role: "page" });
                }
                else if (CURRENT_JOBID_SEARCH_MODE == JOBID_SEARCH_INPUT_BARCODE) {
                    SCAN_PAGE_TARGET = SCAN_JOB_ID;
                    triggerBarcodeExistenceCheck = true;
                    c2('consumptiononjob row 848 - NEW consumption for this job finished by user, switching to barcode job search ');
                    $.mobile.navigate("#page_scantest", { role: "page" });
                }

                c1('consumptiononjob row 852: Another sparepart. Consumption screen.');
            }
        });

        $("#consumption_on_job_consumption_finished_popup_button1").unbind().click(function (event) {
            c6('consumptiononjob row 1216, navigateToOnNewConsumption: ' + navigateToOnNewConsumption);
            navigateToOnNewConsumption = 1;
            c6('consumptiononjob row 1218, navigateToOnNewConsumption: ' + navigateToOnNewConsumption);
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup_button2").unbind().click(function (event) {
            c6('consumptiononjob row 1223, navigateToOnNewConsumption: ' + navigateToOnNewConsumption);
            navigateToOnNewConsumption = 0;
            c6('consumptiononjob row 1225, navigateToOnNewConsumption: ' + navigateToOnNewConsumption);
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup").popup().popup("open");
    }

    self.CreateNewConsumptionFailure = function (data, status, xhr) {

        $("#consumption_on_job_quantity").val("");
        c1('consumptiononjob row 1224: Unable to register spare part consumption in datatbase.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.updatePredefinedConsumption = function (consumptionQtyToAdd) {


        var consumptionId = self.predefinedConsumptionId;
        var selectedJobId = $.cookie("currently_selected_jobid");
        var UserId = $.cookie("user_id");

        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "consumptionid": consumptionId, "consumedqty": consumptionQtyToAdd, "userid": UserId, "jobid": selectedJobId, "session_token": current_session_token },
            success: self.CommitPredefinedConsumptionSuccess,
            error: self.CommitPredefinedConsumptionFailure,
            url: "RegisterChangeInExistingConsumption"
        });

        requester.ExecuteRequest();
    }


    self.CommitPredefinedConsumptionSuccess = function (data, status, xhr) {
        console.clear();

        var message = ReturnPhraseOnKey("consumption_on_job_dialogue_predefined_consumption_ok");
        var navigateToOnPredefinedConsumption = 0;


        $("#consumption_on_job_consumption_on_job_consumption_finished_popup_header").html(message);
        $("#consumption_on_job_consumption_on_job_consumption_finished_popup_text").html(message);

        $("#consumption_on_job_consumption_finished_popup").off().on("popupafterclose", function (event, ui) {

            event.preventDefault();
            event.stopPropagation();

            self.sparepartCleanup();
            self.resetSearchInputElements();
            c5('consumptiononid row 1270, navigateToOnPredefinedConsumption: ' + navigateToOnPredefinedConsumption);
            if (navigateToOnPredefinedConsumption == 1) {

                triggerBarcodeExistenceCheck = false;
                testMe8 = '';

                if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                    $.mobile.navigate("#page_consumption_on_job", { role: "page" });
                    e1('consumptiononjob row 1272');
                }
                else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                    triggerBarcodeExistenceCheck = true;
                    SCAN_PAGE_TARGET = SCAN_SPAREPART_FOR_JOB;
                    $.mobile.navigate("#page_scantest", { role: "page" });
                    e1('consumptiononjob row 1276');
                }
                else {
                    c1("Could not decide about next navigation step, moving to manual selection as final resort");
                    $.mobile.navigate("#page_consumption_on_job", { role: "page" });
                    e1('consumptiononjob row 1281');
                }
            }
            else {
                $.cookie("currently_selected_jobid", '');

                detectedJobIDBarcode = '';
                detectedSparePartBarcode = '';

                if (CURRENT_JOBID_SEARCH_MODE == JOBID_SEARCH_INPUT_MANUAL) {
                    c2('consumptiononjob row 945 - PREDEFINED CONSUMPTION for this job finished by user, switching to manual job search');
                    $.mobile.navigate("#page_jobsearch_onid", { role: "page" });
                }
                else if (CURRENT_JOBID_SEARCH_MODE == JOBID_SEARCH_INPUT_BARCODE) {
                    SCAN_PAGE_TARGET = SCAN_JOB_ID;
                    triggerBarcodeExistenceCheck = true;
                    c2('consumptiononjob row 951 - PREDEFINED CONSUMPTION for this job finished by user, switching to barcode job search ');
                    $.mobile.navigate("#page_scantest", { role: "page" });
                }

                c1('consumptiononjob row 1204: Another sparepart. Consumption screen.');
            }
        });

        $("#consumption_on_job_consumption_finished_popup_button1").unbind().click(function (event) {
            c6('consumptiononjob row 1297, navigateToOnPredefinedConsumption: ' + navigateToOnPredefinedConsumption);
            navigateToOnPredefinedConsumption = 1;
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup_button2").unbind().click(function (event) {
            c6('consumptiononjob row 1303, navigateToOnPredefinedConsumption: ' + navigateToOnPredefinedConsumption);
            navigateToOnPredefinedConsumption = 0;
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup").popup().popup("open");
    }

    self.CommitPredefinedConsumptionFailure = function (data, status, xhr) {
        $("#consumption_on_job_quantity").val("");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.validateConsumedQtyInput = function (inputValueToValidate) {

        if ($("#consumption_on_job_sparepart_errormessage").is(":visible")) {
            $("#consumption_on_job_sparepart_errormessage").text("");
            $("#consumption_on_job_sparepart_errormessage").hide();
        }


        var validationTest = true;

        var wholeNumberRegEx = /^[1-9]\d*$/;

        if (inputValueToValidate == '') {
            $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey('addconsumption_err_validnumber'));
            validationTest = false;
        }
        else if (!wholeNumberRegEx.test(inputValueToValidate)) {
            $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey('addconsumption_err_positivenumbersonly'));
            validationTest = false;
        }
        else if (inputValueToValidate == 0) {
            $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey('addconsumption_err_nozeroes'));
            validationTest = false;
        }

        if (validationTest == false) {
            $("#consumption_on_job_quantity").val("");
            $("#consumption_on_job_quantity").focus();
            $("#consumption_on_job_sparepart_errormessage").show();

        }

        return validationTest;
    }

    self.consumptionTrigger = function () {
        var consumptionToRegister = $("#consumption_on_job_quantity").val();
        if (self.validateConsumedQtyInput(consumptionToRegister) == true) {

            if ($("#consumption_on_job_sparepart_errormessage").is(":visible")) {
                $("#consumption_on_job_sparepart_errormessage").text("");
                $("#consumption_on_job_sparepart_errormessage").hide();
            }

            if (self.selectedStockPredefined == false) {
                self.commitConsumption(consumptionToRegister);
            }
            else {
                self.updatePredefinedConsumption(consumptionToRegister);
            }
        }
    }


    self.sparepartCleanup = function () {
        $("#consumption_on_job_sparepart_search_value").show();
        $("#consumption_on_job_sparepart_search_value").val("");
        $("#consumption_on_job_sparepart_search").show();
        $("#consumption_on_job_dynamic_content").hide();
        $("#consumption_on_job_dynamic_content").empty();
        $("#consumption_on_job_consumption_section").hide();
        $("#consumption_on_job_quantity").val("");
        if ($("#consumption_on_job_spare_part_search_box").is(":hidden")) {
            $("#consumption_on_job_spare_part_search_box").show();
        }

        if ($("#consumption_on_job_sparepart_errormessage").is(":visible")) {
            $("#consumption_on_job_sparepart_errormessage").text("");
            $("#consumption_on_job_sparepart_errormessage").hide();
        }


        self.selectedSparepartNo = '';
        self.selectedSparepartId = '';
        self.selectedSparepartName = '';
        self.AvailableStockList = '';
        self.selectedStockId = null;
        self.selectedMachineId = null;
        self.selectedStockPredefined = false;
        self.predefinedConsumptionId = '-1';
        self.predefinedPlannedConsumption = '0';
        self.predefinedRealConsumption = '0';


        $("#consumption_on_job_sparepart_search_value").focus();

    }

    self.resetSearchInputElements = function () {
        if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {

        }
        else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
            $("#consumption_on_job_spare_part_search_box").css("display", "block");
        }
    }

    self.jobCleanup = function () {
        self.currentJob = null;
        self.currentJobType = null;
    }

    self.setErrorMsg = function (msg) {

        $('#consumption_on_job_sparepart_errormessage').html(msg);
        $('#consumption_on_job_sparepart_errormessage').show();
    }

    self.clearErrorMsg = function (msg) {
        $('#consumption_on_job_sparepart_errormessage').html('');
        $('#consumption_on_job_sparepart_errormessage').hide();
    }

    return self;

}

//var consumeOnJobBarcodeHandler = null;
var consumptionOnJob = ConsumptionOnJob();

$(document).on("pagebeforeshow", "#page_consumption_on_job", function (e, data) {

    $('#consumption_on_job_textbox_content').text('');
    consumptionOnJob.clearErrorMsg();
    //$('#consumption_on_job_scanagain').hide();
    
    //if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
    //    $('#consumption_on_job_camera').html(ReturnPhraseOnKey("consumption_on_job_search_sp_manually"));
    //}
    //else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
    //    $('#consumption_on_job_camera').html(ReturnPhraseOnKey("consumption_on_job_search_sp_with_camera"));
    //}
});


$(document).one("pageshow", "#page_consumption_on_job", function (e) {

    $("#consumption_on_job_consume_button").click(function () {
        consumptionOnJob.consumptionTrigger();
        e1('consumptiononjob row 1462');
    });

    $('#consumption_on_job_quantity').bind("commitConsumptionOnJob", function (e) {
        consumptionOnJob.consumptionTrigger();
        e1('consumptiononjob row 1467');
    });


    $('#consumption_on_job_quantity').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("commitConsumptionOnJob");
            e1('consumptiononjob row 1474');
        }
    });

    $("#consumption_on_job_back_button").click(function () {
        $.mobile.navigate("#page_stores_functionselection", { role: "page" });
        e1('consumptiononjob row 1480');
    });


});

$(document).on("pagebeforeshow", "#page_consumption_on_job", function (e, data) {
    if (SessionTokenStatus == true) {
        if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE && triggerBarcodeExistenceCheck) {
            var prevPageId = data.prevPage.attr("id");
            c1(prevPageId);

            if (prevPageId !== "page_scantest") {
                c9('consumptiononjob row 1518 - previous page is other than barcode scan, skipping barcode lookup');
                return;
            }
            else if (triggerBarcodeExistenceCheck == true) {
                c9('consumptiononjob row 1522 - previous page IS barcode scan, MAKING barcode lookup');
                consumptionOnJob.checkForSparepartExistence();
            }


        }
        else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {

            $("#consumption_on_job_camera_section").css("display", "none");
            $("#consumption_on_job_manual_search_switch").css("display", "none");
            $("#consumption_on_job_spare_part_search_box").css("display", "block");
        }

        consumptionOnJob.init();
    }
});


$(document).on("pageshow", "#page_consumption_on_job", function (e, data) {

    $("#consumption_on_job_sparepart_search_value").focus();

    if (SessionTokenStatus == true) {
        //*****************************************************************************************************************
        //20200331 - moved to pagebeforeshow event
        //if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE && triggerBarcodeExistenceCheck) {
        //    var prevPageId = data.prevPage.attr("id");
        //    c1(prevPageId);

        //    if (prevPageId !== "page_scantest") {
        //        c9('consumptiononjob row 1518 - previous page is other than barcode scan, skipping barcode lookup');
        //        return;
        //    }
        //    else if (triggerBarcodeExistenceCheck == true) {
        //        c9('consumptiononjob row 1522 - previous page IS barcode scan, MAKING barcode lookup');
        //        consumptionOnJob.checkForSparepartExistence();
        //    }


        //}
        //else if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {

        //    $("#consumption_on_job_camera_section").css("display", "none");
        //    $("#consumption_on_job_manual_search_switch").css("display", "none");
        //    $("#consumption_on_job_spare_part_search_box").css("display", "block");
        //}

        //consumptionOnJob.init();
        //******************************************************************************************************************


        $("#consumption_on_job_sparepart_search").unbind().click(function (event) {
            CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL
            consumptionOnJob.checkForSparepartExistence();
            e1('consumptiononjob row 1547');
        });

        $("#consumption_on_job_sparepart_search_2").unbind().click(function (event) {
            consumptionOnJob.checkForSparepartExistence();
            e1('consumptiononjob row 1552');
        });

        $("#consumption_on_job_camera").unbind().click(function (event) {
            event.preventDefault();
            event.stopPropagation();
            consumptionOnJob.resetSearchResults();


            $('#consumption_on_job_textbox_content').text(ReturnPhraseOnKey('sp_barcodecam_info_text'));
            $("#consumption_on_job_sparepart_errormessage").text('');
            $("#consumption_on_job_sparepart_errormessage").hide();

            e1('consumptiononjob row 1572');

            CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_BARCODE;
            SCAN_PAGE_TARGET = SCAN_SPAREPART_FOR_JOB;
            testMe8 = '';
            initScanner(undefined);
            setTimeout($.mobile.navigate("#page_scantest", { role: "page" }), 100);
            triggerBarcodeExistenceCheck = true;
            c2('consumptiononjob row 1573 - navigating to barcode scanner to fetch the barcode');

        });

        $("#consumption_on_job_manual").unbind().click(function (event) {
            event.preventDefault();
            event.stopPropagation();
            consumptionOnJob.resetSearchResults();

            CONSUMPTION_SP_SEARCH_MODE= SPAREPART_SEARCH_INPUT_MANUAL;
            $('#consumption_on_job_scanagain').hide();
            $("#consumption_on_job_spare_part_search_box").css("display", "block");
            $('#consumption_on_job_textbox_content').text(ReturnPhraseOnKey(''));

            $("#consumption_on_job_sparepart_errormessage").text('');
            $("#consumption_on_job_sparepart_errormessage").hide();
            e1('consumptiononjob row 1620');

        });

        $("#consumption_on_job_scanagain").unbind().click(function (event) {
            event.preventDefault();
            $("#consumption_on_job_textbox_content").text(ReturnPhraseOnKey("sp_barcodecam_info_text"));
            $("#consumption_on_job_scanagain").hide().fadeOut(1000);
            e1('consumptiononjob row 1631');

        });

        $('#consumption_on_job_sparepart_search_value').unbind().keyup(function (e) {
            if (e.keyCode == 13) {
                consumptionOnJob.checkForSparepartExistence();
                e1('consumptiononjob row 1638');

            }
        });

        $('#consumption_on_job_back_to_main_button').unbind().click(function (event) {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_mainmenu", { role: "page", reverse: false, changeHash: false });
            e1('consumptiononjob row 1645');
        });

    }
    else {
        helper.ForcedLogout();
    }

});

$(document).on("pagehide", "#page_consumption_on_job", function () {
    consumptionOnJob.sparepartCleanup();
    consumptionOnJob.jobCleanup();

    triggerBarcodeExistenceCheck = false;
    testMe8 = '';

    $('#consumption_on_job_textbox_content').text('');
    $('#consumption_on_job_sparepart_errormessage').text('');

});