function Sparepartsearchresult() {

    var self = {};

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

    self.requestSparePartList = function () {
        var sparepart_search_param = $.cookie("sparepartsearchparam");
        var sparepart_group_search_param = $.cookie("spareparttypesearchparam");
        var current_session_token = $.cookie("session_token");

 
        var requester = new AjaxRequest({
            data: { "partial_sp_number": sparepart_search_param, "sparepart_group_id": sparepart_group_search_param, "session_token": current_session_token },
            success: self.SparepartListReceptionSuccess,
            error: self.SparepartListReceptionFailure,
            url: "RequestSparePartListOnPartialNumber"
        });
        requester.ExecuteRequest();

    }

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

        if (data.d.SessionTokenValid == false) {
            $.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });
            e5('sparepartsearchlist row 29');
        }
        else {

            var listData = data.d.SparePartList;
            console.log(listData);
            self.spList = data.d.SparePartList;
            //console.info(listData[0].MachineName);
            //console.info(listData[0].MachineNumber);
            var sp_count = data.d.SparePartList.length;
            c5(sp_count);

            if (sp_count == 0) {
                $("#sparepartlist_search_result_info_text").html(ReturnPhraseOnKey("sparepartsearch_message_nosparepartsfound"));
                $("#sparepartlist_search_result_info_text").show();
            }
            else if (sp_count > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {
                $("#sparepartlist_search_result_info_text").html(ReturnPhraseOnKey("sparepartselect_message_toomanyspareparts"));
                $("#sparepartlist_search_result_info_text").show();

            }
            else {
                $("#sparepartlist_search_result_info_text").html('');
                $("#sparepartlist_search_result_info_text").hide();

                jQuery.each(listData, function () {

                    if (!CheckIfSparePartAlreadyAssociated(this.SparePartNumber)) {
                        var sparepartLink = '<li role="heading" class="list-header-class" data-role="list-divider">';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '</li>';
                        //sparepartLink += '<li class="list-element-class" data-theme="c" data-sparepartnumber="';
                        sparepartLink += '<li class="list-element-class" data-sparepartnumber="';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '" data-sparepartid="';
                        sparepartLink += this.SparePartId;
                        sparepartLink += '"><a href="#dummy" data-transition="slide">';
                        sparepartLink += this.SparePartName;
                        sparepartLink += '</a></li>';
                    }
                    else {
                        var sparepartLink = '<li role="heading" class="list-header-class" data-role="list-divider">';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '</li>';
                        //sparepartLink += '<li data-theme="e" class="list-element-class" data-sparepartnumber="';
                        sparepartLink += '<li class="list-element-class" data-sparepartnumber="';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '" data-sparepartid="';
                        sparepartLink += this.SparePartId;
                        sparepartLink += '"><a href="#dummy" data-transition="slide">';
                        sparepartLink += this.SparePartName;
                        sparepartLink += ' (associated with the job)';
                        sparepartLink += '</a></li>';
                    }

                    $("#sparepartlist_page_sparepart_list").append(sparepartLink);
                });

                $("#sparepartlist_page_sparepart_list").listview('refresh');
            }
        }
    }

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

        c1('sparepartsearchlist row 73: Failed to retrieve spare part search list. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.requestMachineSparePartList = function () {
        var current_machine_nr = $.cookie("currently_selected_machine");
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: { "machine_nr": current_machine_nr, "session_token": current_session_token },
            success: self.MachineSparepartListReceptionSuccess,
            error: self.MachineSparepartListReceptionFailure,
            url: "RequestSparePartListOnMachineNumber"
        });
        requester.ExecuteRequest();

    }


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

        if (data.d.SessionTokenValid == false) {
            $.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });
            e5('sparepartsearchlist row 29');
        }
        else {

            var listData = data.d.SparePartList;
            var sp_count = data.d.SparePartList.length;
            self.machineList = data.d.SparePartList;
            //console.info(listData[0].MachineName);
            //console.info(listData[0].MachineNumber);

            if (sp_count > 0) {

                $("#sparepartlist_associated_with_machine_info_text").html('');
                $("#sparepartlist_associated_with_machine_info_text").hide();

                jQuery.each(listData, function () {

                    if (!CheckIfSparePartAlreadyAssociated(this.SparePartNumber)) {
                        var sparepartLink = '<li role="heading" class="list-header-class" data-role="list-divider">';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '</li>';
                        //sparepartLink += '<li class="list-element-class" data-theme="c" data-sparepartnumber="';
                        sparepartLink += '<li class="list-element-class" data-sparepartnumber="';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '" data-sparepartid="';
                        sparepartLink += this.SparePartId;
                        sparepartLink += '"><a href="#dummy" data-transition="slide">';
                        sparepartLink += this.SparePartName;
                        sparepartLink += '</a></li>';
                    }
                    else {
                        var sparepartLink = '<li role="heading" class="list-header-class" data-role="list-divider">';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '</li>';
                        //sparepartLink += '<li data-theme="e" class="list-element-class" data-sparepartnumber="';
                        sparepartLink += '<li class="list-element-class" data-sparepartnumber="';
                        sparepartLink += this.SparePartNumber;
                        sparepartLink += '" data-sparepartid="';
                        sparepartLink += this.SparePartId;
                        sparepartLink += '"><a href="#dummy" data-transition="slide">';
                        sparepartLink += this.SparePartName;
                        sparepartLink += ' (associated with the job)';
                        sparepartLink += '</a></li>';
                    }

                    $("#sparepartlist_page_associated_with_machine_list").append(sparepartLink);
                });

                $("#sparepartlist_page_associated_with_machine_list").listview('refresh');
            }
            else {
                $("#sparepartlist_associated_with_machine_info_text").html(ReturnPhraseOnKey("sparepartlist_no_associated_spareparts_message"));
                $("#sparepartlist_associated_with_machine_info_text").show();
                
            }

            $("#sparepartlist_associated_with_machine").show();

        }
    }

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

        c1('sparepartsearchlist row 73: Failed to retrieve spare part search list. Unable to reach web service.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }



    var CheckIfSparePartAlreadyAssociated = function (sparePartIdToCheck) {

        if (defined(CheckIfSparePartAlreadyAssociated)) {
            var present = false;
            jQuery.each(SparePartListAlreadyAssignedForJob, function () {
                if (this == sparePartIdToCheck) {
                    present = true;
                    return present;
                }
            })

            return present;
        }
        else {
            return true;
        }
    }



    self.CheckStockExistenceForSelectedSparePart = function () {
        var user_id = $.cookie("user_id");
        var machine_id = $.cookie("currently_selected_machine");
        var sparepart_id = $.cookie("currently_selected_sparepartid");
        var current_session_token = $.cookie("session_token");


        var requester = new AjaxRequest({
            data: { "userid": user_id, "sparepart_id": sparepart_id, "machine_id": machine_id, "session_token": current_session_token }, // This is for the json request
            success: self.CheckForSparePartStockPresenceCompleted,
            error: self.CheckForSparePartStocksPresenceNotCompleted,
            url: "CheckForSparePartStockPresenceAtLocationAndForUser"
        });
        requester.ExecuteRequest();

    }

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

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

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

            $("#sparepartlist_generic_popup_button").unbind("click").click(function () {
                $("#sparepartlist_generic_popup").popup("close");
            });

            $("#sparepartlist_generic_popup").popup().popup("open");
        }
        else if (data.d.TrueOrFalse) {
            //$.mobile.navigate("#page_sparepartdetail", { role: "page" });
            $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartdetail", { role: "page", reverse: false, changeHash: false });
            e5('sparepartsearchlist row 136');
        }
        else {
            StoreSelectedSemaphore = STORE_NOT_SELECTED;

            //Set cookie indicating selected stock to 'no stock', since there are no available stocks.
            //If stocks are available, cookie is set in page_sparepartdetail page.
            var noStoreFlag = 0;
            $.cookie("stock_selected_for_new_consumption", noStoreFlag);

            //$.mobile.navigate("#page_createnewconsumption", { role: "page" });
            $(":mobile-pagecontainer").pagecontainer("change", "#page_createnewconsumption", { role: "page", reverse: false, changeHash: false });
            e5('sparepartsearchlist row 148');
        }

    }


    self.CheckForSparePartStocksPresenceNotCompleted = function (data, status, xhr) {
        console.info("Check for existence of stores for selected spare part failed!");
    }


    self.StoreExistFork = function () {
        self.CheckStockExistenceForSelectedSparePart();

    }

    self.attachEventToList = function () {
        $('#sparepartlist_page_sparepart_list').on('click', 'li', function () {
            //alert($(this).text());
            e5('sparepartsearchlist row 167');
            var sparepart_nr = $(this).data("sparepartnumber");
            var sparepart_id = $(this).data("sparepartid");
            if (sparepart_nr !== undefined) {
                $.cookie("currently_selected_sparepartnumber", sparepart_nr);
                $.cookie("currently_selected_sparepartid", sparepart_id);

                if (!CheckIfSparePartAlreadyAssociated(sparepart_nr)) {
                    self.StoreExistFork();
                }
                else {
                    $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
                    e5('sparepartsearchlist row 179');
                }
            }
        });


        $('#sparepartlist_page_associated_with_machine_list').on('click', 'li', function () {
            var sparepart_nr = $(this).data("sparepartnumber");
            var sparepart_id = $(this).data("sparepartid");
            if (sparepart_nr !== undefined) {
                $.cookie("currently_selected_sparepartnumber", sparepart_nr);
                $.cookie("currently_selected_sparepartid", sparepart_id);

                if (!CheckIfSparePartAlreadyAssociated(sparepart_nr)) {
                    self.StoreExistFork();
                }
                else {
                    $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
                    e5('sparepartsearchlist row 179');
                }
            }
        });
    }

    self.populateLists = function () {
        switch (CURRENT_SP_SEARCH) {
            case MACHINE_LIST_ONLY:
                c8('sparepartsearchlist row 313 - machine list only');
                $("#sparepartlist_search_result").hide();
                $("#sparepartlist_associated_with_machine").show();
                self.requestMachineSparePartList();
                break;
            
            case SEARCH_ONLY:
                c8('sparepartsearchlist row 318 - search output only');
                $("#sparepartlist_associated_with_machine").hide();
                $("#sparepartlist_search_result").show();
                self.requestSparePartList();
                break;

            case COMBINED:
                c8('sparepartsearchlist row 330 - combined search output')
                if (CURRENT_SPAREPART_SEARCH_RECORD_COUNT > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {
                    $("#sparepartlist_search_result_info_text").html(ReturnPhraseOnKey("sparepartselect_message_toomanyspareparts"));
                    $("#sparepartlist_search_result_info_text").show();
                    $("#sparepartlist_search_result").show();

                }
                else {
                    $("#sparepartlist_search_result_info_text").html('');
                    $("#sparepartlist_search_result_info_text").hide();
                    $("#sparepartlist_search_result").show();
                    self.requestSparePartList();                    
                }

                self.requestMachineSparePartList();

                
                break;
            
            default:
        }

    }




    return self;

}

