function loadXML(XMLf)
{
	var xslf="_en_ly_appmenu.xsl";
	var sw = new Array();
	sw['news.aspx?cateid=d9cf0b374cdc4f5bb6ff557cf0e5a8d8'] = 'news.aspx?cateid=073a9bde1ef648d2b00a5498d3967c61';
	sw['news.aspx?cateid=fda7c12415354660942d7458c0bb33b1'] = 'news.aspx?cateid=6a3b067e956d4fd1a1d0c132291b8ff3';
	sw['news.aspx?cateid=4fb48d3ce6404472a6ead3bfa0eaab87'] = 'news.aspx?cateid=90118d8136c141e88f168a3dc8c8b7ef';
	sw['news.aspx?cateid=073a9bde1ef648d2b00a5498d3967c61'] = 'news.aspx?cateid=d9cf0b374cdc4f5bb6ff557cf0e5a8d8';
	sw['news.aspx?cateid=6a3b067e956d4fd1a1d0c132291b8ff3'] = 'news.aspx?cateid=fda7c12415354660942d7458c0bb33b1';
	sw['news.aspx?cateid=90118d8136c141e88f168a3dc8c8b7ef'] = 'news.aspx?cateid=4fb48d3ce6404472a6ead3bfa0eaab87';
	try
	{
		if (navigator.userAgent.toLowerCase().indexOf("safari") >= 0) 
		{
			var current = MUrl.decode(window.location.href.substring(window.location.href.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9_=]*/g, ''));
			if (current.indexOf('#') >= 0)
				current = current.substring(0, current.indexOf('#'));;
			current = current.replace(/"/g,'')
			var xmlhttp = new XMLHttpRequest();
			xmlhttp.open("GET", "SiteMapXslt.aspx?xml=" + XMLf + "&xsl=" + xslf, false);
			xmlhttp.async = false;
			xmlhttp.send(null);
			var HTML = xmlhttp.responseText;
			var index = HTML.indexOf('id="appmenu"');
			HTML = HTML.substring(0, index+12) + ' style="width:100%;" ' + HTML.substring(index+12);
			
			document.getElementById('Menu').getElementsByTagName('td')[0].innerHTML = HTML;
			var td = document.getElementById('Menu').getElementsByTagName('td')[0];
			menuHighlight(td, current, sw);
		}
		else if (navigator.userAgent.indexOf('MSIE') >= 0) 
		{
			var myXML=new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
			myXML.async=false;
			myXML.load(XMLf);
			myXML.setProperty("SelectionLanguage", "XPath");
			var current = MUrl.decode(window.location.href.substring(window.location.href.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9_=]*/g, ''));
			if (current.indexOf('#') >= 0)
				current = current.substring(0, current.indexOf('#'));;
			current = current.replace(/"/g,'');
			
			var nCur = myXML.selectSingleNode('//Menu[@id != "appmenu"]/Level[contains("'+current+'",translate(@pageid, "ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"))]');
			if (!nCur) 
			{
				current = sw[current] || current;
				nCur = myXML.selectSingleNode('//Menu[@id != "appmenu"]/Level[contains("'+current+'",translate(@pageid, "ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"))]');
			}
			if (nCur) 
			{
				nCur.setAttribute('selected', '_s');
				//var i = parseInt(nCur.parentNode.getAttribute('id').substring(8));
				link = nCur.parentNode.getAttribute('id');
				var p = myXML.selectSingleNode('//Menu[@id="appmenu"]/Level[@link="' + link + '"]');
				if (p)
					p.setAttribute('selected', '_s');
			}
			else 
			{
			        var p = myXML.selectSingleNode('//Menu[@id = "appmenu"]/Level[contains("'+current+'",translate(@pageid, "ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"))]');
				if (!p) 
				{
				    current = sw[current] || current;
				    p = myXML.selectSingleNode('//Menu[@id = "appmenu"]/Level[contains("'+current+'",translate(@pageid, "ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"))]');
				}
			        if (p)
			            p.setAttribute('selected', '_s');
			}
			
			var myxsl=new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
			myxsl.async=false;  
			myxsl.load(xslf);
			HTML=myXML.transformNode(myxsl);
			
			document.write(HTML);
		}
		else if (navigator.userAgent.indexOf('Firefox') >= 0) 
		{
			var current = MUrl.decode(window.location.href.substring(window.location.href.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9_=]*/g, ''));
			if (current.indexOf('#') >= 0)
				current = current.substring(0, current.indexOf('#'));;
			current = current.replace(/"/g,'')

			var myXML=document.implementation.createDocument("","",null);
			myXML.async=false;
			myXML.load(XMLf);
			var myxsl=document.implementation.createDocument("","",null);
			myxsl.async=false;  
			myxsl.load(xslf);
			var oProcessor = new XSLTProcessor();
			oProcessor.importStylesheet(myxsl);
			oResultDom=oProcessor.transformToFragment(myXML, document);
			var serializer = new XMLSerializer();
			HTML=serializer.serializeToString(oResultDom);
			
			var index = HTML.indexOf('id="appmenu"');
			HTML = HTML.substring(0, index+12) + ' style="width:100%;" ' + HTML.substring(index+12);
			var td = document.getElementById('Menu').getElementsByTagName('td')[0];
			var range = td.ownerDocument.createRange();
			range.selectNodeContents(td);
			range.deleteContents();
			var fragment = range.createContextualFragment(HTML);
			td.appendChild(fragment);

			menuHighlight(td, current, sw);
		}
		else if (navigator.userAgent.toLowerCase().indexOf("blackberry") >= 0) 
		{
			var current = MUrl.decode(window.location.href.substring(window.location.href.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9_=]*/g, ''));
			if (current.indexOf('#') >= 0)
				current = current.substring(0, current.indexOf('#'));;
			current = current.replace(/"/g,'')
			var xmlhttp = new XMLHttpRequest();
			xmlhttp.open("GET", "SiteMapXslt.aspx?xml=" + XMLf + "&xsl=" + xslf, false);
			xmlhttp.async = false;
			xmlhttp.send(null);
			var HTML = xmlhttp.responseText;
			var index = HTML.indexOf('id="appmenu"');
			HTML = HTML.substring(0, index+12) + ' style="width:100%;" ' + HTML.substring(index+12);
			
			document.getElementById('Menu').getElementsByTagName('td')[0].innerHTML = HTML;
			var td = document.getElementById('Menu').getElementsByTagName('td')[0];
			menuHighlight(td, current, sw);
		}
		else 
		{
			alert('Your browser is not currently supported.');
			return;
		}			
	}
	catch (exception)
	{
		alert(exception.description);
	}
		
	if (window.$)
		$(document).ready(function() {
			genSubmenu();
			//if($('ul.submenu').length == 0) $('div.schBody').css('margin-top', '33px');
		});
		else
			setTimeout('genSubmenu()', 200);

}

var genSubmenuCounter = 3;

