// Counter to create unique IDs with various generated inlineEditor elements (mainly calendar and TinyMCE elements).
var inlineEditorCounter = 0;

window.addEvent('domready', function() {
	if ($('pageContent').getElement('form.annotationForm') != null) {
		prepareAnnotationForm($('pageContent').getElement('form.annotationForm'));
	}
});

function getId(stringId) {
	var _index = stringId.indexOf('_');

	if (_index == -1 || _index == (stringId.length - 1)) {
		return null;
	}

	var id = stringId.substring(_index + 1).toInt();

	if (isNaN(id)) {
		return null;
	}

	return id
}

function prepareAnnotationsEdit(parentElement, language) {
	if (security['editAnnotation']) {
		var editButtonSrc = __images + '/edit-gray.gif';
		var okButtonSrc = __images + '/ok.gif';
		var cancelButtonSrc = __images + '/cancel.gif';

		var annotations = parentElement.getElements('.annotation');
		var editAction = __root + '/secure/annotation/editAnnotation.do';

		$each(annotations, function(annotation) {
			/*var editables = annotation.getElements('.editable');

			$each(editables, function(editable) {
				var editButton = new Element('img', {
					'src': editButtonSrc,
					'cursor': 'pointer',
					'styles': {
					'marginRight': '.5em'
				}
				});

				if (editable.hasClass('complex')) {
					editButton.setStyle('float', 'left');
					editButton.setStyle('position', 'relative');
					editButton.setStyle('bottom', '-2px');
					editButton.setStyle('marginRight', '.5em');
				}

				editButton.inject(editable, 'before');

				editButton.addEvent('click', function() {
					new InlineEditor(editable, annotation, {
						action: editAction,
						editButton: editButton,
						okButton: okButtonSrc,
						cancelButton: cancelButtonSrc,
						language: language
					});
				});

				editButton.addEvent('mouseenter', function() {editable.addClass('hovered');});
				editButton.addEvent('mouseleave', function() {editable.removeClass('hovered');});
				editButton.setProperty('title', messages.get('edit_clickToEdit'));
			});*/


			prepareEditAnnotationButtons(annotation);
		});

		prepareAnnotationDrag(parentElement.getElement('.annotations'));



	}
}

function prepareAnnotationDrag(dragParent) {
	var url = __root + '/secure/annotation/editArticle.do';

	$each(dragParent.getElements('li'), function(annotation) {
		var annotationFooter = annotation.getElement('.annotationFooter');
		var handle = new Element('div', {
			'class': 'handle'
		});

		var handleImg = new Element('img', {
			'class': 'handleImg',
			'src': __images + '/handle.gif',
			'styles': {
				'cursor': 'n-resize',
				'zIndex': 1000
			}
		});
		handle.grab(handleImg);

		annotationFooter.grab(handle);
	});

	var sortables = new Sortables(dragParent, {
		constrain: true,
		clone: true,
		handle: '.handle',
		opacity: .5,
		revert: true,

		onStart: function(element, clone) {
			element.setStyle('visibility', 'hidden');
			clone.setStyle('opacity', .5);
		},

		onComplete: function(element) {
			element.setStyle('visibility', 'visible');
			dragParent.addClass('dirty');

			var articleId = dragParent.getParent('.annotationsGroup').get('id');
			articleId = getId(articleId);

			var sortOrder = '';
			var lis = dragParent.getElements('li');

			$each(lis, function(li, index) {
				sortOrder = sortOrder + getId(li.get('id'));
				if (index < lis.length - 1) {
					sortOrder = sortOrder + ',';
				}
			});

			var request = new Request.JSON({
				url: url,
				method: 'post',
				data: {
					id: articleId,
					field: 'annotationsOrder',
					value: sortOrder
				},
				onFailure: function() {},
				onRequest: function() {},
				onSuccess: function(responseJSON, responseText) {}

			}).send();
		}

	});
}

