function Stockmanagementadjustment() {

    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('stockmanagementadjust 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" });
            $("#stockmanagementadjust_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#stockmanagementadjust_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#stockmanagementadjust_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagementadjust_generic_popup").popup("close");
            });

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

            //Update of spare part information
            stock_data = 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('stockmanagementadjust_sparepartname');
            htmlSparePartDetails += '<br></b>';
            htmlSparePartDetails += sparePartName;
            htmlSparePartDetails += '</p><p><strong>';
            htmlSparePartDetails += ReturnPhraseOnKey('stockmanagementadjust_sparepartnumber');
            htmlSparePartDetails += '</strong><br>';
            htmlSparePartDetails += sparePartNumber;
            htmlSparePartDetails += '</p>';
            $("#stockmanagementadjust_sparepartinfo").empty();
            $("#stockmanagementadjust_sparepartinfo").html(htmlSparePartDetails);


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

        }

    }

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

    self.requestStockAdjustment = function () {
        current_userid = $.cookie("user_id");
        var currently_selected_stockid = $("#stockmanagementadjust_stockselect").val();
        var adjustToQty = $("#stockmanagementadjust_qty").val();
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: {
                "userid": current_userid,
                "stockid": currently_selected_stockid,
                "adjustedstockquantity": adjustToQty,
                "adjustmentreasonid": DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON,
                "session_token": current_session_token
            },
            success: self.StockAdjustmentRequestComplete,
            error: self.StockAdjustmentRequestIncomplete,
            url: "RequestStockAdjustment"
        });
        requester.ExecuteRequest();

    }

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

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

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

            $("#stockmanagementadjust_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagementadjust_generic_popup").popup("close");
            });

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

            var stockInStoreBeforeAdjust = 0;

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

            //update localy stored stock information with new stock quantity
            var currently_selected_stockid = $("#stockmanagementadjust_stockselect").val();

            jQuery.each(stock_data, function (i, stock_element) {
                if (stock_element.StockId == currently_selected_stockid) {
                    stockInStoreBeforeAdjust = stock_element.StockInStore;
                    stock_element.StockInStore = data.d.ValueToPass;
                }
                return;
            });

            var popupMessage = '<H3>';
            popupMessage += ReturnPhraseOnKey('stockmanagementadjust_stockadjustedmessage_a');
            popupMessage += stockInStoreBeforeAdjust;
            popupMessage += ReturnPhraseOnKey('stockmanagementadjust_stockadjustedmessage_b');;
            popupMessage += data.d.ValueToPass;
            popupMessage += '</H3>';

            $("#stockmanagementadjust_notification").html(popupMessage);

            if ($('#stockmanagementadjust_notification').is(":hidden")) {
                $('#stockmanagementadjust_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 });
                        e5('stockmanagementadjust row 188 - autonavigating to manual spare part search after successful stock adjustment');
                    },
                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 });
                        e5('stockmanagementadjust row 196 - autonavigating to barcode spare part search after successful stock adjustment');
                    },
                3000);

            }

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

            //$("#stockmanagementadjust_info_popup").off().on("popupafterclose", function (event, ui) {
            //    $.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
            //});

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

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



    }

    self.StockAdjustmentRequestIncomplete = function (data, status, xhr) {
        c1('stockmanagementadjust row 221: Failed to complete requested spare part stock adjustment. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }


    self.UpdateStockList = function (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('stockmanagementadjust_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>';
        });


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

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

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

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

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

                $("#stockmanagementadjust_qty_info").html(stock_element.StockInStore);
                $("#stockmanagementadjust_min_qty_info").html(stock_element.StockInStore);

            }
            return;
        });
    }

    self.ValidateConsumption = function () {

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


        //Hack to bypass regex check when stock adjustment and inserted value == 0

        if (quantityToValidate == 0) {
            validationTest = true;
        }

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

        return validationTest;
    }



    return self;
}

var stockManagementAdjustment = Stockmanagementadjustment();




$(document).one("pageshow", "#page_stockmanagementadjust", function (e) {
    $('#stockmanagementadjust_qty').bind("triggerCommitAdjustment", function (e) {
        stockManagementAdjustment.requestStockAdjustment();
        e5('stockmanagementadjust row 353');
    });

    $('#stockmanagementadjust_qty').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("triggerCommitAdjustment");
        }
        e5('stockmanagementadjust row 360');
    });

    $("#stockmanagementadjust_stockselect").change(function () {
        stockManagementAdjustment.updateStockInformation();
        e5('stockmanagementadjust row 365');
    });

    $("#stockmanagementadjust_commit").click(function () {
        if (stockManagementAdjustment.ValidateConsumption()) {
            stockManagementAdjustment.requestStockAdjustment();
            e5('stockmanagementadjust row 371');
        }
    });

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

        if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselectinstore", { role: "page", reverse: false, changeHash: true });
            c5('stockmanagementadjust row 379 - 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 });
            c5('stockmanagementadjust row 383 - moving back to barcode spare part search');
        }

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



    

});

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

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


    if (SessionTokenStatus == true) {
        $("#stockmanagementadjust_errormessage").hide();
        $("#stockmanagementadjust_notification").hide();
        $("#stockmanagementadjust_notification").html("");

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


});


//20200401 - moved to pagebeforeshow event

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

//    $("#stockmanagementadjust_qty").focus();
    

    if (SessionTokenStatus == true) {
//        $("#stockmanagementadjust_errormessage").hide();
//        $("#stockmanagementadjust_notification").hide();
//        $("#stockmanagementadjust_notification").html("");

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


});

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

