// ----------------------------------------------
// DATEPICKER FR
// ----------------------------------------------
jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Valider',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Aujourd\'hui',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dateFormat: 'dd/mm/yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});

// ----------------------------------------------
// INNER WINDOW
// ----------------------------------------------
jQuery (function($) {

	// ----------------------------------------------
	//  PATH TO DOCUMENT FOLDER (IE6 HACK)
	// ----------------------------------------------
	/**/
	$(".affTextArea a:not([href^='http'])").each(function(){
		var linker = this.href;
		if (linker.search(/javascript:|mailto:|wiki/) == -1) {
			$(this).attr('href',claroRoot+'document/goto/index.php/'+linker);
		}		
	});
	
	// ----------------------------------------------
	// globals vars
	// ----------------------------------------------

	// z-index 
	$.zindex = {
		iw : 100,
		ws : 0
	}
	
	// ----------------------------------------------
	// INNER WINDOW
	// ----------------------------------------------

	// enable click to .iw_loader elem to open inner window
	$(".iw_loader").live('click',function(){
		var ifIwExist = '#iw_'+$(this).attr('id');
		$(this).toggleFocus({group:'.iw_loader', applyTo:'none'});	
		if ($(ifIwExist).length) {
			$(ifIwExist).css('display','');
			$(ifIwExist).switchIndex({
				group 	: '.innerWindow',
				zindex 	: 'iw',
				focus	: true,
				msDown	: false
			});					
			return false;
		} else {
			$(this).innerWindow({
				zindex	: $.zindex.iw,
				ident 	: $(this).attr('id'),
				title 	: $(this).attr('title'),
				load 	: $(this).attr('href'),
				single	: $(this).attr('rel')
			});								
			return false;				
		}			
	});			
});
// swicth z-index for draggable group elem
(function($) {
	jQuery.fn.switchIndex = function(params) {
		var params = $.extend({
			group 	: '',
			zindex 	: 0,
			focus	: false,
			msDown	: true
		}, params);
		if (params.msDown) {
			// give this function on press to target elem
			$(this).mousedown(function(){
				$.zindex[params.zindex]++;
				$(this).css('zIndex', $.zindex[params.zindex]);
				$(this).toggleFocus({group: params.group});
			});
		}
		if (params.focus) {
			// focus & z-index target elem
			$.zindex[params.zindex]++;
			$(this).css('zIndex', $.zindex[params.zindex]);
			$(this).toggleFocus({group: params.group});	
		}
	};
})(jQuery);
// single focus elem of a group
(function($) {
	jQuery.fn.toggleFocus = function(params) {
		var params = $.extend({
			group 	: '',
			applyTo : this
		}, params);
		// remove focus class in all
		$(params.group).removeClass('focus');
		// focus if applyTo is enable
		if (params.applyTo != 'none')
			$(params.applyTo).addClass('focus');
	};
})(jQuery);
// close iw
(function($) {
	jQuery.fn.iw_close = function() {
		$(this).fadeOut(
			"fast",
			function(){
				$(this).remove();
			});		
	};
})(jQuery);

//------------------
// DETECT BROWSER
//------------------
	var d, n, na, nua, win, mac, lin, dom, op, konq, saf, moz, ie, ie6, ie4, ie5x, ie5mac, ie5xwin;
	d = document;
	n = navigator;
	na = n.appVersion;
	nua = n.userAgent;
	win = ( na.indexOf( 'Win' ) != -1 );
	mac = ( na.indexOf( 'Mac' ) != -1 );
	lin = ( nua.indexOf( 'Linux' ) != -1 );
	if ( !d.layers ){
		dom = ( d.getElementById );
		op = ( nua.indexOf( 'Opera' ) != -1 );
		konq = ( nua.indexOf( 'Konqueror' ) != -1 );
		saf = ( nua.indexOf( 'Safari' ) != -1 );
		moz = ( nua.indexOf( 'Gecko' ) != -1 && !saf && !konq);
		ie = ( d.all && !op );
		ie6 = ( d.all && !op );
		ie4 = ( ie && !dom );
		ie5x = ( d.all && dom );
		ie5mac = ( mac && ie5x );
		ie5xwin = ( win && ie5x );
	}
	if (window.XMLHttpRequest)
		ie6 = null;

