function ModifyExistingConsumption() {

    var self = {};

    self.tmp = null;
    self.selection = {};
    self.UserId = null;
    self.jobID = null;
    self.ConsumptionInfo = null;
    self.ConsumptionQty = -1;
    self.sourcePage = '';


    self.RequestConsumptionInfo = function () {
        var consumptionId = $.cookie("currently_selected_consumptionid");
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "consumptionid": consumptionId, "session_token": current_session_token },
            success: self.ConsumptionInfoRequestSuccess,
            error: self.ConsumptionInfoRequestError,
            url: "RequestConsumptionInformation"
        });

        requester.ExecuteRequest();
    }

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

        if (data.d.HasContent == true && data.d.SessionTokenValid == true) {

            self.ConsumptionInfo = data.d;

            $("#sparepartconsumption_details").empty();
            var receivedStoreName = 'not selected';
            var receivedPositions = 'not selected';
            if (self.ConsumptionInfo.StoreName != '') {
                receivedStoreName = self.ConsumptionInfo.StoreName;
                if (self.ConsumptionInfo.StoreArea != '') {
                    receivedPositions = self.ConsumptionInfo.StoreArea;

                    if (self.ConsumptionInfo.StoreSection != '') {
                        receivedPositions += ' / ';
                        receivedPositions += self.ConsumptionInfo.StoreSection;
                    }
                    if (self.ConsumptionInfo.StorePostion != '') {
                        receivedPositions += ' / ';
                        receivedPositions += self.ConsumptionInfo.StorePosition;
                    }
                }
            }

            var consumptionInformationHTML = '';
            consumptionInformationHTML += '<p><b>';
            consumptionInformationHTML += ReturnPhraseOnKey('modifyconsumption_sparepartname');
            consumptionInformationHTML += '<br></b>';
            consumptionInformationHTML += self.ConsumptionInfo.SparePartName;
            consumptionInformationHTML += '</p><p><strong>';
            consumptionInformationHTML += ReturnPhraseOnKey('modifyconsumption_sparepartno');
            consumptionInformationHTML += '</strong><br>';
            consumptionInformationHTML += self.ConsumptionInfo.SparePartNumber;
            consumptionInformationHTML += '</p><p><strong>';
            consumptionInformationHTML += ReturnPhraseOnKey('modifyconsumption_store');
            consumptionInformationHTML += '</strong> ';
            consumptionInformationHTML += receivedStoreName;
            consumptionInformationHTML += '</p><p><strong>';
            consumptionInformationHTML += ReturnPhraseOnKey('modifyconsumption_positionatstore');
            consumptionInformationHTML += '</strong> ';
            consumptionInformationHTML += receivedPositions;
            consumptionInformationHTML += '<br></p><p><b> ';
            consumptionInformationHTML += ReturnPhraseOnKey('modifyconsumption_qtytoconsume');
            consumptionInformationHTML += '</b>';
            consumptionInformationHTML += self.ConsumptionInfo.ScheduledConsumption;
            consumptionInformationHTML += ' / '
            consumptionInformationHTML += self.ConsumptionInfo.ActualConsumption;
            consumptionInformationHTML += '</p>'

            $("#sparepartconsumption_details").html(consumptionInformationHTML);

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

            $("#sparepartconsumption_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#sparepartconsumption_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#sparepartconsumption_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e3('modifyexistingconsumption row 88');
            });

            $("#sparepartconsumption_generic_popup_button").unbind("click").click(function () {
                $("#sparepartconsumption_generic_popup").popup("close");
            });

            $("#sparepartconsumption_generic_popup").popup().popup("open");
        }
        else if (data.d.HasContent == false) {
            c1("modifyexistingconsumption row 97: No info available for this machine");
        }
    }

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

        c1('modifyexistingconsumption row 104: Failed to retrieve spare part consumption information. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.CommitConsumption = function () {

        var consumptionId = $.cookie("currently_selected_consumptionid");
        var selectedJobId = $.cookie("currently_selected_jobid");
        var current_session_token = $.cookie("session_token");

        //console.log('********************');
        //console.log(consumptionId);
        //console.log(self.ConsumptionQty);
        //console.log(self.UserId);
        //console.log(selectedJobId);
        //console.log('********************');


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

        requester.ExecuteRequest();
    }


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

        $("#sparepartconsumption_quantity").val("");

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

            $("#sparepartconsumption_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e3('modifyexistingconsumption row 145');
            });

            $("#sparepartconsumption_generic_popup_button").unbind("click").click(function () {
                $("#sparepartconsumption_generic_popup").popup("close");
            });

            $("#sparepartconsumption_generic_popup").popup().popup("open");
        }
        else {
            //$.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
            //e3('modifyexistingconsumption row 156');


            c5('Entry point was ' + self.sourcePage);

            if (self.sourcePage == "page_finishjobwizard_1") {

                //$(":mobile-pagecontainer").pagecontainer("change", "#page_finishjobwizard_1", { role: "page", reverse: false, changeHash: false });
                $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });

                c6('consumption commited, moving back to finish job wizard page');
            }
            else if (self.sourcePage == "page_handle_sp_consumption") {

                $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
                c6('consumption commited, moving back to handle spare parts for job page');
            }
        }
    }

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

        $("#sparepartconsumption_quantity").val("");
        //alert('Consumption info failed to be generated!');
        c1('modifyexistingconsumption row 161: Failed to save spare part consumption. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.ValidateAndCommitConsumption = function () {

        var validationTest = true;
        $("#sparepartconsumption_errortext").hide();
        var wholeNumberRegEx = /^[1-9]\d*$/;
        var quantityToConsume = $("#sparepartconsumption_quantity").val();
        if (quantityToConsume == '') {
            $("#sparepartconsumption_errortext").text(ReturnPhraseOnKey('modifyconsumption_err_validnumber'));
            validationTest = false;
        }
        else if (!wholeNumberRegEx.test(quantityToConsume)) {
            $("#sparepartconsumption_errortext").text(ReturnPhraseOnKey('modifyconsumption_err_positivenumbersonly'));
            validationTest = false;
        }
        else if (quantityToConsume == 0) {
            $("#sparepartconsumption_errortext").text(ReturnPhraseOnKey('modifyconsumption_err_nozeroes'));
            validationTest = false;
        }

        if (validationTest) {

            self.ConsumptionQty = quantityToConsume;
            self.CommitConsumption();
            $("#sparepartconsumption_quantity").val("");

        }
        else {

            $("#sparepartconsumption_quantity").val("");
            $("#sparepartconsumption_errortext").show();

        }
    }

    return self;

}

