﻿/*======================================================================/*
// InstantForum.NET	© InstantASP Limited.							//
// http://www.instantasp.co.uk/											//
\*======================================================================*/

instantasprichtextbox = new Object();

function InstantASPRichTextBox(rtbID) { 

    this.id = rtbID;
    this.textArea = null;
    
    // public properties
    this.JSON = null;   
    this.jsonproxy = null;

    this.ImgFolder = null;
    this.SpellCheckClientID = null;
    this.InsertImageSrc = null;
    this.InsertAttachmentSrc = null;
    this.InsertAttachmentSpaceSrc = null;
    this.Height = "375px";
    this.ToolbarLayout = 1;
    this.EnableHTML = false;
    this.EnableImageUpload = true;
    this.EnableEmotIcons = true;
    this.EnableIFCode = true;
    
    this.TabIndex = null;
    this.HasFocus = null;    
    this.DesignStyle = "font-family: Verdana, Arial, Tahoma; font-size: 12px; color: #1F5080; cursor: text; width: auto;";
    this.HTMLStyle = "font-family: courier new, monospace; font-size: 10pt; color: #1F5080;";
    
    // DropDowns
    this.DropDowns = new Array();
    this.DropDowns['fonts'] = {
		id: "fonts",
		name: "Font",
		command: "FontName",
		label: "<font style=\"font-family:{value};font-size:12px;\">{value}</font>",
		width: "90px",
		elements: new Array(
			"Arial", 
			"Sans Serif", 
			"Tahoma", 
			"Verdana", 
			"Courier New", 
			"Georgia", 
			"Times New Roman", 
			"Impact", 
			"Comic Sans MS"
		)
	};
    // Font sizes
	this.DropDowns['fontsizes'] = {	
		id: "fontsizes",
		name: "Size",
		command: "FontSize",
		label: "<font size=\"{value}\">Size {value}</font>",
		width: "75px",
		elements: new Array(
			"1", 
			"2", 
			"3", 
			"4", 
			"5", 
			"6"
		)
	};
	
	// Headings
	this.DropDowns['headings'] = {	
		id: "headings",
		name: "Headings",
		command: "FormatBlock",
		label: "<{value} style=\"margin:0px;text-decoration:none;font-family:Arial\">{value}</{value}>",
		width: "80px",
		elements: new Array(
			"H1", 
			"H2", 
			"H3", 
			"H4", 
			"H5", 
			"H6"
		)
	};	

    // internal 
    this.commonUI = null;
    this.colorLevels = Array('1', '3', '5', '7', '9', 'B', 'D','F');
    this.colorsArray = new Array();
    this.colorsPerLine = 5;
    this.EmotIcons = new Array();
    this.IFCodes = new Array();
    this.DesignMode = true;
    this.ImageContextMenu = null;
    this.tempRng = null;
    this.initialized = false;
    this.initmenus = false;
    this._xmlHttp = null;

    // resize tracker    
        
    this.curHeight = 0;
    this.curPos = 0;
    this.newPos = 0;
    this.resizing = false;

    // default values

    this.txtYouTubeDefaultVal = "Enter the YouTube Video URL...";
    this.txtInsertLinkDefaultVal = "Enter the URL for your link...";
    this.txtHttpDefaultVal = "http://";
     
    if (instantasprichtextbox[rtbID]!=null) {
        return instantasprichtextbox[rtbID];
    } else { 
        instantasprichtextbox[rtbID]=this;
    }
    return this;
    
}

// ----------------------------------------------
// build editor
// ----------------------------------------------

InstantASPRichTextBox.prototype.initialize = function() {

    this.textArea = iasp_FindControl(this.id);

    // parse json to internal arrays for emoticons & IFCode    
    if (this.JSON != null && this.JSON != "") {
        this.parseJSON();
    }

    // generate colors array for color picker
    if (this.colorsArray.length == 0) {
        this.genColorsArray();
    }

    // init common ui
    if (this.commonUI == null) {
        this.commonUI = new InstantASPCommonUI(this.ImgFolder)
    }

    // build editor
    var s = this.buildEditor();

    // Insert the editor after the textarea	    
    if (this.initialized == false) {
        this.textArea.insertAdjacentHTML("afterEnd", s);
    }

    this.initialized = true;

    //hide textarea
    this.textArea.style.display = "none";

    // register toolbar mouseover events
    this.initMouseOvers(this.id);

    // setup editor

    var content = this.textArea.value;
    var win = this.getEditorWindow(this.id);
    var doc = null;
    if (win != null) {
         doc = win.document;
    }
    
    if (doc != null) {
    
        // write any existing context to iframe
        doc.open();
        doc.write(content);
        doc.close();

        // ensure content is editable
        if (doc.body.contentEditable) {
            doc.body.contentEditable = true;
        }
        else {
            doc.designMode = "on";
        }
            
        // set default iframe style	
        this.setDesignStyle(this.id);

        // build context menu objects
        this.buildContextMenus();

        // add context menu
        if (this.ImageContextMenu != null) {
            document.write(this.ImageContextMenu.genMenu());
        }

        // attach evetns
        this.addEvents();

        // set focus?
        if (this.HasFocus) { doc.body.focus(); }

    }

}

InstantASPRichTextBox.prototype.buildContextMenus = function() {

    // create context menus
    if (this.ImageContextMenu == null) {

        var ctx = new InstantASPContextMenu(this.id + "_ctxImg");
        ctx.absWidth = 190;
        ctx.menuOnClick = this.ctxMnuImgClick;

        ctx.add('1', 'Align Left', 'javascript: return false;', this.ImgFolder + "RichTextBox/Icons/mnu_Left.gif", true);
        ctx.add('2', 'Align Center', 'javascript: return false;', this.ImgFolder + "RichTextBox/Icons/mnu_Center.gif", true);
        ctx.add('3', 'Align Right', 'javascript: return false;', this.ImgFolder + "RichTextBox/Icons/mnu_Right.gif", true);
        ctx.addSeparator();
        ctx.add('4', 'Clear Align', '', '', true);
             
        this.setImageCtxMenu(ctx)
      
    }

}
    
// parse json data

InstantASPRichTextBox.prototype.parseJSON = function() {
    
    // setup json prozy
    this.jsonproxy = new InstantASPJSONProxy(this.JSON);
    
    // populate internal arrays
    this.EmotIcons = this.SelectEmotIcons();
    this.IFCodes = this.SelectIFCodes();

}
  
InstantASPRichTextBox.prototype.SelectEmotIcons = function() {

    var data = this.jsonproxy.getData();
    if (data.EmotIconCollection != null) {
        return this.jsonproxy.objToArray(data.EmotIconCollection.EmotIcons);
    }
    return null;
}

InstantASPRichTextBox.prototype.SelectIFCodes = function() {

    var data = this.jsonproxy.getData();
    if (data.IFCodeCollection != null) {
        return this.jsonproxy.objToArray(data.IFCodeCollection.IFCodes);
    }
    return null;
}

// add main events

InstantASPRichTextBox.prototype.addEvents = function() {

    // add evetns for editor resize 

    var id = this.id;

    // add events to document for resizing

    addEvent(document.body, 'mousemove', function(e) {
        InstantASPRichTextBox.prototype.setDivPosition(id, e)
    }
    );

    addEvent(window, 'load', function(e) {
        InstantASPRichTextBox.prototype.getInstance(id).initmenus = true;
    }
    );
    
    addEvent(document.body, 'mouseup', function(e) {
        InstantASPRichTextBox.prototype.endDivPosition(id, e)
    }
    );

    var doc = null;
    var win = this.getEditorWindow(this.id);
    if (win != null) {
        doc = win.document;
    }

    if (doc != null) {

        addEvent(doc, 'mousemove', function(e) {
            InstantASPRichTextBox.prototype.setDivPosition(id, e)
        }
        );

        addEvent(doc, 'mouseup', function(e) {
            InstantASPRichTextBox.prototype.endDivPosition(id, e)
        }
        );

        // populate hidden field with HTML

        addEvent(doc, 'mouseover', function(e) {
            InstantASPRichTextBox.prototype.populateHiddenField(id, e)
        }
        );

        addEvent(doc, 'mouseout', function(e) {
            InstantASPRichTextBox.prototype.populateHiddenField(id, e)
        }
        );

        // hide menus on click

        addEvent(doc, 'click', function(e) {
            iasp_HideAllMenus();
            hideAllMenu();
        }
        );

        // add key press to catch carriage returns within editor

//        addEvent(doc, 'keypress', function(e) {
//            return InstantASPRichTextBox.prototype.invertIELineBreaks(id, e);
//        }
//        );

        // add context menu events

        addEvent(doc, 'contextmenu', function(e) {
            return InstantASPRichTextBox.prototype.contextMenu(id, e)
        }
        );   

    }
    
    addEvent(document.body, 'mousedown', function(e) {
        InstantASPRichTextBox.prototype.populateHiddenField(id, e)
    }
    );

    // ensure we populate the editor with text from the hidden field

    addEvent(window, 'load', function(e) {
        InstantASPRichTextBox.prototype.populateRichText(id, e)
    }
    );  

}

// build main editor

InstantASPRichTextBox.prototype.buildEditor = function() {

    var resizemousedown = "InstantASPRichTextBox.prototype.getDivPosition('" + this.id + "', event);";

    var s = "";
    s += "<div id=\"container" + this.id + "\" class=\"rtb_Container\">";

    // build toolbars
    switch (this.ToolbarLayout) {
        case "3": // minimum  
            s += this.buildMinimalToolbar();
            break;
        case "2": // basic
            s += this.buildBasicToolbar();
            break;
        default: // all        
            s += this.buildToolbar();
            break;
    }

    s += this.buildAttachments();

    s += "<iframe frameborder=\"0\" id=\"iframe" + this.id + "\" class=\"rtb_TextBox\" style=\"width:100%;height:" + this.getHeight() + "px;\"";
    if (this.TabIndex != null) {
        s += " tabindex=\"" + this.TabIndex + "\"";
    }
    s += "></iframe>";

    // resize bar
    var resizeCSS = this.EnableHTML ? "rtb_ResizeBar" : "rtb_ResizeBarNoBorder";
    s += "<div id=\"resizeBar" + this.id + "\" unselectable=\"on\" class=\"" + resizeCSS + "\" onmousedown=\"" + resizemousedown + "\">";
    s += "<img src=\"" + this.ImgFolder + "richtextbox/icons/mnu_resize.gif\" alt=\"Resize Editor\" unselectable=\"on\" /></div>";

    // show HTML / design buttons?
    if (this.EnableHTML) {
        s += "<div style=\"float: left;\">";
        s += this.butSwitchDesign();
        s += this.butSwitchHTML();
        s += "</div>";
    } else {
        s += "<div style=\"float: left; height: 0px;\">&nbsp;</div>";
    }

    s += "</div>";
    s += "</div>";

    if (iasp_IsIE) {
        s += "  <object id=\"dlgColors\" CLASSid=\"clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b\" width=\"0\" height=\"0\" style=\"float: left;\" />"
    }

    return s;

}

// ----------------------------------------------
// toolbars
// ----------------------------------------------

// fulll toolbars

InstantASPRichTextBox.prototype.buildToolbar = function() {
       
    var s = "<div id=\"toolbars" + this.id + "\" class=\"rtb_ToolBarContainer\">";    
    
    // toolbar 1
    s += "<div class=\"rtb_ToolBar\">";    
    s += this.butGrabber()
    
    s += this.buildButton("insertunorderedlist", "mnu_bullets.gif", "Bulleted List");    
    s += this.buildButton("insertorderedlist", "mnu_numlist.gif", "Numbered List");           
    s += this.buildButton("indent", "mnu_indent.gif", "Increase Indent");    
    s += this.buildButton("outdent", "mnu_unindent.gif", "Decrease Indent");    

    s += this.butSeperator();

    s += this.buildButton("justifyleft", "mnu_Left.gif", "Decrease Indent");    
    s += this.buildButton("justifycenter", "mnu_Justify.gif", "Decrease Indent");    
    s += this.buildButton("justifyright", "mnu_Right.gif", "Decrease Indent");    

    s += this.butSeperator();
        

    s += this.buildMenuButton("ForeColor", "mnu_fontcolor.gif", "Font Color");    
    s += this.buildMenuButton("BackColor", "mnu_highlight.gif", "Background Color");           

    s += this.butSeperator();

    s += this.buildMenuButton("InsertLink", "mnu_link.gif", "Insert Link", true);

    if (this.InsertImageSrc != null && this.EnableImageUpload) {
        s += this.butSeperator();       
        s += this.buildMenuButton("InsertImage", "mnu_insertimg.gif", "Insert Image", true); 
    }
    
    
    if (this.EmotIcons != null && this.EmotIcons.length > 0 && this.EnableEmotIcons) {
        s += this.butSeperator();   
        s += this.buildMenuButton("EmotIcon", "mnu_emot.gif", "Insert EmotIcon");    
    }
    
    s += this.butSeperator();  
        
    s += this.buildMenuButton("YouTube", "mnu_youtube.gif", "Insert YouTube Video", true);    

    s += this.butSeperator();

    s += this.buildButton("Quote", "mnu_quote.gif", "Insert Quote");

    s += this.butSeperator();

    s += this.buildButton("RemoveFormat", "mnu_stripformatting.gif", "Remove All Formatting");

    if (this.IFCodes != null && this.IFCodes.length > 0 && this.EnableIFCode) {
        s += this.butSeperator();      
        s += this.buildTextButton("IFCode", "IF Code", "Insert IF Code");    
    }
        
    s += "</div>"
    
    // toolbar seperator
    s += "<div class=\"rtb_ToolBarSeperator\"></div>";
        
    // toolbar 2
    s += "<div class=\"rtb_ToolBar\">";    
    s += this.butGrabber();    
        
    s += this.buildButton("Bold", "mnu_bold.gif", "Bold Text");    
    s += this.buildButton("Italic", "mnu_italics.gif", "Italiize Text");    
    s += this.buildButton("Underline", "mnu_underline.gif", "Inderline Text");    
    s += this.buildButton("StrikeThrough", "mnu_strike.gif", "Strike Through");  
      
    s += this.butSeperator();
    
    s += this.buildDropDownButton("fonts")
    s += this.buildDropDownButton("fontsizes")       
    s += this.buildDropDownButton("headings")   
  
    s += this.butSeperator();
    
    s += this.buildButton("SpellCheck", "mnu_spell.gif", "Spell Check");    
    
    if (this.InsertAttachmentSrc != null) {
        s += this.butSeperator();
        s += this.buildTextButton("InsertAttachment", "Attach Files", "Insert IF Code", "mnu_attachments.gif", true);    
    }
    
    s += "</div>";    
    s += "</div>";
    
    return s
        
}

