function Mainmenu() {

    var self = {};

    self.tmp = null;
    self.selection = {};
    self.UserId = null;
    self.StoresPresent = false;
    self.StockChangeReasonList = null;

    self.requestStockChangeReasonList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestStockChangeReasonListSuccess,
            error: self.requestStockChangeReasonListFailure,
            url: "RequestStockChangeReasons"
        });
        requester.ExecuteRequest();

    }

    self.requestStockChangeReasonListSuccess = function (data, status, xhr) {
        self.StockChangeReasonList = data.d.StockChangeReasonList;
    }

    self.requestStockChangeReasonListFailure = function (request, status, error) {
        c1('mainmenu row 27: Unable to retrieve stock change reason list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.requestPM5Settings = function () {
            var userid = $.cookie("user_id");
            var current_session_token = $.cookie("session_token");
            var requester = new AjaxRequest({
                data: { "userid": userid, "session_token": current_session_token }, // This is for the json request
                success: self.requestPM5SettingsSuccess,
                error: self.requestPM5SettingsFailure,
                url: "RequestPM5Settings"
        });
        requester.ExecuteRequest();

    }

    self.requestPM5SettingsSuccess = function (data, status, xhr) {
        c1('mainmenu row 45 - requesting PM5 Client settings');
        if (data.d.PM5ClientSettings[0].SettingValue == "True") {
            CLEANUP_ACTIVE = true;
        }
        else {
            CLEANUP_ACTIVE = false;
        }
    }

    self.requestPM5SettingsFailure = function (request, status, error) {
        c1('mainmenu row 27: Unable to retrieve stock change reason list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    

    self.testUserMedia = function () {
        //return;
        if (hasGetUserMedia()) {
            c2('Detected user media - barcode scanner through camera will be accessible');
            // Good to go!
        } else {
            c2('No user media detected - barcode scanner through camera will not be accessible');
            hideBarcodeScannerAccessComponents();
        }
    };

    self.testProtocolIsSecure = function () {
        //return;
        if (location.protocol === 'https:') {
            c2('Detected https protocol, connection is secure - barcode scanner through camera will be accessible');
        }
        else {
            c2('Protocol is not HTTPS - barcode scanner through camera will not be accessible');
            hideBarcodeScannerAccessComponents();
        }
    };

    self.requestUserStockAccess = function () {
        var userid = $.cookie("user_id");
        var current_session_token = $.cookie("session_token");
        var requester = new AjaxRequest({
            data: { "userid": userid, "session_token": current_session_token }, // This is for the json request
            success: self.requestUserStockAccessSuccess,
            error: self.requestUserStockAccessFailure,
            url: "CheckUserAccessToStores"
        });
        requester.ExecuteRequest();
    };

    self.requestUserStockAccessSuccess = function (data, status, xhr) {
        var userAccessToStoresGranted = data.d.TrueOrFalse;
        if (userAccessToStoresGranted == true) {
            if ((DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED) || (DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED)) {

                jQuery.each(mainMenu.StockChangeReasonList, function () {
                    if (this.StockChangeReasonIndex == 2 && DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED) {
                        DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON = 2;
                    }
                    if (this.StockChangeReasonIndex == 3 && DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED) {
                        DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON = 3;
                    }
                });

                if ((DEFAULT_REPLENISHMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED) || (DEFAULT_ADJUSTMENT_STOCK_CHANGE_REASON == NO_REASON_SELECTED)) {

                    $("#mainmenu_generic_popup_header").html(ReturnPhraseOnKey("mainmenu_personalsettinsmissing_header"));
                    $("#mainmenu_generic_popup_text").html(ReturnPhraseOnKey("mainmenu_personalsettingsmissing_text"));

                    $("#mainmenu_generic_popup").off().on("popupafterclose", function (event, ui) {
                        $(":mobile-pagecontainer").pagecontainer("change", "#page_personalsettings", { role: "page", reverse: false, changeHash: false });
                        e2('mainmenu row 76');
                    });

                    $("#faultcreated_generic_popup_button").unbind("click").click(function () {
                        $("#mainmenu_generic_popup").popup("close");
                    });

                    $("#mainmenu_generic_popup").popup().popup("open");
                }
                else if (DEFAULT_SELECTED_STORE == NO_STORE_SELECTED) {
                    $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartstoreselect", { role: "page", reverse: true, changeHash: true });
                    e2('mainmenu row 87');
                }
                else {
                    CURRENT_SELECTED_STORE = DEFAULT_SELECTED_STORE;
                    $(":mobile-pagecontainer").pagecontainer("change", "#page_stores_functionselection", { role: "page", reverse: true, changeHash: true });
                    e2('mainmenu row 92');
                }
            }
            else if (DEFAULT_SELECTED_STORE == NO_STORE_SELECTED) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartstoreselect", { role: "page", reverse: true, changeHash: true });
                e2('mainmenu row 97');
            }
            else {
                CURRENT_SELECTED_STORE = DEFAULT_SELECTED_STORE;
                $(":mobile-pagecontainer").pagecontainer("change", "#page_stores_functionselection", { role: "page", reverse: true, changeHash: true });
                e2('mainmenu row 102');
            }
        }
        else {
            c1('mainmenu row 103: No stores available for this user');
            $("#mainmenu_generic_popup_header").html(ReturnPhraseOnKey("mainmenu_nostoreaccessforuser_header"));
            $("#mainmenu_generic_popup_text").html(ReturnPhraseOnKey("mainmenu_nostoreaccessforuser_text"));

            $("#mainmenu_generic_popup").off().on("popupafterclose", function (event, ui) {
                $.mobile.navigate("#page_mainmenu", { role: "page" });
                e2('mainmenu row 112');
            });

            $("#faultcreated_generic_popup_button").unbind("click").click(function () {
                $("#mainmenu_generic_popup").popup("close");
            });

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

    self.requestUserStockAccessFailure = function (data, status, error) {
        c1("mainmenu row 120: Unable to verify user's right to access store management function.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    };

    self.CheckForSparePartStorePresence = function () {

        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.CheckForSparePartStorePresenceSuccess,
            error: self.CheckForSparePartStorePresenceFailure,
            url: "CheckForSparepartStorePresence"
        });
        requester.ExecuteRequest();
    }

    self.CheckForSparePartStorePresenceSuccess = function (data, status, xhr) {
        self.StoresPresent = data.d.TrueOrFalse;

        if (self.StoresPresent == false) {
            $('#mainmenu_stores').data('disabled', true);
            $('#mainmenu_stores').addClass('ui-disabled');
        }
        else {
            $('#mainmenu_stores').data('disabled', false);
            $('#mainmenu_stores').removeClass('ui-disabled');
        }
    }

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

        helper.DeleteSessionCookies();
        c1('mainmenu row 151: Unable to reach web service. Could not confirm presence of spare part stores.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.LogoutCurrentUser = function () {
        var username = $.cookie("username")
        var userid = $.cookie("user_id");
        var current_session_token = $.cookie("session_token");
        var requester = new AjaxRequest({
            data: { "username": username, "userid": userid, "session_token": current_session_token }, // This is for the json request
            success: self.LogoutSuccess,
            error: self.LogoutFailure,
            url: "RequestUserLogout"
        });
        requester.ExecuteRequest();
    }

    self.LogoutSuccess = function (data, status, xhr) {
        SessionTokenStatus = false;
        helper.DeleteSessionCookies();
        helper.SaveUserSettings();
        locationNavigation.resetToTop();
        $.mobile.navigate("#page_login", { role: "page" });
        e2('mainmenu row 179');
    }

    self.LogoutFailure = function (data, status, xhr) {
        SessionTokenStatus = false;
        helper.DeleteSessionCookies();
        c1('mainmenu row 180: Unable to reach web service. Logout could not be confirmed.');
        $.mobile.navigate("#page_login", { role: "page" });
        e2('mainmenu row 187');

        //DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    return self;

}

var mainMenu = Mainmenu();


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

    //$("#mainmenu_machines").click(function () {
    //    currently_selected_application_section = MACHINES_SECTION;
    //    c1("machines section marked");

    //})

    //alert('remember to activate protocol check. remember to check access to camera.');

    $("#mainmenu_machines").unbind().click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        currently_selected_application_section = MACHINES_SECTION;

        if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_MANUAL) {
            c1('Main menu row 228 - Machine selection preset to manual search.');
            $.mobile.navigate("#page_machineselect", { role: "page" });
        }
        else if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_BARCODE) {
            c1('Main menu row 232 - Machine selection preset to barcode scan.');
            SCAN_PAGE_TARGET = SCAN_MACHINE;
            $.mobile.navigate("#page_scantest", { role: "page" });
        }
        else {
            c1('Main menu row 236 - Machine selection mode unknown. Reseting to manual selection.');
            CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_MANUAL
            $.mobile.navigate("#page_machineselect", { role: "page" });
        }
    });

    $("#mainmenu_joblist").click(function () {
        currently_selected_application_section = USER_SECTION;

    })

    $("#mainmenu_stores").click(function () {
        currently_selected_application_section = SPAREPARTS_SECTION;
        mainMenu.requestUserStockAccess();
    })

    $("#mainmenu_progconfig").click(function () {

        currently_selected_application_section = SETTINGS_SECTION;
        //$.mobile.navigate("#page_personalsettings", { role: "page" });

    })


    $("#mainmenu_logout").click(function () {
        currently_selected_application_section = NO_SECTION_SELECTED;
        mainMenu.LogoutCurrentUser();

    })

    config.setTechnicalGroupsInJobList();
    config.setTaskTypesInJobList();
    config.setFaultTypesInJobList();
    config.setPriorityTypesInJobList();
    config.requestPM5ClientSettings();
    config.populateSigningPersonelFilter();
    config.initializeJobTypesFilter();
    config.checkForMachineAccountExistence();
    mainMenu.testUserMedia();

    mainMenu.testProtocolIsSecure();

    //e1('Test Alpha Bravo Charlie');
    //e2('Test Alpha Bravo Charlie');
    //e3('Test Alpha Bravo Charlie');
    //e4('Test Alpha Bravo Charlie');
    //e5('Test Alpha Bravo Charlie');
})



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

    //$("#mainmenu_machines").unbind().click(function (e) {
    //    e.preventDefault();
    //    e.stopPropagation();
    //    c3(CURRENT_SPAREPART_SEARCH_MODE);

    //    if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_MANUAL) {
    //        c1('test main menu machines button -> manual search');
    //        $.mobile.navigate("#page_machineselect", { role: "page" });
    //    }
    //    else if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_BARCODE) {
    //        c2('test main menu machines button -> barcode scan page');
    //        $.mobile.navigate("#page_barcode_cam", { role: "page" });
    //    }
    //    else {
    //        $.mobile.navigate("#page_machineselect", { role: "page" });
    //    }
    //});


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

        //Hack for hiding first instance of 'Fault groups' button in 'Create new fault' form.
        //Should be moved to some more unobtrusive place.
        $('#createfault_showallfaulttypes').hide();
        $('#finishjobwizard_1_showallfaultcauses').hide();

        mainMenu.requestStockChangeReasonList();
        mainMenu.requestPM5Settings();

        //mainMenu.CheckForSparePartStorePresence();
    }
    else {
        helper.ForcedLogout();
    }


}
  );