function onLoad() {

	$ES(".resizable-textarea").each(function(value, index) {
		new AutoResize({
			elem : value
		});
	});

	initWysiwyg();

	// initUpload();

	/*
	 * var draggableOptions = { onStart:function() { }, onComplete:function() {
	 * var insertLink = $$("#content .insert"); for (var i=0;i<insertLink.length;
	 * i++) { insertLink[i].setStyle("background-color", "transparent;"); if
	 * ((this.element.getPosition().y >
	 * insertLink[i].getPosition().y-25)&&((this.element.getPosition().y <
	 * insertLink[i].getPosition().y+25))) {
	 * insertLink[i].setStyle("background-color", "#eeeeee;"); } }
	 *  }, onDrag:function() { var insertLink = $$("#content .insert"); for (var
	 * i=0;i<insertLink.length; i++) {
	 * insertLink[i].setStyle("background-color", "transparent;"); if
	 * ((this.element.getPosition().y >
	 * insertLink[i].getPosition().y-25)&&((this.element.getPosition().y <
	 * insertLink[i].getPosition().y+25))) {
	 * insertLink[i].setStyle("background-color", "#eeeeee"); } } }
	 *  };
	 * 
	 * var comps = $$('#content
	 * .component-cursor').makeDraggable(draggableOptions);
	 */

	selectZoneInit();
	autoScroll();

	/* set calendar */
	// yCal1 = new Calendar({ contentdate: 'd/m/Y' }, { direction: 1, tweak: {
	// x: 6, y: 0 }});
	/* Init box toggler */
	$$(".box-toggleable").each(function(box) {
		var data = box.getProperty('id');
		if (data != null) {
			data = new Hash.Cookie("box." + data, {
				duration : 365 * 60 * 60 * 1000
			});
		}
		var toggler = box.getElements(".toggler")[0];
		var body = box.getElements(".box-body")[0];
		var savedHeight = body.getCoordinates().height;
		var opened = toggler.hasClass('open') || !toggler.hasClass('close');

		var fxRunning = false;
		var hideFx = new Fx.Style(body, 'height', {
			duration : savedHeight,
			onStart : function() {
				fxRunning = true;
				if (!opened) {
					body.setStyle("overflow", "hidden");
				}
			},
			onComplete : function() {
				fxRunning = false;
				if (opened) {
					body.setStyle("overflow", null);
				}
			}
		});
		var refreshState = function() {
			toggler.removeClass(opened ? 'close' : 'open');
			toggler.addClass(opened ? 'open' : 'close');
			box.removeClass(opened ? 'closed' : 'opened');
			box.addClass(opened ? 'opened' : 'closed');
		};
		if (data != null) {
			var openedCookie = data.get('opened');
			if ($defined(openedCookie)) {
				opened = openedCookie;
				refreshState();
			}
		}
		var toogleIt = function() {
			if (!fxRunning) {
				opened = !opened;
				if (opened) {
					hideFx.start(0, savedHeight);
					box.fireEvent('open');
				} else {
					hideFx.start(savedHeight, 0);
					box.fireEvent('close');
				}
				refreshState();
				if (data != null) {
					data.set("opened", opened);
				}
			}
		};

		if (!opened) {
			hideFx.set(0);
			body.setStyle("overflow", "hidden");
		}
		toggler.addEvent('click', toogleIt);
	});

	/* Init IM */
	{
		// var IM_URL = DEFINED IN HTML;
		var DEST_USER_SEPARATOR = ":";
		var GLOBAL_USERNAME = "all";
		var box = $('im-box');
		if ($defined(box)) {
			var currendId = 0;
			var delayId = null;
			var scrollFx = new Fx.Scroll('im-messages');
			var users = {};

			var userList = $('im-users');
			userList.empty();
			var emptyOption = new Element("option");
			emptyOption.setText(" ");
			emptyOption.inject(userList);
			emptyOption.setProperty('selected', 'selected');

			var isBoxClosed = function() {
				return box.hasClass("closed");
			};
			var messageCountElement = $('im-message-count');
			var messageCount = -1;
			var refreshMessageCount = function(newMessageCount) {
				if (isBoxClosed()) {
					if ($defined(newMessageCount) && messageCount >= 0) {
						if (newMessageCount > 0) {
							messageCount += newMessageCount;
						}
					} else {
						messageCount = null;
					}
				} else {
					messageCount = null;
				}
				if (messageCount == null) {
					messageCountElement.setText("");
				} else {
					messageCountElement.setText("(" + messageCount + ")");
				}
			};
			box.addEvent("open", function() {
				refreshMessageCount();
			});

			var startRefresh = function(message) {
				$clear(delayId);
				var postData = {
					"currentId" : currendId
				};
				if ($defined(message)) {
					var username = null;
					var pos = message.indexOf(DEST_USER_SEPARATOR);
					if (pos >= 0) {
						var destUser = message.substring(0, pos);
						if ($defined(users[destUser])) {
							username = destUser;
						}
					}
					if (username == null) {
						username = userList.getValue();
						if (username == null || ("" + username).trim() == "") {
							username = GLOBAL_USERNAME;
						}
						message = username + DEST_USER_SEPARATOR + " " + message;
					}
					postData.message = message;
				}
				new Ajax(IM_URL, {
					postBody : postData,
					onComplete : function(response) {
						var lastEl = null;
						var rep = Json.evaluate(response);
						var newMessageCount = 0;
						// console.log(rep.users);
						rep.messages.each(function(message) {
							var el = new Element('li');
							var username = message.from;
							var user = rep.users[username];
							var text = message.message;
							var pos = text.indexOf(DEST_USER_SEPARATOR);
							if (pos >= 0) {
								var destUser = text.substring(0, pos);
								if (destUser == GLOBAL_USERNAME) {
									text = text.substring(pos + DEST_USER_SEPARATOR.length);
								} else {
									el.addClass("im-private-message");
									if (destUser == rep.currentUser) {
										el.addClass("im-to-current-user");
									}
								}
							}

							if ($defined(user)) {
								el.setStyle('color', user.color);
							}

							var fromSpan = new Element('span');
							fromSpan.addClass('im-username');
							fromSpan.setText(username + "> ");
							fromSpan.inject(el);
							fromSpan.addEvent('click', function() {
								try {
									users[username].option.setProperty("selected", "selected");
								} catch (ex) {
								}
							});
							var msgSpan = new Element('span');
							msgSpan.addClass('im-message');
							msgSpan.setHTML(text);
							msgSpan.inject(el);
							lastEl = el;
							el.inject($('im-messages'));
							newMessageCount++;
						});
						currendId = rep.newCurrentId;
						users = rep.users;
						userList.getChildren().each(function(option) {
							var username = option.getProperty('value');
							if (username != "") {
								var user = users[username];
								if ($defined(user)) {
									user.option = option;
								} else {
									userList.removeChild(option);
								}
							}
						});
						for ( var username in users) {
							var user = users[username];
							if (!$defined(user.option)) {
								var newOption = new Element('option');
								newOption.setStyle('color', user.color);
								newOption.setText(user.username);
								newOption.setProperty('value', user.username);
								newOption.inject(userList);
								user.option = newOption;
							}
						}
						if (lastEl != null) {
							scrollFx.toBottom();
						}
						refreshMessageCount(newMessageCount);
						delayId = startRefresh.delay(2000);
					}
				}).request();
			};

			$('send-form').addEvent("submit", function() {
				if ("" != $('im-message').getValue()) {
					startRefresh($('im-message').getValue());
					$('im-message').setProperty("value", "");
				}
			});
			startRefresh();
		}
	}
}

