//////////////////////////////////////////////////////////////
//    
// Miscellaneous JavaScript functions - 2006-09-20
//
//	© Enki Technologies
//	info@enki-tech.com
//
//////////////////////////////////////////////////////////////


/////////////////////
// BrowserCheck
/////////////////////
function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.v = parseInt(navigator.appVersion)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v==5)
	this.ns6 = (this.b=="ns" && this.v==6)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (navigator.userAgent.indexOf('MSIE 4')>0)
	this.ie5 = (navigator.userAgent.indexOf('MSIE 5')>0)
	if (this.ie5) this.v = 5
	this.ie6 = (navigator.userAgent.indexOf('MSIE 6')>0)
	if (this.ie6) this.v = 6
	this.min = (this.ns||this.ie)
	this.mac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
}


/////////////////////
// getObject
/////////////////////
function getObject(objectId) {
	var obj;
	if (document.getElementById) {
		// DOM
		obj = document.getElementById(objectId);
	}
	else if (document.all) {
		// ie4
		obj = eval("document.all." + objectId);
	}
	else {
		// nn4
		obj = getObjectNN4(document,objectId);
	}
	return obj;
}
function getObjectNN4(container,objectId)
{
	var x = container.layers;
	var obj;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == objectId) { obj = x[i]; }
		else {
			if (x[i].layers.length) {
				var tmp = getObjectNN4(x[i],objectId);
				if (tmp) { obj = tmp; }
			}
		}
	}
	return obj;
}



/////////////////////
// hideObject
/////////////////////
function hideObject(obj) {
	if (obj) {
		if (document.getElementById) {
			// DOM
			obj.style.visibility="hidden";
			obj.style.display="none";
		}
		else if (document.all) {
			// ie4
			obj.style.visibility="hidden";
			obj.style.display="none";
		}
		else {
			// nn4
			obj.visibility="hide";
		}
	}
}


/////////////////////
// showObject
/////////////////////
function showObject(obj) {
	if (obj) {
		if (document.getElementById) {
			// DOM
			obj.style.visibility="visible";
			obj.style.display="block";
		}
		else if (document.all) {
			// ie4
			obj.style.visibility="visible";
			obj.style.display="block";
		}
		else {
			// nn4
			obj.visibility="show";
		}
	}
}

/**
	Fonction qui determine si la rubrique du menu gauche doit etre cache au prochain
	chargement. Pour cela, elle écrit les valeurs dans un formulaire caché qui est transmit
	à PHP
	@deprecated
*/

function display(idField, page, nbCat,prefix){
	var form = document.menu_g;
	var input = form[prefix+idField];
	
	for (i = 1; i <= nbCat; i++){
		form[prefix+i].value = 'none';
	}
	
	if (input.value == 'block'){
		input.value = 'none';
	}
	else{
		input.value = 'block';
	}
	form.action = page;
	form.submit();
}

/**
	Fonction liée à display. Elle permet d'acceder à une page en conservant les données du formulaire caché.
	@deprecated
*/
function submitForm(page){
	var form = document.menu_g;
	form.action = page;
	form.submit();
}


/**
* Enregistre dans un formulaire caché la catégorie par défaut à déplier dans le menu de gauche.
* Cette méthode est appellée à partir du menu de navigation en haut de page.
* @param id est l'identifiant de la catégorie qui doit être ouverte par défaut
@deprecated
* @param pageCible est la page à charger suite au clic sur le menu haut
* @return void
*/
function storeCategoryIdentifierToOpenFirst(id, pageCible){
	var form = document.menu_haut;
	if (!form) return;
	form.action = pageCible;
	form["first_open"].value = id;
	form.submit();
}

/**
* Retrieves an array containing all the children html element
* A children is retrieved by adding to an id another level delimited with a new underscore and a number that identifies the child position
* example : parent_0_0 is the first child of parent_0
* @param string id the id of the html element which children have to be retrieved
* @return htmlElement[]  without the current one
*/
function getChildrenAsDomElementFromId(id){
	var childrenPrefix = id+"_";
	var i = 0;
	var el = document.getElementById(childrenPrefix+i);
	var children = new Array();
	while (el != null && el != undefined){
		children.push(el);
		i++;
		el = document.getElementById(childrenPrefix+i);
	}
	return children;
}

/**
* Retrieves an array containing all the brothers html element
* Brothers are retrieved by cycling through the current level simply by increasing the number at the end of 'id'
* example : parent_0_1 is one of the brothers of parent_0_0
* @param string id the id of the html element which brothers have to be retrieved
* @return htmlElement[]  without the current one
*/
function getBrothersAsDomElementFromId(id){
	var brotherPrefix = id.substr(0, id.lastIndexOf("_") + 1);
	var i = 0;
	var el = document.getElementById(brotherPrefix+i);
	var brothers = new Array();
	while (el != null && el != undefined){
		var currentId = brotherPrefix+i;
		if (currentId == id) { i++; continue; }
		brothers.push(el);
		i++;
		el = document.getElementById(brotherPrefix+i);
	}
	return brothers;
}