function prepareArticleEdit(level, language) {
	if (security['editArticle'] && context['editionMode']) {
		// Images for the interfaces
		var editButtonSrc = __images + '/edit-gray.gif';
		var okButtonSrc = __images + '/ok.gif';
		var cancelButtonSrc = __images + '/cancel.gif';
		var rightShifterSrc = __images + '/shiftRight.gif';
		var leftShifterSrc = __images + '/shiftLeft.gif';
		var adderSrc = __images + '/add.gif';

		// Add class visually separate each level for easier structure editin.
		level.addClass('levelEditing');

		// Inline editor interface
		var editables = level.getElements('.editable');
		var editAction = __root + '/secure/law/editArticle.do';

		$each(editables, function(editable) {
			var articleParent = editable.getParent('div.level');
			var editButton = new Element('img', {
				'src': editButtonSrc,
				'cursor': 'pointer',
				'styles': {
					'marginLeft': '.5em'
				}
			});

			if (editable.hasClass('complex')) {
				editButton.setStyle('float', 'left');
				editButton.setStyle('position', 'relative');
				editButton.setStyle('bottom', '-10px');
				editButton.setStyle('marginRight', '.5em');
				editButton.inject(editable, 'before');
			} else {
				editButton.inject(editable, 'after');
			}

			editButton.addEvent('click', function() {
				new InlineEditor(editable, articleParent, {
					action: editAction,
					editButton: editButton,
					okButton: okButtonSrc,
					cancelButton: cancelButtonSrc,
					language: language
				});
			});

			editButton.addEvent('mouseenter', function() {editable.addClass('hovered');});
			editButton.addEvent('mouseleave', function() {editable.removeClass('hovered');});
			editButton.setProperty('title', messages.get('edit_clickToEdit'));
		});

		// Shifter interface
		var shifters = new Element('div', {
			'class': 'shifters',
			'styles': {
				'marginLeft': -level.getStyle('marginLeft').toInt() - 60
			}
		});
		var rightShifter = new Element('img', {
			'src': rightShifterSrc,
			'class': 'rightShifter',
			'styles': {
				'float': 'right',
				'cursor': 'pointer'
			}
		});
		var leftShifter = new Element('img', {
			'src': leftShifterSrc,
			'class': 'leftShifter',
			'styles': {
				'float': 'left',
				'cursor': 'pointer'
			}
		});
		shifters.grab(leftShifter);
		shifters.grab(rightShifter);

		if (level.hasClass('level1') || getFirstChildArticle(level) != null) {
			leftShifter.setStyle('display', 'none');
		}

		if (getPreviousSiblingArticle(level) == null) {
			rightShifter.setStyle('display', 'none');
		}

		level.grab(shifters, 'top');

		activateShifters(level, leftShifter, rightShifter);

		// Adder interface
		var adder = new Element('div', {
			'class': 'adder',
			'styles': {
			}
		});
		var adderImg = new Element('img', {
			'src': adderSrc,
			'class': 'adderImg',
			'styles': {
				'cursor': 'pointer'
			}
		});
		adder.grab(adderImg);
		level.grab(adder, 'bottom');

		var previousLevel = level.getPrevious('div');
		if (previousLevel == null || !previousLevel.hasClass('level')) {
			adderFirst = adder.clone();
			adderFirst.addClass('before');
			level.grab(adderFirst, 'top');
		}

		activateAdder(level);

		// Delete interface. Place the garbage icon before the adder icon (so we can float it right).

		/* GAEL Comment from HERE */
		var url = __root + '/secure/law/article.do';
		var articleDelete = new Element('div', {
			'class': 'articleDelete'
		});

		var deleteImg = new Element('img', {
			'class': 'deleter',
			'src': __images + '/garbage.gif',
			'alt': messages.get('edit_deleteArticle'),
			'title': messages.get('edit_deleteArticle')
		});

		articleDelete.grab(deleteImg);
		articleDelete.inject(adder, 'before');

		deleteImg.addEvent('click', function(_e) {
			_e.preventDefault();
			var confirmation = confirm(messages.get('edit_deleteArticleConfirmation'));

			if (confirmation) {
				var deleteRequest = new Request.HTML({
					url: url,
					data: {
						action: 'delete',
						lawId: '1',
						id: getId(level.get('id'))
					},
					onRequest: function() {},
					onFailure: function() {
						alert(messages.get('edit_communicationError'));
					},
					onSuccess: function(tree, elements, html, javascript) {
						level.nix({duration: 1000}, true).chain(function() {
							window.location.reload();
						});
					}

				}).send();
			}
		});/* GAEL Comment stop HERE */
	}

}

