// Mozilla Rich Text Editing Modificat
var command = "";

//Para insertar cosas, como por ejemplo una tabla
function insertNodeAtSelection(win, insertNode)
  {
      // get current selection
      var sel = win.getSelection();

      // get the first range of the selection
      // (there's almost always only one range)
      var range = sel.getRangeAt(0);

      // deselect everything
      sel.removeAllRanges();

      // remove content of current selection from document
      range.deleteContents();

      // get location of current selection
      var container = range.startContainer;
      var pos = range.startOffset;

      // make a new range for the new selection
      range=document.createRange();

      if (container.nodeType==3 && insertNode.nodeType==3) {

        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.nodeValue);

        // put cursor after inserted text
        range.setEnd(container, pos+insertNode.length);
        range.setStart(container, pos+insertNode.length);

      } else {


        var afterNode;
        if (container.nodeType==3) {

          // when inserting into a textnode
          // we create 2 new textnodes
          // and put the insertNode in between

          var textNode = container;
          container = textNode.parentNode;
          var text = textNode.nodeValue;

          // text before the split
          var textBefore = text.substr(0,pos);
          // text after the split
          var textAfter = text.substr(pos);

          var beforeNode = document.createTextNode(textBefore);
          afterNode = document.createTextNode(textAfter);

          // insert the 3 new nodes before the old one
          container.insertBefore(afterNode, textNode);
          container.insertBefore(insertNode, afterNode);
          container.insertBefore(beforeNode, insertNode);

          // remove the old node
          container.removeChild(textNode);

        } else {

          // else simply insert the node
          afterNode = container.childNodes[pos];
          container.insertBefore(insertNode, afterNode);
        }

        range.setEnd(afterNode, 0);
        range.setStart(afterNode, 0);
      }

      sel.addRange(range);
  };

//Sólo hace falta para el color...
function getOffsetTop(elm) {

  var mOffsetTop = elm.offsetTop;
  var mOffsetParent = elm.offsetParent;

  while(mOffsetParent){
    mOffsetTop += mOffsetParent.offsetTop;
    mOffsetParent = mOffsetParent.offsetParent;
  }
 
  return mOffsetTop;
}

//Sólo hace falta para el color...
function getOffsetLeft(elm) {

  var mOffsetLeft = elm.offsetLeft;
  var mOffsetParent = elm.offsetParent;

  while(mOffsetParent){
    mOffsetLeft += mOffsetParent.offsetLeft;
    mOffsetParent = mOffsetParent.offsetParent;
  }
 
  return mOffsetLeft;
}

function boto(id)
{
  if ((id == "forecolor") || (id == "hilitecolor")) {
    parent.command = id;
    buttonElement = document.getElementById(id);
    //document.getElementById("colorpalette").style.left = getOffsetLeft(buttonElement);
    //document.getElementById("colorpalette").style.top = getOffsetTop(buttonElement) + buttonElement.offsetHeight;
    //document.getElementById("colorpalette").style.visibility="visible";
  } else if (id == "CreateLink") {
    var theUrl = prompt("Enter a URL:", "http://");
	 //var theTarget = (confirm("_parent or _blank"))? "_parent" : "_blank";
	 var theTarget = "_blank";

//http://www.sitepoint.com/forums/showthread.php?t=312803

theSelection = document.getElementById("editor").contentWindow.getSelection();
theRange = theSelection.getRangeAt(0);
var newLink = document.getElementById("editor").contentWindow.document.createElement("a");
var linkText = document.getElementById("editor").contentWindow.document.createTextNode(theSelection);
newLink.target = theTarget;
newLink.href = theUrl;
newLink.appendChild(linkText);
theRange.deleteContents();
theRange.insertNode(newLink);
    
	 /*
	 if ((szURL != null) && (szURL != "")) {
      document.getElementById('editor').contentWindow.document.execCommand("CreateLink",false,szURL);
    }
	 */
  } else if (id == "InsertImage") {
    imagePath = prompt('Enter Image URL:', 'http://');
    if ((imagePath != null) && (imagePath != "")) {
      document.getElementById('edit').contentWindow.document.execCommand('InsertImage', false, imagePath);
    }
  } else if (id == "CreateTable") {
    e = document.getElementById("editor");
    rowstext = prompt("enter rows");
    colstext = prompt("enter cols");
    rows = parseInt(rowstext);
    cols = parseInt(colstext);
    if ((rows > 0) && (cols > 0)) {
      table = e.contentWindow.document.createElement("table");
      table.setAttribute("border", "1");
      table.setAttribute("cellpadding", "2");
      table.setAttribute("cellspacing", "2");
      tbody = e.contentWindow.document.createElement("tbody");
      for (var i=0; i < rows; i++) {
        tr =e.contentWindow.document.createElement("tr");
        for (var j=0; j < cols; j++) {
          td = e.contentWindow.document.createElement("td");
          br = e.contentWindow.document.createElement("br");
          td.appendChild(br);
          tr.appendChild(td);
        }
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);      
      insertNodeAtSelection(e.contentWindow, table);
    }
  } else {
    document.getElementById('editor').contentWindow.document.execCommand(id, false, null);
  }
}

