
var mko_VERIFIER_DATE = { VIDE : 1, ERREUR_DE_SAISIE : 2, INVALIDE : 3, VALIDE : 4}

function mko_VerifierDateOrdre(parDateDebut, parDateFin)
{
	// ------------------------------------------------------------------------------------------------
	// Déclaration des variables
	var iDebutJour 	= (parDateDebut.split(/\//))[0];
	var iDebutMois 	= (parDateDebut.split(/\//))[1];
	var iDebutAnnee = (parDateDebut.split(/\//))[2];
	var iFinJour 	= (parDateFin.split(/\//))[0];
	var iFinMois 	= (parDateFin.split(/\//))[1];
	var iFinAnnee 	= (parDateFin.split(/\//))[2];
	
	if (iFinAnnee < iDebutAnnee)
		return mko_VERIFIER_DATE.INVALIDE;
	if (iFinMois < iDebutMois)
		return mko_VERIFIER_DATE.INVALIDE;
	if (iFinJour < iDebutJour)
		return mko_VERIFIER_DATE.INVALIDE;
	return mko_VERIFIER_DATE.VALIDE;
}

function _mko_VerifierDate(parDate)
{
	// ------------------------------------------------------------------------------------------------
	// Déclaration des variables
	var iJour = (parDate.split(/\//))[0];
	var iMois = (parDate.split(/\//))[1];
	var iAnnee = (parDate.split(/\//))[2];
	var nbJours = new Array('',31,28,31,30,31,30,31,31,30,31,30,31);
	
	// ------------------------------------------------------------------------------------------------
	// On vérifie la saisie
	if (iAnnee == 0 && iMois == 0 && iJour == 0)
		return mko_VERIFIER_DATE.VIDE;	// pas de date
	if (iAnnee == 0 || iMois == 0 && iJour != 0)
		return mko_VERIFIER_DATE.ERREUR_DE_SAISIE;
	// A partir d'ici on a forcément une année de saisie
	
	// ------------------------------------------------------------------------------------------------
	// Si on a pas de jour alors la date ne peut etre que bonne
	if (iJour == 0)
		return mko_VERIFIER_DATE.VALIDE;
	
	// ------------------------------------------------------------------------------------------------
	// On vérifie la validité de la date JJ/MM/AAAA
	//
	// On modifie le nombre de jour en fonction de l'année bisextile ou non
	if (iAnnee%4 == 0 && iAnnee%100 > 0 || iAnnee%400 == 0 )
		nbJours['2'] = 29;
	if (iJour > nbJours[Math.round(iMois)])
		return mko_VERIFIER_DATE.INVALIDE;
	
	return mko_VERIFIER_DATE.VALIDE;
}


function mko_VerifierDate(parDate)
{	
	// ------------------------------------------------------------------------------------------------
	// Récupération des dates
	var szDate 	= $(parDate + '_jour').value + '/' + $(parDate + '_mois').value + '/' + $(parDate + '_annee').value;  
	
	// ------------------------------------------------------------------------------------------------
	// Vérification de la date de début
	switch(_mko_VerifierDate(szDate))
	{
		case mko_VERIFIER_DATE.ERREUR_DE_SAISIE:
			alert('Il y a une erreur de saisie dans la date!');
			return false;
		
		case mko_VERIFIER_DATE.INVALIDE:
			alert('La date est invalide!');
			return false;
		
		case mko_VERIFIER_DATE.VIDE:
			alert('Vous devez saisir une date!');
			return false;
		
		case mko_VERIFIER_DATE.VALIDE:
			return true;
	}
}



function mko_VerifierDateDebutFin(parDateDebut, parDateFin)
{
	// ------------------------------------------------------------------------------------------------
	// Récupération des dates
	var szDateDebut 	= $(parDateDebut + '_jour').value + '/' + $(parDateDebut + '_mois').value + '/' + $(parDateDebut + '_annee').value;  
	var szDateFin 		= $(parDateFin + '_jour').value + '/' + $(parDateFin + '_mois').value + '/' + $(parDateFin + '_annee').value;  
	
	// ------------------------------------------------------------------------------------------------
	// Vérification de la date de début
	switch(_mko_VerifierDate(szDateDebut))
	{
		case mko_VERIFIER_DATE.ERREUR_DE_SAISIE:
			alert('Il y a une erreur de saisie dans la date de début!');
			return false;
		
		case mko_VERIFIER_DATE.INVALIDE:
			alert('La date de début est invalide!');
			return false;
		
		case mko_VERIFIER_DATE.VIDE:
			alert('Vous devez saisir une date de début!');
			return false;
		
		case mko_VERIFIER_DATE.VALIDE:
			break;
	}
	
	// ------------------------------------------------------------------------------------------------
	// Vérification de la date de fin
	switch(_mko_VerifierDate(szDateFin))
	{
		case mko_VERIFIER_DATE.ERREUR_DE_SAISIE:
			alert('Il y a une erreur de saisie dans la date de fin!');
			return false;
		
		case mko_VERIFIER_DATE.INVALIDE:
			alert('La date de fin est invalide!');
			return false;
		
		case mko_VERIFIER_DATE.VIDE:
			// Si il n'y a pas de date de fin, pas besoin de vérifier
			// que la date de fin est bien après la date de début
			return true;
			
		case mko_VERIFIER_DATE.VALIDE:
			break;
	}
	
	// ------------------------------------------------------------------------------------------------
	// Vérification que la date de fin est bien après la date de début
	if (mko_VerifierDateOrdre(szDateDebut,szDateFin) == mko_VERIFIER_DATE.INVALIDE)
	{
		alert('La date de début doit être avant la date de fin!');
		return false;
	}
	return true;
}

// -----------------------------------------------------------------------------------------------
// -                                          BDD Switch                                         -
// -----------------------------------------------------------------------------------------------

function mko_BddSwitchSauver()
{
	// Déclaration des variables locales
	var szLangue;
	var szChampsNom;
	var szChampsType;
	
	// On evalue les champs au cas où
	//if (!bdd_langues_champs)
	eval($('[bdd_langues_champs]').value);
	
	// On parcourt le liste des champs
	for (i=0; i < bdd_langues_champs.length; i++)
	{
		// On retire le type du nom de chaque champs
		szChampsNom		= (bdd_langues_champs[i].split(/\#/)[0]);
		szChampsType 	= (bdd_langues_champs[i].split(/\#/)[1]);
		if (szChampsNom == "")
			continue;
		
		// On récupère la langue courante du champs
		szLangue = $('[local_'  + szChampsNom + '_langue]').value;
		if (szLangue != "")
		{
			// Traitement spécial pour le wysiwyg
			if (szChampsType == "wysiwyg")
			{
				wysiwyg_GetTexte('[form_'  + szChampsNom + '_' + szLangue + ']');
			}
			else
			{
				$('[form_'  + szChampsNom + '_' + szLangue + ']').value = $('[local_'  + szChampsNom + '_valeur]').value;//.replace(/\"/g,"'");
			}
		}
	} 
}

function mko_BddSwitchChanger(parLangue)
{
	// Déclaration des variables locales
	var szLangue;
	var szChampsNom;
	var szChampsType;
	
	// On evalue les champs au cas où
	//if (!bdd_langues_champs)
	eval($('[bdd_langues_champs]').value);
	
	// On parcourt le liste des champs
	for (i=0; i < bdd_langues_champs.length; i++)
	{
		// On retire le type du nom de chaque champs
		szChampsNom		= (bdd_langues_champs[i].split(/\#/)[0]);
		szChampsType 	= (bdd_langues_champs[i].split(/\#/)[1]);
		if (!szChampsNom)
			continue;
		
		// Traitement spécial pour le wysiwyg
		if (szChampsType == 'wysiwyg')
		{
			$('[local_'  + szChampsNom + '_langue]').value = parLangue;
			wysiwyg_SetTexte('[form_'  + szChampsNom + '_' + parLangue + ']');
		}
		else
		{
			$('[local_'  + szChampsNom + '_langue]').value = parLangue;
			$('[local_'  + szChampsNom + '_valeur]').value = $('[form_'  + szChampsNom + '_' + parLangue + ']').value;
		}
	}
	
	$('#champs_langues_courante').innerHTML = '(' + parLangue + ')';
}

// -----------------------------------------------------------------------------------------------
// -                                        BDD Formulaire                                       -
// -----------------------------------------------------------------------------------------------
function mko_BddFormulaireAfficher(parForm,parParams,parAfficher)
{
	if (parAfficher == true)
	{
		mko_AjaxGet('../noyau/formulaires/form_' + parForm + '.php',parParams,_mko_BddFormulaireGetPage,false);
	}
	mko_BddAfficher('#bdd_formulaire',parAfficher);
}


function _mko_BddFormulaireGetPage(parReponse)
{

	$('#bdd_formulaire_corps').innerHTML = parReponse;
	
	// Récupération des scripts pour les faire prendre en compte
	var varAllScripts = parReponse.extractTags("script");
	varAllScripts.forEach(function(v){
		window.eval(v);
	});
	return true;
}


// -----------------------------------------------------------------------------------------------
// -                                         BDD Question                                        -
// -----------------------------------------------------------------------------------------------
var mko_QUESTION_TYPE 		= {	OK : 1,	OUI_NON : 2,	OUI_ANNULER : 3, VALIDER_ANNULER : 4}

function mko_Question(parType,parQuestion,parFonction1,parFonction2)
{
	// Affichage de la question
	$('#bdd_question_question').innerHTML = parQuestion;
	
	// Mise en place des callbacks
	if (parFonction1 != null)
		$('#bdd_question_bouton1').onclick = function(){ mko_BddAfficher('#bdd_question',false); parFonction1() };
	else
		$('#bdd_question_bouton1').onclick = function(){ mko_BddAfficher('#bdd_question',false)};
	
	if (parFonction2 != null)
		$('#bdd_question_bouton2').onclick = function(){ mko_BddAfficher('#bdd_question',false); parFonction2() };
	else
		$('#bdd_question_bouton2').onclick = function(){ mko_BddAfficher('#bdd_question',false)};
	
	// Affichage personnalisé
	switch(parType)
	{
		case mko_QUESTION_TYPE.OK:
			$('#bdd_question_bouton1').style.display = '';
			$('#bdd_question_bouton1').className = 'btn_ok';
			$('#bdd_question_bouton2').style.display = 'none';
			$('#bdd_question_bouton2').className = '';
			break;
		case  mko_QUESTION_TYPE.OUI_NON:
			$('#bdd_question_bouton1').style.display = '';
			$('#bdd_question_bouton1').className = 'btn_oui';
			$('#bdd_question_bouton2').style.display = '';
			$('#bdd_question_bouton2').className = 'btn_non';
			break;
		case  mko_QUESTION_TYPE.OUI_ANNULER:
			$('#bdd_question_bouton1').style.display = '';
			$('#bdd_question_bouton1').className = 'btn_oui';
			$('#bdd_question_bouton2').style.display = '';
			$('#bdd_question_bouton2').className = 'btn_annuler';
			break;
		case  mko_QUESTION_TYPE.VALIDER_ANNULER:
			$('#bdd_question_bouton1').style.display = '';
			$('#bdd_question_bouton1').className = 'btn_valider';
			$('#bdd_question_bouton2').style.display = '';
			$('#bdd_question_bouton2').className = 'btn_annuler';
			break;
	}
	
	// Affichage de la boite de dialogue
	mko_BddAfficher('#bdd_question',true);
}


// -----------------------------------------------------------------------------------------------
// -                                           BDD Image                                         -
// -----------------------------------------------------------------------------------------------
function mko_ImageImprimer()
{
	$('#bordure_haut').style.display = 'none';
	$('#page').style.display = 'none';
	$('#bordure_bas').style.display = 'none';
	
	window.print();
	
	$('#bordure_haut').style.display = 'block';
	$('#page').style.display = 'block';
	$('#bordure_bas').style.display = 'block';
}

function mko_ImageAfficher(url,afficher)
{
	mko_FondNoir(afficher);
	
	if (afficher == true)
	{
		$('#bdd_image_image').src = url;
		$('#bdd_image').style.display = "block";
	}
	else
	{
		$('#bdd_image_image').src = "";
		$('#bdd_image').style.display = "none";
	}
}

// -----------------------------------------------------------------------------------------------
// -                                            BDDS                                             -
// -----------------------------------------------------------------------------------------------
function mko_BddAfficher(id,afficher)
{
	mko_FondNoir(afficher);
	
	if (afficher == true)
	{
		$(id).style.display = "block";
	}
	else
	{
		$(id).style.display = "none";
	}
}

// -----------------------------------------------------------------------------------------------
// -                                        BDD Fond noir                                        -
// -----------------------------------------------------------------------------------------------
function mko_FondNoir(afficher)
{
	if (afficher == true)
	{
		$('#en_tete_flash').style.display = "none";
		
		$('#bdd_fond_noir').style.opacity = ".0";
		$('#bdd_fond_noir').style.filter = "alpha(opacity=0)";
		
		$('#bdd_fond_noir').style.display = 'block';
		
		for(var i=1;i<30;i++)
		{
			setTimeout("$('#bdd_fond_noir').style.opacity = '." + ((i * 0.025) + "").substring(2) + "';", (i * 20));
			setTimeout("$('#bdd_fond_noir').style.filter = 'alpha(opacity=" + (i * 2.5) + ")';", (i * 20));
		}
	}
	else
	{
		$('#bdd_fond_noir').style.display = "none";
		$('#en_tete_flash').style.display = "block";
	}
}






// -----------------------------------------------------------------------------------------------
// -                                        Composant AJAX                                       -
// -----------------------------------------------------------------------------------------------
function HttpClient(){ }
HttpClient.prototype = 
{
	// Objet XMLHttpRequest
	varXmlHttp:false,
	
	callback:false,
	
	// Initialisation de l'objet xmlhttpclient
	_Initialitation: function()
	{	
		try
		{
			// Mozilla / Safari
			this.varXmlHttp = new XMLHttpRequest();
		}
		catch (e)
		{
			// IE
			var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');
			var varSucces = false;
			for (var i=0;i < XMLHTTP_IDS.length &&!varSucces; i++)
			{
				try
				{
					this.varXmlHttp = new ActiveXObject(XMLHTTP_IDS[i]);
					varSucces = true;
				}
				catch (e){}
			}
			if (!varSucces)
			{
				alert('Unable to create XMLHttpRequest.');
			}
		}
	},
	
	Requete: function(parMethode,parUrl,parParams,parCallBackFn,parCallBackParams)
	{
		// Si on a pas encore créé le client HTTP alors on le fait
		if (!this.varXmlHttp)
			this._Initialitation();
		
		// Si on est en port alors on doit envoyer les paramètres
		if (parMethode == "GET")
		{
			parUrl = parUrl + "?" + parParams;
		}
		
		// Connexion à  l'adresse désirée
		this.varXmlHttp.open(parMethode,parUrl,false);
		
		// On interdit le cache pour les pages chargées dynamiquement 
		this.varXmlHttp.setRequestHeader("Cache-Control","no-cache");
		
		// Si on est en port alors on doit envoyer les paramètres
		if (parMethode == "POST")
		{
			//
			this.varXmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			
			// Envoie des paramètres
			this.varXmlHttp.send(parParams);
		}
		else
		{
			this.varXmlHttp.send('');
		}
		
		// Traitement de la réponse
		switch(this.varXmlHttp.readyState)
		{
			case 4:
				try
				{
					
					if (this.varXmlHttp.status == 200)
					{
						if (parCallBackParams == false)
							parCallBackFn(this.varXmlHttp.responseText);
						else
							parCallBackFn(this.varXmlHttp.responseText,parCallBackParams);
					}
					else if (this.varXmlHttp.status == 404)
					{
						alert("Cette page n'existe pas!\n" + parUrl);
					}
					else
					{
						alert('HTTP Error, bad response: '+'['+this.varXmlHttp.status+'] ' + this.varXmlHttp.statusText);
					}
				}
				catch(e)
				{
					alert("XMLHttp error: " + e.message);
				}
				break;
			default:
				alert('HTTP Bad State [' + this.varXmlHttp.readyState + '] : ');
				break;
		}
		
		
	}
}
var mko_AjaxClient = new HttpClient();


// -----------------------------------------------------------------------------------------------
// -                                              GET                                            -
// -----------------------------------------------------------------------------------------------
function mko_AjaxGet(parUrl,parParams,parCallBackFn,parCallBackParams)
{
	mko_AjaxClient.Requete('GET',parUrl,parParams,parCallBackFn,parCallBackParams);
	return false;
}



// -----------------------------------------------------------------------------------------------
// -                                             POST                                            -
// -----------------------------------------------------------------------------------------------
function mko_AjaxPost(parUrl,parParams,parCallBackFn,parCallBackParams)
{
	mko_AjaxClient.Requete('POST',parUrl,parParams,parCallBackFn,parCallBackParams);
	return false;
}


function mko_AjaxPostMoveOrMessage(parReponse, parParams)
{
	if (parReponse.substring(0,2) == 'EM') 
	{
		document.location = parParams[0];
	}
	else
	{
		$(parParams[1]).innerHTML = parParams[2];
	}
	return true;
}
			
			
			
			
			
			

// -----------------------------------------------------------------------------------------------
// -                                       Prototypes spéciaux                                   -
// -----------------------------------------------------------------------------------------------
String.prototype.extractTags = function(tag)
{
	var matchAll = new RegExp('(?:<' + tag + '.*?>)((\n|\r|.)*?)(?:<\/' + tag + '>)','img');
	var matchOne = new RegExp('(?:<' + tag + '.*?>)((\n|\r|.)*?)(?:<\/' + tag + '>)','im');
	return (this.match(matchAll) || []).map(function(scriptTag)
	{
		return (scriptTag.match(matchOne) || ['', ''])[1]; 
	});
}

Object.prototype.forEach = function(delegate,ownpropertiesonly)
{
	if (typeof(delegate) == "function")
	{
		if (this instanceof Array && typeof(ownpropertiesonly) == "undefined")
		{
			ownpropertiesonly = true;
		}
		for (key in this)
		{
			var ok = (!ownpropertiesonly);
			if (!ok)
			{
				try
				{
					ok = this.hasOwnProperty(key);
				}
				catch(ex)
				{
				}
			}
			if (ok)
			{
				try
				{
					delegate(this[key],key,this);
				}
				catch(ex)
				{
				}
			}
		}
	}
}

Object.prototype.map=function(iterator)
{
	var results = [];
	this.forEach(function(value,index)
	{
		results.push(iterator(value,index));
	});
	return results;
}







// -----------------------------------------------------------------------------------------------
// -                                             WYSIWYG                                         -
// -----------------------------------------------------------------------------------------------
function wysiwyg_Demarrage()
{
	wysiwyg_InitBoutons();
	wysiwyg_EcrireIFrame();
	wysiwyg_RendreEditable();
	
	// Initialisation de la classe
	mko_wysiwyg._initialisation();
}


function wysiwyg_InitBoutons()
{
	var boutons = $('#wysiwyg a.bouton_classique');
	for (var i=0; i < boutons.length; i++)
	{
		boutons[i].onclick = function()
		{
			wysiwyg_Commande(this.id, null);
			return false;
		}
	}

}



function wysiwyg_EcrireIFrame()
{
	if(window.ActiveXObject)
		var edoc = window.frames['wysiwyg_design'].document;
	else
		var edoc = $('#wysiwyg_design').contentDocument;
	
	edoc.open();
	edoc.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
	edoc.write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"><title>Design page</title>");
	edoc.write("<link href=\"../commun_style_all.css.php\" rel=\"stylesheet\" type=\"text/css\" />");
	edoc.write("<style>");
	edoc.write("  body{padding:0px;margin:0px;font-family:verdana;font-size:12px;line-height:14px;text-align:justify}");
	edoc.write("  h4{ display: inline;font-family:verdana;font-weight: bold;font-style: normal;font-size:12px;text-align: justify;text-decoration: none;	margin: 0px;margin-right: 4px; }");
	edoc.write("</style></head><body id=\"page\" contenteditable=\"true\">");
	edoc.write("</body></html>");
	edoc.close(); 
}

function wysiwyg_Apercu()
{
	if(window.ActiveXObject)
		var iFrameDoc = window.frames['wysiwyg_design'].document;
	else
		var iFrameDoc = $('#wysiwyg_design').contentDocument;
	
	var Win = open("","","width=500,height=300,menubar=yes,scrollbars=yes");
	var edoc = Win.document;
	Win.moveTo(200,200);
	
	edoc.open();
	edoc.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
	edoc.write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"><title>Design page</title>\r\n");
	edoc.write("<link href=\"../commun_style_all.css.php\" rel=\"stylesheet\" type=\"text/css\" />");
	edoc.write("<style>\r\n");
	edoc.write("  body{padding:0px;margin:0px;font-family:verdana;font-size:12px;line-height:14px;text-align:justify}");
	edoc.write("  h4{ display: inline;font-family:verdana;font-weight: bold;font-style: normal;font-size:12px;text-align: justify;text-decoration: none;	margin: 0px;margin-right: 4px; }");
	edoc.write("</style></head><body id=\"page\">\r\n");
	edoc.write(iFrameDoc.body.innerHTML);
	edoc.write("</body></html>\r\n");
	edoc.close();
}


function wysiwyg_ActionLienHyperText()
{
	var varParam = prompt("Entrez le lien :", "http://");
	if (varParam != '' && varParam != null)
	{
		wysiwyg_Commande("createlink",varParam);
	}
}

function wysiwyg_ActionClean()
{
	wysiwyg_Commande('removeFormat',0);
	wysiwyg_Commande('unlink',0);
}

function wysiwyg_RendreEditable()
{
	if ($('#wysiwyg_design').contentWindow.document.body)
		$('#wysiwyg_design').contentWindow.document.body.designMode = 'On'; 			// Moz, IE, Op, Saf
	
	//in moz you cannot change desgin mode straight away so try and then retry
	try
	{
		$('#wysiwyg_design').contentWindow.document.designMode = "on";
	}
	catch(e)
	{
		setTimeout(wysiwyg_RendreEditable,250);
	}

}


function wysiwyg_GetTexte(parId)
{
	//
	if ($('#wysiwyg_vue').value == "")
		return;
	
	//
	// On récupère le contenu de l'éditeur
	if(window.ActiveXObject)
		var edoc = window.frames['wysiwyg_design'].document;
	else
		var edoc = $('#wysiwyg_design').contentDocument;
	
	//
	// Récupération du code
	var varTexte;
	if ($('#wysiwyg_vue').value == "design")
		varTexte = edoc.body.innerHTML;
	else
		varTexte = $('#wysiwyg_texte').value;
	
	// 
	// On remplace les " par des ' et on sauvegarde le texte reformaté
	$(parId).value = varTexte;//.replace(/\"/g,"'");
}

function wysiwyg_SetTexte(parId)
{
	//
	// On initialise les champs cachés et on passe en vue design
	wysiwyg_VueDesign();
	
	//
	// On récupère le contenu de l'éditeur
	if(window.ActiveXObject)
		var edoc = window.frames['wysiwyg_design'].document;
	else
		var edoc = $('#wysiwyg_design').contentDocument;
	
	edoc.body.innerHTML = $(parId).value;
}


function wysiwyg_VueDesign()
{
	//
	if ($('#wysiwyg_vue').value == "design")
		return;
	
	//
	// On récupère le contenu de l'éditeur
	if(window.ActiveXObject)
		var edoc = window.frames['wysiwyg_design'].document;
	else
		var edoc = $('#wysiwyg_design').contentDocument;
	
	//
	// On cache la barre d'outils
	$('#wysiwyg_barre_design').style.display = "block";
	$('#wysiwyg_barre_texte').style.display = "none";
	
	//
	// On cache la vue texte
	$('#wysiwyg_vue_texte').style.display = "none";
	
	//
	// Affichage du code design
	edoc.body.innerHTML = $('#wysiwyg_texte').value;
	
	//
	// Sauvegarde de la vue
	$('#wysiwyg_vue').value = "design";
	
	//
	// On rend de nouveau éditable
	wysiwyg_RendreEditable();
}

function wysiwyg_VueTexte()
{
	//
	if ($('#wysiwyg_vue').value == "texte")
		return;
	
	//
	// On récupère le contenu de l'éditeur
	if(window.ActiveXObject)
		var edoc = window.frames['wysiwyg_design'].document;
	else
		var edoc = $('#wysiwyg_design').contentDocument;
	
	//
	// Affichage du code HTML
	$('#wysiwyg_texte').value = edoc.body.innerHTML;
	
	//
	// On cache la barre d'outils
	$('#wysiwyg_barre_design').style.display = "none";
	$('#wysiwyg_barre_texte').style.display = "block";
	
	//
	// On affiche la vue texte
	$('#wysiwyg_vue_texte').style.display = "block";
	
	//
	// Sauvegarde de la vue
	$('#wysiwyg_vue').value = "texte";
}







function walkChildNodes(objRef, n) {
    var obj;
    if (objRef)
    {
        if (typeof objRef == "string") {
            obj = document.getElementById(objRef);
        } else {
            obj = objRef;
        }
    } else {
        obj = (document.body.parentElement) ? document.body.parentElement : document.body.parentNode;
    }
    var output = "";
    var indent = "";
    var i, group, txt;
    if (n)
    {
        for (i = 0; i < n; i++)
        {
            indent += "+---";
        }
    } else {
        n = 0;
        output += "Child Nodes of <" + obj.tagName.toLowerCase( );
        output += ">\n=  ==  ==  ==  ==  ==  ==  ==  ==  ==  ==\n";
    }
    group = obj.childNodes;
    for (i = 0; i < group.length; i++)
    {
        output += indent;
        switch (group[i].nodeType)
        {
            case 1:
                output += "<" + group[i].tagName.toLowerCase( );
                output += (group[i].id) ? " ID=" + group[i].id : "";
                output += (group[i].name) ? " NAME=" + group[i].name : "";
                output += ">\n";
                break;
            case 3:
                txt = group[i].nodeValue.substr(0,15);
                output += "[Text:\"" + txt.replace(/[\r\n]/g,"<cr>");
                if (group[i].nodeValue.length > 15) {
                    output += "...";
                }
                output += "\"]\n";
                break;
            case 8:
                output += "[!COMMENT!]\n";
                break;
            default:
                output += "[Node Type = " + group[i].nodeType + "]\n";
        }
        if (group[i].childNodes.length > 0)
        {
            output += walkChildNodes(group[i], n+1);
        }
    }
    return output;
}










function wysiwyg_Commande(parCommande,parParametre)
{
	
	switch(parCommande)
	{
		case "bold":
			mko_wysiwyg.StyleModify(mko_wysiwyg.RangeGet(),"STRONG",true,null);
			return;
		case "italic":
			mko_wysiwyg.StyleModify(mko_wysiwyg.RangeGet(),"I",true,null);
			return;
		case "underline":
			mko_wysiwyg.StyleModify(mko_wysiwyg.RangeGet(),"U",true,null);
			return;
	
	}
	
	$('#wysiwyg_design').contentWindow.document.execCommand(parCommande,0,parParametre);
	$('#wysiwyg_design').contentWindow.focus();
}
	

// -----------------------------------------------------------------------------------------------
// -                                           WYSIWYG                                           -
// -----------------------------------------------------------------------------------------------

function wysiwyg(){ }
wysiwyg.prototype = 
{
	_initialisation : function()
	{
		// Déclaration des variables
		var t = this, d = document, w = window, na = navigator, ua = na.userAgent;
		
		// Récupération de la fenetre et du document
		t.elt = $('#wysiwyg_design');
		t.win =  $('#wysiwyg_design').contentWindow;
		t.doc = $('#wysiwyg_design').contentWindow.document;
		
		// Vérification des navigateurs
		t.isOpera = w.opera && opera.buildNumber;
		t.isWebKit = /WebKit/.test(ua);
		t.isOldWebKit = t.isWebKit && !w.getSelection().getRangeAt;
		t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);
		t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
		t.isGecko = !t.isWebKit && /Gecko/.test(ua);
		t.isMac = ua.indexOf('Mac') != -1;
		return;
	},
	
	// Toutes les fonctions
	//http://fr.selfhtml.org/javascript/objets/node.htm
	
	
	/* Print Range */
	RangePrint : function(oRange, sStruct)
	{
		// -----------------------------------------------------------------------------------------------
		// Déclaration des variables
		var t = this, oCurNode;
		var sResStruct = {iStarted : 0, iEnded : 0, oNode : t.doc.body};
		
		// -----------------------------------------------------------------------------------------------
		// Initialisation de la structure
		if (sStruct != null)
			sResStruct = sStruct;
		oCurNode = sResStruct.oNode;
		
		// -----------------------------------------------------------------------------------------------
		// On est sur une feuille
		if (oCurNode.nodeType == 3)
		{
			// -------------------------------------------------------------------------------------------
			// Si on a trouvé le noeud de départ
			if (oCurNode == oRange.oStartNode)
			{
				sResStruct.iStarted = 1;
				alert(oCurNode.nodeValue.substring(oRange.iStartOffset));
			}
			// -------------------------------------------------------------------------------------------
			// Si on a trouvé le noeud de fin
			else if (oCurNode == oRange.oEndNode)
			{
				alert(oCurNode.nodeValue.substring(0,oRange.iEndOffset));
				sResStruct.iEnded = 1;
				return sResStruct;
			}
			// -------------------------------------------------------------------------------------------
			// Si on est entre les deux
			else if (sResStruct.iStarted == 1)
			{
				alert(oCurNode.nodeValue);
			}
		}
		
		// -----------------------------------------------------------------------------------------------
		// On parcourt l'arbre avec les enfants
		for (var i = 0; i < oCurNode.childNodes.length; i++)
		{
			sResStruct.oNode = oCurNode.childNodes[i];
			sResStruct = t.RangePrint(oRange,sResStruct);
			
			if (sResStruct.iEnded == 1)// Si on est à la fin
				return sResStruct;
		}
		return sResStruct;
	},
	
	// ---------------------------------------------------------------------------------------------------
	// Ajout de style
	// ---------------------------------------------------------------------------------------------------
	StyleModify : function(oRange, szStyle, bAddStyle , sStruct)
	{
		var t = this, oCurNode, oCurChildNode, oNewChildNode, iLevel, tStyles = new Array();
		var sResStruct = {iStarted : 0, iEnded : 0, bFound : 0, iLevel : 0, 
		tStyles : new Array(),
		oNode : t.doc.body, 
		oStartRootNode : null, oStartNode : null, iStartOffet : null, 
		oEndRootNode : null, oEndNode : null, iEndOffset : null};
		
		// -----------------------------------------------------------------------------------------------
		// Initialisation de la structure
		if (sStruct != null)
			sResStruct = sStruct;
		oCurNode = sResStruct.oNode;
		iLevel 	 = sResStruct.iLevel;
		
		
		// -----------------------------------------------------------------------------------------------
		// Si on est au niveau 1 et que l'on est sur la branche de début de selection
		if (iLevel == 1 && oCurNode == oRange.oStartRootNode)
			sResStruct.iStarted	= 1;
		
		// -----------------------------------------------------------------------------------------------
		// Si on est au niveau 1 et que l'on est sur la branche de fin de selection
		if (iLevel == 1 && oCurNode == oRange.oEndRootNode)
			sResStruct.iEnded 	= 1;
		
		// -----------------------------------------------------------------------------------------------
		// Affichage du noeud courant
		//if (sResStruct.iStarted)
		//	alert('NIVEAU: ' + iLevel + ' - CUR(' + oCurNode.nodeName + ':' + oCurNode.nodeValue + ') - STYLE: ' + sResStruct.tStyles);		
		
		// -----------------------------------------------------------------------------------------------
		// On est sur une feuille (le début et la fin de la selection sont ici)
		if (oCurNode.nodeType == 3)
		{
			// -------------------------------------------------------------------------------------------
			// On regarde le chemin parcouru
			if (sResStruct.iStarted == 1)
			{
				// ---------------------------------------------------------------------------------------
				// On copie le path courant dans un autre tableau et on regarde si le style est déja dans le chemin
				sResStruct.bFound = false;
				for (var i = 0; i < sResStruct.tStyles.length; ++i)
				{
					if (sResStruct.tStyles[i] == szStyle)
						sResStruct.bFound = true;
					tStyles.push(sResStruct.tStyles[i]);
				}
				tStyles.sort();
				
				
			}
		}
		
		// -----------------------------------------------------------------------------------------------
		// On parcourt l'arbre avec les enfants
		for (var i = 0; i < oCurNode.childNodes.length; i++)
		{
			// -------------------------------------------------------------------------------------------
			// On sauvegarde l'enfant
			oCurChildNode = oCurNode.childNodes[i];
			
			// -------------------------------------------------------------------------------------------
			// Traitement préfixé
			sResStruct.oNode	= oCurChildNode;
			sResStruct.iLevel   = iLevel + 1;						// On incrémente le niveau
			sResStruct.bFound 	= 0;								//
			if (oCurChildNode.nodeType != 3)
				sResStruct.tStyles.push(oCurChildNode.nodeName);	// On ajoute le style si on est pas sur le noeud root
			
			// -------------------------------------------------------------------------------------------
			// Parcours récursif
			sResStruct = t.StyleModify(oRange, szStyle, bAddStyle, sResStruct);
			
						
			// -------------------------------------------------------------------------------------------
			// Traitement postfixé
			sResStruct.iLevel	= iLevel;
			sResStruct.tStyles.pop();
			
			// -------------------------------------------------------------------------------------------
			// Si l'enfant est une feuille, que l'on est dans la selection
			// que l'on doit ajouter le style et que l'on ne l'a pas trouvé
			if (oCurChildNode.nodeType == 3 && sResStruct.iStarted == 1 && bAddStyle && !sResStruct.bFound)
			{
			
				
				if (oCurChildNode == oRange.oStartNode && oCurChildNode == oRange.oEndNode)
				{
					// -----------------------------------------------------------------------------------
					// Ajout du noeud de style pour la selection
					if (i == (oCurNode.childNodes.length -1))
						oNewChildNode = oCurNode.appendChild(t.doc.createElement(szStyle));
					else
						oNewChildNode = oCurNode.insertBefore(t.doc.createElement(szStyle),oCurNode.childNodes[i + 1]);
					oNewChildNode.appendChild(t.doc.createTextNode(oCurChildNode.nodeValue.substr(oRange.iStartOffset,oRange.iEndOffset - oRange.iStartOffset)));
					i++;
					
					// -----------------------------------------------------------------------------------
					// Ajout du noeud de style pour l'après selection
					if (i == (oCurNode.childNodes.length -1))
						oNewChildNode = oCurNode.appendChild(t.doc.createTextNode(oCurChildNode.nodeValue.substr(oRange.iEndOffset)));
					else
						oNewChildNode = oCurNode.insertBefore(t.doc.createTextNode(oCurChildNode.nodeValue.substr(oRange.iEndOffset)),oCurNode.childNodes[i + 1]);
					i++;
					
					// -----------------------------------------------------------------------------------
					// On modifie le noeud courant
					oCurChildNode.nodeValue = oCurChildNode.nodeValue.substr(0,oRange.iStartOffset);
					break;
				}
				else if (oCurChildNode == oRange.oStartNode)
				{
				
					// -----------------------------------------------------------------------------------
					// Ajout du noeud de style
					if (i == (oCurNode.childNodes.length -1))
						oNewChildNode = oCurNode.appendChild(t.doc.createElement(szStyle));
					else
						oNewChildNode = oCurNode.insertBefore(t.doc.createElement(szStyle),oCurNode.childNodes[i + 1]);
					oNewChildNode.appendChild(t.doc.createTextNode(oCurChildNode.nodeValue.substr(oRange.iStartOffset)));
					i++;
					
					// -----------------------------------------------------------------------------------
					// On modifie le noeud enfant
					oCurChildNode.nodeValue = oCurChildNode.nodeValue.substr(0,oRange.iStartOffset);
				
				}
				else if (oCurChildNode == oRange.oEndNode)
				{
					// -----------------------------------------------------------------------------------
					// Ajout du noeud de style
					oNewChildNode = oCurNode.insertBefore(t.doc.createElement(szStyle),oCurNode.childNodes[i]);
					oNewChildNode.appendChild(t.doc.createTextNode(oCurChildNode.nodeValue.substr(0,oRange.iEndOffset)));
					
					// -----------------------------------------------------------------------------------
					// On modifie le noeud enfant
					oCurChildNode.nodeValue = oCurChildNode.nodeValue.substr(oRange.iEndOffset);
					break;
				}
				else
				{
					// -----------------------------------------------------------------------------------
					// Ajout du noeud de style
					if (i == (oCurNode.childNodes.length -1))
						oNewChildNode = oCurNode.appendChild(t.doc.createElement(szStyle));
					else
						oNewChildNode = oCurNode.insertBefore(t.doc.createElement(szStyle),oCurNode.childNodes[i + 1]);
					oNewChildNode.appendChild(t.doc.createTextNode(oCurChildNode.nodeValue));
					
					// -----------------------------------------------------------------------------------
					// On supprime le noeud courant
					oCurNode.removeChild(oCurChildNode);
				}
				
				// ---------------------------------------------------------------------------------------
				//alert('AJOUT ' + walkChildNodes(t.doc.body,0));
			}
			
			
			
			// -------------------------------------------------------------------------------------------
			// Si on a trouvé la dernière branche
			if (iLevel == 0 && sResStruct.iEnded == 1)
				break;
		}
		return sResStruct;
	},
	
	
	
	
	// ---------------------------------------------------------------------------------------------------
	// Recherche des neouds du range, NoeudDebut NoeudFin, NoeudRacineDebut, NoeudRacineFin, OffsetDebut, OffsetFin
	// ---------------------------------------------------------------------------------------------------
	_RangeFindNodes :function(ieStruct,ffStruct,sStruct)
	{
		var t = this, oCurNode, iLevel, iCurLength;
		var sResStruct = {iStarted : 0, iEnded : 0, iFound : 0, iLevel : 0, iCurLength : 0, 
		oNode : t.doc.body, 
		oStartRootNode : null, oStartNode : null, iStartOffet : null, 
		oEndRootNode : null, oEndNode : null, iEndOffset : null};
		
		// -----------------------------------------------------------------------------------------------
		// Initialisation de la structure
		if (sStruct != null)
			sResStruct = sStruct;
		oCurNode 	= sResStruct.oNode;
		iLevel 		= sResStruct.iLevel;
		iCurLength	= sResStruct.iCurLength;
		
		// -----------------------------------------------------------------------------------------------
		// On est sur une feuille
		if (oCurNode.nodeType == 3)
		{
			// -------------------------------------------------------------------------------------------
			// Si on a passé une structure IE
			if (ieStruct)
			{
			
				// ---------------------------------------------------------------------------------------
				// Si on a trouvé le noeud de départ
				if (sResStruct.iStarted == 0 && (sResStruct.iCurLength + oCurNode.nodeValue.length) > ieStruct.iStartCaretPos)
				{
					sResStruct.oStartNode 	= oCurNode;
					sResStruct.iStartOffset	= ieStruct.iStartCaretPos - sResStruct.iCurLength;
					sResStruct.iStarted 	= 1;
					sResStruct.iFound 		= 1;
				}
				
				// ---------------------------------------------------------------------------------------
				// Si on a trouvé le noeud de fin
				if ((sResStruct.iCurLength + oCurNode.nodeValue.length) > ieStruct.iEndCaretPos)
				{
					sResStruct.oEndNode 	= oCurNode;
					sResStruct.iEndOffset	= ieStruct.iEndCaretPos - sResStruct.iCurLength;
					sResStruct.iEnded 		= 1;
					sResStruct.iFound 		= 1;
					sResStruct.iLevel 	   -= 1; // On remonte donc on décrémente le niveau
					return sResStruct;
				}
			}
			else
			// -------------------------------------------------------------------------------------------
			// Si on a passé une structure FF
			{
			
				// ---------------------------------------------------------------------------------------
				// Si on a trouvé le noeud de départ
				if (sResStruct.iStarted == 0 && oCurNode == ffStruct.startContainer)
				{
					sResStruct.oStartNode 	= oCurNode;
					sResStruct.iStartOffset	= ffStruct.startOffset;
					sResStruct.iStarted 	= 1;
					sResStruct.iFound 		= 1;
				}
				
				// ---------------------------------------------------------------------------------------
				// Si on a trouvé le noeud de fin
				if (oCurNode == ffStruct.endContainer)
				{
					sResStruct.oEndNode 	= oCurNode;
					sResStruct.iEndOffset	= ffStruct.endOffset;
					sResStruct.iEnded 		= 1;
					sResStruct.iFound 		= 1;
					sResStruct.iLevel 	   -= 1; // On remonte donc on décrémente le niveau
					return sResStruct;
				}
			
			}
			
			// -------------------------------------------------------------------------------------------
			// On met à jour la taille courante depuis le début
			sResStruct.iCurLength += oCurNode.nodeValue.length;
		}
		
		// -----------------------------------------------------------------------------------------------
		// On parcourt l'arbre avec les enfants
		for (var i = 0; i < oCurNode.childNodes.length; i++)
		{
			// -------------------------------------------------------------------------------------------
			// Traitement préfixé
			if (iLevel == 0 && sResStruct.iStarted == 0)
				sResStruct.oStartRootNode = oCurNode.childNodes[i];
			
			// -------------------------------------------------------------------------------------------
			// Parcours récursif
			sResStruct.oNode	= oCurNode.childNodes[i];
			sResStruct.iLevel   = iLevel + 1;
			sResStruct = t._RangeFindNodes(ieStruct,ffStruct,sResStruct);
			
			// -------------------------------------------------------------------------------------------
			// Traitement postfixé
			if (iLevel == 0 && sResStruct.iEnded == 1)
				sResStruct.oEndRootNode = oCurNode.childNodes[i];
			
			// -------------------------------------------------------------------------------------------
			// Si on est à la fin
			if (sResStruct.iEnded == 1)
			{
				sResStruct.iLevel -= 1; // On remonte donc on décrémente le niveau
				return sResStruct;
			}
		}
		
		// -----------------------------------------------------------------------------------------------
		// On remonte donc on décrémente le niveau
		sResStruct.iLevel -= 1;
		return sResStruct;
	},
	
	
	// ---------------------------------------------------------------------------------------------------
	// Get Range
	// ---------------------------------------------------------------------------------------------------
	RangeGet : function()
	{
		var t = this, oSel, oRng, iStart,iEnd;
		
		if (t.isIE)
		{
			// Récupération de la sélection
			oSel = t.doc.selection;
			oRng = oSel.createRange();
			iStart = 0 - oRng.moveStart ('character', t.doc.body.innerHTML.length * - 1);
			iEnd = 0 - oRng.moveEnd ('character', t.doc.body.innerHTML.length * - 1);
			
			// Recherche des noeuds
			return t._RangeFindNodes({iStartCaretPos : iStart, iEndCaretPos : iEnd},null,null);
		}
		else
		{
			// Récupération de la sélection
			oSel = t.win.getSelection();
			oRng = oSel.rangeCount > 0 ? oSel.getRangeAt(0) : (oSel.createRange ? oSel.createRange() : this.doc.createRange());
			
			// Recherche des noeuds
			return t._RangeFindNodes(null,oRng,null);
		}
		return sRes;
	}


}
var mko_wysiwyg = new wysiwyg();

