/************* AMVE Parameters can be changed by user *************/
var encloseChar			= getEncloseChar('`');
var encloseAllFormula	= getEncloseType("false");

var menuUpdateMathML	= getMenuUpdateType("true");

var autoUpdateMathML	= getAutoUpdateType("false");
var autoUpdateInterval	= getAutoUpdateInterval(10); //in seconds

var style				= getStyle("officeXP");
var language 			= getLanguage("FR");

var cookieSave 			= getCookieSaveType("true");

var AMVE_languageRessource = new Array();

/************* AMVE Locale properties *************/
var AMVEversion = "1.3";
var isIE = (document.createElementNS==null);
var isNS = !isIE;

var AMVEsymbols;
var textAreaForSaveASCII;
var autoUpdateTimerID;

if(style == "outsetBlue") mathcolor = "white";
else mathcolor = "black";

var futurDate = new Date(2099,11,31);

/************* AMVE methods *************/
var windowIsOpenning = false

function showModelessWindow(file,width,height,top,left,name,scrollbars) {
	if(!windowIsOpenning) {
		windowIsOpenning = true;
		if(!name) name ='';
		if(!scrollbars) scrollbars = 'no';
		
		if(isNS) {
			var win = window.open(file,name,"height="+height+",width="+width+",top="+top+",left="+left+",status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=" + scrollbars + ",modal=yes,dependable=yes");
			win.focus();
			windowIsOpenning = false;
			return win;
		} else {
			var caller = new Object();
			caller.window = window;
			caller.href = file;
			var h = height+20;
			window.showModelessDialog(file,caller,"dialogHeight:"+h+"px;dialogWidth:"+width+"px;dialogTop:"+top+"px;dialogLeft:"+left+"px;edge:raised;center:no;help:No;resizable:no;status:no;");
			windowIsOpenning = false;
		}
	}
}

function showWindow(file,width,height,top,left,name,scrollbars) {
	if(!windowIsOpenning) {
		windowIsOpenning = true;
		if(!name) name ='';
		if(!scrollbars) scrollbars = 'no';

		var win = window.open(file,name,"height="+height+",width="+width+"top="+top+",left="+left+",status=yes,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=" + scrollbars + ",modal=no,dependable=yes");
		win.focus();
		windowIsOpenning = false;
		return win;
	} else {
		return null;
	}
}

function getFrame(frameID) {
	if(isNS)
		return document.getElementById(frameID);
	else
		return document.frames(frameID);
}

function getWindow(frameID)
{
  if(isNS)
    return getFrame(frameID).contentWindow;
  else
    return getFrame(frameID).window;
};

function getDoc(frameID)
{
  if(isNS)
    return getWindow(frameID).document;
  else
    return eval(frameID+".document");
};

function disableEvent(event) {
	if(isNS)
		event.preventDefault();
	else
		window.event.returnValue = false;
}

function mozillaInsertNodeAtSelection(frameID,insertNode)
{
	try {
		// get current selection
		var sel = getWindow(frameID).getSelection();
		// get the first range of the selection
		// (there's almost always only one range)
		var range = sel.getRangeAt(0);
		// deselect everything
		sel.removeAllRanges();
		// remove content of current selection from document
		range.deleteContents();
		// get location of current selection
		var container = range.startContainer;
		var pos = range.startOffset;
		// make a new range for the new selection
		range=document.createRange();
		if (container.nodeType==3 && insertNode.nodeType==3) {
			// if we insert text in a textnode, do optimized insertion
			container.insertData(pos, insertNode.nodeValue);
			// put cursor after inserted text
			range.setEnd(container, pos+insertNode.length);
			range.setStart(container, pos+insertNode.length);
		} else {
			var afterNode;
			if (container.nodeType==3) {
				// when inserting into a textnode
				// we create 2 new textnodes
				// and put the insertNode in between
				var textNode = container;
				container = textNode.parentNode;
				var text = textNode.nodeValue;
				// text before the split
				var textBefore = text.substr(0,pos);
				// text after the split
				var textAfter = text.substr(pos);
				var beforeNode = document.createTextNode(textBefore);
				var afterNode = document.createTextNode(textAfter);
				// insert the 3 new nodes before the old one
				container.insertBefore(afterNode, textNode);
				container.insertBefore(insertNode, afterNode);
				container.insertBefore(beforeNode, insertNode);
				// remove the old node
				container.removeChild(textNode);
			} else {
				// else simply insert the node
				afterNode = container.childNodes[pos];
				container.insertBefore(insertNode, afterNode);
			}
			
			range.setEnd(afterNode, 0);
			range.setStart(afterNode, 0);
		}

		sel.addRange(range);
	} catch(Error) {};
}

function setFocus(frameID)
{
	getWindow(frameID).focus();
	
	if(isNS) window.setTimeout("getWindow('" + frameID + "').focus();", 100);  //to let time to set focus
};

/** get a symbol in the symbols table.
@param input a imput of the symbols ASCIIMathML table.
@return the symbol object or null if the symbol is not in the table.
*/
function getSymbolInTable(input) {
	var symbol = null;
	
	for (var i=0; i<AMsymbols.length; i++) {
		if (AMsymbols[i].input == input) {
			symbol = AMsymbols[i];
			break;
		}
	}
	
	return symbol;
}

