var whizzywig_version = 'Whizzywig v50'; 

//CONFIG VARIABLES (please set outside script)
var buttonPath="scripts/whizzery/buttons/";  //path to toolbar button images;  unset or "textbuttons" means don't use images
var cssFile="scripts/whizzery/simple.css";     //url of CSS stylesheet to attach to edit area
var imageBrowse; //path to page for image browser
var linkBrowse;  //path to page for link browser
var idTa;        //id of the textarea to whizzywig (param to makeWhizzyWig)
var gentleClean=false;  //if true, cleanUp preserves spans, inline styles and classes
var controls = "fontname fontsize newline bold italic underline color hilite | image link unlink cleanup | number bullet indent outdent | left center right justify | undo redo";
//OTHER GLOBALS
var oWhizzy; //object of Whizzy
var rng;  //range at current selection
var sel;  //current selection
var papa; //parent of current selection IE only
var trail = ''; //DOM tree path IE only

function popup(page,popupname,height,width) {
var topPosition = (screen.height - height) / 2;
var leftPosition = (screen.width - width) / 2;
var windowprops = "width=" + width + ",height=" + height + ",top=" + topPosition + ",left=" + leftPosition + ",location=no,menubar=no,toolbar=no,scrollbars=no,resizable=no,status=no";
newWindow = window.open(page,popupname,windowprops);
}

function offsetLeft(elem)
{
	var p = elem.offsetParent;
	if(!p)
		return elem.offsetLeft;
	else
		return elem.offsetLeft+offsetLeft(p);
}

function offsetTop(elem)
{
	var p = elem.offsetParent;
	if(!p)
		return elem.offsetTop;
	else
		return elem.offsetTop+offsetTop(p);
}


function iframe(src,nom,elementid)
{
var c = document.getElementById('iframe1');

if(c.style.display=="none")
  {
  //set source
  c.src='scripts/'+src;
  
  // get element position
  var mx=0;
  var my=0;
  var xpos=50;
  var ypos=100;
  mx = offsetLeft(document.getElementById(elementid));
  my = offsetTop(document.getElementById(elementid));
 
 if(mx>0)xpos = mx+0;
 if(my>0)ypos = my+25 - 25;
  
  // set the position
  c.style.left = xpos + "px";
  c.style.top = ypos + "px";

  //open
  c.style.display = "";
  } 
else
  {
  c.style.display="none";
  c.src="";
  }

return false;
}

function colorpicker(type)
{
var c = document.getElementById('iframe1');
c.style.width="210px";
c.style.height="160px";
iframe("whizzery/palette.html?type="+type+"","palette",'color');

return false;
}

function imagepicker()
{
var c = document.getElementById('iframe1');

c.style.width="398px";
c.style.height="120px";
iframe("whizzery/image.html?rte=edited&command=forecolor","image",'image');

return false;
}

function urlpicker()
{
var c = document.getElementById('iframe1');
c.style.width="398px";
c.style.height="120px";
iframe("whizzery/url.html","link",'link');

return false;
}