var MUrl = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function genSubmenu() {
//alert("A");
    var current;
var c = 0;
    if (window.location.href.indexOf('referrer=') >= 0)
    {
//alert("B");
        var surl = MUrl.decode(window.location.href);
        current = surl.substring(surl.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9-_=]*/g, '').replace(/#[a-z0-9-_=]*/g, ''); 
        // have to set special case for disclaimer, because the refermenu could not be used 
        // setting for Retail 
        var pURL = current.replace(/\?[a-z0-9-_=&.,]*/g, '');
        var sDtl = '|comparefunds.aspx|fundprices.aspx|performance.aspx|cumulativeperformance.aspx|fundfactsheetsreports.aspx|annualreturn.aspx|funddetails.aspx|historicalfundprices.aspx|portfolioinformation.aspx|performance.aspx|';
        if ( sDtl.toLowerCase().indexOf('|' + pURL + '|') >= 0)
            current = 'fundprices.aspx' ; 
         if (pURL.indexOf('fund-codes.aspx') >= 0 ) 
            current = 'fund-codes.aspx' ;
         if (pURL.indexOf('fund-dividends.aspx') >= 0 ) 
            current = 'fund-dividends.aspx' ;
        // seting for MPF 
        sDtl = '|MPFHistfundprices.aspx|fund-fact-sheets-reports.aspx|'
        if (sDtl.toLowerCase().indexOf('|' + pURL + '|') >= 0)
            current = 'MPFfund-prices.aspx' ; 
        // seting for ORSO 
        sDtl = '|ORSOLPfund-fact-sheets-reports.aspx|ORSOSPPfund-prices.aspx|ORSOSPPfund-fact-sheets-reports.aspx|ORSOSPPHistfundprices.aspx|'
        if (sDtl.toLowerCase().indexOf('|' + pURL + '|') >= 0)
            current = 'ORSOLPfund-prices.aspx' ; 
        current = current.toLowerCase() ; // for prevent letter issue 
        //alert(pURL);
    }
    else
    {
        current = window.location.href.substring(window.location.href.lastIndexOf('/') + 1).toLowerCase().replace(/&[a-z0-9_=]*/g, '').replace(/#[a-z0-9-_=]*/g, '');
    }
//alert("1 " + current);
    if (document.getElementById('refermenu'))
        current = document.getElementById('refermenu').getAttribute('link').toLowerCase();
//alert("2 " + current);
    var top = document.getElementById('appmenu');
	if(document.getElementById('appmenu')){
    for (c=0; c<top.childNodes.length; c++) {
        if(sub = document.getElementById(top.childNodes[c].getAttribute('link'))) {
            for (var cc=0; cc<sub.childNodes.length; cc++) {
		var href = getFirstChildElem(sub.childNodes[cc]).href;
               // var href = sub.childNodes[cc].firstChild.href;

                href = href.substring(href.lastIndexOf('/') + 1).toLowerCase();
//alert(href);
                if (href == current) {

                  top.childNodes[c].className = 'ly_mn0_s';
                  sub.childNodes[cc].className = ('ly_mnp_s' + (cc == 0 ? ' firstlink' : ''));
                  break;
                }
            }
        }
    }

    for (c=0; c<top.childNodes.length; c++) {
        if (top.childNodes[c].className == 'ly_mn0_s') {
            break;
        }
    }
//alert(top.childNodes.length);
//alert(c);
    if (top.childNodes.length == c)
      return;
//alert(c);
    if (document.getElementById(top.childNodes[c].getAttribute('link'))) {
        var td = document.getElementById(top.childNodes[c].getAttribute('link')).parentNode;
        var clone = document.getElementById(top.childNodes[c].getAttribute('link')).cloneNode(true);
        clone.id = clone.id + '_clone';
        clone.className = 'submenu';
        td.appendChild(clone);
    }
    }
    else
    {
	if (genSubmenuCounter-- > 0)
		setTimeout('genSubmenu()', 200);
    }
}





function changeMonthYear(vname)
{
	setValue( '_' + vname + '_cal_tp', 'month');
	formSubmit('');
}

/* 2006-02-01 : enhanced to accept year as optional argument */
function gotoDay( tp, vname,  month, day, year) {
	if (year != null)
		setValue(vname+'_cal_year', year);
	setValue( vname + '_cal_month', month);
	setValue( '_' + vname + '_cal_day', day);
	setValue( '_' + vname + '_cal_tp', tp);
	formSubmit('');
}

function toggleTreeMenu(id)
{
	// change img 
	var el = document.getElementById(id);
	
	var elFC = el.firstChild;

	if (el.className == 'treemenu_opened')
	{
		elFC.setAttribute('src','../images/standardform/plus.gif');
		el.className = 'treemenu_closed';
	}
	else 
	{
		elFC.setAttribute('src','../images/standardform/minus.gif');
		el.className = 'treemenu_opened';
	}
	// get first sibling 
	var ele = elFC;
	while (ele != null)
	{
		if (ele.tagName == 'UL')
		{
			var nd = ele.firstChild;
			while (nd != null)
			{
				if (nd.nodeType == 1)
				{
					if (nd.style.display == 'none')
						nd.style.display='';
					else
						nd.style.display='none';
				}
				nd = nd.nextSibling;
			}
		}
		ele = ele.nextSibling;
	}
}

function toggle_treeview(nName, image, treeicon) {

	var nodeName=document.getElementById("node_" + nName);
	var imgName=document.images["img_" + nName];
	var src;

	if (nodeName.style.display == "none") {
		nodeName.style.display = "block";
		if( image == null)
		{
			if (treeicon == null || treeicon == '')
				src = "../images/standardform/open.gif";
			else
				src = "../images/"+treeicon+"_open.gif";
			imgName.src = src;
		}
		setValue("tg_" + nName, "1" );
	}
	else {
		nodeName.style.display = "none";
		if( image == null )
		{
			if (treeicon == null || treeicon == '')
				src = "../images/standardform/fold.gif";
			else
				src = "../images/"+treeicon+"_fold.gif";
			imgName.src = src;
		}
		setValue("tg_" + nName, "0" );
	}
}

function showHTMLToolbar(e,idName, offset) {

	var id = "";
	var layoutID = "";
	
//	if(!colorPickerWin.closed)
//		colorPickerWin.close();
	for (var i=0;i< document.ContentForm.elements.length;i++)
	{
		id = document.ContentForm.elements[i].id;
		if((id.substring(0,4) == "frt_") && (id.substring(id.length-10, id.length) == "_Paragraph"))
		{
			layoutID = id.replace("Paragraph", "Toolbar")
	
			if(layoutID != idName)
			{
				var f=getID(layoutID);
				f.style.display = "none";
				setSelect("visible");	
			}	
		}
	
	}
			
	var p = getID(idName);
	if( p != null ) 
	{
		var s = p.style;
		p.width = 500;
		eventX = findMenuPos(0, e, offset);
		eventY = findMenuPos(1, e, offset);				
				
		if(offset == 0)
			eventY +=  e.offsetHeight;
		else 
			eventX +=  e.clientWidth;
			
		s.left = eventX;	
		s.display="block"
		s.top=eventY - e.height - p.clientHeight+18;
								
		setHTMLSelect("hidden" , s.left.replace('px',''), s.top.replace('px',''), p.clientHeight , e.width);
	}

	autoFitInParentIframe2();
}

function setHTMLSelect(s , topX, topY, toolHeight, toolWidth)
{	
	var p = document.ContentForm;
	var id = "";
	for (var i=0;i< p.elements.length;i++)
		if ( p.elements[i].type == "select-one" ) 
		{
			id = p.elements[i].id;			
			if(id.substring(0,4) != "frt_")
			{	
				eventX = findMenuPos(0, p.elements[i], 0);
				eventY = findMenuPos(1, p.elements[i], 0);
				
				eventY +=  p.elements[i].offsetHeight;
				
					
				var lowerY = 0;
				var upperY = 0;
				var positionY = 0;
				
				var leftX = 0;
				var rightX = 0;
				var positionX = 0;
				
				lowerY = parseInt(topY);
				upperY = parseInt(topY) + parseInt(toolHeight);
				positionY = parseInt(eventY);
				
				leftX = parseInt(topX);
				rightX = parseInt(topX) + parseInt(toolWidth);
				positionX = parseInt(eventX);
				
				
				if(((lowerY <= positionY) && (positionY <= upperY)) && ((leftX <= positionX) && (positionX <= rightX)))
				{									
					p.elements[i].style.visibility = s;
				}
			}
		}
}

function setHTMLToolbarMouseOverOn(idName) {

	var p = getID(idName);
	p.mouseOver = "1";

}

function setHTMLToolbarMouseOut(idName) {

	var p = getID(idName);
	p.mouseOver = "0";
}


function closeHTMLToolbar(idName) {

	var p = getID(idName);
	
	if(p.mouseOver == '0')
	{
		p.style.display = "none";
		setSelect("visible");
	}
	
}

function toggle_expandview(idName, vName, image) {
	
	var nodeName=document.getElementById(idName);	
	var imgName=document.images[idName];
		
	if(idName.toString().indexOf("view_open") != -1) {
		nodeName.style.display = "none";
		getID(vName+'_view_open').style.display = 'none';   
		getID(vName+'_view_fold').style.display = 'block'; 
		collapseall(vName);
	
	}
	else {
	
		nodeName.style.display = "none";		
		getID(vName+'_view_open').style.display = 'block';   
		getID(vName+'_view_fold').style.display = 'none'; 
		expandall(vName);
	}
}


function ExpandTreeView(nName, image)
{
	var nodeName=document.getElementById("node_" + nName);
	var imgName=document.images["img_" + nName];

	if (nodeName != null)
	{
		nodeName.style.display = "block";
		if( image == null)
			imgName.src = "..\\images\\standardform\\open.gif"
		setValue("tg_" + nName, "1")
	}
	
}
	

function CollapseTreeView(nName, image)
{
	var nodeName=document.getElementById("node_" + nName);
	var imgName=document.images["img_" + nName];
	
	if (nodeName != null)
	{
		nodeName.style.display = "none";
		if( image == null )
			imgName.src = "..\\images\\standardform\\fold.gif"
		setValue("tg_" + nName, "0" )	
	}
	
}




function showTabSelect(ntab, tp){
	ftrace("showTabSelect")
	var tpg = "_tabpage_" + tp
	var ctab = getValue( tpg )
	if( ctab == "" ) 
		ctab = "1"
	setDisplay( tpg + "_" + ctab, false )
	setDisplay( tpg + "_" + ntab, true )
	setValue( tpg, ntab )
}

function showTab(ntab, tp)
{
	ftrace("showTab")
	var tpg = "_tabpage_" + tp
	var ctab = getValue( tpg )
	if( ctab == "" ) 
		ctab = "1"
	setDisplay( tpg + "_" + ctab, false )
	setDisplay( tpg + "_" + ntab, true )
	setClass( "_tab_" + tp + "_" + ctab, "tab" ) 
	setClass( "_tab_" + tp + "_" + ntab, "tabselected" ) 
	setValue( tpg, ntab )
}

function hightlight(m, s) {
	m.className = s;
}

function highlight(m, s) {
	m.className = s;
}

function setSelect(s)
{
	var	cl;
	var	atb;
	cl = doc.getElementsByTagName('select');
	if (!!cl)
	{
		for (k = 0; k < cl.length; k++)
		{
			if (cl[k].type == "select-one")
				cl[k].style.visibility = s;
		}
	}
/*
	var p = document.ContentForm;
	for (var i=0;i< p.elements.length;i++)
		if ( p.elements[i].type == "select-one" ) 
			p.elements[i].style.visibility = s;
*/
}

function toogleDisplay(p, p2, sty) {
	var s = document.all[p];
	var s2 = document.all[p2];
	if( s.style.display == "block" )
	{
		s.style.display = "none"; 
		if( s2 != null )
			s2.className = sty + "_close";
	}
	else
	{
		s.style.display = "block"; 
		if( s2 != null )
			s2.className = sty + "_open";
	}
}

function changePortal(form) {
	portalSubmit(s.options[s.selectedIndex].value);
}

function findMenuPos(dir, obj, offset)
{
	var cobj = obj;
	//alert(obj.offsetParent.offsetLeft);
	for( var cur = 0; obj.offsetParent; obj = obj.offsetParent)
	{
		// modified on 2006-02-16 
		// For view's pull down menu
		if (obj.tagName == "UL" && obj.style.display == 'block')
		{		
			cur += dir == 0 ? parseInt(obj.style.left.replace('px','')) : parseInt(obj.style.top.replace('px',''));
			break;
		}
		
		if (offset == 0 && obj.tagName == 'UL')
			break;
/*
		if( dir == 0 && obj.tagName == 'UL' && obj.className != 'ly_mn_Lp')
		{
			if( obj.parentNode.id != 'classic_pmenu' )
				break;
			else
				cur += cobj.offsetWidth;
		}
*/
		cur += dir == 0 ? obj.offsetLeft : obj.offsetTop
		//alert('Tag_'+obj.tagName+ '    left_'+obj.offsetLeft+ '    top_'+obj.offsetTop+ '    cur_'+cur);
		
	}
	return cur;
}


function showpulldownmenu(fieldname, viewkey, e, menu, offset) {
	setValue(fieldname, viewkey);
	showmenu(e, menu, offset);
}



function showmenu(e,menu,offset){

	var p = getID(menu);
	if( p != null ) 
	{
		var s = p.style;
		eventX = findMenuPos(0, e, offset);
		eventY = findMenuPos(1, e, offset);
		eventY += 1;
		if(offset == 0)
		{
			eventY +=  e.offsetHeight;
		}
		else 
			eventY +=  e.clientHeight;

		var dx = document.body.clientWidth-eventX - p.offsetWidth;
		var dy = document.body.clientHeight-eventY - p.offsetHeight;
		s.left = eventX + (dx < 0 ? dx : 0) + "px";
	//	s.top= eventY + (dy < 0 ? dy: 0) + "px";
		s.top = eventY + "px";

		var newY = 0;
		newY = eventY + p.clientHeight - (document.body.clientHeight + document.body.scrollTop);
			
		//if(newY > 0)
		//	s.top = (eventY - p.clientHeight) + "px";

		//setSelect("hidden");

		/*var addOffset = false;
		for( var obj = e; obj.parentNode; obj= obj.parentNode)
		{
			if (obj.tagName == 'TABLE')
			{
			      if(obj.parentNode.tagName != 'BODY')
			     {
				addOffset = true;
				break;
			     }
			}
		}
		if (e.parentNode.className == 'ly_mn0' && addOffset){
			s.left = eventX + e.offsetParent.offsetLeft;
			s.top = eventY + e.offsetParent.offsetTop;
		}*/
		s.display="block"

	}
	clearhidemenu(menu);
}

var timeOut = new Array();

function closeMenu(menu){

	var im = menu.split("_")
	var mn = im[0];
	for( var i=1; i < im.length; i++)
	{
		mn += "_" + im[i];
		var p = getID(mn)
		if( p != null )
		{
			if( p.className == 'ly_mn_Lp' )
				timeOut[mn] = setTimeout("hidemenu(\'" +  mn + "\')", (5 - i) * 50);
		}
	}
}

function hidemenu(menu){ 
	var p = document.getElementById(menu);
	if (p != null) {
		p.style.display = "none";
		setSelect("visible");
	}
}

function clearhidemenu(menu){
		var im = menu.split("_")
		var mn = im[0];
		for( var i=1; i < im.length; i++)
		{
			mn += "_" + im[i];
			if( timeOut[mn] != null )
			{
				clearTimeout(timeOut[mn]);
				timeOut[mn] = null;
			}
		}
}

var pmenu = null

function setMenu(menu, id)
{
	if( pmenu != null )
		pmenu.style.display = "none"
	else {
		var k = getID(getValue("menuSelected"))
		if( k != null )
			pmenu.style.display = "none"
	}		
	setValue('_menu_LS', id)
	var p = getID(menu)
	if( p != null )
	{
		var s = p.style
		pmenu = s
		s.display = "inline"
	}
	else
		pmenu = null
}


	// Custom function to call when user clicks on a link
	function fs_scrap_linkFunction()
	{
		alert("Hyper links are not supported in this page!");
	}

	// Custom function to call when user clicks on a element with an OnClick handler
	function fs_scrap_onClickFunction()
	{
		alert("OnClick events are not supported in this page!");
	}

	// Custom function to call when user clicks on a submit element
	function fs_scrap_SubmitFunction()
	{
		alert("Submit elements are not supported in this page!");
	}

	// Custom function to call when user clicks on a element with an OnClick handler
	function fs_scrap_onChangeFunction()
	{
		alert("OnChange events are not supported in this page!");
	}

var format="HTML"
var textEdit;
var ancestorArea;
var fedid;

function setEditor(ed) {
	fedid = ed.id;
	textEdit = window.frames[ed.id];
	format = textEdit.document.body.getAttribute("editmode");
	if (!format || format == "")
		format = "HTML";            
	textEdit.focus();
	textEdit.document.onclick = click;
	textEdit.document.onkeyup = keyUp;
	textEdit.document.onmousedown = mouseDown;
	//ancestorArea = document.getElementById(ed.id + '_AncestorArea');
	UpdateToolbars(ed.id);
}

function setHtmlEditor(ed) {
	htmlEditor = document.getElementById(ed);
}

function setParentEditor(ed) {
	textEdit = window.opener.frames[ed];
}

function swapMode(b) {
	swapModes()
	b.innerHTML = format + " Mode"
}

function workAroundCopyAndPaste(command)
{	//IE produce strange HTML when copy and paste across tables
	//this function works for HTML mode (not design mode; design mode can use built-in copy and paste
	var s = null;

	//find the most accessible ancestor
	var k;
	var ele;
	var win = window;
	
	//window.top may not be accessible, use a loop to find the topmost accessible window
	for (k = 0; k < 20; k++)	//limit the ancestor tree (sometimes, window.opener is tricked to itself which may cause infinite loop
	{
		if (win.parent != null)
		{
			try {
				ele = win.frameElement;
				if (ele != null)
				{	//current win is a frame, use parent
					win = win.parent;
					continue;
				}
			} catch (ex) {
				//just go on to try opener
			}
		}		
		try {
			if (win.opener.closed)
				break;
			if (document.all)
			{	//IE, we need to avoid permission denied when accessing opener
				s = window.opener.location.toString();
			}
			win = win.opener;
		} catch (ex) {
			break;
		}
	}

	if (command == 'Copy' || command == 'Cut')
	{
		var tp = textEdit.document.selection.type.toLowerCase();
		if (tp != 'none')
		{
			if (tp == 'text')
			{
				var rg = textEdit.document.selection.createRange();
				s = rg.htmlText;
			}
			else if (tp == 'control')
			{
				s = null;
			}
			if (textEdit.document.execCommand(command))
			{
				win.clipHTML = s;
				if (s == null)
					win.clipTEXT = null;
				else
					win.clipTEXT = clipboardData.getData('Text');
			}
			else
			{
				win.clipHTML = null;
				win.clipTEXT = null;
			}
		}
	}
	else if (command == 'Paste')
	{
		if (win.clipHTML == null || win.clipTEXT == null || win.clipTEXT != clipboardData.getData('Text'))
		{
			textEdit.document.execCommand(command);
			win.clipTEXT = null;
			win.clipHTML = null;
		}
		else
		{
			var rg = textEdit.document.selection.createRange();
			try
			{
				rg.pasteHTML(win.clipHTML);
			}
			catch (ex)
			{
				textEdit.document.execCommand(command);	//fallback to use standard paste
			}
		}
	}
}

function doFormat(command) {
	textEdit.focus();
	if (format=="HTML") {
		if (command=='InsertImage') {
			var imgSrc = prompt('Enter image location', ''); 
			if(imgSrc != null && imgSrc!='') 
				textEdit.document.execCommand(command, false, imgSrc); 
/*			textEdit.document.execCommand(command, true, arguments[1]); */
		} else if (command=='DeleteContents') {
			if (confirm('Do you want to delete all the HTML and text presently in the editor?')) {	
				textEdit.document.body.innerHTML = '';
			}
		} else if (command=='InsertDate') {
			var d = new Date();
			InsertHTML(d.toLocaleDateString());
		} else if (command=='InsertTime') {
			var d = new Date();
			InsertHTML(d.toLocaleTimeString());
		} else if (command=='SymbolsMenu') {
			//InsertHTML(this.list.options[this.list.options.selectedIndex].value);
		} else if (command=='namelink') {
			var isNewLink = false;
			var a;
			if (isIE) {
				var sel = GetSelection();
				var range = sel.createRange();
				switch (sel.type) {
					case "Text":
					case "None":
						a = range.parentElement();
						break;
					case "Control":
						a = range.item(0);
						if (a.tagName.toLowerCase() != 'a')
							a = a.parentElement;
						break;
					default:
						a = textEdit.document.body;
				}
			} else
				a = GetParentElement();
			if (a.tagName.toLowerCase() != 'a')
			{
				var guid = ("namelink" + ((new Date()).getTime())) + Math.random();
				if (textEdit.document.execCommand('createlink',false,guid))
				{
					textEdit.focus();
					isNewLink = true;
					var linkCount = textEdit.document.links.length;
					for (var k = 0; k < linkCount; k++)
					{
						if (textEdit.document.links[k].href.indexOf(guid) >= 0)
						{
							a = textEdit.document.links[k];
							break;
						}
					}				
				}
			}
			if (a.tagName.toLowerCase() == 'a')
			{
				var s = "";
				if (a.name)
					s = a.name;
				var name = prompt('Enter name to give to link (blank to clear name)', s);
				if(name != null)
				{
					a.name = name;
					if (name.length == 0)
					{
						if (a.href != "")
							a.removeAttribute("name");
						else
							textEdit.document.execCommand('unlink');						
					}
				}
				if (isNewLink)
				{
					if(name != null)
						a.removeAttribute("href");
					else
						textEdit.document.execCommand('unlink');
				}
			}
		} else {
			if (arguments[1] == null) 
			{	//special handling for Copy and Paste
				if (command=='Copy' || command=='Cut' || command=='Paste')
					workAroundCopyAndPaste(command);
				else
					textEdit.document.execCommand(command)
			}
			else 
				textEdit.document.execCommand(command,false, arguments[1])
		}
		textEdit.focus();
	}
}

function doImage() 
{ 
	var imgSrc = prompt('Enter image location', ''); 
	if(imgSrc != null && imgSrc!='') 
		textEdit.document.execCommand('insertimage', false, imgSrc); 
	textEdit.focus();
} 

function doPickImage() {
	popupForm('_en_imagepicker','_EDIT','P', 
	'toolbar=0,location=0, directories=0,status=1, menubar=0,scrollbars=1,resizable=1,copyhistory=0,width=600,height=300' ,'','')
}

function swapModes() {
	textEdit.focus();
	if (format=="HTML") {
		textEdit.document.body.innerText = textEdit.document.body.innerHTML
		format="Design"
	} else {
		//textEdit.document.body.innerHTML = textEdit.document.body.innerText;
		setTextEditInnerHTML(textEdit.document, textEdit.document.body, textEdit.document.body.innerText);
		format="HTML"
	}
	textEdit.document.body.setAttribute("editmode",format);
	textEdit.focus()
}

// The functions below are for Fourm Application.
function AddSmileyIcon(imagePath) {
	//textEdit.document.body.innerHTML += '<img src="' + imagePath + '"/>';
	setTextEditInnerHTML(textEdit.document, textEdit.document.body, textEdit.document.body.innerHTML + '<img src="' + imagePath + '"/>');
}

function drawArrow(enid, alias, docid, id, action, lastthreadid) {
/*
	document.write(' <a href="javascript:');
	document.write('topicSubmit(&quot;' + enid + '&quot;, &quot;' + alias + '&quot;, &quot;' + docid + '=\'' + id + '\'&quot;, &quot;' + action + '&quot;, &quot;' + lastthreadid+ '&quot;)">');
	document.write('<img align="middle" src="../images/standardforum/right_arrow.gif" border="0"/></a>');
*/	
	document.write(' <a href="javascript:');
	document.write('setValue(\'_threadid\',\'' + lastthreadid + '\');');
	document.write('docSubmit(&quot;' + enid + '&quot;, &quot;' + alias + '&quot;, &quot;' + docid + '=\'' + id + '\'&quot;, &quot;' + action + '&quot;, &quot;&quot;, &quot;&quot;)">');
	document.write('<img align="middle" src="../images/standardforum/right_arrow.gif" border="0"/></a>');
}

function topicSubmit(enid, alias, docID, action, threadid) {
	setValue('_threadid', threadid);
	docSubmit(enid, alias, docID, action, "","");
}
// The functions above are for Fourm Application.
function deletePortlet(pid) {
	setValue('portletid', pid);
	pageSubmit('_sf_portletDisplay','_DELETE')
	
}

// The functions below are RichTextEditor related
var button = new Array(0);
var dropdownlist = new Array(0);
var eventButton = new Array(0);

var undoArray = new Array();
var undoArrayMax = 16;
var undoArrayPos = -1;

var htmlEditor;

var doc=window.document;
var navVersion=navigator.appVersion.toLowerCase();
var ie4=(!doc.getElementById&&doc.all)?true:false;
var ie5=(navVersion.indexOf("msie 5.0")!=-1)?true:false;
var ie55=(navVersion.indexOf("msie 5.5")!=-1)?true:false;
var ie6=(navVersion.indexOf("msie 6.0")!=-1)?true:false;
var ie7=(navVersion.indexOf("msie 7.0")!=-1)?true:false;
var isIE=(ie5||ie55||ie6||ie7)?true:false;
var isGecko=!isIE;

function SetSelected(list, commandValue) {
	value = String(commandValue).toLowerCase();

	for (var i=0; i<list.options.length; i++) {
		if (list.options[i].value.toLowerCase() == value || list.options[i].text.toLowerCase() == value) {
			list.selectedIndex = i;
			return;
		}
	}
}

function click() {
	UpdateToolbars(fedid);
}

function keyUp() {
	var pKey = textEdit.event.keyCode;
	if (pKey>=33 && pKey<=40) {
		//update toolbar when
		//Home End PageUp PageDown (and four cursor keys)
		UpdateToolbars(fedid);
	}
}

function mouseDown() {
	UpdateToolbars(fedid);
}

function UpdateToolbars(edid) {
	for (var i=0; i<button.length; i++) {
		if (button[i][0]==edid) {
			id = document.getElementById(button[i][1]);
			if (QueryCommandState(button[i][2])) {
				id.className = 'HTMLEditTool2_BTN_Normal';
			} else {
				id.className = 'HTMLEditTool2_BTN_On';
			}
		}
	}
	for (var i=0; i<dropdownlist.length; i++) {
		if (dropdownlist[i][0]==edid) {
			id = document.getElementById(dropdownlist[i][1]);
			SetSelected(id, QueryCommandValue(dropdownlist[i][2]));
		}
	}
	SetToolbarItemsEnabledState(edid);
}

function UpdateAncestorTrail() {
	ancestors = GetAllAncestors();
	ancestorArea.innerHTML = "Path(" + ancestors.length + "): ";	
	for (var i = ancestors.length-1; i>-1; i--) {
		var el = ancestors[i];
		if (!el) {
			continue;
		}
		var a = document.createElement("a");
		a.href = "javascript:void();";
		a.el = el;
		a.ftb = this;
		a.onclick = function() {
			this.blur();
			this.SelectNodeContents(this.el);
			this.UpdateToolbars();
			return false;
		};
		a.oncontextmenu = function () {
			this.EditElementStyle(this.el);
			return false;
		}

		var txt = el.tagName.toLowerCase();
		if (txt == "input") txt = el.type;
		a.title = el.style.cssText;
		if (el.id) {
			txt += "#" + el.id;
		}
		if (el.className) {
			txt += "." + el.className;
		}
		a.appendChild(document.createTextNode("<" + txt + ">"));
		this.ancestorArea.appendChild(a);
		//if (i != 0)
		//	this.ancestorArea.appendChild(document.createTextNode(String.fromCharCode(0xbb)));

	}
				
}

function SetToolbarItemsEnabledState(edid) {	

	for (var i=0; i<eventButton.length; i++)
	{
		if (eventButton[i][0]==edid) {
			id = document.getElementById(eventButton[i][1]);
			if (!eval(eventButton[i][2])) {
				DisableButton(id);
			} else {
				EnableButton(id);
			}
		}
	}
}

function buttonDisabled(){
	return false;
}
function buttonEnabled() {
	return true;
}
function EnableButton(id) {
	if (isIE) {
		//id.childNodes[0].style.filter = "alpha(opacity = 100);";
		id.firstChild.firstChild.style.filter = "";
		id.firstChild.firstChild.onclick = buttonEnabled;
		id.className="HTMLEditTool2_BTN_Normal";
	} else {
		id.childNodes[1].style.MozOpacity = 1;
	}
}
function DisableButton(id) {
	if (isIE) {
		id.firstChild.firstChild.style.filter = "alpha(opacity = 25);";
		id.firstChild.firstChild.onclick = buttonDisabled;
		id.className="";
	} else {
		id.childNodes[1].style.MozOpacity = 0.25;
	}
}

// START: Table Functions ----------------------------------------------- */
function InsertTable(cols,rows,width,widthUnit,align,cellpadding,cellspacing,border) {
	textEdit.focus();
	var sel = GetSelection();
	var range = CreateRange(sel);	
	
	var doc = textEdit.document;
	// create the table element
	var table = doc.createElement("table");	

	// assign the given arguments
	table.style.width 	= width + widthUnit;
	table.align	 		= align;
	table.border	 	= border;
	table.cellSpacing 	= cellspacing;
	table.cellPadding 	= cellpadding;
	
	var tbody = doc.createElement("tbody");
	table.appendChild(tbody);
	
	for (var i = 0; i < rows; ++i) {
		var tr = doc.createElement("tr");
		tbody.appendChild(tr);
		for (var j = 0; j < cols; ++j) {
			var td = doc.createElement("td");
			td.innerText=" ";
			tr.appendChild(td);			
			if (!isIE) td.appendChild(doc.createElement("br"));
		}
	}
	
	if (isIE) {
		range.pasteHTML(table.outerHTML);
	} else {
		InsertNodeAtSelection(table);
	}
	
	return true;
}

function InsertTableWindow(id) {
	LaunchTableWindow(id, false);
}
function EditTable(id) {
	LaunchTableWindow(id, true);
}
function LaunchTableWindow(id, editing) {
		
	var tableWin = window.open("","tableWin","width=400,height=200");
	if (tableWin) {
		tableWin.focus();
	} else {
		fsAlert("PopUpBlocked");
		return;
	}
		
	tableWin.document.body.innerHTML = '';
	tableWin.document.open();
	tableWin.document.write(generateWin("TablePopUpHtml"));
	tableWin.document.close();
	
	launchParameters = new Object();
	launchParameters['id'] = id;
	launchParameters['table'] = (editing) ? GetNearest("table") : null;	
	tableWin.launchParameters = launchParameters;
	tableWin.load();
}

function InsertTableColumnBefore() {
	InsertTableColumn(false);
	textEdit.focus();
}
function InsertTableColumnAfter() {
	InsertTableColumn(true);
	textEdit.focus();
}
function InsertTableColumn(after) {
   var td = GetNearest("td");
   if (!td) {
      return;
   }
   var rows = td.parentNode.parentNode.rows;
   var index = td.cellIndex;
   for (var i = rows.length; --i >= 0;) {
      var tr = rows[i];
      var otd = textEdit.document.createElement("td");
      otd.innerHTML = (isIE) ? "" : "<br />";

      //if last column and insert column after is select append child
      if (index==tr.cells.length-1 && after) {
         tr.appendChild(otd);
      } else {
         var ref = tr.cells[index + ((after) ? 1 : 0)]; // 0 
         tr.insertBefore(otd, ref);
      } 
   }
}
function InsertTableRowBefore() {
	InsertTableRow(false);
	textEdit.focus();
}
function InsertTableRowAfter() {
	InsertTableRow(true);
	textEdit.focus();
}
function InsertTableRow(after) {
	var tr = GetNearest("tr");
	if (!tr) return;
	var otr = tr.cloneNode(true);
	ClearRow(otr);
	tr.parentNode.insertBefore(otr, ((after) ? tr.nextSibling : tr));
}


function DeleteTableColumn() {
	var td = GetNearest("td");
	if (!td) {
		return;
	}
	var index = td.cellIndex;
	if (td.parentNode.cells.length == 1) {
		return;
	}
	// set the caret first to a position that doesn't disappear
	SelectNextNode(td);
	var rows = td.parentNode.parentNode.rows;
	for (var i = rows.length; --i >= 0;) {
		var tr = rows[i];
		tr.removeChild(tr.cells[index]);
	}
	textEdit.focus();
}
function DeleteTableRow() {
	var tr = GetNearest("tr");
	if (!tr) {
		return;
	}
	var par = tr.parentNode;
	if (par.rows.length == 1) {
		return;
	}
	// set the caret first to a position that doesn't disappear.
	SelectNextNode(tr);
	par.removeChild(tr);
	textEdit.focus();
}

// helper table
function ClearRow(tr) {
	var tds = tr.getElementsByTagName("td");
	for (var i = tds.length; --i >= 0;) {
		var td = tds[i];
		td.rowSpan = 1;
		td.innerHTML = (isIE) ? "" : "<br />";
	}
	textEdit.focus();
}

function SplitRow(td) {
	var n = parseInt("" + td.rowSpan);
	var nc = parseInt("" + td.colSpan);
	td.rowSpan = 1;
	tr = td.parentNode;
	var itr = tr.rowIndex;
	var trs = tr.parentNode.rows;
	var index = td.cellIndex;
	while (--n > 0) {
		tr = trs[++itr];
		var otd = editor._doc.createElement("td");
		otd.colSpan = td.colSpan;
		otd.innerHTML = mozbr;
		tr.insertBefore(otd, tr.cells[index]);
	}
}

function SplitCol(td) {
	var nc = parseInt("" + td.colSpan);
	td.colSpan = 1;
	tr = td.parentNode;
	var ref = td.nextSibling;
	while (--nc > 0) {
		var otd = editor._doc.createElement("td");
		otd.rowSpan = td.rowSpan;
		otd.innerHTML = mozbr;
		tr.insertBefore(otd, ref);
	}
}

function SplitCell(td) {
	var nc = parseInt("" + td.colSpan);
	splitCol(td);
	var items = td.parentNode.cells;
	var index = td.cellIndex;
	while (nc-- > 0) {
		SplitRow(items[index++]);
	}
}
// -----------------------------------------------------------------------------------------------------------------------------
// Image/File/Flash upload functions
function insertFile(ed,filetype,path,name,width,height) {
	setParentEditor(ed);
	if (filetype=='image')
		InsertHTML('<img src="'+path+'" border="0">');
	else if (filetype=='doc')
		InsertHTML('<a href="' + path + '">' + name + '</a>');
	else if (filetype=='flash')
		insertFileFlash(path,width,height);
}
function insertFileFlash(path,width,height) {
	var flashStr = '<OBJECT codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" height="' + height + '" width="' + width + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" VIEWASTEXT>';
	flashStr = flashStr + '<PARAM NAME="movie" VALUE="' + path + '">';
	flashStr = flashStr + '<PARAM NAME="quality" VALUE="high">';
	flashStr = flashStr + '<embed src="' + path + '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="' + width + '" height="' + height+ '"></embed>';
	flashStr = flashStr + '</OBJECT>';
	InsertHTML(flashStr);
}

// -----------------------------------------------------------------------------------------------------------------------------
function FontForeColorPicker(id) {
	LaunchColorPickerWindow(id,'forecolor');
}
function FontBackColorPicker(id) {
	LaunchColorPickerWindow(id,'backcolor');
}

function LaunchColorPickerWindow(id, commandName, startValue) 
{
	var pickerWin = window.open("","colorPickerWin","width=290,height=180");
	if (pickerWin) {
		pickerWin.focus();
	} else {
		fsAlert("PopUpBlocked");
		return;
	}
	
	pickerWin.document.body.innerHTML = '';
	pickerWin.document.open();
	pickerWin.document.write(generateWin("ColorPickerHtml"));
	pickerWin.document.close();

	launchParameters = new Object();
	launchParameters['id'] = id;
	launchParameters['commandName'] = commandName;
	pickerWin.launchParameters = launchParameters;
	pickerWin.load();
}

function ImageUploadPicker(id) {
	LaunchUploadPicker(id, 'image');
}

function DocUploadPicker(id) {
	LaunchUploadPicker(id, 'doc');
}

function FlashUploadPicker(id) {
	LaunchUploadPicker(id, 'flash');
}

function LaunchUploadPicker(id, fileType) {
	var pickerWin = window.open("","uploadPickerWin","width=350,height=100");
	if (pickerWin) {
		pickerWin.focus();
	} else {
		fsAlert("PopUpBlocked");
		return;
	}
	
	pickerWin.document.body.innerHTML = '';
	pickerWin.document.open();
	pickerWin.document.write(generateWin("UploadPickerHtml"));
	pickerWin.document.close();

	launchParameters = new Object();
	launchParameters['id'] = id;
	launchParameters['fileType'] = fileType;
	pickerWin.launchParameters = launchParameters;
	pickerWin.load();
}

// Misc functions
function SetListValue(list, value, checkText) {
	checkText = checkText || false;
	value = String(value).toLowerCase();

	for (var i=0; i<list.options.length; i++) {
		if (list.options[i].value.toLowerCase() == value || (checkText && list.options[i].text.toLowerCase() == value)) {
			list.selectedIndex = i;
			return;
		}
	}
}
function ParseUnit(styleString) {
	var unit = new Object();
	unit.value = 0;
	unit.unitType = '';
	for(var i=0; i<styleString.length; i++) {
		if (isNaN(styleString.charAt(i)))
			unit.unitType += styleString.charAt(i);
		else 
			unit.value = parseInt(unit.value.toString() + styleString.charAt(i));
	}
	return unit;
}
function DecToHex(dec) {
	return parseInt(dec).toString(16); 
}
function IntToHexColor( intColor ) {
	if (!intColor) return null;
	intColor = intColor.toString(16).toUpperCase();
	while (intColor.length < 6) intColor = "0" + intColor;
	return "#" + intColor.substring(4,6) + intColor.substring(2,4) + intColor.substring(0,2);
}

function RgbToHex(r,g,b) {
	return "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);
}

function IntToHex(dec){ 
	var result = (parseInt(dec).toString(16)); 
	if(result.length ==1) 
	result= ("0" +result); 
	return result.toUpperCase(); 
}

function RgbStringToHex(rgbString){ 
	var r, g, b;
	rgbString = rgbString.toString().toLowerCase();	
	if(rgbString.indexOf("rgb(") == -1 || rgbString.indexOf(")") == -1) return rgbString;
	
	rgbString = rgbString.substring(rgbString.indexOf("(")+1, rgbString.indexOf(")")-1);
	rgb = rgbString.split(',');
	r = rgb[0];
	g = rgb[1];
	if (rgb.length == 2) b = rbg[2]; else b = 0;	
	return RgbToHex(r,g,b);
}

function InsertHTML(html) {
	textEdit.focus();
	if (isIE) {
		sel = textEdit.document.selection.createRange();
		if (textEdit.document.selection.type.toUpperCase() == "CONTROL") {
			if (sel.length > 0) {
				sel.item(0).outerHTML = html;
				for (var i=1;i<sel.length;i++) sel.item(i).outerHTML = '';
			}
		} else {
			sel.pasteHTML(html);
		}
	} else {

        selection = textEdit.window.getSelection();
		if (selection) {
			range = selection.getRangeAt(0);
		} else {
			range = editor.document.createRange();
		}

        var fragment = textEdit.document.createDocumentFragment();
        var div = textEdit.document.createElement("div");
        div.innerHTML = html;

        while (div.firstChild) {
            fragment.appendChild(div.firstChild);
        }

        selection.removeAllRanges();
        range.deleteContents();

        var node = range.startContainer;
        var pos = range.startOffset;

        switch (node.nodeType) {
            case 3:
                if (fragment.nodeType == 3) {
                    node.insertData(pos, fragment.data);
                    range.setEnd(node, pos + fragment.length);
                    range.setStart(node, pos + fragment.length);
                } else {
                    node = node.splitText(pos);
                    node.parentNode.insertBefore(fragment, node);
                    range.setEnd(node, pos + fragment.length);
                    range.setStart(node, pos + fragment.length);
                }
                break;

            case 1:
                node = node.childNodes[pos];
                node.parentNode.insertBefore(fragment, node);
                range.setEnd(node, pos + fragment.length);
                range.setStart(node, pos + fragment.length);
                break;
        }
        selection.addRange(range);
	}
}

FTB_BUTTON_ON = 0;
FTB_BUTTON_OFF = 1;

function QueryCommandState(commandName) {
	try {
		if (textEdit.document.queryCommandState(commandName)) {
			return FTB_BUTTON_ON;
		} else {
			// special case for paragraph on IE
			if (commandName == 'justifyleft') {
				if (textEdit.document.queryCommandState('justifyright') == false &&
					textEdit.document.queryCommandState('justifycenter') == false &&
					textEdit.document.queryCommandState('justifyfull') == false ) {
					return FTB_BUTTON_ON;
				} else {
					return FTB_BUTTON_OFF;
				}
			} else { 
				return FTB_BUTTON_OFF;
			}
		}
	} catch(exp) {
		return FTB_BUTTON_OFF;
	}
}

function QueryCommandValue(commandName) {
	value = textEdit.document.queryCommandValue(commandName);
	switch (commandName) {
		case "backcolor":
			if (isIE) {
				value = IntToHexColor(value);
			} else {
				if (value == "") value = "#FFFFFF";
			}
			break;
		case "forecolor":
			if (isIE) {
				value = IntToHexColor(value);
			} else {
				if (value == "") value = "#000000";
			}
			break;
		case "formatBlock":
			if (!isIE) {
				if (value == "" || value == "<x>")
					value = "<p>";
				else
					value = "<" + value + ">";
			}
			break;
	}
	if (value == '' || value == null) {
		if (commandName == 'fontsize') return '3';
		if (commandName == 'fontname') return 'Times New Roman';	
		if (commandName == 'forecolor') return '#000000';	
		if (commandName == 'backcolor') return '#ffffff';
	}
	return value;
}

function SelectAll() {
	SelectNodeContents(textEdit.document.body);
}

function CopyDesignToHtml () {
	htmlEditor.value = textEdit.document.body.innerHTML;
}

function Preview() {
	var contents;
	if (format=="HTML")
		contents = textEdit.document.body.innerHTML;
	else
		contents = textEdit.document.body.innerText;
	printWindow = window.open('','','toolbars=no,scrollbars=1,resizable=1');
	printWindow.document.open();
	printWindow.document.write("<html><head><link rel='stylesheet' href='" + "" + "' type='text/css' />" + (('' != '') ? "<base href='" + "" + "' />" : "") + "</head><body>" + contents + "</body></html>");
	printWindow.document.close();	
}

function GetParentElement() {

	var sel = GetSelection();
	var range = sel.createRange();
	if (isIE) {
		switch (sel.type) {
		    case "Text":
		    case "None":
				return range.parentElement();
		    case "Control":
				return range.item(0);
		    default:
				return textEdit.document.body;
		}
	} else try {
		var p = range.commonAncestorContainer;
		if (!range.collapsed && range.startContainer == range.endContainer &&
		    range.startOffset - range.endOffset <= 1 && range.startContainer.hasChildNodes())
			p = range.startContainer.childNodes[range.startOffset];
		/*
		alert(range.startContainer + ":" + range.startOffset + "\n" +
		      range.endContainer + ":" + range.endOffset);
		*/
		while (p.nodeType == 3) {
			p = p.parentNode;
		}
		return p;
	} catch (e) {
		return null;
	}
}

function InsertNodeAtSelection(toBeInserted) {
	if (!isIE) {
		var sel = GetSelection();
		var range = sel.createRange();
		// remove the current selection
		sel.removeAllRanges();
		range.deleteContents();
		var node = range.startContainer;
		var pos = range.startOffset;
		switch (node.nodeType) {
		    case 3: // Node.TEXT_NODE
			// we have to split it at the caret position.
			if (toBeInserted.nodeType == 3) {
				// do optimized insertion
				node.insertData(pos, toBeInserted.data);
				range = this._createRange();
				range.setEnd(node, pos + toBeInserted.length);
				range.setStart(node, pos + toBeInserted.length);
				sel.addRange(range);
			} else {
				node = node.splitText(pos);
				var selnode = toBeInserted;
				if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
					selnode = selnode.firstChild;
				}
				node.parentNode.insertBefore(toBeInserted, node);
				SelectNodeContents(selnode);
			}
			break;
		    case 1: // Node.ELEMENT_NODE
			var selnode = toBeInserted;
			if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
				selnode = selnode.firstChild;
			}
			node.insertBefore(toBeInserted, node.childNodes[pos]);
			SelectNodeContents(selnode);
			break;
		}
	}
}