/** set a mathematic symbol in the editor.
@param input a imput of the symbols ASCIIMathML table.
*/
function setSymbolInEditor(input) {
	var symbol;

	if((symbol = getSymbolInTable(input)) != null) {
		setInEditor(symbol.input);
	}
}

/** set a formula in the editor.
@param formula the formula to set in the editor. It can be a symbol, a function or a matrix.
@see setSymbolInEditor(input)
*/
function setInEditor(formula) {

	if(encloseAllFormula) {
		formula = encloseChar + formula + encloseChar;
	}
	setInASCIIEditor(formula + " ");

	if(menuUpdateMathML) {
		updateMathMLEditor();
	}
}

function setInASCIIEditor(formula) {

	setFocus("frameascii");
	
	if(isNS) {
		mozillaInsertNodeAtSelection("frameascii",getDoc("frameascii").createTextNode(formula));
	} else {
		var range = getDoc("frameascii").selection.createRange();
		range.text = formula;
	}
	
	setFocus("frameascii");
}

function setInMathMLEditor(content) {
	if(content) {
		waitUpdate();

		if(!encloseAllFormula) {
			content = encloseChar + content + encloseChar;

			content = content.replace(/\n/gi, encloseChar + "<br/>" + encloseChar);
			content = content.replace(/<br>/gi, encloseChar + "<br/>" + encloseChar);
			content = content.replace(/<p>/gi, encloseChar + "<br/>" + encloseChar);
			content = content.replace(/<\/p>/gi, "");
			content = content.replace(/<pre>/gi, encloseChar + "<br/>" + encloseChar);
			content = content.replace(/<\/pre>/gi, "");
		 }

		document.getElementById("divmathml").innerHTML = content;

		window.setTimeout("translateASCIItoMathML();", 1);  //to let time to refresh divmathml HTML
	}
}

function setStatus(msg,win) {
	
	var thewin = win?win:self;

	if(msg && msg.length > 0) {
		thewin.document.getElementById("divstatus").innerHTML = msg;
	} else {
		emptyStatus(thewin);
	}
}

function emptyStatus(win) {
	var thewin = win?win:self;

	if(thewin.document.getElementById("divstatus")) {
		thewin.document.getElementById("divstatus").innerHTML = "&nbsp ";
	}
}

function waitUpdate() {
	setStatus("Updating MathML...");
	document.getElementById("divmathml").style.visibility = "hidden";
}

function unwaitUpdate() {
	document.getElementById("divmathml").style.visibility = "visible";
	emptyStatus();
}

function translateASCIItoMathML() {
	translateById("divmathml");
	unwaitUpdate();
}

function getBoolean(text) {
	if(text == "true") return true;
	else return false;
}

function getTexteForHTML(obj) {
	if(obj) return obj;
	else return "";
}

function getTokenTypeForHTML(ttype) {
	switch (ttype) {
		case CONST:
			return "CONST";
		case UNARY:
			return "UNARY";
		case BINARY:
			return "BINARY";
		case INFIX:
			return "INFIX";
		case LEFTBRACKET:
			return "LEFTBRACKET";
		case RIGHTBRACKET:
			return "RIGHTBRACKET";
		case SPACE:
			return "SPACE";
		case UNDEROVER:
			return "UNDEROVER";
		case DEFINITION:
			return "DEFINITION";
		case LEFTRIGHT:
			return "LEFTRIGHT";
		case TEXT:
			return "TEXT";
	}
}

function getSymbolProperties(input) {
	var symbol = getSymbolInTable(input);
	
	if(symbol != null) {
		alert( 
			  "input: " + symbol.input + "\n"
			+ "tag: " + symbol.tag + "\n"
			+ "output: " + symbol.output + "\n"
			+ "tex: " + symbol.tex + "\n"
			+ "ttype: " + symbol.ttype + " (" + getTokenTypeForHTML(symbol.ttype) + ")\n"
			+ "invisible: " + symbol.invisible + "\n"
			+ "func: " + symbol.func + "\n"
			+ "acc: " + symbol.acc + "\n"
			+ "atname: " + symbol.atname + "\n"
			+ "atval: " + symbol.atval + "\n"
			+ "codes: " + symbol.codes + "\n"
		);
	} else {
		alert("Symbol isn't in ASCIIMathML symbols table.");
	}
}

function initialiseEditor() {
	initialiseAMSymbols();
	initialiseTextArea();

	initialiseButtons();
	initialisePopMenus()

	intialiseParams();

	choseCSS();

	document.getElementById("waitContener").style.display = "none";
	document.getElementById("editorContener").style.display = "block";

	initialiseASCIIEditor();
	initialiseMathMLEditor();

	setFocus("frameascii"); //TO DO : set it in loadAscii() method

	window.setTimeout("loadAscii()",100); //to let time to load frameascii body... TO DO : better to do it in frameascii onload
}

function initialiseAMSymbols() {
	AMVEsymbols = AMsymbols; //get the initial list of symbols before concated and sorted it
	AMinitSymbols(); //call the fonction to concat list of symbols with tex symbols and sorted it
}

function initialiseTextArea() {
	if(window.opener && !window.opener.closed) {
		var textObjectID = getURLParamValue(document.location.href,"textarea");
		if(textObjectID) {
			textAreaForSaveASCII = window.opener.document.getElementById(textObjectID);
		}
	}
}