function initWysiwyg() {
	if(typeof(window.tinyMCE) !== 'undefined') {	
		tinyMCE.init({
			// General options
			mode : "specific_textareas",
			theme : "advanced",
			editor_selector : 'tinymce-light',
			plugins : "paste",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,cut,copy,paste,pastetext,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|",
			theme_advanced_buttons2 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true

		});
	}
}

function actionOnForm(number, form) {
	form.number.value = number;
	form.submit();
}

function SpecialActionOnForm(number, form) {
	form.comp_id.value = number;
	form.submit();
}

function insert(number, anchor, repeat) {
	var form = document.forms["insert"];
	form.action = '#' + anchor;
	form.repeat.value = repeat;
	actionOnForm(number, form);
}

function remove(number, anchor) {
	var form = document.forms["remove"];
	form.action = '#' + anchor;
	actionOnForm(number, form);
}

function copy(number, anchor) {
	var form = document.forms["copy"];
	form.action = '#' + anchor;
	SpecialActionOnForm(number, form);
}

function repeat(number, anchor) {
	var form = document.forms["repeat"];
	form.action = '#' + anchor;
	actionOnForm(number, form);
}

function unrepeat(number, anchor) {
	var form = document.forms["unrepeat"];
	form.action = '#' + anchor;
	actionOnForm(number, form);
}

