var ClientLogin = Class.create ({
    initialize: function () {
        this.submit_count = 0;

        this.q = null;
    },

    CheckLoginForm: function (ev) {
        var theForm = $('login-form');
        var why = "";

        if (theForm.FirstName)
            why += isEmpty(theForm.FirstName.value, "First Name");
        if (theForm.LastName)
            why += isEmpty(theForm.LastName.value, "Last Name");
        if (theForm.EmailAddress)
            why += checkEmail(theForm.EmailAddress.value);
        if (theForm.Username)
            why += isEmpty(theForm.Username.value, "Username");
        if (theForm.Password && theForm.PasswordConfirm) {
            why += isEmpty(theForm.Password.value, "Password");
            why += isEmpty(theForm.PasswordConfirm.value, "Confirm Password");
            if (theForm.Password.value != theForm.PasswordConfirm.value)
                why += appendBreak("- Password and its confirmation do not match.");
            if (theForm.Password.value.length < 4)
                why += appendBreak("- Password must be 4 characters or longer.");
        }

        if (theForm.CAT_Custom_17382)
            why += checkDropdown(theForm.CAT_Custom_17382.value, "Where did you buy your copy?");
        if (theForm.CAT_Custom_17384)
            why += isCurrency(theForm.CAT_Custom_17384.value, "Postcode");
        if (theForm.CAT_Custom_17385) {
            why += isEmpty(theForm.CAT_Custom_17385.value, "Question");

            var answer = theForm.CAT_Custom_17385.value;
            var crypted_answer = public_answer (answer);

            if (crypted_answer != this.q.answer)
                why += "- The answer to the question is incorrect\n";
        }

        if(why != "") {
            alert(why);
            Event.stop (ev);
            return;
        }

        if (this.submit_count == 0) {
            this.submit_count++;
            theForm.submit ();
        }
        else {
            alert("Form submission is in progress.");
            Event.stop (ev);
        }
    },

    Start: function (questions) {
        var n = rand (questions.length - 1);

        this.q = questions[n];

        $('random-question').childElements ().invoke ('remove');
        $('random-question').insert (new Element ('div').insert (
                this.q.question.escapeHTML ()));

        $('login-form').observe ('submit', this.CheckLoginForm.bind (this));
    }
});

document.observe ('dom:loaded',
                  function () { new ClientLogin ().Start (questions); });
