/*
 * Multi-Login recoded in jQuery.
 */

var value_of = {};                      // remember value of fields by id
                                        // ..across changing apps.
$(document).ready(function() {
    // javascript is enabled, clear out the warning message
    $('#my_top_data').empty();

    //
    // build application selector
    //
    $app_selector = $e('select', { 'id' : 'app' })
        .change(function() {
            $(':input').each(function() {
                value_of[$(this).attr('id')] = $(this).val();
            });                         // save current values
            show_app_form( $(this).val() );
        })
        .appendTo('#my_top_data')
        ;
    $.each( apps, function(i) {
        $app_selector.append(
            $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() );
    
    // allow GET query parameter override default application and load other
    // saved settings.
    $.extend( value_of, $.searchparams() );
    
    // don't select ucontrol if they came from ucontrol's webmail link
    if ( $.searchparams().from == 'ucontrol' && value_of.app == 5 ) {
        value_of.app = default_app();
    }

    // set the application to initial value
    $app_selector.val( value_of.app );
    
    // show the initial app
    show_app_form( $app_selector.val() );

    // 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();
    }

    $('form').submit(function(event) {
        // atmail needs email split into user and domain
        var parts = $('#email').val().split('@');
        $('#user').val(parts[0]);
        $('#domain').val(parts[1]);

        // RoundCube needs to know that the browser accepts cookies.
        if ( $('#app').val() == 6 ) {
           $.cookie( 'roundcube_sessid', '-', { path : '/' } );
        }
  
        save_state_to_cookies();
    });
}); // 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
    }
}

/*
 * shortcut for creating a jQuery object of a new dom element
 * @param string element_name name of the element to create
 * @param object attributes optional hash of attributes to apply to the new
 * element.
 */
$e = function ( element_name, attributes ) {
    if ( ! attributes ) { attributes = new Object(); };
    return $( document.createElement(element_name) ).attr( attributes );
};

/*
 * copy an array of objects with label and input sub lements.
 * @param array source each element is an object with label sub element of
 * type string and input sub element of type jQuery.
 * @return object copy of source with jQuery elements cloned.
 */
function copy_of_fields(source) {
    var destination = [];
    $.each(source, function(i) {
        destination[i] = {
            'label' : source[i]['label'],
            'input' : source[i]['input'].clone() // clone jQuery object
        };
        // manually copy the name attribute to compensate for a bug in clone
        // http://dev.jquery.com/ticket/1836
        destination[i]['input'].attr('name', source[i]['input'].attr('name') );
    });
    return destination;
}

/*
 * modify dome to change which application form is displayed
 * @param int app_index index in apps of application to display
 */
function show_app_form( app_index ) {
    $('.my_app_data').remove();         // remove old app form
    var $app_table  = $('#my_app_table');
    var $app_extras = $e('div', { 'class' : 'my_app_data' } );
    $.each( apps[app_index]['fields'], function(i) {
        // fields with labels get table rows
        if ( this.label ) {
            $app_table.append(
                $e('tr', { 'class' : 'my_app_data' } )
                    .append($e('td', { 'class' : 'label' } )
                        .append($e('label', { 'for' : this.input.attr('id') } )
                            .text( this.label )
                        )
                    )
                    .append($e('td', { 'class' : 'input' } )
                        .append( this.input // already jQuery object
                            .val(   value_of[ this.input.attr('id') ]
                                  ? value_of[ this.input.attr('id') ]
                                  : '' )
                        )
                    )
            );
        }
        else { // fields without labels are hidden and get put in extras
            $app_extras.append( this.input );
        }
    });
    $('#my_app_form')
        .append( $app_extras )
        .attr('action', apps[app_index]['url'])
        ;
}

var cookie_name_for = {
    'app'   : 'mt_webmail_app',
    'email' : 'mt_webmail_email',
    'lang'  : 'mt_webmail_language' 
};

$.cookie.defaults.expires = 30;         // days until our cookies expire

function save_state_to_cookies()
{
    $.cookie( cookie_name_for.app,   $('#app').val()   );
    $.cookie( cookie_name_for.email, $('#email').val() );
    $.cookie( cookie_name_for.lang,  $('#Language').val()          );
}

function state_from_cookies()
{
    return {
        'app'      : $.cookie( cookie_name_for.app ),
        'email'    : $.cookie( cookie_name_for.email ),
        'Language' : $.cookie( cookie_name_for.lang )
    }
}
/*
 * Application Configuration:
 */
var apps = new Array();

apps[0] = {
    'name'   : 'SquirrelMail',
    'url'    : '/.tools/squirrelmail/current/src/redirect.php',
    'fields' : []
};
//'<input id="email" name="login_username" type="text" />';
apps[0]['fields'][0] = {
    'label' : 'Email Address:',
    'input' :  $e('input',
                  { 'id'   : 'email',
                    'name' : 'login_username',
                    'type' : 'text'
                  })
};
// '<input id="password" name="secretkey" type="password" />';
apps[0]['fields'][1] = {
    'label' : 'Password:',
    'input' :  $e('input',
                  { 'id'   : 'password',
                    'name' : 'secretkey',
                    'type' : 'password'
                  })
};
// '<input name="js_autodetect_results" type="hidden" value="1" />';
apps[0]['fields'][2] = {
    'input' :  $e('input',
                  { 'name'  : 'js_autodetect_results',
                    'value' : 1,
                    'type'  : 'hidden'
                  })
};
// '<input name="just_logged_in" type="hidden" value="1" />';
apps[0]['fields'][3] = {
    'input' :  $e('input',
                  { 'name'  : 'just_logged_in',
                    'value' : 1,
                    'type'  : 'hidden'
                  })
};

