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

function fill_in_values(fields, email, password, language) {//{{{

    // split out smaller pieces for some mail clients
    var parts = email.split('@');
    var user = parts[0];
    var domain = parts[1];

    var newfields = {};
    $.each( fields, function(key, value) {
        if (value.replace) {
            value = value.replace('#email#', email);
            value = value.replace('#password#', password);
            value = value.replace('#user#', user);
            value = value.replace('#domain#', domain);
            value = value.replace('#language#', language);
        }
        newfields[key] = value;
    });

    return newfields;
}//}}}

// cookie handling
//{{{
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(app, email, language)
{
    $.cookie( cookie_name_for.app,   app      );
    $.cookie( cookie_name_for.email, email    );
    $.cookie( cookie_name_for.lang,  language );
}

function state_from_cookies()
{
    return {
        'app'      : $.cookie( cookie_name_for.app ),
        'email'    : $.cookie( cookie_name_for.email ),
        'Language' : $.cookie( cookie_name_for.lang )
    }
}//}}}

/*
 * Log the customer into atmail 6
 */
function login_atmail(email, password, mail_access_domain) {//{{{
    var fields = {
        'emailName'       : '#user#',
        'emailDomain'     : '#domain#',
        'password'        : '#password#',
        'MailType'        : 'IMAP',
        'requestedServer' : 'localhost',
        'Language'        : '',
        'email'           : '#email#'
    }
    $('form#atmail_login').remove();
    $('body').append($e('form', {
        'id':'atmail_login',
        'method':'post',
        'action': 'https://' + mail_access_domain + '/webmail/index.php/mail/auth/processlogin'
    }));

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

    save_state_to_cookies(0, email, '');
    $('form#atmail_login').submit();
}//}}}

