// type de navigateur
var b = new getBrowserType();
function getBrowserType() {
	this.IE = false;
	this.NS4 = false;
	this.NS6 = false;
	this.id = "";

	if (document.all) {this.IE = true; this.id = "IE";}
	else if (document.getElementById) {this.NS6 = true; this.id = "NS6";}
	else if (document.layers) {this.NS4 = true; this.id = "NS4";}
}


centerId = function(id) { centerObj($(id)); }
centerObj = function(obj) {
	var wh = getInnerWindowHeight();
	var ww = getInnerWindowWidth();
	var oh = getHeight(obj);
	var ow = getWidth(obj);
	var left = Math.floor((wh-oh)/2)+getScrollY();
	var top = Math.floor((ww-ow)/2)+getScrollX();
	moveObjTo(obj, top, left);
}

var iv = new Array();
var ot = new Array();
changeInputFocus = function(id)
{
	if (!iv[id]) iv[id] = '+'+$F(id);
	if ('+'+$F(id) == iv[id])
		$(id).value = '';
	else if (trim($F(id)) == '')
		$(id).value = iv[id].substring(1);
}

// vérifie que le code d'un item est bien composé de caractères alphanumériques
checkCode = function(obj) {
	var code = $F(obj);
	if (code.length > 0)
	{
		var regexp = /[a-z0-9\ \-]/;
		$('erreur').value = 1;
	}
}


// validation d'une adresse email
checkEmail = function(email) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(email))
		return true;
	else
		return false;
}


// écriture de texte dans un élément
$W = function(ele, text) {
    if (typeof ele == 'string')
		$(ele).innerHTML = text;
	else
		ele.innerHTML = text;
}

// récupération du contenu d'un élément XML
getElementTextNS = function(local, parentElem, index) {
	var result = parentElem.getElementsByTagName(local)[index];
	if (result)
	{
        if (result.childNodes.length > 1)
            return URLDecode(result.childNodes[1].nodeValue);
        else if (result.firstChild)
			return URLDecode(result.firstChild.nodeValue);
        else
			return '';
	}
	else return 'n/a';
}


// récupération de la hauteur intérieure d'une fenêtre
getInnerWindowHeight = function() {
	var val;
	if (b.IE) val=document.body.clientHeight;
	else if (b.NS6 || b.NS4) val=window.innerHeight;
	return val;
}


// récupération de la largeur intérieure d'une fenêtre
getInnerWindowWidth = function() {
	var val;
	if (b.IE) val=document.body.clientWidth;
	else if (b.NS6 || b.NS4) val=window.innerWidth;
	return val;
}



// détermination de la position du scroll
// x = horizontal
// y = vertical
getScrollX = function() {
	var val = 0;
	if (b.IE) val=document.body.scrollLeft;
	else if (b.NS6 || b.NS4) val=window.pageXOffset;
	return val;
}
getScrollY = function() {
	var val = 0;
	if (b.IE) val=document.body.scrollTop;
	else if (b.NS6 || b.NS4) val=window.pageYOffset;
	return val;
}


// fonctions de récupération de la position et de la taille
getTop = function(obj) {
	var top = 0;
    do
    {
        top += obj.offsetTop;
        obj = obj.offsetParent;
    }
    while( obj != null );
    return top;
}


