/*
 * New multi-login, with support for migrating to Atmail 6.
 */

var value_of = {};                      // remember value of fields by id
                                        // ..across changing apps.

// two cluster styles exist:
// oldest: on clusters 1-7, showing old atmail as default
// slightly_newer: on clusters 8-10, showing roundcube as the default
if (cluster < 8 ) {
    cluster_style = 'oldest';
}
else {
    cluster_style = 'slightly_newer';
}


// either atmail6_available or atmail6_unavailable
// indicates whether or not the user is allowed to migrate
var multi_login_mode = 'atmail6_available';

$(document).ready(function() {//{{{

    // detect which mode we are in by looking at what's visible
    // if both the login (email) and the picker (select) are visible,
    // then obviously atmail6 isn't available
    if ($('#legacy_select_label').is(":visible") && $('#email_label').is(":visible")) {
        multi_login_mode = 'atmail6_unavailable';
    }

    //
    // build application selector
    //
    app_selector = $('select#app');

    app_selector.change(function() {
        value_of[$(this).attr('id')] = $(this).val();

        update_legacy_language();
    });

    // create the optgroups, if atmail6 is on the table
    if (multi_login_mode === 'atmail6_available') {
        app_selector.append(
                $e('optgroup', { 'id' : 'legacy', 'label' : 'Legacy WebMail Clients' })
                );
    }

    $.each( apps, function(i) {
        // skip non-legacy clients if atmail6 isn't available
        if (multi_login_mode === 'atmail6_unavailable') {
            if (apps[i]['section'] !== 'legacy') {
                return;
            }
            app_selector.append(
                $e('option', { 'value' : i }).text(apps[i]['name'])
            );
        }
        else {
            var section = apps[i]['section'];
            if (section) {
                $('optgroup#' + section).append(
                    $e('option', { 'value' : i }).text(apps[i]['name'])
                    );
            }
            else {
                app_selector.prepend(
                    $e('option', { 'value' : i }).text(apps[i]['name'])
                    );
            }
        }
    });

    value_of.app = default_app();

    // allow cookies to override default application and load other saved
    // settings.
    $.extend( value_of, state_from_cookies() );

    // select app (either from cookie or default)
    $('select#app').val(value_of['app']);
    update_legacy_language();

    $('#email').val(value_of['email']);
    $('#Language').val(value_of['Language']);

    // make it faster for the user to enter data by placing focus
    // appropriately
    if ( $('#email').val() == '' ) { // no email entered yet
        $('#email').focus();
    }
    else {
        $('#password').focus();
    }

    // if we're here from the landing page, set up bouncing back
    $('.get-started').click(function(e) {
        e.preventDefault();
        toss_to_landing_page(email, password);
    });

    // listen for submit
    $('input').on('keyup', function(e) {
        if(e.keyCode == 13) {
            $('form#login').submit();
        }
    });
    
    $('#loginbutton').on('click', function(e) {
        $('form#login').submit();
        e.preventDefault();
    });

    // react when form is submitted
    $('form#login').on('submit', handle_login);
}); // end document ready//}}}

/*
 * Decide default application using a bit of black magic based on
 * browser type and version.
 */
function default_app() {//{{{
    if ( $.browser.opera || $.browser.safari ) {
        return 2;       // Atmail simple Ajax
    }
    else if ( $.browser.msie ) {
        if ( parseInt($.browser.version) >= 6 ) {
            return 4;   // Atmail advanced IE6+
        }
        else {
            return 2;   // Atmail simple Ajax
        }
    }
    else if ( $.browser.mozilla ) {
        if ( parseFloat($.browser.version) >= 1.9 ) {
            return 0;   // SquirrelMail. Atmai breaks on FF3
        }
        else {
            return 3;   // Atmail advanced Mozilla
        }
    }
    else {
        return 1;       // Atmail simple Any browser
    }
}//}}}


