function Sparepartsearchinstore() {

    var self = {};

    self.tmp = null;
    self.selection = {};
    self.UserId = null;

    self.init = function () {
        self.PopulateSparepartGroupList();
        $("#sparepartselectinstore_sparepart_id_input").val("");
        self.update();
    }

    self.update = function () {
       
    }

    self.handleScannedValues = function (barcode) {
        keyboardbuffer.set('');
    }

    self.processCurrentlySelectedStore = function () {
        var requester = new AjaxRequest({
            data: { "current_store_id": CURRENT_SELECTED_STORE }, // This is for the json request
            success: self.StockNameProcessComplete,
            error: self.StockNameProcessIncomplete,
            url: "RequestCurrentlySelectedStoreName"
        });
        requester.ExecuteRequest();
    }

    self.StockNameProcessComplete = function (data, status, xhr) {
        //If store name request contains no valid name, show appropriate error message
        if (data.d.TrueOrFalse == false) {
            $("#selectsparepartinstore_errormessage").text(ReturnPhraseOnKey("sparepartsearchinstore_message_nosparepartstocksfound"));
            $("#selectsparepartinstore_errormessage").show();
        }
        else {
            var headerText = ReturnPhraseOnKey("sparepartsearchinstore_header") + ' ' + data.d.StringToPass;
            $("#sparepartselectonstore_header").html(headerText);
        }
    }

    self.StockNameProcessIncomplete = function (data, status, xhr) {
        c1('sparepartsearchonstore row 46: Failed to get name of currently selected spare part store. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.checkForSparepartExistence = function () {
        var sparepart_search_param = $("#sparepartselectinstore_sparepart_id_input").val();
        var sparepart_search_groupid_param = $("#sparepartsearchonstore_sparepartgroups").val();
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "sparepart_search_param": sparepart_search_param, "spareparttype_search_param": sparepart_search_groupid_param, "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;
        var sparePartCount = data.d.ValueToPass;


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

            $("#selectsparepartinstore_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#selectsparepartinstore_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#selectsparepartinstore_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e2('sparepartsearchonstore row 80');
            });

            $("#selectsparepartinstore_generic_popup_button").unbind("click").click(function () {
                $("#selectsparepartinstore_generic_popup").popup("close");
            });

            $("#selectsparepartinstore_generic_popup").popup().popup("open");
        }
        else if (sparePartPresent == false) {
            $("#selectsparepartinstore_errormessage").text(ReturnPhraseOnKey("sparepartsearchinstore_message_nosparepartsfound"));
            $("#selectsparepartinstore_errormessage").show();
        }
        else if (sparePartCount > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {
            self.setErrorMsg(ReturnPhraseOnKey("sparepartselect_message_toomanyspareparts"));
        }

        else if (sparePartPresent == true) {
            if ($("#selectsparepartinstore_errormessage").is(":visible")) {
                $("#selectsparepartinstore_errormessage").hide();
            }


            self.checkForSparePartStockPresenceAtSelectedStore();



            //console.log('navigating to selected spare part');
            //$.cookie("sparepartsearchparam", $("#sparepartselect_sparepart_id_input").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" });
            //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlist", { role: "page", reverse: false, changeHash: false });
        }

    }

    self.SparepartExistenceRequestIncomplete = function (data, status, xhr) {
        c1('sparepartsearchonstore row 117: Failed to confirm spare part search results. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.checkForSparePartStockPresenceAtSelectedStore = function () {

        var sparepart_search_param = $("#sparepartselectinstore_sparepart_id_input").val();
        var spareparttype_search_param = $("#sparepartsearchonstore_sparepartgroups").val();
        var current_store_id = CURRENT_SELECTED_STORE;
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: { "sparepart_search_param": sparepart_search_param, "spareparttype_search_param":spareparttype_search_param, "store_id": current_store_id, "session_token": current_session_token }, // This is for the json request
            success: self.CheckForStockPresenceSuccess,
            error: self.CheckForStockPresenceFailure,
            url: "CheckForSparepartPresenceAtSpecificStore"
        });
        requester.ExecuteRequest();

    }

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

        var checkValidation = data.d.SessionTokenValid;
        var stockCount = data.d.ValueToPass;

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

            $("#selectsparepartinstore_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#selectsparepartinstore_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#selectsparepartinstore_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e2('sparepartsearchonstore row 154');
            });

            $("#selectsparepartinstore_generic_popup_button").unbind("click").click(function () {
                $("#selectsparepartinstore_generic_popup").popup("close");
            });

            $("#selectsparepartinstore_generic_popup").popup().popup("open");
        }
        else {
            var stockCount = data.d.ValueToPass;
            var sparePartId = data.d.StringToPass;

            if (stockCount == 0) {
                $("#selectsparepartinstore_errormessage").text(ReturnPhraseOnKey("sparepartsearchinstore_message_nosparepartstocksfound"));
                $("#selectsparepartinstore_errormessage").show();
            }
            else {

                if ($('#selectsparepartinstore_errormessage').is(":visible")) {
                    $("#selectsparepartinstore_errormessage").hide();
                }


                $.cookie("sparepartsearchparam", $("#sparepartselectinstore_sparepart_id_input").val());
                $.cookie("spareparttypesearchparam", $("#sparepartsearchonstore_sparepartgroups").val());
                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlistonstore", { role: "page", reverse: false, changeHash: true });
                e2('sparepartsearchonstore row 181');
            }
        }

    }

    self.CheckForStockPresenceFailure = function (data, status, xhr) {
        c1('sparepartsearchonstore row 186: Failed to get number of stocks for spare part at selected store. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.PopulateSparepartGroupList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.PopulateSparepartGroupListComplete,
            error: self.PopulateSparepartGroupListIncomplete,
            url: "RequestSparePartGroupList"
        });
        requester.ExecuteRequest();
    };

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

        var sparepartGroupList = '<option value=0>' + ReturnPhraseOnKey("sparepartsearch_no_group_selected") + '</option>';

        jQuery.each(data.d.SparepartGroupsInSystem, function () {

            sparepartGroupList += '<option value="'
            sparepartGroupList += this.SparepartGroupId;
            sparepartGroupList += '">';
            sparepartGroupList += this.SparepartGroupName;
            sparepartGroupList += '</option>';
        });

        $("#sparepartsearchonstore_sparepartgroups").html(sparepartGroupList);
        $("#sparepartsearchonstore_sparepartgroups").selectmenu().selectmenu("refresh");
    };

    self.PopulateSparepartGroupListIncomplete = function (request, status, error) {
        c1("sparepartsearchonstore row 219: Unable to reach web service. Failed to populate machine type list.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    };

    self.goToCameraScan = function (e) {

        CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_BARCODE;
        SCAN_PAGE_TARGET = SCAN_SPAREPART;
        initScanner(undefined);
        $.mobile.navigate("#page_scantest", { role: "page" });
        c1('sparepartsearchonstore row 236 - navigating to barcode search for spare parts in specific store');
    }

    self.setErrorMsg = function (msg) {

        $('#selectsparepartinstore_errormessage').html(msg);
        $('#selectsparepartinstore_errormessage').show();
    }

    self.clearErrorMsg = function (msg) {
        $('#selectsparepartinstore_errormessage').html('');
        $('#selectsparepartinstore_errormessage').hide();
    }


    return self;

}

var sparepartSearchInStore = Sparepartsearchinstore();

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

    $('#sparepartselectinstore_sparepart_id_input').bind("triggerSparePartSearchInStore", function (e) {
        sparepartSearchInStore.checkForSparepartExistence();
    });
    $('#sparepartselectinstore_sparepart_id_input').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("triggerSparePartSearchInStore");
        }
        e2('sparepartsearchonstore row 249');
    });

    $("#selectsparepartinstore_searchbutton").click(function () {
        sparepartSearchInStore.checkForSparepartExistence();
    });

});


