////////////////////////////////////////////////////////////////////////////////
// rteft by Thimios Katsoulis  ( thk at kaotonik.net ) based on code of
// Richtext Editor: Fork (RTEF) VERSION: 0.004
// that was Released on  9/07/2006
//
////////////////////////////////////////////////////////////////////////////////

// Constants
var minWidth = 200;					// minumum width
var wrapWidth = 1268;				// width at which all icons will appear on one bar
var maxchar = 64000;				// maximum number of characters per save
var lang = "en";					// xhtml language
var lang_direction = "ltr";			// language direction:ltr=left-to-right,rtl=right-to-left
var encoding = "utf-8";				// xhtml encoding
var zeroBorder = "#c0c0c0";			// guideline color - see showGuidelines()
var btnText = "submit";				// Button value for non-designMode() & fullsceen rte
var resize_fullsrcreen = true;
// (resize_fullsrcreen) limited in that: 1)won't auto wrap icons. 2)won't
// shrink to less than (wrapWidth)px if screen was initized over (wrapWidth)px;
//
var keep_absolute = true;			// !!!Disabled - see line 565 for details!!!!!
// By default IE will try to convery all hyperlinks to absolute paths. By
// setting this value to "false" it will retain the relative path.

// Pointers
var InsertChar;
var InsertTable;
var InsertLink;
var InsertImg;
var dlgReplace;
var dlgPasteText;
var dlgPasteWord;

//Init Variables & Attributes
var ua = navigator.userAgent.toLowerCase();
var isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1))? true:false;

var isIE7 = (isIE && (ua.indexOf("msie 7") !=-1));
var isIE5 = (isIE && (ua.indexOf("msie 5.0") !=-1));
var	isOpera = (ua.indexOf("opera") != -1)? true:false;
var OperaVersion = parseFloat(ua.substring(ua.lastIndexOf("Opera/") + 7));
var	isGecko = (ua.indexOf("gecko") != -1)? true:false;
var	isSafari = (ua.indexOf("safari") != -1)? true:false;
var SafariVersion = parseFloat(ua.substring(ua.lastIndexOf("safari/") + 7));
var	isKonqueror = (ua.indexOf("konqueror") != -1)? true:false;
var rng;
var currentRTE;
var allRTEs = "";
var obj_width;
var obj_height;
var imagesPath;
var includesPath;
var cssFile;
var generateXHTML = true;
var isRichText = false;
var myStyle
var  smileysRootWebPath="/media/rtefT/images/";
//check to see if designMode mode is available
if(document.getElementById && document.designMode) {
    isRichText = true;
}
//for testing standard textarea, uncomment the following line
//isRichText = false;

var replacements = new Array (
new RegExp(String.fromCharCode(145),'g'), "'",
new RegExp(String.fromCharCode(146),'g'), "'",
new RegExp("'"), "&#39;",
//convert all types of double quotes
new RegExp(String.fromCharCode(147),'g'), "\"",
new RegExp(String.fromCharCode(148),'g'), "\""
//new RegExp("\""), "&#34;",
//replace carriage returns & line feeds
//new RegExp("[\r\n]",'g'), " \n"
);

var DEFAULT_BUTTONS = "undo,redo,bold,italic,underline,ol,ul,special-char,link,unlink,image,table,smiley";



function rteSafe(html) {
    html = trim(html);
    for (i=0; i<replacements.length; i = i+2) {
        html = html.replace(replacements[i], replacements[i+1]);
    }
    return html;
}

function initRTE(imgPath, incPath, css, genXHTML) {
    // CM 05/04/05 check args for compatibility with old RTE implementations
    if (arguments.length == 3) {
        genXHTML = generateXHTML;
    }
    //set paths vars
    imagesPath = imgPath;
    includesPath = incPath;
    cssFile = css;
    generateXHTML = genXHTML;
    if(isRichText) {
        document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');

    }

    if(!isIE) {
        minWidth = minWidth-50;
        wrapWidth = wrapWidth-106;
    } else if(isIE7) {
        minWidth = minWidth+2;
        wrapWidth = wrapWidth+4;
    }

}

function writeRichText(rte, htmlContentId, css ,  buttonArrStr  , w , h ) {

    buttonArrayStr  = buttonArrStr || DEFAULT_BUTTONS;
    width = w || 0;
    height = h || 0 ;
    buttons=true;
    if (buttonArrayStr.length == 0 )
        {buttons = false;}
    htmlContentElement = document.getElementById(htmlContentId)
    if (htmlContentElement != null)
        {html = htmlContentElement.innerHTML;
         //remove cdata  start and end
         //alert(html);
         //html=html.substring(12,html.length);
         //html=html.substring(0,html.length-6);

         }
    else
        {html = "not found htmlContentId : " + htmlContentId;}

    currentRTE = rte;
    if(allRTEs.length > 0)
        {allRTEs += ";";}

    allRTEs += rte;

    if(isRichText)

           {
            var rte_css = "";
            if (css.length > 0)
               {rte_css = css;}
            else
               {rte_css = cssFile;}

            //============  LETS GO  ==================//

            //document.writeln('<img src="'+imagesPath+'design.gif" style="display:none">');
            rteDivStartHtml = '<span class="rteDiv" id="' + "rtediv_"  + rte + '" ';
            if (width > 0 )
                rteDivStartHtml += ' style="width:' + width + 'px;"';
             rteDivStartHtml += ">";
             document.writeln(rteDivStartHtml);
             //=============  DRAW THE BUTTON TOOLBAR  ====================//
             if(buttons)
                 {createToolbar(rte , buttonArrayStr);}

             // ================ DRAW THE IFRAME =========================//
             iframeHtmla = '<iframe id="'+rte+'" src="' + includesPath + 'blank.htm" onfocus="dlgCleanUp();" ';
             if (height > 0)
                iframeHtmla += 'style="height:' + height + 'px;"';
             iframeHtmla += '></iframe>';
             //alert(iframeHtml);
             document.writeln(iframeHtmla);
             //=====================  SWITCH TO HTML =====================//

             document.writeln('<div class="editor-toolbar-bottom">');
             document.writeln('<a id="_xtSrc'+rte+'" class="switch code-switch" href="javascript:toggleHTMLSrc(\''+rte+'\', ' + buttons + ');" >' + lblModeHTML +  '</a>');
             document.writeln('</div>');

             document.writeln('<iframe width="142" height="98" id="cp'+rte+'" src="' + includesPath + 'palette.htm" scrolling="no" frameborder=0 style="margin:0;border:0;visibility:hidden;position:absolute;border:1px solid #cdcdcd;top:-1000px;left:-1000px"></iframe>');
             document.writeln('<input type="hidden" id="hdn'+rte+'" name="'+rte+'" value="" style="position: absolute;left:-1000px;top:-1000px;">');

             document.writeln('</span>');
             document.getElementById('hdn'+rte).value = html;

             enableDesignMode(rte, html, rte_css);

             }

       else   // IsRichtext = false
             {
                html = parseBreaks(html);
                document.writeln('<textarea cols=80 rows=20 name="'+rte+'" id="'+rte+'" class="rte_textarea" >' + html + '</textarea>');

              }

}  //WRITErICHtEXT  ENDS



function insertBar() {
    document.writeln('<td><img class="rteBar" src="'+imagesPath+'bar.gif" alt=""></td>');
}

function insertSep() {
    document.writeln('<td><img class="rteSep" src="'+imagesPath+'blackdot.gif" alt=""></td>');
}
function searchableArray(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}


