$(function(){
    /**
     * Define all properties we'll be using within this scope.
     */
    var signupform      = $('#signupform'), // The form element
        step            = 'initial',        // Validation step we're at
        errors          = null;             // Holds, when available, all errors.
    
    /**
     * This function builds, and displays the errors currently available.
     */
    var displayErrors = function() {
        var errorContainer = $('<div />').attr('title', 'ONJUISTE INVOER'), // The container for the errors, with a title for jqueryUI Dialog
            errorList = $('<ul />'),                                        // The unordered list
            errItem = $('<li />');                                          // The list item
        
        
        // Loop through all errors
        for(var error in errors) {
            
            // Append the error to the list, by cloning the error list item, and setting the error
            errorList.append(errItem.clone().text(errors[error].message));
        }
        
        // Set the built list in the error container
        errorContainer.html(errorList);
        
        // Display the error container inside of a dialog.
        errorContainer.dialog({
            modal: true,
            width: '450',
            buttons: {
                Ok: function() {
                    
                    // Close the dialog
                    $( this ).dialog( "close" );
                }
            }
        });
    };
    
    /**
     * Abstract function for validations. Simply calls the server and 
     * calls callback with returned data.
     * @param   The data to send to the server
     * @param   The function to call after the call to the server has completed
     */
    var validate = function(data, callback) {
        
        // Make ajax to set datatype
        $.ajax({
            type: "POST",
            url: "/",
            dataType: 'json',
            data: data,
            success: function(data){
                callback(data);
            }
        });
    };
    
    var submitForm = function(signupform, callback) {
        
        // Set the data.
        var data = signupform.serialize() + '&validationType=submit';
        
        // Call validate with the set data
        validate(data, function(data) {
            
            // Is this data valid?
            if(data.status === 'errors') {
                
                errors = data.messages;
            }
            
            callback(data);
        });
    }
    
    /**
     * Funtion to validate the form in its current state.
     * @param   The form being validated
     * @param   Function to call after validating the form
     */
    var validateForm = function(signupform, callback) {
        
        // Set the data.
        var data = signupform.serialize() + '&validationType=form';
        
        // Call validate with the set data
        validate(data, function(data) {
            
            // Is this data valid?
            if(data.status === 'ok') {
                
                // Set step to captcha (next step)
                step = 'done';
            }
            else {
            
                // It's not, set the errors.
                errors = data.messages;
            }
            
            // Execute the callback function.
            callback();
        });
    };
    
    /**
     * The callback on form submit.
     * Will handle things differently based on the current step.
     * Steps explained:
     * - Initial:   Nothing has happened yet, or the entered form data was invalid
     * - Done:      Everything was valid, the form will be submitted.
     */
    signupform.submit(function(evt) {
        
        // Prevent the default
        evt.preventDefault();
        
        // Switch to determine the step
        switch(step) {
            
            // Initial step?
            case 'initial':
                
                // Validate the form with callback
                validateForm($(this), function() {
                
                    // If after validation the step is initial,
                    if(step === 'initial') {
                        
                        // then validation failed.
                        displayErrors();
                    }
                    
                    // Else, if the step equals captcha after validation
                    else if(step === 'done') {
                        
                        // then validation was a success, show captcha
                        signupform.submit();
                    }
                    
                    // Not really needed. Indicate we're not submitting the form
                    return false;
                });
                
                // Break the switch, we're done here.
                break;
            
            // Are we done?
            case 'done':
                submitForm(signupform, function(){
                    signupform[0].reset();
                    $('<div />').attr('title','Bedankt!').append($('<span />').text('Bedankt voor je aanmelding! In je inbox vind je een activatiemail waarmee je je profiel NU kunt activeren')).dialog({
                        modal: true,
                        width: '450',
                        buttons: {
                            Ok: function() {
                                
                                // Close the dialog
                                $( this ).dialog( "close" );
                            }
                        }
                    });
                });
        }
    });
    
    /**
     * Initial. Set action on form, add hidden element.
     */
    $('#signupform').attr('action','/');
});