function makeWhizzyWig(txtArea, controls){ // make a WhizzyWig from the textarea
 if ((navigator.userAgent.indexOf('Safari') != -1 ) || !document.getElementById || !document.designMode ) {//no designMode
  alert("Whizzywig "+t("editor not available for your browser"));
  return;
 }
 idTa = txtArea;
 var taContent = o(idTa).defaultValue ? o(idTa).defaultValue : o(idTa).innerHTML ? o(idTa).innerHTML: ''; //anything in the textarea?
 taWidth = o(idTa).style.width ? o(idTa).style.width : o(idTa).cols + "em";  //grab the width and...
 taHeight = o(idTa).style.height ? o(idTa).style.height : o(idTa).rows + "em";  //...height from the textarea
 //o(idTa).style.color = '#000';
 o(idTa).style.zIndex = '2';
 if (!o(idTa).rows) o(idTa).rows='50';//IE won't use %
 h(idTa);
 var frm=o(idTa).parentNode;
 if (frm.addEventListener) frm.addEventListener("submit", syncTextarea, false);
  else frm.attachEvent("onsubmit", syncTextarea);

 w('<style type="text/css">.whizzybutton {vertical-align:middle;padding:0;margin:4px 0} select{vertical-align:middle;margin:1px;font-size:10px;}  .ctrl {font-family:verdana,arial,helvetica;font-size:11px;background:#FFF4F4; border:1px solid ButtonShadow;padding:0px;width:100%;} #sourceTa{color:#000;font-family:mono;}</style>');
 var sels = 'fontname fontsize';
 var buts = ' bold italic underline | left center right | number bullet indent outdent | undo redo  | color hilite rule cleanup | link unlink image | html ';
// var tbuts = ' tstart add_row_above add_row_below delete_row | add_column_before add_column_after delete_column | table_in_cell';
 //var t_end = ''; //table controls end, if needed

 //buts += tbuts;
 controls = controls.toLowerCase();
 if (!controls || controls == "all") controls = sels +' newline '+ buts +' source';
// else controls += tbuts;
 w('<div id="CONTROLS" class="ctrl" >');
 gizmos = controls.split(' ');
 for (var i = 0; i < gizmos.length; i++) {
   if (gizmos[i]){ //make buttons and selects for toolbar, in order requested
      if (gizmos[i] == 'tstart') {
        w('<div id="TABLE_CONTROLS" style="display:none" unselectable="on">');
        t_end = '</div>';
      }
      else if (gizmos[i] == '|') w(' <img align="absmiddle" src="'+buttonPath+'separator.gif" border="0"> ');
      else if (gizmos[i] == 'newline') w('<br>');
    else if (sels.indexOf(gizmos[i]) != -1) makeSelect(gizmos[i])
    else if (buts.indexOf(gizmos[i]) != -1) makeButton(gizmos[i]);
   }
 }
 //w(t_end) //table controls end

 w('</div>'); //controls end
 w('<div class="ctrl" id="showWYSIWYG" style="display:none;"><button type="button" class="" onclick="showDesign();">'+t("Cacher la source")+'</button></div>');
 
 w('<iframe style="width:'+taWidth+';height:'+taHeight+';border:1px inset #000;" src="javascript:;" id="whizzyWig"></iframe><br>');

 w('<iframe scrolling=no frameborder=no src="" id="iframe1" style="padding:1px;overflow:visible;border:1px solid gray;position:absolute;display:none;left:50px;top:50px;"></iframe>');

 var startHTML = "<html>\n";
 startHTML += "<head>\n";
 if (cssFile) {
  startHTML += '<link media="all" type="text/css" href="'+ cssFile +'" rel="stylesheet">\n';
 }
 startHTML += "</head>\n";
 startHTML += "<body>\n";
 startHTML += tidyD(taContent);
 startHTML += "</body>\n";
 startHTML += "</html>";
 
 oWhizzy = o("whizzyWig").contentWindow;
 try {
	 oWhizzy.document.designMode = "on";
 } catch (e) { //not set? try again
  setTimeout('oWhizzy.designMode = "on";', 100);
 }
 if (oWhizzy.addEventListener)oWhizzy.addEventListener("keypress", kb_handler, true); //keyboard shortcuts for Moz

 oWhizzy.document.open();
 oWhizzy.document.write(startHTML);
 oWhizzy.document.close();

 if (document.frames) oWhizzy.document.designMode = "On"; 
 /*
 if (document.frames) { //IE
  oWhizzy = frames['whizzyWig'];
 } else { //Moz
  oWhizzy = o("whizzyWig").contentWindow;
  try {
    o("whizzyWig").contentDocument.designMode = "on";
  } catch (e) { //not set? try again
    setTimeout('o("whizzyWig").contentDocument.designMode = "on";', 100);
  }
  oWhizzy.addEventListener("keypress", kb_handler, true); //make keyboard shortcuts work for Moz
 }
 oWhizzy.document.open();
 oWhizzy.document.write(startHTML);
 oWhizzy.document.close();
 if (document.frames) oWhizzy.document.designMode = "On";
 */
 oWhizzy.focus();
 whereAmI();
} //end makeWhizzyWig


