/*
* 	Author : Planet Bourgogne
*	Version : 1.10
*	Changelog : 
*		04/09/2008 : Passage en version 1.0
*		08/09/2008 : actions->setY + actions->setX : Amélioration de la fonction
*		09/09/2008 : action  : rajout de hidden="auto"
*		09/09/2008 : action : correction d un bug dans les balises styles (prob du retour a la ligne)
*		15/09/2008 : chargement : affiche un petit icone de chargelent en bas a droite pendant un appel ajax
*		15/09/2008 : styleCss : block Try Catch pour IE
*		18/09/2008 : Gestion du voile   voile="on"/voile="off"
*		02/10/2008 : Div de chargement plus beau
*		28/10/2008 : Rajout du type innerHTMLAdd
*		28/10/2008 : Rajout d un test pour destroy_element()
*		28/10/2008 : Rajout de l execution de script JS avant l execution des actions
*		28/10/2008 : /charte/ajax_loader au lieu de ../charte/ajax_loader.js
*		30/03/2009 : Completion rajout du onclick
*		31/03/2009 : Gestion de la configuration + Completion vide (empty)
*		05/05/2009 : AMelioration destroy_element ( is_string / is_object) 
*		05/05/2009 : variable de conf de loading 
*		05/05/2009 : Try catch sur l eval du javascript  (==> à ameliorer)
*		23/06/2009 : Utilisation de Prototype OU de jQuery
*		23/06/2009 : Framework non obligatoire
*		27/07/2009 : Correction envoi requete Ajax : req.setRequestHeader
*/

/*
* Configuration	
*/
img_fermer = '/images/x.gif';
img_printer = '/images/printer.png';
img_ajax_loader = '/images/ajax_loader.gif';
loading = 0; // 0 ou 1 : afficher ou non le petit picto en bas de chargement
/*
* Fin Configuration	
*/

/*
Permet d integrer directement les fichiers JS necessaires
function include(fileName)
{  
	document.write("<script type='text/javascript' src='"+fileName+"'></script>" );
}  
include("/javascripts/scriptaculous/prototype.js" );  
include("/javascripts/scriptaculous/scriptaculous.js" );  
*/

function executeAjax(url, pars)
{
	if(framework_used)
	{
		if(loading) { affiche_chargement(); }
		if(framework_used == 'Prototype') 
		{
			var ajax = new Ajax.Updater(
					'', url , { parameters: pars, method:'post', onComplete:
					function(requester) { executeXML(requester); if(loading) {cache_chargement();} }});
		}
		if(framework_used == 'jQuery') 
		{
			$.ajax({ type: 'POST', url: url, data: pars, success: function(msg){executeXML(msg); if(loading){cache_chargement();}}});
		}
	} else {
		if (window.XMLHttpRequest) {
 			req = new XMLHttpRequest();
		} 
		else if (window.ActiveXObject)  {
			try { req = new ActiveXObject("Msxml2.XMLHTTP");} catch (e){try { req = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}}
        }
		req.onreadystatechange = function()
		{ 
			if(loading) { affiche_chargement(); }
			if(req.readyState == 4)
			{
				if(req.status == 200){executeXML(req); }	
				else	{alert(req.status + " " + req.statusText);}	
				if(loading) {cache_chargement();}
			} 
		}; 
		req.open('POST', url, true); 
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", pars.length);
		req.send(pars); 
	}
}



