﻿// Cross-Browser Rich Text Editor
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)
// Visit the support forums at http://www.kevinroth.com/forums/index.php?c=2
// This code is public domain. Redistribution and use of this code, with or without modification, is permitted.
//
// UI Modifications by Timothy Bell (tim@NOSPAMthirdspin.com - remove NOSPAM)
// Backward Compatibility and Non-designMode() Browser Modifications by Craig Morey http://www.craig247.com (Mods marked with CM)

// Constants
var minWidth = 545; // minumum width
var wrapWidth = 1064; //width at which all icons will appear on one bar
var lang = "fi"; //xhtml language
var encoding = "UTF-8"; //xhtml encoding
var zeroBorder = "#c0c0c0"; //guideline color - see showGuidelines()
var btnText = "submit"; // Button value for non-designMode() & fullsceen rte
var resize_fullsrcreen = true;
// (resize_fullsrcreen) limited in that: 1)won't auto wrap icons. 2)won't
// shrink to less than (wrapWidth)px if screen was initized over (wrapWidth)px;

// Pointers
var InsertChar;
var InsertTable;
var InsertImage;
var InsertLink;
var dlgReplace;

//Init Variables & Attributes
var ua = navigator.userAgent.toLowerCase();
var isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1))? true:false;
var	isGecko = (ua.indexOf("gecko") != -1)? true:false;
var	isSafari = (ua.indexOf("safari") != -1)? true:false;
var	isKonqueror = (ua.indexOf("konqueror") != -1)? true:false;
var rng;
var currentRTE;
var allRTEs = "";
var obj_width;
var obj_height;
var imagesPath;
var includesPath;
var cssFile;
var generateXHTML = true;
var isRichText = false;
//check to see if designMode mode is available
//Safari/Konqueror think they are designMode capable even though they are not
if(document.getElementById && document.designMode && !isSafari && !isKonqueror) isRichText = true;
//for testing standard textarea, uncomment the following line
//isRichText = false;