function createToolbar(rte , buttonArrStr)
{           buttonArr= buttonArrStr.split(',');
            btnList = searchableArray(buttonArr);
            document.writeln('<div class="editor-toolbar-container-top" id="editor-toolbar-container-top-' + rte + '">');
            document.writeln('<div class="editor-toolbar-top" id="editor-toolbar-' + rte + '">');
            if (('undo' in btnList) || ('redo' in btnList))
            {
              openSpanButtonGroup();
              if ('undo' in btnList)
                {insertButton(rte,lblUndo,"editor-undo-"+rte,"tool editor-undo","rteCommand('"+rte+"','undo')");}
              if ('redo' in btnList)
                insertButton(rte,lblRedo,"editor-redo-"+rte,"tool editor-redo","rteCommand('"+rte+"','redo')");
              closeSpan();
            }

            if (('bold' in btnList) || ('italic' in btnList) || ('underline' in btnList))
                {
                openSpanButtonGroup();
                if ('bold' in btnList)
                    insertButton(rte,lblBold,"editor-bold-"+rte,"tool editor-bold", "rteCommand('"+rte+"','bold')");
                if ('italic' in btnList)
                    insertButton(rte,lblItalic,"editor-italic-"+rte,"tool editor-italic","rteCommand('"+rte+"','italic')");
                if ('underline' in btnList)
                    insertButton(rte,lblUnderline,"editor-underline-"+rte,"tool editor-underline","rteCommand('"+rte+"','underline')");
                closeSpan();
                }


             if (('ol' in btnList) || ('ul' in btnList))
                    {
                    openSpanButtonGroup();
                    if ('ol' in btnList)
                        insertButton(rte,lblOL,"editor-numbered-list-"+rte,"tool editor-numbered-list","rteCommand('"+rte+"','insertorderedlist')");
                    if ('ul' in btnList)
                        insertButton(rte,lblUL,"editor-list-"+rte,"tool editor-list","rteCommand('"+rte+"','insertunorderedlist')");
                    closeSpan();
                    }

            if (('special-char' in btnList) || ('link' in btnList) || ('unlink' in btnList)
                || ('image' in btnList) || ('table' in btnList) || ('smiley' in btnList))
                {
                openSpanButtonGroup();
                //if(!isOpera)
                if ('special-char' in btnList)
                   insertButton(rte,lblInsertChar,"editor-special-char-" + rte,"tool editor-special-char","dlgLaunch('"+rte+"','char')");

                if ('link' in btnList)
                    {insertButton(rte,lblInsertLink,"editor-hyperlink-" + rte,"tool editor-hyperlink","linkPopup('"+rte+"')");
                     createLinkPopup(rte);}
                if('unlink' in btnList)
                   insertButton(rte,lblUnLink,"editor-unlink-" + rte,"tool editor-unlink","rteCommand('"+rte+"','Unlink')");
                if ('image' in btnList)
                    {insertButton(rte,lblAddImage,"editor-image-" + rte,"tool editor-image","imagePopup('"+rte+"')");
                     createImagePopup(rte);}
                if('table' in btnList)
                    insertButton(rte,lblInsertTable,"editor-insert-table-" + rte,"tool editor-insert-table","dlgLaunch('"+rte+"','table')");
                if ('smiley' in btnList)
                    {insertButton(rte,lblSmiley,"editor-smiley-" + rte,"tool editor-smiley","smileysPopup('" + rte + "')") ;
                    createSmileysPopup(rte);}
                closeSpan();
                }

            document.writeln('</div><!--editor-toolbar top end-->');
            document.writeln('</div><!--editor-toolbar container top end-->');


}

// ==== Link control ===== //

function createLinkPopup(rte)
{
LinkPopupID="link-popup-" + rte ;

if (! document.getElementById(LinkPopupID))
     {
         LinkPopupClass = "popup link-popup";
         document.writeln('<div  id="' + LinkPopupID + '" class = "' + LinkPopupClass  + '" style="display:none;" >' ) ;
         document.writeln( 'link <input type="text" id="link-url-' + rte + '" class ="text"></input>');
         document.writeln( 'text <input type="text" id="link-text-' + rte + '" class ="text" style="display: block;" ></input>');
         buttonId ="editor-hyperlink-" + rte;
         insertButtonWithText(rte,"Cancel","plain","showHideElement('" + LinkPopupID +  "','hide',false);resetButton('" + buttonId + "','tool editor-hyperlink');","Cancel" );
         insertButtonWithText(rte,"Insert Link","plain","insertLink('" + rte + "')","Ok" );
         document.writeln('</div>' ) ;
     }
}

////////////////
// thanks to google answers and elegie
// for the following
function getElementsFromSelection(rte){
   var nodes=null, candidates=[], children, el, parent, rng;

   // Main
   var oRTE = returnRTE(rte);
   rng=getSelectionRange(oRTE);
   if(rng) {
     parent=getCommonAncestor(rng);
     if(parent) {
       // adjust from text node to element, if needed
       while(parent.nodeType!=1) parent=parent.parentNode;

       // obtain all candidates from parent (excluded)
       // up to BODY (included)
       if(parent.nodeName.toLowerCase()!="body") {
         el=parent;
         do {
           el=el.parentNode;
           candidates[candidates.length]=el;
         } while(el.nodeName.toLowerCase()!="body");
       }

       // obtain all candidates down to all children
       children=parent.all||parent.getElementsByTagName("*");
       for(var j=0; j<children.length; j++)
         candidates[candidates.length]=children[j];

       // proceed - keep element when range touches it
       nodes=[parent];
       for(var ii=0, r2; ii<candidates.length; ii++) {
         r2=createRangeFromElement(oRTE , candidates[ii]);
         if(r2 && rangeContact(rng, r2))
           nodes[nodes.length]=candidates[ii];
       }
     }
   }
   return nodes;

   // Helpers
   function getSelectionRange(oRTE) {
     var rng=null;
     if(oRTE.window.getSelection) {
       rng= oRTE.window.getSelection();
       if(rng && rng.rangeCount && rng.getRangeAt) {
         rng=rng.getRangeAt(0);
       }
     } else if(oRTE.document.selection && oRTE.document.selection.type=="Text") {
       rng= oRTE.document.selection.createRange();
     }
     return rng;
   }

   function getCommonAncestor(rng) {
     return rng.parentElement ?
              rng.parentElement() : rng.commonAncestorContainer;
   }

   function rangeContact(r1, r2) {
     var p=null;
     if(r1.compareEndPoints) {
       p={
         method:"compareEndPoints",
         StartToStart:"StartToStart",
         StartToEnd:"StartToEnd",
         EndToEnd:"EndToEnd",
         EndToStart:"EndToStart"
       }
     } else if(r1.compareBoundaryPoints) {
       p={
         method:"compareBoundaryPoints",
         StartToStart:0,
         StartToEnd:1,
         EndToEnd:2,
         EndToStart:3
       }
     }
     return p && !(
           r2[p.method](p.StartToStart, r1)==1 &&
           r2[p.method](p.EndToEnd, r1)==1 &&
           r2[p.method](p.StartToEnd, r1)==1 &&
           r2[p.method](p.EndToStart, r1)==1
           ||
           r2[p.method](p.StartToStart, r1)==-1 &&
           r2[p.method](p.EndToEnd, r1)==-1 &&
           r2[p.method](p.StartToEnd, r1)==-1 &&
           r2[p.method](p.EndToStart, r1)==-1
         );
   }

   function createRangeFromElement(oRTE,el) {
     var rng=null;
     if(oRTE.document.body.createTextRange) {
       rng= oRTE.document.body.createTextRange();
       rng.moveToElementText(el);
     } else if(oRTE.document.createRange) {
       rng=oRTE.document.createRange();
       rng.selectNodeContents(el);
     }
     return rng;
   }

}



/////////////////



function insertLink(rte)
{

linkInputID= "link-url-" + rte ;
textInputID= "link-text-" + rte ;
LinkPopupID="link-popup-" + rte ;
buttonId = "editor-hyperlink-" + rte ;
buttonCssClass = "tool editor-hyperlink";
buttonElem = document.getElementById(buttonId);

mandatoryInputs = [ [linkInputID,lblLinkUrl]  ];
valid = validateNotNull(mandatoryInputs);
inputText = document.getElementById(textInputID).value;
url= document.getElementById(linkInputID).value;

if (valid)
    {   aNode = getFirstNodeInRange(rte , 'A');
        if (aNode)
        {
            aNode.href=url;
            if (inputText)
            {aNode.innerHTML=inputText;

            }


        }
        else
        {
            html='<a href="' + url +'">' + inputText + '</a>' ;
            insertHTML(html);
        }
        showHideElement( LinkPopupID ,'hide',false)
        buttonElem.className = buttonCssClass;
    }
}



