function Stockmanagementreplenishment() {

    var self = {};
    var current_machine = null;
    var current_userid = null;
    var current_sparepart_nr = null;
    var store_labels = null;
    var stock_data = null;


    self.requestSelectedStockLabels = function () {

        var requester = new AjaxRequest({
            data: {
                "stockid": CURRENT_SELECTED_STORE
            },
            success: self.StockLabelRequestSuccess,
            error: self.StockLabelRequestFailure,
            url: "RequestStoreLabels"
        });
        requester.ExecuteRequest();

    }

    self.StockLabelRequestSuccess = function (data, status, xhr) {
        store_labels = data.d;
    }

    self.StockLabelRequestFailure = function (data, status, xhr) {
        c1('stockmanagementreplenish row 30: Failed to retrieve spare part store labels. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.requestSparePartInfo = function () {
        current_sparepart_id = $.cookie("currently_selected_sparepartid");
        current_sparepart_number = $.cookie("currently_selected_sparepartnumber");
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: {
                "sparepart_id": current_sparepart_id,
                "sparepart_nr": current_sparepart_number,
                "store_id": CURRENT_SELECTED_STORE,
                "session_token": current_session_token
            },
            success: self.SparePartInfoRequestComplete,
            error: self.SparePartInfoRequestIncomplete,
            url: "RequestSparePartInformationForStockManagement"
        });
        requester.ExecuteRequest();

    }

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

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

            $("#stockmanagementreplenish_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e1('stockmanagementreplenish row 63');
            });

            $("#stockmanagementreplenish_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagementreplenish_generic_popup").popup("close");
            });

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

            //Update of spare part information
            console.log(data.d);
            stock_data = data.d.StockList.StockElementList;
            console.log(data.d.StockList.StockElementList);



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

            var htmlSparePartDetails = "";


            htmlSparePartDetails = '<p><b>';
            htmlSparePartDetails += ReturnPhraseOnKey('stockmanagementreplenish_sparepartname');


            htmlSparePartDetails += '<br></b>';
            htmlSparePartDetails += sparePartName;
            htmlSparePartDetails += '</p><p><strong>';
            htmlSparePartDetails += ReturnPhraseOnKey('stockmanagementreplenish_sparepartnumber');
            htmlSparePartDetails += '</strong><br>';
            htmlSparePartDetails += sparePartNumber;
            htmlSparePartDetails += '</p>';
            $("#stockmanagementreplenish_sparepartinfo").empty();
            $("#stockmanagementreplenish_sparepartinfo").html(htmlSparePartDetails);


            self.UpdateStockList(data.d.StockList.StockElementList);

        }

    }

    self.SparePartInfoRequestIncomplete = function (data, status, xhr) {
        c1('stockmanagementreplenish row 106: Failed to retrieve spare part information. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.requestStockReplenishment = function () {
        current_userid = $.cookie("user_id");
        var currently_selected_stockid = $("#stockmanagementreplenish_stockselect").val();
        var replenishWithQty = $("#stockmanagementreplenish_qty").val();
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: {
                "userid": current_userid,
                "stockid": currently_selected_stockid,
                "qtytoadd": replenishWithQty,
                "replenishmentreasonid": DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON,
                "session_token": current_session_token
            },
            success: self.StockReplenishmentRequestComplete,
            error: self.StockReplenishmentRequestIncomplete,
            url: "RequestStockReplenishment"
        });
        requester.ExecuteRequest();

    }

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

        function showCustomPopup() {

            $('#stockmanagementreplenish_info_popup').popup('open', { history: false });
            setTimeout(closeCustopPopup, 2000);
            
        };

        function closeCustopPopup() {
            $('#stockmanagementreplenish_info_popup').popup('close');
            try {
                $.mobile.popup.active = null;
                delete $.mobile.popup.active;
            } catch (e) { }

            //$.mobile.navigate("##page_sparepartselectinstore", { role: "page" });
            //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
            //console.log('back in step 1');
        }

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

            $("#stockmanagementreplenish_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e1('stockmanagementreplenish row 162');
            });

            $("#stockmanagementreplenish_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagementreplenish_generic_popup").popup("close");
            });

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

            //update stock qty info on screen
            $("#stockmanagementreplenish_qty_info").html(data.d.ValueToPass);

            //update localy stored stock information with new stock quantity
            var currently_selected_stockid = $("#stockmanagementreplenish_stockselect").val();
            var stockInStoreBeforeRefill = 0;
            jQuery.each(stock_data, function (i, stock_element) {
                if (stock_element.StockId == currently_selected_stockid) {
                    stockInStoreBeforeRefill = stock_element.StockInStore;
                    stock_element.StockInStore = data.d.ValueToPass;
                }
                return;
            });

            var popupMessage = '<H3>';
            popupMessage += ReturnPhraseOnKey('stockmanagementreplenish_replenishmessage_a');
            popupMessage += $("#stockmanagementreplenish_qty").val();
            popupMessage += ReturnPhraseOnKey('stockmanagementreplenish_replenishmessage_b');
            popupMessage += '<br>';
            popupMessage += ReturnPhraseOnKey('stockmanagementreplenish_replenishmessage_c');
            popupMessage += data.d.ValueToPass;
            popupMessage += '</H3>';

            $("#stockmanagementreplenish_notification").html(popupMessage);
            if ($('#stockmanagementreplenish_notification').is(":hidden")) {
                $('#stockmanagementreplenish_notification').show();
            }

            if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                setTimeout(
                    function () {
                        $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
                        c1('stockmanagementreplenish row 206 - auto-navigating to manual spare part search after completed replenish');
                    },
                3000);
            }
            else if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                setTimeout(
                    function () {
                        $(":mobile-pagecontainer").pagecontainer("change", "#page_scantest", { role: "page", reverse: false, changeHash: true });
                        e1('stockmanagementreplenish row 215 - auto-navigating to bardode scan spare part search after completed replenish');
                    },
                3000);

            }

            //$('#stockmanagementreplenish_info_popup').html(popupMessage);

            //showCustomPopup();

            //var interval = setInterval(function () {
            //    $('#stockmanagementreplenish_info_popup').popup('open', { history: false });
            //    var intervalClose = setInterval(function () {
            //        $('#stockmanagementreplenish_info_popup').popup('close');
            //        clearInterval(intervalClose);
            //    }, 2000);
            //    clearInterval(interval);
            //}, 1);
        }

        //reset input field
        $("#stockmanagementreplenish_qty").val("");



    }

    

    self.StockReplenishmentRequestIncomplete = function (data, status, xhr) {
        c1('stockmanagementreplenish row 241: Failed to complete requested spare part stock replenishment. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }


    self.UpdateStockList = function (stocklist) {

        console.log(stocklist);

        var sparePartStoreElements = '';
        jQuery.each(stocklist, function () {
            sparePartStoreElements += '<option value="'
            sparePartStoreElements += this.StockId;
            sparePartStoreElements += '">';
            sparePartStoreElements += this.StockStore;
            if ((this.StockPositionI.length == 0) && (this.StockPositionII.length == 0) && (this.StockPositionIII.length == 0)) {
                sparePartStoreElements += ' - ';
                sparePartStoreElements += ReturnPhraseOnKey('stockmanagementreplenish_positionunspecified');
            }
            else {
                if (this.StockPositionI.length > 0) {
                    sparePartStoreElements += ' - ';
                    sparePartStoreElements += this.StockPositionI;
                }
                if (this.StockPositionII.length > 0) {
                    sparePartStoreElements += ' - ';
                    sparePartStoreElements += this.StockPositionII;
                }
                if (this.StockPositionIII.length > 0) {
                    sparePartStoreElements += ' - ';
                    sparePartStoreElements += this.StockPositionIII;
                }
            }
            sparePartStoreElements += '</option>';
        });


        $("#stockmanagementreplenish_stockselect").html(sparePartStoreElements);
        $("#stockmanagementreplenish_stockselect").selectmenu().selectmenu("refresh");
        $("#stockmanagementreplenish_stockselect").trigger('change');

        if (stocklist.length == 1) {
            $("#stockmanagementreplenish_stockselection_section").hide();
        }
        else {
            if ($('#stockmanagementreplenish_stockselection_section').is(":hidden")) {
                $('#stockmanagementreplenish_stockselection_section').show();
            }
        }
    }

    self.updateStockInformation = function () {
        var selectedStock = $("#stockmanagementreplenish_stockselect").val();
        jQuery.each(stock_data, function (i, stock_element) {
            if (stock_element.StockId == selectedStock) {

                $("#stockmanagementreplenish_storename").html(stock_element.StockStore);

                if (stock_element.StockPositionI.length > 0) {
                    var area_text = store_labels.StoreArea + ' ' + stock_element.StockPositionI;
                    $("#stockmanagementreplenish_areainfo").html(area_text);
                }
                else {
                    $("#stockmanagementreplenish_areainfo").html(ReturnPhraseOnKey('global_unspecified'));
                }
                if (stock_element.StockPositionII.length > 0) {
                    var section_text = store_labels.StoreSection + ' ' + stock_element.StockPositionII;
                    $("#stockmanagementreplenish_sectioninfo").html(section_text);
                }
                else {
                    $("#stockmanagementreplenish_sectioninfo").html(ReturnPhraseOnKey('global_unspecified'));
                }
                if (stock_element.StockPositionIII.length > 0) {
                    var position_text = store_labels.StorePosition + ' ' + stock_element.StockPositionIII;
                    $("#stockmanagementreplenish_positioninfo").html(position_text);
                }
                else {
                    $("#stockmanagementreplenish_positioninfo").html(ReturnPhraseOnKey('global_unspecified'));
                }

                $("#stockmanagementreplenish_qty_info").html(stock_element.StockInStore);
                $("#stockmanagementreplenish_min_qty_info").html(stock_element.StockInStore);

            }
            return;
        });
    }

    self.ValidateConsumption = function () {

        var validationTest = true;
        $("#stockmanagementreplenish_errormessage").hide();
        var wholeNumberRegEx = /^[1-9]\d*$/;
        var quantityToValidate = $("#stockmanagementreplenish_qty").val();
        if (quantityToValidate == '') {
            $("#stockmanagementreplenish_errormessage").text(ReturnPhraseOnKey('stockmanagementadjust_err_validnumber'));
            validationTest = false;
        }
        else if (!wholeNumberRegEx.test(quantityToValidate)) {
            $("#stockmanagementreplenish_errormessage").text(ReturnPhraseOnKey('stockmanagementadjust_err_positivenumbersonly'));
            validationTest = false;
        }


        if (validationTest == false) {
            $("#stockmanagementreplenish_errormessage").show();
        }

        return validationTest;
    }



    return self;
}

var stockManagementReplenishment = Stockmanagementreplenishment();




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

    $('#stockmanagementreplenish_qty').bind("triggerCommitReplenishment", function (e) {
        stockManagementReplenishment.requestStockReplenishment();
        e1('stockmanagementreplenish row 368');
    });

    $('#stockmanagementreplenish_qty').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("triggerCommitReplenishment");
        }
        e1('stockmanagementreplenish row 375');
    });

    $("#stockmanagementreplenish_stockselect").change(function () {
        stockManagementReplenishment.updateStockInformation();
        e1('stockmanagementreplenish row 380');
    });

    $("#stockmanagementreplenish_commit").click(function () {
        if (stockManagementReplenishment.ValidateConsumption()) {
            stockManagementReplenishment.requestStockReplenishment();
            e1('stockmanagementreplenish row 386');
        }
    });

    $("#stockmanagementreplenish_backbutton").click(function () {

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

        if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
            c1('stockmanagementreplenish row 396 - moving back to manual spare part search');
        }
        else if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
            SCAN_PAGE_TARGET = SCAN_SPAREPART;
            $(":mobile-pagecontainer").pagecontainer("change", "#page_scantest", { role: "page", reverse: false, changeHash: true });
            c1('stockmanagementreplenish row 400 - moving back to barcode spare part search');
        }

    });

    //$("#stockmanagementreplenish_info_popup").on("popupafterclose", function (event, ui) {

    //    event.preventDefault();
    //    console.log('hail mary in replenish');
    //    //$.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
    //    $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
    //});

});


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

    if (SessionTokenStatus == true) {
        $("#stockmanagementreplenish_errormessage").hide();
        $("#stockmanagementreplenish_notification").hide();
        $("#stockmanagementreplenish_notification").html("");

        //stockManagementReplenishment.requestSelectedStockLabels();
        //stockManagementReplenishment.requestSparePartInfo();
    }
    else { helper.ForcedLogout(); }


});

//20200401 - moved to pagebeforeshow event

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

//    //$("#stockmanagementreplenish_info_popup").on("popupafterclose", function (event, ui) {

//    //    event.preventDefault();
//    //    console.log('hail mary in replenish');
//    //    //$.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
//    //    $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
//    //});
    




    if (SessionTokenStatus == true) {
//        $("#stockmanagementreplenish_errormessage").hide();
//        $("#stockmanagementreplenish_notification").hide();
//        $("#stockmanagementreplenish_notification").html("");

        stockManagementReplenishment.requestSelectedStockLabels();
        stockManagementReplenishment.requestSparePartInfo();
    }
    else { helper.ForcedLogout(); }


});

$(document).on("pagehide", "#page_stockmanagementreplenish", function () {
    $("#stockmanagementreplenish_notification").hide();
    $("#stockmanagementreplenish_notification").html("");
    $("#stockmanagementadjust_qty").val("");
});

