// //////////////////////////////////////////////////////////////////////////////////////////
// NOTE: This javascript file depends on mootools, lexum-classes.js and lexacto-resources.js,
// for variables like _bundle, _language, _months and _weekdays
// //////////////////////////////////////////////////////////////////////////////////////////

// ///////////////////////////////////////////////////////////////////////////////////////
// FOR CLARITY SAKE, PLEASE LEAVE THIS SECTION AT THE TOP OF THE FILE
// Put in there the functions that need to be called when the all the DOM is done loading.
// ///////////////////////////////////////////////////////////////////////////////////////
var _debug = true;
var messages = _bundle.get(_language);
var lexactoMonths = _months.get(_language);
var lexactoWeekdays = _weekdays.get(_language);
var logger = new Logger(_debug);
var incrementalId = 0;

window.addEvent('domready', function() {
	//prepareMenu();
	prepareLevelsLoader();
	//prepareSearchForms();
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
function prepareMenu() {
	if ($('menu')) {
		new Menu($('menu').getElement('ul'), {
			hoverClass: 'menuHover'
		});
	}
}


function prepareSearchForms() {
	if ($('searchForms') && $('formsTab')) {
		var simpleSearchTogglee = new Togglee($('simpleSearch'), true, {
			duration: 450
		});

		var advancedPreshow = function() {
			simpleSearchTogglee.toggleState();
			simpleSearchTogglee.hide();
		};

		var advancedPosthide = function() {
			simpleSearchTogglee.toggleState();
			simpleSearchTogglee.show();
		};

		var advancedSearchTogglee = new Togglee($('advancedSearch'), false, {
			duration: 450,
			preshow: advancedPreshow,
			posthide: advancedPosthide
		});
		//var simpleSearchToggler = new Toggler($('formsTab'), simpleSearchTogglee, {});
		var advancedSearchToggler = new Toggler($('formsTab').getElement('.tab'), advancedSearchTogglee, {
			collapsedText: messages.get('advancedSearch'),
			expandedText: messages.get('simpleSearch')
		});
	}
}


function prepareAnnotationsLoader(annotationsGroup, annotationsCount) {
	if (!context.editionMode) {
		// This will get the id of the article these annotations are attached to.
		var underscoreIndex = annotationsGroup.getProperty('id').indexOf('_');
		var annotationsGroupId = annotationsGroup.getProperty('id').substring(underscoreIndex + 1);

		// This sets the title of the annotations area ("x annotations")
		setAnnotationsAnnounce(annotationsGroup, annotationsCount);

		var annotationsGroupTitle = annotationsGroup.getElement('h3');

		// This creates the content of each of the article's annotations.
		var annotationsGroupContent = annotationsGroup.getElement('.annotationsGroupContent');
		if (annotationsGroupContent != null) {
			var annotations = annotationsGroupContent.getElement('.annotations');

			// Stuff to prep the request
			var request = new Request.HTML({
				url: __root + '/getAnnotations.do',
				method: 'post',
				data: {
					id: annotationsGroupId,
					lang: _language
				}
			});

			var preshow = function() {
				if (annotations.hasClass('dirty')) {
					request.addEvent('failure', function() {
						displayTogglerState(annotationsGroupTitle, __images + '/error-small-gray.gif');
						// TODO: should have some kind or error message
						displayAjaxError(annotations, 'Erreur lors de la communication avec le serveur');
					});

					request.addEvent('request', function() {
						displayTogglerState(annotationsGroupTitle, __images + '/wait-gray.gif');
					});

					request.addEvent('success', function(tree, elements, html, javascript) {
						try {
							annotations.set('html',html);
							annotations.removeClass('dirty');
							// If secure, allow edition of the annotation.
							prepareAnnotationsEdit(annotationsGroupContent, _language);
						} catch (error) {
							// Communication with server went fine, but something in the response was wrong...
						}

						displayTogglerState(annotationsGroupTitle);
					});

					request.send();
				} else {
					return;
				}
			}

			if (annotationsCount > 0 || security['newAnnotation']) {
				var annotationTogglee = new Togglee(annotationsGroupContent, false, {
					duration: 250,
					preshow: preshow,
					scrollToOnClose: annotationsGroup
				});

				var toggler1 = annotationsGroupContent.getElement('.annotationsFooter').getElement('.toggler');
				var annotationToggler1 = new Toggler(toggler1.getElement('img'), annotationTogglee);
				var annotationToggler2 = new Toggler(annotationsGroupTitle, annotationTogglee, {
					collapsedImage: __images + '/expand.gif',
					expandedImage: __images + '/collapse.gif',
					imagePosition: 'inside'
				});

				// The select to filter the type of annotations to show.
				prepareAnnotationTypeFilter(annotationsGroup, annotationTogglee, request);

				// Add function on button to add an annotation.
				prepareAnnotationButton(annotationsGroupContent);

			} else if (!security['newAnnotation']) {
				annotationsGroup.getElement('form.annotationFilter').setStyle('display', 'none');
				annotationsGroupContent.getElement('.annotations').setStyle('display', 'none');
				annotationsGroupContent.getElement('.annotationsFooter').setStyle('display', 'none');
			}
		}
	}
}

function prepareAnnotationTypeFilter(annotationsGroup, annotationTogglee, request) {
	var annotationTypeFilter = annotationsGroup.getElement('form.annotationFilter').annotationTypeFilter;
	var annotations = annotationsGroup.getElement('.annotations');

	filterChange = function() {
		// Gael fix
		if (annotationTypeFilter.value == 'all') {
			request.options.data.annotationTypeId = null;
		} else {
			request.options.data.annotationTypeId = annotationTypeFilter.value;
		}
		annotations.addClass('dirty');

		if (annotationTogglee.isVisible()) {
			annotationTogglee.hide();
			setTimeout(function() {annotationTogglee.show();}, annotationTogglee.options.duration + 50);
		}
	};

	if (!IE6 && !IE7) {
		annotationTypeFilter.addEvent('change', filterChange);
	} else {
		annotationTypeFilter.onchange = filterChange;
	}

}

function setAnnotationsAnnounce(annotationsGroup, annotationCount) {
	var annotationsAnnounceSubstitution= {count: annotationCount, plural: annotationCount > 1 ? 's':  ''};
	var annotationsAnnounce = messages.get('annotationCountTemplate').substitute(annotationsAnnounceSubstitution);
	annotationsGroup.getElement('.annotationsAnnounce').set('text', annotationsAnnounce);
}

function displayTogglerState(parent, imageSrc) {
	var imgElement = parent.getElement('img.togglerState');

	if ($defined(imageSrc)) {

		if (imgElement == null) {
			imgElement = new Element('img', {
				'class': 'togglerState',
				'src': imageSrc
			});

			parent.grab(imgElement, 'bottom');
		}

		imgElement.setProperty('src', imageSrc);
	} else {
		if (imgElement != null) {
			var fader = new Fx.Tween(imgElement);
			fader.start('opacity', 0).chain((function() {
				this.destroy();
			}).bind(imgElement));
		}
	}
}

function displayAjaxError(target, message) {
	var p =  target.getElement('p.ajaxError');

	if (p == null) {
		p = new Element('p', {
			'class': 'ajaxError',
			'html': message
		});
		target.grab(p);
	}
}


function prepareLevelsLoader() {
	if ($defined($('documentContent'))) {
		var levels = $('documentContent').getElements('div.level');

		$each(levels, function(level, index) {
			// TODO Backend changes needed before using edition mode.
			// If secure, allow edition of the title and label of the article.
			prepareArticleEdit(level, _language);

			var underscoreIndex = level.getProperty('id').indexOf('_');
			var levelId = level.getProperty('id').substring(underscoreIndex + 1);
			var levelContent = level.getElement('div.levelContent');

			if (levelContent != null) {
				var levelTitle = level.getElement('.levelTitle');

				var levelText = level.getElement('div.levelText');

				var annotationsGroup = level.getElement('.annotationsGroup');

				var preshow = function() {
					if (levelText.hasClass('dirty')) {
						var request = new Request.JSON({
							url: __root + '/getArticle.do',
							method: 'post',
							data: {
								id: levelId,
								language: _language,
								lang: _language,
								field: 'text'
							},
							onFailure: function() {
								displayTogglerState(levelTitle, __images + '/error-small.gif');
								prepareAnnotationsLoader(annotationsGroup, 0);
								// TODO: should have some kind or error message
								displayAjaxError(levelText, 'Erreur lors de la communication avec le serveur');
							},
							onRequest: function() {
								displayTogglerState(levelTitle, __images + '/wait.gif');
							},
							onSuccess: function(responseJSON, responseText) {
								try {
									prepareAnnotationsLoader(annotationsGroup, responseJSON.annotationSize.toInt());
									levelText.set('html', responseJSON.text);
									levelText.removeClass('dirty');
								} catch(error) {
									// Communication with server went fine, but something in the response was wrong...
								}

								displayTogglerState(levelTitle);
							}
						}).send();

					} else if (levelText.hasClass('expanded')) {
						// Get annotation count from the markup
						var annotationCountText = annotationsGroup.getElement('.annotationsAnnounce').get('text');
						var whiteSpaceIndex = annotationCountText.indexOf('\n');
						var annotationCount = annotationCountText.substring(0, whiteSpaceIndex);

						prepareAnnotationsLoader(annotationsGroup, annotationCount);
						displayTogglerState(levelTitle);
					} else {
						return;
					}
				};

				var levelTogglee = new Togglee(levelContent, levelText.hasClass('expanded'), {
					duration: 250,
					preshow: preshow
				});
				var levelToggler = new Toggler(levelTitle, levelTogglee, {
					togglerImage: levelTitle.getElement('.togglerImage'),
					collapsedImage: __images + '/levelExpand.gif',
					expandedImage: __images + '/levelCollapse.gif',
					imagePosition: 'after'
				});

				if (levelText.hasClass('expanded')) {
					preshow();
				}


			}
		});
	}
}

