/**
 * portal.js - Javascript used in portugalmail portal.
 *
 * Copyright 2010 Portugalmail
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * @author Rui Carneiro <rui.carneiro@portugalmail.net>
 */
var Portal = {
    /* Determine in which webmail this client should be authenticated */
    login: function(e)
    {
        var user = $('#horde_user'),
            pass = $('#horde_pass'),
            parameters_list;

        /* Do not submit when username is empty */
        if (user.value == '') {
            e.stop();
            user.focus();
            return;
        }

        /* Do not submit when password is empty */
        if (pass.value == '') {
            e.stop();
            pass.focus();
            return;
        }

        /* Loading */
        $('#login input, #loading, #horde_login, #login .logoutMessage').toggle();
    },

    toggleLabels: function()
    {
        var input;

        $('#horde_user, #horde_pass').each(function(i, element) {
            input = $(element);

            //Hide "manually" on focus
            input.focus(function (e) {
                if (!$(this).val()) {
                    $(this).prev().hide();
                }
            });

            //Show "manually" on focus
            input.blur(function (e) {
                if (!$(this).val()) {
                    $(this).prev().show();
                }
            });

            if (!input.val()) {
                Portal._toggleLabel(input);
            }
        });

        /* Set intervals to handle autocompletes */
        setInterval(function(e) {
            Portal._toggleLabel($('#horde_user'));
            Portal._toggleLabel($('#horde_pass'));
        }, 250); // every half second
    },

    _toggleLabel: function(input, e)
    {
        var label = input.prev();

        if (!input.is(":focus")) {
            !input.val() ? label.show() : label.hide();
        }
    },

    //Try to complete user email if he didn't provided a full address
    completeUserEmail: function(e)
    {
        var mail = $("#horde_user").val();

        if (mail.indexOf("@") == -1) {
            var domain = null;

            $(PORTAL.signup_domains).each(function (i, d) {
                if (document.domain.search(d) != -1) {
                    domain = d;
                }
            });

            if (domain !== null) {
                $("#horde_user").val(mail + "@" + domain);
            }
        }
    },

    onDomLoad: function()
    {
        /* Add click handler. */
        $('#horde_login').click(Portal.login);
        $('#horde_user').change(Portal.completeUserEmail);

        /* Browser auto complete detection */
        Portal.toggleLabels();

        /* Enable login is javascript is enabled */
        $('#login > div').show();

    }
};

/* Initialize onload handler. */
$(document).ready(Portal.onDomLoad);
