function AddConsumption() {

    var self = {};

    self.jobID = null;
    self.StockId = null;
    self.ActivityId = null;
    self.FaultId = null;
    self.ConsumeSparePartId = null;
    self.ConsumptionTypeId = 1;
    self.ConsumeAmount = 0;
    self.ConsumeNote = '';
    self.UserId = null
    self.SparePartStockId = null;
    self.Recorded = null;
    self.SubstractedFromStock = null;
    self.ConsumeAmountSubstracted = null;
    self.ConsumedOK = null;
    self.ConsumeMachineID = null;
    self.ConsumeAmountDirect = null;
    self.ConsumeFromHandheld = null;
    self.AccountID = null;


    self.ConsumptionQty = -1;


    self.RequestSparePartInfo = function () {
        var sparePartId = $.cookie("currently_selected_sparepartid");
        var sparePartNr = $.cookie("currently_selected_sparepartnumber");
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "sparepart_id": sparePartId, "session_token": current_session_token },
            success: self.SparePartInfoRequestSuccess,
            error: self.SparePartInfoRequestError,
            url: "RequestSparePartInfoOnSparePartId"
        });

        requester.ExecuteRequest();
    }



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


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

            $("#createnewconsumption_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#createnewconsumption_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#createnewconsumption_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
            });

            $("#createnewconsumption_generic_popup_button").unbind("click").click(function () {
                $("#createnewconsumption_generic_popup").popup("close");
            });

            $("#createnewconsumption_generic_popup").popup().popup("open");

        }
        else {


            var sparePartName = data.d.SparePartList[0].SparePartName;
            var sparePartNumber = data.d.SparePartList[0].SparePartNumber;

            var htmlSparePartDetails = "";


            htmlSparePartDetails = '<p><b>';
            htmlSparePartDetails += ReturnPhraseOnKey('addconsumption_sparepartname');
            htmlSparePartDetails += '<br></b>';
            htmlSparePartDetails += sparePartName;
            htmlSparePartDetails += '</p><p><strong>';
            htmlSparePartDetails += ReturnPhraseOnKey('addconsumption_sparepartnumber');
            htmlSparePartDetails += '</strong><br>';
            htmlSparePartDetails += sparePartNumber;
            htmlSparePartDetails += '</p>';

            $("#createnewconsumption_detail").empty();
            $("#createnewconsumption_detail").html(htmlSparePartDetails);
        }

    }

    self.SparePartInfoRequestError = function (data, status, xhr) {
        c1('addconsumption row 93: Unable to get spare part information.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }


    self.RequestSelectedStockInfo = function () {
        var sparePartStockId = $.cookie("stock_selected_for_new_consumption");


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

        requester.ExecuteRequest();
    }

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

        if (StoreSelectedSemaphore == STORE_SELECTED) {
            htmlStockInformationDetails = '<p><strong>';
            htmlStockInformationDetails += ReturnPhraseOnKey('addconsumption_store');
            htmlStockInformationDetails += '</strong>';
            htmlStockInformationDetails += storeNameToPresent;
            htmlStockInformationDetails += '</p>';
            htmlStockInformationDetails += '<p><strong>';
            htmlStockInformationDetails += ReturnPhraseOnKey('addconsumption_positionatstore');
            htmlStockInformationDetails += '</strong>';
            htmlStockInformationDetails += storePositionsToPresent;
            htmlStockInformationDetails += '</p>'
            htmlStockInformationDetails += '<p><br></p>';
        }



        $("#createnewconsumption_detail").append(htmlStockInformationDetails);

    }

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

    self.RegisterNewConsumption = function () {

        self.ActivityId = $.cookie("currently_selected_activity");
        var current_session_token = $.cookie("session_token");

        if (self.ActivityId == undefined) {
            self.ActivityId = 0;
        }
        self.FaultId = $.cookie("currently_selected_fault");
        if (self.FaultId == undefined) {
            self.FaultId = 0;
        }
        self.ConsumeSparePartId = $.cookie("currently_selected_sparepartid");
        self.ConsumptionTypeId = 1;
        self.ConsumeAmount = 0;
        self.ConsumeNote = '';
        self.UserId = $.cookie("user_id");
        self.SparePartStockId = $.cookie("stock_selected_for_new_consumption");
        self.ConsumeMachineID = $.cookie("currently_selected_machine");
        self.ConsumedOK = 1;

        var consumptionFromField = $("#createnewconsumption_quantity").val();

        if (StoreSelectedSemaphore == STORE_SELECTED) {
            self.SubstractedFromStock = 1;
            self.ConsumeAmountSubstracted = consumptionFromField;
            self.ConsumeAmountDirect = 0;

        }

        if (StoreSelectedSemaphore == STORE_NOT_SELECTED) {
            self.SubstractedFromStock = 0;
            self.ConsumeAmountSubstracted = 0;
            self.ConsumeAmountDirect = consumptionFromField;
        }



        var requester = new AjaxRequest({

            data: {
                "activityid": self.ActivityId, "faultid": self.FaultId, "sparepartid": self.ConsumeSparePartId, "consumptiontypeid": self.ConsumptionTypeId,
                "consumenote": self.ConsumeNote, "userid": self.UserId, "sparepartstockid": self.SparePartStockId, "substractedfromstock": self.SubstractedFromStock,
                "ammountsubstracted": self.ConsumeAmountSubstracted, "consumedok": self.ConsumedOK, "machinenumber": self.ConsumeMachineID, "consumeddirect": self.ConsumeAmountDirect,
                "session_token": current_session_token
            },
            success: self.CreateNewConsumptionSuccess,
            error: self.CreateNewConsumptionFailure,
            url: "RegisterNewConsumption"
        });

        requester.ExecuteRequest();

    }

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

        c_objects(data.d);

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

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

            $("#createnewconsumption_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e4('addconsumption row 234');
            });

            $("#createnewconsumption_generic_popup_button").unbind("click").click(function () {
                $("#createnewconsumption_generic_popup").popup("close");
            });

            $("#createnewconsumption_generic_popup").popup().popup("open");
        }
        else {
            if (JOB_HANDLE_MODE == FINISH_JOB) {

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

                c3('addconsumption row 249 - moving to finish job page');
            }
            else if (JOB_HANDLE_MODE == HANDLE_ACTIVITY) {

                $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
                c3('addconsumption row 254 - moving to handle consumption page (activity)');
            }
            else if (JOB_HANDLE_MODE == HANDLE_FAULT) {

                $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
                c3('addconsumption row 259- moving to handle consumption page (fault)');
            }


            //$(":mobile-pagecontainer").pagecontainer("change", "#page_finishjobwizard_1", { role: "page", reverse: false, changeHash: false });
            //e4('addconsumption row 245');
        }

    }

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

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

        c1('addconsumption row 252: Unable to register spare part consumption in datatbase.');

        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.ValidateAndCommitConsumption = function () {

        var validationTest = true;
        $("#createnewconsumption_errortext").hide();
        var wholeNumberRegEx = /^[1-9]\d*$/;
        var quantityToConsume = $("#createnewconsumption_quantity").val();
        if (quantityToConsume == '') {
            $("#createnewconsumption_errortext").text(ReturnPhraseOnKey('addconsumption_err_validnumber'));
            validationTest = false;
        }
        else if (!wholeNumberRegEx.test(quantityToConsume)) {
            $("#createnewconsumption_errortext").text(ReturnPhraseOnKey('addconsumption_err_positivenumbersonly'));
            validationTest = false;
        }
        else if (quantityToConsume == 0) {
            $("#createnewconsumption_errortext").text(ReturnPhraseOnKey('addconsumption_err_nozeroes'));
            validationTest = false;
        }

        if (validationTest) {
            self.RegisterNewConsumption();
        }
        else {
            $("#createnewconsumption_quantity").val("");
            $("#createnewconsumption_errortext").show();

        }
    }


    return self;

}