function activateAdder(level) {
	var url = __root + '/secure/law/article.do?action=newArticle';
	var adders = level.getElements('img.adderImg');
	var addersSize = adders.length;

	$each(adders, function(adder, index) {
		var uniqueId = ++incrementalId;

		adder.addEvent('click', function() {
			var originalDisplay = this.getStyle('display');
			this.setStyle('display', 'none');

			var request = new Request.HTML({
				url: url,
				method: 'post',
				onFailure: function() {
					adder.setStyle('display', originalDisplay);
				},
				onRequest: function() {
				},
				onSuccess: function(tree, elements, html, javascript) {
					var formContainer = new Element('div', {
						'class': 'articleForm',
						'html': html
					});

					if (index == 0 && addersSize > 1) {
						level.grab(formContainer, 'top');
					} else {
						level.grab(formContainer, 'bottom');
					}

					var form = formContainer.getElement('form');

					form.addEvent('submit', function(_e) {
						console.log(_e);
						console.log(form.action);

						$each(form.getElements('textarea'), function(textArea) {
							tinyMCE.triggerSave();
							//tinyMCE.execCommand('mceFocus', false, textArea.get('id'));
							//tinyMCE.execCommand('mceRemoveControl', false, textArea.get('id'));
						});

						new Event(_e).preventDefault();

						form.set('send', {
							url: __root + '/secure/law/article.do',
							onFailure: function() {
								alert(messages.get('edit_communicationError'));
							},
							onSuccess: function() {
								window.location.reload();
							}
						});
						form.send();



					});

					addArticleSetIds(level, form, adder.getParent().hasClass('before'));

					var tabs = form.getElement('.tabs').getElements('li');
					var tabContents = form.getElement('.tabsContent').getElements('.tabContent');
					var tabber = new Tabber(tabs, tabContents);

					$each(tabContents, function(tabContent) {
						// Prepare TinyMCE for the comments. All languages must have the same id number.
						var text = tabContent.getElement('textarea');
						var textId = text.get('id');
						text.set('id', textId + uniqueId);
						tinyMCE.execCommand('mceAddControl', false, text.get('id'));
					});

					//Ok and Cancel buttons
					/*var okButton = form.getElement('div.art_submit').getElement('img.art_ok');
					okButton.addEvent('click', function(_e) {
						_e.preventDefault();

						$each(form.getElements('textarea'), function(textArea) {
							tinyMCE.triggerSave();
							//tinyMCE.execCommand('mceFocus', false, textArea.get('id'));
							//tinyMCE.execCommand('mceRemoveControl', false, textArea.get('id'));
						});

						form.fireEvent('submit', new Event());

						return false;
					});*/

					var cancelButton = form.getElement('div.art_submit').getElement('img.art_cancel');
					cancelButton.addEvent('click', function(_e) {
						_e.preventDefault();
						$each(form.getElements('textarea'), function(textArea) {
							tinyMCE.execCommand('mceFocus', false, textArea.get('id'));
							tinyMCE.execCommand('mceRemoveControl', false, textArea.get('id'));
						});
						form.destroy();
						adder.setStyle('display', originalDisplay);
					});
				}
			}).send();
		});
	});
}

