function Stockmanagement() {

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

    self.setNavBar = function () {

        if (SELECTED_SPAREPART_JOB_TYPE == NO_STOCK_JOB_TYPE_SELECTION) {
            $("#stockmanagement_addtostock").trigger('click');
        }
        else if (SELECTED_SPAREPART_JOB_TYPE == STOCK_ADJUSTMENT) {
            $("#stockmanagement_adjuststock").trigger('click');
        }
        else if (SELECTED_SPAREPART_JOB_TYPE == STOCK_REPLENISHMENT) {
            $("#stockmanagement_addtostock").trigger('click');
        }

    }

    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('stockmanagement row 43: 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" });
            $("#stockmanagement_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#stockmanagement_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#stockmanagement_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagement_generic_popup").popup("close");
            });

            $("#stockmanagement_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('stockmanagement_sparepartname');
            htmlSparePartDetails += '<br></b>';
            htmlSparePartDetails += sparePartName;
            htmlSparePartDetails += '</p><p><strong>';
            htmlSparePartDetails += ReturnPhraseOnKey('stockmanagement_sparepartnumber');
            htmlSparePartDetails += '</strong><br>';
            htmlSparePartDetails += sparePartNumber;
            htmlSparePartDetails += '</p>';

            $("#stockmanagement_sparepartinfo").empty();
            $("#stockmanagement_sparepartinfo").html(htmlSparePartDetails);


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

        }

    }

    self.SparePartInfoRequestIncomplete = function (data, status, xhr) {
        c1('stockmanagement row 118: 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 = $("#stockmanagement_stockselect").val();
        var adjustToQty = $("#stockmanagement_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" });
            $("#stockmanagement_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#stockmanagement_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#stockmanagement_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagement_generic_popup").popup("close");
            });

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

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

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

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

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



    }

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

    self.requestStockReplenishment = function () {
        current_userid = $.cookie("user_id");
        var currently_selected_stockid = $("#stockmanagement_stockselect").val();
        var qtyToAddToStock = $("#stockmanagement_qty").val();
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: {
                "userid": current_userid,
                "stockid": currently_selected_stockid,
                "qtytoadd": qtyToAddToStock,
                "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) {

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

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

            $("#stockmanagement_generic_popup_button").unbind("click").click(function () {
                $("#stockmanagement_generic_popup").popup("close");
            });

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

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

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

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

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



    }

    self.StockReplenishmentRequestIncomplete = function (data, status, xhr) {
        c1('stockmanagement row 253: 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('stockmanagement_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>';
        });

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

    self.updateStockInformation = function () {
        var selectedStock = $("#stockmanagement_stockselect").val();
        jQuery.each(stock_data, function (i, stock_element) {
            if (stock_element.StockId == selectedStock) {
                if (stock_element.StockPositionI.length > 0) {
                    var area_text = store_labels.StoreArea + ' ' + stock_element.StockPositionI;
                    $("#stockmanagement_areainfo").html(area_text);
                }
                else {
                    $("#stockmanagement_areainfo").html(ReturnPhraseOnKey('global_unspecified'));
                }
                if (stock_element.StockPositionII.length > 0) {
                    var section_text = store_labels.StoreSection + ' ' + stock_element.StockPositionII;
                    $("#stockmanagement_sectioninfo").html(section_text);
                }
                else {
                    $("#stockmanagement_sectioninfo").html(ReturnPhraseOnKey('global_unspecified'));
                }
                if (stock_element.StockPositionIII.length > 0) {
                    var position_text = store_labels.StorePosition + ' ' + stock_element.StockPositionIII;
                    $("#stockmanagement_positioninfo").html(position_text);
                }
                else {
                    $("#stockmanagement_positioninfo").html(ReturnPhraseOnKey('global_unspecified'));
                }

                $("#stockmanagement_qty_info").html(stock_element.StockInStore);
                $("#stockmanagement_min_qty_info").html(stock_element.StockInStore);

            }
            return;
        });
    }

    self.ValidateConsumption = function () {

        var validationTest = true;
        $("#stockmanagement_errormessage").hide();
        var wholeNumberRegEx = /^[1-9]\d*$/;
        var quantityToValidate = $("#stockmanagement_qty").val();
        if (quantityToValidate == '') {
            $("#stockmanagement_errormessage").text(ReturnPhraseOnKey('stockmanagement_err_validnumber'));
            validationTest = false;
        }
        else if (!wholeNumberRegEx.test(quantityToValidate)) {
            $("#stockmanagement_errormessage").text(ReturnPhraseOnKey('stockmanagement_err_positivenumbersonly'));
            validationTest = false;
        }
        else if (quantityToValidate == 0 && SELECTED_SPAREPART_JOB_TYPE == STOCK_REPLENISHMENT) {
            $("#stockmanagement_errormessage").text(ReturnPhraseOnKey('stockmanagement_err_nozeroes'));
            validationTest = false;
        }

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

        if (SELECTED_SPAREPART_JOB_TYPE == STOCK_ADJUSTMENT && quantityToValidate == 0) {
            validationTest = true;
        }

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

        return validationTest;
    }

    self.selectDefaultJobType = function () {
        if (SELECTED_SPAREPART_JOB_TYPE == 1) {
            $("#stockmanagement_adjuststock").trigger('click');
        }
        else if (SELECTED_SPAREPART_JOB_TYPE == 2) {
            $("#stockmanagement_addtostock").trigger('click');
        }
    }


    return self;
}

var stockManagement = Stockmanagement();




$(document).one("pageshow", "#page_stockmanagement", function (e) {
    $("#stockmanagement_stockselect").change(function () {
        stockManagement.updateStockInformation();
    });

    $("#page_stockmanagement .btn-select-jobtype-type").click(function () {
        $("#page_stockmanagement .btn-select-jobtype-type").removeClass("navbarSelected");
        $(this).addClass("navbarSelected");

        var selectedJobType = $(this).attr('id');

        if (selectedJobType == 'stockmanagement_addtostock') {
            SELECTED_SPAREPART_JOB_TYPE = STOCK_REPLENISHMENT;
        }
        else if (selectedJobType == 'stockmanagement_adjuststock') {
            SELECTED_SPAREPART_JOB_TYPE = STOCK_ADJUSTMENT;

        }

        e3('stockmanagement row 398');

    })

    $("#stockmanagement_commit").click(function () {
        if (stockManagement.ValidateConsumption()) {
            if (SELECTED_SPAREPART_JOB_TYPE == STOCK_ADJUSTMENT) {
                stockManagement.requestStockAdjustment();
            }
            else if (SELECTED_SPAREPART_JOB_TYPE == STOCK_REPLENISHMENT) {
                stockManagement.requestStockReplenishment();
            }
            else {
                c1('stockmanagement row 406: job type parameter is not in range specified in system');
            }
        }

        e3('stockmanagement row 415');
    })

});

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

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

        stockManagement.setNavBar();

        stockManagement.requestSelectedStockLabels();
        stockManagement.requestSparePartInfo();
        stockManagement.selectDefaultJobType();
    }
    else { helper.ForcedLogout(); }


});

