// conceptuel Rich Text Editor
// http://www.conceptuel.co.uk
//
// version 1.03
// Introduce Reduced Interface version
// Produce xhtml output
//
// version 1.02
// Improve compatibility with Mozilla Browser
// Replace Link picker from a javascript prompt to a popup window
//
// version 1.01
// Replace Image picker from a javascript prompt to a popup window
//
// version 1.00
// change core application to support multiple languages
// Add Smiley picker

//init variables
var isRichText = false;
var rng;
var currentRTE;
var allRTEs = "";

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;

var language;
var encoding;

function initRTE(imgPath, incPath, css, lang) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);

	//check to see if designMode mode is available
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}

	if(!isIE) document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT | Event.MOUSEDOWN | Event.MOUSEUP);
	document.onmouseover = raiseButton;
	document.onmouseout  = normalButton;
	document.onmousedown = lowerButton;
	document.onmouseup   = raiseButton;

	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
        switch(lang) {
            case 'FR' :
               language = 'fr';
               encoding = 'iso-8859-1';
               break;
            case 'EN' :
            default   :
               language = 'en';
               encoding = 'iso-8859-1';
               break;
            }
}

function writeRichText(rte, html, width, height, buttons, readOnly, reduced) {
	if (reduced) {
	   if (isNaN(width)) {
	      width = 378;
	      }
	   if (width < 378) {
	      width = 378;
	      }
	   }
	else {   
	   if (isNaN(width)) {
	      width = 505;
	      }		
	   if (width < 505) {
	      width = 505;
	      }		   
       }
	if (isNaN(height)) {
	   height = 100;
	   }		
	if (height < 100) {
	   height = 100;
	   }	       
	if (isRichText) {
		if (allRTEs.length > 0) allRTEs += ";";
		allRTEs += rte;
       
		writeRTE(rte, html, width, height, buttons, readOnly, language, reduced);
	} else {
		writeDefault(rte, html, width, height, buttons, readOnly);
	}
}

function writeDefault(rte, html, width, height, buttons, readOnly) {
    if (html == '') {
       html = "<div class='MsoNormal' style='margin: 0cm 0cm 0pt'></div>";
       }
	if (!readOnly) {
		document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
	} else {
		document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>');
	}
}

function raiseButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}

	className = el.className;
	if (className == 'btnImage' || className == 'btnImageLowered') {
		el.className = 'btnImageRaised';
	}
}

function normalButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}

	className = el.className;
	if (className == 'btnImageRaised' || className == 'btnImageLowered') {
		el.className = 'btnImage';
	}
}

function lowerButton(e) {
	if (isIE) {
		var el = window.event.srcElement;
	} else {
		var el= e.target;
	}

	className = el.className;
	if (className == 'btnImage' || className == 'btnImageRaised') {
		el.className = 'btnImageLowered';
	}
}

