/**
 * Fichier de base de l'éditeur
 *
 */

var largeurEditeur = '480px'
var hauteurEditeur = '150px';
var imgSrc = 'images/RSeditor';

// tableau des types d'entête
var heading = [
	 {cle:'',valeur:'Formats'}
	,{cle:'<p>',valeur:'Paragraphe'} 
	,{cle:'<H1>',valeur:'En-tête 1'}
	,{cle:'<H2>',valeur:'En-tête 2'}
	,{cle:'<H3>',valeur:'En-tête 3'}
	,{cle:'<H4>',valeur:'En-tête 4'}
	,{cle:'<H5>',valeur:'En-tête 5'}
	,{cle:'<H6>',valeur:'En-tête 6'}
]


var toolBox = [
	 {image:imgSrc+'/bold.png',alt: 'Mettre en gras',action: 'textFormat',args: ['bold']}
	,{image:imgSrc+'/italic.png',alt: 'Mettre en italic',action: 'textFormat',args: ['italic']}
	,{image:imgSrc+'/underline.png',alt: 'Souligner',action: 'textFormat',args: ['underline']}
	,{image:imgSrc+'/separator.png',alt:'',action:''}
	,{image:imgSrc+'/alignLeft.png',alt: 'Aligner à gauche',action: 'textFormat',args: ['justifyleft']}
	,{image:imgSrc+'/alignCenter.png',alt: 'Aligner centré',action: 'textFormat',args: ['justifycenter']}
	,{image:imgSrc+'/alignRight.png',alt: 'Aligner à droite',action: 'textFormat',args: ['justifyright']}
	,{image:imgSrc+'/alignJustify.png',alt: 'Aligner justifié',action: 'textFormat',args: ['justifyfull']}
	,{image:imgSrc+'/separator.png',alt:'',action:''}
	,{liste:heading,action: 'setHeading',args: ''}
	,{image:imgSrc+'/unorderedList.png',alt: 'Inserer une liste non ordonée',action: 'textFormat',args: ['insertunorderedlist']}
	,{image:imgSrc+'/orderedList.png',alt: 'Inserer une liste ordonée',action: 'textFormat',args: ['insertorderedlist']}
	,{image:imgSrc+'/link.png',alt: 'Inserer un lien',action: 'createLink',args:''}
	,{image:imgSrc+'/unlink.png',alt: 'Supprimer le lien',action: 'unLink',args:''}
	//,{image:imgSrc+'/image.png',alt: 'Inserer une image',action: 'insertImage',args:''}
	,{image:imgSrc+'/hr.png',alt: 'Inserer une ligne horizontale',action: 'textFormat',args:['inserthorizontalrule']}
	,{image:imgSrc+'/separator.png',alt:'',action:''}
	,{image:imgSrc+'/gomme.png',alt: 'Supprimer le formatage de la sélection',action: 'textFormat',args:['RemoveFormat']}
	,{image:imgSrc+'/source.png',alt: 'Voir la source',action: 'showSource',args: []}
]


Event.observe(window, 'load', RSeditInit, false);

/**
 * Construction des éditeurs de la page
 * Si le mode design n'est pas supporté effectue un retour silencieux
 */
function RSeditInit(){
	if(!checkCompatibility()){
		return;
	}

	var listEl = document.getElementsByClassName('RSedit');
	var nbEl = listEl.length;
	try {
	for(var i = 0; i < nbEl; i++){
		listEl[i].form.onsubmit=saveEditorContent;
		createEditor(listEl[i]);
	}
	}catch(e){}
	/*var listForm = document.getElementsByTagName('form');
	var nbForm = listForm.length;
	for(var i = 0; i< nbForm; i++){
		alert(listForm[i].onsubmit);
		listForm[i].onsubmit=saveEditorContent;
	}*/
}

/**
 * Test de la compatibilité du navigateur avec le mode design
 */
function checkCompatibility(){
	if(document.designMode){
		return true;
	}
	return false;
}

/**
 * Création de l'étideur
 * et masquage du textarea associé
 */