//Sirve para título, por ejemplo...
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.getElementById('editor').contentWindow.document.execCommand(selectname, false, selected);
    document.getElementById(selectname).selectedIndex = 0;
  }
  document.getElementById('editor').contentWindow.focus();
}

/*
function dismisscolorpalette()
{
  document.getElementById("colorpalette").style.visibility="hidden";
}
*/

function Start() {
  if (document.attachEvent){
	document.getElementById('editor').contentWindow.document.body.contentEditable = true;
  } else {
	document.getElementById('editor').contentWindow.document.designMode = "on";
  }
  try {
    document.getElementById('editor').contentWindow.document.execCommand("undo", false, null);
  }  catch (e) {
    alert("This demo is not supported on your level of Mozilla.");
  }

/*
  if (document.addEventListener) {
    document.addEventListener("mousedown", dismisscolorpalette, true);
    document.getElementById("edit").contentWindow.document.addEventListener("mousedown", dismisscolorpalette, true);
    document.addEventListener("keypress", dismisscolorpalette, true);
    document.getElementById("edit").contentWindow.document.addEventListener("keypress", invertIELineBreakCapability, true);
  } else if (document.attachEvent) {
    document.attachEvent("mousedown", dismisscolorpalette, true);
    document.getElementById("edit").contentWindow.document.attachEvent("mousedown", dismisscolorpalette, true);
    document.attachEvent("keypress", dismisscolorpalette, true);
    document.getElementById("edit").contentWindow.document.attachEvent("onkeypress", invertIELineBreakCapability, true);
  }
*/
}

function invertIELineBreakCapability(e) {
	//Fonts:
	//http://www.forosdelweb.com/f13/detectar-enter-textbox-421922/
	//OpenWYSIWYG
	//http://msdn.microsoft.com/en-us/library/ms536656(VS.85).aspx
	
	var editor = document.getElementById("editor").contentWindow;
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla == 13) {
		var sel = editor.document.selection;
		if (sel!=null) {
    		var rng = sel.createRange();
    		if (rng!=null)
       		rng.pasteHTML("<br>");
		}
		editor.event.cancelBubble = true;
	    editor.event.returnValue = false;
		rng.select();
	    rng.moveEnd("character", 1);
	    rng.moveStart("character", 1);
	    rng.collapse(false);
	    return false;
	}  
}

function create_toolbar(){
	var botons = new Array(
		"",				   
		"Bold",
		"Italic",
		"Underline",
		"StripWordHTML",
		"",
		"JustifyLeft",
		"JustifyCenter",
		"JustifyRight",
		"JustifyFull",
		"",
		"InsertOrderedList",
		"InsertUnorderedList",
		"Outdent",
		"Indent",
		"",
		"CreateLink",
		"UnLink",
		"",
		"Undo",
		"Redo"
	);
	
	/*
		"InsertTable",
		"InsertImage",
		"InsertVideo",
		"",*/

	panellBotons = "<table style='width:100%' cellpadding='0' cellspacing='0'><tr>";
	panellBotons += "<td class='cellBotoLlarg'><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<botons.length; b++){
		if (botons[b] == ""){
			panellBotons += "<td class='cellSeparador'></td>";
		}else{
			panellBotons +=	"<td class='cellBotoPetit'><button type='button' class='botoPetit' id='" + botons[b] + "' title='" + language[botons[b]] + "' onclick='boto(this.id)' /><img src='editor/images/" + botons[b] + ".png' /></button></td>";
		}
	}
	panellBotons += "<td align='right'><button type='button' class='botoLlarg' onclick='desa_pagina()'/><table><tr><td><img src='editor/images/Save.png' /></td><td>" + language['Save'] + "</td></tr></table></button><button type='button' class='botoLlarg' onclick='confirma_desactiva()' /><table><tr><td><img src='editor/images/Cancel.png' /></td><td>" + language['No save'] + "</td></tr></table></button></td>";

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