/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.current_user = null;
FLYFI.didInitialLogin = false; // prevent recursion when page is first loaded

FLYFI.loggedIn = function() {
    return FLYFI.current_user && FLYFI.current_user.hasPassword; // if no password, then its an 'artifical' user
};

FLYFI.onLogin_reloadPage = function() { // bind this to FLYFI.MSG_LoginUpdated on pages that need to reload on Login
    if (FLYFI.didInitialLogin) {
        document.location.reload(); // on change in login, need to reload the page to see the right lists
        return;
    } 
    FLYFI.didInitialLogin = true;  // first time, we just get to see the page
};

FLYFI.onTimer_ensureLoggedIn = function() {
    if (!FLYFI.loggedIn()) { // if no password, then its an 'artifical' user
        FLYFI.loginLinks().click();
    }
};

FLYFI.ensureLoggedIn = function() {
    setTimeout(FLYFI.onTimer_ensureLoggedIn, 1500); // NYI - should trigger after initial login
};

FLYFI.resetDialog_Login = function() {
    var dialog = $('#login_dialog');
    dialog.find('.login_button').removeAttr("disabled");
    dialog.find('.cancel_button').removeAttr("disabled");
    dialog.find('.dialog_error').text('').hide();
    dialog.find('#nickname_field').focus();
};

FLYFI.onClick_Login = function(event) {
    var dialog = $('#login_dialog');
    dialog.find('.login_button').attr("disabled", "disabled");
    dialog.find('.cancel_button').attr("disabled", "disabled");
    FLYFI.postJSONWithSpinner('/json/login/',
        { nickname: $('#login_dialog #nickname_field').val(),
          password: $('#login_dialog #password_field').val()
        },
        '#login_dialog .spinner',
        FLYFI.onServer_Login,
        FLYFI.resetDialog_Login);
    if (event) {
        event.preventDefault();
    }
};

FLYFI.onServer_Login = function(json) {
    FLYFI.resetDialog_Login();
    if (json.error) {
        $('#login_dialog .dialog_error').text(json.error).show();
        return;
    }
     
    $('#login_dialog #password_field').val('');
    FLYFI.setUser(json.user);
    tb_remove();
};

FLYFI.resetDialog_Signup = function() {
    var dialog = $('#signup_dialog');
    dialog.find('.signup_button').removeAttr("disabled");
    dialog.find('.cancel_button').removeAttr("disabled");
    dialog.find('.dialog_error').text('').hide();
};

FLYFI.onClick_Signup = function(event) {
    var dialog = $('#signup_dialog');
    dialog.find('.signup_button').attr("disabled", "disabled");
    dialog.find('.cancel_button').attr("disabled", "disabled");
    var affiliation = dialog.find('#affiliation_id').val();
    FLYFI.postJSONWithSpinner('/json/signup/',
        { nickname: dialog.find('#nickname').val(),
          password: dialog.find('#password').val(),
          password_2: dialog.find('#password_2').val(),
          email: dialog.find('#email').val(),
          affiliation_id: affiliation ? affiliation : ''
        },
        '#signup_dialog .spinner',
        FLYFI.onServer_Signup,
        FLYFI.resetDialog_Signup);
    if (event) {
        event.preventDefault();
    }
};

FLYFI.onServer_Signup = function(json) {
    FLYFI.resetDialog_Signup();
    var dialog = $('#signup_dialog');
    var user = json.user;
    var error = json.error;
    if (user) { 
        FLYFI.setUser(user);
        $('#sign_in_sign_up').hide();
        tb_remove();
    } else {
        if (error) { // We don't give the user time to read the message so don't show if signup was OK
            dialog.find('.dialog_error').text(error).show();
        }
    } 
};

FLYFI.onClick_LogoutLink = function(event) {
    if (FLYFI.current_user) {
        FLYFI.postJSONWithSpinner('/auth/json/logout/',
            {},
            '#audnavcontainer .spinner',
            function() {
                FLYFI.loginLinks().show();
                FLYFI.signupLinks().show();                
                FLYFI.logoutLinks().hide();
                FLYFI.setUser(null);
            },
            FLYFI.showJSONError);
    }
    if (event) {
        event.preventDefault();
    }
};