function getFirstNodeInRange(rte ,tagName)
{

nodes=getElementsFromSelection(rte);
if (nodes)
{for (i=0;i<nodes.length;i++)
    {
        nod=nodes[i];
        if (nod.nodeName == tagName)
           {return nod;}
    }
}
return null;
}


function linkPopup(rte)
{
text=getText(rte);
linkTextInput = document.getElementById("link-text-" + rte );
linkTextInput.value = text;
var oRTE = returnRTE(rte);

aElem = getFirstNodeInRange(rte , 'A');
if (aElem)
{urlId = 'link-url-' + rte;
document.getElementById(urlId).value= aElem.href;}

LinkPopupID="link-popup-" + rte ;
LinkPopupElem=document.getElementById(LinkPopupID);
LinkButtonClass = "tool editor-hyperlink";

LinkButton=document.getElementById("editor-hyperlink-" + rte);
relativeLeft=LinkButton.offsetLeft;


if (LinkPopupElem)
    {   oRTE.focus();
        if (LinkPopupElem.style.display == "none")
           {
              LinkButton.onmouseup = function() { return false; };
              LinkButton.onmouseout = function() { return false; };
              LinkPopupElem.style.display="block" ;

              if (isIE)
                {relativeLeft += 21;
                 LinkPopupElem.style.marginTop = '25px';}

              LinkPopupElem.style.left = relativeLeft+'px';

              // LinkPopupElem.style.top ='25px';
              LinkButton.className=LinkButtonClass + " pressed";
            }
        else
            {
              LinkPopupElem.style.display="none" ;
              LinkButton.onmouseup = function() { this.className=LinkButtonClass + " hover";};
              LinkButton.onmouseout = function() { this.className= LinkButtonClass ; };
              LinkButton.className=LinkButtonClass ;
              }
        oRTE.focus();
    }

} // end func linkPopup



//===smileys=======
function createSmileysPopup(rte)
{
SmileysPopupID="smileys-popup-" + rte ;

if (! document.getElementById(SmileysPopupID))
     {
         SmileysPopupClass = "popup smileys-popup";
         document.writeln('<div id="' + SmileysPopupID + '" class = "' + SmileysPopupClass  + '" style="display:none;" >' ) ;

        smileys=[ 'angry','beer','eyeroll','gnu','island','sad','sleepy','smile','sun','tongue','umbrella','weird','hot','laugh','nerd','neutral'];
          for (i in smileys)
                { name=smileys[i];
                  //param = "'/rtefT/images/" + name + ".gif'";
                  param = smileysRootWebPath + name + ".gif";
                  id = name + '-' + rte;
                  classname = 'tool white editor-' + name;
                //insertButton(rte,name,id,classname,"rteCommand('" + rte + "','insertimage'," + param + ")" );
                insertButton(rte,name,id,classname,"insertSmiley('" + rte + "','" + param + "')" );
                }
          document.writeln('</div>' ) ;
         }
}


function closePopups(rte)
{
SmileysPopupID="smileys-popup-" + rte ;
LinkPopupID="link-popup-" + rte;


         if (document.getElementById(SmileysPopupID).style.display != "none" )
            {smileysPopup(rte);}
         if (document.getElementById(LinkPopupID).style.display != "none" )
            {linkPopup(rte);}

}

function smileysPopup(rte)
{

SmileysPopupID="smileys-popup-" + rte ;
SmileysPopupElem=document.getElementById(SmileysPopupID);
SmileysButtonClass = "tool editor-smiley";

SmileysButton=document.getElementById("editor-smiley-" + rte);
relativeLeft=SmileysButton.offsetLeft;
relativeTop=SmileysButton.offsetTop;
var oRTE = returnRTE(rte);
//alert( smileysButton.offsetLeft );
if (SmileysPopupElem)
    {   oRTE.focus();
        if (SmileysPopupElem.style.display == "none")
           {
                   SmileysButton.onmouseup = function() { return false; };
                   SmileysButton.onmouseout = function() { return false; };
                   SmileysPopupElem.style.display="block" ;


                   if (isIE)
                        {relativeLeft += 21;
                        SmileysPopupElem.style.marginTop = '25px';}
                   SmileysPopupElem.style.left = relativeLeft  +'px';
                   SmileysButton.className=SmileysButtonClass + " pressed";
                   //alert (relativeLeft);

             }
        else
            {
              SmileysPopupElem.style.display="none" ;
              SmileysButton.onmouseup = function() { this.className=SmileysButtonClass + " hover";};
              SmileysButton.onmouseout = function() { this.className= SmileysButtonClass ; };
              SmileysButton.className=SmileysButtonClass ;
            }
            oRTE.focus();
    }
}

function insertSmiley(rte,imageUrl)
{

    html='<img src="' + imageUrl +'" class="smiley" />' ;
    insertHTML(html);
}


//=========== Image control ============//

function resetButton(btnId , className)
{
btn = document.getElementById(btnId);
if (btn)
	{
		btn.className = className;
		btn.onmouseover = function(){this.className += ' hover';};
		btn.onmouseout = function(){this.className = className;};
	}

}


function createImagePopup(rte)
{
PopupID="image-popup-" + rte ;

if (! document.getElementById(PopupID))
     {
        cssClass = "popup image-popup";
        document.writeln('<div  id="' + PopupID + '" class = "' + cssClass  + '" style="display:none;" >' ) ;


        document.writeln('<div class="tablabels">');
        document.writeln('<a id = "insert_image_link_Title" class="tablabel tablabel_active" href="#" onclick="switchMenuTab(\'insert_image_link_Title\' , \'insert_image_link_tab\' , \'' + PopupID + '\');return false ">' + lblInsertLinkedImage + '</a>');
        document.writeln('<a id = "insert_image_from_site_Title" class="tablabel tablabel_inactive" href="#" onclick="switchMenuTab(\'insert_image_from_site_Title\' , \'insert_image_from_site_tab\' , \'' + PopupID + '\');return false ">' + lblInsertImageFromSite + '</a>');
        document.writeln('<a  class="tablabel tablabel_inactive" target="_new" href="../add_image" >' + lblUploadNewImage + '</a>');

        document.writeln('</div>' ) ;

        document.writeln('<div id ="insert_image_link_tab" class="tab tab_active">');
        document.writeln( lblImageUrl +': <input type="text" id="image-url-' + rte + '" class ="text"></input>');
        document.writeln( lblAltText +': <input type="text" id="image-alt-' + rte + '" class ="text"></input>');
        imageCssClasses = ",left,right";
        document.writeln('css class');
        insertSelect ("image-class-" + rte , 'text' , imageCssClasses);
        buttonId ="editor-image-" + rte;
        insertButtonWithText(rte,"Cancel","plain","showHideElement('" + PopupID +  "','hide',false);resetButton('" + buttonId + "','tool editor-image');","Cancel" );
        insertButtonWithText(rte,"Insert Image","plain","insertImageAction('" + rte + "')","Ok" );
        document.writeln('</div>' ) ;

        document.writeln('<div id ="insert_image_from_site_tab" class="tab tab_inactive">');
        document.writeln('<a id = "fetch_image_from_site-' +  rte + '"  href="#" class="ablock" onclick="fetchImages(\'' + rte  +'\');return false ">' + lblFetchImagesFromSite + '</a>');
        document.writeln('<div id = "images_from_site-' +  rte + '" class ="available-images"></div>');


        imageCssClasses = ",left,right";

        document.writeln('css class');
        insertSelect ("image-from-site-class-" + rte , 'text' , imageCssClasses);
        buttonId ="editor-image-" + rte;
        insertButtonWithText(rte,"Cancel","plain","showHideElement('" + PopupID +  "','hide',false);resetButton('" + buttonId + "','tool editor-image');","Cancel" );
        insertButtonWithText(rte,"Insert Image","plain","insertImageFromSiteAction('" + rte + "')","Ok" );
        document.writeln('</div>' ) ;

        document.writeln('</div>' ) ;
         }
}
var ie_compatible = false;
var firefox_compatible = false;
var not_supported = false;
var xmlDoc;