function addArticleSetIds(level, form, beforeFirst) {
	var nextSibling = null;

	if (beforeFirst) {
		form.articleNextSiblingId.value = getId(level.get('id'));
	} else {
		var levelMargin = level.getStyle('marginLeft').toInt();

		// The parent
		form.articleParentElementId.value = getId(level.get('id'));

		// The next sibling
		nextSibling = level.getNext('.level');
		if (nextSibling != null && nextSibling.getStyle('marginLeft').toInt() > levelMargin) {
			form.articleNextSiblingId.value = getId(nextSibling.get('id'));
		}
	}
}

function activateShifters(level, leftShifter, rightShifter) {
	var articleId = getId(level.get('id'));

	var shifters = leftShifter.getParent();
	var request = new Request.HTML({
		url: __root + '/secure/law/article.do',
		onFailure: function() {
			alert(messages.get('edit_communicationError'));
		},
		onSuccess: function() {
			window.location.reload();
		}
	});

	leftShifter.addEvent('click', function() {
		request.options.data = {
			action: 'shift',
			direction: 'LEFT',
			lawId: '1',
			id: articleId
		};

		request.send();
	});

	rightShifter.addEvent('click', function() {
		request.options.data = {
			action: 'shift',
			direction: 'RIGHT',
			lawId: '1',
			id: articleId
		};

		request.send();
	});
}

function getParentArticle(level) {
	var leftMargin = level.getStyle('marginLeft').toInt();
	var potentialParents = level.getAllPrevious('.level');
	var parent = null;

	for (var i = 0; i < potentialParents.length; i++) {
		var potentialParent = potentialParents[i];
		if (potentialParent.getStyle('marginLeft').toInt() < leftMargin) {
			parent = potentialParent;
			break;
		}
	}

	return parent;
}

function getPreviousSiblingArticle(level) {
	var leftMargin = level.getStyle('marginLeft').toInt();

	var potentialPreviousSiblings = level.getAllPrevious('.level');
	var previousSibling = null;

	for (var i = 0; i < potentialPreviousSiblings.length; i++) {
		var potentialPreviousSibling = potentialPreviousSiblings[i];
		if (potentialPreviousSibling.getStyle('marginLeft').toInt() < leftMargin) {
			break;
		}

		if (potentialPreviousSibling.getStyle('marginLeft').toInt() == leftMargin) {
			previousSibling = potentialPreviousSibling;
			break;
		}
	}

	return previousSibling;
}

function getNextSiblingArticle(level) {
	var leftMargin = level.getStyle('marginLeft').toInt();

	var potentialNextSiblings = level.getAllNext('.level');
	var nextSibling = null;

	for (var i = 0; i < potentialNextSiblings.length; i++) {
		var potentialNextSibling = potentialNextSiblings[i];
		if (potentialNextSibling.getStyle('marginLeft').toInt() < leftMargin) {
			break;
		}

		if (potentialNextSibling.getStyle('marginLeft').toInt() == leftMargin) {
			nextSibling = potentialNextSibling;
			break;
		}
	}

	return nextSibling;
}

function getLastChildArticle(level) {
	// The margin difference between each levels' depth.
	var marginStep = 25;

	var leftMargin = level.getStyle('marginLeft').toInt();

	var potentialChildren = level.getAllNext('.level');
	var lastChild = null;

	for (var i = 0; i < potentialChildren.length; i++) {
		var potentialChild = potentialChildren[i];
		if (potentialChild.getStyle('marginLeft').toInt() == leftMargin + marginStep) {
			lastChild = potentialChild;
		}

		if (potentialChild.getStyle('marginLeft').toInt() <= leftMargin) {
			break;
		}
	}

	return lastChild;
}

function getFirstChildArticle(level) {
	// The margin difference between each levels' depth.
	var marginStep = 25;

	var leftMargin = level.getStyle('marginLeft').toInt();

	var child = level.getNext('.level');

	if (child != null && child.getStyle('marginLeft').toInt() == leftMargin + marginStep) {
		return child;
	}

	return null;
}

function moveArticleSetIds() {

}


