var UserManagement = {

    init: function (puzzleId, serviceURL, loginTime) {


        this.loginAborted = false;
        this.isLoggedIn = false;

        //Set class variables
        this.puzzleId = puzzleId;
        this.serviceURL = serviceURL;
        this.loginTime = loginTime;
        

        setTimeout(function()
        {
            if(UserManagement.loginTime)
            {
                UserManagement.addInterface();
            }

            if(UserManagement.loadUserState() == false)
            {
                UserManagement.onLoad();
            }
        }, 100);
    },

    addInterface: function() {

        var userToolbar = $("#user-toolbar");

        if (userToolbar.length === 0)
        {
            userToolbar = $("<div id='user-toolbar' class='toolbar'>\n\
                                           <div id='user-toolbar-form' style='text-align:right;'><input id='login-btn' class='login-btn-management' type='button' value='Login'/></div>\n\
                                       </div>");
            
            userToolbar.css({
                "position" : "relative",
                "top": "0px",
                "left": "0px",
                "width": "100%",
                "height": "24px",
                "color": "#FFF",
                "font-weight": "bold",
                "font-size": "18px",
                "background-color" : "transparent"
            });
        }

        userToolbar.prependTo($("body"));

        $('#login-btn').click(function() {
            if(UserManagement.isLoggedIn)
            {
                UserManagement.doLogout(null);
            }
            else
            {
                UserManagement.loginFrom = "toolbar";
                UserManagement.doLogin(null);
            }
        });
    },

    onLoad: function() {

        if(this.loginTime && this.loginTime == "1")
        {
            if(puzzleTimer){
                puzzleTimer.stop();}

            this.loginFrom = "start";
            UserManagement.doLogin();
        }
    },

    submitLeaderboard: function(callback) {

        if(this.loginTime)
        {
            this.loginFrom = "end";
            UserManagement.doLogin(callback);
        }
    },

    doLogin: function(callback) {

        if(this.isLoggedIn)
        {
            //If we were paused, start the timer just in case.
            //Klinde[TODO]: Might have to be conditional. If tutorial is showing, don't!
            $('#puzzle-dimmed-layer').fadeOut();
            if(puzzleTimer && !puzzleTimer.isCounting()){
                puzzleTimer.resume();}

            if(callback != null)
            {
                callback(true);
            }
            return;
        }

        this.loginAborted = false;
        this.loginCallback = callback;
        UserManagement.showLoginBox();
    },

    onLoggedIn: function() {

        this.isLoggedIn = true;

        if(this.loginCallback)
        {
            this.loginCallback(true);
        }

        this.saveUserState("");
        $('#login-btn').val('Logout');

        //If we were paused, start the timer just in case.
        //Klinde[TODO]: Might have to be conditional. If tutorial is showing, don't!
        $('#puzzle-dimmed-layer').fadeOut();
        if(puzzleTimer && !puzzleTimer.isCounting()){
            puzzleTimer.resume();}

        TrackPuzzle.analyticsEvent("UserManagement", "Login", this.loginFrom);
    },

    doLogout: function(callback) {

        this.loginCallback = callback;

        this.onLogOut();

        TrackPuzzle.analyticsEvent("UserManagement", "Logout");
    },

    onLogOut: function() {

        this.isLoggedIn = false;

        if(this.loginCallback)
        {
            this.loginCallback(false);
        }

        this.clearUserState();
        $('#login-btn').val('Login');
    },

    isLoggedIn: function() {

        return this.isLoggedIn;
    },

    isPending: function() {

        if(this.loginTime)
        {
            if(this.loginTime == '0')
                return false;
        }
        else
        {
            return false;
        }

        if(this.isLoggedIn)
            return false;

        if(this.loginAborted)
            return false;

        return true;
    },

    isRequired: function() {
        if(this.loginTime && (this.isLoggedIn == false))
        {
            return true;
        }
        else
        {
            return false;
        }
    },

    getUserId: function() {
        if(this.loginTime && this.isLoggedIn)
        {
            return this.userId;
        }

        return -1;
    },

    showLoginBox: function(callback) {
        var gameLoginForm = $("#puzzle-login-form");
        if (gameLoginForm.length === 0) {
            gameLoginForm = $("<div id='puzzle-login-form' class='puzzle-box'>\n\
                                           <div class='close-btn'>x</div>\n\
                                           <div id='puzzle-login-form-content'></div>\n\
                                       </div>");
            
            gameLoginForm.css({
                "color": "#FFF",
                "font-weight": "bold",
                "font-size": "18px",
                "padding": "30px",
                "top": "75px",
                "border": "2px solid #FFF",
                "border-radius": "10px",
                "cursor": "pointer"
            });
        }

        gameLoginForm.find('.close-btn').click(function() {
            
            if(UserManagement.loginCallback)
            {
                UserManagement.loginCallback(false);
            }

            //Force resume just in case we were paused.
            if(puzzleTimer && !puzzleTimer.isCounting()){
                puzzleTimer.resume();}

            $('#puzzle-dimmed-layer').fadeOut();

            UserManagement.loginAborted = true;
            gameLoginForm.fadeOut();
        });


        UserManagement.showLoginForm(gameLoginForm);
        gameLoginForm.appendTo($("div.puzzle"));

        $('#puzzle-dimmed-layer').fadeIn();
        gameLoginForm.fadeIn();


        //HAcks for focus..
        TweenLite.to($('#puzzle-login-form'), 0, {z: 42});
        TweenLite.to($('.close-btn'), 0, {z: 44});

    },
    showRegisterForm: function (gameLoginForm)
    {

        gameLoginForm.find('#puzzle-login-form-content').html('<form id="registerForm" medthod="post" action="#" onsubmit="return false;"></div>');

        var formContent = gameLoginForm.find('#puzzle-login-form-content').find('#registerForm');

        var puzzleId = "" + UserManagement.puzzleId;
        var requestOperation = "getRegister";

        formContent.load(this.serviceURL,{
            "puzzle_id": puzzleId,
            "request": requestOperation
        }, function()
        {

            var buttonRow = '<input style="float:left;" class="register-btn-back" name="back" value="Back" type="button">\n\
                            <input style="float:right;" class="register-btn-register"  name="submit" value="Register" type="submit">\n\
                            ';

            formContent.append(buttonRow);


            $(formContent).find('input.register-btn-back').click(function() {
                UserManagement.showLoginForm(gameLoginForm);

                return false;
            });

            $(formContent).find('input.register-btn-register').click(function()
            {

                var puzzleId = "" + UserManagement.puzzleId;
                var requestOperation = "doRegister";

                var formField = { "puzzle_id": puzzleId, "request": requestOperation};

                formContent.find('input').each(function()
                {
                    var fieldName = $(this).attr('name');
                    var type = $(this).attr('type');
                    var fieldValue = null;

                    if(type == 'radio')
                    {
                        var doContinue = true;
                        
                        if($(this).prop("checked"))    //jquery 1.9+
                        {
                           doContinue = false;
                        }

                        if($(this).attr('checked') == 'checked')
                        {
                           doContinue = false;
                        }

                        //Radiogroup, skipp if the given radio is not checked, to proceed to others.
                        
                        if(doContinue)
                            return true;

                        
                        fieldValue = $(this).val();
                    }
                    else if(type == 'checkbox')
                    {
                        fieldValue = $(this).is(":checked") ? "1" : "0";
                    }
                    else
                    {
                        fieldValue = $(this).val();
                    }
                    
                    formField[fieldName] = fieldValue;
                });

                formContent.find('select').each(function()
                {
                    var fieldName = $(this).attr('name');
                    var fieldValue = $(this).val();
                    formField[fieldName] = fieldValue;
                });

                $.ajax({
                    contentType : "application/x-www-form-urlencoded; charset=utf-8",
                    dataType : "json",
                    type : "POST", 
                    async : false,
                    timeout: 5000,
                    url : UserManagement.serviceURL,
                    data : formField,
                    success: function(msg)
                    {
                        if(msg.success)
                        {
                            UserManagement.userId = msg.data.user_id;
                            //alert("user loged in as: " + UserManagement.userId);

                            UserManagement.onLoggedIn();

                            gameLoginForm.fadeOut();
                        }
                        else
                        {
                            alert(msg.msg);
                        }
                    },
                    complete: function()
                    {
                    }
                });

                return false;
            });



        });

    },
    showLoginForm: function (gameLoginForm) {

        var formContent = gameLoginForm.find('#puzzle-login-form-content');

        formContent.html('  <form id="loginForm" medthod="post" action="#" onsubmit="return false;">\n\
                                <div>\n\
                                    <input name="username" type="text" placeholder="Username">\n\
                                    <br class="break"/>\n\
                                    <input name="password" type="password" placeholder="Password">\n\
                                </div>\n\
                                <input style="float:left;" class="login-btn-forgot" name="forgot" value="Forgot Password" type="button">\n\
                                <input style="float:left;" class="login-btn-register" name="register" value="Register" type="button">\n\
                                <input style="float:right;" class="login-btn-login" name="submit" value="Login" type="submit">\n\
                            </form>');

        $(formContent).find('input.login-btn-register').click(function() {
            UserManagement.showRegisterForm(gameLoginForm);
        });

        $(formContent).find('input.login-btn-forgot').click(function() {
            UserManagement.showForgotForm(gameLoginForm);
        });

        $(formContent).find('input.login-btn-login').click(function()
        {
            var puzzleId = "" + UserManagement.puzzleId;
            var requestOperation = "doLogin";

            var formField = { "puzzle_id": puzzleId, "request": requestOperation};

            formContent.find('input').each(function()
            {
                var fieldName = $(this).attr('name');
                var fieldValue = $(this).val();
                formField[fieldName] = fieldValue;
            });

              $.ajax({
                contentType : "application/x-www-form-urlencoded; charset=utf-8",
                dataType : "json",
                type : "POST", 
                async : false,
                timeout: 5000,
                url : UserManagement.serviceURL,
                data : formField,
                success: function(msg)
                {
                    if(msg.success)
                    {
                        UserManagement.userId = msg.data.user_id;

                        UserManagement.onLoggedIn();

                        gameLoginForm.fadeOut();
                    }
                    else
                    {
                        alert(msg.msg);
                    }
                },
                complete: function()
                {
                }
            });

            return false;
        });

    },
    showForgotForm: function (gameLoginForm) {

        var formContent = gameLoginForm.find('#puzzle-login-form-content');

        formContent.html('<form id="forgotForm" medthod="post" action="#">\n\
                                <div>\n\
                                    <input name="email" class="email" type="email" placeholder="E-mail"/>\n\
                                    <br class="break"/>\n\
                                    <input style="float:left;" class="forgot-btn-back" name="forgot" value="Back" type="button"/>\n\
                                    <input style="float:right;" class="forgot-btn-submit" name="submit" value="Submit" type="submit"/>\n\
                                </div>\n\
                          </form>');

        $(formContent).find('input.forgot-btn-back').click(function() {
            UserManagement.showLoginForm(gameLoginForm);
        });

        $(formContent).find('input.forgot-btn-submit').click(function()
        {
            var email = $('#forgotForm').find('.email').val();

            if (email == '')
                return false;
            
            $.ajax({
                type: 'POST',
                dataType: 'json',
                async: false,
                url: baseURL + '/password.php?do=set_forgot',
                data: 'email=' + email,
                success: function(data)
                {
                    if (data.success == 1)
                    {
                        alert('A mail has been sent to the given address. Please follow the intructions in it');
                    }
                    else
                    {
                        alert(data.message);
                    }
                }
            });
            
            return false;
        });

    },
    saveUserState: function(value) {
        var timeString = "";
        if (this.userId > -1 && this.isLoggedIn) {
            timeString = ";" + this.userId;
        }

        value += timeString;
        if (GameState.isCookiesSupported())
            GameState.setCookie(this.cookieName, value);
        else if (GameState.isLocalStorageSupported())
            localStorage[this.cookieName] = value;
    },
    loadUserState: function() {
        if (this.loginTime)
        {

            var userStateString = false;
            if (GameState.isCookiesSupported())
            {
                userStateString = GameState.getCookie(this.cookieName);
            }
            else if (GameState.isLocalStorageSupported())
            {
                userStateString = localStorage[this.cookieName];
            }

            if (userStateString)
            {
                userStateString = userStateString.split(";");
                
                //Set userId if available
                if (userStateString.length > 1)
                {
                    this.userId = userStateString[1];
                    this.onLoggedIn();
                }

                //Return user state
                if (userStateString.length > 0)
                    return userStateString[0];
                
            }

        }
        
        return false;
    },
    clearUserState: function() {
        if (GameState.isCookiesSupported())
            GameState.setCookie(this.cookieName, "");
        else if (GameState.isLocalStorageSupported())
            localStorage[this.cookieName] = "";
    },
    loginTime: undefined,
    puzzleId: undefined,
    serviceURL: undefined,
    isLoggedIn: false,
    loginAborted: false,
    loginCallback: undefined,
    userId: undefined,
    cookieName: "user-state",
    loginFrom: undefined
};