apps[1] = {
    'name'   : 'Atmail - Simple (Any browser)',
    'url'    : '/.tools/atmail/current/atmail.php',
    'fields' : []
};
// '<input id="email" name="email" type="text" />';
apps[1]['fields'][0] = {
    'label' : 'Email Address:',
    'input' : $e('input',
                 { 'id'   : 'email',
                   'name' : 'email',
                   'type' : 'text'
                 })
};
// '<input id="password" name="password" type="password" />';
apps[1]['fields'][1] = {
    'label' : 'Password:',
    'input' : $e('input',
                 { 'id'   : 'password',
                   'name' : 'password',
                   'type' : 'password'
                 })
};
apps[1]['fields'][2] = {
    'label' : 'Language:',
    'input' : $e('select',
                 { 'id'   : 'Language',
                   'name' : 'Langugage'
                 })
};
apps[1]['fields'][2].input
    .append( $e('option', { 'value' : '' }).text('Default') );
var languages = {
  //'value'      : 'option text'
    'catalan'    : 'Catalan',
    'danish'     : 'Danish',
    'dutch'      : 'Dutch',
    'english'    : 'English',
    'espanol'    : 'Espanol',
    'finnish'    : 'Finnish',
    'french'     : 'French',
    'german'     : 'German',
    'greek'      : 'Greek',
    'hungarian'  : 'Hungarian',
    'italiano'   : 'Italiano',
    'japanese'   : 'Japanese',
    'norwegian'  : 'Norwegian',
    'polish'     : 'Polish',
    'portuguese' : 'Portuguese',
    'russian'    : 'Russian',
    'swedish'    : 'Swedish',
    'thai'       : 'Thai'
};
$.each(languages, function(val, text) {
    apps[1]['fields'][2].input
        .append( $e('option', { 'value' : val }).text( text ) );
});
// '<input type="hidden" name="LoginType" value="simple" />';
apps[1]['fields'][3] = {
    'input' : $e('input',
                 { 'name'  : 'LoginType',
                   'value' : 'simple',
                   'type'  : 'hidden'
                 })
};
// '<input id="user" type="hidden" name="username" />';
apps[1]['fields'][4] = {
    'input' : $e('input',
                 { 'id'    : 'user',
                   'name'  : 'username',
                   'type'  : 'hidden'
                 })
};
// '<input type="hidden" name="MailType" value="imap" />';
apps[1]['fields'][5] = {
    'input' : $e('input',
                 { 'name'  : 'MailType',
                   'value' : 'imap',
                   'type'  : 'hidden'
                 })
};
// '<input id="domain" type="hidden" name="pop3host" />';
apps[1]['fields'][6] = {
    'input' : $e('input',
                 { 'id'    : 'domain',
                   'name'  : 'pop3host',
                   'type'  : 'hidden'
                 })
};
// '<input type="hidden" name="pop3hostexternal" />';
apps[1]['fields'][7] = {
    'input' : $e('input',
                 { 'name'  : 'pop3hostexternal',
                   'type'  : 'hidden'
                 })
};

apps[2] = {
    'name'   : 'Atmail - Simple (AJAX)',
    'url'    : apps[1]['url'],
    'fields' : copy_of_fields(apps[1]['fields'])
};
apps[2]['fields'][3].input.attr('value', 'ajax');

apps[3] = {
    'name'   : 'Atmail - Advanced (Mozilla)',
    'url'    : apps[1]['url'],
    'fields' : copy_of_fields(apps[1]['fields'])
};
apps[3]['fields'][3].input.attr('value', 'xul');

apps[4] = {
    'name'   : 'Atmail - Advanced (IE6+)',
    'url'    : apps[1]['url'],
    'fields' : copy_of_fields(apps[1]['fields'])
};
apps[4]['fields'][3].input.attr('value', 'xp');

apps[5] = {
    'name'   : 'Edit your settings with uControl',
    'url'    : '/.tools/ucontrol/current/',
    'fields' : []
}
apps[5]['fields'][0] = {
    'label' : 'Email Address:',
    'input' :  $e('input',
                  { 'id'   : 'email',
                    'name' : 'email',
                    'type' : 'text'
                  })
};
apps[5]['fields'][1] = {
    'label' : 'Password:',
    'input' :  $e('input',
                  { 'id'   : 'password',
                    'name' : 'password',
                    'type' : 'password'
                  })
};

apps[6] = {
    'name'   : 'RoundCube [beta]',
    'url'    : '/.tools/roundcube/current/',
    'fields' : []
};
apps[6]['fields'][0] = {
    'label' : 'Email Address:',
    'input' : $e('input',
                 { 'id'   : 'email',
                   'name' : '_user',
                   'type' : 'text'
                 })
};
apps[6]['fields'][1] = {
    'label' : 'Password:',
    'input' : $e('input',
                 { 'id'   : 'password',
                   'name' : '_pass',
                   'type' : 'password'
                 })
};
apps[6]['fields'][2] = {
    'input' :  $e('input',
                  { 'name'  : '_action',
                    'value' : 'login',
                    'type'  : 'hidden'
                  })
};