function createTabs(form) {
	var newAnnotation = form;
	var tabs = newAnnotation.getElements('ul.tabs > li');
	var contents = newAnnotation.getElements('div.tabsContent > div');

	new Tabber(tabs, contents);
}

function prepareAnnotationButton(parent) {
	if (security['newAnnotation']) {
		var annotationsFooter = parent.getElement('.annotationsFooter');
		var button = createAnnotationButton(annotationsFooter, 'edit_addAnnotation', 'top');

		var request = __root + '/secure/annotation/annotation.do?action=newAnnotation';
		var articleId = getId(button.getParent('.annotationsGroup').get('id'));
		request = request + '&articleId=' + articleId;

		var popup = new Popup(request, {
			height: '600',
			toolbar: 'no',
			width: '720'
		});

		button.addEvent('click', function(_e) {
			_e.preventDefault();
			popup.pop();
		});
	}
}

function prepareEditAnnotationButtons(annotation) {
	if (security['editAnnotation']) {
		var annotationFooter = annotation.getElement('.annotationFooter');
		var button = createAnnotationButton(annotationFooter, 'edit_editAnnotation');

		var request = __root + '/secure/annotation/annotation.do?action=query';
		var articleId = getId(button.getParent('.annotationsGroup').get('id'));
		//var annotationId = getId(button.getParent('div.annotation').get('id'));
		request = request + '&articleId=' + articleId;

		// Can't remember why this chunk of code is here. In which circumstances
		// can this button -- whose purpose is to edit an annotation -- exist if
		// it doesn't have a div.annotation as parent?? I believe this is useless now.
		var annotationId = null;
		if (button.getParent('.annotation')) {
			annotationId = getId(button.getParent('.annotation').get('id'));
			request = request + '&id=' + annotationId;
		}

		var popup = new Popup(request, {
			height: '600',
			toolbar: 'no',
			width: '720'
		});

		button.addEvent('click', function(_e) {
			_e.preventDefault();
			popup.pop()
		});

		// Now for the Delete annotation button
		var url = __root + '/secure/annotation/deleteAnnotation.do';
		var deleteImg = new Element('img', {
			'class': 'annotationDelete',
			'src': __images + '/garbage.gif',
			'alt': messages.get('edit_deleteAnnotation'),
			'title': messages.get('edit_deleteAnnotation')
		});

		deleteImg.inject(button, 'before');

		deleteImg.addEvent('click', function(_e) {
			_e.preventDefault();
			var confirmation = confirm(messages.get('edit_deleteAnnotationConfirmation'));

			if (confirmation) {
				var deleteRequest = new Request.JSON({
					url: url,
					data: {
						id: getId(annotation.get('id'))
					},
					onRequest: function() {},
					onFailure: function() {},
					onSuccess: function(responseJSON, responseText) {
						var annotationsCount = responseJSON.nbAnnotations;
						setAnnotationsAnnounce(annotation.getParent('.annotationsGroup'), annotationsCount);

						annotation.getParent('.annotations').addClass('dirty');
						annotation.nix({duration: 1000}, true);
					}

				}).send();
			}
		});

	}
}

function createAnnotationButton(parent, messageKey, position) {
	if (!$chk(position)) {
		position = 'bottom';
	}

	var button = new Element('button', {
		'text': messages.get(messageKey),
		'class': 'annotationButton'
	});

	parent.grab(button, position);

	return button;
}

