
var LoginBottomValidator;
var LoginBottomSuccessful = function(response) {
    // Reload
    location.reload(true);
}
var Errors;
var LoginErrors;
var HandleLoginErrors = function(errors) {
    var fieldErrors = {};
    $('error', errors).each(function() {
        field = $('field', this).text();
        message = $('message', this).text();
        
        // Modifying to compensate for 2nd appearance of form on page
        if($('#' + field + '2').length == 0) {
            // General error
            // Add the error to the errors section
            
            // Shorten some error messages
            if(message == 'Incorrect email/password combination, could not authenticate')
            {
                message = 'Incorrect';
            }
            LoginErrors.show();
            LoginErrors.append("<li>"+message+"</li>");
        }
        else {
            // Specific field error
            fieldErrors[field] = message;
            LoginBottomValidator.showErrors(fieldErrors);
        }
        LoginErrors.show();
        Errors.show();
    });
}
$(document).ready( function() {
    var options = {};
    options.timeout = 10000;
    options.url = ServicesPath + 'AuthenticateUser.ajax';
    options.type = 'POST';
    
    options.success = function(response, status) {
        response = text2xml(response);
        if($('error', response).length > 0) {
            // Errors
            HandleLoginErrors(response);
        }
        else {
            // Otherwise, reload the page
            location.reload(true);
        }
    }
    Errors = $('#errors2');
    LoginErrors = $('ul', $('#errors2'));
    
    var bottomValidationOptions = {
        rules: {
            "email2": {
            required: true,
            email: true
            },
            "password2": {
                required: true,
                minlength: 6,
                maxlength: 14
            }
        },
        messages: {
            "email2": {
                required: "Email required",
                email: "Email invalid"
            },
            "password2": {
                required: "Password required",
                minlength: "Password > 5 chars",
                maxlength: "Password < 15 chars"
            }
        },
        errorContainer: Errors ,
        errorLabelContainer: $("ul", Errors),
        wrapper: 'li',
        submitHandler: function(form) {
            LoginErrors.empty();
            LoginErrors.hide();
            $(form).ajaxSubmit(options);
            return false;
        }
    };
    
    LoginBottomValidator = $('#login2').validate(bottomValidationOptions);
});

