// RATOOLI EDITOR
// A non Iframe, simple and powerful WYSIWYG javascript editor


// References:
// http://www.mozilla.org/editor/midasdemo
// http://msdn.microsoft.com/es-es/library
// http://blog.josh420.com/archives/2007/11/determine-if-any-other-outside-element-was-clicked-with-javascript.aspx (sam comment)
// http://www.disegnocentell.com.ar/notas2.php?id=180

// Some design ideas from:
// http://nicedit.com
// http://www.openwebware.com
// http://sites.google.com
// http://wave.google.com


////////////////
// Initialize //
////////////////
var isStarted = false;
var elemActive = null;
var editor;
var toolbar_box;

function ratooli(){
	//document.getElementById(editor).style.zIndex = 101;
	//alert(document.getElementById("panel").offsetTop);
	editor = document.getElementById(editor_id);
	toolbar_box = document.getElementById(toolbar_box_id);
	getModules();
}


//////////////////////////////////////
// Get the modules content via Ajax //
//////////////////////////////////////
function getModules(){
	var modules = editor.getElementsByTagName("div");
	for (i=0; i<modules.length; i++){
		if (modules[i].className == "module") miAjax(modules_path + modules[i].getAttribute("name"), modules[i]);
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This function emulate onblur accions. If click outside, the editor buttons will be disabled                                    // 
// Idea from: http://blog.josh420.com/archives/2007/11/determine-if-any-other-outside-element-was-clicked-with-javascript.aspx (sam comment) //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function clickedOutsideElement(theElem,obj) {
	while(theElem != null) {
		if(theElem == obj) return true;
		theElem = theElem.parentNode;
	}
	return false;
}

document.onmousedown = function(e){
	if (isStarted){
		var evt = (window.event)? window.event : e;
		var targ = (evt.target)? evt.target : evt.srcElement;
		if (targ != null) {
			if(targ.nodeType == 3) targ = targ.parentNode;
		}
		if (clickedOutsideElement(targ,editor) || clickedOutsideElement(targ,toolbar_box)){
			if (elemActive != editor && elemActive != null){
				elemActive.style.display = "none";
				elemActive = editor;
				activateButtons(true,null);
			}else{
				if (elemActive == null && clickedOutsideElement(targ,editor)){
					activateButtons(true,null);
					elemActive = editor;
				}
			}
		}else{
			if (elemActive == editor || elemActive != null){
				if (elemActive != editor) elemActive.style.display = "none";
				elemActive = null;
				activateButtons(false,null);
			}
		}
	}
};

function activateButtons(sn,thisButton){
	var buttons = document.getElementsByTagName("button");
	var n;
	for (b=0; b<buttons.length; b++){
		if (buttons[b] != thisButton){
			buttons[b].disabled = !sn;
		}else{
			if (thisButton != null) n = b;
		}
	}
	images = toolbar_box.getElementsByTagName("img");
	for (i=0; i<images.length; i++){
		if (i != n){
			transp = (sn)? 100 : 25;
			if (document.selection){
				images[i].style.filter = "alpha(opacity=" + transp + ")";
			}else{
				images[i].style.opacity = transp/100;
			}
		}
	}
}

/////////////////////
// MiAjax function //
/////////////////////
function createRequestObject(){
	var peticio;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
       	peticio = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        peticio = new XMLHttpRequest();
	}
	return peticio;
}

var http = new Array();
var n = 0;

function miAjax(url,capa){
    var act = n++;	
    http[act] = createRequestObject();
    http[act].open('get', url);
    http[act].onreadystatechange = function() {
    	if (http[act].readyState == 4) {           
	  	    var dades = http[act].responseText;			
            if (http[act].status == 200 || http[act].status == 304) {      			
                if (dades != "") capa.innerHTML = dades;
			}
	  	}
	}
	http[act].send(null);
}


////////////////////////
// The action buttons //
////////////////////////
function tbclick(boto){		
	if (boto.id.indexOf("Insert-") == 0){
		//In case of a Insert Button
		activateButtons(false,boto);
		if (boto.id == "Insert-Link"){
			if (insertHTML() == false){
				//Falla amb FF mirar insertHTML
				alert(language['No text selected']);
				return false;
			}				
		}else{
			insertHTML();	
		}
		if (boto.parentNode.hasChildNodes()){
			form = boto.parentNode.lastChild;
			if (elemActive != form && form.nodeName.toLowerCase() == "form"){
				form.style.display = "block";
				elemActive = form;
			}
		}
		form.elements[0].focus();
		//alert(document.body.innerHTML);		
	}else{
		//The rest of buttons, format actions, first of all
		document.execCommand(boto.id, false, null);
		editor.focus();
	}
}

/*
function createPanelParameters(){
	var panel = document.createElement("form");
	panel.setAttribute("action" , "javascript:submitForm();");
	panel.setAttribute("id", "panelParameters");	
	panel.setAttribute("style", "position:fixed; border:2px solid; padding:5px; float:left; display:none; background-color:#FFF");
 	toolbar = document.getElementById(toolbar_box);
	mainNode = toolbar.parentNode;
	mainNode.insertBefore(panel,toolbar);
}
*/