//function prepareAnnotationForm(form, action, button) {
function prepareAnnotationForm(form) {
	var uniqueId = ++incrementalId;
	var globalTable = form.getElement('.globalInputs').getElement('table');
	createTabs(form);

	var articleId = form.getElement('input.articleId').get('value');
	var annotationsGroup = window.opener.$('annotationsGroup_' + articleId);

	//Ok and Cancel buttons
	var okButton = form.getElement('div.ann_submit').getElement('img.ann_ok');
	okButton.addEvent('click', function(_e) {
		_e.preventDefault();

		$each(form.getElements('textarea'), function(textArea) {
			tinyMCE.triggerSave();
			//tinyMCE.execCommand('mceFocus', false, textArea.get('id'));
			//tinyMCE.execCommand('mceRemoveControl', false, textArea.get('id'));
		});

		form.fireEvent('submit');
		form.submit();
		annotationsGroup.getElement('.annotations').addClass('dirty');
		return false;
	});

	var cancelButton = form.getElement('div.ann_submit').getElement('img.ann_cancel');
	cancelButton.addEvent('click', function(_e) {
		_e.preventDefault();
		$each(form.getElements('textarea'), function(textArea) {
			tinyMCE.execCommand('mceFocus', false, textArea.get('id'));
			tinyMCE.execCommand('mceRemoveControl', false, textArea.get('id'));
		});
		form.destroy();
		window.close();
		//button.setStyle('display', 'inline');
	});

	var languageTabs = form.getElements('div.tabContent');
	$each(languageTabs, function(languageTab) {
		// Prepare TinyMCE for the comments. All languages must have the same id number.
		var comment = languageTab.getElement('tr.ann_comment').getElement('textarea');
		var commentId = comment.get('id');
		comment.set('id', commentId + uniqueId);
		tinyMCE.execCommand('mceAddControl', false, comment.get('id'));
		// Prepare the references and authors/sources input/select combo
		var source = languageTab.getElement('tr.ann_source');
		new TextToSelect(source.getElement('input'), source.getElement('select'), source.getElement('select').getNext('a'));
		var references = languageTab.getElement('tr.ann_references');
		new TextToSelect(references.getElement('input'), references.getElement('select'), references.getElement('select').getNext('a'));
	});

	// Prepare the Calendar for the annotation date
	var date = globalTable.getElement('tr.ann_date').getElement('input');
	var dateId = date.get('id');
	date.set('id', dateId + uniqueId);
	prepareCalendar(date.get('id'));
}

function prepareCalendar(calendarId) {
	var object = new Object();
	object[calendarId] = 'Y-m-d';
	new Calendar(object, {days: lexactoWeekdays, months: lexactoMonths, navigation: 1, tweak: {x: 5, y: 0}});
}

/**
 * The Editor class
 */