// function to handle authenticating the user and sending
// them to the migration page or the legacy picker
function handle_login(e) {//{{{
    e.preventDefault();

    // if the legacy webmail select is visible, then
    // handle that selection
    if (multi_login_mode === 'atmail6_available' && $('#legacy_select_label').is(":visible")) {
        login_legacy_email(email, password, { 'record_webmail_type': true});
    }
    else {
        if ($('#email').val() === '') {
            show_error('Please enter a valid email address.');
            return;
        }
        else if ($('#password').val() === '') {
            show_error('Please enter a password.');
            return;
        }

        email = $('#email').val();
        password = $('#password').val();

        $.ajax({
            type: "POST",
            url: "api.php",
            data: { 'email': email, 'password': password, 'method': 'auth' },
            dataType: 'json',
            beforeSend: function() {
                $("span.loading").addClass("loading-animate");
            }
        }).done(function(msg, data) {
            $("span.loading").removeClass("loading-animate");
            if (msg['error']) {
                var errorCode = msg['data']['code'];

                // 1000 means login failed
                // 1002 means invalid email address
                if( errorCode == '1000'  || errorCode == '1002' || errorCode == '1003' ) {
                    show_error( "The email address or password you entered is invalid. Please try again.");
                }
                else {
                    show_error("p.message").html( "Error #" + msg['data']['code'] + ": Login failed. If this continues, please contact your administrator.");
                }
            }
            else {
                // if atmail6 isn't available, do the legacy login
                if (multi_login_mode === 'atmail6_unavailable') {
                    // intentionally don't set the webmail_type here,
                    // as the choice isn't being made yet
                    login_legacy_email(email, password, { 'record_webmail_type': false });
                }
                else if (msg['data']['webmail_type'] === 'legacy') {
                    // 'legacy' means they haven't chosen
                    // form post to landing page
                    toss_to_landing_page(email, password);
                }
                else if (msg['data']['webmail_type'] === 'none') {
                    // 'none' means they're new and should be shuttled over to atmail6

                    // set the webmail_type, and then log them into atmail
                    set_webmail_type(email, password, 'atmail6', function () {
                        login_atmail(email, password, msg['data']['mail_access_domain']);
                    });
                }
                else if (msg['data']['webmail_type'] === 'atmail6') {
                    // 'atmail6' means they've chosen to migrate their settings over
                    login_atmail(email, password, msg['data']['mail_access_domain']);
                }
                else {
                    show_legacy_picker();
                }
            }
        });
    }
}//}}}

function show_error(message) {//{{{
    $("p.message").show();
    $("p.message").removeClass("info error notice");
    $("p.message").addClass("error");

    $("p.message").html(message);
}//}}}

function show_legacy_picker () {//{{{
    $('#mail-ad').show();
    $('p.message').hide();

    $('#loginbutton').text('Go');

    $('#legacy_select_label').show();
    $('#email_label').hide();
    $('#password_label').hide();
    $('#remember_label').hide();
}//}}}

function update_legacy_language() {//{{{
    if ($('#legacy_select_label').is(":visible")) {
        var app = apps[$(app_selector).val()];
        if (app['show_languages']) {
            $('#legacy_select_language_label').show();
        }
        else {
            $('#legacy_select_language_label').hide();
        }
    }
}//}}}

function toss_to_landing_page(email, password) {//{{{
    $('body').append(
            $e('form', {'id':'exit', 'method':'post', 'action':'landing.php'})
            .append($e('input', { 'name' : 'password', 'type' : 'hidden', 'value' : password }))
            .append($e('input', { 'name' : 'email', 'type' : 'hidden', 'value' : email }))
            );

    $('form#exit').submit();
}//}}}

function set_webmail_type(email, password, new_webmail_type, callback) {//{{{
    $.ajax({
        type: "POST",
        url: "api.php",
        data: { 'email': email, 'password': password, 'new_webmail_type': new_webmail_type, 'method': 'set_webmail' },
        dataType: 'json',
        beforeSend: function() {
            $("span.loading").addClass("loading-animate");
        }
    }).done(callback).complete(function() {
        $("span.loading").removeClass("loading-animate");
    });
}//}}}