FLYFI.setUser = function(user) {
    FLYFI.current_user = user;
    if (FLYFI.loggedIn()) {
        var name = FLYFI.current_user.nickname;
        FLYFI.loginLinks().hide();
        FLYFI.signupLinks().hide();        
        FLYFI.logoutLinks().show();
        FLYFI.noMemberNameLinks().hide();
        FLYFI.memberNameLinks().text(name).show();
    } else {
        FLYFI.logoutLinks().hide();
        FLYFI.loginLinks().show();
        FLYFI.signupLinks().show();        
        FLYFI.noMemberNameLinks().show();
        FLYFI.memberNameLinks().text('').hide();
    }
    
    $(window).trigger(FLYFI.MSG_LoginUpdated);
};

FLYFI.onClick_LoginDialogSignupLink = function(event) {
    tb_remove(); // close the login dialog
    setTimeout(FLYFI.showSignup, 400); // do this on a timer so ThickBox has time to reset itself
};
FLYFI.showSignup = function () {
    $('.signup_link').click(); 
};
FLYFI.showLogin = function () {
    $('.login_link').click(); 
};

FLYFI.onClick_ForgotPasswordSignupLink = function(event) {
    event.preventDefault();
    tb_remove(); // close the login dialog
    setTimeout(FLYFI.showForgotPassword, 400); // do this on a time so ThickBox has time to reset itself
};
FLYFI.showForgotPassword = function () {
    var dialog = $('#signup_dialog');
    dialog.find('.signup_button').removeAttr("disabled");
    dialog.find('.cancel_button').removeAttr("disabled");
    dialog.find('.dialog_error').text('').hide();
    $('#forgot_password_link').click(); 
};    

FLYFI.start_currentUser = function() {
    if (window.FlyFi_jsonOwner) {
        FLYFI.setUser(window.FlyFi_jsonOwner);
    } else {
        FLYFI.loginLinks().show();
    }
    $('#loadskrim').hide();
};

FLYFI.onSubmit_ForgotPassword = function(event) {
    event.preventDefault();
    FLYFI.postJSONWithSpinner('/' + window.level + '/auth/json/forgotpassword/',
        { email: $('#forgot_password_email').val(),
          nickname: $('#forgot_password_nickname').val()
        },
        '#forgot_password_dialog .spinner',
        FLYFI.onServer_ForgotPassword,
        FLYFI.showJSONError);
};

FLYFI.onServer_ForgotPassword = function(json) {
    if (json && json.substr(0, 'Success'.length) == 'Success') {
        var s = json.split('\t');
        $('#password_reminder_dialog .nickname').text(s[1]);
        $('#password_reminder_dialog .email').text(s[2]);
        tb_remove();
        setTimeout(FLYFI.onSuccess_ForgotPassword, 500);
    } else {
        $('#forgot_password_dialog .dialog_error').text(json);
    }
};

FLYFI.onSuccess_ForgotPassword = function() {
    $('#forgot_password_success_link').click();
};

FLYFI.loginLinks = function() {
    return $('#auth_verify_signin .login_link, #header .login_link, #homeleftcol .login_link');
};
FLYFI.logoutLinks = function() {
    return $('#header .logout_link');
};
FLYFI.signupLinks = function() {
    return $('#header .signup_link');
};
FLYFI.memberNameLinks = function() {
    return $('#insidepage_rightcol .membername a, #header .membername a, #homeleftcol .membername a');
};
FLYFI.noMemberNameLinks = function() {
    return $('#insidepage_rightcol .nomembername a, #homeleftcol .nomembername a');
};

$(document).ready(function() {
    FLYFI.loginLinks().click(FLYFI.resetDialog_Login); 
    $('#auth_login .signup_link, #homeleftcol .signup_link, #insidepage_rightcol .signup_link, #login_dialog .signup_link').click(FLYFI.resetDialog_Signup); 
    FLYFI.logoutLinks().click(FLYFI.onClick_LogoutLink);
    $('#login_form').submit(FLYFI.onClick_Login);
    $('#signup_form').submit(FLYFI.onClick_Signup);
    $('#login_dialog_signup_link').click(FLYFI.onClick_LoginDialogSignupLink);
    $('#forgot_password_dialog_link').click(FLYFI.onClick_ForgotPasswordSignupLink);
    $('#forgot_password_form').submit(FLYFI.onSubmit_ForgotPassword);
    if (typeof(tb_remove) != 'undefined') {
        $('#thickbox_password_reminder_dialog .ok').click(tb_remove);
    }
});