function initRTE(imgPath, incPath, css, genXHTML){
	// CM 05/04/05 check args for compatibility with old RTE implementations
	if (arguments.length == 3) {
		genXHTML = generateXHTML;
	}
	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	generateXHTML = genXHTML;
	if(isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
	if(isIE){
	  document.onmouseover = raiseButton;
	  document.onmouseout  = normalButton;
	  document.onmousedown = lowerButton;
	  document.onmouseup   = raiseButton;
  }else{
	  minWidth = minWidth-48;
	  wrapWidth = wrapWidth-112;
  }
}

function writeRichText(rte, html, css, width, height, buttons, readOnly, fullscreen) {
	currentRTE = rte;
	if(allRTEs.length > 0) allRTEs += ";";
	allRTEs += rte;
	// CM 06/04/05 stops single quotes from messing everything up
	html=replaceIt(html,'\'','&apos;');
	// CM 05/04/05 a bit of juggling for compatibility with old RTE implementations
	if (arguments.length == 6) {
		fullscreen = false;
		readOnly = buttons;
		buttons = height;
		height = width;
		width = css;
		css = "";
	}
	if(readOnly) buttons = false;
	if(fullscreen)
	{
		// fullscreen is not readOnly and must show buttons
		readOnly = false;
    buttons = true;
		// resize rte on resize if the option resize_fullsrcreen = true.
		if(isRichText && resize_fullsrcreen) window.onresize = resizeRTE;
		document.body.style.margin = "0px";
    document.body.style.overflow = "hidden";
  	//adjust maximum table widths
		findSize("");
		width = obj_width;
  	if(width < wrapWidth) {
			height = (obj_height - 83);
		}else{
      height = (obj_height - 55);
		}
		if (width < minWidth){
      document.body.style.overflow = "auto";
      if(isIE){
				height = obj_height-22;
		  }else{
        height = obj_height-24;
	    }
      width = minWidth;
		}
		var tablewidth = width;
  }else{
	  fullscreen = false;
		//adjust minimum table widths
		if (buttons && (width < minWidth)) width = minWidth;
		if(isIE){
	    var tablewidth = width;
	  }else{
		  var tablewidth = width + 4;
	  }
  }
	if(isRichText){
		var rte_css = "";
		if(css.length > 0) {
	    rte_css = css;
		}else{
      rte_css = cssFile;
		}
		document.writeln('<span class="rteDiv">');
		if(buttons){
			document.writeln('<table class="rteBk" cellpadding=0 cellspacing=0 id="Buttons1_'+rte+'" width="' + tablewidth + '">');
			document.writeln('<tr>');
			document.writeln('<td><img class="rteBar" src="'+imagesPath+'bar.gif" alt=""></td>');
			if(fullscreen) document.writeln('<td><input type=image class="rteImg" src="'+imagesPath+'save.gif" alt="Tallenna" title="Tallenna"></td>');
      document.writeln('<td><img class="rteImg" src="'+imagesPath+'print.gif" alt="Tulosta" title="Tulosta" onClick="rtePrint(\''+rte+'\')"></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'undo.gif" alt="Peruuta" title="Peruuta" onClick="rteCommand(\''+rte+'\', \'undo\')"></td>');
      document.writeln('<td><img class="rteImg" src="'+imagesPath+'redo.gif" alt="Tee uudelleen" title="Tee uudelleen" onClick="rteCommand(\''+rte+'\', \'redo\')"></td>');
      document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			if(isIE){
				document.writeln('<td><img class="rteImg" src="'+imagesPath+'cut.gif" alt="Leikkaa" title="Leikkaa" onClick="rteCommand(\''+rte+'\', \'cut\')"></td>');
				document.writeln('<td><img class="rteImg" src="'+imagesPath+'copy.gif" alt="Kopio" title="Kopio" onClick="rteCommand(\''+rte+'\', \'copy\')"></td>');
				document.writeln('<td><img class="rteImg" src="'+imagesPath+'paste.gif" alt="Liitä" title="Liitä" onClick="rteCommand(\''+rte+'\', \'paste\')"></td>');
				document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			}
			document.writeln('<td><select id="formatblock_'+rte+'" onchange="selectFont(\''+rte+'\', this.id);" style="font-size:14px;width:83px;height:20px;margin:1px;">');
			document.writeln('	<option value="">Muoto</option>');
			document.writeln('	<option value="<h1>">Otsikko 1</option>');
			document.writeln('	<option value="<h2>">Otsikko 2</option>');
			document.writeln('	<option value="<h3>">Otsikko 3</option>');
			document.writeln('	<option value="<h4>">Otsikko 4</option>');
			document.writeln('	<option value="<h5>">Otsikko 5</option>');
			document.writeln('	<option value="<h6>">Otsikko 6</option>');
			document.writeln('	<option value="<p>">Sisältö</option>');
			document.writeln('	<option value="<address>">Osoite</option>');
			document.writeln('	<option value="<pre>">Esimuotoiltu</option>');
			document.writeln('</select></td><td>');
			document.writeln('<select id="fontname_'+rte+'" onchange="selectFont(\''+rte+'\', this.id)" style="font-size:14px;width:122px;height:20px;margin:1px;">');
			document.writeln('	<option value="Font" selected>Fontti</option>');
			document.writeln('	<option value="Arial, Helvetica, sans-serif">Arial</option>');
			document.writeln('	<option value="Courier New, Courier, mono">Courier New</option>');
			document.writeln('	<option value="Palatino Linotype">Palatino Linotype</option>');
			document.writeln('	<option value="Times New Roman, Times, serif">Times New Roman</option>');
			document.writeln('	<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>');
			document.writeln('</select></td><td>');
			document.writeln('<select unselectable="on" id="fontsize_'+rte+'" onchange="selectFont(\''+rte+'\', this.id);" style="font-size:14px;width:58px;height:20px;margin:1px;">');
			document.writeln('	<option value="Size">Koko</option>');
			document.writeln('	<option value="1">1</option>');
			document.writeln('	<option value="2">2</option>');
			document.writeln('	<option value="3">3</option>');
			document.writeln('	<option value="4">4</option>');
			document.writeln('	<option value="5">5</option>');
			document.writeln('	<option value="6">6</option>');
			document.writeln('	<option value="7">7</option>');
			document.writeln('</select></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img id="insertchar_'+rte+'" class="rteImg" src="'+imagesPath+'special_char.gif" alt="Lisää merkki Character" title="Lisää merkki" onClick="dlgInsertChar(\''+rte+'\', \'insertchar\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'hr.gif" alt="Lisää vaakaerotin" title="Lisää vaakaerotin" onClick="rteCommand(\''+rte+'\', \'inserthorizontalrule\', \'\')"></td>');
			if(tablewidth < wrapWidth){
				document.writeln('		<td width="100%"></td>');
				document.writeln('</tr>');
				document.writeln('</table>');
				document.writeln('<table class="rteBk" cellpadding="0" cellspacing="0" id="Buttons2_'+rte+'" width="' + tablewidth + '">');
				document.writeln('<tr>');
      }
		  document.writeln('<td><img class="rteBar" src="'+imagesPath+'bar.gif" alt=""></td>');
			document.writeln('<td><img id="bold" class="rteImg" src="'+imagesPath+'bold.gif" alt="Lihavointi" title="Lihavointi" onClick="rteCommand(\''+rte+'\', \'bold\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'italic.gif" alt="Kursivointi" title="Kursivointi" onClick="rteCommand(\''+rte+'\', \'italic\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'underline.gif" alt="Alleviivaus" title="Alleviivaus" onClick="rteCommand(\''+rte+'\', \'underline\', \'\')"></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			//document.writeln('<td><img class="rteImg" src="'+imagesPath+'superscript.gif" alt="Superscript" title="Superscript" onClick="rteCommand(\''+rte+'\', \'superscript\', \'\')"></td>');
      //document.writeln('<td><img class="rteImg" src="'+imagesPath+'subscript.gif" alt="Subscript" title="Subscript" onClick="rteCommand(\''+rte+'\', \'subscript\', \'\')"></td>');
      //document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'left_just.gif" alt="Tasaa vasen reuna" title="Tasaa vasen reuna" onClick="rteCommand(\''+rte+'\', \'justifyleft\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'centre.gif" alt="Keskitä" title="Keskitä" onClick="rteCommand(\''+rte+'\', \'justifycenter\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'right_just.gif" alt="Tasaa oikea reuna" title="Tasaa oikea reuna" onClick="rteCommand(\''+rte+'\', \'justifyright\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'justifyfull.gif" alt="Tasaa molemmat reunat" title="Tasaa molemmat reunat" onclick="rteCommand(\''+rte+'\', \'justifyfull\', \'\')"></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'numbered_list.gif" alt="Järjestetty lista" title="Järjestetty lista" onClick="rteCommand(\''+rte+'\', \'insertorderedlist\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'list.gif" alt="Järjestämätön lista" title="Järjestämätön lista" onClick="rteCommand(\''+rte+'\', \'insertunorderedlist\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'outdent.gif" alt="Sisennä vasemmalle" title="Sisennä vasemmalle" onClick="rteCommand(\''+rte+'\', \'outdent\', \'\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'indent.gif" alt="Sisennä" title="Sisennä" onClick="rteCommand(\''+rte+'\', \'indent\', \'\')"></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><div id="forecolor_'+rte+'"><img class="rteImg" src="'+imagesPath+'textcolor.gif" alt="Tekstin väri" title="Tekstin väri" onClick="dlgColorPalette(\''+rte+'\', \'forecolor\', \'\')"></div></td>');
			document.writeln('<td><div id="hilitecolor_'+rte+'"><img class="rteImg" src="'+imagesPath+'bgcolor.gif" alt="Taustaväri" title="Taustaväri" onClick="dlgColorPalette(\''+rte+'\', \'hilitecolor\', \'\')"></div></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'replace.gif" alt="Etsi ja korvaa" title="Etsi ja korvaa" onClick="dlgSearchRepalce(\''+rte+'\', \'replace\', \'\')"></div></td>');
			document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'hyperlink.gif" alt="Lisää linkki" title="Lisää linkki" onClick="dlgInsertLink(\''+rte+'\', \'link\')"></td>');
			document.writeln('<td><img class="rteImg" src="'+imagesPath+'image.gif" alt="Lisää kuva" title="Lisää kuva" onClick="dlgInsertImage(\''+rte+'\',\'image\', \'\')"></td>');
			document.writeln('<td><div id="table_'+rte+'"><img class="rteImg" src="'+imagesPath+'insert_table.gif" width="25" height="24" alt="Lisää taulukko" title="Lisää taulukko" onClick="dlgInsertTable(\''+rte+'\', \'table\', \'\')"></div></td>');
      //if(isIE){
		//		document.writeln('<td><img class="rteImg" src="'+imagesPath+'spellcheck.gif" width="25" height="24" alt="Spell Check" //title="Spell Check" onClick="checkspell()"></td>');
		//		}
			document.writeln('<td width="100%"></td></tr></table>');
		}
		document.writeln('<iframe id="'+rte+'" name="'+rte+'" width="' + (tablewidth - 2) + 'px" height="' + height + 'px" frameborder=0 style="border: 1px solid #d2d2d2" src="' + includesPath + 'blank.htm" onfocus="dlgCleanUp();"></iframe>');
		if(!readOnly) document.writeln('<table id="vs'+rte+'" name="vs'+rte+'" class="rteBk" cellpadding=0 cellspacing=0 width="' + tablewidth + '"><tr><td onclick="toggleHTMLSrc(\''+rte+'\', ' + buttons + ');"><img src="'+imagesPath+'code.gif" alt="Vaihda muoto" style="margin:1px;" align=absmiddle><span id="txtSrc'+rte+'" style="font-family:tahoma,sans-serif;font-size:12px;color:#0000ff;CURSOR: default;">Näytä HTML</span></td></tr></table>');
		document.writeln('<iframe width="142" height="98" id="cp'+rte+'" src="' + includesPath + 'palette.htm" scrolling="no" frameborder=0 style="margin:0;border:0;visibility:hidden;position:absolute;border:1px solid #cdcdcd;top:-1000px;left:-1000px"></iframe>');
		document.writeln('<input type="hidden" id="hdn'+rte+'" name="'+rte+'" value="" style="position: absolute;left:-1000px;top:-1000px;">');
		if(!fullscreen) document.writeln('<input type="hidden" id="size'+rte+'" name="size'+rte+'" value="'+height+'" style="position: absolute;left:-1000px;top:-1000px;">');
		document.writeln('</span>');
		document.getElementById('hdn' + rte).value = html;
		enableDesignMode(rte, html, rte_css, readOnly);
	}else{
		buttons = false;
		if(fullscreen && height > 90) height = (height - 75);tablewidth=tablewidth-30;
		// CM non-designMode() UI
		html = parseBreaks(html);
		document.writeln('<div style="font:12px Verdana, Arial, Helvetica, sans-serif;width: ' + tablewidth + 'px;padding:15px;">');
		if(!readOnly){
		  document.writeln('<div style="color:gray">To use the Rich Text Editor, a <a href="http://www.mozilla.org/" target="_new">Mozilla 1.3+</a> browser (eg, <a href="http://www.mozilla.org/products/firefox/" target=_new>Firefox</a>) or <a href="http://www.microsoft.com/windows/ie/default.asp" target="_new">MS IE5+</a> (Windows) are required. Apple Safari, IE5(Mac) and Opera browsers are not currently supported and all text must be in HTML.</div><br>');
		  document.writeln('<input type="radio" name="autobr" value="1" checked="checked" onclick="autoBRon(\'' + rte + '\');" /> Use Auto Line Breaks <input type="radio" name="autobr" value="0" onclick="autoBRoff(\'' + rte + '\');" />Use Only Raw HTML<br>');
		  document.writeln('<textarea name="'+rte+'" id="'+rte+'" style="width: ' + tablewidth + 'px; height: ' + height + 'px;">' + html + '</textarea>');
		}else{
			document.writeln('<textarea name="'+rte+'" id="'+rte+'" style="width: ' + tablewidth + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
		}
		if(fullscreen) document.writeln('<br><input type="submit" value="'+btnText+'" />');
		document.writeln('</div>');
	}
}

function enableDesignMode(rte, html, css, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\"><head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if(css.length > 0){
	  frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + css + "\" rel=\"stylesheet\">\n";
	} else {
	  frameHtml += "<style>body {background:#FFFFFF;margin:8px;padding:0px;}</style>\n";
	}
	frameHtml += "</head><body>\n";
	frameHtml += html + "\n";
	frameHtml += "</body></html>";
	if(document.all){
	  var oRTE = frames[rte].document;
	  oRTE.open();
	  oRTE.write(frameHtml);
	  oRTE.close();
	  if(!readOnly){
	    oRTE.designMode = "On";
			//frames[rte].document.attachEvent("onkeypress", function evt_ie_keypress(event) {ieKeyPress(event, rte);});
		}
	}else{
	  try{
			if(!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try{
			  var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if(isGecko && !readOnly){
				  //attach a keyboard handler for gecko browsers to make keyboard shortcuts work
				  oRTE.addEventListener("keypress", geckoKeyPress, true);
				}
		  }catch(e){
				alert("Virhe sisällön lataamisessa.");
			}
		}catch(e){
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if(isGecko){
			  setTimeout("enableDesignMode('" + rte + "', '" + html + "', '" + css + "', " + readOnly + ");", 200);
			}else{
			  return false;
			}
		}
	}
	setTimeout('showGuidelines("'+rte+'")',300);
}

function updateRTE(rte) {
	if(isRichText) {
	  dlgCleanUp(); // 	Closes Pop-ups
	  stripGuidelines(rte); // Removes Table Guidelines
  }
	parseRTE(rte);
}

function parseRTE(rte) {
	if (!isRichText) {
		 autoBRoff(rte); // sorts out autoBR
		 return false;
	}
	//check for readOnly mode
	var readOnly = false;
	if(document.all){
		if (frames[rte].document.designMode != "On") readOnly = true;
	}else{
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}

	if(isRichText && !readOnly){
		//if viewing source, switch back to design view
		if(document.getElementById("txtSrc" + rte).innerHTML == "Näytä muotoiltu teksti"){
			 if(document.getElementById("Buttons1_"+rte)){
				 toggleHTMLSrc(rte, true);
			 }else{
         toggleHTMLSrc(rte, false);
			 }
			 stripGuidelines(rte);
		}
		setHiddenVal(rte);
	}
}

function setHiddenVal(rte){
	//set hidden form field value for current rte
	var oHdnField = document.getElementById('hdn'+rte);
	//convert html output to xhtml (thanks Timothy Bell and Vyacheslav Smolin!)
	if(oHdnField.value == null) oHdnField.value = "";
	if(document.all){
		if(generateXHTML){
			try{
			  oHdnField.value = get_xhtml(frames[rte].document.body, lang, encoding);
	    }catch(e){
        oHdnField.value = frames[rte].document.body.innerHTML;
			}
		}else{
			oHdnField.value = frames[rte].document.body.innerHTML;
		}
	}else{
		if (generateXHTML) {
			try{
			  oHdnField.value = get_xhtml(document.getElementById(rte).contentWindow.document.body, lang, encoding);
			}catch(e){
        oHdnField.value = document.getElementById(rte).contentWindow.document.body.innerHTML;
			}
		}else{
			oHdnField.value = document.getElementById(rte).contentWindow.document.body.innerHTML;
		}
	}
	//if there is no content (other than formatting) set value to nothing
	if(stripHTML(oHdnField.value.replace("&nbsp;", " ")) == "" &&
		oHdnField.value.toLowerCase().search("<hr") == -1 &&
		oHdnField.value.toLowerCase().search("<img") == -1) oHdnField.value = "";
}

function updateRTEs(){
	var vRTEs = allRTEs.split(";");
	for(var i=0; i<vRTEs.length; i++){
		updateRTE(vRTEs[i]);
	}
}

function rteCommand(rte, command, option){
	dlgCleanUp();
  //function to perform command
	var oRTE;
	if(document.all){
		oRTE = frames[rte];
	}else{
		oRTE = document.getElementById(rte).contentWindow;
	}
	try{
		oRTE.focus();
	  oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	}catch(e){
//		alert(e);
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
	}
}

function toggleHTMLSrc(rte, buttons){
	dlgCleanUp();
  //contributed by Bob Hutzel (thanks Bob!)
  var cRTE = document.getElementById(rte);
  var hRTE = document.getElementById('hdn' + rte);
  var sRTE = document.getElementById("size"+rte);
  var tRTE = document.getElementById("txtSrc" + rte);
  var oRTE;
	if(document.all){
	  oRTE = frames[rte].document;
  }else{
		oRTE = cRTE.contentWindow.document;
 	}
	if(sRTE){
	  obj_height = parseInt(sRTE.value);
  }else{
    findSize(rte);
	}
	if(tRTE.innerHTML == "Näytä HTML"){
		stripGuidelines(rte);
		//we are checking the box
		tRTE.innerHTML = "Näytä muotoiltu teksti";
		if(buttons){
			showHideElement("Buttons1_" + rte, "hide", true);
			if(document.getElementById("Buttons2_"+rte)){
			  showHideElement("Buttons2_" + rte, "hide", true);
			  cRTE.style.height = obj_height+56;
			}else{
        cRTE.style.height = obj_height+28;
			}
		}
		setHiddenVal(rte);
  	if(document.all){
   		oRTE.body.innerText = hRTE.value;
		}else{
   		var htmlSrc = oRTE.createTextNode(hRTE.value);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	}else{
		//we are unchecking the box
		obj_height = parseInt(cRTE.style.height);
		tRTE.innerHTML = "Näytä HTML";
		if(buttons){
			showHideElement("Buttons1_" + rte, "show", true);
		  if(document.getElementById("Buttons2_"+rte)){
        showHideElement("Buttons2_" + rte, "show", true);
			  cRTE.style.height = obj_height-56;
			}else{
        cRTE.style.height = obj_height-28;
      }
		}
		if(document.all){
			//fix for IE
			var output = escape(oRTE.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			oRTE.body.innerHTML = unescape(output);
		}else{
   		var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
		showGuidelines(rte);
	}
}

function dlgColorPalette(rte, command) {
	//function to display or hide color palettes
	setRange(rte);
	//get dialog position
	var oDialog = document.getElementById('cp' + rte);
	var buttonElement = document.getElementById(command+"_"+rte);
	var iLeftPos = getOffsetLeft(buttonElement);
	var iTopPos = getOffsetTop(buttonElement)+22;
	oDialog.style.left = iLeftPos + "px";
	oDialog.style.top = iTopPos + "px";
	if((command == parent.command)&&(rte == currentRTE)){
		//if current command dialog is currently open, close it
		if(oDialog.style.visibility == "hidden"){
			showHideElement(oDialog, 'show', false);
		}else{
			showHideElement(oDialog, 'hide', false);
		}
	}else{
		//if opening a new dialog, close all others
		var vRTEs = allRTEs.split(";");
		for(var i = 0; i<vRTEs.length; i++){
			showHideElement('cp' + vRTEs[i], 'hide', false);
		}
		showHideElement(oDialog, 'show', false);
	}
	//save current values
	currentRTE = rte;
	parent.command = command;
}

function dlgInsertChar(rte, command) {
	//function to open/close insert character dialog
	//save current values
	parent.command = command;
	currentRTE = rte;
	InsertChar = popUpWin(includesPath+'insert_char.htm', 'InsertChar', 50, 50, 'status=yes,');
}

function dlgInsertTable(rte, command) {
	//function to open/close insert table dialog
	//save current values
	parent.command = command;
	currentRTE = rte;
	InsertTable = popUpWin(includesPath + 'insert_table.htm', 'InsertTable', 50, 50, 'status=yes,');
}
function dlgInsertImage(rte, command) {
	try{
	//function to open/close insert table dialog
	//save current values
	parent.command = command;
	currentRTE = rte;
	//InsertImage = popUpWin(includesPath + 'insert_image.htm', 'Lisää kuva', 400, 250, 'status=yes,');
	//Sva kutsutaan suoraan hässäkkää yläsubmenun srcriptillä
	dlgCleanUp();
	//var leftPos = (screen.availWidth - width) / 2;
	//var topPos = (screen.availHeight - height) / 2;
	//options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
	//return window.open(url, win, options);
	lisaakuvascripti();
	}catch (e){

	}
}

function dlgInsertLink(rte, command) {
	//function to open/close insert table dialog
	//save current values
	parent.command = command;
	currentRTE = rte;

	//get currently highlighted text and set link text value
setRange(rte);
	  var linkText = '';
	  if (isIE) {
		  linkText = stripHTML(rng.htmlText);
	  } else {
		  linkText = stripHTML(rng.toString());
	  }

	parseRTE(rte);
	InsertLink = popUpWin(includesPath + 'insert_link.htm', 'InsertLink', 50, 50, 'status=yes,');
	setFormText("0", linkText);
}

function dlgSearchRepalce(rte, command) {
	//function to open/close insert table dialog
	//save current values
	parent.command = command;
	currentRTE = rte;

	//get currently highlighted text and set link text value
	setRange(rte);
	  var searchText = '';
	  if (isIE) {
		  searchText = stripHTML(rng.htmlText);
	  } else {
		  searchText = stripHTML(rng.toString());
	  }

	parseRTE(rte);
	dlgReplace = popUpWin(includesPath + 'replace.htm', 'dlgReplace', 50, 50, 'status=yes,');
	setFormText("1", searchText);
}

function setFormText(popup, content){
	//set link text value in insert link dialog
	try{
		switch(popup){
		  case "0": InsertLink.document.getElementById("linkText").value = content; break;
		  case "1": dlgReplace.document.getElementById("searchText").value = content; break;
		  //default: break;
		}
	}catch(e){
		//may take some time to create dialog window.
		//Keep looping until able to set.
		setTimeout("setFormText('"+popup+"','" + content + "');", 10);
	}
}

function dlgCleanUp(){
	var vRTEs = allRTEs.split(";");
	for(var i = 0; i < vRTEs.length; i++){
	  showHideElement('cp' + vRTEs[i], 'hide', false);
	}
	if(InsertChar!=null) InsertChar.close();InsertChar=null;
	if(InsertTable!=null) InsertTable.close();InsertTable=null;
	if(InsertImage!=null) InsertImage.close();InsertImage=null;
	if(InsertLink!=null) InsertLink.close();InsertLink=null;
	if(dlgReplace!=null) dlgReplace.close();dlgReplace=null;
}

function popUpWin (url, win, width, height, options) {
  dlgCleanUp();
	var leftPos = (screen.availWidth - width) / 2;
	var topPos = (screen.availHeight - height) / 2;
	options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
	return window.open(url, win, options);
}

function setColor(color) {
	//function to set color
	var rte = currentRTE;
	var parentCommand = parent.command;
	if(document.all){
		if(parentCommand == "hilitecolor") parentCommand = "backcolor";
		//retrieve selected range
		rng.select();
	}
	rteCommand(rte, parentCommand, color);
	showHideElement('cp' + rte, "hide", false);
}

/*function addImage(rte) {
  dlgCleanUp();
	//function to add image
	imagePath = prompt('Enter Image URL:', 'http://');				
	if((imagePath != null)&&(imagePath != "")){
		rteCommand(rte, 'InsertImage', imagePath);
	}
}*/
function rtePrint(rte) {
  dlgCleanUp();
	if(isIE){
	  document.getElementById(rte).contentWindow.document.execCommand('Print');
  }else{
 	  document.getElementById(rte).contentWindow.print();
	}
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetTop(elm){
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; //the positioning div is 2 elements up the tree
	while(parents_up > 0){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm){
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;
	while(parents_up > 0){
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	return mOffsetLeft;
}

function selectFont(rte, selectname){
	//function to handle font changes
	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if(idx != 0){
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		rteCommand(rte, cmd, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function insertHTML(html){
	//function to add HTML -- thanks dannyuk1982
	var rte = currentRTE;
	var oRTE;
	if(document.all){
		oRTE = frames[rte];
	}else{
		oRTE = document.getElementById(rte).contentWindow;
	}
	oRTE.focus();
	if(document.all){
		var oRng = oRTE.document.selection.createRange();
		oRng.pasteHTML(html);
		oRng.collapse(false);
		oRng.select();
	}else{
		oRTE.document.execCommand('insertHTML', false, html);
	}
}

function replaceHTML(tmpContent, searchFor, replaceWith) {
  var runCount = 0;
	var intBefore = 0;
	var intAfter = 0;
	var tmpOutput = "";
	while(tmpContent.toUpperCase().indexOf(searchFor.toUpperCase()) > -1) {
    runCount = runCount+1;
    // Get all content before the match
    intBefore = tmpContent.toUpperCase().indexOf(searchFor.toUpperCase());
    tmpBefore = tmpContent.substring(0, intBefore);
    tmpOutput = tmpOutput + tmpBefore;
    // Get the string to replace
    tmpOutput = tmpOutput + replaceWith;
    // Get the rest of the content after the match until
    // the next match or the end of the content
    intAfter = tmpContent.length - searchFor.length + 1;
    tmpContent = tmpContent.substring(intBefore + searchFor.length);
  }
  return runCount+"|^|"+tmpOutput+tmpContent;
}

function SearchAndReplace(searchFor, replaceWith, replaceOptions) {
  var cfrmMsg = "Oletko varma että haluat korvata nämä? Muutokset";
	var rte = currentRTE;
	stripGuidelines(rte);
	var oRTE;
	if(document.all){
		oRTE = frames[rte];
	}else{
		oRTE = document.getElementById(rte).contentWindow;
	}
	var tmpContent = oRTE.document.body.innerHTML.replace("'", "\'").replace('"', '\"');
  var tmpAfter = new String();
  var tmpOutput = new String();

  if(searchFor.length == 0){
    showGuidelines(rte);
		alert("Lisää haettaviin \"Haettavat:\".");
		return;
	} 
  //if(replaceOptions.indexOf("wholeWord") != -1) searchFor = " "+searchFor+" ";
  if(replaceOptions.indexOf("matchCase") != -1){
	  var tmpArray = tmpContent.split(searchFor);
	  if(tmpArray.length>1){
		  if(confirm(cfrmMsg+" \"["+replaceWith+"]\".\n\n"+tmpArray.join("["+replaceWith+"]"))){
	      tmpOutput = (tmpArray.length-1)+"|^|"+tmpArray.join(replaceWith);
	    }else{
        showGuidelines(rte);
				alert("Toiminto keskeytetty.");
        return;
      }
		}else{
      tmpOutput = "0|^|0";
		}
  }else{
    tmpOutput = replaceHTML(tmpContent, searchFor, "["+replaceWith+"]");
    tmpConfirm = tmpOutput.split("|^|");
    if(tmpConfirm[0]>0){
		  if(confirm(cfrmMsg+" \"["+replaceWith+"]\".\n\n"+tmpConfirm[1])){
        tmpOutput = replaceHTML(tmpContent, searchFor, replaceWith);
		  }else{
        showGuidelines(rte);
				alert("Toiminto keskeytetty.");
        return;
      }
		}else{
      tmpOutput = "0|^|0";
		}
  }
  tmpAfter = tmpOutput.split("|^|");
  if(tmpAfter[0] > 0){
	  oRTE.document.body.innerHTML = tmpAfter[1].replace("\'", "'").replace('\"', '"');
		showGuidelines(rte);
		alert("["+searchFor+"] korvattu"+tmpAfter[0]+" kertaa.");
  }else{
    showGuidelines(rte);
		alert("["+searchFor+"] ei löytynyt.");
	}
}
		
function showHideElement(element, showHide, rePosition){
	//function to show or hide elements
	//element variable can be string or object
	if(document.getElementById(element)){
		element = document.getElementById(element);
	}
	if(showHide == "show"){
		element.style.visibility = "visible";
	  if(rePosition){
		  element.style.position = "relative";
	    element.style.left = "auto";
	    element.style.top = "auto";
    }
	}else if(showHide == "hide"){
		element.style.visibility = "hidden";
    if(rePosition){
			element.style.position = "absolute";
    	element.style.left = "-1000px";
    	element.style.top = "-1000px";
	  }
  }
}

function setRange(rte){
	//function to store range of current selection
	var oRTE;
	if(document.all){
		oRTE = frames[rte];
		var selection = oRTE.document.selection;
		if(selection != null) rng = selection.createRange();
	}else{
		oRTE = document.getElementById(rte).contentWindow;
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	return rng;
}

function stripHTML(strU) {
	//strip all html
	var strN = strU.replace(/(<([^>]+)>)/ig,"");
	//replace carriage returns and line feeds
  strN = strN.replace(/\r\n/g," ");
  strN = strN.replace(/\n/g," ");
  strN = strN.replace(/\r/g," ");
	strN = trim(strN);
	return strN;
}

function trim(inputString) {
  if (typeof inputString != "string") return inputString;
  var retValue = inputString;
  var ch = retValue.substring(0, 1);
  while(ch == " "){
    retValue = retValue.substring(1, retValue.length);
    ch = retValue.substring(0, 1);
  }
  ch = retValue.substring(retValue.length - 1, retValue.length);
  while(ch == " "){
    retValue = retValue.substring(0, retValue.length - 1);
    ch = retValue.substring(retValue.length - 1, retValue.length);
  }
	// Note that there are two spaces in the string - look for multiple spaces within the string
  while (retValue.indexOf("  ") != -1) {
	  // Again, there are two spaces in each of the strings
    retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
  }
  return retValue; // Return the trimmed string back to the user
}

function showGuidelines(rte) {
  if(rte.length == 0) rte = currentRTE;
	var oRTE;
	if(document.all){
    oRTE = frames[rte];
  }else{
	  oRTE = document.getElementById(rte).contentWindow;
	}
  var tables = oRTE.document.getElementsByTagName("table");
  for(var i=0; i<tables.length; i++){
    if(tables[i].getAttribute("border") == "0"){
      var trs = tables[i].getElementsByTagName("tr");
      for(var j=0; j<trs.length; j++){
        var tds = trs[j].getElementsByTagName("td");
        for(var k=0; k<tds.length; k++){
  				if(j == 0 && k == 0){
			   	  tds[k].style.border = "dashed 1px "+zeroBorder;
					}else if(j == 0 && k != 0){
    		    tds[k].style.borderBottom = "dashed 1px "+zeroBorder;
						tds[k].style.borderTop = "dashed 1px "+zeroBorder;
						tds[k].style.borderRight = "dashed 1px "+zeroBorder;
	        }else if(j != 0 && k == 0) {
			      tds[k].style.borderBottom = "dashed 1px "+zeroBorder;
					  tds[k].style.borderLeft = "dashed 1px "+zeroBorder;
						tds[k].style.borderRight = "dashed 1px "+zeroBorder;
          }else if(j != 0 && k != 0) {
            tds[k].style.borderBottom = "dashed 1px "+zeroBorder;
					  tds[k].style.borderRight = "dashed 1px "+zeroBorder;
		      }
        }
      }
    }
  }
}

function stripGuidelines(rte) {
  var oRTE;
	if(document.all){
    oRTE = frames[rte];
  }else{
	  oRTE = document.getElementById(rte).contentWindow;
	}
	var tbls = oRTE.document.getElementsByTagName("table");
  for(var j=0; j<tbls.length; j++) {
    if(tbls[j].getAttribute("border") == "0") {
      var tds = tbls[j].getElementsByTagName("td");
      for(var k=0; k<tds.length; k++) {
        tds[k].removeAttribute("style");
      }
    }
  }
}

function findSize(obj) {
  if(obj.length > 0 && document.all) {
	  obj = frames[obj];
  } else if(obj.length > 0 && !document.all) {
	  obj = document.getElementById(obj).contentWindow;
  } else {
    obj = this;
	}
	if ( typeof( obj.window.innerWidth ) == 'number' ) {
    //Non-IE
    obj_width = obj.window.innerWidth;
    obj_height = obj.window.innerHeight;
  } else if( obj.document.documentElement && ( obj.document.documentElement.clientWidth || obj.document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    obj_width = document.documentElement.clientWidth;
    obj_height = document.documentElement.clientHeight;
  } else if( obj.document.body && ( obj.document.body.clientWidth || obj.document.body.clientHeight ) ) {
    //IE 4 compatible
    obj_width = obj.document.body.clientWidth;
    obj_height = obj.document.body.clientHeight;
  }
}

function resizeRTE() {
  document.body.style.overflow = "hidden";
	var oPointer = currentRTE;
  var oRTE = document.getElementById(oPointer);
  var oBut1 = document.getElementById('Buttons1_'+oPointer);
  var oBut2;
  var oVS = document.getElementById('vs'+oPointer);
  findSize("");
  width = obj_width;
  if (width < minWidth){
		document.body.style.overflow = "auto";
		width = minWidth;
	}
  var height = obj_height - 83;
	if (document.getElementById("txtSrc" + oPointer).innerHTML == "Näytä muotoiltu teksti") {
	  height = obj_height-28;
		if (!document.getElementById('Buttons2_'+oPointer) && width < wrapWidth) {
	    document.body.style.overflow = "auto";
			width = wrapWidth;
		}
		if (document.getElementById('Buttons2_'+oPointer)) document.getElementById('Buttons2_'+oPointer).style.width = width;
  } else {
    if (document.getElementById('Buttons2_'+oPointer)) {
		  document.getElementById('Buttons2_'+oPointer).style.width = width;
    } else {
			height = obj_height - 55;
			if(width < wrapWidth){
	 		  document.body.style.overflow = "auto";
		    width = wrapWidth;
			}
    }
  }
  if (document.body.style.overflow == "auto" && isIE) height = height-22;
  if (document.body.style.overflow == "auto" && !isIE) height = height-24;
  oBut1.style.width = width;
  oVS.style.width = width;
	oRTE.style.width = width-2;
  oRTE.style.height = height;
  if(!document.all)oRTE.contentDocument.designMode = "on";
}

function replaceIt(string,text,by) {
  // CM 19/10/04 custom replace function
  var strLength = string.length, txtLength = text.length;
  if ((strLength == 0) || (txtLength == 0)) return string;
  var i = string.indexOf(text);
  if ((!i) && (text != string.substring(0,txtLength))) return string;
  if (i == -1) return string;
  var newstr = string.substring(0,i) + by;
  if (i+txtLength < strLength)
    newstr += replaceIt(string.substring(i+txtLength,strLength),text,by);
  return newstr;
}

//********************
// Non-designMode() Functions
//********************

function autoBRon(rte) {
  // CM 19/10/04 used for non RTE browsers to deal with auto <BR> (and clean up other muck)
	var oRTE = document.forms[0].elements[rte];
	oRTE.value=parseBreaks(oRTE.value);
	oRTE.value=replaceIt(oRTE.value,'&apos;','\'');
}

function autoBRoff(rte) {
  // CM 19/10/04 used for non RTE browsers to deal with auto <BR> (auto carried out when the form is submitted)
	var oRTE = document.forms[0].elements[rte];
	oRTE.value=replaceIt(oRTE.value,'\n','<br />');
	oRTE.value=replaceIt(oRTE.value,'\'','&apos;');
}

function parseBreaks(funcInput) {
  // CM 19/10/04 used for non RTE browsers to deal with auto <BR> (and clean up other muck)
	funcInput=replaceIt(funcInput,'<br>','\n');
	funcInput=replaceIt(funcInput,'<BR>','\n');
	funcInput=replaceIt(funcInput,'<br/>','\n');
	funcInput=replaceIt(funcInput,'<br />','\n');
	funcInput=replaceIt(funcInput,'\t',' ');
	funcInput=replaceIt(funcInput,'    ',' ');
	funcInput=replaceIt(funcInput,'   ',' ');
	funcInput=replaceIt(funcInput,'  ',' ');
	funcInput=replaceIt(funcInput,'  ',' ');
	funcInput=replaceIt(funcInput,'\n ','\n');
	funcInput=replaceIt(funcInput,' <p>','<p>');
	funcInput=replaceIt(funcInput,'</p><p>','\n\n');
	funcInput=replaceIt(funcInput,'&apos;','\'');
	return funcInput;
}

//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
	//function to add bold, italic, and underline shortcut commands to gecko RTEs
	//contributed by Anti Veeranna (thanks Anti!)
	var rte = 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;
		};
		if (cmd) {
			rteCommand(rte, cmd, null);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

//*****************
//IE-Only Functions
//*****************
function ieKeyPress(evt, rte) {
	var key = (evt.which || evt.charCode || evt.keyCode);
	var stringKey = String.fromCharCode(key).toLowerCase();
//the following breaks list and indentation functionality in IE (don't use)
//	switch (key) {
//		case 13:
//			//insert <br> tag instead of <p>
//			//change the key pressed to null
//			evt.keyCode = 0;
//			//insert <br> tag
//			currentRTE = rte;
//			insertHTML('<br>');
//			break;
//	};
}

function checkspell() {
	dlgCleanUp();
	//function to perform spell check
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
}

function raiseButton(e) {
	var el = window.event.srcElement;
	className = el.className;
	if (className == 'rteImg' || className == 'rteImgDn') {
		el.className = 'rteImgUp';
	}
}

function normalButton(e) {
	var el = window.event.srcElement;
	className = el.className;
	if (className == 'rteImgUp' || className == 'rteImgDn') {
		el.className = 'rteImg';
	}
}

function lowerButton(e) {
	var el = window.event.srcElement;
	className = el.className;
	if (className == 'rteImg' || className == 'rteImgUp') {
		el.className = 'rteImgDn';
	}
}

