// Initialise form and set up required fields
$(document).ready(function() {
	
	$.each(requiredFields, function(i, field) {
		
		var msg = '<span class="required" id="' + field.fieldName + '_val_msg"></span>';
						
		if(field.displayNode)
			$('#' + field.displayNode).append(msg);
		else
			$('[name=' + field.fieldName + ']').after(msg);

		$('[name=' + field.fieldName + ']').bind('blur', { validators: field.validators, customAction: field.customAction }, function(event) { 

			$('#' + field.fieldName + '_val_msg').empty();

			var f = $(this);

            if(event.data.customAction) event.data.customAction(f, true);
			
			$.each(event.data.validators, function(i, getValidator) {
				
				var validatorObject = getValidator(f);
				
				if(!validatorObject.valid) 
                {
                    if(event.data.customAction)
					    event.data.customAction(f, false);
                    else
                        $('#' + field.fieldName + '_val_msg').append(validatorObject.message);
                }
				
			});

		});
			
		// Only show the mandatory field indicator if an isRequiredValidator 
		// has been specified as a validator for this field
		$.each(field.validators, function(i, validator) {
			if(validator == isNotEmptyValidator)
			{
				if(field.displayNode)
					$('#' + field.displayNode + ' span').before('<span class="req_indicator">&nbsp;&nbsp;*&nbsp;&nbsp;</span>');
				else
					$('[name=' + field.fieldName + ']').after('<span class="req_indicator">&nbsp;&nbsp;*&nbsp;&nbsp;</span>');
				return false;
			}
		});
		
	});

    $('#' + formName).bind('submit', submitForm);
});

// This function will dynamically add or update an option and then re-sort the options alphabetically
function updateSelect(select, val, text, isNew)
{
    if (isNew)
    {
        // Remove the first option before adding the new one and sorting
        // We do this because otherwise the 'Add new' option ends up in the wrong place after sort  
        var firstOption = select.find('option:first').remove();
        
        // Add in the new item
        select.append('<option value="' + val + '">' + text + '</option>');
        
        // Replace the select's HTML with the sorted array of options
        select.html($.makeArray($('#' + select.attr('id') + ' option')).sort(function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 }));

        // Put the first option
        select.prepend(firstOption);
        
        select.val(val);
    }
    else
    {
        // Just update the box with the new customer name
        select.find('option[value=' + val + ']').html(text);
    }
}

var submitForm = function() {

    var isValid = true;

    $.each(requiredFields, function(i, field) {

        $('#' + field.fieldName + '_val_msg').empty();

        var f = $('[name=' + field.fieldName + ']');

        if (field.customAction) field.customAction(f, true);

        $.each(field.validators, function(i, getValidator) {

            var validatorObject = getValidator(f);

            if (!validatorObject.valid) {
                if (field.customAction)
                    field.customAction(f, false);
                else
                    $('#' + field.fieldName + '_val_msg').append(validatorObject.message);

                isValid = false;
            }
        });

    });

    if (isValid) {
        return true;
    }

    return false;
};