// basic toolbars

InstantASPRichTextBox.prototype.buildBasicToolbar = function() {
       
    var s = "<div id=\"toolbars" + this.id + "\" class=\"rtb_ToolBarContainer\">";    
    
    // toolbar 2
    s += "<div class=\"rtb_ToolBar\">";    
    s += this.butGrabber();    
        
    s += this.buildButton("Bold", "mnu_bold.gif", "Bold Text");    
    s += this.buildButton("Italic", "mnu_italics.gif", "Italiize Text");    
    s += this.buildButton("Underline", "mnu_underline.gif", "Inderline Text");    
    s += this.buildButton("StrikeThrough", "mnu_strike.gif", "Strike Through");  
      
    s += this.butSeperator();
    
    s += this.buildButton("insertunorderedlist", "mnu_bullets.gif", "Bulleted List");    
    s += this.buildButton("insertorderedlist", "mnu_numlist.gif", "Numbered List");           
    s += this.buildButton("indent", "mnu_indent.gif", "Increase Indent");    
    s += this.buildButton("outdent", "mnu_unindent.gif", "Decrease Indent");    
  
    s += this.butSeperator();

    s += this.buildMenuButton("ForeColor", "mnu_fontcolor.gif", "Font Color");    
    s += this.buildMenuButton("BackColor", "mnu_highlight.gif", "Background Color");           

    s += this.butSeperator();
    
    s += this.buildDropDownButton("fonts")
    s += this.buildDropDownButton("fontsizes")       

    s += this.butSeperator();

    s += this.buildMenuButton("InsertLink", "mnu_link.gif", "Insert Link", true);

    if (this.InsertImageSrc != null && this.EnableImageUpload) {
        s += this.butSeperator();       
        s += this.buildMenuButton("InsertImage", "mnu_insertimg.gif", "Insert Image", true); 
    }

    if (this.EmotIcons != null && this.EmotIcons.length > 0 && this.EnableEmotIcons) {
        s += this.butSeperator();   
        s += this.buildMenuButton("EmotIcon", "mnu_emot.gif", "Insert EmotIcon");
    }

    if (this.IFCodes != null && this.IFCodes.length > 0 && this.EnableIFCode) {
        s += this.butSeperator();
        s += this.buildButton("Quote", "mnu_quote.gif", "Insert Quote");
        s += this.butSeperator();
        s += this.buildTextButton("IFCode", "IF Code", "Insert IF Code");
    }
        
    s += "</div>";    
    s += "</div>";
    
    return s;
        
}

// minimal toolbars

InstantASPRichTextBox.prototype.buildMinimalToolbar = function() {
       
    var s = "<div id=\"toolbars" + this.id + "\" class=\"rtb_ToolBarContainer\">";    
    
    // toolbar 2
    s += "<div class=\"rtb_ToolBar\">";    
    s += this.butGrabber();    
        
    s += this.buildButton("Bold", "mnu_bold.gif", "Bold Text");    
    s += this.buildButton("Italic", "mnu_italics.gif", "Italiize Text");    
    s += this.buildButton("Underline", "mnu_underline.gif", "Inderline Text");    
    s += this.buildButton("StrikeThrough", "mnu_strike.gif", "Strike Through");  
      
    s += this.butSeperator();
    
    s += this.buildDropDownButton("fonts")
    s += this.buildDropDownButton("fontsizes")       
  
    s += this.butSeperator();

    s += this.buildMenuButton("ForeColor", "mnu_fontcolor.gif", "Font Color");    
    s += this.buildMenuButton("BackColor", "mnu_highlight.gif", "Background Color");           

    s += this.butSeperator();

    s += this.buildMenuButton("InsertLink", "mnu_link.gif", "Insert Link", true);

    if (this.InsertImageSrc != null && this.EnableImageUpload) {
        s += this.butSeperator();       
        s += this.buildMenuButton("InsertImage", "mnu_insertimg.gif", "Insert Image", true); 
    }
    
    s += "</div>"    
    s += "</div>"
    
    return s;
        
}

// ----------------------------------------------
// Attachments Panel
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildAttachments = function() {
       
    var s = "<div id=\"attachments" + this.id + "\" style=\"display: none;\" class=\"rtb_AttachmentsContainer\">";    
    s += "<div id=\"attachmentstext" + this.id + "\" class=\"rtb_Attachments\">";    
    s += "</div>";
    s += "</div>";
            
    return s;    
    
}

InstantASPRichTextBox.prototype.showAttachments = function(id, strText) {
    
    // get attachment layers
    var pnl = this.getAttachmentsPanel(id);
    var txt = this.getAttachmentsText(id);

    // populate & display
    if (pnl != null && txt != null) {    
        txt.innerHTML = strText;
        pnl.style.display = "";
    }

    // hode modal menu & remove from dom to reset iframe
    var cmd = "InsertAttachment";
    var mnu = this.getMenu(id, cmd);
    if (mnu != null) {
        this.hideModalMenu(id, cmd, true);
    }
    
}

InstantASPRichTextBox.prototype.hideAttachments = function(id) {

    // get attachment layers
    var pnl = this.getAttachmentsPanel(id);
    var txt = this.getAttachmentsText(id);

    // hide
    if (pnl != null && txt != null) {
        pnl.style.display = "none";
        txt.innerHTML = "";
    }

    // hode modal menu & remove from dom to reset iframe
    var cmd = "InsertAttachment";
    var mnu = this.getMenu(id, cmd);
    if (mnu != null) {
        this.hideModalMenu(id, cmd, true);
    }  
}

InstantASPRichTextBox.prototype.deleteAttachment = function (id, callbackURL) {

    if (!confirm(iasp_DelAttachment)) { return; }

    var attSpan = iasp_FindControl("att_" + id);

    if (attSpan != null) {

        var pnl = this.getAttachmentsPanel(this.id);

        // callback url
        arrURL = callbackURL.split("?");

        // setup xmlhttp
        if (this._xmlHttp == null) { this._xmlHttp = new iasp_XmlHttpRequest(); }

        var objXmlHttpHandler = function (obj) {
            if (obj.responseXML != null) {
                var items = obj.responseXML.getElementsByTagName("result");
                if (items.length > 0) {
                    for (var i = 0; i < items.length; i++) {
                        var nd = items[i];
                        // get result
                        var identity = nd.getAttribute("identity") == null ? 0 : nd.getAttribute("identity");

                        if (identity > 0) {

                            attSpan.style.display = 'none';

                            var prn = attSpan.parentNode;
                            if (prn != null) {
                                var spans = prn.getElementsByTagName("SPAN");
                                var spanVisible = false;
                                if (spans != null) {
                                    for (var i = 0; i < spans.length; i++) {
                                        var span = spans[i];
                                        if (span.style.display != "none") {
                                            spanVisible = true;
                                        }

                                    };
                                }

                                if (!spanVisible) {
                                    if (pnl != null) {
                                        pnl.style.display = "none";
                                    }
                                }
                            }

                        } else {
                            alert(iasp_DelAttachmentErr);
                        }
                        // end loader
                        iasp_AjaxExtensionsEndRequest();
                        // hide menu
                        iasp_HideAllMenus();

                    }
                }
            }
        };

        // setup params
        var strParams = arrURL[1] + "&ID=" + id;
        // setup loader
        iasp_AjaxExtensionsInitializeRequest();
        // make request
        this._xmlHttp.Connect(arrURL[0], "GET", strParams, objXmlHttpHandler);

    }

}

// ----------------------------------------------
// toolbar buttons
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildButton = function(cmd, img, title) {
    
    var onclick = "InstantASPRichTextBox.prototype.execCommand('" + this.id + "', '" + cmd + "');";
    
    var s = "<div class=\"rtb_Button\">";
    s += "<span onclick=\"" + onclick + "\">"
    s += "<img src=\"" + this.ImgFolder + "richtextbox/icons/" + img + "\" alt=\"" + title + "\" />";
    s += "</span></div>"
    
    return s;
    
}

// menu button
InstantASPRichTextBox.prototype.buildMenuButton = function(cmd, img, title, modal) {

    if (modal == null) { modal = false; }
    var butid = cmd + this.id + "_smMenu";
    var onclick = "InstantASPRichTextBox.prototype.showMenu('" + this.id + "', '" + butid + "','" + cmd + "', true, " + modal + ");"
    var onmouseover = "";

    // if not modal menu show on mouseover also
    if (modal == false) {
       onmouseover = "InstantASPRichTextBox.prototype.showMenu('" + this.id + "', '" + butid + "','" + cmd + "', false, " + modal + ");"
    }

    var s = "<span class=\"rtb_Button\">";
    s += "<span id=\"" + butid + "\" ";
    s += "onclick=\"" + onclick + "\" onmouseover=\"";
    s += onmouseover + "\" style=\"float: left;\">";
    s += "<img src=\"" + this.ImgFolder + "richtextbox/icons/" + img + "\" alt=\"" + title + "\" />";
    s += "</span></span>"

    return s;

}

// text button
InstantASPRichTextBox.prototype.buildTextButton = function(cmd, text, title, img, modal) {

    if (modal == null) { modal = false; }
    var butid = cmd + "_smMenu";
    var onclick = "InstantASPRichTextBox.prototype.showMenu('" + this.id + "', '" + butid + "','" + cmd + "', true, " + modal + ");"
    var onmouseover = "";

    // if not modal show menuu on mouse over
    if (modal == false) {
        onmouseover = "InstantASPRichTextBox.prototype.showMenu('" + this.id + "', '" + butid + "','" + cmd + "', false, " + modal + ");"
    }
    
    var s = "<span class=\"rtb_Links\">";
    s += "<span id=\"" + butid + "\" ";
    s += "onclick=\"" + onclick + "\" onmouseover=\"";
    s += onmouseover + "\" style=\"float: left;\">";
    s += "<a href=\"javascript: void(0);\">"
    if (img != null) {
        s += "<img src=\"" + this.ImgFolder + "richtextbox/icons/" + img + "\" alt=\"" + title + "\" />";
    }
    s += text;
    s += "</a></span></span>"

    return s;

}

// build drop down menu

InstantASPRichTextBox.prototype.buildDropDownButton = function(dropdownid) {
   	
	var dropdown = this.DropDowns[dropdownid];

    var butid = dropdownid + "_smMenu";
    var onclick = "InstantASPRichTextBox.prototype.showDropDownMenu('" + this.id + "', this.id, '" + dropdown.id + "', true);";
    var onmouseover = "InstantASPRichTextBox.prototype.showDropDownMenu('" + this.id + "', this.id, '" + dropdown.id + "', false); this.className = 'rtb_DropDownOver';";
    var onmouseout = "this.className = 'rtb_DropDown';";
    
	var s = "";    
	s += "<span id=\"" + butid + "_" + this.id + "\" class=\"rtb_DropDown\" style=\"width: " + dropdown.width + ";\" onclick=\"" + onclick + "\" onmouseover=\"" + onmouseover + "\" onmouseout=\"" + onmouseout + "\">";
	s += "<div class=\"rtb_DropDownTxt\">" + dropdown.name + "</div>";	
	s += "<div class=\"rtb_DropDownImg\">"
	s += "<img src=\"" + this.ImgFolder + "richtextbox/icons/mnu_dropdown.gif\" />";
	s += "</div>";	
	s += "</span>";
	
	return s;
	
}

// seperators & splitters

InstantASPRichTextBox.prototype.butSeperator = function() {
    return "<img src=\"" + this.ImgFolder + "richtextbox/icons/mnu_sep.gif\" class=\"rtb_Seperator\" alt=\"\" unselectable=\"on\" />"
}