/**
* Retrieves the parent element
* @param string id the id of the html element which parent has to be retrieved
* @return htmlElement parent
*/
function getParentAsDomElementFromId(id){
	var parentName = id.substr(0, id.lastIndexOf("_"));
	var parent = document.getElementById(parentName);
	if (parent == null || parent == undefined) throw new Error("Unknown parent");
	return parent;
}

/**
* Unfold the menu category. When a catgory has to be unfold, it searches for its parent recursively to unfold it too. The recursion stops
* whenever the parent doesnt exist.
* example: trying to unfold cat_0_0 will result in unfolding cat_0 and cat if both of them belongs to the DOM
* @param string id the id of the element to be unfolded
* @return void
*/
function openMenuCategory(id){
	var parent = null;
	try {
		parent = getParentAsDomElementFromId(id);
		tryFold(id);
		openMenuCategory(parent.id);
	}
	catch (e){
		// Id hasnt got any parent
		tryFold(id);
	}
}

/**
* Tells the web browser to load actionPage from server and transmits to it the category to open. Besides that, the web server prints out a little javascript snippet which will 
* tells the web browser to open this category.
* @param string actionPage the page to load
* @param cnameToOpen the category that should be open when server sends back the page
*/
function postAndDisplay(actionPage, cnameToOpen){
	var form = document.getElementById("menu");
	document.getElementById("cname_toshow").value = cnameToOpen;
	form.action = actionPage;
	form.submit();
}


/**
* Cache ou montre l'element designé par id en fonction de son état. Chaque élement possédant le même prefixe devant le _ sera automatiquement caché
* Ainsi, un seul élement d'une meme famille est visible
* @param id est une chaine forcément suffixé de _x ou x appartient à [0...n]
* @param string[] ids est une tableau des prefixe des ids à fermer
*/
function tryFold(id, ids){
	var el = document.getElementById(id);
	var identifier = id.substr(0, id.indexOf("_"));
	var i = 0;
	
	if (ids != null){
		var otherElementsToClose = ids.length;
		for (j = 0; j < otherElementsToClose; j++){
			var k = 0;
			while (true){
				var elementToClose = document.getElementById(ids[j]+"_"+k);
				k++;
				if (elementToClose == null) break;
				elementToClose.style.display = 'none';
			}
		}
	}
	while (true){
		var myid = identifier+"_"+i;
		if (myid == id) {
			i++;
			continue;
		}
		var elementToClose = document.getElementById(myid);
		if (elementToClose == null) break;
		elementToClose.style.display = 'none';
		i++;
	}
	if (!el) return;
	var displayStyle = el.style.display;
	el.style.display = (displayStyle == 'block' ? 'none' : 'block');
}


/////////////////////
// getObjectPositionX
/////////////////////
function getObjectPositionX(obj) {
	var is = new BrowserCheck();
	if (is.ns && is.v<5) {
		return obj.x;
	}
	else {
		x = 0;
		while (obj && obj.tagName != 'BODY') {
			x += obj.offsetLeft;
			obj = obj.offsetParent;
		}
		return x;
	}
}