function paste(number, anchor) {
	var form = document.forms["paste"];
	form.action = '#' + anchor;
	actionOnForm(number, form);
}

function pastePage(number, anchor) {
	var form = document.forms["paste-page"];
	form.action = '#' + anchor;
	actionOnForm(number, form);
}

function countLines(strtocount, cols) {
	var hard_lines = 1;
	var last = 0;
	while (true) {
		last = strtocount.indexOf("\n", last + 1);
		hard_lines++;
		if (last == -1)
			break;
	}
	var soft_lines = Math.round(strtocount.length / (cols - 1));
	var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
	if (hard)
		soft_lines = hard_lines;
	return soft_lines;
}

function displayMessageErrorMessageAsPopup() {
	var errorMessages = $$("#message .error");
	if (errorMessages.length > 0) {
		var message = $("message");
		if (!message.hasClass("popup")) {
			message.setProperty("class", "popup");
			message.setProperty("onmouseover", "");

			var title = new Element('h2');
			title.setHTML(MSG_ERROR);
			title.injectTop(message);

			var commandElement = new Element('div', {
				'style' : 'text-align: center;'
			});

			var closeElem = new Element('input', {
				'type' : 'button',
				'name' : 'close_message',
				'value' : MSG_CLOSE
			});
			closeElem.onclick = function() {
				$("message").setHTML("");
				$("message").setProperty("class", "");
				$("container").setOpacity(1);
				$("container").setProperty("onclick", "");
			}

			commandElement.injectInside(message);
			closeElem.injectInside(commandElement);
			$('container').setOpacity(0.2);
			$('container').setProperty("onclick", "return false;");
		}
	}
}

function resizeTextArea(textArea) {
	nCols = textArea.cols;
	sVal = textArea.value;
	var rows = countLines(sVal, nCols);
	if (rows > 30) {
		rows = 30;
	}
	textArea.rows = rows;
}

function closeComponent() {
	var componentForm = $('command');
	var closeCommand = $('component_reduction');
	closeCommand.setHTML('<a href="#">&lt;</a>');
	componentForm.setProperty("style", "right: -190px;");
	closeCommand.setProperty("onclick", "openComponent(); return false;")
}

function openComponent() {
	var componentForm = $('command');
	var openCommand = $('component_reduction');
	openCommand.setHTML('<a href="#">&gt;</a>');
	componentForm.setProperty("style", "right: 0px; width: 200;");
	openCommand.setProperty("onclick", "closeComponent(); return false;")
}

var IE = document.all ? true : false
if (!IE)
	document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0