InstantASPRichTextBox.prototype.butGrabber = function() {
    return "<img src=\"" + this.ImgFolder + "richtextbox/icons/mnu_grab.gif\" class=\"rtb_ToolBarGrabber\" alt=\"\" />";
}


InstantASPRichTextBox.prototype.butSwitchDesign = function() {

    var onclick = "if (this.src.indexOf('_off') >= 0) {InstantASPRichTextBox.prototype.SwitchEditor('" + this.id + "', true);}";
    return "<img id=\"switchDesign" + this.id + "\" src=\"" + this.ImgFolder + "richtextbox/icons/tab_edit_on.gif\" style=\"float: left; padding: 9px; width: 65px; height: 19px; cursor: pointer;\" onclick=\"" + onclick + "\" unselectable=\"on\" alt=\"Switch to editor view\" />";
}

InstantASPRichTextBox.prototype.butSwitchHTML = function() {

    var onclick = "if (this.src.indexOf('_off') >= 0) {InstantASPRichTextBox.prototype.SwitchEditor('" + this.id + "', false);}";
    return "<img id=\"switchHTML" + this.id + "\" src=\"" + this.ImgFolder + "richtextbox/icons/tab_html_off.gif\" style=\"float: left; padding: 9px; width: 65px; height: 19px; cursor: pointer; border: 0px;\" onclick=\"" + onclick + "\" unselectable=\"on\" alt=\"Switch to HTML view\" />";
}


InstantASPRichTextBox.prototype.getHeight = function() {

    if (this.Height != null) {
        var intArr = this.Height.split('p')
        return intArr[0];
    }
    
}

// ----------------------------------------------
// Siwtch Editor
// ----------------------------------------------

InstantASPRichTextBox.prototype.SwitchEditor = function(id, designMode) {

    var imgFolder = this.getInstance(id).ImgFolder;
    var butDesign = this.getDesignButton(id);
    var butHTML = this.getHTMLButton(id);
    var doc = this.getEditorWindow(id).document;

    // update variable to track state
    this.getInstance(id).DesignMode = designMode;

    // update controls
    if (butDesign != null && butHTML != null) {

        if (designMode) {

            // update txt
            var txt = null;
            if (iasp_IsIE) {
                txt = doc.body.innerText
            } else {
                txt = doc.body.textContent;
            }
            
            // update text
            if (txt != null) { doc.body.innerHTML = txt; }

            // switch styles
            this.setDesignStyle(id);

            // disable tools
            this.enableToolbars(id);

            // toggle images
            butDesign.src = imgFolder + "RichTextBox/Icons/tab_edit_on.gif";
            butHTML.src = imgFolder + "RichTextBox/Icons/tab_html_off.gif";

        } else {
            
            // update txt
            var txt = doc.body.innerHTML;
            txt = this.cleanHTML(txt);

            if (iasp_IsIE) {
            
                // tidy markup for HTML view
                txt = txt.replace(/<br\/>+/g, "\n<br/>");                       
                txt = txt.replace(/<ul>+/g, "<ul>\n");
                txt = txt.replace(/<\/ul>+/g, "\n</ul>");
                txt = txt.replace(/<li>+/g, "<li>\n");
                txt = txt.replace(/<\/li>+/g, "\n</li>");
                txt = txt.replace(/<ul><li>+/g, "<ul>\n<li>");
                txt = txt.replace(/<ol><li>+/g, "<ol>\n<li>");
                txt = txt.replace(/<\/li><\/ul>+/g, "</li>\n</ul>");
                txt = txt.replace(/<\/li><\/ol>+/g, "</li>\n</ol>");          
                txt = txt.replace(/<\/li><li>+/g, "</li>\n<li>");
                txt = txt.replace(/<table([^>]*)>+/g, "<table$1>\n");
                txt = txt.replace(/<tr([^>]*)>+/g, "<tr$1>\n");
                txt = txt.replace(/<td([^>]*)>+/g, "<td$1>\n");
                txt = txt.replace(/<\/td>+/g, "\n</td>");
                txt = txt.replace(/<\/tr>+/g, "\n</tr>");
                txt = txt.replace(/<tbody>+/g, "<tbody>\n");
                txt = txt.replace(/<\/tbody>+/g, "\n</tbody>");
                txt = txt.replace(/<\/table>+/g, "\n</table>\n");
                txt = txt.replace(/<\/h([1-9])>+/g, "</h$1>\n");
                
                doc.body.innerText = txt;
                
            } else {
                doc.body.textContent = txt;
            }

            // switch style
            this.setHTMLStyle(id);

            // disable tools
            this.diableToolbars(id);

            // toggle images
            butDesign.src = imgFolder + "RichTextBox/Icons/tab_edit_off.gif";
            butHTML.src = imgFolder + "RichTextBox/Icons/tab_html_on.gif";

        }

    }

}

InstantASPRichTextBox.prototype.cleanHTML = function(s) {

    if (s.substring(0, 6).toLowerCase() == "&nbsp;") { s = s.substring(6, s.length) }
 
    // clean html to ensure xhtml compliance
    s = s.replace(/<br>+/g, "<br/>");
    s = s.replace(/<BR>+/g, "<br/>");
    s = s.replace(/<P align=center[^>]*>(.*?)<\/P>/gi, '<center>$1</center>');
    s = s.replace(/<P align=right[^>]*>(.*?)<\/P>/gi, '<p align="right">$1</p>');
    s = s.replace(/<P align=left[^>]*>(.*?)<\/P>/gi, '<p align=left>$1</p>');
    s = s.replace(/<DIV align=right[^>]*>(.*?)<\/DIV>/gi, '<p align="right">$1</p>');
    s = s.replace(/<DIV align=left[^>]*>(.*?)<\/DIV>/gi, '<p align="left">$1</p>');
    s = s.replace(/<P>+/g, "<p>");
    s = s.replace(/<\/P>+/g, "</p>");
    s = s.replace(/<P style=([^>]*)>+/g, "<p>");
    s = s.replace(/<P([^>]*)>+/g, "<p$1>");
    s = s.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi, '');
    s = s.replace(/<p>(.*?)<\/p>/gi, '$1<br/><br/>'); 
    s = s.replace(/<UL>+/g, "<ul>");
    s = s.replace(/<UL[^>]*>+/g, "<ul>");
    s = s.replace(/<OL>+/g, "<ol>");
    s = s.replace(/<OL[^>]*>+/g, "<ol>");
    s = s.replace(/<\/OL>+/g, "</ol>");    
    s = s.replace(/<\/UL>+/g, "</ul>");
    s = s.replace(/<LI>+/g, "<li>");
    s = s.replace(/<\/LI>+/g, "</li>");
    s = s.replace(/<ul>[^>]*<li>+/g, "<ul><li>");
    s = s.replace(/<ol>[^>]*<li>+/g, "<ol><li>");
    s = s.replace(/<\/li>([^li]*)<li>+/g, "</li><li>");
    s = s.replace(/(<br\/><br\/>[^>]*)<ul>+/g, "<ul>");
    s = s.replace(/(<br\/>[^>]*)<ul>+/g, "<ul>");
    s = s.replace(/<TABLE([^>]*)>+/g, "<table$1>");
    s = s.replace(/<TR([^>]*)>+/g, "<tr$1>");
    s = s.replace(/<TD([^>]*)>+/g, "<td$1>");
    s = s.replace(/<\/TD>+/g, "</td>");
    s = s.replace(/<\/TR>+/g, "</tr>");
    s = s.replace(/<TBODY>+/g, "<tbody>");
    s = s.replace(/<\/TBODY>+/g, "</tbody>");
    s = s.replace(/<\/TABLE>+/g, "</table>");
    s = s.replace(/<STRONG>+/g, "<strong>");
    s = s.replace(/<\/STRONG>+/g, "</strong>");
    s = s.replace(/<A+/g, "<a");
    s = s.replace(/<\/A>+/g, "</a>");
    s = s.replace(/<DIV([^>])*>+/g, "");
    s = s.replace(/<DIV>+/g, "");
    s = s.replace(/<\/DIV>+/g, "");    
    s = s.replace(/<div><br\/><\/div>+/g, "<br/><br/>"); // safari
    s = s.replace(/<\/div>+/g, "");
    s = s.replace(/<U>+/g, "<span style=\"text-decoration: underline;\">");
    s = s.replace(/<\/U>+/g, "</span>");
    s = s.replace(/<u>+/g, "<span style=\"text-decoration: underline;\">");
    s = s.replace(/<\/u>+/g, "</span>");
    s = s.replace(/<I>+/g, "<span style=\"font-style: italic;\">");
    s = s.replace(/<\/I>+/g, "</span>");
    s = s.replace(/<i>+/g, "<span style=\"font-style: italic;\">");
    s = s.replace(/<\/i>+/g, "</span>");
    s = s.replace(/<B>+/g, "<strong>");
    s = s.replace(/<\/B>+/g, "</strong>");
    s = s.replace(/<b>+/g, "<strong>");
    s = s.replace(/<\/b>+/g, "</strong>");
    s = s.replace(/<EM>+/g, "<i>");
    s = s.replace(/<\/EM>+/g, "</i>");
    s = s.replace(/<CENTER>+/g, "<center>");
    s = s.replace(/<\/CENTER>+/g, "</center>");
    s = s.replace(/<STRIKE>+/g, "<strike>");
    s = s.replace(/<\/STRIKE>+/g, "</strike>");
    s = s.replace(/<SPAN +/g, "<span ");
    s = s.replace(/<IMG([^>]*)>+/g, "<img$1/>");
    s = s.replace(/<HR([^>]*)>+/g, "<hr$1/>");
    s = s.replace(/FONT-SIZE\: +/g, "font-size: ");
    s = s.replace(/FONT-STYLE\: italic+/g, "font-style: italic;");
    s = s.replace(/TEXT-DECORATION\: underline+/g, "text-decoration: underline;");
    s = s.replace(/BACKGROUND-COLOR\: +/g, "background-color: ");
    s = s.replace(/<\/SPAN>+/g, "</span>");
    s = s.replace(/<IMG src+/g, "<img src");
    s = s.replace(/ alt=(http[^\"]*) +/g, " alt=\"$1\" ");
    s = s.replace(/<img alt=\"([^\"]*)\" src=\"([^\"]*)\">+/g, "<img src=\"$2\" alt=\"$2\" />");
    s = s.replace(/<img src=\"([^\"]*)\">+/g, "<img src=\"$1\" alt=\"$1\" />");
    s = s.replace(/<FONT/g, '<font');
    s = s.replace(/<\/FONT>/g, '</font>');
    s = s.replace(/\sclass=Apple-style-span/g, '');
    s = s.replace(/<FORM([^>])*>+/g, "");
    s = s.replace(/<FORM>+/g, "");
    s = s.replace(/<\/FORM>+/g, "");
    s = s.replace(/<form([^>])*>+/g, "");
    s = s.replace(/<\/form>+/g, "");
    s = s.replace(/<H([1-9])([^>])*>+/g, "<h$1>");
    s = s.replace(/<\/H([1-9])>+/g, "</h$1>");
    s = s.replace(/\n/g, '');
    s = s.replace(/<p align=left[^>]*>(.*?)<\/p>/gi, '$1');
    
    for (var i = 0; i < 5; i++) {
        if (s.substring(s.length - 5).toLowerCase() == "<br/>") { s = s.substring(0, s.length - 5) }
    }
    
    return s;

}

InstantASPRichTextBox.prototype.setDesignStyle= function(id) {

    var win = this.getEditorWindow(id);
    
    var b = null;    
    if (win != null) {
        b = win.document.body;
    }
    
    if (b != null) {    

        var sHeight = this.getEditor(id).style.height;
        heightArray = sHeight.split('p')
        intHeight = parseInt(heightArray[0]) - 16;        
        this.getInstance(id).commonUI.setAttribute(b, "style", this.getInstance(id).DesignStyle + "height: " + intHeight + "px;");
    
    }
		
}

InstantASPRichTextBox.prototype.setHTMLStyle= function(id) {

    var b = this.getEditorWindow(id).document.body;    
	this.getInstance(id).commonUI.setAttribute(b, "style", this.getInstance(id).HTMLStyle);
		
}

// ----------------------------------------------
// methods to populate hidden text field for ASP.NET control
// ----------------------------------------------

InstantASPRichTextBox.prototype.populateHiddenField = function(id) {

    var win = this.getEditorWindow(id);

    var s = "";
    if (win != null) {
        s =  win.document.body.innerHTML;
    } else {
        return;
    }
    
    // replace line breaks in hidden field
    s = s.replace(/\n/g, '');
    s = s.replace(/\r/g, '');
    
    if (this.getInstance(id).DesignMode) {
        iasp_FindControl(id).value = this.cleanHTML(s);
    }

}

InstantASPRichTextBox.prototype.populateRichText = function(id) {

    var hidden = iasp_FindControl(id);
    
    if (hidden.value != "") {

        var win = this.getEditorWindow(id);
        if (win != null) {
            win.document.body.innerHTML = hidden.value;
        }
    }

}

// ----------------------------------------------
// show toolbar menus
// ----------------------------------------------

InstantASPRichTextBox.prototype.showToolbarMenu = function(id, butid, divid, width, height, modal) {
    
    if (!width) {width = "110px";}
    if (!height) {height = "";}
    var but = iasp_FindControl(butid);   
    if (but != null) {
        iasp_OpnMnu(but.id, divid, width, height, modal)
    }

}

InstantASPRichTextBox.prototype.showToolbarMenuMouseOver = function(id, butid, divid, width, height, modal) {
    
    if (!width) {width = "110px";}
    if (!height) {height = "";}
    var but = iasp_FindControl(butid); 
    if (but != null) {
        iasp_OpnMnuMO(but.id, divid, width, height, modal)
    }
}

// ----------------------------------------------
// menu button click events
// ----------------------------------------------

// show menu

InstantASPRichTextBox.prototype.showMenu = function(id, butid, cmd, onclick, modal) {

    // are we in design mode?
    if (!this.getInstance(id).DesignMode && onclick) { return; }
    if (!this.getInstance(id).initialized || !this.getInstance(id).initmenus) { return; }

    // set menu dimensions
    var width = "110px";
    var height = "";
    var div = null;

    switch (cmd) {

        case "ForeColor":

            width = "126px";
            div = this.buildColorPickerMenu(id, cmd);
          
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
       
            break;

        case "BackColor":

            width = "126px";
            div = this.buildColorPickerMenu(id, cmd);
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            break;

        case "IFCode":

            height = "300px";
            width = "173px"
            div = this.buildIFCodeMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            break;

        case "EmotIcon":

            width = "180px"
            div = this.buildEmotIconMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            break;

        case "InsertImage":

            width = "525px"
            div = this.buildInsertImageMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            this.initInsertImageTable(id);
            break;

        case "InsertAttachment":

            width = "558px"
            div = this.buildInsertAttachmentMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            break;

        case "InsertLink":

            width = "560px"
            div = this.buildInsertLinkMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            this.initInsertLinkTable(id);
            break;

        case "YouTube":

            width = "550px"
            div = this.buildYouTubeMenu(id, cmd)
            if (iasp_FindControl(div.id) == null) { document.body.appendChild(div); }
            this.initInsertYouTubeTable(id);
            break;

    }

    if (onclick) {
        this.showToolbarMenu(id, butid, div.id, width, height, modal);
    } else {
        this.showToolbarMenuMouseOver(id, butid, div.id, width, height, modal);
    }

    // for modal menuus ensure we disable the editor
    if (modal && iasp_MenusActive) {

        // add event to hide modal menus on resize as they are not added to our simple menu array
        addEvent(window, 'resize', function() {
            InstantASPRichTextBox.prototype.hideModalMenu(id, cmd);
        }
        );

        // close menus on escape key
        addEvent(window.document.body, 'keydown', function(e) {
            var keyCode = getKeyCode(e);
            var esc = (window.event) ? 27 : e.DOM_VK_ESCAPE // MSIE : Firefox
            if (e.keyCode == esc) {
                InstantASPRichTextBox.prototype.hideModalMenu(id, cmd);
                return false;
            }
        }
        );

        // disable editor
        this.disableIFrame(id);

    }

}

InstantASPRichTextBox.prototype.hideModalMenu = function(id, cmd, removeFromDOM) {

    var mnu = this.getMenu(id, cmd);

    if (mnu != null) {

        // hide menu
        mnu.style.display = "none";

        // page level variables for simple menu control
        iasp_ModalActive = false;
        iasp_MenusActive = false;

        // enable body
        iasp_enableBody();

        // enable iframe
        this.enableIFrame(id);

        // reenable any form
        enableFormSubmit();

        // we need to remove menus with iframes to reset the iframes
        if (removeFromDOM == null) { removeFromDOM = false; }
        if (removeFromDOM) {
            document.body.removeChild(mnu);
        }

    }

}


// show drop down list menu

InstantASPRichTextBox.prototype.showDropDownMenu = function(id, butid, dropdownid, onclick) {

    if (!this.getInstance(id).initialized || !this.getInstance(id).initmenus) { return; }

    var but = iasp_FindControl(butid);
    var div = this.getInstance(id).buildDropDownMenu(id, dropdownid);

    if (iasp_FindControl(div.id) == null) {
        document.body.appendChild(div);
    }

    if (but != null && div != null) {
        if (onclick) {
            iasp_OpnMnu(but.id, div.id, '130px', '400px')
        } else {
            iasp_OpnMnuMO(but.id, div.id, '130px', '400px')
        }
    }

}

// ----------------------------------------------
// build drop down menu
// ----------------------------------------------
	
InstantASPRichTextBox.prototype.buildDropDownMenu = function(id, dropdownid) {

    // get drop down item
    var dropdown = this.getInstance(id).DropDowns[dropdownid];
	dropdown.elements.sort();
	
	// build drop down menu
    var div = document.createElement('div');
    div.id = "dd_" + dropdown.id + "_" + id;
    div.style.display = 'none';
    div.className = "rtb_DropDownMnu";
    
	// build menu
	var m = "";
	for (var i = 0; i < dropdown.elements.length;i++) {
	
		if (dropdown.elements[i]) {
		
			var value = dropdown.elements[i];
			var label = dropdown.label.replace(/{value}/gi, value);

			var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + dropdown.command + "','" + value + "')\;";            			
            var onmouseover = "this.className = 'rtb_DropDownMnuButOver';"; 
            var onmouseout = "this.className = 'rtb_DropDownMnuBut';";
            
	  		m += "<button type=\"button\" onclick=\"" + onclick + "\" onmouseover=\"" + onmouseover + "\" onmouseout=\"" + onmouseout + "\"  class=\"rtb_DropDownMnuBut\" style=\"width: 100%;\">";
	  		m += '<table cellpadding="0" cellspacing="0" border="0"><tr>';
	  		m += '<td align="left">' + label + '</td>';
	  		m += '</tr></table></button><br/>';	
	  	}
	  	
  	}
  	
  	// populate div
	div.innerHTML = m;
	
	// return menu
	return div;


}


// ----------------------------------------------
// EmotIcons Menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildEmotIconMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildEmotIconTable(id, cmd);
    
    return div;

}