function initialiseASCIIEditor() {
	getDoc("frameascii").designMode = "on";
}

function initialiseMathMLEditor() {
	//very slow, find it in HTML 
	/*	if(isIE) {
			var obj;
			for (var i=0; i<document.all.length; i++) {
				obj = document.all(i);
				if(!(obj.tagName == "TEXTBOX" ||
					(obj.tagName == "INPUT" && 
						(obj.type=="text"
						 || obj.type=="file"
						 || obj.type=="password"
					))
				)) {obj.unselectable = "on";}
			}
		}
	*/
}

function intialiseParams() {
	document.formcookie.cookietype.checked 				= cookieSave;
	
	document.formenclose.enclosetype.checked			= encloseAllFormula;
	document.formenclose.enclosechar.value				= encloseChar;

	document.formmenuupdate.menuupdatetype.checked		= menuUpdateMathML;
	document.formautoupdate.autoupdatetype.checked		= autoUpdateMathML;
	document.formautoupdate.autoupdateinterval.value	= autoUpdateInterval;
	scheduleAutoUpdate();
}

function initialiseLinkTitle() {
	var tags = document.getElementsByTagName("A");

	for (var i=0; i < tags.length; i++) {
		if(tags[i].title && tags[i].title.indexOf("javascript:") == 0) {
			tags[i].title = eval(tags[i].title.substring("javascript:".length,tags[i].title.length));
		}
	}
}

function initialiseButtons() {

	initialiseLinkTitle();

	var tags = document.getElementsByTagName("A");

	var f0 = new Function("event","disableEvent(event);"); //don't work in mozilla ?
	var f1 = new Function("this.className='buttonMouseOver';setStatus(this.title);");
	var f2 = new Function("this.className='button';emptyStatus();");
	var f3 = new Function("this.className='buttonMouseDown';");
	var f4 = new Function("this.className='buttonMouseOver';setStatus(this.title);hidePopMenus();");
	var f5 = new Function("this.className='directButton';emptyStatus();");
	var f6 = new Function("this.className='buttonMouseDown';");
	var f7 = new Function("event","this.className='menuButtonMouseOver';setStatus(this.title);this.onclick(event)");
	var f8 = new Function("this.className='menuButton';emptyStatus();");

	for (var i=0; i < tags.length; i++) {
		if (tags[i].className.indexOf("button") == 0) {
			tags[i].onmouseover   = f1;
//			tags[i].onmouseout    = f2;
			tags[i].onmouseout    = new Function("this.className='" + tags[i].className + "';emptyStatus();");;
			tags[i].onmousedown   = f3;
			tags[i].onmouseup     = f2;
			tags[i].onselectstart = f0;
			tags[i].ondragstart   = f0;

			if(!tags[i].href) {
				tags[i].href = "#";
			}
		} else if (tags[i].className == "directButton") {
			tags[i].onmouseover   = f4;
			tags[i].onmouseout    = f5;
			tags[i].onmousedown   = f6;
			tags[i].onmouseup     = f5;
			tags[i].onselectstart = f0;
			tags[i].ondragstart   = f0;

			if(!tags[i].href) {
				tags[i].href = "#";
			}
		} else if (tags[i].className == "menuButton") {
			tags[i].onmouseover   = f7;
			tags[i].onmouseout    = f8;
			tags[i].onselectstart = f0;
			tags[i].ondragstart   = f0;
			
			if(!tags[i].href) {
				tags[i].href = "#";
			}
		}
	}
}

function initialisePopMenus() {
	hidePopMenus();
	hidePopMenu("windowMatrix");
	hidePopMenu("windowParam");
	hidePopMenu("windowOpenAscii");

	document.getElementById("frameascii").onmouseover = hidePopMenus;
	document.getElementById("divmathml").onmouseover  = hidePopMenus;

	var tags = document.getElementsByTagName("TD");
	
	var f1 = new Function("event","this.style.cursor='move';startMove(event,this.id.substring(0,this.id.length - 'Header'.length));");
	var f2 = new Function("this.style.cursor='default';stopMove();");
	
	for (var i=0; i < tags.length; i++) {
		if (tags[i].className == "header") {
			tags[i].onmousedown = f1;
			tags[i].onmouseup   = f2;
		}
	}
}

var AMVEoldX = 0;
var AMVEoldY = 0;

function startMove(event,menuID) {
	if(isNS) {
		AMVEoldX = event.clientX;
		AMVEoldY = event.clientY;
	} else {
		AMVEoldX = window.event.clientX;
		AMVEoldY = window.event.clientY;
	}

	document.body.onselectstart = new Function("event","disableEvent(event);");	
	document.onmousemove = new Function("event","movePopMenu(event,'" + menuID + "');");
}

function stopMove() {
	AMVEMove = false;
	document.onmousemove = null;
	document.body.onselectstart = null;	
}

