window.loadActions = [ ];
window.unloadActions = [ ];


window.onload = function() {
//-----======

	var
		i;
		
	for (i = 0; i < window.loadActions.length; i++)
		window.loadActions[i]();
}


window.onunload = function() {
//-----========

	var
		i;
		
	for (i = 0; i < window.unloadActions.length; i++)
		window.unloadActions[i]();
}


// --- IDENTIFICATION DE LA PLATE-FORME ---


function Platform (words) {
//-------========--------

	/*
		If words is given :
		
			Platform() returns true or false depending if all words are matched
			or not in the client's identification.
		
			(words is a \W+ separated list of words. Words order and case are
			irrelevant.)
			
		If not :
		
			Platform() returns a string identifying the platform.
		
		MacOS is matched with	: mac
		Windows ...				: win
		Explorer ...			: msie
		Netscape ... 			: netscape
	
		Examples :
		
			Platform('msie mac')
			Platform('mac')
			Platform('WIN')
			Platform('NETSCAPE')
	*/

	var
		i,
		wordsList;
		
	if (typeof Platform.PLATFORM == 'undefined')
		Platform.PLATFORM =
			(typeof navigator == 'undefined' ?
				'' :
				(typeof navigator.userAgent == 'undefined' ?
					'' :
					navigator.userAgent +
						(typeof navigator.PLATFORM == 'string' ? 
							navigator.PLATFORM :
							''
						)
				)
			);
	if (words == null)
		return Platform.PLATFORM;
	wordsList = words.split(/\W+/);
	for (i = 0; i < wordsList.length; i++)
		if (! Platform.PLATFORM.match(new RegExp(wordsList[i], 'i')))
			return false;
	
	return true;
}


// --- NAVIGATION ---


function R(view, focus) { // (R)equest
//-------=-------------

	document.forms[0]['S-N-VIEW'].value = view;
	document.forms[0]['S-N-FOCUS'].value = focus;
	document.forms[0].submit();
}


// --- GESTION DE TOUCHES OU CLICS PARTICULIERS ---


function StoreModifiers(evt) {
//-------==============-----

	/*
		Assure l'envoi au serveur des modifiers possiblement associés au clic
		ou à la frappe qui déclenche la requête.
		
		(Par exemple, le traitement d'un clic sur un bouton "Submit" de la vue
		"Articles" sera différent selon que le modifier SHIFT est présent ou
		non. Dans le premier cas, si les droits le permettent, l'activation de
		l'article concerné sera effectuée dans la foulée.
	*/
	
	document.forms[0]['S-KBD-MODIFIERS'].value =
		'' +
		(evt.shiftKey ? 'S' : '') +
		(evt.altKey   ? 'A' : '') +
		(evt.ctrlKey  ? 'C' : '');
}


window.document.onmousedown = function(evt) {
//--------------===========

	if (! evt || ! evt.target)
		evt = window.event;
	StoreModifiers(evt);
	return true;
}


window.document.onkeypress = function(evt) {
//--------------==========

	var
		target,
		tagName,
		type;
		
	if (! evt || ! evt.target)
		evt = window.event;
	StoreModifiers(evt);
	if (evt.keyCode == 27) { // Seules les touches ESC et ...
		LogPanelToggle(false);
		return false; // Empêche tout traitement par défaut
	}
	else if (evt.keyCode == 13) { // ... RTN font l'objet d'un traitement particulier.
		tagName = (
			evt.target && evt.target.tagName ?
				(target = evt.target).tagName :
				(evt.srcElement && evt.srcElement.tagName ? (target = evt.srcElement).tagName : '')
		).toLowerCase();
		if (
			tagName == 'textarea' ||
			tagName == 'select' ||
			(tagName == 'input' && (type = target.type).toLowerCase() != 'text' && type != 'password')
		) return true; // Traitement par défaut
		if (evt.shiftKey)
			LogPanelToggle();
		return false; // Empêche tout traitement par défaut
	}
	return true;
}


function LogPanelToggle(mode) {
//-------==============------

	var
		logPanel = document.getElementById('iLOGIN_PANEL'),
		logInput;
	
	if (logPanel && document.getElementById('iLOGIN_SUBMIT')) {
		logPanel.style.display = (mode == null ? (logPanel.style.display == 'none' ? 'block' : 'none') : (mode ? 'block' : 'none'));
		if (logPanel.style.display == 'block' && (logInput = document.getElementById('iLOGIN_INPUT')))
			logInput.focus();
	}
}


// -- GESTION DU RANKING --