var InlineEditor = new Class({
	Implements: Options,

	uniqueId : null,

	// Information about the document about to be edited.
	// For example, if we change the title of an annotation,
	// we need to know the type of document (in this case, annotation) and its
	// id (the id of the document). This is NOT the title (in this example).
	documentData: {
		type: null,
		id: null
	},

	// Information about the field about to be edited.
	// We need to know whether this field is a date, an option (select tag in HTML)
	// or a textarea (complex).
	// We also need to know the name of the field (metaname), for example 'title', 'date', 'author', etc.
	editorData: {
		isDate: false,
		isOption: false,
		isComplex: false,
		isCombo: false,
		metaname: null
	},

	options: {
		editButton: null,
		language: 'en',
		user: null
	},

	/*
	 * data: l'élément qui contient la donnée qu'on modifie.
	 * documentType: le type de document où on fait des changements (loi, annotation). L'élément doit être un input.
	 * documentId: l'id (dans la db) du document qu'on édite.
	 */
	initialize: function(data, parent, options) {
		// unique ID to distinguish various inline editors elements.
		this.uniqueId = 'inlineEditor_' + ++inlineEditorCounter;

		this.setOptions(options);
		this.setDocumentData(parent);

		// Information about the element that is about to change
		this.originalData = $(data);
		this.editorData.isDate = this.originalData.hasClass('date');
		this.editorData.isOption = this.originalData.hasClass('option');
		this.editorData.isComplex = this.originalData.hasClass('complex');
		this.editorData.isCombo = this.originalData.hasClass('combo');
		this.editorData.metaname = this.extractData(this.originalData);

		// Adjust the edit button, if there is one.
		if ($chk(this.options.editButton)) {
			if (this.editorData.isComplex) {
				this.options.editButton.setStyle('float', 'left');
			}
		}

		// Elements created to build the inline editor (ile) interface
		this.ileInterface = this.createIleInterface();
	},

	/**
	 *
	 */
	extractData: function(data) {
		var stringId = data.getProperty('id');
		return stringId.substring(0, stringId.indexOf('_'));
	},

	setDocumentData: function(parent) {
		var stringId = parent.getProperty('id');
		var _index = stringId.indexOf('_');

		this.documentData.type = stringId.substring(0, stringId.indexOf('_'));
		this.documentData.id = stringId.substring(stringId.indexOf('_') + 1);
	},

	/**
	 *
	 */
	createIleInterface: function() {
		var ileForm = new Element('form', {
			'class': 'edit',
			'styles': {
				'margin-bottom': this.originalData.getStyle('margin-bottom'),
				'margin-top': this.originalData.getStyle('margin-top')
			}
		});

		var ileInterface = new Element('div');

		ileInterface.adopt([this.createEditInput(), this.createButtons()]);
		ileForm.adopt(ileInterface);

		ileForm.inject(this.originalData, 'before');
		ileForm.setStyles(this.originalData.getStyles(
				'position', 'float', 'top', 'bottom', 'left', 'right'
		));

		if (this.editorData.isDate) {
			this.prepCalendar(this.uniqueId); // prep calendar only once the input is inserted in the DOM.
		} else if (this.editorData.isComplex) {
			tinyMCE.execCommand('mceAddControl', false, this.uniqueId);
		}

		this.originalData.fireEvent('mouseleave');
		this.originalData.addClass('removed');
		if (this.options.editButton) {
			this.options.editButton.fireEvent('mouseleave');
			this.options.editButton.addClass('removed');
		}

		if ($defined(ileForm.getElement('input'))) {
			ileForm.getElement('input').focus();
		}

		return ileForm;
	},

	/**
	 *
	 */
	createEditInput: function() {
		var inputField = new Element('input');

		if (this.editorData.isComplex) {
			// Init tinyMCE
			var originalCopy = this.originalData.clone();
			inputField = new Element('textarea', {
				'id': this.uniqueId
			});

			// Under these circumstances, set('html') doesn't work with IE.
			if (IE) {
				inputField.adopt(originalCopy.getChildren());
			} else {
				inputField.set('html', originalCopy.get('html'));
			}

		} else if (this.editorData.isCombo) {
			//var childEditables =
		} else {
			inputField.set({
				'type': 'text',
				'value': this.originalData.get('text'),
				'styles': {
					'font-size': this.originalData.getStyle('font-size'),
					'font-weight': this.originalData.getStyle('font-weight')
				}
			});

			//var inlineEditor = this;
			inputField.addEvent('keydown', (function(event){
				if (event.key == 'enter'){
					event.preventDefault();
					this.acceptChange();
				}
			}).bind(this));

			if (this.editorData.isDate) {
				inputField.setProperty('id', this.uniqueId);
			}
		}

		return inputField;
	},

	/**
	 * Simply creates the accept and cancel buttons
	 */
	createButtons: function() {
		var acceptButton = this.createAcceptButton();
		var cancelButton = this.createCancelButton();
		var buttons = new Element('div', {
			'class': 'editButtons'
		});

		buttons.adopt([acceptButton, cancelButton]);

		return buttons;
	},

	/**
	 * Simply creates the accept button
	 */
	createAcceptButton: function() {
		var inlineEditor = this;
		var acceptButton = new Element('img',  {
			'src': this.options.okButton,
			'alt': messages.get('edit_acceptChange'),
			'title': messages.get('edit_acceptChange')
		});

		acceptButton.addEvent('click', (function(){
			this.acceptChange();
		}).bind(this));
		return acceptButton;
	},

	/**
	 * Accepts the change and sends the information to the server.
	 * Then the new information is taken from the server's response
	 * and put in place of the old information.
	 */edit_addArticle: '',
	acceptChange: function() {
		var newData = null;

		if (this.editorData.isComplex) {
			tinyMCE.triggerSave();
			newData = tinyMCE.get(this.uniqueId).getContent().clean();
		} else {
			newData = this.ileInterface.getElement('input').value.clean();
		}

		if (newData == this.originalData.get('html').clean()) {
			this.cancelChange();
		} else {
			var requestData = new Object();
			requestData['id'] = this.documentData.id;
			requestData['field'] = this.editorData.metaname;
			requestData['language'] = this.options.language;
			requestData['value'] = newData;
			if (this.options.user) {
				requestData['user'] = this.options.user;
			}

			var myself = this;

			var request = new Request.JSON({
				url: myself.options.action,
				data: requestData,
				onRequest: function() {
				},

				onFailure: function() {
					myself.destroy();
				},

				onSuccess: function(responseJSON, responseText) {
					myself.originalData.set('html', responseJSON[requestData.field]);
					myself.destroy();
				}
			}).send();
		}

	},

	/**
	 * Simply creates the cancel button.
	 */
	createCancelButton: function() {
		var inlineEditor = this;
		var cancelButton = new Element('img', {
			'src': this.options.cancelButton,
			'alt': messages.get('edit_cancelChange'),
			'title': messages.get('edit_cancelChange')
		});

		cancelButton.addEvent('click', function(){inlineEditor.cancelChange();});
		return cancelButton;
	},

	/**
	 * Cancels the change and revert to the original information
	 * This function is set to the click event of the cancel button.
	 */
	cancelChange: function() {
		this.destroy();
	},

	/**
	 *
	 */
	prepCalendar: function(uniqueId) {
		if (this.editorData.isDate) {
			var object = new Object();
			object[uniqueId] = 'Y-m-d';
			new Calendar(object, {days: lexactoWeekdays, months: lexactoMonths});
		}
	},


	/**
	 * Deletes the edit interface and brings back the original data
	 */
	 destroy: function() {
		if (this.editorData.isComplex) {
			tinyMCE.execCommand('mceFocus', false, this.uniqueId);
			tinyMCE.execCommand('mceRemoveControl', false, this.uniqueId);
		}

	 	this.ileInterface.destroy();
	 	this.originalData.removeClass('removed');
	 	if (this.options.editButton) {
			this.options.editButton.removeClass('removed');
		}


	 }
});


