function Machinesearch() {

    var self = {};

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


    self.init = function () {

        $("#selectmachine_machineid_input").val("");
        self.PopulateMachineTypeList();
        self.update();
    };



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




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

    self.checkForMachineExistenceWithScanner = function (incomingBarcode) {
        var machine_search_param = incomingBarcode;
        var machine_type_selected_id = 0;
        var current_session_token = $.cookie("session_token");
        var user_id = $.cookie("user_id");


        var requester = new AjaxRequest({
            data: {
                "machine_search_param": machine_search_param, "machinetype_search_param": machine_type_selected_id, "search_all_locations": false,
                "start_location_index": locationNavigation.currentLocationId, "user_id": user_id, "session_token": current_session_token}, // This is for the json request
            success: self.MachineExistenceRequestComplete,
            error: self.MachineExistenceRequestIncomplete,
            url: "CheckForMachinePresence"
        });
        requester.ExecuteRequest();
    }

    self.checkForMachineExistence = function () {

        CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_MANUAL;

        var machine_search_param = $("#selectmachine_machineid_input").val();
        var machine_type_selected_id = $("#machinesearch_machinetypes").val();
        var current_session_token = $.cookie("session_token");
        var user_id = $.cookie("user_id");

        c3(machine_search_param);
        c3(machine_type_selected_id);
        c3(current_session_token);
        c3(user_id);

        var requester = new AjaxRequest({
            data: { "machine_search_param": machine_search_param, "machinetype_search_param": machine_type_selected_id, "search_all_locations": self.includeAllMachinesInSearchResult, "start_location_index": locationNavigation.currentLocationId, "user_id": user_id, "session_token": current_session_token }, // This is for the json request
            success: self.MachineExistenceRequestComplete,
            error: self.MachineExistenceRequestIncomplete,
            url: "CheckForMachinePresence"
        });
        requester.ExecuteRequest();
    }

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

        var checkValidation = data.d.SessionTokenValid;
        var machinesPresent = data.d.TrueOrFalse;
        var machineCount = data.d.ValueToPass;

        if (checkValidation == false) {

            //$.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });

            $("#machineselect_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#machineselect_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#machineselect_generic_popup_button").unbind("click").click(function () {
                $("#machineselect_generic_popup").popup("close");
            });

            $("#machineselect_generic_popup").popup().popup("open");

        }
        else if (machinesPresent == false) {
            $("#selectmachine_errormessage").text(ReturnPhraseOnKey("machineselect_message_nomachinesfound"));
            $("#selectmachine_errormessage").show();
        }
        else if (machineCount > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {
            self.setErrorMsg(ReturnPhraseOnKey("machineselect_message_toomanymachines"));
        }

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

            $.cookie("machinesearchparam", $("#selectmachine_machineid_input").val());
            $.cookie("machinetypeidsearchparam", $("#machinesearch_machinetypes").val());
            $("selectmachine_machineid_input").text("");

            initScanner(undefined);
            $.mobile.navigate("#page_machinelist", { role: "page" });
            e5('machinesearch row 56');
        }

    }

    self.MachineExistenceRequestIncomplete = function (data, status, xhr) {
        c1("machinesearch row 113: Unable to reach web service. Can't verify presence of machine search result.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.PopulateMachineTypeList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.PopulateMachineTypeListComplete,
            error: self.PopulateMachineTypeListIncomplete,
            url: "RequestMachineTypesList"
        });
        requester.ExecuteRequest();
    }

    self.PopulateMachineTypeListComplete = function (data, status, xhr) {
        var machineTypeList = '<option value=0>' + ReturnPhraseOnKey("machineselect_type_not_selected") + '</option>';
        jQuery.each(data.d.MachineTypesInSystem, function () {

            machineTypeList += '<option value="'
            machineTypeList += this.MachineTypeId;
            machineTypeList += '">';
            machineTypeList += this.MachineTypeName;
            machineTypeList += '</option>';
        });

        $("#machinesearch_machinetypes").html(machineTypeList);
        $("#machinesearch_machinetypes").selectmenu().selectmenu("refresh");
    };

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

    };

    self.setErrorMsg = function (msg) {

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

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



    return self;

}

var machineSearch = Machinesearch();

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

    //$('#selectmachine_machineid_input').bind("triggerMachineSearch", function (e) {
    //    machineSearch.checkForMachineExistence();
    //});

    //$('#selectmachine_machineid_input').keyup(function (e) {
    //    if (e.keyCode == 13) {
    //        $(this).trigger("triggerMachineSearch");
    //    }
    //});



    $("#machineselect_show_valid_machines_at_all_locations").bind("change", function (event, ui) {
        event.preventDefault();
        event.stopPropagation();
        if ($("#machineselect_show_valid_machines_at_all_locations").is(":checked")) {
            machineSearch.includeAllMachinesInSearchResult = true;
        }
        else {
            machineSearch.includeAllMachinesInSearchResult = false;
        }

    });

});


$(document).on("pagebeforeshow", "#page_machineselect", function (e) {
    $("#machineselect_selectedlocation_info").html(locationNavigation.returnCurrentLocationInfo(3));
    $("#machineselect_show_valid_machines_at_all_locations").removeAttr('checked').checkboxradio('refresh');
    machineSearch.includeAllMachinesInSearchResult = false;
    machineSearch.init();
});


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

    
    if (SessionTokenStatus == true) {

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

        

        CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_MANUAL;

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

        $("#selectmachine_searchbutton").unbind().click(function (event) {
            machineSearch.checkForMachineExistence();
            e5('machinesearch row 206');
        });

        $('#selectmachine_machineid_input').unbind().keypress(function (event) {
            if (event.keyCode == '13') {
                event.preventDefault();
                //handleLocation.clearErrorMsg();
                machineSearch.checkForMachineExistence();
            }
        });


        $("#selectmachine_camera").unbind().click(function (event) {
            initScanner(undefined);

            CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_BARCODE;
            SCAN_PAGE_TARGET = SCAN_MACHINE;
            setTimeout($.mobile.navigate("#page_scantest", { role: "page" }), 100);
            //$.mobile.navigate("#page_scantest", { role: "page" });

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

});

$(document).on("pagehide", "#page_machineselect", function () {
    $("#selectmachine_errormessage").hide();
    $("#selectmachine_machineid_input").val("");
    $("#machinesearch_machinetypes").val(1);
});