InstantASPRichTextBox.prototype.buildEmotIconTable = function(id, cmd) {

    var imgfolder = this.getInstance(id).ImgFolder;
    var emoticons = this.getInstance(id).EmotIcons;
    var cols = 5
    
    var s = "";
    s += "<table cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">";
    
    for (i = 0; i < emoticons.length; i++) {
    
        if (i % cols == 0) {
            s += "<tr>";
        }

        var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','" + emoticons[i].Code + "')\;";
        var onmouseover = "this.className = 'rtb_DropDownMnuButOver';"; 
        var onmouseout = "this.className = 'rtb_DropDownMnuBut';";

        s += "<td>";        
        s += "<button type=\"button\" onclick=\"" + onclick + "\" onmouseover=\"" + onmouseover + "\" onmouseout=\"" + onmouseout + "\" onclick=\"" + onclick + "\" class=\"rtb_DropDownMnuBut\">";
        s += "<img src=\"" + imgfolder + "EmotIcons/" + emoticons[i].File + "\" alt=\"" + emoticons[i].Desc + "\" />";
        s += "</button></td>";
        
        if (i % cols == cols - 1) {
            s += "</tr>";
        }
        
    }

    if (i % cols != 0) {
        s += "</tr>";
    }
    
    s += "</table>";

    return s;

}

// ----------------------------------------------
// Insert Image Menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildInsertImageMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildInsertImageTable(id, cmd);
    
    return div;    

}

InstantASPRichTextBox.prototype.buildInsertImageTable = function(id, cmd) {
    
    // get default val and iframe url
     var iframesrc = this.getInstance(id).InsertImageSrc;
     var lnkDefaultVal = this.getInstance(id).txtHttpDefaultVal;
     
     // control ids
     var txtid = "txtInsertImageURL" + id;
     var butid = "butInsertImage" + id;
     var iframeid = "insertimageiframe" + id;
 
    // setup ids for toggle options
    var lnk1 = "lnk1" + id + cmd;
    var lnk2 = "lnk2" + id + cmd;
    var pnl1 = "pnl1" + id + cmd;
    var pnl2 = "pnl2" + id + cmd;
    
    // control events
     var onkeydown = "return catchKeyDown('" + butid + "', event)"
     var onclick = "InstantASPRichTextBox.prototype.addImageOnClick('" + iframeid + "','" + id + "','" + cmd + "'); return false;";
     var onrowclick = "InstantASPRichTextBox.prototype.toggleMenuOptions('" + id + "', '" + cmd + "');"
     var closeonclick = "InstantASPRichTextBox.prototype.hideModalMenu('" + id + "', '" + cmd + "');"
     
    // build menu options

    var s = "";
    s += "<table cellspacing=\"1\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"PanelBar_SubHeader\">";
    
    s += "<div style=\"float: left; width: 50%;\">";
    s += "<span>Edit Image</span>";
    s += "</div>";
    s += "<div style=\"float: right; text-align: left; width: 49%;\">";
    s += "<a href=\"javascript:void(0);\" onclick=\"" + closeonclick + "\">";
    s += "<img src=\"" + this.getInstance(id).ImgFolder + "Misc_CloseWindow.gif\" align=\"right\" />";
    s += "</a>";
    s += "</div>";
    s += "</td></tr>";

    s += "<tr><td class=\"TableCell_Light\">";

    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr>";
    s += "<td class=\"rtb_MenuOptLnkSel\" id=\"" + lnk1 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Link Image:";
    s += "</a>";
    s += "</td>";
    s += "<td rowspan=\"3\" class=\"rtb_MenuOptContainer\" valign=\"top\">";

    //link to image

    s += "<div  id=\"" + pnl1 + "\" style=\"height: 100px;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "The URL for the image you wish to display...<br/><br/>"
    s += "<input id=\"" + txtid + "\" type=\"text\" onkeydown=\"" + onkeydown + "\" tabindex=\"1\" style=\"width: 99%;\" value=\"" + lnkDefaultVal + "\" class=\"FormInputText\" style=\"width: 97%\" />";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";

    // upload image

    s += "<div  id=\"" + pnl2 + "\" style=\"display: none; height: 100px;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "<iframe frameborder=\"0\" id=\"" + iframeid + "\" src=\"" + iframesrc + "?key=" + id + "\" scrolling=\"no\" style=\"width:100%; height:80px;\"></iframe>";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";


    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxtBold\" id=\"" + lnk2 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Upload Image:";
    s += "</a>";
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";

    s += "</table>";

    s += "</td></tr>";
    s += "<tr><td class=\"TableCell_Light\" align=\"right\">";
    s += "<button id=\"" + butid + "\" class=\"FormButtonBig\" onclick=\"" + onclick + "\">Add Image</button>";
    s += "</td></tr>"
    s += "</table>"; 

    return s;

}

// event called from insert image iframe
InstantASPRichTextBox.prototype.addImageOnClick = function(iframeid, id, cmd) {

    // local vars
    var sDefault = this.getInstance(id).txtHttpDefaultVal;

    // get URL textbox
    var txtURL = this.getInsertImageURL(id);

    // check to see if we have an upload?
    var bolHasUpload = false;
    var txtUpload = this.getUploadTextBox("insertimageiframe" + id, id, cmd)
    if (txtUpload != null) {
        if (txtUpload.value != "") {
            bolHasUpload = true;
        }
    }

    var sImgURL = null;
    if (txtURL != null) {
        if (txtURL.value != sDefault) {
            sImgURL = txtURL.value;
        } else {
            sImgURL = "";
        }
    }

    if (sImgURL != null && bolHasUpload == false) {
        if (sImgURL != "") {
            this.execCommand(id, cmd, sImgURL);
        } else {
           this.hideModalMenu(id, cmd, true);
        }
    } else {
        this.clickSubmitInIframe(iframeid, id, cmd);
    }

    // return false
    return false;


}

InstantASPRichTextBox.prototype.addImage = function(id, cmd, imageURL) {
 
    var sDefault = this.getInstance(id).txtHttpDefaultVal;

    // get image URL from textbox or upload
    var sImgURL = null;
    if (imageURL != null && imageURL != "") {
        sImgURL = imageURL;
    }

    // do we have an image?
    if (sImgURL != null) {

        // get range
        var doc = this.getEditorWindow(id).document;
        var sel = this.getSelection(id)
        var rng = this.getRange(sel);

        // use temp range if available
        if (this.getInstance(id).tempRng != null) {
            rng = this.getInstance(id).tempRng;
        }
        
        var img = this.findParent("IMG", rng);
        var update = (img == null) ? false : true;
        if (!update) {
   
            // if we don't have a link return
            if (sImgURL == "" || sImgURL == sDefault) {
                return;
            } else {
                // create link
                img = doc.createElement("IMG");
                
            }
        } else {
            // remove img if we don't have a URL
            if (sImgURL == "" || sImgURL == sDefault) {
                this.removeNode(id);
            }
        }

 
        // we have a URL, set the attributes
        this.getInstance(id).commonUI.setAttribute(img, "src", sImgURL);
     
        img.removeAttribute("width");
        img.removeAttribute("height");

        // on update exit here
        if (update) { return; }

        // Check if IE or Mozilla (other)
        if (iasp_IsIE) {
            rng.pasteHTML(img.outerHTML);
        }
        else {
            this.insertNodeAtSelection(img, id);
        }


    }


    // use true to remove from DOM for Iframe
    this.hideModalMenu(id, cmd, true);

}