var tempY = 0
function getMouseXY(e) {
	if (IE) {
		// tempX = e.clientX + document.body.scrollLeft;
		// tempY = e.clientY + document.body.scrollTop;
	} else {
		tempX = e.pageX
		tempY = e.pageY
	}
	if (tempX < 0) {
		tempX = 0
	}
	if (tempY < 0) {
		tempY = 0
	}
	if ($('preview-image')) {
		if (tempX < 520) {
			$('preview-image').setStyle("left", tempX + 16);
		} else {
			$('preview-image').setStyle("left", tempX - 516);
		}
		if (tempY < 200) {
			$('preview-image').setStyle("top", tempY);
		} else if ((tempY > 200) && (tempY < 500)) {
			$('preview-image').setStyle("top", tempY - 200);
		} else {
			$('preview-image').setStyle("top", tempY - 400);
		}
	}
	return true
}

function previewImage(src) {
	$('preview-image').setHTML('<img src="' + src + '" />');
}

function previewClear() {
	$('preview-image').setHTML('');
}

/**
 * filter a list of element (set in onkeydown input field)
 * 
 * @param {Object}
 *            elems a liste of element (sample: tr, li...)
 * @param {Object}
 *            value the value must be filtered
 */
function filter(elems, value) {
	elems.each(function(elem, index) {
		if (!elem.getText().contains(value)) {
			if (elem.oldDisplay == null) {
				elem.oldDisplay = elem.getStyle("display");
			}
			elem.setStyle("display", "none");
		} else {
			if (elem.oldDisplay != null) {
				elem.setStyle("display", elem.oldDisplay);
				elem.oldDisplay = null;
			}
		}
	});
	return false;
}

function selectZoneInit() {

	var zoneSelector = $$("div[class=zone-selector]");

	for ( var i = 0; i < zoneSelector.length; i++) {

		var zoneId = zoneSelector[i].getProperty("id");
		var elemId = zoneId.replace("zone-", "");
		zoneSelector[i].imageLinked = $("picture-" + elemId);
		zoneSelector[i].inputLinked = $("input-" + elemId);

		var centerX = zoneSelector[i].getCoordinates().width / 2;
		var centerY = zoneSelector[i].getCoordinates().height / 2;

		var position = zoneSelector[i].inputLinked.value.split(',');

		var positionX = Math.round((position[0] / 1000) * zoneSelector[i].imageLinked.getCoordinates().width);
		// positionX = positionX + zoneSelector[i].imageLinked.getPosition().x -
		// centerX;

		var positionY = Math.round((position[1] / 1000) * zoneSelector[i].imageLinked.getCoordinates().height);
		// positionY = positionY + zoneSelector[i].imageLinked.getPosition().y -
		// centerY;

		var draggableOptions = {

			/*
			 * limit: {'x':
			 * [zoneSelector[i].imageLinked.getPosition().x-centerX,
			 * zoneSelector[i].imageLinked.getCoordinates().right-centerX], 'y':
			 * [zoneSelector[i].imageLinked.getPosition().y-centerY,
			 * zoneSelector[i].imageLinked.getCoordinates().bottom-centerY]},
			 */

			limit : {
				'x' : [ -centerX, zoneSelector[i].imageLinked.getCoordinates().width - centerX ],
				'y' : [ -centerY, zoneSelector[i].imageLinked.getCoordinates().height - centerY ]
			},

			onDrag : function() {
				var relativeX = Math.round((((this.handle.getPosition().x - centerY) - this.handle.imageLinked.getPosition().x + this.handle.getCoordinates().width / 2) * 1000) / this.handle.imageLinked.getCoordinates().width);
				var relativeY = Math.round((((this.handle.getPosition().y - centerX) - this.handle.imageLinked.getPosition().y + this.handle.getCoordinates().height / 2) * 1000) / this.handle.imageLinked.getCoordinates().height);
				this.handle.inputLinked.value = relativeX + "," + relativeY;
			},

			onComplete : function() {

			}
		};

		zoneSelector[i].makeDraggable(draggableOptions);
		zoneSelector[i].setOpacity(0.5);
		/*
		 * alert("zoneSelector[i].getCoordinates().left =
		 * "+zoneSelector[i].getCoordinates().left); alert("positionX =
		 * "+positionX);
		 */
		zoneSelector[i].setStyle("left", positionX);
		zoneSelector[i].setStyle("top", positionY);
	}
	;
}