// IE6 HACK
// Lancement de la class:hidden après le chargement du FILTRE IEPNG
function iePngOnLoad() {
	if (ie6) document.getElementById('contentBody').innerHTML +='<style>.hidden { display:none; }</style>';
}

//------------------
// COOKIES
//------------------
document.cookie	= "javascriptEnabled=true";

//------------------
// RECONNEXION AUTO
//------------------
// reload profil interval => 10 minutes (maxTimeOut)
// ouverture de la fenêtre de log si $_SESSIONS => TIMEOUT 

var maxTimeOut	= 600000;
var timeout		= window.setTimeout('loadingIco()', 1500);
var timer 		= window.setInterval('reloadLog()',maxTimeOut); 

function reconnect() {
	clearInterval(timer);
	openDialog('login');
}
// load iframe
function loadLog() {
	try {
	document.getElementById('timer').className = 'reload';	
	var timout = window.setTimeout("loadingIco()", 1500);
	} 
	catch(err) {}
}
// reconnexion
function reloadLog() {
	try {
	document.getElementById('timer').className = 'reload';	
	document.getElementById('iframe_timer').src = claroRoot+"/inc/reload.php?tim="+forceReload();	
	var timout = window.setTimeout("loadingIco()", 1500);
	} 
	catch(err) {}
}
// lancement de l'anim loading
function loadingIco() {
	try {
	document.getElementById('timer').className = 'noload';
	} 
	catch(err) {}	
}
// force le chargement evite le cache
function forceReload() {
	var reloading = new Date()
	var reloader = reloading.getHours()+'0'+reloading.getMinutes()+'0'+reloading.getSeconds(); 
	return reloader;
}

//------------------------------
// SWITCH MENU principal
//------------------------------
function switchMainMenu() {
	try {
	document.getElementById('timer').className = 'reload';	
	document.getElementById('iframe_timer').src = claroRoot+"/inc/reload.php?switchMM=swt";	
	var timout = window.setTimeout("loadingIco()", 1500);
	} 
	catch(err) {}
}
function hideMainMenu() {
	try {
	document.getElementById('main_menu').style.display = 'none';
	document.getElementById('main_content').className = 'block';
	document.getElementById('switchMainMenuBt').style.display = 'block';
		$('#calendar').fullCalendar('resize');
	} 
	catch(err) {}
}
function showMainMenu() {
	try {
	document.getElementById('main_menu').style.display = '';
	document.getElementById('main_content').className = '';
	document.getElementById('switchMainMenuBt').style.display = 'none';
		$('#calendar').fullCalendar('resize');
	} 
	catch(err) {}
}

