
GFLoginManager = function()
{
    var dom             = {};
    var FORMAT_PARAM    = "format";
    var onLoginSuccess  = null;
    var onLoginFailure  = null;
    var onLogoutSuccess = null;
    var onLogoutFailure = null;

    // temporary to create a panel for use as a dialog box
    function createLightPanel(title, div, size)
    {
        var width = size || "400px";
        var panel = new YAHOO.widget.Panel(title,{width: width, 
                                                  constraintoviewport: true,
                                                  fixedcenter: true,
                                                  close: true,
                                                  draggable: true,
                                                  zindex:4,
                                                  modal: true,
                                                  visible: true});
        panel.setHeader(title);
        panel.setBody(div);
        panel.render(document.body);
        div.style.display = "block";
        return panel;
    }

    function show_register(show)
    {
        if (show)
        {
            if ( ! dom.panel_register)
            {
                var registerdiv = document.getElementById("panel_register");
                dom.panel_register = createLightPanel("Register", registerdiv);
                var button_register = new YAHOO.widget.Button("reg_button_register");
                button_register.on("click", function () {
                    var url       = "/accounts/register?" + FORMAT_PARAM + "=json";
                    var email     = $("#reg_input_email").val().trim();
                    var firstname = $("#reg_input_first_name").val().trim();
                    var lastname  = $("#reg_input_last_name").val().trim();
                    var nickname  = $("#reg_input_nick_name").val().trim();
                    var password1 = $("#reg_input_password1").val().trim();
                    var password2 = $("#reg_input_password2").val().trim();

                    if (!EmailFilter.test(email))
                    {
                        alert("Please enter a valid email address.")
                        return ;
                    }

                    if (password1 == "")
                    {
                        alert("Empty passwords not allowed.")
                        return ;
                    }

                    if (password1 != password2)
                    {
                        alert("Passwords do not match.")
                        return ;
                    }

                    var callback = {
                        success: function(response) {
                            var json = JSON.parse(response.responseText);
                            if (json.code.toString() != "0")
                            {
                                document.getElementById("registration_result").innerHTML = json.value;
                            }
                            else
                            {
                                if (dom.panel_register) {
                                    dom.panel_register.hide();
                                }
                                $("#input_username").val(email);
                                $("#input_password").val(password1);
                                document.getElementById("login_result").innerHTML = json.value;
                            }
                        },
                        failure: ajaxErrorHandler,
                        argument: {}
                    };
                    var data = "email=" + email     +
                        "&password1=" + password1   +
                        "&password2=" + password2   +
                        "&first_name=" + firstname  + 
                        "&nick_name=" + nickname  + 
                        "&last_name=" + lastname;

                    var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback, data);
                });
            }
            dom.panel_register.show();
        }
        else
        {
            if (dom.panel_register)
            {
                dom.panel_register.destroy();
                dom.panel_register= null;
            }
        }
    }

    function show_login(show, callback)
    {
        if (show)
        {
            if ( ! dom.panel_login)
            {
                var logindiv = document.getElementById("panel_login");
                dom.panel_login = createLightPanel("Login", logindiv);
                var button_login = new YAHOO.widget.Button("button_login");
                button_login.on("click", function () {
                    var url = "/accounts/login?" + FORMAT_PARAM + "=json";
                    var callback = {
                        success: function(response) {
                            var json = JSON.parse(response.responseText);
                            if (json['code'] == 0)
                            {
                                var uservalue = json['value'];
                                show_login(false);
                                userInfo.user = "LOGGEDIN";
                                document.getElementById("logged_in").style.display = "block";
                                document.getElementById("logged_out").style.display = "none";

                                if (typeof onLoginSuccess !== 'undefined' && onLoginSuccess != null)
                                {
                                    onLoginSuccess();
                                }
                                onLoginSuccess = null;
                                onLoginFailure  = null;
                            }
                            else
                            {
                                $("#login_result").html(json.value);
                                if (typeof onLoginFailure !== 'undefined' && onLoginFailure != null)
                                {
                                    onLoginFailure();
                                }
                                onLoginSuccess = null;
                                onLoginFailure  = null;
                            }
                        },
                        failure: ajaxErrorHandler,
                        argument: {},
                    };

                    var username    = $("#input_username");
                    var password    = $("#input_password");
                    var data        = "username=" + username.val() + "&password=" + password.val();
                    var transation = YAHOO.util.Connect.asyncRequest('POST', url, callback, data);
                });
                var button_registerlink = new YAHOO.widget.Button("button_registerlink");
                button_registerlink.on("click", show_register);
            }
            dom.panel_login.show();
        }
        else
        {
            if (dom.panel_login)
            {
                dom.panel_login.destroy();
                dom.panel_login = null;
            }
        }
    }


    return {
        getActiveAlias:     function()
        {
            // alert("Cookie, Index: " + get_cookie("activeUserAlias") + ", " + $("#userAliases").val());
            var val = get_cookie("activeUserAlias");
            if (val == "null") return "";
            return  val || "";
        },

        // 
        // Selects the active user alias by referring to the appropriate cookie or
        // if non is found then sets the curretnly selected alias as the active
        // one.
        selectActiveAlias:  function()
        {
            var activeAlias = get_cookie("activeUserAlias");
            var selAlias = $("#userAliases option[value='" + activeAlias + "']").val();
            if (activeAlias && typeof selAlias != 'undefined' && selAlias)
            {
                $("#userAliases").val(activeAlias);
            }
            else
            {
                SetCookie("activeUserAlias", $("#userAliases").val(), 2);
            }
        },

        login: function(onLogin)
        {
            onLoginSuccess  = onLogin;
            onLoginFailure  = null;
            show_login(true);
        },

        logout: function(onLogout)
        {
            onLogoutSuccess = null;
            onLogoutFailure = null;
            FB.Connect.logout(function () {

                if (typeof onLogout !== 'undefined' && onLogout)
                    onLogout();
            });
        },

        isLoggedIn: function()
        {
            var userListVal = $("#userAliases").val();
            return (typeof userListVal !== 'undefined' && userListVal != null)
        },

        //
        // This decorator, when we want to applied to a function that needs
        // a user to be logged in, handles all things like bringing up a dialog
        // box, and sending credentials to the server and waiting for
        // authentication before the callback is called.
        //
        // TODO: Limit logins to a given subset of users.
        //
        ensureLogin: function(onSuccess)
        {
            if (typeof onSuccess !== 'undefined' && onSuccess)
            {
                var userListVal = $("#userAliases").val();
                if (!this.isLoggedIn())
                {
                    this.login(onSuccess);
                }
                else
                {
                    onSuccess();
                }
            }
        },
    };
}();


function call_function() 
{
    var args = Array.prototype.slice.call(arguments);
    var func = args.shift();
    return function() {
        return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
    }();
}

function fb_user_logged_in()
{
    // ok now close the box, and go to the "next" page
    // window.location = "{{next}}";
    // FB.Facebook.get_sessionState().waitUntilReady(function() {alert('Hello world - Session now ready');})
    // - next = ' + "{{next}}");
    FB.Facebook.get_sessionState().waitUntilReady(function() { refreshPage(); })
}