function executeXML(requester)
{
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Recupèration du flux XML											//
	//////////////////////////////////////////////////////////////////////////////////////////
	try //Internet Explorer
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		if(framework_used == 'Prototype' || framework_used == null ){
			xmlDoc.loadXML(requester.responseText);
		}
		if(framework_used == 'jQuery'){
			xmlDoc = requester;
		}
	}
	catch(e)
	{
		try //Firefox, Mozilla, Opera, etc.
		{
			if(framework_used == 'Prototype' || framework_used == null){
				xmlDoc = requester.responseXML;
			}
			if(framework_used == 'jQuery'){
				xmlDoc = requester;
			}
		}
		catch(e) {alert(e.message)}
	}
	
	if(xmlDoc.firstChild.nodeName == 'parsererror' || xmlDoc.firstChild.nodeName != 'actions' )
	{
		var msg = 'Erreur de ParserXml. XML non conforme.\n\n';
		msg += 'Description de l\'erreur : \n\n';
		msg += xmlDoc.firstChild.firstChild.nodeValue+'\n\n';
		msg += 'Contenu de la reponse : \n\n';
		msg += requester.responseText+'\n\n';
		alert(msg);
		return false;
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Gestion du mode DEBUG												//
	//////////////////////////////////////////////////////////////////////////////////////////
	var debug = xmlDoc.getElementsByTagName('debug');
	if(debug.length > 0)
	{
		if(!document.getElementById('div_debug'))
		{
			mondiv = document.createElement('div');
			mondiv.innerHTML = requester.responseText;
			mondiv.setAttribute("id","div_debug");
			
			mondiv.style.float = 'left';
			mondiv.style.position = 'absolute';
			mondiv.style.display = 'block';
			mondiv.style.background = 'black';
			mondiv.style.color = 'white';
			mondiv.style.border = '2px solid red';
			mondiv.style.width = '300px';
			mondiv.style.height = '500px';
			mondiv.style.top = '20px';
			mondiv.style.left = '20px';
			
			mondiv.setAttribute("onclick","document.getElementById('div_debug').style.display = 'none';");
			
			document.getElementsByTagName('body')[0].appendChild(mondiv);
		}
		else
		{
			mondiv = document.getElementById('div_debug');
			mondiv.innerHTML = requester.responseText;
			mondiv.style.display = 'block';
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Script JS			BEGIN											//
	//////////////////////////////////////////////////////////////////////////////////////////
	var scrs = xmlDoc.getElementsByTagName('script');
	if (scrs.length >= 1)
	{
		for (var i = 0; i < scrs.length; i++)
		{
			try
			{
				node = scrs.item(i);
				if ((node.getAttribute('type') != null && node.getAttribute('type') == 'begin'))
				{
					var value = '' + node.getElementsByTagName('content').item(0).firstChild.data;
					try { 
						eval(value);
					} catch (err) {
						//alert(err.name);
					}
				}
			}
			catch (e)
			{
				throw e;
			}
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Actions																//
	//////////////////////////////////////////////////////////////////////////////////////////
	var actions = xmlDoc.getElementsByTagName('action');
	for (var i = 0; i < actions.length; i++)
	{
		node = actions.item(i);
		var src = document.getElementById(node.getAttribute('blockId'));
		var src_id = node.getAttribute('blockId');
		if (node.getAttribute('frame') != null && node.getAttribute('frame') != "")
		{
			if(node.getAttribute('frame') == 'parent')
			{
				src = window.parent.document.getElementById(node.getAttribute('blockId'));
			}
			else
			{
				src = window.parent.frames[node.getAttribute('frame')].getElementById(node.getAttribute('blockId'));
			}
		}
		
		if (!src)
		{
			src = document.createElement('div');
			src.id = src_id;
			document.getElementsByTagName('body')[0].appendChild(src);
			src.style.zIndex = '500';
		}
		if (src)
		{
			/////////		VOILE				////////
			if ((node.getAttribute('voile') != null && node.getAttribute('voile') == "on"))
			{
				elt_div_voile = document.createElement('div');
				elt_div_voile.id = 'div_voile';
				document.getElementsByTagName('body')[0].appendChild(elt_div_voile);
				elt_div_voile.style.zIndex = '499';
				elt_div_voile.setAttribute('style','top:0;left:0;margin:0;padding:0;width:100%;height:100%;position:absolute;background:white;-moz-opacity:0.5;opacity:0.5;filter:alpha(opacity=50);');
			}
			if ((node.getAttribute('voile') != null && node.getAttribute('voile') == "off"))
			{
				destroy_element('div_voile');
			}
			
			
			/////////		CHANGE LE STYLE			//////
			if ( node.getElementsByTagName('styles').length > 0  )
			{
				var chaine_style = '';
				var styles = node.getElementsByTagName('styles');
				var elt = styles.item(0).firstChild;
				while ( elt != null )
				{
					if(elt.nodeName != '#text')//Corrige un bug du au retour à la ligne
					{
						chaine_style += elt.nodeName+':'+elt.firstChild.nodeValue+';';
						try {
							eval('src.style.'+elt.nodeName+' = "'+elt.firstChild.nodeValue+'";');
						}
						catch(err) 
						{
							//alert(err.description);
							//alert(elt.nodeName+':'+elt.firstChild.nodeValue+';');
							//src.setAttribute('style',elt.nodeName+':'+elt.firstChild.nodeValue+';');
							src.style.cssText  = elt.nodeName+':'+elt.firstChild.nodeValue+';';
						}
					}
					elt = elt.nextSibling;
				}
			}

			///////			INNERHTML		//////
			if ((node.getAttribute('type') != null && node.getAttribute('type') == "innerHTML"))
			{
				var value = ' ' + node.getElementsByTagName('content').item(0).firstChild.data;
				src.innerHTML = value;
			}
			///////			INNERHTMLADD		//////
			if ((node.getAttribute('type') != null && node.getAttribute('type') == "innerHTMLAdd"))
			{
				var value = ' ' + node.getElementsByTagName('content').item(0).firstChild.data;
				src.innerHTML += value;
			}
			///////			CHANGE LA CLASS CSS		/////
			if (node.getAttribute('cssBlock') != null && node.getAttribute('cssBlock') != "")
			{
				src.className = node.getAttribute('cssBlock');
			}
			////////		CHANGE LA POSITION Y	///////
			if (node.getAttribute('setY') != null && node.getAttribute('setY') != "")
			{
				var positionY = 0;
				positionY = getY(node.getAttribute('setY'));
				var parent = window.document.getElementById(node.getAttribute('setY')).offsetParent;
			 	while (parent) 
			 	{
				 	positionY = parent.offsetTop + positionY;
				 	parent = parent.offsetParent;
			 	}
				setY(src_id,positionY);
			}
			if (node.getAttribute('plusY') != null && node.getAttribute('plusY') != "")
			{
				setY(src_id, getY(src_id) + parseInt(node.getAttribute('plusY')) );
			}
			////////		CHANGE LA POSITION X	///////
			if (node.getAttribute('setX') != null && node.getAttribute('setX') != "")
			{
				var positionX = 0;
				positionX = getX(node.getAttribute('setX'));
				var parent = window.document.getElementById(node.getAttribute('setX')).offsetParent;
			 	while (parent) 
			 	{
				 	positionX = parent.offsetLeft + positionX;
				 	parent = parent.offsetParent;
			 	}
				setX(src_id,positionX);
				
			}
			if (node.getAttribute('plusX') != null && node.getAttribute('plusX') != "")
			{
				setX(src_id, getX(src_id) + parseInt(node.getAttribute('plusX')) );
			}
			
			/////////		STYLE DISPLAY			//////
			if ((node.getAttribute('display') != null) && (node.getAttribute('display') != ""))
			{
				src.style.display = node.getAttribute('display');
			}
			
			var onmouseover = '';
			var onmouseout = '';
			
			/////////		PRINT			//////
			if ((node.getAttribute('print') != null) && (node.getAttribute('print') == 'print'))
			{
				var name_div_print = 'print_div';
				src.innerHTML = '<div id="'+name_div_print+'" style="position:absolute;top:0px;right:0px;border:none;display:none;z-index:500;padding:0px;margin:2px 15px;"><img src="'+img_printer+'" alt="Imprimer" style="cursor:pointer;" onclick="javascript:window.print();"/></div>' + src.innerHTML;
				onmouseover += "document.getElementById('"+name_div_print+"').style.display='block';";
				onmouseout += "document.getElementById('"+name_div_print+"').style.display='none';";
			}
			/////////		CLOSE			//////
			if ((node.getAttribute('close') != null) && (node.getAttribute('close') == 'auto'))
			{
				//Pour virer le voile
				destroy_voile = '';
				if ((node.getAttribute('voile') != null && node.getAttribute('voile') == "on"))
				{
					destroy_voile = 'destroy_element(\'div_voile\');';
				}
				
				var name_div_close = 'close_div';
				src.innerHTML = '<div id="'+name_div_close+'" style="position:absolute;top:0px;right:0px;border:none;display:none;z-index:500;padding:0px;margin:2px;"><img src="'+img_fermer+'" alt="Fermer" style="cursor:pointer;" onclick="javascript:destroy_element(\''+src_id+'\');'+destroy_voile+'"/></div>' + src.innerHTML;
				onmouseover += "document.getElementById('"+name_div_close+"').style.display='block';";
				onmouseout += "document.getElementById('"+name_div_close+"').style.display='none';";
			}
			/////////		HIDDEN			//////
			if ((node.getAttribute('hidden') != null) && (node.getAttribute('hidden') == 'auto'))
			{
				var name_div_close = 'close_div';
				src.innerHTML = '<div id="'+name_div_close+'" style="position:absolute;top:0px;right:0px;border:none;display:none;z-index:500;padding:0px;margin:2px;"><img src="'+img_fermer+'" alt="Fermer" style="cursor:pointer;" onclick="javascript:document.getElementById(\''+src_id+'\').style.display=\'none\';"/></div>' + src.innerHTML;
				onmouseover += "document.getElementById('"+name_div_close+"').style.display='block';";
				onmouseout += "document.getElementById('"+name_div_close+"').style.display='none';";
			}
			
			//	POUR FF setAttribute et POUR IE eval
			if(onmouseover != ''){src.setAttribute("onmouseover","javascript:"+onmouseover);eval ('src.onmouseover = function() { '+onmouseover+'; };');}
			if(onmouseout != ''){src.setAttribute("onmouseout","javascript:"+onmouseout);eval ('src.onmouseout = function() { '+onmouseout+'; };');}
			
			
			
			
			//////// 		TYPE SELECT			//////////
			if ((node.getAttribute('type') != null && node.getAttribute('type') == "select"))
			{
				src.options.length = 0;
				//src.options[src.options.length] = new Option('',0); //==> Permet de mettre le premier element a vide
				var options = node.getElementsByTagName('option');
				for (var o = 0; o < options.length; o++)
				{
					option = options.item(o);
					var valeur = option.getAttribute('value');
					var text = option.firstChild.data;
					src.options[src.options.length] = new Option(text,valeur);
					if(option.getAttribute('selected'))
					{
						src.selectedIndex = src.options.length - 1;
					}
				}
			}
		}
		
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Message																//
	//////////////////////////////////////////////////////////////////////////////////////////
	var messages = xmlDoc.getElementsByTagName('message');
	for (var i = 0; i < messages.length; i++)
	{
		node = messages.item(i);
		var src = document.getElementById(node.getAttribute('blockId'));
		if (src)
		{
			//	Nouvel element cree
			createId = 'div_message';
			if (node.getAttribute('createId') != null && node.getAttribute('createId') != "")
			{
				createId = node.getAttribute('createId');
			}
			//Le temps que va rester afficher le block
			time = 0;
			if (node.getAttribute('time') != null && node.getAttribute('time') != "")
			{
				time = node.getAttribute('time');
			}
			//On supprime le bloc si il est deja cree
			if(document.getElementById(createId)){destroy_element(createId);}
			
			mondiv = document.createElement('div');
			mondiv.innerHTML = '';
			//si le temps est a 0 alors on propose une croix pour fermer le block
			if(time==0)
			{
				mondiv.innerHTML += '<img src="'+img_fermer+'" alt="X" style="float:right;position:relative;margin:2px 2px;" onclick="javascript:destroy_element(\''+createId+'\');"/>';
			}//
			// Permet d afficher un texte au survol
			if (node.getAttribute('onmouseover') != null && node.getAttribute('onmouseover') != "")
			{
				eltSource = node.getAttribute('onmouseover');
				eltSource.setAttribute("onmouseout","destroy_element('"+createId+"');");
				eltSource.onmouseout = function() {destroy_element(createId);};// POUR IE
			}
			mondiv.innerHTML += node.getElementsByTagName('content').item(0).firstChild.data;
			mondiv.setAttribute('id',createId);
			mondiv.style.float = 'left';
			mondiv.style.position = 'absolute';
			mondiv.style.display = 'block';
			mondiv.style.background = '#F4F5F4';
			mondiv.style.color = 'black';
			mondiv.style.border = '1px solid black';
			mondiv.style.padding = '0px 0px';
			mondiv.style.align = 'left';
			//Si la taille du block est d�fini
			if (node.getAttribute('width') != null && node.getAttribute('width') != "")
			{
				mondiv.style.width = node.getAttribute('width')+'px';
			}
			
			insertAfter(mondiv,src);
			
			if(time!=0)
			{
				setTimeout("destroy_element('"+createId+"');", time);
			}
			
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Completion															//
	//////////////////////////////////////////////////////////////////////////////////////////
	var completions = xmlDoc.getElementsByTagName('completion');
	for (var i = 0; i < completions.length; i++)
	{	
		node = completions.item(i);
		var target = node.getAttribute('target');
		//document.getElementById(target).value='';
		var source = node.getAttribute('blockId');
		
		var src = document.getElementById(node.getAttribute('blockId'));
		if (src)
		{
			if(document.getElementById('div_completion')){destroy_element('div_completion');}
			var title = '';
			var titles = node.getElementsByTagName('title');
			if(titles.length > 0)
			{
				title = titles.item(0).firstChild.data;
			}
			var texte = '';
			var textes = node.getElementsByTagName('texte');
			if(textes.length > 0)
			{
				texte = textes.item(0).firstChild.data;
			}
			
			var empty = '';
			var emptys = node.getElementsByTagName('empty');
			if(emptys.length > 0)
			{
				empty = emptys.item(0).firstChild.data;
			}
			
			var options = node.getElementsByTagName('option');
			
			mondiv = document.createElement('div');
			mondiv.setAttribute('id','div_completion');
			mondiv.style.float = 'left';
			mondiv.style.position = 'absolute';
			mondiv.style.display = 'block';
			mondiv.style.background = '#F4F5F4';
			mondiv.style.color = 'black';
			mondiv.style.border = '1px solid black';
			mondiv.style.padding = '0px 0px';
			mondiv.style.textAlign = 'left';
			if (node.getAttribute('width') != null && node.getAttribute('width') != "")
			{
				mondiv.style.width = node.getAttribute('width')+'px';
			}
			
			mondiv.innerHTML = '<img src="'+img_fermer+'" alt="X" style="float:right;position:relative;margin:2px 2px;" onclick="javascript:destroy_element(\'div_completion\');"/>';
			if(texte!='')
			{
				mondiv.innerHTML +=  texte;
			}
			if(options.length>0)
			{
				mondiv.innerHTML += '<ul style="background:#D4D0C8;font-weight:bold;margin:0;padding:0 2px;">'+title+'';
				for (var o = 0; o < options.length; o++)
				{
					option = options.item(o);
					var text = option.firstChild.data;
					var id_opt = option.getAttribute('id');
					var valeur = option.getAttribute('value');
					
					var onclick = "document.getElementById(\""+source+"\").value=\""+valeur+"\";document.getElementById(\""+target+"\").value=\""+id_opt+"\";destroy_element(\"div_completion\");";
					if(option.getAttribute('onclick'))
					{
						onclick = "destroy_element('div_completion');"+option.getAttribute('onclick').replace('"','"');
					}
					
					mondiv.innerHTML += '<li style="list-style-type:none;padding-left:10px;cursor:pointer;" onclick="javascript:'+onclick+'">'+text+'</li>';
				}
				mondiv.innerHTML += '</ul>';
			}
			else if (empty != '')
			{
				mondiv.innerHTML += empty;
			}
			
			insertAfter(mondiv,src);
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//					Script JS			END												//
	//////////////////////////////////////////////////////////////////////////////////////////
	var scrs = xmlDoc.getElementsByTagName('script');
	if (scrs.length >= 1)
	{
		for (var i = 0; i < scrs.length; i++)
		{
			
			try
			{
				node = scrs.item(i);
				if (node.getAttribute('type') == null || (node.getAttribute('type') != null && node.getAttribute('type') != 'begin'))
				{
					var value = '' + node.getElementsByTagName('content').item(0).firstChild.data;
					try { 
						eval(value);
					} catch (err) {
						alert(err.name);
					}
				}
			}
			catch (e)
			{
				throw e;
			}
			
		}
	}
	
}

///////////////////////////////////
/////	FONCTIONS INUTILES	///////
function recupXML(requester){try {xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.loadXML(requester.responseText);}catch(e){try {xmlDoc = requester.responseXML;}catch(e) {alert(e.message)}}return xmlDoc;}
function recupXMLElement(xmlDoc, nomNoeud){var value = xmlDoc.getElementsByTagName(nomNoeud);return (value[0].firstChild.nodeValue);}
//////////////////////////////////

function getX(id) { return window.document.getElementById(id).offsetLeft; } 
function getY(id) { return window.document.getElementById(id).offsetTop; } 

function setX(id,value) { window.document.getElementById(id).style.left = value+'px'; } 
function setY(id,value) { window.document.getElementById(id).style.top = value+'px'; }

function destroy_element(element)
{
	if(is_string(element) && document.getElementById(element))
	{
		document.getElementById(element).parentNode.removeChild(document.getElementById(element));
	}else if( is_object(element) )
	{
		element.parentNode.removeChild(element);
	}
}

function insertAfter(newElement,targetElement)
{
	//target is what you want it to go after. Look for this elements parent.
	var parent = targetElement.parentNode;
	//if the parents lastchild is the targetElement...
	if(parent.lastchild == targetElement) 
	{
		//add the newElement after the target element.
		parent.appendChild(newElement);
	} 
	else 
	{
		// else the target has siblings, insert the new element between the target and it's next sibling.
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}

function show_miniature(path_img, origin, max_x, max_y)
{
	if(document.getElementById('img_thumbnail')){document.getElementById('img_thumbnail').parentNode.removeChild(document.getElementById('img_thumbnail'));}
	
	monimg = document.createElement('img');
	
	monimg.setAttribute('id','img_thumbnail');
	monimg.style.float = 'left';
	monimg.style.position = 'absolute';
	monimg.style.display = 'block';
	monimg.style.background = '#F4F5F4';
	monimg.style.color = 'black';
	monimg.style.border = '1px solid black';
	monimg.style.padding = '5px 5px';
	monimg.src = path_img;
	monimg.width = max_x;
	//monimg.height = max_y;
	
	monimg.setAttribute("onclick","destroy_element('img_thumbnail');");
	monimg.onclick = function() { destroy_element('img_thumbnail'); }
	insertAfter(monimg,document.getElementById(origin));
	
}


function affiche_chargement()
{
	mondiv = document.createElement('div');
	
	mondiv.setAttribute('id','div_chargement');
	mondiv.style.float = 'right';
	mondiv.style.right = '0px';
	mondiv.style.bottom = '0px';
	mondiv.style.position = 'absolute';
	mondiv.style.display = 'block';
	mondiv.style.padding = '2px 10px';
	mondiv.style.margin = '0px';
	
	//Pour qu il soit plus beau
	mondiv.style.background = 'white';
	mondiv.style.color = 'black';
	mondiv.style.border = '2px solid black';
	
	mondiv.innerHTML = '<b><img src="'+img_ajax_loader+'" alt="Chargement ... !" /></b>';
	
	document.getElementsByTagName('body')[0].appendChild(mondiv);
}

function cache_chargement()
{
	destroy_element('div_chargement');
}

function is_string(input){
    return typeof(input)=='string';
}

function is_object(input){
    return typeof(input)=='object';
}

function recup_framework() 
{
	var fw = null;
	if( typeof Prototype == 'object' ) {
		fw = 'Prototype';
	}
	if(typeof jQuery == 'function') {
		fw = 'jQuery';
	}
	return fw;
}

framework_used = recup_framework();
