// magic class names
//  no-labels: on the form or element to not add a label
//  focus: on the field to enable the auto-focus

function ConfigureForms()
{
    $$('form').each(function(formId) {
        ConfigureForm(formId);
    });
    
    // focus on first form field that has a class of "focus".
    for (var i = 0, formCount = document.forms.length; i < formCount; ++i) {
        var elements = document.forms[i].getElements();
        for (var j = 0, fieldCount = elements.length; j < fieldCount; ++j) {
            if (elements[j].hasClassName('focus')) {
                elements[j].focus();
                return;
            }
        }
    }
}

function ConfigureForm(formId)
{
    var form = $(formId);
    
    // enable validation on this form
    new Validation(formId);


    // loop over all the input fields
    form.getElements().each(function(field) { LabelField(field, form); } );
}

function LabelField(field, form)
{
    var labelTemplate = new Template('<label id="#{id}" for="#{fieldId}">#{text}</label>');
    var field_type = field.readAttribute("type");
    if (field_type == null) field_type = "";
    
    // skip special types of form elements
    if (field.tagName != "INPUT" && field.tagName != "TEXTAREA" && field.tagName != "SELECT") return;
    if (field_type == "hidden") return;

    // add a class to tell us what kind of field it is
    if (field.tagName == "INPUT")
        field.addClassName("type_" + field_type);

    // magic parameters to disable adding labels
    var addLabels = !field.hasClassName('no-labels') && (form == null || !form.hasClassName('no-labels')) &&
                    field_type != "button" && field_type != "submit";
    
    // make a label for it, unless we say otherwise
    if (addLabels)
    {
       var labelId = "label_for_" + field.id;
       var text = field.readAttribute("title") != null ? field.readAttribute("title") : field.readAttribute("name");
       var html = labelTemplate.evaluate({id: labelId, fieldId: field.id, text: text});
       switch (field_type.toLowerCase()) {
			case 'checkbox':
			case 'radio':
			    new Insertion.After(field, html);
			    break;
			default:
			    new Insertion.Before(field, html);
	   }                       
       var label = $(labelId);
       if (field.hasClassName('required')) 
       {
            // set required class on the label too
            label.addClassName("required");
        
            // add a <span>*</span> to the front of the label
            new Insertion.Bottom(label, "<span>*</span>");
       }
    }
}