InstantASPRichTextBox.prototype.initInsertImageTable = function(id) {

    // local vars
    var sDefault = this.getInstance(id).txtHttpDefaultVal;

    // setup focus to editor
    this.getEditorWindow(id).focus();

    // local link variables
    var lnk = this.getInsertImageURL(id);

    // get current selection
    var sel = this.getSelection(id);
    var rng = this.getRange(sel);

    // add range to internal variable
    if (rng != null) {
        this.getInstance(id).tempRng = rng;
    }

    // local variables

    var sLnk = null;
    var a = this.findParent("IMG", rng);
    if (a != null) {
        sLnk = a.src;  
    }

    // populate menu controls

    if (lnk != null) {
        if (sLnk != null) {
            lnk.value = sLnk;
        } else {
            lnk.value = sDefault;
        }
    }

}

// ----------------------------------------------
// Insert Attachment Menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildInsertAttachmentMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildInsertAttachmentTable(id, cmd);
    
    return div;
    
}

InstantASPRichTextBox.prototype.buildInsertAttachmentTable = function(id, cmd) {

    var iframesrc = this.getInstance(id).InsertAttachmentSrc;
    var iframespansrc = this.getInstance(id).InsertAttachmentSpaceSrc;
    
    // setup ids for toggle options
    var lnk1 = "lnk1" + id + cmd;
    var lnk2 = "lnk2" + id + cmd;
    var pnl1 = "pnl1" + id + cmd;
    var pnl2 = "pnl2" + id + cmd;

    // click event for button

    var iframeid = "insertattachmentiframe" + id
    var onclick = "InstantASPRichTextBox.prototype.clickSubmitInIframe('" + iframeid + "','" + id + "','" + cmd + "'); return false;"
    var onrowclick = "InstantASPRichTextBox.prototype.toggleMenuOptions('" + id + "', '" + cmd + "');"
    var closeonclick = "InstantASPRichTextBox.prototype.hideModalMenu('" + id + "', '" + cmd + "');"
     
    // build menu options

    var s = "";
    s += "<table cellspacing=\"1\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"PanelBar_SubHeader\">";


    s += "<div style=\"float: left; width: 50%;\">";
    s += "<span>Upload Attachment</span>";
    s += "</div>";
    s += "<div style=\"float: right; text-align: left; width: 49%;\">";
    s += "<a href=\"javascript:void(0);\" onclick=\"" + closeonclick + "\">";
    s += "<img src=\"" + this.getInstance(id).ImgFolder + "Misc_CloseWindow.gif\" align=\"right\" />";
    s += "</a>";
    s += "</div>";
    
    s += "</td></tr>";

    s += "<tr><td class=\"TableCell_Light\">";

    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr>";
    s += "<td class=\"rtb_MenuOptLnkSel\" id=\"" + lnk1 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Upload:";
    s += "</a>";
    s += "</td>";
    s += "<td rowspan=\"4\" class=\"rtb_MenuOptContainer\" valign=\"top\">";

    // upload attachment

    s += "<div  id=\"" + pnl1 + "\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "<iframe frameborder=\"0\" id=\"" + iframeid + "\" src=\"" + iframesrc + "&key=" + id + "\" scrolling=\"no\" style=\"width:100%; height: 110px;\"></iframe>";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";

    // attachment space

    s += "<div  id=\"" + pnl2 + "\" style=\"display: none;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"LargeTxtBold\">";
    s += "<iframe frameborder=\"0\" id=\"spaceframe" + id + "\" src=\"" + iframespansrc + "?key=" + id + "\" scrolling=\"no\" style=\"width:100%; height: 110px;\"></iframe>";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";

    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxtBold\" id=\"" + lnk2 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Free Space:";
    s += "</a>";
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";

    s += "</table>";

    s += "</td></tr>";
    s += "<tr><td class=\"TableCell_Light\" align=\"right\">";
    s += "<button class=\"FormButtonBig\" onmousedown=\"" + onclick + "\">Add Attachment</button>";
    s += "</td></tr>"
    s += "</table>";

    return s;

}

InstantASPRichTextBox.prototype.clickSubmitInIframe = function (iframeid, id, cmd) {

    if (iframeid == null || iframeid == "") { return }

    var d = document;
    var f = d.frames ? d.frames[iframeid] : d.getElementById(iframeid);
    var fdoc = f.document || f.contentWindow.document;
    var but = iasp_findSubmit(fdoc);
    if (but != null) { but.click(); }


}

InstantASPRichTextBox.prototype.getUploadTextBox = function(iframeid, id, cmd) {

    var d = document;
    var f = d.frames ? d.frames[iframeid] : d.getElementById(iframeid);
    var fdoc = f.document || f.contentWindow.document;
    var txt = iasp_findUpload(fdoc);
    return txt;
    
}

// ----------------------------------------------
// YouTube Menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildYouTubeMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildYouTubeTable(id, cmd);
    
    return div;
    
}

InstantASPRichTextBox.prototype.buildYouTubeTable = function(id, cmd) {
    
    var txtid = "txtYouTube" + id;
    var butid = "butYouTube" + id;
    var defaultVal = this.getInstance(id).txtYouTubeDefaultVal;
    
    var onfocus = "clearTxt(this, '" + defaultVal + "', true);"
    var onblur = "clearTxt(this, '" + defaultVal + "');";
    var onkeydown  = "return catchKeyDown('" + butid + "', event)"
    var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','')\;";
    var closeonclick = "InstantASPRichTextBox.prototype.hideModalMenu('" + id + "', '" + cmd + "');"
     
    var s = "";
    s += "<table cellspacing=\"1\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"PanelBar_SubHeader\">";

    s += "<div style=\"float: left; width: 50%;\">";
    s += "<span>YouTube Video</span>";
    s += "</div>";
    s += "<div style=\"float: right; text-align: left; width: 49%;\">";
    s += "<a href=\"javascript:void(0);\" onclick=\"" + closeonclick + "\">";
    s += "<img src=\"" + this.getInstance(id).ImgFolder + "Misc_CloseWindow.gif\" align=\"right\" />";
    s += "</a>";
    s += "</div>";  
    
    s += "</td></tr>";

    s += "<tr><td class=\"TableCell_Light\">";


    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr>";
    s += "<td class=\"rtb_MenuOptLnkSel\">";
    s += "<a href=\"javascript: void(0);\" class=\"SmallTxtBold\">";
    s += "You Tube:";
    s += "</a>";
    s += "</td>";
    s += "<td rowspan=\"3\" class=\"rtb_MenuOptContainer\" valign=\"top\">";

    // web address

    s += "<div  id=\"pnlURL_" + id + "\" style=\"height: 115px;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "The YouTube web page URL for the video:<br/><br/>"
    s += "<input id=\"" + txtid + "\" type=\"text\" style=\"width: 99%;\" onfocus=\"" + onfocus + "\" onblur=\"" + onblur + "\" onkeydown=\"" + onkeydown + "\" value=\"" + defaultVal + "\" class=\"FormInputText\" style=\"width: 97%\" />";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";

    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";
    s += "</table>";

    s += "</td></tr>";
    s += "<tr><td class=\"TableCell_Light\" align=\"right\">";
    s += "<button id=\"" + butid + "\" class=\"FormButtonBig\" onclick=\"" + onclick + "\">Add Video</button>";
    s += "</td></tr>"
    s += "</table>";
    
    return s;

}

InstantASPRichTextBox.prototype.initInsertYouTubeTable = function(id) {

    // local vars
    var sDefault = this.getInstance(id).txtYouTubeDefaultVal;

    // setup focus to editor
    this.getEditorWindow(id).focus();

    // local link variables
    var youtube = this.getYouTubeTextBox(id);

    // get current selection
    var sel = this.getSelection(id);
    var rng = this.getRange(sel);

    // add range to internal variable
    if (rng != null) {
        this.getInstance(id).tempRng = rng;
    }

    // local variables

    var sTxt = null;
    if (typeof rng.text != 'undefined') {
        sTxt = rng.text;
    } else {

        if (typeof rng.length == "undefined") {
            sTxt = rng.toString();
        }
    }

    // populate menu controls

    if (youtube != null) {
        if (sTxt != null && sTxt != "") {
            var re = new RegExp("http://(\.+)youtube.com/watch\?(\.+)");
            var m = re.exec(sTxt);
            if (m == null || sTxt.toLowerCase().indexOf("[youtube]") >= 0) {
                youtube.value = sDefault;
            } else {
                youtube.value = sTxt;
            }
        } else {
            youtube.value = sDefault;
        }
    }

}

// ----------------------------------------------
// Insert Link Menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildInsertLinkMenu = function(id, cmd) {

    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';       

    // populate color picker
    div.innerHTML = this.buildInsertLinkTable(id, cmd);

    return div;

}

InstantASPRichTextBox.prototype.buildInsertLinkTable = function(id, cmd) {

    var txtid = "txtInsertLinkText" + id;
    var lnkid = "txtInsertLinkURL" + id;
    var emailid = "txtInsertLinkEmail" + id;
    var butid = "butInsertLink" + id;

    var lnk1 = "lnk1" + id + cmd;
    var lnk2 = "lnk2" + id + cmd;
    var pnl1 = "pnl1" + id + cmd;
    var pnl2 = "pnl2" + id + cmd;    
    
    var lnkDefaultVal = this.getInstance(id).txtHttpDefaultVal;    
    var onkeydown = "return catchKeyDown('" + butid + "', event)"
    var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','')\;";
    var onrowclick = "InstantASPRichTextBox.prototype.toggleMenuOptions('" + id + "', '" + cmd + "');"
    var closeonclick = "InstantASPRichTextBox.prototype.hideModalMenu('" + id + "', '" + cmd + "');"
      
    var s = "";        
    s += "<table cellspacing=\"1\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"PanelBar_SubHeader\">";
    s += "<div style=\"float: left; width: 50%;\">";
    s += "<span>Edit Link</span>";
    s += "</div>";
    s += "<div style=\"float: right; text-align: left; width: 49%;\">";
    s += "<a href=\"javascript:void(0);\" onclick=\"" + closeonclick + "\">";
    s += "<img src=\"" + this.getInstance(id).ImgFolder + "Misc_CloseWindow.gif\" align=\"right\" />";
    s += "</a>";
    s += "</div>";
    s += "</td></tr>";

    s += "<tr id=\"trText_" + id + "\" style=\"display: inline;\">";
    s += "<td class=\"TableCell_Light\">";
    s += "<div class=\"SmallTxtBold\" style=\"float: left; padding-right: 9px;\">";
    s += "Text to Display:";
    s += "</div>";
    s += "<div style=\"float: left; width: 70%;\">";
    s += "<input id=\"" + txtid + "\" type=\"text\" tabindex=\"100\" onkeydown=\"" + onkeydown + "\" value=\"\" class=\"FormInputText\" style=\"width: 97%\" />";
    s += "</div>";
    
    s += "</td>"
    s += "</tr>"

    s += "<tr><td class=\"TableCell_Light\">";

    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr>";
    s += "<td class=\"rtb_MenuOptLnkSel\" id=\"" + lnk1 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Web Address:";
    s += "</a>";
    s += "</td>";
    s += "<td rowspan=\"3\" class=\"rtb_MenuOptContainer\" valign=\"top\">";

    // web address

    s += "<div  id=\"" + pnl1 + "\" style=\"height: 100px;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "To which URL should this link go?<br/><br/>"
    s += "<input id=\"" + lnkid + "\" type=\"text\" onkeydown=\"" + onkeydown + "\" tabindex=\"101\" style=\"width: 99%;\" value=\"" + lnkDefaultVal + "\" class=\"FormInputText\" style=\"width: 97%\" />";
    s += "</td>";
    s += "</tr>";
    s += "</table>";        
    s += "</div>";

    // email address

    s += "<div  id=\"" + pnl2 + "\" style=\"display: none; height: 100px;\" class=\"rtb_MenuOptPnl\">";
    s += "<table cellspacing=\"0\" cellpadding=\"9\" width=\"100%\">";
    s += "<tr><td class=\"SmallTxtBold\">";
    s += "To which email address should this link go?<br/><br/>"
    s += "<input id=\"" + emailid + "\" type=\"text\" onkeydown=\"" + onkeydown + "\" tabindex=\"102\" style=\"width: 99%;\" value=\"\" class=\"FormInputText\" style=\"width: 97%\" />";
    s += "</td>";
    s += "</tr>";
    s += "</table>";
    s += "</div>";
        
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxtBold\" id=\"" + lnk2 + "\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + onrowclick + "\" class=\"SmallTxtBold\">";
    s += "Email Address:";
    s += "</a>";
    s += "</td>";
    s += "</tr>";
    s += "<tr>";
    s += "<td class=\"SmallTxt\">";
    s += "&nbsp;";
    s += "</td>";
    s += "</tr>";

    s += "</table>";

    s += "</td></tr>";
    s += "<tr><td class=\"TableCell_Light\" align=\"right\">";
    s += "<button id=\"" + butid + "\" class=\"FormButtonBig\" onclick=\"" + onclick + "\">Add Link</button>";
    s += "</td></tr>"
    s += "</table>";

    return s;

}