/** *********************************************
 ** ************** MESSAGES BUNDLE **************
 **
 ** Additional messages for the edit interface.
 ** They are added to the global messages bundle.
 **
 ************************************************
 ************************************************ */
var _en_editBundle = new Hash({
	edit_clickToEdit: 'Click to edit',
	edit_acceptChange: 'Accept change',
	edit_cancelChange: 'Cancel change',
	edit_addAnnotation: 'Add an annotation',
	edit_editAnnotation: 'Edit this annotation',
	edit_deleteAnnotation: 'Delete this annotation',
	edit_deleteAnnotationConfirmation: 'Are you sure you want to delete this annotation?',
	edit_deleteArticle: 'Delete this article',
	edit_deleteArticleConfirmation: 'Are you sure you want to delete this article?',
	edit_communicationError: 'Server communication error. Please try again.'
});

var _fr_editBundle = new Hash({
	edit_clickToEdit: 'Cliquez pour modifier',
	edit_acceptChange: 'Acceptez la modification',
	edit_cancelChange: 'Annulez la modification',
	edit_addAnnotation: 'Ajoutez une annotation',
	edit_editAnnotation: 'Modifier cette annotation',
	edit_deleteAnnotation: 'Supprimer cette annotation',
	edit_deleteAnnotationConfirmation: 'Voulez-vous vraiment supprimer cette annotation?',
	edit_deleteArticle: 'Supprimer cet article',
	edit_deleteArticleConfirmation: 'Voulez-vous vraiment supprimer cet article?',
	edit_communicationError: 'Erreur de communication avec le serveur. Veuillez r\u00E9essayer.'
});

_en_lexactoBundle.combine(_en_editBundle);
_fr_lexactoBundle.combine(_fr_editBundle);