getLeft = function(obj) {
	var left = 0;
    do
    {
//    	alert(obj.tagName+' - '+obj.id+' - '+obj.offsetLeft);
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    while( obj != null );
    return left;
}


getHeight = function(obj) { return obj.offsetHeight; }

getWidth = function(obj) { return obj.offsetWidth; }


// affichage + masquage de l'élement (obj)
hide = function() {
	for (var i=0; i<arguments.length; i++)
		$(arguments[i]).style.display="none";
}
show = function() {
	for (var i=0; i<arguments.length; i++)
		$(arguments[i]).style.display="block";
}

// limitation du nombre de caractères des textarea
limitTextarea = function(obj, limit) {
	var text=$F(obj);
	if (text.length > limit) {
		alert('Limite dépassée. Le texte supplémentaire sera supprimé.');
		obj.value=text.substring(0,textareaLimit);
	}
}


// suppression des espaces de début de chaine
ltrim = function(str) {
	var re = /\s*((\S+\s*)*)/;
	return str.replace(re, "$1");
}


// positionnement d'une objet en x,y
moveIdTo = function(id, x,y) { moveObjTo($(id),x,y); }
moveObjTo = function(obj, x, y) {
	if (b.IE) { obj.style.pixelLeft=x; obj.style.pixelTop=y; }
	else if (b.NS4) { obj.left=x; obj.top=y; }
	else if (b.NS6) {
		x = x - $('body').offsetLeft;
		y = y - $('body').offsetTop;
		obj.style.left=x+"px"; obj.style.top=y+"px";
	}
}


// suppression des espaces de fin de chaine
rtrim = function(str) {
	var re = /((\s*\S+)*)\s*/;
	return str.replace(re, "$1");
}


function showError(msg) {
	if (!$('msg_erreur').style.display) {
		$W('msg_erreur', msg);
		show('box_erreur');
		centerId('box_erreur');
	}
	else
		moveIdTo('msg_erreur', getLeft(btn)+70, getTop(btn)+getHeight(btn));
}


// suppression des espaces de début et de fin de chaine
trim = function(str) {
	return ltrim(rtrim(str));
}


// décodage des éléments reçus en URL
URLDecode = function(encoded)
{
	var HEXCHARS = "0123456789ABCDEFabcdef";
	var plaintext = "";
	var i = 0;
	while (i < encoded.length) {
		var ch = encoded.charAt(i);
		if (ch == "+") {
			plaintext += " ";
			i++;
		} else if (ch == "%") {
			if (i < (encoded.length-2)
				&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
				&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};


// encodage des éléments envoyés en URL
URLEncode = function(plaintext) {
	return escape(plaintext);
}


// gestion des appels de scripts dynamiques (AJAX)
var Request = {
	send: function(url, callback, data) {
		var w= arguments.length == 4 ? arguments[4] : 1;
		if (window.XMLHttpRequest)
			req = new XMLHttpRequest;
		else if (window.ActiveXObject)
			req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			//prompt('', 'http://localhost'+url+"?"+data);
			req.onreadystatechange = function() {
				if (req.readyState == 4) {
					if (req.status < 400)
						callback(req);
					else { /*problème lors de la récupération*/ }
					hide('waitingDiv');
				} else if (w)
					show('waitingDiv');
			}
			req.open("GET", url+"?"+data, true);
			req.send(null);
		}
	}
}

// gestion des objets <select> pour modifier à la volée les listes de choix
var Select = {
	append: function(select, value, content) {
		var opt;
		opt = document.createElement("option");
		if (value) opt.value = value;
		opt.appendChild(document.createTextNode(content));
		select.appendChild(opt);
	},

	build: function(selectName) {
		function appendToSelect(select, value, content) {
			var opt;
			opt = document.createElement('option');
			opt.value = value;
			opt.appendChild(document.createTextNode(content));
			select.appendChild(opt);
		}
		function buildSelect(req) {
			var response = document.getElementById('response');
			var select = document.getElementById(selectName);
			var items = req.responseXML.getElementsByTagName('item');
			// traitement des éléments <item>
			for (var i=0; i<items.length; i++) {
				value = items[i].firstChild.nodeValue;
				appendToSelect(select, i, items[i].firstChild.nodeValue);
			}
			show(selectName);
		}
		Request.send('test.php5', buildSelect, 'hello=hello');
	},

	clear: function(select) {
		while (select.length > 0)
			select.remove(0);
	}
}




//===========================================================================================


Villes = new Object();


Villes.list = function(obj, ajoutCp, ajoutPays) {
	var select = $('select-'+obj.id);
	/* affichage dans un <select> */
	function listInSelect(req, data)
	{
		var items = req.responseXML.getElementsByTagName("ville");
		if (items.length > 0) {
			Select.clear(select);
			show(select);
			Select.append(select, '', '');
			for (var i=0; i<items.length; i++)
			{
				id = getElementTextNS("id", items[i], 0);
				nom = getElementTextNS("nom", items[i], 0);
				cp = getElementTextNS("cp", items[i], 0);
				pays = getElementTextNS("pays", items[i], 0);
				Select.append(select, id, nom+" ("+(ajoutPays ? pays+' - ' :'')+cp+")");
			}
		}
	}
	if ($F(obj).length >= 3) {
		Request.send('/outils/villes_liste.php5', listInSelect, 'q='+$F(obj)+'&cp='+ajoutCp);
	}
}

Villes.listCP = function(id) {
	var ville = $F('ville_id');
	function listInSelect(req,data)
	{
		var cps = req.responseText.split(',');
		if (cps.length == 1)
			$('cp').value = cps[0];
		else
		{
			var select = $('select-cp');
			Select.clear(select);
			show(select);
			hide('cp');
			for (var i=0; i<cps.length; i++)
				Select.append(select, cps[i], cps[i]);
			$(select.id).style.display = 'block';
		}
	}
	Request.send('/outils/codes_postaux_liste.php5', listInSelect, 'id='+ville);
}


Villes.update = function(obj) {
	var details = obj.options[obj.selectedIndex].innerHTML.split("(");
	var vil_id = obj.options[obj.selectedIndex].value;
	if ($('ville_id')) {
		$('ville_id').value=vil_id;
	}
	var pos = obj.id.lastIndexOf('+');
	var m = '';
	if (pos >= 0)
		m = obj.id.substring(pos, obj.id.length);
	$('ville'+m).value = trim(details[0]);
	pos = details[1].lastIndexOf(' - ');
	details = details[1].split(' - ');
	if ($('pays'+m)) {
		$('pays'+m).value = trim(details[0]);
		$('pays'+m).readonly = 'readonly';
	}
	if ($('geo_pays')) {
		var options = $('geo_pays').options;
		for (i=0; i<options.length; i++)
			if (options[i].value == trim(details[0]))
				$('geo_pays').options[i].selected = true;
	}
	if ($('cp'+m)) {
		$('cp'+m).value = trim(details[1]).substring(0,details[1].length-1);
		$('cp'+m).readonly = 'readonly';
	}
	if ($('salle'+m))
		$('salle'+m).readonly = '';
	if ($('vil_lat'))
		Villes.updateCoords($F(obj));
	obj.style.display = 'none';
}

Villes.updateCoords = function(id) {
	function updateCoords(req,data)
	{
		var coords = req.responseXML.getElementsByTagName('coords');
		var lat = getElementTextNS("lat", coords[0], 0);
		var lng = getElementTextNS("long", coords[0], 0);
		$('vil_lat').value = lat;
		$('vil_long').value = lng;
	}
	Request.send('/outils/ville_coords_get.php5', updateCoords, 'id='+id);
}


Salles = new Object();


Salles.checkAll = function() {
	var ville = $F('vil_idx');
	var code = $F('sal_code_new');
	var nom = $F('sal_nom');
	function statusCheck(req)
	{
		/**
		 * si <true>, affichage d'un message d'existence
		 */
		if (req.responseText == 1)
		{
			$('sal_nom').className = 'input_error';
			$('sal_nom_error').className = 'td_error';
			$W('sal_nom_error', 'Existe déjà');

			$('sal_code_new').className = 'input_error';
			$('sal_code_error').className = 'td_error';
			$W('sal_code_error', 'Existe déjà');

			$('ville').className = 'input_error';
			$('vil_nom_error').className = 'td_error';
			$W('vil_nom_error', 'Existe déjà');

			$('erreur').value = 1;
		}
		else
		{
			$('sal_nom').className = '';
			$('sal_nom_error').className = '';
			$W('sal_nom_error', '');

			$('sal_code_new').className = '';
			$('sal_code_error').className = '';
			$W('sal_code_error', '');

			$('ville').className = '';
			$('vil_nom_error').className = '';
			$W('vil_nom_error', '');

			$('erreur').value = 0;
		}
	}
	Request.send("/outils/check_salle.php5", statusCheck, "code="+code+"&nom="+nom+"&ville="+ville)
}


Salles.getCoords = function() {
	var address = $F('sal_adresse');
	var coords = [];
	if (address.length && address != $F('sal_adresse_old'))
		geocode(address, $F('cp'), $F('vil'), $F('pays'), 'sal_lat', 'sal_long');
}


Salles.list = function(obj, sel) {
	var pos = obj.id.lastIndexOf('+');
	var m = '';
	if (!sel)
		sel = 0;
	if (pos >= 0)
		m = obj.id.substring(pos, obj.id.length);
	var select = $('select-salle'+m);
	var ville = $F('ville'+m);
	//alert(ville);
	function listInSelect(req, data)
	{
		var items = req.responseXML.getElementsByTagName("salle");
		if (items.length > 0) {
			Select.clear(select); show(select);
			Select.append(select, '', '');
			for (var i=0; i<items.length; i++)
			{
				id = getElementTextNS("id", items[i], 0);
				nom = getElementTextNS("nom", items[i], 0);
				Select.append(select, id, nom);
			}
		}
	}
	if (ville || sel)
	{
		//prompt('', 'http://localhost/outils/salles_liste.php5?recherche='+$F(obj)+'&ville='+ville);
		Request.send('/outils/salles_liste.php5', listInSelect, 'recherche='+$F(obj)+'&ville='+ville+'&sel='+sel);
	}
	else
		showError();
}


Salles.checkDate = function(obj) {
	//alert('check');
	var date = $F('date');
	var salle = $F('salle');
	var ville = $F('ville');
	//alert('date = '+date);
	//alert('salle = '+salle);
	//alert('ville = '+ville);
	function statusCheck(req)
	{
		//alert(req.responseText);
		if (req.responseText == 1)
		{
			$W('salle_message', 'Déjà occupé');
			$("salle_message").className = 'td_error';
			$("salle").className = 'input_error';
			return 0;
		}
		else
		{
			$W("salle_message", '');
			$("salle_message").className = '';
			$("salle").className = '';
			return 1;
		}
	}
	if (date.length > 0 && salle.length > 0 && ville.length > 0)
	{
		//alert('request');
		//prompt('', "/outils/salle_date_check.php5?ville="+ville+"&salle="+salle+"&date="+date);
		Request.send("/outils/salle_date_check.php5", statusCheck, "ville="+ville+"&salle="+salle+"&date="+date);
	}
}

Salles.checkCode = function() {
	function getAnswer(req, data)
	{
		var result = req.responseText;
		if (result == 1)
			setCheckStatus('sal_code_new', 'good', Salles);
		else
			setCheckStatus('sal_code_new', 'bad', Salles);
	}
	var code = trim($F('sal_code_new'));
	var id = $F('sal_id');

	if (code.length > 0) {
		Request.send('/outils/salle_code_check.php5', getAnswer,
			'id='+id+'code='+URLEncode(code));
	} else {
		setCheckStatus('sal_code_new', 'clear', Salles);
	}
}

Salles.checkNom = function() {
	function getAnswer(req, data)
	{
		var result = req.responseText;
		if (result == 1)
		{
			setCheckStatus('sal_nom', 'good', Salles);
			setCheckStatus('vil_nom', 'good', Salles);
		}
		else
		{
			setCheckStatus('sal_nom', 'bad', Salles);
			setCheckStatus('vil_nom', 'bad', Salles);
		}
	}
	var id = $F('sal_id');
	var nom = trim($F('sal_nom'));
	var ville = trim($F('vil_nom'));

	if (nom.length > 0 && ville.length > 0) {
		Request.send('/outils/salle_nom_check.php5', getAnswer,
			'id='+id+'&nom='+URLEncode(nom)+'&ville='+URLEncode(ville));
	} else {
		setCheckStatus('sal_nom', 'clear', Salles);
		setCheckStatus('vil_nom', 'clear', Salles);
	}
}

Salles.update = function(obj) {
	var pos = obj.id.lastIndexOf('+');
	var m = '';
	if (pos >= 0)
		m = obj.id.substring(pos, obj.id.length);
	$('salle'+m).value = obj.options[obj.selectedIndex].innerHTML;
	var vil_id = obj.options[obj.selectedIndex].value;
	if ($('salle_id'+m)) {
		$('salle_id'+m).value=vil_id;
	}
	hide(obj.id);
}

Salles.defCode = function() {
	var nom = $F('sal_nom');
	var ville = $F('vil_nom');
	$('sal_code_new').value = ville + '|' + nom;
	Salles.checkCode();
}

Salles.setButtonStatus = function() {

}

//================
// Google Maps
//================
var map;

// creation des marqueurs
mapCreateMarker = function(point, txt)
{
	var marker = new GMarker(point, {draggable: true});
	GEvent.addListener(marker, "click", function()
	{
    	marker.openInfoWindowHtml(txt);
  	});
	GEvent.addListener(marker, "dragstart", function() {
		map.closeInfoWindow();
	});
	GEvent.addListener(marker, "dragend", function() {
		var npoint = marker.getPoint();
		var nlat = 60*npoint.lat();
		var nlng = 60*npoint.lng();
		marker.openInfoWindowHtml(txt+"<br/>"+(60*point.lat())+"<br/>"+nlat+"<br/>"+(60*point.lng())+"<br/>"+nlng);
	});
	return marker;
}

mapLoad = function()
{
	var type = '';
	if (arguments.length = 1)
		type = arguments[0];


	if (GBrowserIsCompatible())
	{
		if (type == 'NORMAL')
			map = new GMap2($("map"),{mapTypes:[G_NORMAL_MAP]});
		else
			map = new GMap2($("map"),{mapTypes:[G_HYBRID_MAP]});

		GEvent.addListener(map, "click", function(marker, point)
		{
			map.addOverlay(mapCreateMarker(point));
			$('sal_glat').value = point.lat()*60;
			$('sal_glong').value = point.lng()*60;
		});

		// ajout des contrôles
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	}
}

// positionnement de la carte
mapSetCenter = function(lat,lng,zoom)
{
	//alert(lat);
	if (map && lat && lng)
		map.setCenter(new GLatLng(parseFloat(lat/60), parseFloat(lng/60)), parseInt(zoom));
}

// ajout d'un marker pour la position de la salle
mapAddMarker = function(lat,lng,txt)
{
	var point = new GLatLng(parseFloat(lat)/60, parseFloat(lng)/60);
	map.addOverlay(mapCreateMarker(point,txt));
}

offCenter = function(txt)
{
	var lat, lng;
	if ($('sal_glat') && $F('sal_glat')) lat = $F('sal_glat');
	else if($('sal_lat24') && $F('sal_lat24')) lat = $F('sal_lat24');
	else if($('vil_lat') && $F('vil_lat')) lat = $F('vil_lat');
	else lat = 48.3416*60;
	if ($('sal_glong') && $F('sal_glong')) lng = $F('sal_glong');
	else if($('sal_long24') && $F('sal_long24')) lng = $F('sal_long24');
	else if($('vil_long') && $F('vil_long')) lng = $F('vil_long');
	else lng = 9.84375*60;
	var zoom = ($('sal_glat') && $F('sal_glat')) || ($('sal_lat24') && $F('sal_lat24')) ? 17 : $F('zoom');
	if (lat && lng)
	{
		mapSetCenter(lat,lng,zoom);
		mapAddMarker(lat,lng,txt);
	}
	else
		mapSetCenter($F('vil_lat'),$F('vil_lng'),$F('zoom'));
}

function initMap24(){
	map24 = Map24.Webservices.getMap24Application({
		AppKey: "FJXee812ecad448a65aead97733243c0X13",
		MapArea: document.getElementById( "map24" ),
		MapWidth: 480,
		MapHeight: 300
	});
}


geocode = function (adresse, cp, ville, pays_code, lat_id, long_id) {
	switch(pays_code)
	{
		case 'BE': pays = 'Belgique'; break;
		case 'FR': pays = 'France'; break;
		case 'LU': pays = 'Luxembourg'; break;
		case 'CH': pays = 'Suisse'; break;
	}
	prompt('', adresse+', '+cp+' '+ville+', '+pays);
	map24.Webservices.sendRequest(
		new Map24.Webservices.Request.MapSearchFree(map24, {
			SearchText: adresse+', '+cp+' '+ville+', '+pays,
			MaxNoOfAlternatives: 3
		})
	);

	map24.onMapSearchFree = function( event ){
		var responses = event.Alternatives.length;
		var coords = [];
		result = event.Alternatives[0];
		coords['lng'] = result.Coordinate.Longitude;
		coords['lat'] = result.Coordinate.Latitude;
		$(lat_id).value = coords['lat'];
		$(long_id).value = coords['lng'];
	}
}


/** initialisation du statut de la saisie */
var done = new Array();


setCheckStatus = function(inputid, status, button)
{
	//alert(inputid);
	var indicator = $(inputid+'-status');
	if (indicator) {
		if (status == "good") {
			//alert('good');
			indicator.style.backgroundImage = "url('/img/good.gif')";
			done[inputid] = true;
		}
		else if (status == "bad") {
			//alert('bad');
			indicator.style.backgroundImage = "url('/img/bad.gif')";
			done[inputid] = false;
		}
		else {
			indicator.style.backgroundImage = 'none';
		}
	}
	button.setButtonStatus();
}


var tabliste = new Array();

function tabDisplay(id)
{
	var tab = 'tabpref'+id;
	var li = 'lipref'+id;
	$(tab).style.display = 'block';
	$(li).className = 'selected';
	for (i=1; i<=5; i++)
	{
		if (i != id)
		{
			$('tabpref'+i).style.display = 'none';
			$('lipref'+i).className = 'none';
		}
	}
}


clearUpdate = function(id) {
	$(id).style.display = 'none';
}

agdFocus = function() {
	for (var i=0; i<arguments.length; i++)
		if ($('tr_'+arguments[i]+'_1'))
			for (var j=1; j<=2; j++)
				$('tr_'+arguments[i]+'_'+j).className='over';
}
agdBlur = function() {
	for (var i=0; i<arguments.length; i++)
		if ($('tr_'+arguments[i]+'_1'))
			for (var j=1; j<=2; j++)
				$('tr_'+arguments[i]+'_'+j).className='';
}