var
	RK_InitialRanking = [ ],
	RK_Sel1,
	RK_Sel2,
	RK_Ranks,
	RK_AfterLast;

	
function RK_Init() {
//-------=======--

	var
		i;
		
	if (typeof(RK_Sel1) == 'undefined') {
		RK_Sel1 = document.getElementById('iRK_SEL1');
		RK_Sel2 = document.getElementById('iRK_SEL2');
		RK_Ranks = document.forms[0].RK_RANKS;
		RK_AfterLast = new Option('  -- THE END --', '');
		for (i = 0; i < RK_Sel1.options.length; i++)
			RK_InitialRanking[i] = RK_Sel1.options[i];
	}
}


function RK_Select() {
//-------=========--

	var
		i,
		option;
		
	RK_Init();
	RK_Sel2.options.length = 0;
	for (i = 0; i < RK_Sel1.options.length; i++)
		if (! (option = RK_Sel1.options[i]).selected)
			RK_Sel2.options[RK_Sel2.options.length] = new Option(option.text, option.value);
	RK_Sel2.options[RK_Sel2.options.length] = RK_AfterLast;
}


function RK_Move() {
//-------=======--

	var
		selSize = RK_Sel1.options.length - (RK_Sel2.options.length - 1),
		offset = RK_Sel2.selectedIndex,
		options = [ ],
		option,
		i,
		j;
		
	RK_Init();
	for (i = 0; i < RK_Sel2.options.length - 1; i++)
		options[i] = RK_Sel2.options[i];
	i = j = 0;
	while (j < selSize)
		if ((option = RK_Sel1.options[i++]).selected)
			options.splice(offset + j++, 0, option);
	RK_Reset(options);
}


function RK_Reset(options) {
//-------========---------

	var
		i;
		
	RK_Init();
	RK_Sel2.options.length = RK_Sel1.options.length = 0;
	for (i = 0; i < options.length; i++)
		RK_Sel1.options[RK_Sel1.options.length] = options[i];
	RK_Sel1.selectedIndex = RK_Sel2.selectedIndex = -1;
	RK_AfterLast.selected = false;
}


function RK_Chron() {
//-------========--

	var
		options = [ ],
		i;

	RK_Init();
	for (i = 0; i < RK_InitialRanking.length; i++)
		options.push(RK_InitialRanking[i]);
	options.sort(
		function(option1, option2) {
			return (
				parseInt(option1.value.replace(/\D+/g, '')) -
				parseInt(option2.value.replace(/\D+/g, ''))
			);
		}
	);
	RK_Reset(options);
}


function RK_Inverse() {
//-------==========--

	var
		options = [ ],
		i;

	RK_Init();
	for (i = RK_Sel1.options.length - 1; i >= 0; i--)
		options.push(RK_Sel1.options[i]);
	RK_Reset(options);
}


function RK_Submit() {
//-------=========--

	var
		ranks = [ ],
		i;
		
	RK_Init();
	for (i = 0; i < RK_Sel1.options.length; i++)
		ranks.push(RK_Sel1.options[i].value);
	RK_Ranks.value = ranks.join(',');
	return true;
}


// -- GESTION DE SPACE MAP --

var
	MAP_Last1 = null,
	MAP_Last2 = null,
	MAP_Img = null;


function MAP_ShowArticles(id1, id2) {
//-------================----------

	if (MAP_Last1) {
		MAP_Last1.style.backgroundColor = '';
		MAP_Last1.style.color = '';
	}
	(MAP_Last1 = document.getElementById(id1)).style.backgroundColor = 'rgb(255, 255, 255)';
		MAP_Last1.style.color = 'rgb(0, 0, 0)';

	if (MAP_Last2) {
		MAP_Last2.style.visibility = 'hidden';
		MAP_Last2.style.zIndex = 0;
		MAP_Last2.style.backgroundColor = '';
		MAP_Last2.style.color = '';
	}
	(MAP_Last2 = document.getElementById(id2)).style.visibility = 'visible';
	MAP_Last2.style.zIndex = 1;
	MAP_Last2.style.backgroundColor = 'rgb(255, 255, 255)';
	MAP_Last2.style.color = 'rgb(0, 0, 0)';
}


function MAP_ShowImage(id1, id2, path) {
//-------=============----------------

	var
		anchor;
		
	if (document.getElementById(id1).style.zIndex == 1) {
		anchor = document.getElementById(id2);
		if (MAP_Img == null) {
			MAP_Img = document.createElement('img');
			MAP_Img.style.position = 'absolute';
			MAP_Img.style.zIndex = 2;
			MAP_Img.style.padding = '2px';
			MAP_Img.style.backgroundColor = 'rgb(127, 127, 127)';
			MAP_Img.style.top = '-2px';
			MAP_Img.style.right = '70px';
		}
		MAP_Img.src = path;
		anchor.appendChild(MAP_Img);
	}
}