function login_legacy_email(email, password, options) {//{{{
    var app_id = $(app_selector).val();
    var app    = apps[app_id];

    // internal function to actually log into legacy
    function _login_legacy_email() {
        var language = $('#Language').val();

        $('form#legacy_login').remove();
        $('body').append($e('form', {'id':'legacy_login', 'method':'post', 'action':app['url']}));

        $.each( fill_in_values(app['fields'], email, password, language), function(key, value) {
            $('form#legacy_login').append($e('input', { 'name' : key, 'type' : 'hidden', 'value' : value }))
        });

        if (!app['skip_cookie_save']) {
            save_state_to_cookies(app_id, email, language);
        }
        if (app['extra_func']) {
            app['extra_func']();
        }
        $('form#legacy_login').submit();
    }

    if (app['webmail_type'] && options['record_webmail_type']) {
        // set the webmail_type, and then log them into whatever they selected
        set_webmail_type(email, password, app['webmail_type'], _login_legacy_email);
    }
    else {
        _login_legacy_email();
    }
}//}}}

/*
 * Application Configuration:
 */
var apps = new Array();//{{{

apps[0] = {
    'name'         : 'SquirrelMail',
    'section'      : 'legacy',
    'webmail_type' : 'squirrelmail',
    'url'          : '/.tools/squirrelmail/current/src/redirect.php',
    'fields'       : {
        'login_username'        : '#email#',
        'secretkey'             : '#password#',
        'just_logged_in'        : 1,
        'js_autodetect_results' : 1
    }
};
apps[1] = {
    'name'           : 'Atmail - Simple (Any browser)',
    'section'      : 'legacy',
    'webmail_type'   : 'atmail5',
    'show_languages' : true,
    'url'            : '/.tools/atmail/current/atmail.php',
    'fields'         : {
        'username'         : '#user#',
        'pop3host'         : '#domain#',
        'password'         : '#password#',
        'LoginType'        : 'simple',
        'Language'         : '#language#',
        'MailType'         : 'imap',
        'pop3hostexternal' : ''
    }
};
apps[2] = {
    'name'           : 'Atmail - Simple (AJAX)',
    'section'      : 'legacy',
    'show_languages' : true,
    'url'            : apps[1]['url'],
    'fields'         : $.extend({}, apps[1]['fields'], {'LoginType' : 'ajax'})
};
apps[3] = {
    'name'           : 'Atmail - Advanced (Mozilla)',
    'section'      : 'legacy',
    'show_languages' : true,
    'url'            : apps[1]['url'],
    'fields'         : $.extend({}, apps[1]['fields'], {'LoginType' : 'xul'})
};
apps[4] = {
    'name'           : 'Atmail - Advanced (IE6+)',
    'section'      : 'legacy',
    'show_languages' : true,
    'url'            : apps[1]['url'],
    'fields'         : $.extend({}, apps[1]['fields'], {'LoginType' : 'xp'})
};
apps[5] = {
    'name'   : 'Edit your settings with uControl',
    'section'      : 'legacy',
    'url'    : '/.tools/ucontrol/current/',
    'fields' : {
        'email'    : '#email#',
        'password' : '#password#'
    }
};
apps[6] = {
    'name'         : 'RoundCube [beta]',
    'section'      : 'legacy',
    'webmail_type' : 'roundcube',
    'url'          : '/.tools/roundcube/current/',
    'extra_func'   : function () { $.cookie( 'roundcube_sessid', '-', { path : '/' } ); },
    'fields'       : {
        '_user'   : '#email#',
        '_pass'   : '#password#',
        '_action' : 'login'
    }
};
apps[7] = {
    'name'             : 'Mail by (mt)',
    'url'              : 'landing.php',
    'skip_cookie_save' : true,
    'fields'           : {
        'email'    : '#email#',
        'password' : '#password#'
    }
};

if (cluster_style === 'slightly_newer') {
    apps2 = new Array();

    // first app is RoundCube
    apps2[0] = apps[6];
    apps2[0]['name'] = 'RoundCube [Recommended]';

    // next up is SquirrelMail
    apps2[1] = apps[0];

    // then uControl
    apps2[2] = apps[5];

    // last is the glorious new atmail 6
    apps2[3] = apps[7];

    apps = apps2;
}
//}}}