function makeButton(button){  // assemble the button requested NEW
 var ucBut = button.substring(0,1).toUpperCase();
 ucBut += button.substring(1);
 ucBut = t(ucBut.replace(/_/g,' '));
   var butHTML = '<a href="javascript:makeSo(\''+button+'\');"><img id="'+button+'" class="whizzybutton" src="'+buttonPath+button+'.gif" border="0"/></a>\n';
 w(butHTML);
}

/*
function fGo(id){ return '<div id="'+id+'_FORM" style="display:none"><hr> '; }//new form

function fNo(txt,go){ //form do it/cancel buttons
 return ' <input type="button" onclick="'+go+'" value="'+txt+'"> <input type="button" onclick="hideDialogs();" value='+t("Cancel")+'>';
}*/

function makeSelect(select){ // assemble the <select> requested
 if (select == 'formatblock') {
  var h = "Heading";
 var values = ["<p>", "<p>", "<h1>", "<h2>", "<h3>", "<h4>", "<h5>", "<h6>", "<address>", "insHTML<big>",  "insHTML<small>", "insHTML<code>", "<pre>"];
 var options = [t("Choose style")+":", t("Paragraph"), t(h)+" 1 ", t(h)+" 2 ", t(h)+" 3 ", t(h)+" 4 ", t(h)+" 5 ", t(h)+" 6", t("Address"), t("Big"), t("Small"), t("Computer code"), t("Fixed width<pre>")];
 } else if (select == 'fontname') {
 var values = ["Verdana, Arial, Helvetica, sans-serif", "Arial, Helvetica, sans-serif", "Comic Sans MS, fantasy", "Courier New, Courier, mono", "Georgia, serif", "Times New Roman, Times, serif", "Verdana, Arial, Helvetica, sans-serif"];
 var options = [t("Police")+":", "Arial", "Comic", "Courier New", "Georgia", "Times New Roman", "Verdana"];
 } else if (select == 'fontsize') {
  var values = ["3", "1", "2", "3", "4", "5", "6", "7"];
  var options = [t("Taille")+":", "1 "+t("Small"), "2", "3", "4", "5", "6", "7 "+t("Big")];
 } else { return }
 w('<select id="' + select + '" onchange="doSelect(this.id);">');
 for (var i = 0; i < values.length; i++) {
  w('<option value="' + values[i] + '">' + options[i] + '</option>');
 }
 w('</select>');
}

function makeSo(command, option) {  //format selected text or line in the whizzy
 whereAmI();
 //hideDialogs();
 if (!document.all) oWhizzy.document.execCommand('useCSS',false, true); //no spans for bold, italic
 if ("leftrightcenterjustify".indexOf(command) !=-1) command = "justify" + command;
 else if (command == "number") command = "insertorderedlist";
 else if (command == "bullet") command = "insertunorderedlist";
 else if (command == "rule") command = "inserthorizontalrule";

 switch (command) {

  case "color":colorpicker('forecolor');break;
  case "hilite" :colorpicker('hilitecolor'); break;
  case "image" : imagepicker(); break;
  case "cleanup" : cleanUp();break;
  case "link" : if (textSel()) urlpicker(); break;
  case "html" : showHTML(); break;
  default: oWhizzy.document.execCommand(command, false, option);
 }
 oWhizzy.focus;
}

function doSelect(selectname) {  //select on toolbar used - do it
 whereAmI();
 var idx = o(selectname).selectedIndex;
 var selected = o(selectname).options[idx].value;

 if ((selected.indexOf('insHTML') === 0)) {
  if (textSel()) insHTML(selected.replace(/insHTML/,''));
 } else {
 var cmd = selectname;
 oWhizzy.document.execCommand(cmd, false, selected);
 }
 o(selectname).selectedIndex = 0;
 oWhizzy.focus();
}