function movePopMenu(event,menuID) {
	var menu;
	var currentX, currentY, deltaX, deltaY;
	if(isNS) {
		currentX = event.clientX;
		currentY = event.clientY;
		deltaX = currentX - AMVEoldX;
		deltaY = currentY - AMVEoldY;
		menu = document.getElementById(menuID);
		menu.style.left  = parseInt(menu.style.left.replace(/px/gi, "")) + deltaX;
		menu.style.top   = parseInt(menu.style.top.replace(/px/gi, "")) + deltaY;
		AMVEoldX = currentX;
		AMVEoldY = currentY;
	} else {
		currentX = window.event.clientX;
		currentY = window.event.clientY;
		deltaX = currentX - AMVEoldX ;
		deltaY = currentY - AMVEoldY;
		menu = document.getElementById(menuID);
		menu.style.left  = menu.style.pixelLeft + deltaX;
		menu.style.top   = menu.style.pixelTop + deltaY;
		AMVEoldX = currentX;
		AMVEoldY = currentY;
	}	
}

function hidePopMenus() {
	var tags = document.getElementsByTagName('TABLE');
	for (var i=0; i < tags.length; i++) {
		if (tags[i].className.indexOf("menuPop") == 0) {
			hidePopMenu(tags[i].id);
		}
	}
}

function hidePopMenu(menuID) {
	document.getElementById(menuID).style.display = "none";
}

function showPopMenu(event,menuID,toolBarID) {
	var menu = document.getElementById(menuID);

	if(menu.style.display != "block") {
		hidePopMenus();

		menu.style.position = "absolute";

		var imgX = document.getElementById(menuID + "X");
		var imgY = document.getElementById(toolBarID + "Y");

		if(isIE) {
			if(imgX) menu.style.left = parseInt(imgX.offsetLeft) + 5;
			else menu.style.left = parseInt(window.event.clientX - window.event.offsetX - 2); 
				
			if(imgY) menu.style.top  = parseInt(imgY.offsetTop) - 5;
			else menu.style.top  = parseInt(window.event.clientY - window.event.offsetY + 24);
		} else {
			if(imgX) menu.style.left   = parseInt(imgX.x);
			else menu.style.left = parseInt(event.clientX);

			if(imgY) menu.style.top   = parseInt(imgY.y) - 4;
			else menu.style.top  = parseInt(event.clientY);
		}

		menu.style.display = "block";
	}
}

function setEncloseType(newEncloseType) {
	encloseAllFormula = newEncloseType;

	if(cookieSave) {
		deleteCookie('AMVE_ENCLOSETYPE');
		setCookie('AMVE_ENCLOSETYPE',newEncloseType,futurDate);
	}
}
function getEncloseType(defaultEncloseType) {
	var theEncloseType;
	
	theEncloseType = getURLParamValue(document.location.href,"enclosetype");
	if(!theEncloseType) theEncloseType = getCookie("AMVE_ENCLOSETYPE");
	if(!theEncloseType && defaultEncloseType) theEncloseType = defaultEncloseType;

	return getBoolean(theEncloseType);
}

function setEncloseChar(newEncloseChar) {
	encloseChar = newEncloseChar;

	if(cookieSave) {
		deleteCookie('AMVE_ENCLOSECHAR');
		setCookie('AMVE_ENCLOSECHAR',newEncloseChar,futurDate);
	}
}
function getEncloseChar(defaultEncloseChar) {
	var theEncloseChar;
	
	theEncloseChar = getURLParamValue(document.location.href,"enclosechar");
	if(!theEncloseChar) theEncloseChar = getCookie("AMVE_ENCLOSECHAR");
	if(!theEncloseChar && defaultEncloseChar) theEncloseChar = defaultEncloseChar;

	return theEncloseChar;
}


function setAutoUpdateType(newAutoUpdateType) {
	autoUpdateMathML = newAutoUpdateType;

	if(cookieSave) {
		deleteCookie('AMVE_AUTOUPDATETYPE');
		setCookie('AMVE_AUTOUPDATETYPE',newAutoUpdateType,futurDate);
	}
}
function getAutoUpdateType(defaultAutoUpdateType) {
	var theAutoUpdateType;
	
	theAutoUpdateType = getURLParamValue(document.location.href,"autoupdatetype");
	if(!theAutoUpdateType) theAutoUpdateType = getCookie("AMVE_AUTOUPDATETYPE");
	if(!theAutoUpdateType && defaultAutoUpdateType) theAutoUpdateType = defaultAutoUpdateType;

	return getBoolean(theAutoUpdateType);
}

function setAutoUpdateInterval(newAutoUpdateInterval) {
	window.clearTimeout(autoUpdateTimerID);

	autoUpdateInterval = newAutoUpdateInterval;

	if(cookieSave) {
		deleteCookie('AMVE_AUTOUPDATEINTERVAL');
		setCookie('AMVE_AUTOUPDATEINTERVAL',newAutoUpdateInterval,futurDate);
	}

	scheduleAutoUpdate();
}
function getAutoUpdateInterval(defaultAutoUpdateInterval) {
	var theAutoUpdateInterval;
	
	theAutoUpdateInterval = getURLParamValue(document.location.href,"autoupdateinterval");
	if(!theAutoUpdateInterval) theAutoUpdateInterval = getCookie("AMVE_AUTOUPDATEINTERVAL");
	if(!theAutoUpdateInterval && defaultAutoUpdateInterval) theAutoUpdateInterval = defaultAutoUpdateInterval;

	return theAutoUpdateInterval;
}

