/*****************************
 * FORMBUILDER
 * Author: Homme Zwaagstra
 *****************************/

/* Handle a 'does validate' response from Formbuilder */
function validate_response(id) {
    var div = $(id + '.error');
    var ctrl = $(id);
    div.innerHTML = '';
    div.className = 'noerror';
    ctrl.className = '';
	check_submit();
}

/* Handle a 'does not validate' reponse from Formbuilder */
function validate_error(id, t) {
    if (t.status == 422) {
        var div = $(id + '.error');
        var ctrl = $(id);
        div.innerHTML = t.responseText;
        div.className = 'error';
        ctrl.className = 'error';
    } else {
        alert('Error ' + t.status + ' -- ' + t.statusText);
    }
	check_submit();
}

/* Validate the contents of an HTML control */
function validate(control) {
    new Ajax.Request(control.getAttribute('fb:url'), {
        onSuccess: function(t) { validate_response(control.id) },
        onFailure: function(t) { validate_error(control.id, t) },
        method: "put",
        postBody: control.value
    });
	check_submit();
}


function check_submit() {
	var submit = $('metadata_submit');

	if (!submit) {
		return;
	}

	if (form_is_valid('metadata-form')) {
		submit.removeAttribute('disabled');
	} else {
		submit.disabled= "disabled";
	}
	return; 
}
/* Ensure the form does not contain any errors before submission */
function form_is_valid(name) {
    elementList = Form.getElements(name);
	for (key in elementList) {
		if (elementList[key].className) {
			if (elementList[key].className.indexOf("error") != -1) {
				/*alert(elementList[key].name);
				  alert(elementList[key].className);*/
				return false;
			}
		}
	}

    return true;
}


/* Ensure the form does not contain any errors before submission */
function check_form(name) {
    elementList = Form.getElements(name);
    for (key in elementList) {
        if (elementList[key].className == 'error') {
            alert('Please suitably fill in all boxes marked with errors');
            return false;
        }
    }
    return true;
}


/* FORMBUILDER JAVASCRIPT CODE

Time-stamp: <2003-10-17 12:09:45 cco>
Author: Homme Zwaagstra
Description: A library of functions used by FormBuilder forms. The Submit*() functions are called in onClick events to prepare action specific data and then submit the form. SubmitAdd(), for instance, generates POST data that specifies where formbuilder should add content. This functionality could be achieved through normal 'submit' buttons but then we would be constrained in design choices; with potentially so many buttons on a form we can do without the clunky grey button! Javascript combined with CSS broadens the design scope.

*/

// Basic function that appends to a form a field with a specified name, value and type. Returns true on success, false otherwise
function AddFormField(form, fieldName, fieldValue, fieldType) 
{
	if (!form) {
		alert('Please place this input in an HTML form');
		return false;
	}
	
	var field = document.createElement('input');
	field.name = fieldName;
	field.value = fieldValue;
	field.type = fieldType;
	form.appendChild(field);
	return true;
}

// Appends to a form a hidden field with a specified name and value. Returns true on success, false otherwise
function AddHiddenFormField(form, fieldName, fieldValue) 
{
	return AddFormField(form, fieldName, fieldValue, 'hidden');
}

// Appends to a form a POST variable called javascript_enabled with a value of 1. The existence of this variable can be checked on the server, thereby defining if javascript with the requisite functionality is enabled on the user's browser. Returns true on success, false otherwise
function JavascriptCheck(form) 
{
	return AddHiddenFormField(form, 'javascript_enabled', '1');
}

// Appends a hidden field to a form with a specified name and value before submitting the form. Returns true on success, false otherwise
function SubmitForm(form, fieldName, fieldValue) {
	if (AddHiddenFormField(form, fieldName, fieldValue) == true) {
		//Check(form);
		return form.submit();
	}
	return false;
}

// Appends the specified action to a form as a hidden field before submitting it. An action consists of a correctly formatted POST variable name and associated value. Returns true on success, false otherwise
function SubmitFormAction(form, action, fieldName, fieldValue) {
	fieldName += '[' + action + ']';
	return SubmitForm(form, fieldName, fieldValue);
}

// Submits the form, having specified the action formbuilder should take as being a content addition. Returns true on success, false otherwise
function SubmitAdd(form, fieldName, fieldValue) 
{
	return SubmitFormAction(form, 'add', fieldName, fieldValue);
}

// Submits the form, having specified the action formbuilder should take as being a content deletion. Returns true on success, false otherwise
function SubmitDelete(form, fieldName, fieldValue) 
{
	if (confirm('Are you sure you want to delete this element?'))
		SubmitFormAction(form, 'delete', fieldName, fieldValue);
}

// Submits the form, having specified the action formbuilder should take as being a content swap. Returns true on success, false otherwise
function SubmitChoice(select, fieldName, fieldValue) 
{
	var selectValue = select.options[select.selectedIndex].value;
	if (!selectValue)			// the user has selected the explanation option
		return;

	if (confirm('Changing the form content structure will replace the current choice; are you sure you want to continue?')) {
		fieldValue += selectValue;
		SubmitFormAction(select.form, 'choice', fieldName, fieldValue);
	}
}

// Debugging function used to print out all form variable names and associated values
function Check(form) 
{
	var s = "";
	for (var i = 0; i < form.elements.length; i++) {
		s += form.elements[i].name + "=" + form.elements[i].value + "\n";
	}
	alert(s);	
}