function writeRTE(rte, html, width, height, buttons, readOnly, language, reduced) {
	if (isIE) {
		var tablewidth = width;
	} else {
		var tablewidth = width + 4;
	}
	
    if (html == '') {
       html = "<div class='MsoNormal' style='margin: 0cm 0cm 0pt'></div>";    
       }
       
        switch(language) {
            case 'fr' :
               var styleWord     = 'Style';
               var fontWord      = 'Fontes';
               var sizeWord      = 'Taille';
               var boldWord      = 'Gras';
               var italicWord    = 'Italique';
               var underlineWord = 'Souligné';
               var alignLWord    = 'Alignement à gauche';
               var alignCWord    = 'Alignement au centre';
               var alignRWord    = 'Alignement à droite';
               var alignFWord    = 'Alignement justifié';
               var rulerWord     = 'Ajouter une barre horizontale';
               var orderWord     = 'Numerotation'
               var unorderWord   = 'Puces'
               var outdentWord   = 'Diminuer le retrait'
               var indentWord    = 'Augmenter le retrait'
               var textColorWord = 'Couleur du texte'
               var backColorWord = 'Couleur de fond du texte'
               var linkWord      = 'Ajouter un hyperlien'
               var imageWord     = 'Ajouter une image'
               break;
            case 'en' :
            default   :
               var styleWord     = 'Style';
               var fontWord      = 'Font';
               var sizeWord      = 'Size';
               var boldWord      = 'Bold';
               var italicWord    = 'Italic';
               var underlineWord = 'Underline';
               var alignLWord    = 'Align Left';
               var alignCWord    = 'Center';
               var alignRWord    = 'Align Right';
               var alignFWord    = 'Justify Full';
               var rulerWord     = 'Horizontal Rule';
               var orderWord     = 'Ordered List'
               var unorderWord   = 'Unordered List'
               var outdentWord   = 'Outdent'
               var indentWord    = 'Indent'
               var textColorWord = 'Text Color'
               var backColorWord = 'Background Color'
               var linkWord      = 'Insert Link'
               var imageWord     = 'Add Image'
               break;
            }


	if (readOnly) buttons = false;
	if (buttons == true) {
		document.writeln('<style type="text/css">');
		document.writeln('.btnImage { background-color:silver; border: 2px solid silver; cursor: pointer; cursor: hand;}');
		document.writeln('.btnImageRaised { background-color:silver; border: 2px outset; cursor: pointer; cursor: hand;}');
		document.writeln('.btnImageLowered { background-color:silver; border: 2px inset; cursor: pointer; cursor: hand;}');
		document.writeln('.vertSep { background-color:silver; border:1px inset;font-size:0px; width:1px; height:20px; }');
		document.writeln('.btnBack { background-color:silver; border:1px outset; letter-spacing:0; padding-top:2px; padding-bottom:2px }');
		document.writeln('img { border-style:none; }');
		document.writeln('</style>');
		if (!reduced) {		
           document.writeln('<table class="btnBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">');
           document.writeln('	<tr>');
           document.writeln('		<td>');
           document.writeln('			<select id="formatblock_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">');
           document.writeln('				<option value="">[' + styleWord + ']</option>');
           document.writeln('				<option value="<p>">Paragraph</option>');
           document.writeln('				<option value="<h1>">Heading 1 <h1></option>');
           document.writeln('				<option value="<h2>">Heading 2 <h2></option>');
           document.writeln('				<option value="<h3>">Heading 3 <h3></option>');
           document.writeln('				<option value="<h4>">Heading 4 <h4></option>');
           document.writeln('				<option value="<h5>">Heading 5 <h5></option>');
           document.writeln('				<option value="<h6>">Heading 6 <h6></option>');
           document.writeln('				<option value="<address>">Address <ADDR></option>');
           document.writeln('				<option value="<pre>">Formatted <pre></option>');
           document.writeln('			</select>');
           document.writeln('		</td>');
           document.writeln('		<td>');
           document.writeln('			<select id="fontname_' + rte + '" onchange="Select(\'' + rte + '\', this.id)">');
           document.writeln('				<option value="Font" selected>[' + fontWord + ']</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="Times New Roman, Times, serif">Times New Roman</option>');
           document.writeln('				<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>');
           document.writeln('			</select>');
           document.writeln('		</td>');
           document.writeln('		<td>');
           document.writeln('			<select unselectable="on" id="fontsize_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">');
           document.writeln('				<option value="Size">[ ' + sizeWord + ']</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>');
           document.writeln('		</td>');
           document.writeln('		<td width="100%">');
           document.writeln('		</td>');
           document.writeln('	</tr>');
           document.writeln('</table>');
           }
		document.writeln('<table class="btnBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">');
		document.writeln('	<tr>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="' + boldWord + '" title="' +boldWord + '" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="' + italicWord + '" title="' + italicWord + '" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="' + underlineWord + '" title="' + underlineWord + '" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')"></td>');
		if (!reduced) {
           document.writeln('	<td><span class="vertSep"></span></td>');
           }
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="' + alignLWord + '" title="' + alignLWord + '" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="' + alignCWord + '" title="' + alignCWord + '" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="' + alignRWord + '" title="' + alignRWord + '" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="' + alignFWord + '" title="' + alignFWord + '" onclick="FormatText(\'' + rte + '\', \'justifyfull\', \'\')"></td>');
		if (!reduced) {
           document.writeln('	<td><span class="vertSep"></span></td>');
           document.writeln('	<td><img class="btnImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="' + rulerWord + '" title="' + rulerWord + '" onClick="FormatText(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>');
           document.writeln('	<td><span class="vertSep"></span></td>');
           }
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="' + orderWord + '" title="' + orderWord + '" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="' + unorderWord + '" title="' + unorderWord + '" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>');
		if (!reduced) {
           document.writeln('	<td><span class="vertSep"></span></td>');
           }
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="' + outdentWord + '" title="' + outdentWord + '" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')"></td>');
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="' + indentWord + '" title="' + indentWord + '" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')"></td>');
		if (!reduced) {		
           document.writeln('	<td><div id="forecolor_' + rte + '"><img class="btnImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="' + textColorWord + '" title="' + textColorWord + '" onClick="popup(\'conceptRTEpalette.html?language=' + language + '&rte=' + rte + '&command=forecolor\', \'palette\',170,250)"></div></td>');
           document.writeln('	<td><div id="hilitecolor_' + rte + '"><img class="btnImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="' + backColorWord + '" title="' + backColorWord + '" onClick="popup(\'conceptRTEpalette.html?language=' + language + '&rte=' + rte + '&command=hilitecolor\', \'palette\',170,250)"></div></td>');
           document.writeln('	<td><span class="vertSep"></span></td>');
           }
		document.writeln('		<td><img class="btnImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="' + linkWord + '" title="' + linkWord + '" onClick="dlgInsertLink(\'' + rte + '\', \'link\')"></td>');
		if (!reduced) {		
           document.writeln('	<td><img class="btnImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="' + imageWord + '" title="' + imageWord + '" onClick="popup(\'conceptRTEimage.html?language=' + language + '&rte=' + rte + '\', \'selectImage\',400,500)"></td>');
           }
        document.writeln('	    <td><img class="btnImage" src="' + imagesPath + 'smiley.gif" width="25" height="24" alt="Smileys" title="Smileys" onClick="popup(\'conceptRTEsmiley.html?language=' + language + '&rte=' + rte + '\', \'selectSmiley\',169,249)"></td>');           
		document.writeln('		<td width="100%"></td>');
		document.writeln('	</tr>');
		document.writeln('</table>');
	}
	document.writeln('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px"></iframe>');
	document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">');
	document.getElementById('hdn' + rte).value = html;
	enableDesignMode(rte, html, readOnly);
}