function setMenuUpdateType(newMenuUpdateType) {
	menuUpdateMathML = newMenuUpdateType;

	if(cookieSave) {
		deleteCookie('AMVE_MENUUPDATETYPE');
		setCookie('AMVE_MENUUPDATETYPE',newMenuUpdateType,futurDate);
	}
}
function getMenuUpdateType(defaultMenuUpdateType) {
	var theMenuUpdateType;
	
	theMenuUpdateType = getURLParamValue(document.location.href,"menuupdatetype");
	if(!theMenuUpdateType) theMenuUpdateType = getCookie("AMVE_MENUUPDATETYPE");
	if(!theMenuUpdateType && defaultMenuUpdateType) theMenuUpdateType = defaultMenuUpdateType;

	return getBoolean(theMenuUpdateType);
}

function updateMathMLEditor() {
	setInMathMLEditor(getDoc("frameascii").body.innerHTML);
}

function autoUpdateMathMLEditor() {
	if(autoUpdateMathML) {
		updateMathMLEditor();
	}
	
	scheduleAutoUpdate();
}

function scheduleAutoUpdate() {
	autoUpdateTimerID = window.setTimeout("autoUpdateMathMLEditor()",autoUpdateInterval*1000);	
}

function viewSymbols(file) {
	showModelessWindow(file,705,430,20,20,"winsymbols","no");
}

function initialiseSymbolList() {
	initialiseAMSymbols();
	document.getElementById('divstatus').innerHTML = "Reading data...";
	window.setTimeout("setASCIISymbolList()",1); //to let time to refresh divstatus HTML
}

function setASCIISymbolList() {
	var symbol;
	var html;
	html = "\n<table>";
	for (var i=0; i<AMVEsymbols.length; i++) {
		symbol = AMVEsymbols[i];
		html = html + "\n\t<tr class='out' onclick=\"getSymbolProperties('";
		if(symbol.input == '\\\\') html = html + "\\\\\\\\";
		else if (symbol.input != '"') html = html + symbol.input; //To Fix IE bug !
		html = html + "')\" onmouseout=\"this.className='out';\" onmouseover=\"this.className='over';\" >";
		html = html + "\n\t\t<td>";
		if(symbol.ttype == INFIX) html = html + "a";
		html = html + symbol.input;
		if(symbol.ttype == INFIX) html = html + "b";
		else if(symbol.ttype == UNARY) html = html + "(a)";
		else if(symbol.ttype == BINARY) html = html + "(a)(b)";		
		html = html + "</td>";
		html = html + "\n\t\t<td>&nbsp;"
		if(symbol.output.length == 1) html = html + symbol.output.charCodeAt(0);
		html = html + "</td>";
		html = html + "\n\t\t<td class='MOsymbol'>" + symbol.output + "</td>";
		html = html + "\n\t\t<td>&lt;" + symbol.tag + "&gt;</td>";
		html = html + "\n\t\t<td class='MMLsymbol'>`";
		if(symbol.ttype == INFIX) html = html + "a";
		html = html + symbol.input;
		if(symbol.ttype == INFIX) html = html + "b";
		else if(symbol.ttype == UNARY) html = html + "(a)";
		else if(symbol.ttype == BINARY) html = html + "(a)(b)";
		html = html + "`</td>";
		html = html + "\n\t\t<td>" + getTexteForHTML(symbol.tex) + "</td>";
		html = html + "\n\t</tr>";
	}
	html = html + "\n</table>"

	document.getElementById('divsymbols').innerHTML = html;
	
	document.getElementById('divstatus').innerHTML = "Updating MathML...";
	window.setTimeout("updateMathMLSymbolList()",1);  //to let time to refresh divstatus HTML
}

function updateMathMLSymbolList() {
	translateById("divsymbols");
	document.getElementById('divstatus').style.display='none';
}

function viewCodes(file) {
	showModelessWindow(file,500,530,20,20,"wincodes","no");
}

function initialiseCodeList() {
	initialiseButtons();
	setASCIICodeList(1,100);
}

function setASCIICodeList(i1,i2) {
	if(!i1 || !i2) {
		var href;
		if(isNS) {
			href = document.location.href;
		} else {
			var caller = window.dialogArguments;
			href = caller.href;
		}
	
		i1 = new Number(getURLParamValue(href,"i1"));
		i2 = new Number(getURLParamValue(href,"i2"));
	}
	
	if(i1 && i2 && i1!=0 && i2!=0) {
		var html;
		html = "\n<table>";
		for(var i=i1;i<=i2;i++) {
			if(i%2 == 0) html = html + "\n\t<tr class='out'>";
			else html = html + "\n\t<tr class='highlite'>";
			html = html + "\n\t\t<td>&amp;#" + i + "</td>";
			html = html + "\n\t\t<td class='MOsymbol'>&#" + i + ";</td>";
			html = html + "\n\t\t<td class='MIsymbol'>&#" + i + ";</td>";
			html = html + "\n\t</tr>";
		}
		html = html + "\n</table>"

		document.getElementById('divcodes').innerHTML = html;
	}		
}

function viewMathML(file) {
	showModelessWindow(file,450,500,100,200,"winmathml","no");
}