function MAP_HideImage() {
//-------=============--

	if (MAP_Img && MAP_Img.parentNode)
		MAP_Img.parentNode.removeChild(MAP_Img);
}


// -- AJAX --


function AX_Send(url, request, callback) {
//-------=======------------------------

	AX_Send.Request = null;		
	if (typeof window.XMLHttpRequest != 'undefined') {
		try { AX_Send.Request = new XMLHttpRequest(); }
		catch(x) { AX_Send.Request = null; }
	}
	else if (typeof window.ActiveXObject != 'undefined') {
		try { AX_Send.Request = new ActiveXObject('Msxml2.XMLHTTP'); }
		catch(x) {
			try { AX_Send.Request = new ActiveXObject('Microsoft.XMLHTTP'); }
			catch(x) { AX_Send.Request = null; }
		}
	}
	if (AX_Send.Request != null) {
		AX_Send.Callback = callback;
		AX_Send.Request.onreadystatechange = AX_Reply;
		AX_Send.Request.open('post', url, true); // true = asynchrone.
		AX_Send.Request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		AX_Send.Request.send(request);

	}
	else
		alert('Browser Failure (browser not ajax-compatible)');
}


function AX_Reply() {
//-------========--

	if (AX_Send.Request.readyState == 4)
		if (AX_Send.Request.status == 200)
			AX_Send.Callback(AX_Send.Request.responseText);
		else
			alert('Request Failure (erroneous ajax request status)');
	return void null;
}


function AX_Quote(txt) {
//-------========-----

	/*
		Renvoie la chaîne donnée entourée d'apostrophes, après avoir procédé aux
		échappements nécessaires éventuels.
	*/
	
	return '\'' + txt.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + '\'';
}


//-- ARTICLE FIELD EDITOR TEXT PREVIEW --


window.TP = { timer: null };

TP.IsPreviewOpen = function() {
//-=============

	return typeof TP.preview != 'undefined' && ! TP.preview.closed;
}


TP.ShowHelp = function() {
//-========

	if (typeof TP.help != 'undefined' && ! TP.help.closed)
		TP.help.focus();
	else {
		TP.help = window.open('system/application/document-help.htm', 'fTP_HELP', 'width=300,height=200,resizable=yes,scrollbars=yes,status=yes');
		window.unloadActions.push(function() { if (! TP.help.closed) TP.help.close(); });
	}
}


TP.ShowPreview = function(url, title, style, base, html, aID, path2space, path2cwd, timeout) {
//-===========

	if (TP.IsPreviewOpen())
		TP.preview.focus();
	else {
		TP.html = html;
		TP.aID = aID;
		TP.path2space = path2space;
		TP.path2cwd = path2cwd;
		TP.timeout = timeout * 1000;
		TP.preview = window.open(url + '?TITLE=' + encodeURIComponent(title) + '&STYLE=' + encodeURIComponent(style) + '&BASE=' + encodeURIComponent(base), 'fTP', 'width=300,height=200,resizable=yes,scrollbars=yes');
		window.unloadActions.push(function() { if (! TP.preview.closed) TP.preview.close(); });
	}
}


TP.SetElement = function(elem, immediate) {
//-==========

	TP.elem = elem;
	if (TP.IsPreviewOpen()) {
		clearTimeout(TP.timer);
		if (immediate)
			TP.Send();
		else {
			TP.timer = setTimeout(TP.Send, TP.timeout);
			TP.preview.document.getElementById('iPV').style.color = 'gray';
		}
	}
}


TP.Send = function() {
//-====

	if (TP.IsPreviewOpen())
		AX_Send(
			'system/ajax-render.php',
			'text=' + encodeURIComponent(TP.elem.value) +
				'&html=' + encodeURIComponent(TP.html) +
				'&aID=' + encodeURIComponent(TP.aID) +
				'&path2space=' + encodeURIComponent(TP.path2space) +
				'&path2cwd=' + encodeURIComponent(TP.path2cwd),
			TP.Reply
		);
}


TP.Reply = function(result) {
//-=====

	if (TP.IsPreviewOpen()) {
		if (Platform('safari'))
			result = Utf8ToUnicode(result);
		TP.preview.document.getElementById('iPV').innerHTML = result;
		TP.preview.document.getElementById('iPV').style.color = '';
	}
}