function fetchImages(rte)
{
pObj = Object();
pObj.rte = rte;
http( 'post'  , '/en/search/xml' , fetchImagesResponse , 'lang=none&category=2' , pObj );
}


function docLoad()
{

     if (window.ActiveXObject)
     {   ie_compatible = true;
         xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
     }
     else if  (document.implementation && document.implementation.createDocument)
     {  firefox_compatible = true; }

     else

     { not_supported=true;}

}

function fetchImagesResponse(obj ,params)
{
    docLoad();
    if (obj["type"]=="xml")
    {
        if (ie_compatible)
        {
            xmlDoc.loadXML(obj["data"].xml);
            imagesXml(xmlDoc , params);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else if (firefox_compatible)
        {
            xmlDoc=obj["data"];
            imagesXml(xmlDoc , params);
        }
    }
}


function imagesXml(xmlDoc , params)
{
rte = params.rte;
PopupID="image-popup-" + rte ;
popupDiv = document.getElementById(PopupID);
imgsDiv = document.getElementById("images_from_site-" + rte);
waitAnimElem = document.getElementById("wait_images_from_site-" + rte);
totalHtml = "";
resultNodes = xmlDoc.getElementsByTagName("result");
if (resultNodes.length > 3)
  {popupDiv.className = "popup image-popup-choose-from-site";
   imgsDiv.style.height = "200px";}
else
  popupDiv.className = "popup image-popup";
imgResizeRatio = 0.5;
for (i=0; i<resultNodes.length; i++)
    {resultNode = resultNodes[i];
     path = getNodeText(resultNode , 'path');
     lang = getNodeText(resultNode , 'lang');
     title = getNodeText(resultNode , 'title');

     imgSrc =  path + "/thumbnail";

     imgHtml = '<a href="#" class="image-from-site-link"  onclick="return false"><img src="' + imgSrc + '" title="' + title +  '" alt="' + title + '" class="borderedImg" onload="resizeImg(this , ' + imgResizeRatio + ');" onmouseover="addToImgSize(this , 20);this.className=\'borderedImg image-from-site-hover\';" onmouseout="subFromImgSize(this , 20);this.className=\'borderedImg\';" onclick="selectImg(this , \'' + rte + '\');"/></a>';
     totalHtml += imgHtml;

    }
imgsDiv.innerHTML = totalHtml;
}

function getSelectedImg(rte)
{

imgsDiv = document.getElementById("images_from_site-" + rte);
imgs = imgsDiv.getElementsByTagName('img');
for (i=0 ; i<imgs.length ; i++)
    {im = imgs[i];
     if (im.className == "borderedImg image-from-site-selected")
        return im;
    }
return null;
}


function selectImg( img , rte)
{
imgsDiv = document.getElementById("images_from_site-" + rte);
imgs = imgsDiv.getElementsByTagName('img');
for (i=0 ; i<imgs.length ; i++)
{im = imgs[i];
 if (im.className == "borderedImg image-from-site-selected")
    {im.className = "borderedImg";
     subFromImgSize(im , 20)
     im.onmouseover = new Function("addToImgSize(this , 20);this.className=\'borderedImg image-from-site-hover\';") ;
     im.onmouseout = new Function("subFromImgSize(this , 20);this.className=\'borderedImg\';");
     break;
    }

}
img.className = "borderedImg image-from-site-selected";
img.onmouseover = function() { return false; };
img.onmouseout = function() { return false; };


}

function resizeImg(img , imgResizeRatio)
{img.width = img.width * imgResizeRatio;}

function addToImgSize(img , step)
{

img.width = img.width + step;
}

function subFromImgSize(img , step)
{

img.width = img.width - step;}


function getNodeText(node , name)
{
data=null;
elems = node.getElementsByTagName(name);
    if (elems.length > 0)
    {//alert(elems.length);
    	fc=elems[0].firstChild;
    	if (fc){
    		data = fc.data;

    	}

    }
return data;
}

function validateNotNull(inputs)
{mandatoryLabels=new Array( );
for (i=0 ; i<inputs.length ; i++)
	{inputId = inputs[i][0];
	el = document.getElementById(inputId);
	if (el)
		{ if (el.value.length <= 0)
		  {el.className += " mandatory";
		  mandatoryLabels.push(inputs[i][1]);}
		  else
		  {el.className = "text";}

		}
	}
valid = true;
if (mandatoryLabels.length > 0 )
	{
	valid = false;
	alert (lblFillMandatory + " : " + mandatoryLabels.join(','));
	}
return valid;
}

function setSelectedValue(id , value,text)
{
selectElem = document.getElementById(id);
option=null;
for (i=0;i<selectElem.options.length;i++)
{
option=selectElem.options[i];
if (option.value==value)
{option.selected=true;return;}
}
newoption=new Option(text,value,false, true);
selectElem.add(newoption,null);
}


function insertImageAction(rte)
{
imageUrlInputID= "image-url-" + rte ;
imageAltInputID= "image-alt-" + rte ;
mandatoryInputs = [ [imageUrlInputID,lblImageUrl] , [imageAltInputID ,lblAltText] ];
valid = validateNotNull(mandatoryInputs);

if ( valid )

    {
       url = document.getElementById(imageUrlInputID).value;
       alt = document.getElementById(imageAltInputID).value;
       imgClassSelectElem = document.getElementById( "image-class-" + rte );
       imgCssClass = imgClassSelectElem[ imgClassSelectElem.selectedIndex ].value;
       imgElem = getFirstNodeInRange(rte,'IMG');

       if (imgElem)
       {
         imgElem.src = url;
         imgElem.alt = alt;
         if (imgCssClass.length > 0)
            {imgElem.className = imgCssClass;}
       }
       else
       {
           if (imgCssClass.length > 0)
             {html='<img src="' + url +'" class="' + imgCssClass +'" alt="' + alt + '"/>';}
           else
             {html='<img src="' + url +'" alt="' + alt +'"/>';}
         insertHTML(html);
        }

       showHideElement( PopupID ,'hide',false)
       buttonId ="editor-image-" + rte;
       document.getElementById(buttonId).className = 'tool editor-image';
    }

}



function insertImageFromSiteAction(rte)
{
oRTE = returnRTE(rte);
img = getSelectedImg(rte);
if (img == null)
{alert ('please select an image');return false;}

url = img.src;
imgAlt = img.alt;
hrefArr = img.src.split('/');
hrefArr = hrefArr.slice(0,hrefArr.length-1);
href = hrefArr.join('/')

title = img.title;
PopupID="image-popup-" + rte ;
       imgClassSelectElem = document.getElementById( "image-from-site-class-" + rte );
       imgCssClass = imgClassSelectElem[ imgClassSelectElem.selectedIndex ].value;
       imgCssClass = "borderedImg " + imgCssClass;

       html='<a href="' + href + '"><img src="' + url +'" class="' + imgCssClass +'" alt="' + imgAlt +'" title="' + imgAlt + '" /></a>';

       html = fixGeckoBaseHREFBug(1 ,rte ,  html);
       insertHTML(html);
       html = fixGeckoBaseHREFBug(2 ,rte ,  html);

       showHideElement( PopupID ,'hide',false)
       buttonId ="editor-image-" + rte;
       document.getElementById(buttonId).className = 'tool editor-image';

       oRTE.focus();

}


function imagePopup(rte)
{
text=getText(rte);
PopupID="image-popup-" + rte ;
PopupElem=document.getElementById(PopupID);
NormalButtonClass = "tool editor-image";
PopupButton=document.getElementById("editor-image-" + rte);
relativeLeft = PopupButton.offsetLeft;
var oRTE = returnRTE(rte);

if (PopupElem)
    {   oRTE.focus();
        if (PopupElem.style.display == "none")
           {
              PopupButton.onmouseup = function() { return false; };
              PopupButton.onmouseout = function() { return false; };
              PopupElem.style.display="block" ;

              if (isIE)
                {relativeLeft += 21;
                 PopupElem.style.marginTop = '25px';
                 }
              PopupElem.style.left = relativeLeft + 'px';

              // LinkPopupElem.style.top ='25px';
              PopupButton.className = NormalButtonClass + " pressed";
              imgElem = getFirstNodeInRange(rte,'IMG');

              if (imgElem)
              {
               document.getElementById('image-url-' + rte).value = imgElem.src;
               document.getElementById('image-alt-' + rte).value = imgElem.alt;
               className= imgElem.className || "";
               setSelectedValue("image-class-" + rte , className,className);
              }
            }
        else
            {
              PopupElem.style.display="none" ;
              PopupButton.onmouseup = function() { this.className=NormalButtonClass + " hover";};
              PopupButton.onmouseout = function() { this.className= NormalButtonClass ; };
              PopupButton.className=LinkButtonClass ;
              }
        oRTE.focus();
    }

} // end func linkPopup



function insertImage(rte,imageUrl)
{

    html='<img src="' + imageUrl +'" />' ;
    insertHTML(html);
}

function openSpanButtonGroup()
{
     document.writeln ('<span class="button-group">');
}

function closeSpan()
{
     document.writeln ('</span>');
}

function insertImg(name, image, command, id) {
//	var span = "<span>";
//	if(id!=null) {
//		span = "<span id='"+id+"'>";
//	}
//	document.writeln(span + '<button onmousemove="return false"  title="'+name+'" onMouseDown="'+command+';return false" onmouseover="this.className=\'rteImgUp\'" onmouseout="this.className=\'rteImg\'" onmousedown="this.className=\'rteImgDn\'" onmouseup="this.className=\'rteImgUp\'"></button></span>');

    //document.writeln(span + '<img class="rteImg" onmousemove="return false" src="'+imagesPath+image+'" alt="'+name+'" title="'+name+'" onMouseDown="'+command+';return false" onmouseover="this.className=\'rteImgUp\'" onmouseout="this.className=\'rteImg\'" onmousedown="this.className=\'rteImgDn\'" onmouseup="this.className=\'rteImgUp\'"></td>');
}


function insertButton( rte,title,id,className,command)
{
btnHtml = '<button type="button" id="' + id + '" class="'+ className + '" title="' + title + '" onmousemove="return false"  onmouseup="this.className=\'' + className + ' hover\'" onmousedown="this.className += \' pressed\';' + command + ';return false"  onmouseover="this.className += \' hover\';"  onmouseout="this.className=\'' + className + '\'"></button>';
//alert(btnHtml);
document.writeln(btnHtml);
}


function insertSelect(id, className , options)
{
document.writeln('<select id="' + id + '" class="' + className + '" >');
optionsArr = options.split(',');
for (i=0; i < optionsArr.length ; i++)
    {
    option = optionsArr[i];
    document.writeln('<option value="' + option + '" >' + option + '</option>');
    }
document.writeln('</select>');
}



function insertButtonWithText( rte,title,className,command,text)
{
document.writeln('<button type="button" id="' + className + '-' + rte + '" class="'+ className + '" title="' + title + '" onmousemove="return false"   onMouseDown="' + command + ';return false"   >' + text + '</button>');
}


function enableDesignMode(rte, html, css) {
    var frameHtml = "<html dir='" + lang_direction + "' lang='" + lang + "' id='" + rte + "'>\n<head>\n";
    frameHtml += "<meta http-equiv='Content-Type' content='text/html; charset=" + encoding + "'>\n";
    frameHtml += "<meta http-equiv='Content-Language' content='" + lang + "'>\n";
    //to reference your stylesheet, set href property below to your stylesheet path and uncomment
    if(css.length > 0) {
        cssArr = css.split(',');
        for (i=0 ; i < cssArr.length ; i++)
        {
            ss = cssArr[i];
            frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + ss + "\" rel=\"stylesheet\">\n";
        }

    } else {
        frameHtml += "<style>@charset \"utf-8\"; body {background:white;margin:8px;padding:0px;}</style>\n";
    }
    frameHtml += "</head><body>\n"+html+"\n</body></html>";

    if(!isSafari && !isKonqueror) var oRTE = returnRTE(rte).document;
    if (document.all) {

        if(isSafari || isKonqueror) var oRTE = frames[rte].document;
        oRTE.open("text/html","replace");



        oRTE.write(frameHtml);
        oRTE.close();

        oRTE.designMode = "On";

    } else {
        try {
            if( !isKonqueror && !isSafari) {

                addLoadEvent(function() { document.getElementById(rte).contentDocument.designMode = "on"; });
            } else  {
                //Safari doen't like the abouve command so we use this instad - Anders Jenbo.
                document.getElementById(rte).contentDocument.designMode = "on";
            }
            try {
                if(isSafari || isKonqueror) var oRTE = document.getElementById(rte).contentWindow.document;
                oRTE.open("text/html","replace");
                oRTE.write(frameHtml);
                oRTE.close();
                if(isGecko) {
                    //attach a keyboard handler for gecko browsers to make keyboard shortcuts work
                    oRTE.addEventListener("keypress", geckoKeyPress, true);
                    oRTE.addEventListener("focus", function () {dlgCleanUp(); }, false);
                }
            }
            catch(e) {
                alert("501 :" + lblErrorPreload);
            }
        }
        catch(e) {
            //gecko may take some time to enable design mode.
            //Keep looping until able to set.
            if(isGecko) {
                setTimeout("enableDesignMode('"+rte+"', '"+html+"', '"+css+"');", 200);
            } else {
                return false;
            }
        }
    }
    setTimeout('showGuidelines("'+rte+'")',300);
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        };
    }
}