/** ****************************** */
/** *** selection management ***** */
/** ****************************** */

/**
 * return a array of string with 0:'prefix', 1:'selection' and 2:'suffix'
 * 
 * @param {Object}
 *            elem
 */
function extractSelection(elem) {
	var sel = new Array(3);
	if (elem.setSelectionRange) {
		sel[0] = elem.value.substring(0, elem.selectionStart);
		sel[1] = elem.value.substring(elem.selectionStart, elem.selectionEnd);
		sel[2] = elem.value.substring(elem.selectionEnd, elem.value.length);
	} else if (document.selection) {
		var value = elem.value;
		var specialCharSequence = "***** ! SPECIAL CHAR SEQUENCE ! ******";
		var selection = insertValue(elem, specialCharSequence);
		sel[0] = elem.value.substring(0, elem.value.indexOf(specialCharSequence));
		sel[1] = selection;
		sel[2] = elem.value.substring(elem.value.indexOf(specialCharSequence) + specialCharSequence.length, elem.value.length);
		elem.value = value;
	}
	return sel;
}

function getPrefixSelection(elem) {
	var sel = "";
	if (elem.setSelectionRange)
		sel = elem.value.substring(0, elem.selectionStart);
	else if (document.selection) {
		var value = elem.value;
		var specialCharSequence = "***** ! SPECIAL CHAR SEQUENCE ! ******";
		insertValue(elem, specialCharSequence);
		sel = elem.value.substring(0, elem.value.indexOf(specialCharSequence));
		elem.value = value;
	}
	return sel;
}

function getSuffixSelection(elem) {
	var sel = "";
	if (elem.setSelectionRange)
		sel = elem.value.substring(elem.selectionEnd, elem.value.length);
	else if (document.selection) {
		var value = elem.value;
		var specialCharSequence = "***** ! SPECIAL CHAR SEQUENCE ! ******";
		insertValue(elem, specialCharSequence);
		sel = elem.value.substring(elem.value.indexOf(specialCharSequence) + specialCharSequence.length, elem.value.length);
		elem.value = value;
	}
	return sel;
}

function getSelection(elem) {
	var sel = "";
	if (elem.setSelectionRange)
		sel = elem.value.substring(elem.selectionStart, elem.selectionEnd);
	else if (document.selection) {
		elem.focus();
		range = document.selection.createRange();
		sel = range.text;
	}
	return sel;
}

/**
 * insert text in the elem selection, return the selected text
 * 
 * @param {Object}
 *            elem
 * @param {Object}
 *            text
 */
function insertValue(elem, text) {
	var result = "";
	// IE support
	if (document.selection) {
		elem.focus();
		sel = document.selection.createRange();
		result = sel.text;
		sel.text = text;
	}
	// MOZILLA/NETSCAPE support
	else if (elem.selectionStart || elem.selectionStart == "0") {
		var startPos = elem.selectionStart;
		var endPos = elem.selectionEnd;
		var chaine = elem.value;

		elem.value = chaine.substring(0, startPos) + text + chaine.substring(endPos, chaine.length);
		result = elem.value.substring(elem.selectionStart, elem.selectionEnd);
	} else {
		elem.value += chaineAj;
		result = elem.value;
	}
	return result;
}

function insertMarker(elem, prefix, suffix) {
	var selection = getSelection(elem);
	insertValue(elem, prefix + selection + suffix);
}