InstantASPRichTextBox.prototype.initInsertLinkTable = function(id) {

    // local vars
    var sDefault = this.getInstance(id).txtHttpDefaultVal;

    // setup focus to editor
    this.getEditorWindow(id).focus();

    // local link variables
    var txt = this.getInsertLinkText(id);
    var lnk = this.getInsertLinkURL(id);
    var email = this.getInsertLinkEmail(id);
    var trText = iasp_FindControl("trText_" + id)


    // get current selection
    var sel = this.getSelection(id);
    var rng = this.getRange(sel);

    // add range to internal variable
    if (rng != null) {
        this.getInstance(id).tempRng = rng;
    }

    // do we have an image selected?
    var img = this.findParent("IMG", rng);
    if (img != null) {
        trText.style.display = "none";
    } else {
        trText.style.display = "";
    }

    // local variables

    var sTxt = null;
    var sLnk = null;
    var sEmail = null;
    var a = this.findParent("A", rng);
    if (a != null) {
        if (a.href.toLowerCase().indexOf("mailto:") >= 0) {
            sEmail = a.href.toLowerCase().replace("mailto:", "");
        } else {
            sLnk = a.href;
        }
        sTxt = a.innerText;
    } else {
        // check for chrome
        if (typeof rng.text != 'undefined') {
            sTxt = rng.text;
        } else {

            if (typeof rng.length == "undefined") {
                sTxt = rng.toString();
            }
        }
    }

    // populate menu controls

    if (txt != null) {
        if (sTxt != null) {
            txt.value = sTxt;
        } else {
            txt.value = "";
        }
    }

    if (lnk != null) {
        if (sLnk != null) {
            lnk.value = sLnk;
        } else {
            lnk.value = sDefault;
        }
    }

    if (email != null) {
        if (sEmail != null) {
            email.value = sEmail;
        } else {
            email.value = "";
        }
    }

}

InstantASPRichTextBox.prototype.addLink = function(id, cmd) {

    // hide menu as it's a modal popup
    this.hideModalMenu(id, cmd);

    // local string varaibles
    var sTxt = "";
    var sURL = "";
    var sEmail = '';
    var sDefault = this.getInstance(id).txtHttpDefaultVal;

    // get controls
    var txr = this.getInsertLinkText(id);
    var lnk = this.getInsertLinkURL(id);
    var email = this.getInsertLinkEmail(id);
    
    // add menu values to local vars
    if (txr != null && lnk != null && email != null) {
        sTxt = txr.value;
        if (email.value.indexOf("@") > -1 || email.value.indexOf(".") > -1) {
            sURL = "mailto:" + email.value;
        } else {
            sURL = lnk.value;
        }
    }

    // get range
    var doc = this.getEditorWindow(id).document;
    var sel = this.getSelection(id)
    var rng = this.getRange(sel);

    // use temp range if available
    if (this.getInstance(id).tempRng != null) {
        rng = this.getInstance(id).tempRng;
    }

    // locate link, if not available create one
    var a = this.findParent("A", rng);
    var update = (a == null) ? false : true;
    if (!update) {
        // if we don't have a link return
        if (sURL == "" || sURL == sDefault) {
            if (sTxt != "") {
                rng.pasteHTML(sTxt);
            }
            return;
        } else {
            // create link
            a = doc.createElement("a");
        }
    } else {
        // remove link if we don't have a URL
        if (sURL == "" || sURL == sDefault) {
            var img = this.findParent("IMG", rng);
            if (img != null) {
                this.removeNode(id);
                this.insertNodeAtSelection(img, id);
                return;        
            } else {
                this.removeNode(id);
            }
        }
    }

    // we have a URL, set the attributes
    this.getInstance(id).commonUI.setAttribute(a, "href", sURL);


    // Check if IE or Mozilla (other)
    if (iasp_IsIE) {

        // if we have text use that
        if (sTxt != "") {
            a.innerHTML = sTxt;
        } else {

            // do we have an image selected?
            var img = this.findParent("IMG", rng);
            if (img != null) {
                a.innerHTML = img.outerHTML;
            } else {
                // if we don't ahve text use URL
                if (sURL != sDefault) { sTxt = sURL; }
                if (sTxt == "") { sTxt = sEmail; }
                if (sTxt != "") {
                    a.innerHTML = sTxt;
                } else {
                    rng.select();
                    a.innerHTML = rng.htmlText;
                }
            }

        }
        // on update exit here
        if (update) { return; }

        // check if selection is a controlrange
        if (typeof rng.length == "undefined") {
            rng.pasteHTML(a.outerHTML);
        } else {
            if (rng.length == 1) {
                rng = this.getTextRange(rng(0));
                if (rng != null) {
                    rng.select();
                    rng.pasteHTML(a.outerHTML);
                }
            } else {
                rng.pasteHTML(a.outerHTML);
            }

        }

    } else {

        var node = rng.startContainer;
        var pos = rng.startOffset;
        if (node.nodeType != 3) { node = node.childNodes[pos]; }

        if (node.tagName != null && node.tagName != "BR") {

            a.appendChild(node);

        } else {

            if (sTxt != "") {
                a.innerHTML = sTxt;
            } else {
                a.innerHTML = sel;
            }

        }

        this.insertNodeAtSelection(a, id);

    }

}

// ----------------------------------------------
// IF Codes menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildIFCodeMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildIFCodesTable(id, cmd);
    
    return div;
    
}

InstantASPRichTextBox.prototype.buildIFCodesTable = function(id, cmd) {

    var imgfolder = this.getInstance(id).ImgFolder;
    var ifcodes = this.getInstance(id).IFCodes;
    var cols = 1
          
    var s = "";
    s += "<table cellspacing=\"4\" cellpadding=\"0\" width=\"100%\">";
    
    for (i = 0; i < ifcodes.length; i++) {
    
        if (i % cols == 0) {
            s += "<tr>";
        }

        // update color preview event
        var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','" + escape(ifcodes[i].Tag) + "')\;";
        var onmouseover = "this.className = 'rtb_DropDownMnuButOver';"; 
        var onmouseout = "this.className = 'rtb_DropDownMnuBut';";

        s += "<td>";        
        s += "<button type=\"button\" onclick=\"" + onclick + "\" onmouseover=\"" + onmouseover + "\" onmouseout=\"" + onmouseout + "\" onclick=\"" + onclick + "\" class=\"rtb_DropDownMnuBut\" style=\"width: 100%;\">";
        s += ifcodes[i].Desc;
        s += "</button></td>";
        
        if (i % cols == cols - 1) {
            s += "</tr>";
        }
        
    }

    if (i % cols != 0) {
        s += "</tr>";
    }
    
    s += "</table>";

    return s;

}

// ----------------------------------------------
// Color Pickers
// ----------------------------------------------

InstantASPRichTextBox.prototype.buildColorPickerMenu = function(id, cmd) {
    
    // build color picker
    var div = document.createElement('div');
    div.id = id + cmd;
    div.style.display = 'none';
    
    // populate color picker
    div.innerHTML = this.buildColorTable(id, cmd);
    
    return div;
    
}

InstantASPRichTextBox.prototype.buildColorTable = function(id, cmd) {

    var colors = this.getInstance(id).colorsArray;
    var cols = this.getInstance(id).colorsPerLine;
     
    var s = "";
    s += "<table cellspacing=\"5\" cellpadding=\"0\" width=\"100%\">";
    
    s += "<tr><td class=\"rtb_ColorPickerPreviewBox\" ";
    s += "colspan=\"" + cols + "\">";
    s += "<div id=\"cpPreview_" + id + "_" + cmd + "\">&nbsp;";
    s += "</div>";
    s += "</td></tr>";

    for (i = 0; i < colors.length; i++) {
    
        if (i % cols == 0) {
            s += "<tr>";
        }

        // update color preview event
        
        var onclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','" + colors[i] + "')\;";
        var onmouseover = "InstantASPRichTextBox.prototype.updateColorPreview('" + id + "', '" + cmd + "', '" + colors[i] + "');";
        
        s += "<td><a class=\"rtb_ColorPickerColorBox\" style=\"color: "
        s += colors[i] + "; background-color: " + colors[i] + ";\" title=\""
        s += colors[i] + "\" href=\"javascript: void(0);\" onmouseover=\"" + onmouseover + "\" onclick=\"" + onclick + "\">";
        s += "&nbsp;</a></td>";
        
        if (i % cols == cols - 1) {
            s += "</tr>";
        }
        
    }

    if (i % cols != 0) {
        s += "</tr>";
    }
    
    // show more colors?
    if (iasp_IsIE) {    
        var moreonclick = "InstantASPRichTextBox.prototype.showMoreColors('" + id + "','" + cmd + "')\;";
        s += "<tr><td colspan=\"" + cols + "\">";
        s += "<span class=\"rtb_ColorPickerLinks\">"
        s += "<a href=\"javascript: void(0)\" onclick=\"" + moreonclick + "\">More Colors...</a>";
        s += "</span>";
        s += "</td></tr>";
    }
    
    var clearcoloronclick = "InstantASPRichTextBox.prototype.execCommand('" + id + "','" + cmd + "','')\;";
     
    s += "<tr><td colspan=\"" + cols + "\">";
    s += "<span class=\"rtb_ColorPickerLinks\">";
    s += "<a href=\"javascript: void(0);\" onclick=\"" + clearcoloronclick + "\">Clear Color</a>";
    s += "</span>";
    s += "</td></tr>";
    s += "</table>";

    return s;

}

// show the IE specific color picker dialog

InstantASPRichTextBox.prototype.showMoreColors = function(id, cmd) {

    var dlgColors = iasp_FindControl('dlgColors').ChooseColorDlg();
    var color = dlgColors.toString(16);

    if (dlgColors.length < 6) {
        var sTmp = "000000".substring(0,6-color.length)
        color = "#" + sTmp.concat(color);
    }
    
    // ensure we have a valid color
    if (color != 0) {
        this.execCommand(id, cmd, color);
    }

}


InstantASPRichTextBox.prototype.updateColorPreview = function(id, cmd, strHexVal) {

    var div = this.getColorPickerPreview(id, cmd);

    if (div != null) {
        div.style.background = strHexVal;
        div.innerHTML = strHexVal;
    }
}

InstantASPRichTextBox.prototype.addColor = function(r, g, b) {

    var red = this.colorLevels[r];
    var green = this.colorLevels[g];
    var blue = this.colorLevels[b];
    this.addColorValue(red, green, blue);

}

InstantASPRichTextBox.prototype.addColorValue = function(r, g, b) {

    this.colorsArray[this.colorsArray.length] = '#' + r + r + g + g + b + b;
    
}

InstantASPRichTextBox.prototype.genColorsArray = function() {

    this.addColorValue('F','E','F');
    this.addColorValue('F','F','0');
    this.addColorValue('0','F','0');
    this.addColorValue('A','D','E');
    this.addColorValue('0','8','0');
    this.addColorValue('8','8','8');
    this.addColorValue('F','D','0');
    this.addColorValue('F','E','E');
    this.addColorValue('0','F','F');
    this.addColorValue('8','C','E');
    this.addColorValue('0','0','F');
    this.addColorValue('A','A','A');
    this.addColorValue('F','A','0');
    this.addColorValue('F','C','C');
    this.addColorValue('A','2','2');
    this.addColorValue('0','8','8');
    this.addColorValue('0','0','8');
    this.addColorValue('C','C','C');
    this.addColorValue('F','0','0');
    this.addColorValue('C','1','8');
    this.addColorValue('8','8','0');
    this.addColorValue('4','0','8');
    this.addColorValue('0','0','0');
    this.addColorValue('8','0','8');
    this.addColorValue('5','F','5');

}

InstantASPRichTextBox.prototype.toggleMenuOptions = function(id, cmd) {

    var lnk1 = iasp_FindControl("lnk1" + id + cmd);
    var lnk2 = iasp_FindControl("lnk2" + id + cmd);
    var pnl1 = iasp_FindControl("pnl1" + id + cmd);
    var pnl2 = iasp_FindControl("pnl2" + id + cmd);

    if (lnk1 != null && lnk2 != null) {
        if (lnk1.className == "rtb_MenuOptLnkSel") {
            lnk1.className = "SmallTxtBold";
            lnk2.className = "rtb_MenuOptLnkSel";
            if (pnl1 != null && pnl2 != null) {
                pnl1.style.display = "none";
                pnl2.style.display = "";

            }
        } else {
            lnk1.className = "rtb_MenuOptLnkSel";
            lnk2.className = "SmallTxtBold";
            if (pnl1 != null && pnl2 != null) {
                pnl1.style.display = "";
                pnl2.style.display = "none";
            }
        }
    }

}

