function ConsumptionToAccount() {

    var self = {};
    self.selectedSparepartNo = '';
    self.selectedSparepartId = '';
    self.selectedSparepartName = '';
    self.selectedStockId = '';
    self.AvailableStockList = '';

    self.init = function () {
        self.setSelectedStoreInfo();
        $("#consumption_to_account_sparepart_search_value").focus();
    };

    self.setSelectedStoreInfo = function () {
        var requester = new AjaxRequest({
            data: {},
            success: function (data, status, xhr) {
                jQuery.each(data.d.AccountsList, function () {
                    if (this.AccountID == SELECTED_ACCOUNT) {
                        var accountInfoText = '<h3>' + ReturnPhraseOnKey("consumption_to_account_details_header") + '<br>' + this.AccountName + '</h3>';
                        $("#consumption_to_account_basic_info").html(accountInfoText);
                    }
                });
            },
            error: function (request, status, error) {
                c1('consumptiontoaccout row 24: Unable to retrieve stock change reason list from database.');
                DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
            },
            url: "RequestAccountList"
        });
        requester.ExecuteRequest();

    }

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


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

        if (consumption_to_account_search_param == "") {
            return;
        }
        else {

            var requester = new AjaxRequest({
                data: { "sparepart_search_param": consumption_to_account_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) {


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


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

            $("#consumption_to_account_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#consumption_to_account_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#consumption_to_account_generic_popup_button").unbind("click").click(function () {
                $("#consumption_to_account_generic_popup").popup("close");
            });

            $("#consumption_to_account_generic_popup").popup().popup("open");
        }
        else if (sparePartPresent == false) {
            $("#consumption_to_account_sparepart_errormessage").text(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
            $("#consumption_to_account_sparepart_errormessage").show();
            $("consumption_to_account_sparepart_search_value").focus();
        }

        else if (sparePartPresent == true) {


            $.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) {
        c1('consumptiontoaccount row 109: Failed to confirm spare part search results. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

    self.LookupSparePartList = function () {
        var sparepart_search_param = $("#consumption_to_account_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");


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

    self.resetSearchResults = function () {

        $("#consumption_to_account_dynamic_content").hide();
        $("#consumption_to_account_new_search2").off();
        $("#consumption_to_account_dynamic_content").empty();
        $("#consumption_to_account_sparepart_search_value").val("");
        $("#consumption_to_account_spare_part_search_box").show();
        $("#consumption_to_account_sparepart_search_value").focus();
    }

    self.attachEventToSparePartList = function () {


        $('#consumption_to_account_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) {

        var listToShow = '<b>';
        listToShow += ReturnPhraseOnKey("consumption_to_account_search_result");
        listToShow += '</b><br><ul class="listview_default_class" id="consumption_to_account_sparepart_list" data-role="listview" data-inset="true" data-divider-theme="b">'
        var listData = data.d.SparePartList;
        var listDataLength = listData.length;


        if (listDataLength == 0) {
            $("#consumption_to_account_sparepart_errormessage").text(ReturnPhraseOnKey("consumption_to_account_error_msg_no_spareparts_with_stocks"));
            $("#consumption_to_account_sparepart_errormessage").show();
        }
        else if (listDataLength == 1) {
            self.selectedSparepartName = listData[0].SparePartName;
            self.selectedSparepartNo = listData[0].SparePartNumber;
            self.selectedSparepartId = listData[0].SparePartId;

            $("#consumption_to_account_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_to_account_new_search2"  href="#" data-role="button"  data-theme="b" data-translatetext="consumption_to_account_new_search_button">Search again</a>'

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

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

            self.attachEventToSparePartList();

            $("#consumption_to_account_spare_part_search_box").hide();
            $("#consumption_to_account_dynamic_content").trigger("create");
            $("#consumption_to_account_dynamic_content").show();
        }

    };

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

    self.attachEventToSparePartStockList = function () {


        $('#consumption_to_account_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.FindSparePartStores = function (selectedSparepartId) {

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

        var requester = new AjaxRequest({
            data: { "sparepartid_param": selectedSparepartId.toString(), "session_token": current_session_token },
            success: self.FindSparePartStoresRequestComplete,
            error: self.FindSparePartStoresIncomplete,
            url: "RequestSparePartStockListOnSparepartId"
        });
        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_to_account_dynamic_content").hide();
        $("#consumption_to_account_dynamic_content").empty();


        if (stockListLength == 1) {
            self.RequestSelectedStockInfo(self.AvailableStockList[0].StockId);
        }
        else {

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

            var stockListHTML = sparepartInfoSection + '<br/><br/><ul id="consumption_to_account_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>';

            /* Create list of stocks belonging to spare part */

            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_to_account_sp_info_section").html(sparepartInfoSection);
            $("#consumption_to_account_dynamic_content").html(stockListHTML);
            $("#consumption_to_account_dynamic_content").trigger("create");
            $("#consumption_to_account_dynamic_content").show();

            self.attachEventToSparePartStockList();
        }

        
    }

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

    self.RequestSelectedStockInfo = function (stockIdToDisplay) {
        self.selectedStockId = stockIdToDisplay;

        var requester = new AjaxRequest({
            data: { "stockid": stockIdToDisplay },
            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 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_to_account_sparepartinfo_label') + '</td></tr>';
        htmlStockInformationDetails += '<tr><td>' + self.selectedSparepartName + ' / ' + self.selectedSparepartNo + '</td></tr>';

        htmlStockInformationDetails += '<tr><td class="label" >' + ReturnPhraseOnKey('consumption_to_account_sparepartinfo_store');
        if (self.selectedStockPredefined) {
            htmlStockInformationDetails += '<span style="font-weight: bold; margin-left: 5%; text-shadow:none; color:khaki">';
            htmlStockInformationDetails += ReturnPhraseOnKey('consumption_to_account_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_to_account_positionatstore') + '</td></tr>';
        htmlStockInformationDetails += '<tr><td>' + storePositionsToPresent + '</td></tr>';
        htmlStockInformationDetails += '</table>';

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

        $("#consumption_to_account_consumption_section").css("display", "block");
        $("#consumption_to_account_quantity").focus();
    };

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

    self.validateConsumedQtyInput = function (inputValueToValidate) {

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


        var validationTest = true;

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

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

        if (validationTest == false) {
            $("#consumption_to_account_quantity").val("");
            $("#consumption_to_account_quantity").focus();
            $("#consumption_to_account_sparepart_errormessage").show();

        }

        return validationTest;
    }

    self.commitConsumptionOnAccount = function () {

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

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

            var outgoingSparepartId = self.selectedSparepartId;
            var outgoingConsumptionTypeId = '1'; //Current standard consumption from PM5 database. Function could be extended to allowing user to select specific type for consumptions directly on account.
            var outgoingStockId = self.selectedStockId;
            var outgoingSubstractedFromStock = '1';
            //consumption amount is fetched from consumptionToRegister
            var outgoingConsumedOK = '1';

            var requester = new AjaxRequest({
                data: {
                        "sparepartid": outgoingSparepartId,
                        "consumptiontypeid": outgoingConsumptionTypeId,
                        "consumenote": '',
                        "userid": $.cookie("user_id"),
                        "sparepartstockid": outgoingStockId,
                        "substractedfromstock": outgoingSubstractedFromStock,
                        "ammountsubstracted": consumptionToRegister,
                        "consumedok": outgoingConsumedOK,
                        "accountid": SELECTED_ACCOUNT,
                        "session_token": $.cookie("session_token")
                },
                success: self.CommitConsumptionToAccountSuccess,
                error: self.CommitConsumptionToAccountFailure,
                url: "RegisterConsumptionDirectlyOnAccount"
            });

            requester.ExecuteRequest();
        }               
    }

    self.CommitConsumptionToAccountSuccess = function (data, status, xhr) {
        var message = ReturnPhraseOnKey("consumption_to_account_dialogue_consumption_ok");
        var navigateToSparepartMenu = 0;

        //console.log(message);

        $("#consumption_to_account_consumption_finished_popup_header").html(message);
        $("#consumption_to_account__consumption_finished_popup_text").html(message);

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

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

            self.cleanup();
            if (navigateToSparepartMenu == 1) {
                $.mobile.navigate("#page_stores_functionselection", { role: "page" });
                e2('consumptiononaccount row 468');
            }
            else {
                $("#consumption_to_account_quantity").focus();
            }
        });

        $("#consumption_to_account_consumption_finished_popup_button1").unbind().click(function (event) {
            navigateToSparepartMenu = 0;
            $("#consumption_to_account_consumption_finished_popup").popup("close");
        });

        $("#consumption_to_account_consumption_finished_popup_button2").unbind().click(function (event) {
            navigateToSparepartMenu = 1;
            $("#consumption_to_account_consumption_finished_popup").popup("close");
        });

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

    self.CommitConsumptionToAccountFailure = function (data, status, xhr) {
        $("#consumption_to_account_quantity").val("");
        c1('consumptiontoaccount row 491: Unable to register spare part consumption in datatbase.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.cleanup = function () {
        $("#consumption_to_account_sparepart_search_value").show();
        $("#consumption_to_account_sparepart_search_value").val("");
        $("#consumption_to_account_sparepart_search").show();
        $("#consumption_to_account_dynamic_content").hide();
        $("#consumption_to_account_dynamic_content").empty();
        $("#consumption_to_account_consumption_section").hide();
        $("#consumption_to_account_quantity").val("");
        if ($("#consumption_to_account_spare_part_search_box").is(":hidden")) {
            $("#consumption_to_account_spare_part_search_box").show();
        }

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

        $("#consumption_to_account_sparepart_errormessage").text("");
        $("#consumption_to_account_sparepart_errormessage").hide();
        self.selectedSparepartNo = '';
        self.selectedSparepartId = '';
        self.selectedSparepartName = '';
        self.AvailableStockList = '';
        self.selectedStockId = null;
        self.selectedMachineId = null;
  
        $("#consumption_to_account_sparepart_search_value").focus();
    }

    return self;

}

var consumptionToAccount = ConsumptionToAccount();

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


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

    $("#consumption_to_account_change_account_button").click(function () {
        $(":mobile-pagecontainer").pagecontainer("change", "#page_consumption_account_select", { role: "page", reverse: false, changeHash: true });
        //$.mobile.navigate("#page_sparepartstoreselect", { role: "page" });
        e2('consumptiononaccount row 538');
    })

    $('#consumption_to_account_quantity').bind("commitConsumptionToAccount", function (e) {
        consumptionToAccount.commitConsumptionOnAccount();
        e2('consumptiononaccount row 543');
    });


    $('#consumption_to_account_quantity').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("commitConsumptionToAccount");
            e2('consumptiononaccount row 550');
        }
    });

    $("#consumption_to_account_consume_button").click(function () {
        consumptionToAccount.commitConsumptionOnAccount();
        e2('consumptiononaccount row 556');
    });



});

$(document).on("pagebeforeshow", "#page_consumption_to_account", function (e) {
    if (SessionTokenStatus == true) {
        consumptionToAccount.init();
    }

});


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

    if (SessionTokenStatus == true) {

        //20200331 - moved to pagebeforeshow event
        //*****************************************
        //consumptionToAccount.init();
        //*****************************************

        $("#consumption_to_account_sparepart_search").unbind().click(function (event) {
            consumptionToAccount.checkForSparepartExistence();
        });

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

    }
    else {
        helper.ForcedLogout();
    }

});

$(document).on("pagehide", "#page_consumption_to_account", function () {
    consumptionToAccount.cleanup();
});