$(document).on("pageshow", "#page_sparepartselectinstore", function (event, data) {
    if (SessionTokenStatus == true) {
        $("#selectsparepartinstore_errormessage").hide();

        $("#sparepartselectinstore_sparepart_id_input").val("");
        $("#sparepartselectinstore_sparepart_id_input").focus();

        sparepartSearchInStore.processCurrentlySelectedStore();

        sparepartSearchInStore.init();
    }


});

$(document).on("pageshow", "#page_sparepartselectinstore", function (event, data) {

    CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;

    if (SessionTokenStatus == true) {

        //**********************************************************
        //20200401 - moved to pagebeforeshow event

        //$("#selectsparepartinstore_errormessage").hide();

        //$("#sparepartselectinstore_sparepart_id_input").val("");
        //$("#sparepartselectinstore_sparepart_id_input").focus();

        //sparepartSearchInStore.processCurrentlySelectedStore();

        //sparepartSearchInStore.init();
        //***********************************************************


        //possible solution for reset of search parameter, may be premature
        $.removeCookie('sparepartsearchparam');



        $("#selectsparepartonstore_searchbutton").unbind().click(function (event) {
            sparepartSearchInStore.checkForSparepartExistence();
        });

        $("#selectsparepartinstore_backbutton").unbind().click(function (event) {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartstoreselect", { role: "page", reverse: false, changeHash: false });
            e2('sparepartsearchonstore row 283');
        });


        $("#sparepartselectinstore_camera").unbind().click(function (event) {
            c2('Before call to scan spare part form with stores');
            sparepartSearchInStore.goToCameraScan(event);
        });

    }
    else { helper.ForcedLogout();}

});