/*
Update the various document lists on the page as well as the document fields
that represent those lists. This a little hokey because we must save the
drag-drop scripts and then execute at the end. I would like to refactor this
and ideally move it to RJS. The main reason it is JS and not RJS is because
of the fact that we may be needing to make our changes from a iframe included
in the page. The only way I could force the context to be right was to actually
attach real Javascript code to the parent window.

document_field - This is the field we are updating. If we are removing an
image we will remove the hidden tag with the matching ID. If we are adding
and element we will insert a new hidden tag with a matching ID.

field_group - The element that holds all the field elements for the
document lists.

modify_document - The document being modified. If positive we are adding. If
negative then we are removing. If 0 then we are simply refreshing

list_container - The lists to update

url - The url to execute to get a fresh list of documents
*/
function update_document_list(document_field, field_group, modify_document, list_container, url) {
	manage_load_scripts = new Array(); // Reset delayed script list. This is a global!
	page_changed();

	remove_document = modify_document < 0;
	adding_document = modify_document > 0;
	modify_document = Math.abs(modify_document);
	if( remove_document ) {
		$(modify_document + '_document').remove();
	} else if(adding_document) {
		var new_field = document.createElement('input');
		new_field.setAttribute('type', 'hidden');
		new_field.setAttribute('value', modify_document);
		new_field.setAttribute('name', document_field + '[]');
		new_field.id = modify_document + '_document';
		$(field_group).appendChild(new_field);
	}

	/* Process each list container. The first one is assumed to be
	the editable one and therefore is treated special */
	list_container_text = list_container;
	list_container = list_container.split('|')
	list_container.each(function(lc) {
		var manage = lc == list_container[0]
		new Ajax.Updater($(lc), url, {
			evalScripts: true,
			parameters: $H({
				manage: manage,
				list_container: list_container_text,
				document_field: document_field,
				field_group: field_group
			}).toQueryString() + '&' + Form.serialize(field_group),
			onSuccess: function() {
				if(!manage) return;
				setTimeout(function() {
					/* Execute the delayed scripts */
					manage_load_scripts.each(function(script){
						eval(script);
					});
				}, 250);
			}
		});
	});
}
var manage_load_scripts = new Array();

/* A element can call this to indicate to the page that something has changed.
The "save" and "published" button will be enabled if they exist */
function page_changed() {
	save = $('page-save');
	publish = $('page-publish');
	if( save ) save.disabled = false;
	if( publish ) publish.disabled = false;
}