function enableDesignMode(rte, html, readOnly) {
	var frameHtml = "<html id=\"" + rte + "\">\n";
	frameHtml += "<head>\n";
	//to reference your stylesheet, set href property below to your stylesheet path and uncomment
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	}
	frameHtml += "<style>\n";
	frameHtml += "body {\n";
	frameHtml += "	background: #FFFFFF;\n";
	frameHtml += "	margin: 0px;\n";
	frameHtml += "	padding: 0px;\n";
	frameHtml += "}\n";
	frameHtml += "</style>\n";
	frameHtml += "</head>\n";
	frameHtml += "<body class=rte>\n";
	frameHtml += html + "\n";
	frameHtml += "</body>\n";
	frameHtml += "</html>";

	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) oRTE.designMode = "On";
	} 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", kb_handler, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10);
			} else {
				return false;
			}
		}
	}
}

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

function updateRTE(rte) {
	if (!isRichText) return;
	
	//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) {
		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) {
       oHdnField.value = get_xhtml(frames[rte].document.body, language, encoding);
	   }	
    else {
       oHdnField.value = get_xhtml(document.getElementById(rte).contentWindow.document.body, language, encoding);
       }
	
	//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 to format text in the text box
function FormatText(rte, command, option) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	try {
		oRTE.focus();
	  	oRTE.document.execCommand(command, false, option);
		oRTE.focus();
	} catch (e) {
		alert(e);
	}
}

function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;

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

	return mOffsetTop;
}

function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;

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

	return mOffsetLeft;
}

function Select(rte, selectname) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];

		//get current selected range
		var selection = oRTE.document.selection;
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	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, '');
		oRTE.focus();
		oRTE.document.execCommand(cmd, false, selected);
		oRTE.focus();
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function kb_handler(evt) {
	var rte = evt.target.id;

	//contributed by Anti Veeranna (thanks Anti!)
	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) {
			FormatText(rte, cmd, true);
			//evt.target.ownerDocument.execCommand(cmd, false, true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function stripHTML(oldString) {
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");

	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");

	//trim string
	newString = trim(newString);

	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);

   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);

   while (ch == " ") { // Check for spaces at the end of the string
      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 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 dlgInsertLink(rte, command) {
	//function to open/close insert linke 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());
	}
	
	popup('conceptRTEurl.html?language=' + language + '&rte=' + rte + '&text=' + linkText, 'selectUrl',400,500);
	
}   