// ----------------------------------------------
// context menu
// ----------------------------------------------

InstantASPRichTextBox.prototype.setImageCtxMenu = function(ctx) {
    ctx.container = this; 
    this.ImageContextMenu = ctx;
}

InstantASPRichTextBox.prototype.contextMenu = function (id, e) {

    var ctx = null;
    var sel = this.getSelection(id)
    var rng = this.getRange(sel);

    if (rng != null) {
        if (typeof sel.type != 'undefined') {
             
            switch (sel.type.toLowerCase()) {

                case "none":

                    return true;

                case "text":

                    return true;

                case "control":

                    if (this.findParent("IMG", rng) != null) {
                        ctx = this.getInstance(id).ImageContextMenu;
                    }
                    break;

            }
        }
    }

    if (!ctx) { return true; }
    ctx.showMenu(0, 0, e);
    return false;

}

InstantASPRichTextBox.prototype.ctxMnuImgClick = function(container, sNode, mId, itemID) {

    var rtb = container.getInstance(container.id)
    rtb.getEditorWindow(container.id).focus();
    
    var sel = rtb.getSelection(rtb.id);
    var rng = rtb.getRange(sel);
    var img = rtb.findParent("IMG", rng);

    if (img != null) {

        var sAlign = null;
        switch (itemID.toString()) {

            case "1":
                sAlign = "left";
                break;
            case "2":
                sAlign = "center";
                break;
            case "3":
                sAlign = "right";
                break;
            case "4":
                sAlign = null;
                break;
        }

        if (sAlign != null) {
            container.commonUI.setAttribute(img, "align", sAlign);
        } else {
            img.removeAttribute("align");
        }

    }
    
    return false;

}

InstantASPRichTextBox.prototype.getSelection = function (id) {

    var ifrm = this.getEditorWindow(id);
    var doc = ifrm.document;
    var sel = null;

    if (iasp_IsIE) {

        if (typeof doc.selection != "undefined") {
            if (doc.selection) {
                sel = doc.selection;
            }
        }

    } else {

        if (typeof ifrm.getSelection != "undefined") {
            if (ifrm.getSelection) {
                sel = ifrm.getSelection();
            }
        }
        if (typeof doc.getSelection != "undefined") {
            if (doc.getSelection && sel == null) {
                sel = doc.getSelection();
            }
        }
    }

    return sel;

}

InstantASPRichTextBox.prototype.getRange = function (s) {

		return s.createRange ? s.createRange() : s.getRangeAt(0);
}

InstantASPRichTextBox.prototype.getTextRange = function(ele) {

    var rng = null
    if (ele.parentTextEdit != null) {
        rng = ele.parentTextEdit.createTextRange();
      rng.moveToElementText(ele);
        return rng;
    }
    return null;

},

InstantASPRichTextBox.prototype.findParent = function(parentTagName, range) {

    parentTagName = parentTagName.toUpperCase();
    var rangeWorking;
    var elmWorking = null;
    try {
        if (!iasp_IsIE) {
            var node = range.startContainer;
            var pos = range.startOffset;
            if (node.nodeType != 3) { node = node.childNodes[pos]; }
            return this.findParentNode(parentTagName, node);
        }
        else {
            elmWorking = (range.length > 0) ? range.item(0) : range.parentElement();
            elmWorking = this.findParentNode(parentTagName, elmWorking);
            if (elmWorking != null) return elmWorking;
            rangeWorking = range.duplicate();
            rangeWorking.collapse(true);
            rangeWorking.moveEnd("character", 1);
            if (rangeWorking.text.length > 0) {
                while (rangeWorking.compareEndPoints("EndToEnd", range) < 0) {
                    rangeWorking.move("Character");
                    if (null != this.findParentTag(parentTagName, rangeWorking)) {
                        return this.findParentTag(parentTagName, rangeWorking);
                    }
                }
            }
            return null;
        }
    }
    catch (e) {
        return null;
    }
}

InstantASPRichTextBox.prototype.findParentNode = function(tagName, node) {

	while (node.tagName != "HTML") {
  		if (node.tagName == tagName){
  			return node;
  		} 
  		node = node.parentNode;
 	}
 	return null;
 	
}

InstantASPRichTextBox.prototype.removeNode = function(id) {

	// get selection and range
    var sel = this.getSelection(id);
	var range = this.getRange(sel);

	// use temp range if available
	if (this.getInstance(id).tempRng != null) {
	    range = this.getInstance(id).tempRng;
	}
	
	// the current tag of range
	var tag = this.getTag(range);
	var parent = tag.parentNode;
	
	if(tag == null || parent == null) { return; }
	if(tag.nodeName == "HTML" || tag.nodeName == "BODY") { return; }

	// copy child elements of the node to the parent element before remove the node
	var childNodes = new Array();
	for(var i=0; i < tag.childNodes.length;i++)
		childNodes[i] = tag.childNodes[i];	
	for(var i=0; i < childNodes.length;i++)
		parent.insertBefore(childNodes[i], tag);	
	
	// remove node
	parent.removeChild(tag);
	
	// validate if parent is a link and the node is only 
	// surrounded by the link, then remove the link too
	if(parent.nodeName == "A" && !parent.hasChildNodes()) {
		if(parent.parentNode) { parent.parentNode.removeChild(parent); }
	}

}

// get the tag for the current range
InstantASPRichTextBox.prototype.getTag = function(range) {

	try {
	    if(!iasp_IsIE) {
			var node = range.startContainer;	
			var pos = range.startOffset;
			if(node.nodeType != 3) { node = node.childNodes[pos]; }
			
			if(node.nodeName && node.nodeName.search(/#/) != -1) {
				return node.parentNode;
			}
			return node;
		}
		else {
			if(range.length > 0) {
				return range.item(0);
			}
			else if(range.parentElement()) {
				return range.parentElement();
			}
		}
		return null;
	}
	catch(e) {
		return null;
	}
	
}
	
// ----------------------------------------------
// execCommand
// ----------------------------------------------

InstantASPRichTextBox.prototype.execCommand = function(id, cmd, value) {

    // are we in design mode?
    if (!this.getInstance(id).DesignMode) { alert(iasp_WYSIWYGPrompt); return; }

    // When user clicks toolbar button make sure it always targets its respective WYSIWYG
   this.getEditorWindow(id).focus();

    // switch command
    switch (cmd) {

        case "FormatBlock":

            this.execCommandInternal(id, cmd, "<" + value + ">");
            break;

        case "ForeColor":

            this.execCommandInternal(id, cmd, value);
            break;

        case "BackColor":

            this.execCommandInternal(id, cmd, value);
            break;

        case "InsertImage":

            this.addImage(id, cmd, value);
            break;


        case "RemoveImage":

            this.removeImage(id);
            break;

        case "RemoveFormat":

            this.removeFormat(id);
            break;
            
        case "EmotIcon":

            this.addCode(id, value, "", "");
            break;

        case "IFCode":

            var chr = "]"
            var val = unescape(value)
            var arr = val.split(chr);

            if (arr.length > -1) {
                var starttag = arr[0] + chr;
                var endtag = arr[1] + chr;
                this.addCode(id, starttag, "", endtag);
            } else {
                this.addCode(id, val, "", "");
            }
            break;

        case "Quote":

            this.addCode(id, "[quote]", "", "[/quote]");
            break;

        case "YouTube":

            // hide menu as it's a modal popup
            this.hideModalMenu(id, cmd);

            // vakye gikds the textbox id for youtube
            var defaultVal = this.getInstance(id).txtYouTubeDefaultVal;
            var t = this.getYouTubeTextBox(id);
            if (t != null) {
                var val = t.value;
                if (val != null && val != defaultVal && val != "") {

                    var re = new RegExp("http://(\.+)youtube.com/watch\?(\.+)");
                    var m = re.exec(val);
                    if (m == null) {
                        alert("Please provide the URL tothe web page containing the YouTube video. For example...\n\nhttp://www.youtube.com/watch?v=l9Ly9jxzZac");
                    } else {
                        this.addCode(id, "[YouTube]", val, "[/YouTube]");
                    }


                    
                }
            }



            break;

        case "InsertLink":

            this.addLink(id, cmd);
            break;

        case "SpellCheck":

            var txt = this.getEditorWindow(id).document.body.innerText;

            var spellid = this.getInstance(id).SpellCheckClientID;
            var spell = GetRadSpell(spellid);
            spell.SetTextSource(new this.spellSource(id))
            spell.StartSpellCheck();

            break;

        case "ViewText":

            this.viewText(n);
            break;

        // Strip any HTML added by word   

        case "RemoveFormat":

            this.removeFormat(id);

            break;

        // Preview thx to Korvo   
        case "Preview":

            //window.open(this.config[n].PopupsDir + 'preview.html?wysiwyg=' + n,'popup', 'location=0,status=0,scrollbars=1,resizable=1,width=' + this.config[n].PreviewWidth + ',height=' + this.config[n].PreviewHeight + ',top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
            break;

        // Print   
        case "Print":

            this.print(n);
            break;


        // Return   
        case "Return":
            location.replace(this.config[n].Opener);
            break;

        default:
            this.execCommandInternal(id, cmd, value);

    }

    // hide any drop down menus
    iasp_HideAllMenus();

    // reanble form
    enableFormSubmit();
    
}

InstantASPRichTextBox.prototype.spellSource = function(id) {

    var bdy = InstantASPRichTextBox.prototype.getEditorWindow(id).document.body;
    
    this.GetText = function() {return bdy.innerHTML;} 
    this.SetText = function(text) {bdy.innerHTML = text;}

}

// internal execCommand

InstantASPRichTextBox.prototype.execCommandInternal = function(id, cmd, value) {

    if(typeof(value) == "undefined") value = null;

    // firefox BackColor problem fixed
    if(cmd == 'BackColor' && !iasp_IsIE) cmd = 'HiliteColor';

    // firefox cut, paste and copy
    if(iasp_IsIE && (cmd == "Cut" || cmd == "Paste" || cmd == "Copy")) {
	    try {
		    this.getEditorWindow(id).document.execCommand(cmd, false, value);
	    }
	    catch(e) {
		    if(confirm("Copy/Cut/Paste is not available in Mozilla and Firefox\nDo you want more information about this issue?")) {
			    window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html');
		    }
	    }
    }

    else {
	    this.getEditorWindow(id).document.execCommand(cmd, false, value);
    }


}

// add code method

InstantASPRichTextBox.prototype.addCode = function(id, startTag, middleTag, endTag) {

    var txt = this.getEditorWindow(id);

    // textrange
    var s = this.getSelection(id);
    var r = this.getRange(s);

    if (iasp_IsIE) {

        var output;

        if (s.type == "Text" || s.type == "None" || typeof s.type == 'undefined') {
            r.colapse;
            if (r.text.length > 0) {
                output = startTag + r.text + endTag;
            } else {
                output = startTag + middleTag + endTag;
            }

            if (r.parentElement().isMultiLine && r.parentElement().isContentEditable || txt.type == "textarea") {
                r.text = output;
              //  r.moveEnd("character", -(endTag.length));
                r.select();
            }
        }

    } else  {

         //  var s = txt.getSelection();
        var spanTxt = null;
        if (s.toString().length > 0) {
            spanTxt = startTag + s + endTag;
        } else {
            spanTxt = startTag + middleTag + endTag;
        }

        var span = document.createElement("span");
        span.appendChild(document.createTextNode(spanTxt));
        this.insertNodeAtSelection(span, id);

    } 

}

InstantASPRichTextBox.prototype.insertNodeAtSelection = function (insertNode, id) {

    // get editor document
    var doc = this.getEditorWindow(id).document;

    // get current selection
    var sel = this.getSelection(id);

    // get the first range of the selection
    // (there's almost always only one range)
    var range = sel.getRangeAt(0);

    // deselect everything
    sel.removeAllRanges();

    // remove content of current selection from document
    range.deleteContents();

    // get location of current selection
    var container = range.startContainer;
    var pos = range.startOffset;

    // make a new range for the new selection
    range = doc.createRange();


    if (container.nodeType == 3 && insertNode.nodeType == 3) {

        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.data);
        // put cursor after inserted text
        range.setEnd(container, pos + insertNode.length);
        range.setStart(container, pos + insertNode.length);
    }
    else {

        var afterNode;
        var beforeNode;

        if (container.nodeType == 3) {
            // when inserting into a textnode
            // we create 2 new textnodes
            // and put the insertNode in between
            var textNode = container;
            container = textNode.parentNode;
            var text = textNode.nodeValue;

            // text before the split
            var textBefore = text.substr(0, pos);
            // text after the split
            var textAfter = text.substr(pos);

            beforeNode = document.createTextNode(textBefore);
            afterNode = document.createTextNode(textAfter);

            // insert the 3 new nodes before the old one
            container.insertBefore(afterNode, textNode);
            container.insertBefore(insertNode, afterNode);
            container.insertBefore(beforeNode, insertNode);

            // remove the old node
            container.removeChild(textNode);
        }
        else {

            // else simply insert the node
            try {
                afterNode = container.childNodes[pos];
                container.insertBefore(insertNode, afterNode);
            }
            catch (e) {
                //alert(e);
            }

        }

        try {
            range.setEnd(afterNode, 0);
            range.setStart(afterNode, 0);
        }
        catch (e) {
            //alert(e);
        }
    }

    sel.addRange(range);

}