/////////////////////
// getObjectPositionY
/////////////////////
function getObjectPositionY(obj) {
	var is = new BrowserCheck();
	if (is.ns && is.v<5) {
		return obj.y;
	}       
	else {
		y = 0;
		while (obj && obj.tagName != 'BODY') {
			y += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return y;
	}
}


/////////////////////
// setObjectPositionX
/////////////////////
function setObjectPositionX(obj,X) {
	if (document.layers) {
		// nn
		obj.left = X;
	}
	else {
		// ie
		obj.style.left = X;
	}
}

/////////////////////
// setObjectPositionY
/////////////////////
function setObjectPositionY(obj,Y) {
	if (document.layers) {
		// nn
		obj.top = Y;
	}
	else {
		// ie
		obj.style.top = Y;
	}
}


/////////////////////
// getParentObject
/////////////////////
function getParentObject(child) {
	var is = new BrowserCheck();
	var parent = document;
	if (child == window) parent = null;
	else if (child == document) parent = window;
	else if (is.ns4) {
		if (child.parentLayer) {
			if (child.parentLayer != window) parent = child.parentLayer;
		}
	}
	else {
		if (child.parentNode) parent = child.parentNode;
		else if (child.parentElement) parent = child.parentElement;
	}
	return parent;
}


/////////////////////
// containsObject
/////////////////////
function containsObject(container,containee) {
	if (container.contains) {
		return container.contains(containee);
	}
	else {
		while (containee != null) {
			if (container == containee) { return true; }
			containee = getParentObject(containee);
		}
		return false;
	}
}


/////////////////////
// FormFunctions
/////////////////////

function isValidEmail(s) {
	if (isEmpty(s)) { return false; }
	//return (s.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
	return (s.search(/^[\w-]+(\.[\w-]+)*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}

/**
* Retrieves a list of separators allowed for a given date format
* @return string[] array containing the separators that can be used to format a date
*/
function getAllowedDateSeparator(){
	return new Array("\/", ":", "\\."); 
}

/**
* Checks if mydate given as first parameter is a valid date format
* @param mydate the date to check
* @param unused is here for backward compatibility but useless considering the function body
* @return boolean true if date is valid, false otherwise
*/
function isValidDate(mydate, unused){
	var allowedDateFormats = getAllowedDateSeparator();
	var nbSeparators = allowedDateFormats.length;
	if (nbSeparators == 0) return false;
	for (i = 0; i < nbSeparators; i++){
		var separator = allowedDateFormats[i];
		var reg = new RegExp('^[0-9]{1,2}'+separator+'[0-9]{1,2}'+separator+'[0-9]{1,4}$');
		var res = mydate.match(reg);
		if (!res) continue;
		var motif = new RegExp(separator);
		var splittedDate = mydate.split(motif);
		var month = splittedDate[1] - 1;
		var date = new Date(splittedDate[2], month, splittedDate[0]);
		return date.getDate() == splittedDate[0] && (date.getMonth() == month) && date.getFullYear() == splittedDate[2];
	}
	return false;
}



function isEmpty(s) {
	if (s == null || s == "") {
		return true;
	}
	return false;
}
function isInteger(s) {
	i = stringToInteger(s);
	return (i == s);
}
function stringToInteger(s) {
	if (s == null || s == "") { i = 0; }
	else { i = parseInt(s); }
	if (isNaN(i)) { i = 0; }
	return i;
}
function isFloat(s) {
	i = stringToFloat(s);
	return (i == s);
}
function stringToFloat(s) {
	if (s == null || s == "") { i = 0; }
	else { i = parseFloat(s); }
	if (isNaN(i)) { i = 0; }
	return i;
}
function radioIsSelected(r) {
	var radioChoice = false;
	if (r) {
		for (counter = 0; counter < r.length; counter++) {
			if (r[counter].checked) {
				radioChoice = true;
			}
		}
	}
	return radioChoice;
}
function setSelectValue(selectObject, optionValue) {
	for (i = 0; i < selectObject.length; i++) {
		if (selectObject[i].value == optionValue) {
			selectObject.selectedIndex = i;
			return;
		}
	}
}



/////////////////////
// Preload Images
/////////////////////

var preloadImagesArray = new Array();
function preloadImages() {
	for (var i=0; i <preloadImages.arguments.length;i++){
		var index = preloadImagesArray.length;
		preloadImagesArray[index]=new Image();
		preloadImagesArray[index].src=preloadImages.arguments[i];
	}
}


/////////////////////
// String functions
/////////////////////

function trim(TRIM_VALUE) {
	if(TRIM_VALUE.length < 1){ return ""; }
	TRIM_VALUE = rTrim(TRIM_VALUE);
	TRIM_VALUE = lTrim(TRIM_VALUE);
	if (TRIM_VALUE==""){ return ""; }
	else { return TRIM_VALUE; }
}

function rTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if (v_length < 0) { return""; }
	var iTemp = v_length -1;
	while (iTemp > -1) {
		if (VALUE.charAt(iTemp) != w_space) {
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}
	return strTemp;
}

function lTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	if (v_length < 1) { return ""; }
	var strTemp = "";
	var iTemp = 0;
	while (iTemp < v_length) {
		if (VALUE.charAt(iTemp) != w_space) {
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	return strTemp;
}



/////////////////////
// String functions
/////////////////////
function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} 
	else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} 
	else {
		alert("Handler could not be attached");
	}
}

function removeEvent(obj, evType, fn, useCapture) {
	if (obj.removeEventListener) {
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	}
	else if (obj.detachEvent) {
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	}
	else {
		alert("Handler could not be removed");
	}
} 


/////////////////////
// safeOnLoad
/////////////////////
var safeOnLoadArray = new Array();
function safeAddOnload(f) {
	var is = new BrowserCheck();
	if (is.mac && is.ie4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = safeOnload;
		safeOnLoadArray[safeOnLoadArray.length] = f;
	}
	else if  (window.onload)
	{
		if (window.onload != safeOnload)
		{
			safeOnLoadArray[0] = window.onload;
			window.onload = safeOnload;
		}		
		safeOnLoadArray[safeOnLoadArray.length] = f;
	}
	else
		window.onload = f;
}
function safeOnload() {
	for (var i=0;i<safeOnLoadArray.length;i++)
		safeOnLoadArray[i]();
}


