function ConsumptionOnJob() {

    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 () {

        //initScanner(this);
        self.requestJobInfo();
    };

    self.requestJobInfo = function () {
        console.log('In request')
        var requestingUser = $.cookie("username");

        //console.log(self.previousPage);

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

        console.log(currentJobId);

        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) {
            console.log("token gone bad when trying to finish job");
            //$.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 });
            });

            $("#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 {

            console.log(data.d);
            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>
        console.log('Unable to retrieve fault information from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };


    self.checkForSparepartExistence = function () {
        var consumption_on_job_search_param = $("#consumption_on_job_sparepart_search_value").val();
        var consumption_on_job_sp_group_param = ""; //for time being, this one is always a dummy
        var current_session_token = $.cookie("session_token");

        console.log('in JSON call for verification of sp presence');
        self.clearErrorMsg();

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


        if (defined(consumption_on_job_search_param) == false || consumption_on_job_search_param.length == 0) {
            self.setErrorMsg(ReturnPhraseOnKey('sparepartsearch_message_empty_searchparam_not_allowed'));
            return;
        }
        else {

            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: "CheckForSparepartPresence"
            });
            requester.ExecuteRequest();
        }

    };

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

        console.log("Request successful");
        console.log(data.d);

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


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

            console.log("token not valid, moving to 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 });
            });

            $("#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) {
            console.log("Could not find spareparts");
            $("#consumption_on_job_sparepart_errormessage").text(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
            $("#consumption_on_job_sparepart_errormessage").show();
        }

        else if (sparePartPresent == true) {


            console.log('spare part exists, populating list');
            $.cookie("sparepartsearchparam", $("#sparepartselect_sparepart_id_input").val());
            $.cookie("spareparttypesearchparam", $("#sparepartsearch_sparepartgroups").val());
            $("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) {
        console.log('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_sparepart_search_value").val();
        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");

        console.log(current_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();
    }

    self.attachEventToSparePartList = function () {

        console.log('attaching events to spare part list');

        $('#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");
            console.log(this.text);
            if (self.selectedSparepartId !== undefined) {
                console.log(self.selectedSparepartNo);
                console.log(self.selectedSparepartId);
                self.FindSparePartStores(self.selectedSparepartId);

            }
        });

    }

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


        console.log('Fetching list here');
        console.log(data.d);

        var listToShow = '<b>Search results</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;

        console.log(listData);
        console.log(listDataLength);

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

            console.log(self.selectedSparepartId + ' - single spare part, skipping spare part list display');
            $("#consumption_on_job_spare_part_search_box").hide();
            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-translatetext="consumption_on_job_new_search_button">Search again</a>'

            console.log(listToShow);
            $("#consumption_on_job_dynamic_content").html(listToShow);
            console.log('1');

            $("#consumption_on_job_new_search2").unbind().click(function (event) {
                console.log('resetting the search results');
                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) {
        console.log('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");
        console.log(typeof selectedSparepartId);

        console.log('**********************************************');
        console.log(currentJobId);
        console.log(requestingUser);
        console.log(current_session_token);
        console.log(selectedSparepartId);
        console.log('**********************************************');


        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) {

        console.log('In FindSparePartStoresRequestComplete');
        console.log(data.d);
        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;

        console.log('*******************************');
        console.log('consumptionIdPredefined: ' + consumptionIdPredefined);
        console.log('consumptionId: ' + consumptionId);
        console.log('consumptionPredefinedToVoidStock: ' + consumptionPredefinedToVoidStock);
        console.log('consumptionStockId: ' + consumptionStockId);
        console.log('stockListLength: ' + stockListLength);
        console.log(self.AvailableStockList);
        console.log('*******************************');

        
        $("#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)) {
            console.log('1');
            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) {
            console.log('2');
            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)) {
            console.log('3');
            self.selectedStockPredefined = false;
            self.predefinedConsumptionId = -1;

            console.log('creating stock list');

            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 += 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 += this.StockId;
                stockListHTML += '">';
                stockListHTML += '<a href="#">'
                stockListHTML += this.StockStore + ' (' + this.StockInStore + ')';
                stockListHTML += '</a></li>';
            });

            stockListHTML += '</ul>';

            console.log(stockListHTML);

            $("#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)) {
            console.log('4');
            self.selectedStockPredefined = true;
            self.predefinedConsumptionId = consumptionId;
            self.predefinedPlannedConsumption = consumptionPlannedConsumption;
            self.predefinedRealConsumption = consumptionRealConsumption;
            self.handleExistingConsumptionWithStock(consumptionId);
        }
    }

    self.FindSparePartStoresIncomplete = function (request, status, error) {
        console.log('In FindSparePartStoresRequestIncomplete');
    };

    self.handleNewConsumptionWithoutNoAvailableStocks = function () {
        console.log('New consumption, no stocks available for sparepart, needs to be consumed without stock');

        //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) {
        console.log('Existing consumption, no stock specified');
        //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) {
        console.log('Existing consumption, stock specified');
        console.log(consumptionToUpdate);
        console.log(self.AvailableStockList);
        self.RequestSelectedStockInfo(consumptionOnJob.AvailableStockList[0].StockId);
    };


    self.attachEventToSparePartStockList = function () {

        console.log('attaching events to spare part stocks');

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

            self.selectedStockId = $(this).data("stockid");
            console.log(self.selectedStockId);
            if (self.selectedStockId > 0) {
                self.RequestSelectedStockInfo(self.selectedStockId);
            }
            else {
                console.log('display text for no stock selected');
                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) {
        console.log(stockIdToDisplay);
        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) {
        console.log(data.d);
        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) {
        console.log('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) {
            console.log("NoStoreSelected");
            ConsumeAmountDirect = qtyToConsume;

        }
        else {
            console.log("Store selected");
            SubstractedFromStock = 1;
            ConsumeAmountSubstracted = qtyToConsume;
        }

        if (self.currentJobType == "Activity") {
            console.log('setting to activity');
            console.log(self.currentJob.ActivityID);
            outgoingActivityId = self.currentJob.ActivityID;
            console.log('outgoingActivityId: ' + outgoingActivityId);
        }
        else if (self.currentJobType == "Fault") {
            console.log('setting to fault');
            outgoingFaultId = self.currentJob.FaultID;
        }

        console.log('***************************');
        console.log('outgoingActivityId: ' + outgoingActivityId);
        console.log('outgoingFaultId: ' + outgoingFaultId);
        console.log('sparepartIdToConsume: ' + sparepartIdToConsume);
        console.log('consumptionTypeId: ' + consumptionTypeId);
        console.log('consumeAmount: ' + consumeAmount);
        console.log('machineId: ' + machineId);
        console.log('consumeNote: ' + consumeNote);
        console.log('UserId: ' + UserId);
        console.log('SparePartStockId: ' + SparePartStockId);
        console.log('SubstractedFromStock: ' + SubstractedFromStock);
        console.log('ConsumeAmountSubstracted: ' + ConsumeAmountSubstracted);
        console.log('ConsumeAmountDirect: ' + ConsumeAmountDirect);

        console.log('***************************');

        //$("#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.log(data.d);

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


        console.log(message);

        $("#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();
            console.log(navigateToOnNewConsumption);

            if (navigateToOnNewConsumption == 1) {
                console.log('New job. Job search screen.');
                self.jobCleanup();
                $.mobile.navigate("#page_jobsearch_onid", { role: "page" });
            }
            else {
                console.log('Another sparepart. Consumption screen.');
                $("#consumption_on_job_quantity").focus();
            }
        });

        $("#consumption_on_job_consumption_finished_popup_button1").unbind().click(function (event) {
            navigateToOnNewConsumption = 0;
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup_button2").unbind().click(function (event) {
            navigateToOnNewConsumption = 1;
            console.log(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("");
        console.log('Unable to register spare part consumption in datatbase.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.updatePredefinedConsumption = function (consumptionQtyToAdd) {

        console.log('Dummy request to update preexisting consumption');

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

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

        console.log('************************************************');
        console.log('Consumption id: ' + consumptionId);
        console.log('Consumption qty:' + consumptionQtyToAdd);
        console.log('Job id: ' + selectedJobId);
        console.log('User id: ' + UserId);
        console.log('Token: ' + current_session_token);
        console.log('************************************************');

        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) {
        var message = ReturnPhraseOnKey("consumption_on_job_dialogue_predefined_consumption_ok");
        var navigateToOnPredefinedConsumption = 0;

        console.log(message);

        $("#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();
            console.log(navigateToOnPredefinedConsumption);
            if (navigateToOnPredefinedConsumption == 1) {
                console.log('User selected to search on new job. Navigating to job search screen.');
                self.jobCleanup();
                $.mobile.navigate("#page_jobsearch_onid", { role: "page" });
            }
            else {
                $("#consumption_on_job_quantity").focus();
            }
        });

        $("#consumption_on_job_consumption_finished_popup_button1").unbind().click(function (event) {
            navigateToOnPredefinedConsumption = 0;
            console.log(navigateToOnPredefinedConsumption);
            $("#consumption_on_job_consumption_finished_popup").popup("close");
        });

        $("#consumption_on_job_consumption_finished_popup_button2").unbind().click(function (event) {
            navigateToOnPredefinedConsumption = 1;
            console.log(navigateToOnPredefinedConsumption);
            $("#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("");
        console.log('Unable to register spare part consumption in datatbase.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.validateConsumedQtyInput = function (inputValueToValidate) {
        console.log('In validation procedure');

        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();
        console.log(consumptionToRegister);
        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 () {
        console.log('sparepart cleanup');
        $("#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();
            console.log('box visible');
        }

        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';

        console.log('before focus');

        $("#consumption_on_job_sparepart_search_value").focus();
        console.log('after focus');
    }

    self.jobCleanup = function () {
        console.log('Nuking job selection information');
        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 consumptionOnJob = ConsumptionOnJob();

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


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

    $("#consumption_on_job_consume_button").click(function() {
        console.log('triggering through button');
        consumptionOnJob.consumptionTrigger();
    });

    $('#consumption_on_job_quantity').bind("commitConsumptionOnJob", function (e) {
        console.log('triggering through ENTER on keyboard');
        consumptionOnJob.consumptionTrigger();
    });


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

    $("#consumption_on_job_back_button").click(function () {
        $.mobile.navigate("#page_stores_functionselection", { role: "page" });


    });


});


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

    //$("#consumption_on_job_sparepart_search_value").show();
    //$("#consumption_on_job_sparepart_search_value").text("");
    //$("#consumption_on_job_sparepart_search").show();
    //$("#consumption_on_job_dynamic_content").hide();
    //$("#consumption_on_job_dynamic_content").empty();

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


    if (SessionTokenStatus == true) {

        consumptionOnJob.init();

        $("#consumption_on_job_sparepart_search").unbind().click(function (event) {
            console.log('pressing search spare part button');


            consumptionOnJob.checkForSparepartExistence();
        });

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

            console.log('pressing search spare part button');

            if (CONSUMPTION_SP_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                c1('consumptiononjob 1102 - toogling to camera');
                $("#consumption_on_job_camera_section").css("display", "block");
                $("#consumption_on_job_spare_part_search_box").css("display", "none");
                CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_BARCODE;
            }
            else if (CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_BARCODE) {
                c1('consumptiononjob 1108 - toogling to manual');
                $("#consumption_on_job_camera_section").css("display", "none");
                $("#consumption_on_job_spare_part_search_box").css("display", "block");
                CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            }
            else {
                return;
            }
        });

        $('#consumption_on_job_sparepart_search_value').unbind().keyup(function (e) {
            if (e.keyCode == 13) {
                consumptionOnJob.checkForSparepartExistence();
            }
        });

        //$("#consumption_on_job_add_sparepart").unbind().click(function () {
        //    $.mobile.navigate("#page_sparepartselect", { role: "page" });
        //});
    }
    else {
        helper.ForcedLogout();
    }

});

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