function returnRTE(rte) {
    var rtn;
    if(document.all) {
        rtn = frames[rte];
    } else {
        rtn = document.getElementById(rte).contentWindow;
    }
    return rtn;
}

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

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

function parseRTE(rte) {
    if (!isRichText) {
        autoBRoff(rte); // sorts out autoBR
        return false;
    }
    //check for readOnly mode
    var readOnly = false;
    var oRTE = returnRTE(rte);
    if(document.all) {
        if(oRTE.document.designMode != "On") {
            readOnly = true;
        }
    } else {
        if(oRTE.document.designMode != "on") {
            readOnly = true;
        }
    }
    if(isRichText && !readOnly) {
        //if viewing source, switch back to design view
        if(document.getElementById("_xtSrc"+rte).innerHTML == lblModeRichText) {
            if(document.getElementById("Buttons1_"+rte)) {
                toggleHTMLSrc(rte, true);
            } else {
                toggleHTMLSrc(rte, false);
            }
            stripGuidelines(rte);
        }
        setHiddenVal(rte);
    }
}

function setHiddenVal(rte) {
    //set hidden form field value for current rte
    var oHdnField = document.getElementById('hdn'+rte);
    //convert html output to xhtml (thanks Timothy Bell and Vyacheslav Smolin!)
    if(oHdnField.value==null) {
        oHdnField.value = "";
    }
    var sRTE = returnRTE(rte).document.body;
    if(generateXHTML) {
        try {
            oHdnField.value = getXHTML(sRTE.innerHTML);
        }
        catch(e) {
            oHdnField.value = sRTE.innerHTML;
        }
    } else {
        oHdnField.value = sRTE.innerHTML;
    }
    // fix to replace special characters added here:
    oHdnField.value = replaceSpecialChars(oHdnField.value);
    //if there is no content (other than formatting) set value to nothing
    if(stripHTML(oHdnField.value.replace("&nbsp;", " ")) == "" &&
    oHdnField.value.toLowerCase().search("<hr") == -1 &&
    oHdnField.value.toLowerCase().search("<img") == -1) {
        oHdnField.value = "";
    }
}

function rteCommand(rte, command, option) {
    dlgCleanUp();
  //function to perform command
    var oRTE = returnRTE(rte);
    try {
        oRTE.focus();
        oRTE.document.execCommand(command, false, option);
        oRTE.focus();
    } catch(e) {
//		alert(e);
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
    }
}