function loadMathML() {
	var mathMLnode;
	var mathMLStr;
	
	if(isNS) {
		var win = window.opener;
		mathMLnode = win.document.getElementById("divmathml");
		mathMLStr = node2string(mathMLnode,"").slice(1); //Very long in IE
	} else {
		var caller = window.dialogArguments;
		mathMLnode = caller.window.document.getElementById("divmathml");
		mathMLStr = mathMLnode.innerHTML.replace(/<m:/gi, "\n<m:").replace(/<m:math/gi, "<m:math xmlns=\"http://www.w3.org/1998/Math/MathML\"");
	}

	document.formmathml.textmathml.value = mathMLStr;
	document.getElementById('divstatus').style.display='none';
}

function node2string(inNode,indent) {
// Last Version by David GRIMA Feb 28 2004
// thanks to James Frazer for contributing an initial version of this function
// thanks to Peter Jipsen http://www.chapman.edu/~jipsen for Version 1.3 Feb 22 2004
   var str = "";
   if(inNode && inNode.nodeType == 1) { // (undefine inNode fix by David GRIMA)
       var name = inNode.nodeName.toLowerCase(); // (IE fix)
       str = "\r" + indent + "<" + name;
       for(var i=0; i < inNode.attributes.length; i++)
           if (inNode.attributes[i].nodeValue!="italic" &&
               inNode.attributes[i].nodeValue!="" &&  //stop junk attributes
               inNode.attributes[i].nodeValue!="inherit" && // (mostly IE)
               inNode.attributes[i].nodeValue!=undefined)
               str += " "+inNode.attributes[i].nodeName+"="+
                     "\""+inNode.attributes[i].nodeValue+"\"";
       if (name == "math") 
           str += " xmlns=\"http://www.w3.org/1998/Math/MathML\"";
       str += ">";
       for(var i=0; i<inNode.childNodes.length; i++)
           str += node2string(inNode.childNodes[i], indent+"  ");
       if (name != "mo" && name != "mi" && name != "mn") str += "\r"+indent;
       str += "</" + name + ">";
   }
   else if(inNode &&  inNode.nodeType == 3) { // (undefine inNode fixed by David GRIMA)
       var st = inNode.nodeValue;
       for (var i=0; i<st.length; i++)
           if (st.charCodeAt(i)<32 || st.charCodeAt(i)>126)
               str += "&#"+st.charCodeAt(i)+";";
           else if (st.charAt(i)=="<") str += "&lt;";
           else if (st.charAt(i)==">") str += "&gt;";
           else if (st.charAt(i)=="&") str += "&amp;";
           else str += st.charAt(i);
   }
   return str;
}

function saveAscii() {
	//TO DO	: a IO system file save with FileSystemObject ActiveX

	if(isIE) {
		var doc = getDoc("frameascii");
		doc.execCommand("SaveAs","true","*.txt");
	} else {
		alert(getText("SORRY_ONLY_IE"));
	}
}

function closeEditor() {
	if(window.opener && !window.opener.closed) {
		window.opener.focus();
		if(textAreaForSaveASCII) textAreaForSaveASCII.focus();
	}
	self.close();
}

function setEquationInCaller() {
	if(window.opener && !window.opener.closed) {
		if(textAreaForSaveASCII) {
			var content;
			if(isNS) {
				content = getDoc("frameascii").body.innerHTML;
				content = content.replace(/<br>/gi, "\n");
				content = content.replace(/&lt;/gi, "<");
				content = content.replace(/&gt;/gi, ">");
				content = content.replace(/&amp;/gi, "&");
				content = content.replace(/&nbsp;/gi," ");
			} else {
				content = getDoc("frameascii").body.innerText;
			}
			textAreaForSaveASCII.value = content;
		}

		closeEditor();
	} else {
		alert("No caller input!")
	}
}

function newEditor() {
	showWindow("asciimathvisualeditor.html",760,520,100,100);
}

function openAscii() {
/*
		//TO DO	: a IO system file save with FileSystemObject ActiveX

		if(isIE) {
			var doc = getDoc("frameascii");
			doc.execCommand("Open","true","*.txt");
		} else {
			alert(getText("SORRY_ONLY_IE"));
		}
*/

//	var frameDoc = getDoc("frameascii");
//	frameDoc.location.href = "file:///" + document.formopen.filepath.value;
// TO DO : Set <html><head><style>... ...</html>

	if(document.formopen.filepath.value) {
		getDoc("frameascii").location.href = "file:///" + document.formopen.filepath.value;
	
		hidePopMenu("windowOpenAscii");
	}
}

function loadAscii() {
	var content = null;
	if(window.opener && !window.opener.closed) {
		if(textAreaForSaveASCII) {
			content = textAreaForSaveASCII.value
		} else {
			var formula = getURLParamValue(document.location.href.replace(/%26/gi,"~AND~"),"formula");
			if(formula) {
				content = formula.replace(/~AND~/gi,"&");
			}
		}
	}

	if(content) {
		content = content.replace(/</gi,"&lt;");
		content = content.replace(/>/gi,"&gt;");
		content = content.replace(/\n/gi,"<br/>");
		content = content.replace(/ /gi,"&nbsp;");
		getDoc("frameascii").body.innerHTML = content;

		updateMathMLEditor();
	}

}

