

function Login() {

    var self = {};


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



    self.sendLoginRequestJson = function () {
        var username = $("#tbLoginUserName").val();
        var password = $("#tbLoginPassword").val();


        var requester = new AjaxRequest({
            data: { "username": username, "password": password }, // This is for the json request
            success: self.LoginRequestSuccess,
            error: self.LoginRequestError,
            url: "ValidateLoginWithIDJson"
        });
        requester.ExecuteRequest();

    }

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

        var userID = data.d.UserID;
        var sessionToken = data.d.SessionToken;
        var errorCode = data.d.ErrorCode;
        var loginGranted = data.d.LoginGranted;

        SessionTokenStatus = true;

        if (data.d.LoginGranted == true) {


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

            $.cookie("username", $("#tbLoginUserName").val());
            $.cookie("session_token", sessionToken);
            $.cookie("user_id", userID);
            self.SetApplicationLanguage();
            $('#tbLoginUserName, #tbLoginPassword').val('');

            CURRENT_MACHINE_SEARCH_MODE = $.cookie("machine_search_mode");
            
            var incoming_sp_search_mode = $.cookie("sparepart_search_mode");

            if (incoming_sp_search_mode !== null && incoming_sp_search_mode !== undefined) {
                CURRENT_SPAREPART_SEARCH_MODE = incoming_sp_search_mode;
            }
            else {
                CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            }

            var incoming_jobid_search_mode = $.cookie("jobid_search_mode");
            if (incoming_jobid_search_mode !== null && incoming_jobid_search_mode !== undefined) {
                CURRENT_JOBID_SEARCH_MODE = incoming_jobid_search_mode;
            }
            else {
                CURRENT_JOBID_SEARCH_MODE = JOBID_SEARCH_INPUT_MANUAL;
            }

            var incoming_consumption_on_job_search_mode = $.cookie("consumption_on_job_mode");
            if (incoming_consumption_on_job_search_mode !== null && incoming_consumption_on_job_search_mode !== undefined) {
                CONSUMPTION_SP_SEARCH_MODE = incoming_consumption_on_job_search_mode;
            }
            else {
                CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            }
          
        }
        else {

            switch (errorCode) {
                case 1:
                    $("#login_errortext").text(ReturnPhraseOnKey('login_errormessage_incorrect_credentials'));
                    break;
                case 2:
                    $("#login_errortext").text(ReturnPhraseOnKey('login_errormessage_incorrect_credentials'));
                    break;
                case 3:
                    $("#login_errortext").text(ReturnPhraseOnKey('login_errormessage_trial_period_expired'));
                    break;
                case 4:
                    $("#login_errortext").text(ReturnPhraseOnKey('login_errormessage_all_login_slots_taken'));
                    break;
                case 5:
                    $("#login_errortext").text(ReturnPhraseOnKey('login_errormessage_previous_mobile_login_exists'));
                    break;
            }

            if ($('#login_errortext').is(":hidden")) {
                $('#login_errortext').show();
            }
        }

    }

    self.LoginRequestError = function (jqXHR, textStatus, errorThrown) {
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_LOGIN);
    }



    self.SetApplicationLanguage = function () {

        var userId = $.cookie("user_id");

        var requester = new AjaxRequest({
            data: { "loginUserId": userId }, // This is for the json request
            success: self.LanguageChangedSuccess,
            error: self.LanguageChangedError,
            url: "RequestLanguageIdOnUserId"
        });
        requester.ExecuteRequest();

    }

    self.LanguageChangedSuccess = function (data, status, xhr) {
        var languageId = data.d;

        if (CurrentSelectedLanguage != languageId) {
            CurrentSelectedLanguage = languageId;
            self.SetLanguage();
        }

        $.mobile.navigate("#page_mainmenu", { role: "page" });
    }

    self.LanguageChangeError = function (request, status, error) {

        alert('error while changing language');
    }

    self.SetLanguage = function () {
        if (CurrentSelectedLanguage == LANG_DK) {
            RunLanguageUpdate(dk);
            SetDatePickerToDanish();
        }
        else if (CurrentSelectedLanguage = LANG_ENG) {
            RunLanguageUpdate(eng);
            SetDatePickerToEnglish();
        }

        //if (hasGetUserMedia()) {

        //    alert('getUserMedia() seems to trigger correctly');

        //} else {
        //    alert('getUserMedia() is not supported in your browser');
        //}

    }


    function hasGetUserMedia() {
        return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
                  navigator.mozGetUserMedia || navigator.msGetUserMedia);
    }

    return self;
}

var login = Login();

$(document).one("pageshow", "#page_login", function (e) {
    $('#tbLoginUserName, #tbLoginPassword').bind("enterKey", function (e) {
        login.sendLoginRequestJson();
    });

    $('#tbLoginUserName, #tbLoginPassword').keyup(function (e) {
        if (e.keyCode == 13) {
            $(this).trigger("enterKey");
        }
    });
});


$(document).on("pageshow", "#page_login", function (e) {
        
    //alert('Remember to activate testProtocolIsSecure in mainmenu.js');

    helper.DeleteSessionCookies();

    $(".default_errormessage").hide();

    $("#bLoginSubmit").unbind().click(function () {

        login.sendLoginRequestJson();
    });

    login.SetLanguage();


});

//$(document).on("pageshow", function (e)
//{
     
        
//    var f = arguments.callee.caller;
//    if (f != null)
//    {
//        f = f.toString();
//        console.log($.mobile.activePage.attr("id") + ' pageshow');
//    }

//});

//$(document).on("pagecontainerbeforehide", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('1)' + $.mobile.activePage.attr("id") + ' pagecontainerbeforehide');
//    }
//});

//$(document).on("pagecontainerhide", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('2)' + $.mobile.activePage.attr("id") + ' pagecontainerhide');
//    }
//});


//$(document).on("pagecontainerbeforeshow", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('3)' + $.mobile.activePage.attr("id") + ' pagecontainerbeforeshow');
//    }
//});

//$(document).on("pageremove", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('4)' + $.mobile.activePage.attr("id") + ' pageremove');
//    }
//});

//$(document).on("pagecontainerbeforeload", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('5)' + $.mobile.activePage.attr("id") + ' pagecontainerbeforeload');
//    }
//});

//$(document).on("pagecontainerload", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('6)' + $.mobile.activePage.attr("id") + ' pagecontainerload');
//    }
//});

//$(document).on("changePage", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('7)' + $.mobile.activePage.attr("id") + ' changePage');
//    }
//});

//$(document).on("pagecontainerbeforetransition", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        //alert('8)' + $.mobile.activePage.attr("id") + ' pagecontainerbeforetransition');
//        console.log('8)' + ' pagecontainerbeforetransition');
//    }
//});

//$(document).on("pagecontainertransition", function (e) {


//    var f = arguments.callee.caller;
//    if (f != null) {
//        f = f.toString();
//        console.log('9)' + $.mobile.activePage.attr("id") + ' pagecontainertransition');
//    }
//});