function createEditor(objTextarea){
	// mise en place d'un container
	var container = document.createElement('div');
	//container.setAttribute('style','float:left;');
	var iframeObj = document.createElement('iframe');
	iframeObj.setAttribute('id',objTextarea.name+'Editor');
	iframeObj.setAttribute('name',objTextarea.name+'Editor');
	var containerElement = objTextarea.parentNode.insertBefore(container,objTextarea);
	containerElement.style.clear='left';
	// on insert la frame puis on masque le textarea
	var iframeElement = containerElement.insertBefore(iframeObj,containerElement.firstChild);
	iframeElement.curentAffichage='html';
	iframeElement.style.width=largeurEditeur;
	iframeElement.style.height=hauteurEditeur
	objTextarea.style.display='none';
	
	// activation du mode design
	addEditorEvent(iframeElement.id,objTextarea);
	// mise en place de la barre d'outils
	addEditorTools(iframeElement);
	// mise en place du contenu dans l'editeur
	return;
}

/**
 * Ajout evenement onload su l'editeur
 */
function addEditorEvent(id,objTextarea){
	Event.observe(id, 'load', function(){initEditor(id,objTextarea)}, false);
}

/**
 * Récupération du document de l'éditeur
 * @return object Document
 */
function getEditorBody(id){
	if(document.getElementById(id).contentWindow.document){
		return document.getElementById(id).contentWindow.document;
	} else {
		return document.getElementById(id).contentDocument;
	}
}

/**
 * Activation du mode design
 */
function initEditor(id,objTextarea){
	try{
	var EditorBody = getEditorBody(id);

	//alert(id+':'+EditorBody);
	EditorBody.designMode = 'On';
	EditorBody.body.style.backgroundColor='#fff';
	EditorBody.body.innerHTML = objTextarea.value;
	}catch(e){}
}

/**
 * Mise en place de la barre d'outils pour l'éditeur
 */
function addEditorTools(editorElement){
	
	var toolBarId = 'RSeditorToolBar'+editorElement.id;
	
	var toolBar = document.createElement('div');
	toolBar.setAttribute('class','RSeditorToolBar');
	toolBar.setAttribute('id',toolBarId);
	toolBar.style.background='buttonface';
	toolBar.style.height='21px';
	toolBar.style.margin='0';
	toolBar.style.paddingTop='2px';
	/*toolBar.style.textAlign='left';
	toolBar.style.clear='left';*/
	toolBar.style.width=largeurEditeur;
	var toolBarElement = editorElement.parentNode.insertBefore(toolBar,editorElement);
	
	var toolBoxLength = toolBox.length;
	

	// ajout des boutons et evenements à lma barre d'outils
	for(var i = 0; i < toolBoxLength; i++){
		var tool = toolBox[i];
		var buttonId = editorElement.id+'-'+i;
		
		if(tool.image){
			var button = buildTool(tool.image,tool.alt,buttonId);
		} else {
			var button = buildList(tool,buttonId);
		}
		
		if(i > 0){
			var insertedButton = toolBarElement.insertBefore(button,toolBarElement.lastChild.nextSibling);
		} else {
			var insertedButton = toolBarElement.insertBefore(button,toolBarElement.firstChild);
		}
		//insertedButton.className='RSeditorButton';
		// ajout d'un observateur d'évenement sur le bouton si une action et défini
		// et que l'élément n'est pas une liste
		if(!tool.liste) {
			if(tool.action != ''){
				addButtonEvent(editorElement,buttonId,tool);
			}
		} else {
			if(tool.action != ''){
				addSelectEvent(editorElement,buttonId,tool.action);
			}
		}
	}
}

function addButtonEvent(editorElement,id,tool){
	Event.observe(id,'click',function(){eval(tool.action)(editorElement,tool.args);},false);
	Event.observe(id,'mouseover',function(){setButtonUp(id);},false);
	Event.observe(id,'mouseout',function(){setButtonUp(id, true);},false);
}

function addSelectEvent(editorElement,id,action){
	Event.observe(id,'change',function(){eval(action)(editorElement,id);},false);
}