function insertHTML(html) {
	//function to add HTML
	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 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;
}

/*==============================================================================

                             HTML2XHTML Converter 1.5
                             ========================
                       Copyright (c) 2004-2006 Vyacheslav Smolin


Author:
-------
Vyacheslav Smolin (http://www.richarea.com, http://html2xhtml.richarea.com,
re@richarea.com)

About the script:
-----------------
HTML2XHTML Converter (H2X) generates a well formed XHTML string from a HTML DOM
object.

Requirements:
-------------
H2X works in  MS IE 5.0 for Windows or above,  in Netscape 7.1,  Mozilla 1.3 or
above. It should work in all Mozilla based browsers.

Usage:
------
Please see description of function get_xhtml below.

Demo:
-----
http://html2xhtml.richarea.com/, http://www.richarea.com/demo/

License:
--------
Free for non-commercial using. Please contact author for commercial licenses.


==============================================================================*/


//add \n before opening tag
var need_nl_before = '|div|p|table|tbody|tr|td|th|title|head|body|script|comment|li|meta|h1|h2|h3|h4|h5|h6|hr|ul|ol|option|link|';
//add \n after opening tag
var need_nl_after = '|html|head|body|p|th|style|';

var re_comment = new RegExp();
re_comment.compile("^<!--(([a]|[^a])*)-->$");

var re_hyphen = new RegExp();
re_hyphen.compile("-$");


