function Sparepartsearch() {

    var self = {};

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

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

    self.update = function () {
        initScanner(self);
        $("#selectsparepart_searchbutton").unbind().click(function () {
            self.dummy($("#sparepartselect_sparepart_id_input").val());
        });
    }

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

    self.standardSearchActive = function(){
        return ($("#sparepartselect_sparepart_id_input").val() != '' || $("#sparepartsearch_sparepartgroups").val() != 0);
    }

    self.machineSparePartSearchActive = function (){
        return ($("#include_machine_spareparts").prop("checked") == true);
    }

    //self.checkForSparepartExistence = function () {
    //    var sparepart_search_param = $("#sparepartselect_sparepart_id_input").val();
    //    var current_session_token = $.cookie("session_token");

    //    var requester = new AjaxRequest({
    //        data: { "sparepart_search_param": sparepart_search_param, "session_token": current_session_token }, // This is for the json request
    //        success: self.SparepartExistenceRequestComplete,
    //        error: self.SparepartExistenceRequestIncomplete,
    //        url: "CheckForSparepartPresence"
    //    });
    //    requester.ExecuteRequest();
    //}

    //self.checkForSparepartExistence = function () {
    //    var sparepart_search_param = $("#sparepartselect_sparepart_id_input").val();
    //    var sparepart_search_groupid_param = $("#sparepartsearch_sparepartgroups").val();
    //    var current_session_token = $.cookie("session_token");
    //    var sparepart_search_check_machine_associations = $("#include_machine_spareparts").prop("checked");
    //    var currently_selected_machine = $.cookie("currently_selected_machine");
    //    c1(sparepart_search_param);
    //    c1(sparepart_search_groupid_param);
    //    c1(current_session_token);
    //    c1(sparepart_search_check_machine_associations);
    //    c1(currently_selected_machine);

    //    var requester = new AjaxRequest({
    //        data: {
    //            "sparepart_search_param": sparepart_search_param, "spareparttype_search_param": sparepart_search_groupid_param,
    //            "lookup_machine_associations": sparepart_search_check_machine_associations,  "owner_machine_id": currently_selected_machine, "session_token": current_session_token},
    //        success: self.SparepartExistenceRequestComplete,
    //        error: self.SparepartExistenceRequestIncomplete,
    //        //url: "CheckForSparepartPresence"
    //        url: "CheckForSparepartPresenceIncludeMachineAssociations"
    //    });
    //    requester.ExecuteRequest();

    //}

    self.checkForSparepartExistence = function () {
        
        var sparepart_search_param = $("#sparepartselect_sparepart_id_input").val();
        var sparepart_search_groupid_param = $("#sparepartsearch_sparepartgroups").val();
        var current_session_token = $.cookie("session_token");
        var sparepart_search_check_machine_associations = $("#include_machine_spareparts").prop("checked");
        c1(sparepart_search_param);
        c1(sparepart_search_groupid_param);
        c1(sparepart_search_check_machine_associations);
        c1(current_session_token);

        if ($("#include_machine_spareparts").prop("checked") == false &&  $("#sparepartselect_sparepart_id_input").val() == '' && $("#sparepartsearch_sparepartgroups").val() == 0)
        {
            self.setErrorMsg(ReturnPhraseOnKey("sparepartselect_message_empty_search_not_allowed"));
        }

        else{
            self.clearErrorMsg();
            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;

        CURRENT_SPAREPART_SEARCH_RECORD_COUNT = data.d.ValueToPass;

        c3('sparepartsearch row 74 - sp existence check response:');
        c3(sparePartPresent);
        c3(sparePartCount);
          


        if (checkValidation == false) {
            c9('sparepartsearch row 120 - user validation failed')
            //$.mobile.navigate("#dialog_token_expired", { role: "dialog" });

            $("#selectsparepart_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#selectsparepart_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#selectsparepart_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e4('sparepartsearch row 72');
            });

            $("#selectsparepart_generic_popup_button").unbind("click").click(function () {
                $("#selectsparepart_generic_popup").popup("close");
            });

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

            //if no machines returned in search
            //if search is for machines only, show error message about no machines present in search
            //if machine -> sparepart list is to be presented OR combined search is performed, continue to presentation screen

        else if (sparePartPresent == false) {

            c9('sparepartsearch row 143 - no spare parts found in search');

            if (CURRENT_SP_SEARCH == SEARCH_ONLY) {
                $("#selectsparepart_errormessage").text(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
                $("#selectsparepart_errormessage").show();
            }

            if (CURRENT_SP_SEARCH == MACHINE_LIST_ONLY || CURRENT_SP_SEARCH == COMBINED) {
                self.presentSearchResult();
            }

        }
            //if number of records > max allowed
            //if search is for machines only, show error message about number of records > max allowed
            //if machine -> sparepart list is to be presented OR combined search is performed, continue to presentation screen

        else if (sparePartCount > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {

            c9('sparepartsearch row 162 - no spare parts found in search');

            if (CURRENT_SP_SEARCH == SEARCH_ONLY)
            {
                c9('sparepartsearch row 166 - search only');
                self.setErrorMsg(ReturnPhraseOnKey("sparepartselect_message_toomanyspareparts"));
            }

            if (CURRENT_SP_SEARCH == MACHINE_LIST_ONLY || CURRENT_SP_SEARCH == COMBINED) {
                c9('sparepartsearch row 162 - machine list only or combined');
                self.presentSearchResult();
            }
        }


        else if (sparePartPresent == true) {
            self.presentSearchResult();

            //if ($("#selectsparepart_errormessage").is(":visible")) {
            //    //$("#selectmachine_errormessage").hide();
            //    self.clearErrorMsg();
            //}
            //$.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" });
            //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlist", { role: "page", reverse: false, changeHash: false });
            //e4('sparepartsearch row 99');
        }

    }

    self.presentSearchResult = function () {
        if ($("#selectsparepart_errormessage").is(":visible")) {
            //$("#selectmachine_errormessage").hide();
            self.clearErrorMsg();
        }
        $.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" });
        $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlist", { role: "page", reverse: false, changeHash: true });

    }

    self.SparepartExistenceRequestIncomplete = function (data, status, xhr) {
        c1('sparepartsearch row 103: Failed to confirm spare part search results. 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>';
        });

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

    self.PopulateSparepartGroupListIncomplete = function (request, status, error) {
        c1("sparepartsearch row 136: 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);
        setTimeout($.mobile.navigate("#page_scantest", { role: "page" }), 100);
        e4('sparepartsearch row 159');
    }

    self.initSearch = function (e) {

        c2('sparepartsearch row 265 - in initSearch');
        if (self.standardSearchActive() == false && self.machineSparePartSearchActive() == false) {

            c2('sparepartsearch row 268 - empty search detected');

            CURRENT_SP_SEARCH = EMPTY_SEARCH;

            self.clearErrorMsg();
            self.setErrorMsg(ReturnPhraseOnKey("sparepartselect_message_empty_search_not_allowed"));
        }
        if (self.standardSearchActive() == true && self.machineSparePartSearchActive() == false) {

            c2('sparepartsearch row 277 - standard search detected');

            CURRENT_SP_SEARCH = SEARCH_ONLY;
            self.checkForSparepartExistence();

        }

        if (self.standardSearchActive() == false && self.machineSparePartSearchActive() == true) {
            c2('sparepartsearch row 285 - machine search only detected');

            CURRENT_SP_SEARCH = MACHINE_LIST_ONLY;

            CURRENT_SPAREPART_SEARCH_RECORD_COUNT = 0;

            self.presentSearchResult();
        }

        if (self.standardSearchActive() == true && self.machineSparePartSearchActive() == true) {
            c2('sparepartsearch row 292 - combined search detected');

            CURRENT_SP_SEARCH = COMBINED;
            self.checkForSparepartExistence();
        }

    }

    self.setErrorMsg = function (msg) {

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

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

    return self;

}

var sparepartSearch = Sparepartsearch();

$(document).on("pagebeforeshow", "#page_sparepartselect", function (e) {
    $('#include_machine_spareparts').removeAttr('checked').checkboxradio('refresh');

    if (SessionTokenStatus == true) {


        $("#selectsparepart_errormessage").hide();

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

        sparepartSearch.init();
    }

});


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

    $('#sparepartselect_sparepart_id_input').bind("triggerSparePartSearch", function (e) {
        sparepartSearch.initSearch();
        e4('sparepartsearch row 162');
    });
    $('#sparepartselect_sparepart_id_input').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("triggerSparePartSearch");
        }
        e4('sparepartsearch row 168');
    });

});