var modifyExistingConsumption = ModifyExistingConsumption();


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

    modifyExistingConsumption.sourcePage = data.prevPage.attr('id');    

    if (JOB_HANDLE_MODE == FINISH_JOB) {
        $("#sparepartconsumption_header").html(ReturnPhraseOnKey('sparepartconsumption_mainheader'));
    }
    else {
        $("#sparepartconsumption_header").html(ReturnPhraseOnKey('modifyconsumption_edit_consumption_header'));
    }

    modifyExistingConsumption.RequestConsumptionInfo();
});


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

    $('#sparepartconsumption_quantity').bind("modifyConsumptionOnEnter", function (e) {
        modifyExistingConsumption.ValidateAndCommitConsumption();
        e3('modifyexistingconsumption row 214');
        
    });

    $('#sparepartconsumption_quantity').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("modifyConsumptionOnEnter");
            e3('modifyexistingconsumption row 221');
        }
    });


});


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

    if (SessionTokenStatus == true) {
        $("#sparepartconsumption_errortext").hide();

        $("#sparepartconsumption_back_button").unbind().click(function () {
            var previouspage_id = data.prevPage.attr('id');

            c5(previouspage_id);

            if (previouspage_id == "page_finishjobwizard_1") {

                //$(":mobile-pagecontainer").pagecontainer("change", "#page_finishjobwizard_1", { role: "page", reverse: false, changeHash: false });
                $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });

                e3('modifyexistingconsumption row 236');
            }
            else if (previouspage_id == "page_handle_sp_consumption") {

                $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
                e3('modifyexistingconsumption row 236');
            }
        });

        //***************************************************
        //20200401 -  moved to pagebeforeshow event

        //modifyExistingConsumption.RequestConsumptionInfo();
        //***************************************************

        modifyExistingConsumption.UserId = $.cookie("user_id");

        $("#sparepartconsumption_commit").unbind().click(function () {

            modifyExistingConsumption.ValidateAndCommitConsumption();

        });
    }
    else {
        helper.ForcedLogout();
    }



});