function getURLParamValue(url,paramName) {
	var paramValue = null;
	var querystring = getURLQuerystring(url);

	if (querystring) {
		var arrayOfParameters = querystring.split("&");
		var tempParamName;
		var tempParamValue;
		var parameter;

		for (var i = 0; i < arrayOfParameters.length; i++) {
			parameter = arrayOfParameters[i];
			posEqual = parameter.indexOf("=");

			if(posEqual > 0) {
				tempParamName = parameter.substring(0,posEqual);
				tempParamValue = parameter.substring(posEqual+1,parameter.length);
			} else {
				tempParamName = parameter;
				tempParamValue = parameter;
			}

			if(tempParamName == paramName) {
				paramValue = tempParamValue;
				break;
			}
		}
	}
	
	return paramValue;
}

function getURLQuerystring(url)
{
	var querystring;

	if ((url != null) && (url != ""))
	{
		querystring = unescape(url);
		
		var posQuerystring = querystring.indexOf("?");
		if (posQuerystring > 0)	{
			var posAnchor = querystring.indexOf("#");
			if (posAnchor > 0) {
				querystring = querystring.substring(posQuerystring+1, posAnchor);
			} else {
				querystring = querystring.substring(posQuerystring+1);
			}
		} else {
			querystring = null;
		}
	}

	return querystring;
}

function getURLAnchor(url) {
	var anchor;

	if ((url != null) && (url != ""))
	{
		anchor = unescape(url);
		
		var posAnchor = anchor.indexOf("#");
		if (posAnchor > 0) {
			anchor = anchor.substring(posAnchor+1);
		} else {
			anchor = null;
		}
	}

	return anchor;
}

function getURLUri(url) {
	var uri;

	if ((url != null) && (url != ""))
	{
		uri = unescape(url);
		
		var posQuerystring = uri.indexOf("?");
		if (posQuerystring > 0)	{
				uri = uri.substring(0, posQuerystring);
		} else {
			var posAnchor = uri.indexOf("#");
			if (posAnchor > 0) {
				uri = uri.substring(0, posAnchor);
			}
		}
	}

	return uri;
}

function replaceURLParamValue(url,paramName,newParamValue) {
		var newURL;
		
		var uri = getURLUri(url);
		var querystring = getURLQuerystring(url);
		var anchor = getURLAnchor(url);

		newURL = uri;

		if(querystring) {
			var re = new RegExp(paramName + "=","gi");
			var s = "old" + paramName + "=";
		
			newURL = newURL + "?" + querystring.replace(re,s) + "&" + paramName + "=" + newParamValue;
		}
		else {
			newURL = newURL + "?" + paramName + "=" + newParamValue;
		}

		if(anchor) newURL = newURL + "#" + anchor;

		return newURL;
}

function setCookie(name,value,expires,path,domain,secure) {
	document.cookie = name + "=" + escape (value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "; path=/") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return getCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",new Date(1999,11,31));
}

function getStyle(defaultStyle) {
	var theStyle;

	theStyle = getURLParamValue(document.location.href,"style");
	if(!theStyle) theStyle = getCookie("AMVE_STYLE");
	if(!theStyle && defaultStyle) theStyle = defaultStyle;

	return theStyle;
}

function setStyle(newstyle) {
	if(newstyle && newstyle != "-" && newstyle != style) {

		if(cookieSave) {
			deleteCookie('AMVE_STYLE');
			setCookie('AMVE_STYLE',newstyle,futurDate);
		}

		style = newstyle;
		//document.location.href = replaceURLParamValue(document.location.href,"style",newstyle);
		choseCSS();
	}
}

/* Currently possible styles are :
javaLook
outsetBlue
officeXP
*/

function writeIMG(src) {
	document.write("<img class='symbol' src='../images/" + mathcolor + "/" + src + "' border='0'/>");
}

function writeAllCSS() {
	var styleDir = "../styles/" + style + "/";

	document.write("<link rel='stylesheet' type='text/css' href='../styles/style.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "tools.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "asciimathvisualeditor.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "frameascii.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "winlist.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "winmathml.css'/>");
	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + "winisotope.css'/>");
}

function writeCSS(file) {
	var styleDir = "../styles/" + style + "/";

	document.write("<link rel='stylesheet' type='text/css' href='" + styleDir + file + "'/>");
}

function choseCSS() {
	var styles = document.getElementsByTagName('style');
	for(var i = 0; i < (styles.length); i++) {
		var title = styles[i].getAttribute("title");
		if(title != style) {
			styles[i].disabled = true;
		} else {
			styles[i].disabled = false;
		}
	}
}

function getLanguage(defaultLanguage) {
	var theLanguage;
	
	theLanguage = getURLParamValue(document.location.href,"language");
	if(!theLanguage) theLanguage = getCookie("AMVE_LANGUAGE");
	if(!theLanguage && defaultLanguage) theLanguage = defaultLanguage;

	return theLanguage;
}

function setLanguage(newlanguage) {
	if(newlanguage && newlanguage != "-" && newlanguage != language) {

		if(cookieSave) {
			deleteCookie('AMVE_LANGUAGE');
			setCookie('AMVE_LANGUAGE',newlanguage,futurDate);
		}

		document.location.href = replaceURLParamValue(document.location.href,"language",newlanguage);
	}
}

function writeText(textID) {
	document.write(getText(textID));
}