function SelectNodeContents(node, pos) {
	var range;
	var collapsed = (typeof pos != "undefined");
	if (isIE) {
		range = textEdit.document.body.createTextRange();
		range.moveToElementText(node);
		(collapsed) && range.collapse(pos);
		range.select();
	} else {
		var sel = GetSelection();
		range = textEdit.document.createRange();
		range.selectNodeContents(node);
		(collapsed) && range.collapse(pos);
		sel.removeAllRanges();
		sel.addRange(range);
	}
}

function SelectNextNode(el) {
	var node = el.nextSibling;
	while (node && node.nodeType != 1) {
		node = node.nextSibling;
	}
	if (!node) {
		node = el.previousSibling;
		while (node && node.nodeType != 1) {
			node = node.previousSibling;
		}
	}
	if (!node) {
		node = el.parentNode;
	}
	SelectNodeContents(node);
}

function GetSelection() {
	if (isIE) {
		return textEdit.document.selection;
	} else {
		return textEdit.getSelection();
	}
}

function CreateRange(sel) {
	if (isIE) {
		return sel.createRange();
	} else {
		if (typeof sel != "undefined") {
			try {
				return sel.getRangeAt(0);
			} catch(e) {
				return textEdit.document.createRange();
			}
		} else {
			return textEdit.document.createRange();
		}
	}
}