function cleanUp(){  //clean up crud inserted by Micro$oft Orifice
 oWhizzy.document.execCommand("removeformat",false,null);
 whereAmI();
 var h = oWhizzy.document.body.innerHTML;
 if (!gentleClean) {
	h = h.replace(/<\/?(SPAN|DEL|INS|DIR)[^>]*>/gi, "")
	.replace(/\b(CLASS|STYLE)=\"?[^\"]*\"?/gi, "");
 }
 h = h.replace(/<\/?(FONT|SHAPE|V:|O:|F:|F |PATH|LOCK|IMAGEDATA|STROKE|FORMULAS)[^>]*>/gi, "")
 .replace(/\bCLASS=\"?MSO\w*\"?/gi, "")
 .replace(/–/g,'-') //long –
 .replace(/[‘’]/g, "'") //single smartquotes ‘’ 
 .replace(/[“”]/g, '"') //double smartquotes “”
 .replace(/align="?justify"?/gi, "") //justify sends some browsers mad
 .replace(/<(TABLE|TD)(.*)(WIDTH|HEIGHT)[^A-Za-z>]*/gi, "<$1$2") //no fixed size tables
 .replace(/<([^>]+)>\s*<\/\1>/gi, ""); //empty tag
 oWhizzy.document.body.innerHTML = h;
 syncTextarea();
}

function insertLink(URL) {
 //hideDialogs();
 if (!URL) URL = o("lf_url").value;
 cmd = URL ? "createlink" : "unlink";
 if (document.selection) rng.select(); //else IE gets lost
 oWhizzy.document.execCommand(cmd, false, URL);
 oWhizzy.focus();
}

function insertImage(URL, side, border, margin, alt) { // insert image as specified
 //hideDialogs();

 if (!URL) URL = o("lf_url2").value;
 if (URL) {
 if (!alt) alt = URL.replace(/.*\/(.+)\..*/,"$1");
 img = '<img alt="' + alt + '" src="' + URL +'" ';
 img += 'border="'+border+'" />';
  insHTML(img);
 }
}


function showDesign() {
 oWhizzy.document.body.innerHTML = tidyD(o(idTa).value);
 h(idTa);
 h('showWYSIWYG');
 s('CONTROLS');
 s('whizzyWig');
 if(o("whizzyWig").contentDocument) o("whizzyWig").contentDocument.designMode = "on"; //FF loses it on hide
 oWhizzy.focus();
}

function showHTML() { 
 var t = (window.get_xhtml) ? get_xhtml(oWhizzy.document.body) : oWhizzy.document.body.innerHTML;
 o(idTa).value = tidyH(t);
 h('CONTROLS');
 h('whizzyWig');
 s(idTa);
 s('showWYSIWYG');
 o(idTa).focus();
}

function syncTextarea() { //tidy up before we go-go
 var b = oWhizzy.document.body;
 if (o(idTa).style.display == 'block') b.innerHTML = o(idTa).value;
 b.innerHTML = tidyH(b.innerHTML);
 o(idTa).value = (window.get_xhtml) ? get_xhtml(b) : b.innerHTML;
}

function tidyD(h){ //FF designmode likes <B>,<I>...
 h = h.replace(/<(\/?)strong>/gi, "<$1B>"); 
 h = h.replace(/<(\/?)em>/gi, "<$1I>");

 return h;
}

function tidyH(h){ //...but <B>,<I> deprecated
 h = h.replace(/<([A-Za-z1-6]+)><\/\1>/g, ""); //empty tag
 h = h.replace(/(<\/?)[Bb]>/g, "$1strong>");
 h = h.replace(/(<\/?)[Ii]>/g, "$1em>");
  h = convertRGBToHex(h,true);
 return h;
}

function convertRGBToHex(s, k) {
	if (s.toLowerCase().indexOf('rgb') != -1) {
		var re = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");
		var rgb = s.replace(re, "$1,$2,$3,$4,$5").split(',');
		if (rgb.length == 5) {
			r = parseInt(rgb[1]).toString(16);
			g = parseInt(rgb[2]).toString(16);
			b = parseInt(rgb[3]).toString(16);

			r = r.length == 1 ? '0' + r : r;
			g = g.length == 1 ? '0' + g : g;
			b = b.length == 1 ? '0' + b : b;

			s = "#" + r + g + b;

			if (k)
				s = rgb[0] + s + rgb[4];
		}
	}

	return s;
}


function kb_handler(evt) { // keyboard controls for Mozilla
 var w = evt.target.id;
 if (evt.ctrlKey) {
  var key = String.fromCharCode(evt.charCode).toLowerCase();
  var cmd = '';
  switch (key) {
   case 'b': cmd = "bold"; break;
   case 'i': cmd = "italic"; break;
   case 'u': cmd = "underline"; break;
   case 'l': cmd = "link"; break;
   case 'm': cmd = "image"; break;
  };
  if (cmd) {
   makeSo(cmd, true);
   evt.preventDefault();  // stop the event bubble
   evt.stopPropagation();
  }
 }
}

function insHTML(html) { // insert arbitrary HTML at current selection
whereAmI();
 if (!html) html = prompt("Enter some HTML to insert:", "");
 if (!html) return;
 if (document.selection) {
  rng.select(); //else IE gets lost
  html = html + rng.htmlText;
  try { oWhizzy.document.selection.createRange().pasteHTML(html); } //
  catch (e) { }// catch error if range is bad for IE
 } else { //Moz
  if (sel) html = html + sel;
  var fragment = oWhizzy.document.createDocumentFragment();
  var div = oWhizzy.document.createElement("div");
  div.innerHTML = html;
  while (div.firstChild) {
   fragment.appendChild(div.firstChild);
  }
  sel.removeAllRanges();
  rng.deleteContents();
  var node = rng.startContainer;
  var pos = rng.startOffset;
  
  switch (node.nodeType) {
   case 3: if (fragment.nodeType == 3) {
    node.insertData(pos, fragment.data);
    rng.setEnd(node, pos + fragment.length);
    rng.setStart(node, pos + fragment.length);
   } else {
    node = node.splitText(pos);
    node.parentNode.insertBefore(fragment, node);
    rng.setEnd(node, pos + fragment.length);
    rng.setStart(node, pos + fragment.length);
   }
   break;
   case 1: 
	oWhizzy.caretPos=5;
	node = node.childNodes[pos];


	node.parentNode.insertBefore(fragment, node);
    rng.setEnd(node, pos + fragment.length);
    rng.setStart(node, pos + fragment.length);
   break;
  }
  sel.addRange(rng);
 }
 oWhizzy.focus();
}

function whereAmI() {//get current selected range if available 
 oWhizzy.focus();
 if (document.all) { //IE
  sel = oWhizzy.document.selection;
  if (sel != null) {
   rng = sel.createRange();
   switch (sel.type) {
    case "Text":case "None":
     papa = rng.parentElement(); break;
    case "Control":
     papa = rng.item(0); break;
    default:
     papa = frames['whizzyWig'].document.body;
   }
   var paNode = papa;
   trail = papa.tagName + '>' +sel.type;
   while (paNode.tagName != 'BODY') {
    paNode = paNode.parentNode;
    trail = paNode.tagName + '>' + trail;
   }
   window.status = trail;
  }
 } else { //Moz
  sel = oWhizzy.getSelection();
  if (sel != null) rng = sel.getRangeAt(sel.rangeCount - 1).cloneRange();
 }
}

function textSel() {
	if (sel != "") return true; 
	else {alert(t("Vous devez d'abord sélectionner du texte.")); return false;}
}
function s(id) {if(o(id)) o(id).style.display = 'block';} //show element
function h(id) {if(o(id)) o(id).style.display = 'none';} //hide element
function o(id) { return document.getElementById(id); } //get element by ID
function w(str) { return document.write(str); } //document write
function t(key) {return (window.language && language[key]) ? language[key] :  key;} //translation