// ----------------------------------------------
// editor resize code
// ----------------------------------------------

InstantASPRichTextBox.prototype.getDivPosition = function(id, event) {

    if (this.getResizeBar(id) == null) { return; }
    
    // update class
    this.getResizeBar(id).className = "rtb_ResizeBarOver"

    //for handling events in ie vs. w3c 
    curevent = (typeof event == 'undefined' ? e : event)

    //sets mouse flag as down 
    this.getInstance(id).resizing = true;

    //gets position of click 
    this.getInstance(id).curPos = curevent.clientY

    //accepts height of the div
    tempHeight = this.getEditor(id).style.height;

    //these lines split the height value from the 'px' units 
    heightArray = tempHeight.split('p')

    // set current height
    this.getInstance(id).curHeight = parseInt(heightArray[0])

}

InstantASPRichTextBox.prototype.setDivPosition = function(id, event) {

    if (this.getInstance(id).resizing) {

        // get event
        curevent = (typeof event == 'undefined' ? e : event)

        //get new mouse position 
        this.getInstance(id).newPos = curevent.clientY

        //calculate movement in pixels 
        var pxMove = parseInt(this.getInstance(id).newPos - this.getInstance(id).curPos)

        //determine new height 
        var newHeight = parseInt(this.getInstance(id).curHeight + pxMove)

        // get default height
        var defaultHeight = this.getInstance(id).getHeight();

        //conditional to set minimum height to 5
        this.getInstance(id).newHeight = (newHeight < defaultHeight ? defaultHeight : newHeight);

        //set the new height of the div        
        this.getEditor(id).style.height = this.getInstance(id).newHeight + 'px'

    }

}

InstantASPRichTextBox.prototype.endDivPosition = function(id, mouse) {

    // disable resizing
    this.getInstance(id).resizing = false;

    // update resize bar css
    var bar = this.getResizeBar(id);
    if (bar != null) {
        bar.className = this.getInstance(id).EnableHTML ? "rtb_ResizeBar" : "rtb_ResizeBarNoBorder";
    }

}

// ----------------------------------------------
// toolbar helpers
// ----------------------------------------------

InstantASPRichTextBox.prototype.initMouseOvers = function(id) {

    var container = iasp_FindControl('toolbars' + id);
    if (container == null) { return; }
    var toolbars = container.getElementsByTagName("DIV");

    for (var i = 0; i < toolbars.length; i++) {

        var toolbar = toolbars[i];
        var buttons = toolbar.childNodes;

        for (j = 0; j < buttons.length; j++) {
            var button = buttons[j];

            if (button.className != null) {
                if (button.className.toLowerCase() == "rtb_button") {

                    button.onselectstart = function() { return (false); };
                    button.setAttribute('unselectable', 'on', 0);

                    button.onmouseover = function() { if (this.disabled != true) { this.className = "rtb_ButtonOver"; } };
                    button.onmouseout = function() { if (this.disabled != true) { this.className = "rtb_Button"; } };
                }
            }

        }
    }
}

InstantASPRichTextBox.prototype.diableToolbars = function(id) {

    var container = iasp_FindControl('toolbars' + id);
    if (container == null) { return; }
    var toolbars = container.getElementsByTagName("DIV");

    for (var i = 0; i < toolbars.length; i++) {

        var toolbar = toolbars[i];
        var buttons = toolbar.childNodes;

        toolbar.disabled = true;

        for (j = 0; j < buttons.length; j++) {
            var button = buttons[j];

            if (button.className != null) {
                if (button.className.toLowerCase().indexOf("rtb_") > -1) {
                
                    if (iasp_IsIE) {
                        button.style.filter = "alpha(opacity=40);"
                    } else {
                        // update button css for Mozilla
                        if (button.className.toLowerCase().indexOf("rtb_button") > -1) {
                            button.className = "rtb_ButtonDisabled";
                        }
                    }
                    button.disabled = true;
                }
            }

        }
    }
}


InstantASPRichTextBox.prototype.enableToolbars = function(id) {

    var container = iasp_FindControl('toolbars' + id);
    var toolbars = container.getElementsByTagName("DIV");

    for (var i = 0; i < toolbars.length; i++) {

        var toolbar = toolbars[i];
        var buttons = toolbar.childNodes;

        toolbar.disabled = false;

        if (!iasp_IsIE) {
            toolbar.style.display = "";
            container.style.height = "";
        }

        for (j = 0; j < buttons.length; j++) {
            var button = buttons[j];

            if (button.className != null) {
                if (button.className.toLowerCase().indexOf("rtb_") > -1) {

                    if (iasp_IsIE) {
                        button.style.filter = "alpha(opacity=100);"
                    } else {
                        // enable css Mozilla
                        if (button.className.toLowerCase().indexOf("rtb_button") > -1) {
                            button.className = "rtb_Button";
                        }
                    }

                    button.disabled = false;
                }
            }
        }
    }
}

// ----------------------------------------------
// helpers
// ----------------------------------------------

InstantASPRichTextBox.prototype.removeFormat = function(id) {

        if (!confirm(iasp_RemoveFormatting)) { return; }
		var doc = this.getEditorWindow(id).document;
		
		var s = doc.body.innerHTML;		
		s = s.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi, '');
	    s = s.replace(/<span[^>]*>/gi, '');
	    s = s.replace(/<\/span[^>]*>/gi, '');
	    s = s.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi, '');
	    s = s.replace(/<p[^>]*>/gi, '');
	    s = s.replace(/<\/p[^>]*>/gi, '');
	    s = s.replace(/<p>]*>/gi, '');
	    s = s.replace(/<\/p>/gi, '');
	    s = s.replace(/<h([^>])[0-9]>(&nbsp;)*\s*<\/h>/gi, '');
	    s = s.replace(/<h[^>][0-9]>/gi, '');
	    s = s.replace(/<\/h[^>][0-9]>/gi, ''); 
		s = s.replace (/<B [^>]*>/ig, '<b>');				
		s = s.replace (/<DIV[^>]*>/ig, '');
		s = s.replace (/<\/DIV>/gi, '');
		s = s.replace (/<[\/\w?]+:[^>]*>/ig, '');
		s = s.replace (/(&nbsp;){2,}/ig, '&nbsp;');
		s = s.replace (/<STRONG>/ig, '');
		s = s.replace(/<\/STRONG>/ig, '');
		s = s.replace (/<TT>/ig, '');
		s = s.replace (/<\/TT>/ig, '');
		s = s.replace (/<FONT [^>]*>/ig, '');
		s = s.replace (/<\/FONT>/ig, '');
		s = s.replace (/STYLE=\"[^\"]*\"/ig, '');
		s = s.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, '<$1$3');
  	    s = s.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, '<$1$3'); 
		s = s.replace(/width=([^ |>]*)([^>]*)/gi, '');
	    s = s.replace(/classname=([^ |>]*)([^>]*)/gi, '');
	    s = s.replace(/align=([^ |>]*)([^>]*)/gi, '');
	    s = s.replace(/valign=([^ |>]*)([^>]*)/gi, '');
	    s = s.replace(/<\\?\??xml[^>]>/gi, '');
	    s = s.replace(/<\/?\w+:[^>]*>/gi, '');
	    s = s.replace(/<st1:.*?>/gi, '');
	    s = s.replace(/o:/gi, ''); 
	    s = s.replace(/<!--([^>])*>(&nbsp;)*\s*<\/-->/gi, '');
   		s = s.replace(/<!--[^>]*>/gi, '');
   		s = s.replace(/<\/--[^>]*>/gi, '');
		
		doc.body.innerHTML = s;

},
	
InstantASPRichTextBox.prototype.disableIFrame = function(id) {

    var doc = this.getEditorWindow(id).document;

    // ensure content is editable
    if (doc.body.contentEditable) {
        doc.body.contentEditable = false;
    }
    else {
        doc.designMode = "off";
    }

}

InstantASPRichTextBox.prototype.enableIFrame = function(id) {

    var doc = this.getEditorWindow(id).document;

    // ensure content is editable
    if (doc.body.contentEditable) {
        doc.body.contentEditable = true;
    }
    else {
        doc.designMode = "on";
    }

}

InstantASPRichTextBox.prototype.invertIELineBreaks = function(id, e) {

    var editor = this.getEditorWindow(id);
    
    var evn = !e ? editor.event : e;
    if (evn == null || typeof evn == "undefined") { return false; }
    
    var kc = getKeyCode(evn);
    if (kc == null || typeof kc == "undefined") { return false; }
    
    if (kc == 13) {

        var sel = this.getRange(this.getSelection(id));

        if (!evn.shiftKey) {

            if (iasp_IsIE) {

                sel.pasteHTML("<br />");
                evn.returnValue = false;           
                sel.select();
                sel.moveEnd("character", 1);
                sel.moveStart("character", 1);
                sel.collapse(false);

            } else {

                if (!iasp_FireFox) {
                    this.insertHTML("<br />", id);
                }

            }

        } else {

            if (iasp_IsIE) {

                sel.pasteHTML("<br/><br/>");
                evn.returnValue = false;
                evn.cancelBubble = true;
                sel.select();
                sel.moveEnd("character", 1);
                sel.moveStart("character", 1);
                sel.collapse(false);

            } else {

                this.insertHTML("<br/>", id);

            }

        }
        
        evn.cancelBubble = true;
        return false;
   
    }

}

InstantASPRichTextBox.prototype.insertHTML = function(html, id) {			
	if (iasp_IsIE) {
	    this.getEditorWindow(id).document.selection.createRange().pasteHTML(html);   
	} 
	else {
	    var div = this.getEditorWindow(id).document.createElement("div");
	    div.style.display = "inline";
	    div.innerHTML = html;
		this.insertNodeAtSelection(div, id);		
	}
},
	
// ----------------------------------------------
// find controls
// ----------------------------------------------

InstantASPRichTextBox.prototype.getContainer = function(id) {
    return iasp_FindControl("container" + id);
}

InstantASPRichTextBox.prototype.getEditor = function(id) {
    return iasp_FindControl("iframe" + id);
    
}

InstantASPRichTextBox.prototype.getEditorWindow = function(id) {

    var editor = this.getEditor(id);
    if (editor != null) {
        return this.getEditor(id).contentWindow;
    }
    return null;
}

InstantASPRichTextBox.prototype.getColorPickerPreview = function(id, cmd) {
    return iasp_FindControl("cpPreview_" + id + "_" + cmd);
}

InstantASPRichTextBox.prototype.getYouTubeTextBox = function(id) {
    return iasp_FindControl('txtYouTube' + id);
}

InstantASPRichTextBox.prototype.getInsertLinkText = function(id) {
return iasp_FindControl('txtInsertLinkText' + id);
}

InstantASPRichTextBox.prototype.getInsertLinkURL = function(id) {
    return iasp_FindControl('txtInsertLinkURL' + id);
}

InstantASPRichTextBox.prototype.getInsertLinkEmail = function(id) {
    return iasp_FindControl('txtInsertLinkEmail' + id);
}

InstantASPRichTextBox.prototype.getInsertLinkEmail = function(id) {
    return iasp_FindControl('txtInsertLinkEmail' + id);
}

InstantASPRichTextBox.prototype.getInsertImageURL = function(id) {
    return iasp_FindControl('txtInsertImageURL' + id);
}

InstantASPRichTextBox.prototype.getMenu = function(id, cmd) {
    return iasp_FindControl(id + cmd + "_smMenu");
}

InstantASPRichTextBox.prototype.getAttachmentsPanel = function(id) {
    return iasp_FindControl('attachments' + id);
}

InstantASPRichTextBox.prototype.getAttachmentsText = function(id) {
    return iasp_FindControl('attachmentstext' + id);
}

InstantASPRichTextBox.prototype.getResizeBar = function(id) {
    return iasp_FindControl("resizeBar" + id);
}

InstantASPRichTextBox.prototype.getDesignButton = function(id) {
    return iasp_FindControl("switchDesign" + id);
}

InstantASPRichTextBox.prototype.getHTMLButton = function(id) {
    return iasp_FindControl("switchHTML" + id);
}

InstantASPRichTextBox.prototype.getAttachmentUploadIframe = function(id) {
    return iasp_FindControl("insertattachmentiframe" + id);
}

InstantASPRichTextBox.prototype.getInstance = function(id) {

    if (instantasprichtextbox[id]!=null) {
        return instantasprichtextbox[id];
    } else {
        alert("Could not find an instance of the editor!")
    }
    
}

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement) {

	HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
	  switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this);
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) { 
				this.parentNode.insertBefore(parsedNode,this.nextSibling); 
			}
			else { 
				this.parentNode.appendChild(parsedNode); 
			}
			break;
	  }
	};

	HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML);
	};


	HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
		var parsedText = document.createTextNode(txtStr);
		this.insertAdjacentElement(where,parsedText);
	};
}