function formathtml(html) {
	//convert html encode html tags so that they show up, then color and format them

	//strip white space
	html = html.replace(/\s/g, ' ');
	//convert html to text
	html = html.replace(/&/g, '&amp;');
	html = html.replace(/</g, '&lt;');
	html = html.replace(/>/g, '&gt;');
	//change all attributes " to &quot; so they can be distinguished from the html we are adding
	html = html.replace(/="/g, '=&quot;');
	html = html.replace(/=&quot;(.*?)"/g, '=&quot;$1&quot;');
	//search for opening tags
	html = html.replace(/&lt;([a-z](?:[^&|^<]+|&(?!gt;))*?)&gt;/gi, "<span class=\"tag\">&lt;$1&gt;</span><div>");
	//Search for closing tags
	html = html.replace(/&lt;\/([a-z].*?)&gt;/gi, "</div><span class=\"tag\">&lt;/$1&gt;</span>");
	//search for self closing tags
	//html = html.replace(/\/&gt;<\/span><blockquote>/gi, "/&gt;</span>");
	//Search for values
	html = html.replace(/&quot;(.*?)&quot;/gi, "<span class=\"literal\">\"$1\"</span>");
	//search for comments
	html = html.replace(/&lt;!--(.*?)--&gt;/gi, "<span class=\"comment\">&lt;!--$1--&gt;</span>");
	//search for html entities
	html = html.replace(/&amp;(.*?);/g, '<b>&amp;$1;</b>');
	return html;
}

function toggleHTMLSrc(rte, buttons) {
    dlgCleanUp();
    // contributed by Bob Hutzel (thanks Bob!)
    var cRTE = document.getElementById(rte);
    var hRTE = document.getElementById('hdn'+rte);
    var sRTE = document.getElementById("size"+rte);
    var tRTE = document.getElementById("_xtSrc"+rte);
    var iRTE = document.getElementById("imgSrc"+rte);
    var buttonsToolbar = document.getElementById("editor-toolbar-"+rte);

    var oRTE = returnRTE(rte).document;
    var htmlSrc;
    if(sRTE) {
        obj_height = parseInt(sRTE.value);
    } else {
        findSize(rte);
    }
	tRTEInnerHTML=tRTE.innerHTML;
    //tRTEInnerHTML=tRTE.innerHTML.replace('\n','');
    //tRTEInnerHTML=tRTEInnerHTML.replace('\r','');

    if(tRTEInnerHTML == lblModeHTML)
    {
        // we are checking the box
        // switching to code view
        tRTE.innerHTML = lblModeRichText;

        stripGuidelines(rte);

        if(buttons)
                {
                    showHideElement("editor-toolbar-" + rte, "hide", false);
                    closePopups(rte);
                    //cRTE.style.height = obj_height + 40;

                }

        setHiddenVal(rte);
        oRTE.body.innerHTML = formathtml(hRTE.value);
        if(isIE) {
			// This resets the undo/redo buffer.
			document.getElementById(rte).value = returnRTE(rte).document.body.innerHTML;
		}
        /*
        if(document.all) {
            oRTE.body.innerText = hRTE.value;

            } else {
            htmlSrc = oRTE.createTextNode(hRTE.value);
            oRTE.body.innerHTML = "";
            oRTE.body.appendChild(htmlSrc);




            }
		*/
                //document.getElementById(rte).style.height="375px";
                //document.getElementById(rte).style.borderTop="1px solid #B19490"

    //	iRTE.innerHTML = '<img src="'+imagesPath+'design.gif" alt="Switch Mode" style="margin:1px;" align=absmiddle>';
		tRTE.className ="switch richtext-switch";

    }

    else

    {
        // we are unchecking the box
        //switching to Richtext editor
        obj_height = parseInt(cRTE.style.height);
        tRTE.innerHTML = lblModeHTML;
        if(buttons) {
            showHideElement("editor-toolbar-" + rte, "show", false);
            //cRTE.style.height = obj_height-50;

            }
        if(document.all) {
            // fix for IE
            var output = escape(oRTE.body.innerText);
            output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
            output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
            oRTE.body.innerHTML = unescape(output);
            // Disabled due to flaw in the regular expressions, this fix
            // does not work with the revamped's enhanced insert link dialog window.

            // Prevent links from changing to absolute paths
            if(!keep_absolute) {
                var tagfix = unescape(output).match(/<a[^>]*href=(['"])([^\1>]*)\1[^>]*>/ig);
                var coll = oRTE.body.all.tags('A');
                for(i=0; i<coll.length; i++) {
                    // the 2 alerts below show when we hinder the links from becoming absolute
                    // alert(tagfix[i]);
                    coll[i].href = tagfix[i].replace(/.*href=(['"])([^\1]*)\1.*/i,"$2");
                    // alert(RegExp.$1 + " " + RegExp.$2 + " " + RegExp.$3);
                }
                var imgfix = unescape(output).match(/<img[^>]*src=['"][^'"]*['"][^>]*>/ig);
                var coll2 = oRTE.body.all.tags('IMG');
                for(i=0; i<coll2.length; i++) {
                    coll2[i].src = imgfix[i].replace(/.*src=['"]([^'"]*)['"].*/i,"$1");
                }
            }
          // end path fix
        } else {
            htmlSrc = oRTE.body.ownerDocument.createRange();

            htmlSrc.selectNodeContents(oRTE.body);
            oRTE.body.innerHTML = htmlSrc.toString();
        }
        oRTE.body.innerHTML = replaceSpecialChars(oRTE.body.innerHTML);
        showGuidelines(rte);
        // (IE Only)This prevents an undo operation from displaying a pervious HTML mode
        // This resets the undo/redo buffer.
        if(document.all) {
            parseRTE(rte);
        }
            //document.getElementById(rte).style.height="350px";
            //document.getElementById(rte).style.borderTop="none"
        tRTE.className ="switch code-switch";
        //iRTE.innerHTML = '<img src="'+imagesPath+'code.gif" alt="Switch Mode" style="margin:1px;" align=absmiddle>';
    }
}

function toggleSelection(rte) {
    var rng = setRange(rte);
    var oRTE = returnRTE(rte).document;
    var length1;
    var length2;
    if(document.all) {
        length1 = rng.text.length;
        var output = escape(oRTE.body.innerText);
        output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
        output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
        length2 = unescape(output).length;
    } else {
        length1 = rng.toString().length;
        var htmlSrc = oRTE.body.ownerDocument.createRange();
        htmlSrc.selectNodeContents(oRTE.body);
        length2 = htmlSrc.toString().length;
    }
    if(length1 < length2) {
        rteCommand(rte,'selectall','');
    } else {
        if(!document.all) {
            oRTE.designMode = "off";
            oRTE.designMode = "on";
        } else {
            rteCommand(rte,'unselect','');
        }
    }
}

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

function dlgLaunch(rte, command) {
    var selectedText = '';
    // save current values
    parent.command = command;
    currentRTE = rte;
    switch(command) {
        case "char":
            InsertChar = popUpWin(includesPath+'insert_char.htm', 'InsertChar', 50, 50, 'status=yes,');
        break;
        case "table":
            InsertTable = popUpWin(includesPath + 'insert_table.htm', 'InsertTable', 50, 50, 'status=yes,');
        break;
        case "image":
            if(!isSafari && !isKonqueror)setRange(rte);
            parseRTE(rte);
            // sending rte and isOpera starte for Opera
            InsertImg = popUpWin(includesPath + 'insert_img.htm?rte='+ rte + '&isOpera=' + isOpera,'AddImage', 50, 50, 'status=yes,');
        break;
        case "link":
            if(!isOpera)selectedText = getText(rte);
            // sending rte and isOpera starte for Opera
            alert (includesPath + 'insert_link.htm?rte='+ rte + '&isOpera=' + isOpera);
            InsertLink = popUpWin(includesPath + 'insert_link.htm?rte='+ rte + '&isOpera=' + isOpera, 'InsertLink', 50, 50, 'status=yes,');
            if(!isOpera)setFormText("0", selectedText);
        break;
        case "replace":
            if(!isOpera)selectedText = getText(rte);
            dlgReplace = popUpWin(includesPath + 'replace.htm', 'dlgReplace', 50, 50, 'status=yes,');
            if(!isOpera)setFormText("1", selectedText);
        break;
        case "text":
            dlgPasteText = popUpWin(includesPath + 'paste_text.htm', 'dlgPasteText', 50, 50, 'status=yes,');
        break;
        case "word":
            dlgPasteWord = popUpWin(includesPath + 'paste_word.htm', 'dlgPasteWord', 50, 50, 'status=yes,');
        break;
    }
}




function getText(rte) {
    // get currently highlighted text and set link text value
    if(isSafari) {
        var oRTE = returnRTE(rte);
        var rtn = oRTE.getSelection();
        //This makes it a text string, i dont know any other ways and it seams quick
        rtn = "" + rtn;
        return rtn;
    } else {
        setRange(rte);
        var rtn = '';
        if (isIE) {
            rtn = stripHTML(rng.htmlText);
        } else {
            rtn = stripHTML(rng.toString());
        }
        parseRTE(rte);
        if(document.all) {
            rtn = rtn.replace("'","\\\\\\'");
        } else {
            rtn = rtn.replace("'","\'");
        }
        return rtn;
    }
}

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

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

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

function setColor(color) {
    // function to set color
    var rte = currentRTE;
    var parentCommand = parent.command;

    if(document.all || isSafari || isKonqueror) {
        if(parentCommand == "hilitecolor") {
            parentCommand = "backcolor";
        }
        // retrieve selected range
        if(!isSafari && !isKonqueror)rng.select();
    }

    rteCommand(rte, parentCommand, color);
    showHideElement('cp'+rte, "hide", false);
}

function addImage(rte) {
    dlgCleanUp();
    // function to add image
    imagePath = prompt('Enter Image URL:', 'http://');
    if((imagePath != null)&&(imagePath != "")) {
        rteCommand(rte, 'InsertImage', imagePath);
    }
}

function rtePrint(rte) {
    dlgCleanUp();
    if(isIE) {
        document.getElementById(rte).contentWindow.document.execCommand('Print');
    } else {
        document.getElementById(rte).contentWindow.print();
    }
}

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

function setStyle(rte, selectname)
{
    if(!isSafari && !isKonqueror)
    {
        //function to add HTML -- thanks dannyuk1982
        var rte = currentRTE;
        var oRTE = returnRTE(rte);
        oRTE.focus();

        selectedText=getText(rte);
        alert("987:" + selectedText);
        html='<a href="/en/Home" class="buzz1">' + selectedText + ' </a>';
        //alert (selT);
        if(document.all)
            {
                alert ('lele');
                var oRng = oRTE.document.selection.createRange();
                alert (oRng);
                oRng.pasteHTML(html);
                oRng.collapse(false);
                oRng.select();
            }
         else
            {
                alert ('kk');
                oRTE.document.execCommand('insertHTML', false, html);
            }
    }
}

function insertHTML(html) {

    if(!isSafari && !isKonqueror) {
        //function to add HTML -- thanks dannyuk1982
        var rte = currentRTE;
        var oRTE = returnRTE(rte);
        oRTE.focus();
        if(document.all) {
            var oRng = oRTE.document.selection.createRange();
        //	alert ("1016:" + oRng);
            oRng.pasteHTML(html);
            oRng.collapse(false);
            oRng.select();
        } else {

            oRTE.document.execCommand('inserthtml', false, html);
        }
    } else {
        var searchFor = 'SafariHTMLReplaceString';
        var rte = currentRTE;
        rteCommand(rte,'InsertText', searchFor);
        var oRTE = returnRTE(rte);
        var tmpContent = oRTE.document.body.innerHTML.replace("'", "\'").replace('"', '\"');
        var strRegex = "/(?!<[^>]*)(" + searchFor + ")(?![^<]*>)/g";
        var cmpRegex=eval(strRegex);
        var runCount = 0;
        var tmpNext = tmpContent;
        var intFound = tmpNext.search(cmpRegex);
        while(intFound > -1) {
            runCount = runCount+1;
            tmpNext = tmpNext.substr(intFound + searchFor.length);
            intFound = tmpNext.search(cmpRegex);
        }
        if (runCount > 0) {
            tmpContent=tmpContent.replace(cmpRegex,html);
            oRTE.document.body.innerHTML = tmpContent.replace("\'", "'").replace('\"', '"');
            updateRTEs();
        }
    }
}

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

function replaceSpecialChars(html) {
    var specials = new Array("&cent;","&euro;","&pound;","&curren;","&yen;","&copy;","&reg;","&trade;","&divide;","&times;","&plusmn;","&frac14;","&frac12;","&frac34;","&deg;","&sup1;","&sup2;","&sup3;","&micro;","&laquo;","&raquo;","&lsquo;","&rsquo;","&lsaquo;","&rsaquo;","&sbquo;","&bdquo;","&ldquo;","&rdquo;","&iexcl;","&brvbar;","&sect;","&not;","&macr;","&para;","&middot;","&cedil;","&iquest;","&fnof;","&mdash;","&ndash;","&bull;","&hellip;","&permil;","&ordf;","&ordm;","&szlig;","&dagger;","&Dagger;","&eth;","&ETH;","&oslash;","&Oslash;","&thorn;","&THORN;","&oelig;","&OElig;","&scaron;","&Scaron;","&acute;","&circ;","&tilde;","&uml;","&agrave;","&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&Agrave;","&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&ccedil;","&Ccedil;","&egrave;","&eacute;","&ecirc;","&euml;","&Egrave;","&Eacute;","&Ecirc;","&Euml;","&igrave;","&iacute;","&icirc;","&iuml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;","&ntilde;","&Ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&ugrave;","&uacute;","&ucirc;","&uuml;","&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&yacute;","&yuml;","&Yacute;","&Yuml;");
    var unicodes = new Array("\u00a2","\u20ac","\u00a3","\u00a4","\u00a5","\u00a9","\u00ae","\u2122","\u00f7","\u00d7","\u00b1","\u00bc","\u00bd","\u00be","\u00b0","\u00b9","\u00b2","\u00b3","\u00b5","\u00ab","\u00bb","\u2018","\u2019","\u2039","\u203a","\u201a","\u201e","\u201c","\u201d","\u00a1","\u00a6","\u00a7","\u00ac","\u00af","\u00b6","\u00b7","\u00b8","\u00bf","\u0192","\u2014","\u2013","\u2022","\u2026","\u2030","\u00aa","\u00ba","\u00df","\u2020","\u2021","\u00f0","\u00d0","\u00f8","\u00d8","\u00fe","\u00de","\u0153","\u0152","\u0161","\u0160","\u00b4","\u02c6","\u02dc","\u00a8","\u00e0","\u00e1","\u00e2","\u00e3","\u00e4","\u00e5","\u00e6","\u00c0","\u00c1","\u00c2","\u00c3","\u00c4","\u00c5","\u00c6","\u00e7","\u00c7","\u00e8","\u00e9","\u00ea","\u00eb","\u00c8","\u00c9","\u00ca","\u00cb","\u00ec","\u00ed","\u00ee","\u00ef","\u00cc","\u00cd","\u00ce","\u00cf","\u00f1","\u00d1","\u00f2","\u00f3","\u00f4","\u00f5","\u00f6","\u00d2","\u00d3","\u00d4","\u00d5","\u00d6","\u00f9","\u00fa","\u00fb","\u00fc","\u00d9","\u00da","\u00db","\u00dc","\u00fd","\u00ff","\u00dd","\u0178");
    for(var i=0; i<specials.length; i++) {
        html = replaceIt(html,unicodes[i],specials[i]);
    }
    return html;
}

function SearchAndReplace(searchFor, replaceWith, matchCase, wholeWord) {
    var cfrmMsg = lblSearchConfirm.replace("SF",searchFor).replace("RW",replaceWith);
    var rte = currentRTE;
    stripGuidelines(rte);
    var oRTE = returnRTE(rte);
    var tmpContent = oRTE.document.body.innerHTML.replace("'", "\'").replace('"', '\"');
    var strRegex;
    if (matchCase && wholeWord) {
        strRegex = "/(?!<[^>]*)(\\b(" + searchFor + ")\\b)(?![^<]*>)/g";
    } else if (matchCase) {
        strRegex = "/(?!<[^>]*)(" + searchFor + ")(?![^<]*>)/g";
    } else if (wholeWord) {
        strRegex = "/(?!<[^>]*)(\\b(" + searchFor + ")\\b)(?![^<]*>)/gi";
    } else {
        strRegex = "/(?!<[^>]*)(" + searchFor + ")(?![^<]*>)/gi";
    }
    var cmpRegex=eval(strRegex);
    var runCount = 0;
    var tmpNext = tmpContent;
    var intFound = tmpNext.search(cmpRegex);
    while(intFound > -1) {
        runCount = runCount+1;
        tmpNext = tmpNext.substr(intFound + searchFor.length);
        intFound = tmpNext.search(cmpRegex);
    }
    if (runCount > 0) {
        cfrmMsg = cfrmMsg.replace("[RUNCOUNT]",runCount);
        if(confirm(cfrmMsg)) {
            tmpContent=tmpContent.replace(cmpRegex,replaceWith);
            oRTE.document.body.innerHTML = tmpContent.replace("\'", "'").replace('\"', '"');
        } else {
            alert("1109:" + lblSearchAbort);
        }
        showGuidelines(rte);
    } else {
        showGuidelines(rte);
        alert("["+searchFor+"] "+lblSearchNotFound);
    }
    if(isSafari || isKonqueror)updateRTEs();
}

function showHideElement(element, showHide, rePosition) {
    // function to show or hide elements
    // element variable can be string or object
    if(document.getElementById(element)) {
        element = document.getElementById(element);

    if(showHide == "show") {
        //element.style.visibility = "visible";
        element.style.display = "Block";
        if(rePosition) {
            element.style.position = "relative";
            element.style.left = "auto";
            element.style.top = "auto";

        }
    } else if(showHide == "hide") {
        //element.style.visibility = "hidden";
        element.style.display = "None";
        if(rePosition) {
            element.style.position = "absolute";
            element.style.left = "-1000px";
            element.style.top = "-1000px";

        }
    }

}
else
{alert ('no element ' + element);}
}

function setRange(rte) {
    // function to store range of current selection
    var oRTE = returnRTE(rte);
    var selection;
    if(document.all) {
        selection = oRTE.document.selection;
        if(selection != null) {
            rng = selection.createRange();

        }
    } else {
        selection = oRTE.getSelection();
        rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
    }
    return rng;
}

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

function trim(inputString) {
    if (typeof inputString != "string") {
        return inputString;
    }
    inputString = inputString.replace(/^\s+|\s+$/g, "").replace(/\s{2,}/g, "");
    return inputString;
}

function showGuidelines(rte) {

    if(rte.length == 0) rte = currentRTE;
    var oRTE = returnRTE(rte);
    var tables = oRTE.document.getElementsByTagName("table");
    var sty = "dashed 1px "+zeroBorder;
    for(var i=0; i<tables.length; i++) {
        if(tables[i].getAttribute("border") == 0) {
            if(document.all) {
                var trs = tables[i].getElementsByTagName("tr");
                for(var j=0; j<trs.length; j++) {
                    var tds = trs[j].getElementsByTagName("td");
                    for(var k=0; k<tds.length; k++) {
                        if(j == 0 && k == 0) {
                            tds[k].style.border = sty;
                        } else if(j == 0 && k != 0) {
                            tds[k].style.borderBottom = sty;
                            tds[k].style.borderTop = sty;
                            tds[k].style.borderRight = sty;
                        } else if(j != 0 && k == 0) {
                            tds[k].style.borderBottom = sty;
                            tds[k].style.borderLeft = sty;
                            tds[k].style.borderRight = sty;
                        } else if(j != 0 && k != 0) {
                            tds[k].style.borderBottom = sty;
                            tds[k].style.borderRight = sty;
                        }
                    }
                }
            } else {
                tables[i].removeAttribute("border");
                tables[i].setAttribute("style","border: " + sty);
                tables[i].setAttribute("rules", "all");
            }
        }
    }
}

function stripGuidelines(rte) {
    var oRTE = returnRTE(rte);
    var tbls = oRTE.document.getElementsByTagName("table");
    for(var j=0; j<tbls.length; j++) {
        if(tbls[j].getAttribute("border") == 0 || tbls[j].getAttribute("border") == null) {
            if(document.all) {
                var tds = tbls[j].getElementsByTagName("td");
                for(var k=0; k<tds.length; k++) {
                    tds[k].removeAttribute("style");
                }
            } else {
                tbls[j].removeAttribute("style");
                tbls[j].removeAttribute("rules");
                tbls[j].setAttribute("border","0");
            }
        }
    }
}

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

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

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

function countWords(rte) {
    parseRTE(rte);
    var words = document.getElementById("hdn"+rte).value;
    var str = stripHTML(words);
    var chars = trim(words);
    chars = chars.length;
    chars = maxchar - chars;
    str = str+" a ";	// word added to avoid error
    str = trim(str.replace(/&nbsp;/gi,' ').replace(/([\n\r\t])/g,' ').replace(/&(.*);/g,' '));
    var count = 0;
    for(x=0;x<str.length;x++) {
        if(str.charAt(x)==" " && str.charAt(x-1)!=" ") {
            count++;
        }
    }
    if(str.charAt(str.length-1) != " ") {
        count++;
    }
    count = count - 1;	// extra word removed
    var alarm = "";
    if(chars<0) {
        alarm = "\n\n"+lblCountCharWarn;
    }
    alert(lblCountTotal+": "+count+ "\n\n"+lblCountChar+": "+chars+alarm);
}



function switchMenuTab(titleId , tabId , menuId)
    {

        menu = document.getElementById(menuId);
        aHrefs = menu.getElementsByTagName( 'a' );

        for (i=0; i<aHrefs.length; i++)

        {   a = aHrefs[i];
            id = a.id;

            if (id.substring( id.length - 5 , id.length) == 'Title')
            {
                if (id != titleId)
                {a.className = "tablabel tablabel_inactive";  }
                else
                {a.className = "tablabel tablabel_active";}
            }
        }

        divs = menu.getElementsByTagName( 'div' );
        for (i=0; i< divs.length ; i++)
        {
            div = divs[i];
            if (div.id.substring( div.id.length - 4,div.id.length) == '_tab')
                {
                if (div.id != tabId)
                    {
                    div.className="tab tab_inactive";

                    }
                else
                    {

                      div.className="tab tab_active";
                    }
                }

        }
    }


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

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

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

//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
    // function to add bold, italic, and underline shortcut commands to gecko RTEs
    // contributed by Anti Veeranna (thanks Anti!)
    var rte = evt.target.id;
    if (evt.ctrlKey) {
        var key = String.fromCharCode(evt.charCode).toLowerCase();
        var cmd = '';
        switch (key) {
            case 'b': cmd = "bold"; break;
            case 'i': cmd = "italic"; break;
            case 'u': cmd = "underline"; break;
        }
        if (cmd) {
            rteCommand(rte, cmd, null);
            // stop the event bubble
            evt.preventDefault();
            evt.stopPropagation();
        }
    }
}



    function fixGeckoBaseHREFBug (m , rte , h) {
        var nl, i;

        e  = returnRTE(rte).document.body;
        if (isGecko) {
            if (m == 1) {
                h = h.replace(/\ssrc=/gi, " xsrc=");
                h = h.replace(/\shref=/gi, " xhref=");

                return h;
            } else {
                var el = new Array('a','img');

                for (var a=0; a<el.length; a++) {

                    var n = e.getElementsByTagName(el[a]);

                    for (i=0; i<n.length; i++) {
                        var xsrc = n[i].getAttribute("xsrc");
                        var xhref = n[i].getAttribute("xhref");

                        if (xsrc != null) {
                            //alert (n[i].src + ',' + xsrc + ',');
                            n[i].src = xsrc;
                            n[i].removeAttribute("xsrc");
                        }

                        if (xhref != null) {
                            n[i].href =  xhref;
                            n[i].removeAttribute("xhref");
                        }

                    }
                }
            }
        }

        return h;
    }


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