function initUpload() {

	/**
	 * We take the first input with this class we can find ...
	 */
	var input = $('upload-filedata');

	/**
	 * Simple and easy
	 * 
	 * swf: the path to the swf container: the object is embedded in this
	 * container (default: document.body)
	 * 
	 * NOTE: container is only used for the first uploader u create, all others
	 * depend on the same swf in that container, so the container option for the
	 * other uploaders will be ignored.
	 * 
	 */

	var flashURL = BASE_PATH + '/js/fancy_upload/Swiff.Uploader.swf';
	if (BASE_PATH == '/') {
		flashURL = '/js/fancy_upload/Swiff.Uploader.swf';
	}

	var upload = new FancyUpload(input, {
		swf : flashURL,
		queueList : 'upload-queue',
		types : {
			'*.*' : '*.*'
		},
		onAllComplete : reloadCurrentPage,
		instantStart : true
	});

	if ($('upload-filedata-submit') != null) {
		$('upload-filedata-submit').setStyle('display', 'none');
	}

	/**
	 * We create the clear-queue link on-demand, since we don't know if the user
	 * has flash/javascript.
	 * 
	 * You can also create the complete xhtml structure thats needed for the
	 * queue here, to be sure that its only in the document when the user has
	 * flash enabled.
	 */
	if ($('upload-status') != null) {
		$('upload-status').adopt(new Element('a', {
			'href' : '#',
			'events' : {
				'click' : (function(e) {
					e.stop();
					upload.clearList(false);
				}).bindWithEvent()
			}
		}).setHTML('Clear Completed'));
	}

};

function reloadCurrentPage() {
	if (CURRENT_MODE != 'admin') {
		window.location.href = CURRENT_URL_EDIT;
	} else {
		window.location.href = CURRENT_URL_ADMIN;
	}
};

/**
 * AutoResize - automatically resize the height of a textarea as its content
 * changes Inspired by Chrys Bader's AutoGrow jQuery plugin
 * 
 * ex: new AutoResize(html elem);
 */
var AutoResize = new Class({

	Implements : Options,

	options : {
		elem : null
	// html id of the textarea to AutoResize
	},

	initialize : function(options) {

		this.options = options;

		this.textarea = this.options.elem;

		this.minHeight = (this.textarea.getAttribute('rows').toInt() + 1) * ($type(this.textarea.getStyle('line-height').toInt()) ? this.textarea.getStyle('line-height').toInt() : '20') + this.textarea.getStyle('padding').toInt();

		// Create a ghost element and copy some style properties involved in
		// height
		this.dummy = new Element('div', {
			'styles' : {
				'display' : 'block',
				'position' : 'absolute',
				'top' : '-9999px',
				'right' : '0',
				'border' : '1px solid red',
				'background-color' : '#ffcccc',
				'font-size' : this.textarea.getStyle('font-size'),
				'font-family' : this.textarea.getStyle('font-family'),
				'line-height' : this.textarea.getStyle('line-height'),
				'width' : this.textarea.getSize().size.x,
				'padding' : this.textarea.getStyle('padding')
			}
		});
		this.dummy.inject(this.textarea, "before");

		// Prepare textarea
		this.textarea.addEvent('focus', this.resize.bind(this));
		this.textarea.addEvent('keyup', this.resize.bind(this));
		// this.textarea.setStyle('overflow-y', 'hidden');

		this.resize();
	},

	resize : function() {
		var contents = this.textarea.value;

		// Replace html tags by dummy content
		contents = contents.replace(/(<|>)/g, 'n');

		// Simulate line breaks
		contents = contents.replace(/\n/g, '<br />n');

		// Refresh width as the textarea could have been changed
		if (this.textarea.getSize().x != 0) {
			this.dummy.setStyle('width', this.textarea.getSize().size.x);
		}

		this.dummy.setHTML(contents);

		// Resize
		var dummyHeight = this.dummy.getSize().size.y;
		var newHeight = dummyHeight + 15;

		if (dummyHeight < 16) {
			newHeight = 16;
		} else if (dummyHeight > 1000) {
			newHeight = 1000;
		}
		this.textarea.setStyle('height', newHeight + "px");

	}

});