function getText(textID,lang) {
	if(lang==null) lang=language;
	var text = AMVE_languageRessource[lang][textID];
	if(text == null) text="";
	return text;
}

function setCookieSaveType(cookieSaveType) {
	cookieSave = cookieSaveType;

	if(cookieSave) {
		deleteCookie('AMVE_COOKIESAVETYPE');
		setCookie('AMVE_COOKIESAVETYPE',cookieSave,futurDate);

		deleteCookie('AMVE_STYLE');
		setCookie('AMVE_STYLE',style,futurDate);

		deleteCookie('AMVE_LANGUAGE');
		setCookie('AMVE_LANGUAGE',language,futurDate);

		deleteCookie('AMVE_ENCLOSECHAR');
		setCookie('AMVE_ENCLOSECHAR',encloseChar,futurDate);

		deleteCookie('AMVE_ENCLOSETYPE');
		setCookie('AMVE_ENCLOSETYPE',encloseAllFormula,futurDate);

		deleteCookie('AMVE_MENUUPDATETYPE');
		setCookie('AMVE_MENUUPDATETYPE',menuUpdateMathML,futurDate);

		deleteCookie('AMVE_AUTOUPDATETYPE');
		setCookie('AMVE_AUTOUPDATETYPE',autoUpdateMathML,futurDate);

		deleteCookie('AMVE_AUTOUPDATEINTERVAL');
		setCookie('AMVE_AUTOUPDATEINTERVAL',autoUpdateInterval,futurDate);

	} else {
		deleteCookie('AMVE_COOKIESAVETYPE');
		deleteCookie('AMVE_STYLE');
		deleteCookie('AMVE_LANGUAGE');
		deleteCookie('AMVE_ENCLOSECHAR');
		deleteCookie('AMVE_ENCLOSETYPE');
		deleteCookie('AMVE_MENUUPDATETYPE');
		deleteCookie('AMVE_AUTOUPDATETYPE');
		deleteCookie('AMVE_AUTOUPDATEINTERVAL');
	}
}
function getCookieSaveType(defaultCookieSaveType) {
	var theCookieSaveType;
	
	theCookieSaveType = getURLParamValue(document.location.href,"cookiesavetype");
	if(!theCookieSaveType) theCookieSaveType = getCookie("AMVE_COOKIESAVETYPE");
	if(!theCookieSaveType && defaultCookieSaveType) theCookieSaveType = defaultCookieSaveType;

	return getBoolean(theCookieSaveType);
}

function showMatrixWindow(event,rows,cols,toolBarID) {
	showPopMenu(event,'windowMatrix',toolBarID);
	updateMatrixWindow(rows,cols);
}

function updateMatrixWindow(rows,cols) {
	if(rows) document.formmatrix.rows.value = rows;
	if(cols) document.formmatrix.cols.value = cols;
	
	rows = document.formmatrix.rows.value;
	cols = document.formmatrix.cols.value;

	var html = "<table>";
	for(var r=1; r<=rows; r++) {
		html += "<tr>";
		for(var c=1; c<=cols; c++) {
			html = html + "<td><input type='text' size='4' name='a_" + r + c + "' value='a_" + r + c + "'/></td>";
		}
		html += "</tr>";
	}
	html += "</table>";

	document.getElementById("showMatrix").innerHTML = html;
}

function setMatrixInEditor() {
	var cols = document.formmatrix.cols.value;
	var rows = document.formmatrix.rows.value;

	var formula = document.formmatrix.leftbracket.value;
	for(var r=1; r<=rows; r++) {
		formula += "(";
		for(var c=1; c<=cols; c++) {
			//formula = formula + "a_" + r + c;
			
			eval("formula = formula + document.formmatrix.a_" + r + c + ".value");
			
			if(c<cols) formula += ",";
		}

		formula += ")";

		if(r<rows) formula += ",";
	}
	formula += document.formmatrix.rightbracket.value;
	
	hidePopMenu("windowMatrix");
	setInEditor(formula);
}


function viewIsotope(file) {
	showModelessWindow(file,600,530,20,500,"winisotope","yes");
}

function setIsotopeInEditor(tag) {
	var html = tag.innerHTML;
	var formula = html;
	var iSUP = html.toLowerCase().indexOf("<sup>");
	var iEndSUP = html.toLowerCase().indexOf("</sup>");

	if( (iSUP > -1) && (iEndSUP > iSUP + "<sup>".length) ) {
		var atomicNb = html.substring(iSUP + "<sup>".length, iEndSUP);
		var element = html.substring(iEndSUP + "</sup>".length, html.length);

		formula = "{::}^" + atomicNb + "text(" + element + ")";
	}

	if(isNS) {
		var win = window.opener;
		win.setInEditor(formula);
	} else {
		var caller = window.dialogArguments;
		caller.window.setInEditor(formula);
	}

	document.element.elementID.selectedIndex = 0;
	document.element.elementName.selectedIndex = 0;
}

function selectElement(selectList) {
	document.location.href = "#" + selectList.options[selectList.selectedIndex].value;
	document.element.elementID.selectedIndex = selectList.selectedIndex;
	document.element.elementName.selectedIndex = selectList.selectedIndex;
}

function viewInfo(file) {
	showWindow(file,600,480,20,400,"wininfo","yes");
}