// Convert inner text of node to xhtml
// Call: get_xhtml(node);
//       get_xhtml(node, lang, encoding) -- to convert whole page
// other parameters are for inner usage and should be omitted
// Parameters:
// node - dom node to convert
// lang - document lang (need it if whole page converted)
// encoding - document charset (need it if whole page converted)
// need_nl - if true, add \n before a tag if it is in list need_nl_before
// inside_pre - if true, do not change content, as it is inside a <pre>
function get_xhtml(node, lang, encoding, need_nl, inside_pre) {

var i;
var text = '';
var children = node.childNodes;
var child_length = children.length;
var tag_name;
var do_nl = need_nl?true:false;
var page_mode = true;

	for (i=0;i<child_length;i++) {
		var child = children[i];

		//to prevent adding parts of html code twice in IE (thanks to Jorn Sjostrom)
		if (child.parentNode && String(node.tagName).toLowerCase() != String(child.parentNode.tagName).toLowerCase()) continue;

		switch (child.nodeType) {

			case 1: { //ELEMENT_NODE
				var tag_name = String(child.tagName).toLowerCase();

				if (tag_name == '') break;

				if (tag_name == 'meta') {
					var meta_name = String(child.name).toLowerCase();
					if (meta_name == 'generator') break;
				}

				//children nodes of <object> tags parsed incorrectly by ie-dom
				//so take their code and lowercase names of tags and attributes
				if (document.all && tag_name == 'object') {
					text += fix_object_code(child.outerHTML);
					continue;
				}

				if (!need_nl && tag_name == 'body') { //html fragment mode
					page_mode = false;
				}

				if (tag_name == '!') { //COMMENT_NODE in IE 5.0/5.5
					//get comment inner text
					var parts = re_comment.exec(child.text);

					if (parts) {
						//the last char of the comment text must not be a hyphen
						var inner_text = parts[1];
						text += fix_comment(inner_text);
					}
				} else {
					if (tag_name == 'html'){
						text = '<?xml version="1.0" encoding="'+encoding+'"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n';
					}

					//inset \n to make code more neat
					if (need_nl_before.indexOf('|'+tag_name+'|') != -1) {
						if ((do_nl || text != '') && !inside_pre) text += '\n';
							else do_nl = true;
					}

					text += '<'+tag_name;

					//add attributes
					var attr = child.attributes;
					var attr_length = attr.length;
					var attr_value;

					var attr_lang = false;
					var attr_xml_lang = false;
					var attr_xmlns = false;

					var is_alt_attr = false;


					for (j=0;j<attr_length;j++) {
						var attr_name = attr[j].nodeName.toLowerCase();

						if (!attr[j].specified &&
							attr_name != 'selected' &&
							attr_name != 'style' &&
							attr_name != 'value') continue; //IE 5.0

						if (attr_name == 'selected' &&
							!child.selected ||
							attr_name == 'style' && //IE 5.0
							child.style.cssText == '') continue;

						if (attr_name == '_moz_dirty' ||
							attr_name == '_moz_resizing' ||
							tag_name == 'br' && attr_name == 'type' &&
							child.getAttribute('type') == '_moz') continue;

						var valid_attr = true;

						switch (attr_name) {
							case "style" :
								attr_value = child.style.cssText;
								break;
							case "class" :
								attr_value = child.className;
								break;
							case "http-equiv":
								attr_value = child.httpEquiv;
								break;
							case "noshade": //this set of choices will extend
							case "checked":
							case "selected":
							case "multiple":
							case "nowrap":
							case "disabled":
								attr_value = attr_name;
								break;
							case "name":
								attr_value = child.name;
								break;
							case "for":
								attr_value = child.htmlFor;
								break;
							default:
								try {
									attr_value = child.getAttribute(attr_name, 2);
								} catch (e) {
									valid_attr = false;
								}
						}

						//html tag attribs
						if (attr_name == 'lang' && tag_name == 'html') {
							attr_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xml:lang') {
							attr_xml_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xmlns') attr_xmlns = true;

						if (valid_attr) {
							//value attribute set to "0" is not handled correctly in Mozilla
							if (!(tag_name == 'li' && attr_name == 'value')) {
								text += ' '+attr_name+'="'+fix_attribute(attr_value)+'"';
							}
						}

						if (attr_name == 'alt') is_alt_attr = true;
					}

					if (tag_name == 'img' && !is_alt_attr) {
						text += ' alt=""';
					}

					if (tag_name == 'html') {
						if (!attr_lang) text += ' lang="'+lang+'"';
						if (!attr_xml_lang) text += ' xml:lang="'+lang+'"';
						if (!attr_xmlns) text += ' xmlns="http://www.w3.org/1999/xhtml"';
					}

					if (child.canHaveChildren || child.hasChildNodes()){
						text += '>';
						if (need_nl_after.indexOf('|'+tag_name+'|') != -1) {
//							text += '\n';
						}
						text += get_xhtml(child, lang, encoding, true,
					inside_pre||tag_name=='pre'?true:false);
						text += '</'+tag_name+'>';
					} else {

						//these tags must have closing tags
						//'a' included as otherwise Mozilla extends <a /> links
						//on content coming after the link, that is wrong
						if (tag_name == 'style' || tag_name == 'title' ||
							tag_name == 'script' || tag_name == 'textarea' ||
							tag_name == 'a') {

							text += '>';
							var inner_text;
							if (tag_name == 'script') {
								inner_text = child.text;
							}else inner_text = child.innerHTML;

							if (tag_name == 'style') {
								inner_text = String(inner_text).replace(/[\n]+/g,'\n');
							}

							text += inner_text+'</'+tag_name+'>';

						} else {
							text += ' />';
						}
					}

				}
				break;
			}
			case 3: { //TEXT_NODE
				if (!inside_pre) { //do not change text inside <pre> tag
					if (child.nodeValue != '\n') {
						text += fix_entities(fix_text(child.nodeValue));
					}
				} else text += child.nodeValue;
				break;
			}
			case 8: { //COMMENT_NODE
				text += fix_comment(child.nodeValue);
				break;
			}
			default:
				break;
		}
	}

	if (!need_nl && !page_mode) { //delete head and body tags from html fragment
			text = text.replace(/<\/?head>[\n]*/gi, "");
			text = text.replace(/<head \/>[\n]*/gi, "");
			text = text.replace(/<\/?body>[\n]*/gi, "");
	}

	return text;
}

//fix inner text of a comment
function fix_comment(text){

	//delete double hyphens from the comment text
	text = text.replace(/--/g, "__");

	if(re_hyphen.exec(text)){ //last char must not be a hyphen
		text += " ";
	}

	return "<!--"+text+"-->";
}

//fix content of a text node
function fix_text(text) {
	//convert <,> and & to the corresponding entities

	//change &lt; and &gt; or the next string convert their & chars
	var temp_text = String(text).replace(/\&lt;/g, "#h2x_lt").replace(/\&gt;/g, "#h2x_gt");
	temp_text = temp_text.replace(/\n{2,}/g, "\n").replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\u00A0/g, "&nbsp;");
	return temp_text.replace(/#h2x_lt/g, "&lt;").replace(/#h2x_gt/g, "&gt;");
}

//fix content of attributes href, src or background
function fix_attribute(text) {
	//convert <,>, & and " to the corresponding entities

	//change &lt; and &gt; or the next string convert their & chars
	var temp_text = String(text).replace(/\&lt;/g, "#h2x_lt").replace(/\&gt;/g, "#h2x_gt");
	temp_text = temp_text.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
	return temp_text.replace(/#h2x_lt/g, "&lt;").replace(/#h2x_gt/g, "&gt;");
}

//lowercase names of tags and its attributes - the best we can do for
//flash objects in IE
function fix_object_code(text) {
var temp = String(text);

	temp = temp.replace(/ style=/gi, ' style=');
	temp = temp.replace(/ codeBase=/gi, ' codebase=');
	temp = temp.replace(/ height=/gi, ' height=');
	temp = temp.replace(/ width=/gi, ' width=');
	temp = temp.replace(/ align=/gi, ' align=');
	temp = temp.replace(/ classid=/gi, ' classid=');
	temp = temp.replace(/ src=/gi, ' src=');
	temp = temp.replace(/ NAME=/gi, ' name=');
	temp = temp.replace(/ VALUE=/gi, ' value=');
	temp = temp.replace(/ quality=/gi, ' quality=');
	temp = temp.replace(/ TYPE=/gi, ' type=');
	temp = temp.replace(/ PLUGINSPAGE=/gi, ' pluginspage=');
	temp = temp.replace(/<OBJECT /gi, '<object ');
	temp = temp.replace(/<\/OBJECT>/gi, '</object>');
	temp = temp.replace(/<PARAM /gi, '<param ');
	temp = temp.replace(/<\/PARAM>/gi, '</param>');
	temp = temp.replace(/<EMBED /gi, '<embed ');
	temp = temp.replace(/<\/EMBED>/gi, '</embed>');

	return temp;
}

//fix entities, eg &euro;
function fix_entities(text) {
var i;
var ents = {
	8364 : "euro",
	402  : "fnof",
	8240 : "permil",
	352  : "Scaron",
	338  : "OElig",
	381  : "#381",
	8482 : "trade",
	353  : "scaron",
	339  : "oelig",
	382  : "#382",
	376  : "Yuml",
	162  : "cent",
	163  : "pound",
	164  : "curren",
	165  : "yen",
	166  : "brvbar",
	167  : "sect",
	168  : "uml",
	169  : "copy",

	170  : "ordf",
	171  : "laquo",
	172  : "not",
	173  : "shy",
	174  : "reg",
	175  : "macr",
	176  : "deg",
	177  : "plusmn",
	178  : "sup2",
	179  : "sup3",
	180  : "acute",
	181  : "micro",
	182  : "para",
	183  : "middot",
	184  : "cedil",
	185  : "sup1",
	186  : "ordm",
	187  : "raquo",
	188  : "frac14",
	189  : "frac12",

	190  : "frac34",
	191  : "iquest",
	192  : "Agrave",
	193  : "Aacute",
	194  : "Acirc",
	195  : "Atilde",
	196  : "Auml",
	197  : "Aring",
	198  : "AElig",
	199  : "Ccedil",
	200  : "Egrave",
	201  : "Eacute",
	202  : "Ecirc",
	203  : "Euml",
	204  : "Igrave",
	205  : "Iacute",
	206  : "Icirc",
	207  : "Iuml",
	208  : "ETH",
	209  : "Ntilde",

	210  : "Ograve",
	211  : "Oacute",
	212  : "Ocirc",
	213  : "Otilde",
	214  : "Ouml",
	215  : "times",
	216  : "Oslash",
	217  : "Ugrave",
	218  : "Uacute",
	219  : "Ucirc",
	220  : "Uuml",
	221  : "Yacute",
	222  : "THORN",
	223  : "szlig",
	224  : "agrave",
	225  : "aacute",
	226  : "acirc",
	227  : "atilde",
	228  : "auml",
	229  : "aring",

	230  : "aelig",
	231  : "ccedil",
	232  : "egrave",
	233  : "eacute",
	234  : "ecirc",
	235  : "euml",
	236  : "igrave",
	237  : "iacute",
	238  : "icirc",
	239  : "iuml",
	240  : "eth",
	241  : "ntilde",
	242  : "ograve",
	243  : "oacute",
	244  : "ocirc",
	245  : "otilde",
	246  : "ouml",
	247  : "divide",
	248  : "oslash",
	249  : "ugrave",
	250  : "uacute",
	251  : "ucirc",
	252  : "uuml",
	253  : "yacute",
	254  : "thorn",
	255  : "yuml",


	913  : "Alpha",
	914  : "Beta",
	915  : "Gamma",
	916  : "Delta",
	917  : "Epsilon",
	918  : "Zeta",
	919  : "Eta",
	920  : "Theta",
	921  : "Iota",
	922  : "Kappa",
	923  : "Lambda",
	924  : "Mu",
	925  : "Nu",
	926  : "Xi",
	927  : "Omicron",
	928  : "Pi",
	929  : "Rho",

	931  : "Sigma",
	932  : "Tau",
	933  : "Upsilon",
	934  : "Phi",
	935  : "Chi",
	936  : "Psi",
	937  : "Omega",

	8756 : "there4",
	8869 : "perp",

	945  : "alpha",
	946  : "beta",
	947  : "gamma",
	948  : "delta",
	949  : "epsilon",
	950  : "zeta",
	951  : "eta",
	952  : "theta",
	953  : "iota",
	954  : "kappa",
	955  : "lambda",
	956  : "mu",
	957  : "nu",
	968  : "xi",
	969  : "omicron",
	960  : "pi",
	961  : "rho",
	962  : "sigmaf",
	963  : "sigma",
	964  : "tau",
	965  : "upsilon",
	966  : "phi",
	967  : "chi",
	968  : "psi",
	969  : "omega",

	8254 : "oline",
	8804 : "le",
	8260 : "frasl",
	8734 : "infin",
	8747 : "int",
	9827 : "clubs",
	9830 : "diams",
	9829 : "hearts",
	9824 : "spades",
	8596 : "harr",
	8592 : "larr",
	8594 : "rarr",
	8593 : "uarr",
	8595 : "darr",
	8220 : "ldquo",
	8221 : "rdquo",
	8222 : "bdquo",
	8805 : "ge",
	8733 : "prop",
	8706 : "part",
	8226 : "bull",
	8800 : "ne",
	8801 : "equiv",
	8776 : "asymp",
	8230 : "hellip",
	8212 : "mdash",
	8745 : "cap",
	8746 : "cup",
	8835 : "sup",
	8839 : "supe",
	8834 : "sub",
	8838 : "sube",
	8712 : "isin",
	8715 : "ni",
	8736 : "ang",
	8711 : "nabla",
	8719 : "prod",
	8730 : "radic",
	8743 : "and",
	8744 : "or",
	8660 : "hArr",
	8658 : "rArr",
	9674 : "loz",
	8721 : "sum",

	8704 : "forall",
	8707 : "exist",
	8216 : "lsquo",
	8217 : "rsquo",
	161  : "iexcl",

// other entities
	977  : "thetasym",
	978  : "upsih",
	982  : "piv",
	8242 : "prime",
	8243 : "Prime",
	8472 : "weierp",
	8465 : "image",
	8476 : "real",
	8501 : "alefsym",
	8629 : "crarr",
	8656 : "lArr",
	8657 : "uArr",
	8659 : "dArr",
	8709 : "empty",
	8713 : "notin",
	8727 : "lowast",
	8764 : "sim",
	8773 : "cong",
	8836 : "nsub",
	8853 : "oplus",
	8855 : "otimes",
	8901 : "sdot",
	8968 : "lceil",
	8969 : "rceil",
	8970 : "lfloor",
	8971 : "rfloor",
	9001 : "lang",
	9002 : "rang",
	710  : "circ",
	732  : "tilde",
	8194 : "ensp",
	8195 : "emsp",
	8201 : "thinsp",
	8204 : "zwnj",
	8205 : "zwj",
	8206 : "lrm",
	8207 : "rlm",
	8211 : "ndash",
	8218 : "sbquo",
	8224 : "dagger",
	8225 : "Dagger",
	8249 : "lsaquo",
	8250 : "rsaquo"
};

	var new_text = '';

var temp = new RegExp();
	temp.compile("[a]|[^a]", "g");

	var parts = text.match(temp);

	if (!parts) return text;
	for (i=0; i<parts.length; i++) {
		var c_code = parseInt(parts[i].charCodeAt());
		if (ents[c_code]) {
			new_text += "&"+ents[c_code]+";";
		} else new_text += parts[i];
	}

	return new_text;
}