function createPanelParameters(boto){
	switch (boto){
		case "Insert-Image":
			inputs = language['Url'] + ": <input type=\"text\" value=\"\" /><br/>";
			inputs += "<input type=\"button\" onclick=\"\" value=\"\" />";
			break;

		case "Insert-Link":
			inputs = language['Url'] + "<br/>";
			inputs += "<input name=\"url\" type=\"text\" value=\"http://terra.es\" /><br/>";
			inputs += "<br/>";
			inputs += language['Where link open'] + "<br/>";
			inputs += "<input type=\"radio\" name=\"targeta\" value=\"_self\" />" + language['Self window'] + "<br/>";
			inputs += "<input type=\"radio\" name=\"targeta\" checked value=\"_blank\" />" + language['Blank window'] + "<br/>";
			inputs += "<br/>";
			inputs += "<input type=\"submit\" value=\"" + language['Insert link button'] + "\" />";
			break;

		case "Insert-Module":
			break;	

		case "Insert-Table":
			break;
	}
	name = "form" + boto.split("-")[1];
	return "<form class=\"formParameters\" name=\"" + name + "\" action=\"javascript:submitForm('" + name + "');\" style=\"display:none; position:absolute; border:1px solid; padding:5px; background-color:#FFF; z-index:1\">" + inputs + "</form>";
}

function insertHTML(){
	if (document.selection){
		//Internet Explorer case
		var txt = document.selection.createRange().text;
		document.selection.createRange().pasteHTML("<a id='link'>" + txt + "</a>");
		sn = (txt == "")? false : true;
	} else {
		//Firefox case
		var txt = window.getSelection();
		document.execCommand("insertHTML",false,"<a id='link'>" + txt + "</a>");
		sn = (txt.value == "")? false : true;
		//Compte que falla amb ff!!
	}
	return sn;
}

function submitForm(name){
	switch (name){
		case "formLink":
			var form = document.formLink;
			for (t = 0; t < form.targeta.length; t++){
				if (form.targeta[t].checked) targeto = form.targeta[t].value;
			}
			text = form.url.value;
			par = document.getElementById("link");
			par.href = text;
			par.removeAttribute("id");
			par.target = targeto;
			break;
			
		case "formTable":
			//Idea from: http://www.disegnocentell.com.ar/notas2.php?id=180
			break;
	}
	form.style.display = "none";
}


// Select actions
function Select(selectname) {
	var cursel = document.getElementById(selectname).selectedIndex;
	/* First one is always a label */
	if (cursel != 0) {
		var selected = document.getElementById(selectname).options[cursel].value;
		document.execCommand(selectname, false, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
	editor.focus();
}


///////////////////////
// Start/stop editor //
///////////////////////
function Edition(sn){

	//Evaluate compatibility browser
	//alert(navigator.appCodeName);
	//alert(navigator.appName);
	//alert(navigator.appVersion);
	//alert(navigator.platform);
	noComp = false;
	if (noComp){
		
		// If problems with the browser
		alert ("Your browser doesn't support this editor");
		
	}else{		
		if (sn){
			//Enable edition
			editor.contentEditable = true;
			createToolbar();
			isStarted = true;
			elemActive = editor;			
			//document.getElementById(editor).focus();
			
		}else{
			//Disable edition
			editor.contentEditable = false;
			toolbar_box.innerHTML = "";
			isStarted = false;
			elemActive = null;
		}
	}
}


////////////////////
// Create toolbar //
////////////////////
function createToolbar(){
	var buttons = new Array(
		"",				   
		"Bold",
		"Italic",
		"Underline",
		"StripWordHTML",
		"",
		"JustifyLeft",
		"JustifyCenter",
		"JustifyRight",
		"JustifyFull",
		"",
		"InsertOrderedList",
		"InsertUnorderedList",
		"Outdent",
		"Indent",
		"",
		"Undo",
		"Redo"
	);
	
	/*
		"InsertTable",
		"InsertImage",
		"InsertVideo",
		"",*/

	buttons_panel = "<table style='width:100%' cellpadding='0' cellspacing='0'><tr>";
	buttons_panel += "<td><select id=\"fontsize\" onchange=\"Select(this.id);\" class=\"botoTitol\"><option value='Tamany'>" + language['Tamany'] + "</option><option value='3'>" + language['Normal'] + "</option><option value='5'>" + language['Title'] + "</option><option value='4'>" + language['Subtitle'] + "</option></select></td>";
	for (b=0; b<buttons.length; b++){
		if (buttons[b] == ""){
			buttons_panel += "<td class='cellSeparador'></td>";
		}else{
			//buttons_panel += "<td><input type='button' class='botoEditor' id='" + buttons[b] + "' title='" + language[buttons[b]] + "' onclick='tbclick(this.id)' style='background-image:url(" + images_path + buttons[b] + ".png)' /></td>";
			buttons_panel += "<td>";
			buttons_panel += "<button type=\"button\" class=\"botoEditor\" id=\"" + buttons[b] + "\" title=\"" + language[buttons[b]] + "\" onclick=\"tbclick(this)\"><img src=\"" + images_path + buttons[b] + ".png" + "\" /></button>";
			if (buttons[b].indexOf("Insert-") == 0) buttons_panel += createPanelParameters(buttons[b]);
			buttons_panel += "</td>";
		}
	}
	//buttons_panel += "<td align='right'><input type='button' class='boto' onclick='desa_pagina()' style='background-image:url(" + images_path + "Save.png)' value='" + language['Save'] + "'/> <input type='button' class='boto' onclick='confirma_desactiva()' style='background-image:url(" + images_path + "Cancel.png)' value='" + language['No save'] + "' /></td>";
	//buttons_panel += "<td align='right'><input type='button' class='boto' onclick='desa_pagina()' value='" + language['Save'] + "'/> <input type='button' class='boto' onclick='confirma_desactiva()' value='" + language['No save'] + "' /></td>";

	//panellBotons += "<td align='right'><input type='button' class='botoLlarg' value='" + language['Save'] + "' name='Save' /></td>";
	buttons_panel += "</tr></table>";
	//document.write(panellBotons);
	toolbar_box.innerHTML = buttons_panel;
}