//-----------------------------------------------
// INSERT CIDREQ et GIDREQ to all URL and ACTION
//-----------------------------------------------
function insertCidGidToUri() {

	// Liste des ZONES qui seront vérifiées
	var elems = new Array (	
	 	document.getElementById('toolViewOption'),
		document.getElementById('main_menu'),
		document.getElementById('main_content')
	);

	//REGLES DE FILTRAGE | on change l'URL si elle : 
	//	(== FALSE)
	//	- ne comporte pas déjà la variable cidReq en dur
	//	- n'est pas un appel de fonction JS
	//	- n'est pas une adresse mail
	//	- n'est pas la racine de la plateforme
	//	(== TRUE)
	//	- pointe sur le même domaine que celui de la plateforme EAD

	var ruleFalse = /javascript:|mailto:|cidReq=|@|http:\/\/foad.iedparis8.net\/claroline\/index.php/;
	var ruleTrue = /foad.iedparis8.net/;
	
	//REGLES pour la gestion des GROUPES | on change l'URL si elle :
	//	(== FALSE)
	//	- ne comporte pas déjà la variable gidReq en dur
	//	- ne comporte pas la variable gidReset en dur
	if (gid) { 
		gidR = 'gidReq'
		gidD = gid;	
	} else {
		gidR = 'gidReset'
		gidD = 'true';	
	}

	if (gid) gid = '&gidReq='+gid;
	else gid = '&gidReset=true';

	var ruleGid = /gidReq=|gidReset=/;

	// Pour chaque ZONE
	for (var j=0; j < elems.length; j++) {
		// IE hack
		if (!ie)	var childs = elems[j].getElementsByTagName('*');
		else 		var childs = elems[j].all;
		// On vérifie toutes les balises
		for (var i=0; i < childs.length; i++) {
			// Si l'élément comporte l'attribut HREF
			try {
				var uri = childs[i].href;
				var splitUri = uri.split('/');
				var lastUri = splitUri[splitUri.length-1];
				if (typeof parseInt(lastUri)=='number' && isNaN(lastUri)) {
					if (uri.search(ruleFalse) == -1 && uri.search(ruleTrue) != -1) {
						if (uri.search(/\?/) != -1)
							childs[i].href = childs[i].href.replace(/\?/,"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "&" : gid+"&"));
						else
							childs[i].href = uri+"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "" : gid);						
					}
				
				}
			} 
			catch(err) {}
			// Si l'élément comporte l'attribut ACTION
			try {
				uri = childs[i].action;
				if (uri.search(ruleFalse) == -1) {
					if (uri.search(/\?/) != -1)
						childs[i].action = childs[i].action.replace(/\?/,"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "&" : gid+"&"));
					else
						childs[i].action = uri+"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "" : gid);						
				}
			} 
			catch(err) {}
			// Si l'élément comporte l'attribut ONCLICK
			try {
				if (childs[i].attributes['onclick'].value != null) {
					uri = childs[i].attributes['onclick'].value;
					if (uri.search(/document.location/) != -1 && uri.search(ruleFalse) == -1) {
						if (uri.search(/\?/) != -1)
							var cleanUri = childs[i].attributes['onclick'].value.replace(/\?/,"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "&" : gid+"&"));		
						else
							var cleanUri = childs[i].attributes['onclick'].value.replace(/';return false;/,"?cidReq="+cid+((uri.search(ruleGid)!= -1) ? "';return false;" : gid+"';return false;"));
						if (!ie6) {
							cleanUri = cleanUri.replace(/;return false;/,'');
							childs[i].onclick = function(){ eval(cleanUri); return false; };
						} else
							childs[i].attributes['onclick'].value = cleanUri;
					}
				}
			} 
			catch(err) {}
		}
	}
	//------------------
	// FLV PLAYER
	//------------------
	// load flv PLAYER.	
	$("a[href*='.flv']").not('.asString').each(function(index) {
		var flvHref = $(this).attr('href');
		flvHref = escape(flvHref);
		$(this).after('<div class="player_legend">'+$(this).html()+'</div>');
		$(this).empty().addClass('playerFlv').attr('id','vdo_'+index);
		$('#vdo_'+index).flowplayer({ 
			src : claroRoot+'player/flowplayer.swf',
			wmode: 'transparent',
			cachebusting: true				
			},{
			canvas: {backgroundColor: '#d9d9d9'},
			clip: {  
				autoPlay: false,
				autoBuffering:true,
				url: flvHref
			}, 			
			plugins: {
				controls: {
				  url: claroRoot+'player/flowplayer.controls.swf',
				  sliderColor: '#000000',
				  tooltipColor: '#C9C9C9',
				  durationColor: '#ffffff',
				  tooltipTextColor: '#333333',
				  backgroundGradient: 'low',
				  progressGradient: 'none',
				  timeColor: '#999999',
				  volumeSliderGradient: 'low',
				  bufferColor: '#000000',
				  volumeSliderColor: '#000000',
				  progressColor: '#009ee0',
				  timeBgColor: '#262626',
				  sliderGradient: 'none',
				  bufferGradient: 'none',
				  borderRadius: '0px',
				  buttonColor: '#000000',
				  buttonOverColor: '#009ee0',
				  backgroundColor: '#CBCBCB',
				  height: 20,
				  opacity: 1.0
			   }
			} 
		});	
	}); 
}

//------------------
// MESSAGE BOX
//------------------

// open
function openMsgBox() {
	try {
		var popup = document.getElementById('messageBox');
		var winH = getWindowHeight();
		var winW = getWindowWidth();
		popup.style.display = 'block';	
		var popupWidth = popup.offsetWidth;
		var popupHeight = popup.offsetHeight;
		var clientWidth = (winW/2)-(popupWidth/2);
		var clientHeight = (winH/2)-(popupHeight/2);
		popup.style.left = clientWidth+'px';
		popup.style.top = clientHeight+'px';
		popup.style.width = popupWidth+'px';
		// resize input text & textera 
		if (document.all) var elems = popup.all;
		else var elems = popup.getElementsByTagName("*");
		for (var i=0; elems.length; i++) { 
			if (elems[i].tagName.toLowerCase() == 'textarea' || (elems[i].tagName.toLowerCase() == 'input' && elems[i].type.toLowerCase() == 'text')) { 
				elems[i].style.width = (popupWidth-35)+'px'; 
			} 
		}
	} 
	catch(err) {}
}

// close
function closeMsgBox() {
	document.getElementById('messageBox').style.display = 'none';
}

// DRAG EVENT
document.onmousemove	= mouseMove;
document.onmouseup		= mouseUp;
var dragObject  		= null;
var resizeObject  		= null;
var resizeObject2 		= null;
var mouseOffset 		= null;

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop - document.body.clientTop
	};
}

function getMouseOffset(target, ev){
	ev = ev || window.event;
	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}
	left += e.offsetLeft;
	top  += e.offsetTop;
	return {x:left, y:top};
}

function mouseMove(ev){
	ev = ev || window.event;
	var target = ev.target || ev.srcElement;
	var mousePos = mouseCoords(ev);
	if(dragObject){
		dragObject.style.top = mousePos.y - mouseOffset.y+'px';
		dragObject.style.left = mousePos.x - mouseOffset.x+'px';
		return false;
	} else if (resizeObject){
		resizeObject.style.width = mousePos.x - mouseOffset.x+'px';
		resizeObject2.style.width = 920 - resizeObject.offsetWidth+'px';
		return false;
	} else {
		return true;
	}
}
function mouseUp(){
	if (resizeObject) {
		resizeObject.className = '';
		resizeObject2 .className = '';
		resizeObject = null;
		resizeObject2 = null;
		ajustAll();
	} else {
		dragObject = null;
	}
}

function makeDraggable(btMove,target){
	btMove.onmousedown = function(ev){
		dragObject  = document.getElementById(target);
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
}

//-----------------------
// RESIZE EVENT (nodepad)
//-----------------------
function getMouseOffsetForResize(target, ev){
	ev = ev || window.event;
	var docWidth = resizeObject.offsetWidth;
	var mousePos = mouseCoords(ev);
	return { x:mousePos.x - docWidth };
}

function makeResize(btMove,target,target_r){
	btMove.onmousedown = function(ev){
		removeAjustAll();
		resizeObject  = document.getElementById(target);
		resizeObject2  = document.getElementById(target_r);
		resizeObject .className = 'inResize';
		resizeObject2 .className = 'inResize';
		mouseOffset = getMouseOffsetForResize(this, ev);
		return false;
	}
}

//-----------------------
// WINDOW HEIGHT / WIDTH
//-----------------------
function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number')
		windowHeight=window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		windowHeight = document.documentElement.clientHeight;
	else if (document.body&&document.body.clientHeight)
		windowHeight=document.body.clientHeight;
	return windowHeight;
}
function getWindowWidth() {
	var windowWidth=0;
	if (typeof(window.innerWidth)=='number')
		windowWidth=window.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		windowWidth = document.documentElement.clientWidth;
	else if (document.body&&document.body.clientWidth)
		windowWidth=document.body.clientWidth;
	return windowWidth;
}


//-----------------------------------
// CHECK / UNCHECK / INVERSE checkbox
//-----------------------------------
function checkBoxAll(field,mod) {
	if (mod == 'all')
		for (i = 0; i < field.length; i++)
			field[i].checked = true;
	else if (mod == 'none')
		for (i = 0; i < field.length; i++)
			field[i].checked = false;
	else if (mod == 'inverse') {
		for (i = 0; i < field.length; i++) {
		 if (field[i].checked == false) field[i].checked = true;
		 else field[i].checked = false;
		}		
	}
}
//-----------------------------------
// SHOW / HIDE with class = "hidden"
//-----------------------------------

function showHideByClass(bt,ident) {
	var elem = document.getElementById(ident);
	if($(elem).is(':hidden')) {
		$(elem).show('blind','fast').removeClass('hidden');
		$(bt).addClass('moins').removeClass('plus');
	} else {
		$(elem).hide('blind','fast').addClass('hidden');
		$(bt).addClass('plus').removeClass('moins');
	}
}

function showAllByClass(prefix,bt) {
	if (!ie)	var elems = document.getElementsByTagName('*');
	else		var elems = document.all;
	for (var i=0; i < elems.length; i++) { 
		var elemClass = elems[i].className;
		var elemId = elems[i].id;
		if (elemId.search(prefix) != -1 && $(elems[i]).is(':hidden'))
			$(elems[i]).show('blind','fast').removeClass('hidden');
		if (elemClass.search(bt) != -1 && $(elems[i]).hasClass('plus'))
			$(elems[i]).addClass('moins').removeClass('plus');
	}
}

function hideAllByClass(prefix,bt) {
	if (!ie)	var elems = document.getElementsByTagName('*');
	else		var elems = document.all;
	for (var i=0; i < elems.length; i++) { 
		var elemClass = elems[i].className;
		var elemId = elems[i].id;
		if (elemId.search(prefix) != -1 && $(elems[i]).is(':visible'))
			$(elems[i]).hide('blind','fast').addClass('hidden');
		if (elemClass.search(bt) != -1 && $(elems[i]).hasClass('moins'))
			$(elems[i]).addClass('plus').removeClass('moins');
	}
}

// FULLSCREEN
function noBackBody(){ 
	if (!ie)	document.body.style.backgroundImage = 'none';
	else		document.getElementsByTagName('body')[0].style.backgroundImage = 'none';
}
// suppression des saut de ligne et des retour à la ligne
function singleLine(txt){
	txt = tinyMCE.regexpReplace(txt,'\n','','gi');
	txt = tinyMCE.regexpReplace(txt,'\r','','gi');
	return txt;
}

/*
  SortTable
  version 2
  7th April 2007
  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
  
  Instructions:
  Download this file
  Add <script src="sorttable.js"></script> to your HTML
  Add class="sortable" to any table you'd like to make sortable
  Click on the headers to sort
  
  Thanks to many, many people for contributions and suggestions.
  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  This basically means: do what you want with it.
*/

 
var stIsIE = /*@cc_on!@*/false;

var sorttable = {

	init: function() {
		// quit if this function has already been called
		if (arguments.callee.done) return;
		// flag this function so we don't do the same thing twice
		arguments.callee.done = true;
		// kill the timer
		if (_timer) clearInterval(_timer);
		if (!document.createElement || !document.getElementsByTagName) return;
		sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
		forEach(document.getElementsByTagName('table'), function(table) {
			if (table.className.search(/\bsortable\b/) != -1) {
        		sorttable.makeSortable(table);
			}
    	});
	},

	makeSortable: function(table) {
		if (table.getElementsByTagName('thead').length == 0) {
			// table doesn't have a tHead. Since it should have, create one and
			// put the first table row in it.
			the = document.createElement('thead');
			the.appendChild(table.rows[0]);
			table.insertBefore(the,table.firstChild);
		}
		// Safari doesn't support table.tHead, sigh
		if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
		
		if (table.tHead.rows.length != 1) return; // can't cope with two header rows
		
		// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
		// "total" rows, for example). This is B&R, since what you're supposed
		// to do is put them in a tfoot. So, if there are sortbottom rows,
		// for backwards compatibility, move them to tfoot (creating it if needed).
		sortbottomrows = [];
		for (var i=0; i<table.rows.length; i++) {
			if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
				sortbottomrows[sortbottomrows.length] = table.rows[i];
			}
		}
		if (sortbottomrows) {
			if (table.tFoot == null) {
				// table doesn't have a tfoot. Create one.
				tfo = document.createElement('tfoot');
				table.appendChild(tfo);
			}
			for (var i=0; i<sortbottomrows.length; i++) {
				tfo.appendChild(sortbottomrows[i]);
			}
			delete sortbottomrows;
		}
		
		// work through each column and calculate its type
		headrow = table.tHead.rows[0].cells;
		for (var i=0; i<headrow.length; i++) {
			// manually override the type with a sorttable_type attribute
			if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
				mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
				if (mtch) { override = mtch[1]; }
				if (mtch && typeof sorttable["sort_"+override] == 'function') {
					headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
				} else {
					headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
				}
				// make it clickable to sort
				headrow[i].sorttable_columnindex = i;
				headrow[i].sorttable_tbody = table.tBodies[0];
				dean_addEvent(headrow[i],"click", function(e) {
					//
					//if (!pagerAll) pager.showForSort();
					//  
					if (this.className.search(/\bsorttable_sorted\b/) != -1) {
						// if we're already sorted by this column, just 
						// reverse the table, which is quicker
						sorttable.reverse(this.sorttable_tbody);
						this.className = this.className.replace('sorttable_sorted','sorttable_sorted_reverse');
						this.removeChild(document.getElementById('sorttable_sortfwdind'));
						sortrevind = document.createElement('span');
						sortrevind.id = "sorttable_sortrevind";
						sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
						this.appendChild(sortrevind);
						return;
					}
					if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
						// if we're already sorted by this column in reverse, just 
						// re-reverse the table, which is quicker
						sorttable.reverse(this.sorttable_tbody);
						this.className = this.className.replace('sorttable_sorted_reverse','sorttable_sorted');
						this.removeChild(document.getElementById('sorttable_sortrevind'));
						sortfwdind = document.createElement('span');
						sortfwdind.id = "sorttable_sortfwdind";
						sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
						this.appendChild(sortfwdind);
						return;
					}
					// remove sorttable_sorted classes
					theadrow = this.parentNode;
					forEach(theadrow.childNodes, function(cell) {
						if (cell.nodeType == 1) { // an element
							cell.className = cell.className.replace('sorttable_sorted_reverse','');
							cell.className = cell.className.replace('sorttable_sorted','');
						}
					});
	
					sortfwdind = document.getElementById('sorttable_sortfwdind');
					if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
					sortrevind = document.getElementById('sorttable_sortrevind');
					if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
				  
					this.className += ' sorttable_sorted';
					sortfwdind = document.createElement('span');
					sortfwdind.id = "sorttable_sortfwdind";
					sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
					this.appendChild(sortfwdind);
		
					// build an array to sort. This is a Schwartzian transform thing,
					// i.e., we "decorate" each row with the actual sort key,
					// sort based on the sort keys, and then put the rows back in order
					// which is a lot faster because you only do getInnerText once per row
					row_array = [];
					col = this.sorttable_columnindex;
					rows = this.sorttable_tbody.rows;
					for (var j=0; j<rows.length; j++) {
					  row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
					}
					/* If you want a stable sort, uncomment the following line */
					sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
					/* and comment out this one */
					//row_array.sort(this.sorttable_sortfunction);
					
					tb = this.sorttable_tbody;
					for (var j=0; j<row_array.length; j++) {
						if (j%2) { 
							if (row_array[j][1].className.search('invisible') != -1)
							row_array[j][1].className = 'trw invisible';
							else 
							row_array[j][1].className = 'trw';
						} else {
							if (row_array[j][1].className.search('invisible') != -1)
							row_array[j][1].className = 'trg invisible';
							else 
							row_array[j][1].className = 'trg';
						}
						tb.appendChild(row_array[j][1]);
					}
					delete row_array;
					//
					//if (!pagerAll) pager.showForSort();
					//  
				});
			}
		}
	},

  guessType: function(table, column) {
    // guess the type of a column based on its first non-blank row
    sortfn = sorttable.sort_alpha;
    for (var i=0; i<table.tBodies[0].rows.length; i++) {
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
      if (text != '') {
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
          return sorttable.sort_numeric;
        }
        // check for a date: dd/mm/yyyy or dd/mm/yy 
        // can have / or . or - as separator
        // can be mm/dd as well
        possdate = text.match(sorttable.DATE_RE)
        if (possdate) {
          // looks like a date
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if (first > 12) {
            // definitely dd/mm
            return sorttable.sort_ddmm;
          } else if (second > 12) {
            return sorttable.sort_mmdd;
          } else {
            // looks like a date, but we can't tell which, so assume
            // that it's dd/mm (English imperialism!) and keep looking
            sortfn = sorttable.sort_ddmm;
          }
        }
      }
    }
    return sortfn;
  },
 
  getInnerText: function(node) {
    // gets the text we want to use for sorting for a cell.
    // strips leading and trailing whitespace.
    // this is *not* a generic getInnerText function; it's special to sorttable.
    // for example, you can override the cell text with a customkey attribute.
    // it also gets .value for <input> fields.
    
    hasInputs = (typeof node.getElementsByTagName == 'function') &&
                 node.getElementsByTagName('input').length;
    
    if (node.getAttribute("sorttable_customkey") != null) {
      return node.getAttribute("sorttable_customkey");
    }
    else if (typeof node.textContent != 'undefined' && !hasInputs) {
      return node.textContent.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.innerText != 'undefined' && !hasInputs) {
      return node.innerText.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.text != 'undefined' && !hasInputs) {
      return node.text.replace(/^\s+|\s+$/g, '');
    }
    else {
      switch (node.nodeType) {
        case 3:
          if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
          return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
        case 11:
          var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += sorttable.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
          return '';
      }
    } return false;
  },
  
  reverse: function(tbody) {
    // reverse the rows in a tbody
    newrows = [];
    for (var i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
		if (i%2) { 
			if (newrows[i].className.search('invisible') != -1)
			newrows[i].className = 'trw invisible';
			else 
			newrows[i].className = 'trw';
		} else {
			if (newrows[i].className.search('invisible') != -1)
			newrows[i].className = 'trg invisible';
			else 
			newrows[i].className = 'trg';
		}
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
	//
	//if (!pagerAll) pager.showForSort();
	//  
  },
  
  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0].toLowerCase()==b[0].toLowerCase()) return 0;
    if (a[0].toLowerCase()<b[0].toLowerCase()) return -1;
    return 1;
  },
  sort_ddmm: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    try { y = mtch[3]; m = mtch[2]; d = mtch[1]; 
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
	} catch(err) {	} return false;
  },
  sort_mmdd: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  
  shaker_sort: function(list, comp_func) {
    // A stable sort function to allow multi-level sorting of data
    // see: http://en.wikipedia.org/wiki/Cocktail_sort
    // thanks to Joseph Nahmias
    var b = 0;
    var t = list.length - 1;
    var swap = true;

    while(swap) {
        swap = false;
        for(var i = b; i < t; ++i) {
            if ( comp_func(list[i], list[i+1]) > 0 ) {
                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
                swap = true;
            }
        } // for
        t--;

        if (!swap) break;

        for(var i = t; i > b; --i) {
            if ( comp_func(list[i], list[i-1]) < 0 ) {
                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
                swap = true;
            }
        } // for
        b++;

    } // while(swap)
  }  
}