$(document).on("pageshow", "#page_sparepartselect", function (event, data) {
    if (SessionTokenStatus == true) {

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

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

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

        //sparepartSearch.init();

        //***************************************************

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


        CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;



        $("#selectsparepart_searchbutton").unbind().click(function (event) {
            sparepartSearch.initSearch();

            //sparepartSearch.checkForSparepartExistence();
        });

        //$(document).click(function (e) {
        //    e.stopPropagation();
        //    e.preventDefault();
        //    e4('sparepartsearch row 199');
        //});


        //$("#selectsparepart_camera").unbind().click(function (event) {
        //    sparepartSearch.goToCameraScan(event);
        //});

        $("#selectsparepart_changetobarcode").unbind().click(function (event) {
            sparepartSearch.goToCameraScan(event);
        });
        selectsparepart_changetobarcode


        sparepartSearch.previousPageId = data.prevPage.attr('id');

        if (sparepartSearch.previousPageId == 'page_finishjobwizard_1') {
            $("#selectsparepart_backbutton").show();
            $("#selectsparepart_backbutton").unbind().click(function (event) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_finishjobwizard_1", { role: "page", reverse: false, changeHash: false });
                e4('sparepartsearch row 214');
            });
        }
        else {
            $("#selectsparepart_backbutton").hide();
            $("#selectsparepart_backbutton").unbind();
        }
        //if (previousPageId == 'page_sparepartstoreselect') {
        //    $("#selectsparepart_backbutton").unbind().click(function (event) {
        //        event.preventDefault();
        //        $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartstoreselect", { role: "page", reverse: false, changeHash: false });
        //    });
        //}
    }
    else { helper.ForcedLogout(); }

});

$(document).on("pagehide", "#page_sparepartselect", function () {
    $("#sparepartselect_sparepart_id_input").val("");

});