var addConsumption = AddConsumption();





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

    $('#createnewconsumption_quantity').bind("createConsumptionOnEnter", function (e) {
        addConsumption.ValidateAndCommitConsumption();
    });
    $('#createnewconsumption_quantity').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("createConsumptionOnEnter");
        }
    });

    //$("#createnewconsumption_backbutton").click(function () {
    //    $(":mobile-pagecontainer").pagecontainer("change", "#page_finishjobwizard_1", { role: "page", reverse: false, changeHash: false });
    //    e4('addconsumption row 309');
    //});


});

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

    if (SessionTokenStatus == true) {
        $("#createnewconsumption_errortext").hide();
        $("#createnewconsumption_quantity").focus();

        addConsumption.RequestSparePartInfo();
        addConsumption.RequestSelectedStockInfo();
    }
});

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

    if (SessionTokenStatus == true) {

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

            c5(previouspage_id);

            if (JOB_HANDLE_MODE == FINISH_JOB) {

                //$(":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 (JOB_HANDLE_MODE == HANDLE_ACTIVITY) {

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

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


        //*******************************************************
        //20200331 - Moved to pagebeforeshow event
        //$("#createnewconsumption_errortext").hide();
        //$("#createnewconsumption_quantity").focus();

        //addConsumption.RequestSparePartInfo();
        //addConsumption.RequestSelectedStockInfo();
        //******************************************************

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

        $("#createnewconsumption_commit").unbind().click(function () {
            addConsumption.ValidateAndCommitConsumption();
        });
    }
    else {
        helper.ForcedLogout();
    }
});