var sparepartSearchResult = Sparepartsearchresult();

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

    $("#sparepartlist_backbutton").click(function () {
        switch (CURRENT_SPAREPART_SEARCH_MODE) {
            case SPAREPART_SEARCH_INPUT_MANUAL:
                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselect", { role: "page", reverse: false, changeHash: true });
                e5('sparepartsearchlist row 201');
                break;
            case SPAREPART_SEARCH_INPUT_BARCODE:
                SCAN_PAGE_TARGET = SCAN_SPAREPART;
                //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepart_barcode_cam", { role: "page", reverse: false, changeHash: true });
                $(":mobile-pagecontainer").pagecontainer("change", "#page_scantest", { role: "page", reverse: false, changeHash: true });
                e5('sparepartsearchlist row 208 - navigating to barcode scan page with spare part settings');
                break;
            default:
                //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselect", { role: "page", reverse: false, changeHash: true });
                CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselect", { role: "page", reverse: false, changeHash: true });                
                c5('sparepartsearchlist row 211 - forced reset to manual spare part search');
                break;
        }
        
        //$(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartselect", { role: "page", reverse: false, changeHash: false });
    });

    console.info("attaching event to spare part search result list");
    sparepartSearchResult.attachEventToList();
});


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

    if (SessionTokenStatus == true) {
        console.info("in spare part list form");

        $("#sparepartlist_errormessage").hide();
        $("#sparepartlist_associated_with_machine_info_text").hide();
        $("#sparepartlist_search_result_info_text").hide();

        $("#sparepartlist_page_sparepart_list").empty();
        $("#sparepartlist_page_associated_with_machine_list").empty();

        //sparepartSearchResult.requestSparePartList();
        //sparepartSearchResult.requestMachineSparePartList();

        sparepartSearchResult.populateLists();
    }
    else { helper.ForcedLogout(); }

});


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

//    if (SessionTokenStatus == true) {
//        console.info("in spare part list form");

//        $("#sparepartlist_errormessage").hide();
//        $("#sparepartlist_page_sparepart_list").empty();
//        sparepartSearchResult.requestSparePartList();
//    }
//    else { helper.ForcedLogout(); }

//});