/* ******************************************************************
   Supporting functions: bundled here to avoid depending on a library
   ****************************************************************** */

// Dean Edwards/Matthias Miller/John Resig

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", sorttable.init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            sorttable.init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            sorttable.init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = sorttable.init;

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini

// http://dean.edwards.name/weblog/2005/10/add-event/

function dean_addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
  this.cancelBubble = true;
}

// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
	forEach, version 1.0
	Copyright 2006, Dean Edwards
	License: http://www.opensource.org/licenses/mit-license.php
*/

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
	Array.forEach = function(array, block, context) {
		for (var i = 0; i < array.length; i++) {
			block.call(context, array[i], i, array);
		}
	};
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
	for (var key in object) {
		if (typeof this.prototype[key] == "undefined") {
			block.call(context, object[key], key, object);
		}
	}
};

// character enumeration
String.forEach = function(string, block, context) {
	Array.forEach(string.split(""), function(chr, index) {
		block.call(context, chr, index, string);
	});
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
	if (object) {
		var resolve = Object; // default
		if (object instanceof Function) {
			// functions have a "length" property
			resolve = Function;
		} else if (object.forEach instanceof Function) {
			// the object implements a custom forEach method so use that
			object.forEach(block, context);
			return;
		} else if (typeof object == "string") {
			// the object is a string
			resolve = String;
		} else if (typeof object.length == "number") {
			// the object is array-like
			resolve = Array;
		}
		resolve.forEach(object, block, context);
	}
};

//------------------
// WEBMAIL
//------------------

function initWebmail() {
	resizeWebmail();
}

function resizeWebmail() {
	var winH = getWindowHeight();
	var cellContent = document.getElementById('contentBody').offsetHeight;
	var cellHeader = document.getElementById('header').offsetHeight;
	var cellFooter = document.getElementById('footer').offsetHeight;
	var webmailHeight = winH-(cellHeader+cellFooter);
	document.getElementById('webmail').style.height = webmailHeight +'px';
	window.onresize = resizeWebmail;
}

// ROOT MAILTO TO ROUNDCUBE
function mailtoRoundCube() {
	var elems = document.getElementsByTagName('A');
	for (var i=0; i < elems.length; i++) { 
		if (elems[i].href.search(/mailto:/) != -1) {
			var email = elems[i].innerHTML;
			var formMail = elems[i].href.replace(/mailto:/,'http://foad.iedparis8.net/claroline/claroline/inc/webmail.php?_task=mail&_action=compose&_to=');
			elems[i].href = formMail;
			elems[i].innerHTML = email;
		} 
	}
}