function GetNearest(tagName) {
	var ancestors = GetAllAncestors();
	var ret = null;
	tagName = ("" + tagName).toLowerCase();
	for (var i=0;i<ancestors.length;i++) {
		var el = ancestors[i];
		if (el) {
			if (el.tagName.toLowerCase() == tagName) {
				ret = el;
				break;
			}
		}
	}
	return ret;
}

function GetAllAncestors() {
	var p = GetParentElement();
	var a = [];
	while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
		a.push(p);
		p = p.parentNode;
	}
	a.push(textEdit.document.body);
	return a;
}

function WordClean() {

	var text = textEdit.document.body.innerHTML;
	
	text=text.replace(/<FONT[^>]*>/gi,"");
	text=text.replace(/<\/FONT>/gi,"");
	text=text.replace(/<U>/gi,"");
	text=text.replace(/<\/U>/gi,"");
	text=text.replace(/<H[^>]*>/gi,"");
	text=text.replace(/<\/H[^>]*>/gi,"");
	
	// Change these tags.
	text=text.replace(/<B[^>]*>/gi,"&bold");
	text=text.replace(/<\/B[^>]*>/gi,"&cbold");
	text=text.replace(/<STRONG[^>]*>/gi,"&bold");
	text=text.replace(/<\/STRONG[^>]*>/gi,"&cbold");

	text=text.replace(/<I[^>]*>/gi,"&ital");
	text=text.replace(/<\/I[^>]*>/gi,"&cital");
	text=text.replace(/<EM[^>]*>/gi,"&ital");
	text=text.replace(/<\/EM[^>]*>/gi,"&cital");
	
	text=text.replace(/<UL[^>]*>/gi,"&ultag");
	text=text.replace(/<LI[^>]*>/gi,"&litag");
	text=text.replace(/<OL[^>]*>/gi,"&oltag");
	text=text.replace(/<\/OL>/gi,"&olctag");
	text=text.replace(/<\/LI>/gi,"&lictag");
	text=text.replace(/<\/UL>/gi,"&ulctag");

	text=text.replace(/<P[^>]*>/gi,"&parag");
	text=text.replace(/<\/P>/gi,"");
	
	/*
	text=text.replace(/?gi,'\"');
	text=text.replace(/?gi,'\"');
	text=text.replace(/?gi,'\"');
	text=text.replace(/mailto:/gi,'\"');
	text=text.replace(/?g,"&Auml;");
	text=text.replace(/?g,"&Ouml;");
	text=text.replace(/?g,"&Uuml;");
	text=text.replace(/?g,"&auml;");
	text=text.replace(/?g,"&ouml;");
	text=text.replace(/?g,"&uuml;");
	text=text.replace(/?gi,"&szlig;");	
	*/
	
	text=text.replace(/&lt;[^>]&gt*;/gi,"");
	text=text.replace(/&lt;\/[^>]&gt*;/gi," ");
	text=text.replace(/<o:[^>]*>/gi,"");
	text=text.replace(/<\/o:[^>]*>/gi,"");
	text=text.replace(/<\?xml:[^>]*>/gi,"");
	text=text.replace(/<\/?st[^>]*>/gi,"");
	text=text.replace(/<[^>]*</gi,"<");
	text=text.replace(/<SPAN[^>]*>/gi,"");
	text=text.replace(/<SPAN[^class]*>/gi,"");
	text=text.replace(/<\/SPAN>/gi,"");
	//text=text.replace(/<\/A>/gi,"");
	
	// Clear the inner parts of other tags.
	text=text.replace(/style=[^>]*"/g,' ');
	text=text.replace(/style=[^>]*'/g," ");
	text=text.replace(/style=[^>]*>/g,">");
	text=text.replace(/lang=[^>]*>/g,">");
	text=text.replace(/name=[^>]* /g,"");
	text=text.replace(/name=[^>]*>/g,">");
	text=text.replace(/<A[^>]*>/g,"");
	
	//text=text.replace(/<p[^>]*>/gi,"<p>");

	
	
	// Put the tags back
	text=text.replace(/&bold/g,"<B>");
	text=text.replace(/&cbold/g,"</B>");

	text=text.replace(/&ital/g,"<EM>");
	text=text.replace(/&cital/g,"</EM>");

	text=text.replace(/&ultag/g,"<UL>");
	text=text.replace(/&litag/g,"<LI>");
	text=text.replace(/&oltag/g,"<OL>");
	text=text.replace(/&olctag/g,"<\/OL>");	
	text=text.replace(/&lictag/g,"<\/LI>");
	text=text.replace(/&ulctag/g,"<\/UL>");

	text=text.replace(/&parag/g,"<BR>");
	
	textEdit.document.body.innerHTML = text;
}

function FindCurrentHtmlClass()
{	//user may click outside the IFRAME editor portion but still able to access this function
	//use inRange to detect this case
	var rg = textEdit.document.selection.createRange();
	var docrg = textEdit.document.body.createTextRange();
	if (docrg.inRange(rg))
	{
		var ele = rg.parentElement();
		while (ele != null)
		{
			if (ele.className != null && ele.className != '')
				break;
			ele = ele.parentElement;
		}
		if (ele != null)
		{
			rg.moveToElementText(ele);
			rg.select();
			alert("Class='"+ele.className+"'");
		}
	}
}

function setTextEditInnerHTML(htmlDoc, bodyNode, innerHTML)
{
	var outerHTML = bodyNode.outerHTML;
	var p = outerHTML.indexOf('>');	
	var bodyOpen = outerHTML.substring(0, p + 1);
	htmlDoc.open();
	htmlDoc.write(bodyOpen + innerHTML + '</BODY>');
	htmlDoc.close()
}

function generateWin(MsgID)
{
	var msgs, msg;
	var aMsg = MsgID.split('|');
	if (typeof(localizedWins) == "undefined")
		msgs = defaultedWins;	//localizedMsgs is not defined
	else
		msgs = localizedWins;
	msg = msgs[aMsg[0]];
	if (!!msg)
	{
		for (var i=1; i<=aMsg.length; i++)
			msg = msg.replace("%" + i + "%", aMsg[i]);
		return(msg);
	}
	else
		return(MsgID);
}
function getID(s) {
	return document.getElementById(s);
}

function getFirstChildElem(nd)
{
	var ele = null;
	if (nd != null)
	{
		ele = nd.firstChild;
		while (ele != null && ele.nodeType != 1)
			ele = ele.nextSibling;
	}
	return(ele);
}

function getNextSiblingElem(nd)
{
	var ele = null;
	if (nd != null)
	{
		ele = nd.nextSibling;
		while (ele != null && ele.nodeType != 1)
			ele = ele.nextSibling;
	}
	return(ele);
}

function menuHighlight(_HTML, _Current, _sw)
{
	//for FireFox & Safari use, to highlight menu (2009-06-02 Alex)
	var nCur;

	nCur = getCurrentMenu(_HTML, _Current, "noapp");

	if (nCur == null)
	{
		_Current = _sw[_Current] || _Current;
		nCur = getCurrentMenu(_HTML, _Current, "noapp");
	}

	if (nCur != null)
	{
		nCur.setAttribute("class", nCur.getAttributeNode("class").nodeValue.replace(/ly_mnp/g,"ly_mnp_s"));
		var link = nCur.parentNode.getAttribute('id');
		nCur = getCurrentMenu(_HTML, link, "link");

		if (nCur != null)
			nCur.setAttribute("class", nCur.getAttributeNode("class").nodeValue.replace(/ly_mn0/g,"ly_mn0_s"));
	}
	else
	{
		nCur = getCurrentMenu(_HTML, _Current, "app");
		if (nCur == null)
		{
			_Current = _sw[_Current] || _Current;
			nCur = getCurrentMenu(_HTML, _Current, "app");
		}
		if (nCur != null)
		{
			nCur.setAttribute("class", nCur.getAttributeNode("class").nodeValue.replace(/ly_mn0/g,"ly_mn0_s"));
		}
		
	}
}

function getCurrentMenu(__HTML, __Current, app)
{
	var _Cur;
	var _ul = __HTML.getElementsByTagName("UL");

	for (var _x = 0; _x < _ul.length; _x++)
	{
	
		if (app == "noapp")
		{
			if ("appmenu" != _ul[_x].getAttributeNode("id").nodeValue)
			{
				var _li = _ul[_x].getElementsByTagName("LI");

				for (var _y = 0; _y < _li.length; _y++)
				{
					if (_li[_y].getElementsByTagName("A").length > 0)
					{ 
						if (__Current.toLowerCase() == ((_li[_y].getElementsByTagName("A"))[0].getAttributeNode("href").nodeValue).toLowerCase())
						{
							_Cur = _li[_y];
						}
					}
				}
			}
		}
		else if (app == "app")
		{
			if ("appmenu" == _ul[_x].getAttributeNode("id").nodeValue)
			{
				var _li = _ul[_x].getElementsByTagName("LI");

				for (var _y = 0; _y < _li.length; _y++)
				{
					if (_li[_y].getElementsByTagName("A").length > 0)
					{ 
						if (__Current.toLowerCase() == ((_li[_y].getElementsByTagName("A"))[0].getAttributeNode("href").nodeValue).toLowerCase())
						{
							_Cur = _li[_y];
						}
					}
				}
			}
		}
		else if (app == "link")
		{
			if ("appmenu" == _ul[_x].getAttributeNode("id").nodeValue)
			{
				var _li = _ul[_x].getElementsByTagName("LI");

				for (var _y = 0; _y < _li.length; _y++)
				{
					if (_li[_y].getAttributeNode("link") != null)
					{ 
						if (__Current.toLowerCase() == (_li[_y].getAttributeNode("link").nodeValue).toLowerCase())
						{
							_Cur = _li[_y];
						}
					}
				}
			}
		}

	}

	if (!!_Cur)
		return _Cur;
	else
		return null;
}