function setButtonUp(ButtonId,clear){
	if(!clear){
		$(ButtonId).style.borderTop= '1px solid buttonhighlight';
		$(ButtonId).style.borderLeft= '1px solid buttonhighlight';
		$(ButtonId).style.borderBottom= '1px solid buttonshadow';
		$(ButtonId).style.borderRight= '1px solid buttonshadow';
	} else {
		$(ButtonId).style.border='1px solid buttonface';
	}
}

function buildTool(image,alt,id){
	var tool = document.createElement('a');
	var toolImg = document.createElement('img');
	
	toolImg.setAttribute('src',image);
	// on applique les styles
	toolImg.style.border='0';
	toolImg.style.verticalAlign='middle';
	toolImg.style.margin='0';
	toolImg.style.padding='0';
	
	tool.setAttribute('title',alt);
	tool.setAttribute('id',id);
	tool.setAttribute('href','javascript:;');

	tool.style.margin='1px';
	tool.style.padding='0';
	tool.style.border='1px solid buttonface';
	
	tool.appendChild(toolImg);

	return tool;
}

/**
 * Création d'une liste déroulante dans le menu
 * @var object toolBox Objet du tableau global toolBox
 * @var string id Id de l'element à créer
 * @return Object Objet select
 */
function buildList(toolBox,id){
	var tool = document.createElement('select');
	var optionList = toolBox.liste;
	tool.setAttribute('id',id);
	optionList.each(
		function (el){
			/*var theTxt = '';
			for(var a in el){
				theTxt += 'clé : '+a+', valeur : '+el[a]+'<br>';
			}
			document.getElementById('debug').innerHTML = theTxt;
			var opt = new Option(el.valeur,el.cle);*/
			var opt = document.createElement('option');
			opt.setAttribute('value',el.cle);
			opt.appendChild(document.createTextNode(el.valeur));
			tool.appendChild(opt);
		}
	);
	
	return tool;
}

function textFormat(editorElement,format){
	RSeditor = getEditorBody(editorElement.id);
	RSeditor.execCommand(format[0],false,null);
}

function showSource(editorElement){
	var RSeditor = getEditorBody(editorElement.id);
	if(editorElement.curentAffichage == 'html'){
		if(document.all){
			var iHtml = RSeditor.body.innerHTML;
			RSeditor.body.innerText = iHtml;
		} else {
			var iHtml = document.createTextNode(RSeditor.body.innerHTML);
			RSeditor.body.innerHTML= '';
			RSeditor.body.appendChild(iHtml);
		}
		editorElement.curentAffichage = 'src';
	} else {
		if(document.all){
			var iText = RSeditor.body.innerText;
			RSeditor.body.innerHTML = iText;
		} else {
			var iHtml = RSeditor.body.ownerDocument.createRange();
			iHtml.selectNodeContents(RSeditor.body);
			RSeditor.body.innerHTML = iHtml.toString();
		}
		editorElement.curentAffichage = 'html';
	}
}

function createLink(editorElement){
	var url = prompt("Entrez l'url", "http://");
	RSeditor = getEditorBody(editorElement.id);
	RSeditor.execCommand('createlink',false,url);
}

function unLink(editorElement){
	RSeditor = getEditorBody(editorElement.id);
	RSeditor.execCommand('unlink',false,null);
}

function insertImage(editorElement){
	var url = prompt("Entrez l'url de l'image", "http://");
	RSeditor = getEditorBody(editorElement.id);
	RSeditor.execCommand('insertimage',false,url);
}

function setHeading(editorElement,selectId){
	var objList = $(selectId);
	var hType = objList.options[objList.selectedIndex].value;
	if(hType !=''){
		RSeditor = getEditorBody(editorElement.id);
		RSeditor.execCommand('formatblock',false,hType);
	}
}

function saveEditorContent(){
	var listEl = document.getElementsByClassName('RSedit');
	var nbEl = listEl.length;
	for(var i = 0; i < nbEl; i++){
		var editorId = listEl[i].name+'Editor';
		var RSeditor = getEditorBody(editorId);
		var src = RSeditor.body.innerHTML;
		listEl[i].value=src;
	}
}
