

// Ramius editor
var RamiusRTE = {
		iframe_css: '',
		iframe_html: function(){
			var html = '<html><head><title>{TITLE}</title>';
			if( this.iframe_css.length > 0 ){
				html += '<link rel="stylesheet" type="text/css" media="all" href="'+this.iframe_css+'" />';
			}
			
			 html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'
			 + '<style>{HIDDEN_CSS}</style><style>{EXTRA_CSS}</style></head>'
			 + '<body onload="document.body._rteLoaded = true;">{CONTENT}</body></html>';
			 return html;
		},
		blank_img: '',
		defaultConfig: {
			height: '300px',
			width: '830px',
			collapse: false,
			ptags: false,
			animate: true,
			dompath: false,
			focusAtStart: false,
			filterWord: true,
			autoHeight: false,
			grouplabels: false,
		    toolbar: {
		        titlebar: false,
				buttons: [				      
			          { group: 'firstrow', label: 'Tools',
			              buttons: [
			                    { type: 'push', label: 'Bold CTRL + B', value: 'bold' },
			                  	{ type: 'push', label: 'Italic CTRL + I', value: 'italic' },
			                  	{ type: 'push', label: 'Underline CTRL + U', value: 'underline' },
			                  	{ type: 'push', label: 'Strike Through', value: 'strikethrough' },
			                  	{ type: 'separator' },
			                  	{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
			                  	{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
			                  	{ type: 'separator' },
			                  	{ type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' }, 
			          			{ type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' }, 
			          			{ type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' }, 
			          			{ type: 'push', label: 'Justify', value: 'justifyfull' },
			          			{ type: 'separator' },
			          			{ type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
				                { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' },
				                { type: 'separator' },
				                { type: 'push', label: 'Indent', value: 'indent' },
				                { type: 'push', label: 'Outdent', value: 'outdent' },
				                { type: 'separator' },
				                { type: 'push', label: 'Remove Formatting', value: 'removeformat' },
				                { type: 'push', label: 'Show Hidden Elements', value: 'hiddenelements' },
				                { type: 'separator' },
				                { type: 'push', label: 'Edit HTML Code', value: 'editcode' },
				                { type: 'push', label: 'Fullscreen', value: 'fullmode' }
			              ]
			          },     
			          { group: 'secondrow', label: 'Tools',
			              buttons: [ 
								{ type: 'select', label: 'Default Font', value: 'fontname', disabled: true,
								    menu: [
								        { text: 'Arial', checked: true },
								        { text: 'Arial Black' },
								        { text: 'Comic Sans MS' },
								        { text: 'Courier New' },
								        { text: 'Lucida Console' },
								        { text: 'Tahoma' },
								        { text: 'Times New Roman' },
								        { text: 'Trebuchet MS' },
								        { text: 'Verdana' }
								    ]
								},
								{ type: 'separator' },
								{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true },
								{ type: 'separator' },
								{ type: 'select', label: 'Normal', value: 'heading', disabled: true,
					                  menu: [
					                      { text: 'Normal', value: 'none', checked: true },
					                      { text: 'Header 1', value: 'h1' },
					                      { text: 'Header 2', value: 'h2' },
					                      { text: 'Header 3', value: 'h3' },
					                      { text: 'Header 4', value: 'h4' },
					                      { text: 'Header 5', value: 'h5' },
					                      { text: 'Header 6', value: 'h6' }
					                  ]
					            },
					            { type: 'separator' },
					            { type: 'button', label: 'Link', value: 'createlink', disabled: true },
				                { type: 'button', label: 'Image', value: 'insertimage' },
				                { type: 'button', label: 'Table', value: 'inserttable' },
				                { type: 'push', label: 'Undo CTRL + Z', value: 'undo' },
				                { type: 'push', label: 'Redo CTRL + SHIFT + Z', value: 'redo' }
			              ]
			          }     
			      ]
			}
		},
		/*******************************************************
		 * Compact config
		 * 
		 * Minimal buttons with available second row.
		 * 
		 *******************************************************/
		compactConfig: {
			height: '300px',
			width: '470px',
			collapse: false,
			ptags: false,
			animate: true,
			dompath: false,
			focusAtStart: false,
			filterWord: true,
			autoHeight: false,
			grouplabels: false,
		    toolbar: {
		        titlebar: false,
				buttons: [
					{ group: 'firstrow', label: 'Tools',
					    buttons: [
					        { type: 'push', label: 'Bold CTRL + B', value: 'bold' },
					        { type: 'push', label: 'Italic CTRL + I', value: 'italic' },
					        { type: 'separator' },
					        { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
					        { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
					        { type: 'separator' },
					        { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' }, 
			        		{ type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
			        		{ type: 'separator' },
			        	    { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
			        	    { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' },
			        	    { type: 'separator' },
			        	    { type: 'push', label: 'Indent', value: 'indent' },
			                { type: 'push', label: 'Outdent', value: 'outdent' },
			                { type: 'separator' },
			        	    { type: 'push', label: 'HTML Link CTRL + L', value: 'createlink', disabled: true },
					        { type: 'push', label: 'Insert Image', value: 'insertimage' },		
					        { type: 'separator' },
			        	    { type: 'button', label: 'More', value: 'togglemore' }			        		
					    ]
					},
										
					// Second Row (hidden)         
					{ group: 'morerow', label: 'More Tools',
						  css: 'display:none',
			              buttons: [
			                  { type: 'select', label: 'Default Font', value: 'fontname', disabled: true,
			                      menu: [
			                          { text: 'Arial', checked: true },
			                          { text: 'Arial Black' },
			                          { text: 'Comic Sans MS' },
			                          { text: 'Courier New' },
			                          { text: 'Lucida Console' },
			                          { text: 'Tahoma' },
			                          { text: 'Times New Roman' },
			                          { text: 'Trebuchet MS' },
			                          { text: 'Verdana' }
			                      ]
			                  },
			                  { type: 'separator' },
			                  { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true },
			                  { type: 'separator' },
			                  { type: 'select', label: 'Normal', value: 'heading', disabled: true,
				                  menu: [
				                      { text: 'Normal', value: 'none', checked: true },
				                      { text: 'Header 1', value: 'h1' },
				                      { text: 'Header 2', value: 'h2' },
				                      { text: 'Header 3', value: 'h3' },
				                      { text: 'Header 4', value: 'h4' },
				                      { text: 'Header 5', value: 'h5' },
				                      { text: 'Header 6', value: 'h6' }
				                  ]
				              },
				              { type: 'separator' },
				              { type: 'push', label: 'Strike Through', value: 'strikethrough' },
				              { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
				              { type: 'separator' },
				              { type: 'push', label: 'Remove Formatting', value: 'removeformat' },
				              { type: 'push', label: 'Edit HTML Code', value: 'editcode' },
				              { type: 'separator' },
				              { type: 'push', label: 'Insert Table', value: 'inserttable' }				              
			              ]
			          }
				]
		    }
		},
	/*******************************************************
	 * Full mode config
	 * 
	 * - All buttons
	 * 
	 *******************************************************/	
	fullConfig: {
			height: '300px',
			width: '830px',
			collapse: false,
			animate: true,
			dompath: false,
			ptags: false,
			focusAtStart: true,
			filterWord: true,
			autoHeight: false,
			grouplabels: false,
		    toolbar: {
		        titlebar: false,
				buttons: [
					{ group: 'firstrow', label: 'Tools',
					    buttons: [
					          { type: 'push', label: 'Bold CTRL + B', value: 'bold' },
					        	{ type: 'push', label: 'Italic CTRL + I', value: 'italic' },
					        	{ type: 'push', label: 'Underline CTRL + U', value: 'underline' },
					        	{ type: 'push', label: 'Strike Through', value: 'strikethrough' },
					        	{ type: 'separator' },
					        	{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
					        	{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
					        	{ type: 'separator' },
					        	{ type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' }, 
								{ type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' }, 
								{ type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' }, 
								{ type: 'push', label: 'Justify', value: 'justifyfull' },
								{ type: 'separator' },
								{ type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
					          { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' },
					          { type: 'separator' },
					          { type: 'push', label: 'Indent', value: 'indent' },
					          { type: 'push', label: 'Outdent', value: 'outdent' },
					          { type: 'separator' },
					          { type: 'push', label: 'Remove Formatting', value: 'removeformat' },
					          { type: 'push', label: 'Show Hidden Elements', value: 'hiddenelements' },
					          { type: 'separator' },
					          { type: 'push', label: 'Edit HTML Code', value: 'editcode' },
					          { type: 'push', label: 'Fullscreen', value: 'fullmode' }
					    ]
					},     
					{ group: 'secondrow', label: 'Tools',
					    buttons: [ 
								{ type: 'select', label: 'Default Font', value: 'fontname', disabled: true,
								    menu: [
								        { text: 'Arial', checked: true },
								        { text: 'Arial Black' },
								        { text: 'Comic Sans MS' },
								        { text: 'Courier New' },
								        { text: 'Lucida Console' },
								        { text: 'Tahoma' },
								        { text: 'Times New Roman' },
								        { text: 'Trebuchet MS' },
								        { text: 'Verdana' }
								    ]
								},
								{ type: 'separator' },
								{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true },
								{ type: 'separator' },
								{ type: 'select', label: 'Normal', value: 'heading', disabled: true,
					                menu: [
					                    { text: 'Normal', value: 'none', checked: true },
					                    { text: 'Header 1', value: 'h1' },
					                    { text: 'Header 2', value: 'h2' },
					                    { text: 'Header 3', value: 'h3' },
					                    { text: 'Header 4', value: 'h4' },
					                    { text: 'Header 5', value: 'h5' },
					                    { text: 'Header 6', value: 'h6' }
					                ]
					          },
					          { type: 'separator' },
					          { type: 'button', label: 'Link', value: 'createlink', disabled: true },
					          { type: 'button', label: 'Image', value: 'insertimage' },
					          { type: 'button', label: 'Table', value: 'inserttable' },
					          { type: 'push', label: 'Undo CTRL + Z', value: 'undo' },
					          { type: 'push', label: 'Redo CTRL + SHIFT + Z', value: 'redo' }
					    ]
					}
			          
			      ]
			}
		},
		
	/*******************************************************
	 * RamiusRTE.init(el,config)
	 * 
	 * Initialize the editor.  Uses the default config and
	 * appends any config options passed in.
	 * 
	 ******************************************************/
	init: function(el_id,config,compact){

		my_config = compact ? RamiusRTE.compactConfig : RamiusRTE.defaultConfig;
		
		if ( config ) {
			
			for (var key in config) {
				  if (config.hasOwnProperty(key)) {
				    my_config[key] = config[key];
				  }
			}
					
		}
		
		
		
		var rte = new YAHOO.widget.Editor(el_id,  my_config );

		RamiusRTE._initCommon(rte);

		if( compact ){
			// Compact init
			rte.initCompact();			
		}
		
		// Initialize Fullscreen Extension
		rte.initFullEditor();

		$(el_id).editor = rte;
		return rte;
	},
	
	
	/*******************************************************
	 * RamiusRTE._initFull(parent)
	 * 
	 * Used internally to create Full mode editor
	 * appends any config options passed in.
	 * Links parent editor
	 * 
	 ******************************************************/
	_initFull: function(parent){

		
		var full_el = document.createElement('div');
		
		// Add empty overlay div with z-index. Panels will stack against others.
		var overlay_el = document.createElement('div');
		overlay_el.className = 'yui-overlay';
		overlay_el.style.zIndex = '99998';
		full_el.appendChild(overlay_el);
		
		var txt_el = document.createElement('textarea');
		full_el.className = 'yui-skin-sam rm-fullRte';
		full_el.appendChild(txt_el);
		document.body.appendChild(full_el);
		
		
		var full_conf = RamiusRTE.fullConfig;
		
		// Copy parent internal css.
		var css = parent.get('css');
		full_conf.css = css;
		
		var full_rte = new YAHOO.widget.Editor(txt_el, full_conf );

		RamiusRTE._initCommon(full_rte);
		
		full_rte.initFullEditClone(parent);
		
		full_rte.render();
		
		$E.addListener(window, 'resize', full_rte.resize, full_rte); 
		
		return full_rte;	

	},
	
	/*******************************************************
	 * RamiusRTE._initCommon(editor)
	 * 
	 * Used internally to initialize common plugins.  Used
	 * by both normal and full edit mode.
	 * 
	 * Place common init items used by all editors.
	 * 
	 ******************************************************/
	_initCommon: function(rte){
		// Common features for normal and full edit.
		
		// Set stylesheet
		rte.set('html', RamiusRTE.iframe_html());
		
		//Set Blank Image
		rte.set('blankimage', RamiusRTE.blank_img);
		
		// Initialize Code Edit Extension
		rte.initCodeEditor();
		
		// Initialize Table Extension
		rte.initTableEditor();
		
		// Initialize Image Upload Extension
		rte.initImgUpload();
		
		rte.initPaste();
		
		// Remap default key mods
		rte._keyMap.BOLD.mods = ['ctrl'];
		rte._keyMap.ITALIC.mods = ['ctrl'];
		rte._keyMap.UNDERLINE.mods = ['ctrl'];
		rte._keyMap.CREATE_LINK.mods = ['ctrl'];

	}
	
}; 
// End of RamiusRTE



/*******************************************************
 * YAHOO Editor Extensions
 * 
 * - Override base functionality
 * - Adds functions to the Editor class
 * 
 ******************************************************/



/*******************************************************
 * Override core code clean-up definitions
 * 
 * - Invalid HTML tags to remove
 * - HTML cleanup rules for initial content
 * 
 ******************************************************/
YAHOO.widget.Editor.prototype._createCurrentElement  = function(tagName, tagStyle) {
           
        tagName = ((tagName) ? tagName : 'a');
        var tar = null,
            el = [],
            _doc = this._getDoc();
        
        if (this.currentFont) {
            if (!tagStyle) {
                tagStyle = {};
            }
            tagStyle.fontFamily = this.currentFont;
            this.currentFont = null;
        }
        this.currentElement = [];

        var _elCreate = function(tagName, tagStyle) {
            var el = null;
            tagName = ((tagName) ? tagName : 'span');
            tagName = tagName.toLowerCase();
                            	
            el = _doc.createElement(tagName);
            if (tagName === 'span') {
                YAHOO.util.Dom.addClass(el, 'yui-tag-' + tagName);
                YAHOO.util.Dom.addClass(el, 'yui-tag');
                el.setAttribute('tag', tagName);
            }

            for (var k in tagStyle) {
                if (YAHOO.lang.hasOwnProperty(tagStyle, k)) {
                    el.style[k] = tagStyle[k];
                }
            }
            
            return el;
        };
			 
        if (!this._hasSelection()) {
            if (this._getDoc().queryCommandEnabled('insertimage')) {
                this._getDoc().execCommand('insertimage', false, 'yui-tmp-img');
                var imgs = this._getDoc().getElementsByTagName('img');
                for (var j = 0; j < imgs.length; j++) {
                    if (imgs[j].getAttribute('src', 2) == 'yui-tmp-img') {
                        el = _elCreate(tagName, tagStyle);
                        imgs[j].parentNode.replaceChild(el, imgs[j]);
                        this.currentElement[this.currentElement.length] = el;
                    }
                }
            } else {
                
                if (this.currentEvent) {
                    tar = YAHOO.util.Event.getTarget(this.currentEvent);
                } else {
                    //For Safari..
                    tar = this._getDoc().body;                        
                }
            }
            if (tar) {
                /*
                * @knownissue Safari Cursor Position
                * @browser Safari 2.x
                * @description The issue here is that we have no way of knowing where the cursor position is
                * inside of the iframe, so we have to place the newly inserted data in the best place that we can.
                */
                el = _elCreate(tagName, tagStyle);
                if (this._isElement(tar, 'body') || this._isElement(tar, 'html')) {
                    if (this._isElement(tar, 'html')) {
                        tar = this._getDoc().body;
                    }
                    tar.appendChild(el);
                } else if (tar.nextSibling) {
                    tar.parentNode.insertBefore(el, tar.nextSibling);
                } else {
                    tar.parentNode.appendChild(el);
                }
                //this.currentElement = el;
                this.currentElement[this.currentElement.length] = el;
                this.currentEvent = null;
                if (this.browser.webkit) {
                    //Force Safari to focus the new element
                    this._getSelection().setBaseAndExtent(el, 0, el, 0);
                    if (this.browser.webkit3) {
                        this._getSelection().collapseToStart();
                    } else {
                        this._getSelection().collapse(true);
                    }
                }
            }
        } else {
        
            
            //Force CSS Styling for this action...
            this._setEditorStyle(true);
            this._getDoc().execCommand('fontname', false, 'yui-tmp'); 
            // Ramius - Include the li & ul
            // Include divs and heading tags.
            var _tmp = [], __tmp, __els = ['font', 'span', 'i', 'b', 'u','li','ul', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

            if (!this._isElement(this._getSelectedElement(), 'body')) {
                __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().tagName);
                __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().parentNode.tagName);
            }
            
            for (var _els = 0; _els < __els.length; _els++) {
            
            
                var _tmp1 = this._getDoc().getElementsByTagName(__els[_els]);
                for (var e = 0; e < _tmp1.length; e++) {
                    _tmp[_tmp.length] = _tmp1[e];
                }
            }
 
            		
            for (var i = 0; i < _tmp.length; i++) {
            	 
                if ((YAHOO.util.Dom.getStyle(_tmp[i], 'font-family') == 'yui-tmp') || (_tmp[i].face && (_tmp[i].face == 'yui-tmp'))) {
                    if (tagName != 'span' || this._isElement(_tmp[i], 'li')){
                        el = _elCreate(tagName, tagStyle);
                    } else {
                        el = _elCreate(_tmp[i].tagName, tagStyle);
                    }
                    
                    el.innerHTML = _tmp[i].innerHTML;
                    if (this._isElement(_tmp[i], 'ol') || (this._isElement(_tmp[i], 'ul'))) {
                    	
                    	_tmp[i].style.fontFamily = 'inherit';                        
                        
                    } else if (this._isElement(_tmp[i], 'li')) {
                          
                    
                        _tmp[i].innerHTML = '';
                        _tmp[i].appendChild(el);
                        _tmp[i].style.fontFamily = 'inherit';
                        
                        this.currentElement[this.currentElement.length] = el;
                    } else {
                        if (_tmp[i].parentNode) {
                            _tmp[i].parentNode.replaceChild(el, _tmp[i]);
                            this.currentElement[this.currentElement.length] = el;
                            this.currentEvent = null;
                            if (this.browser.webkit) {
                                //Force Safari to focus the new element
                                this._getSelection().setBaseAndExtent(el, 0, el, 0);
                                if (this.browser.webkit3) {
                                    this._getSelection().collapseToStart();
                                } else {
                                    this._getSelection().collapse(true);
                                }
                            }
                            if (this.browser.ie && tagStyle && tagStyle.fontSize) {
                                this._getSelection().empty();
                            }
                            if (this.browser.gecko) {
                                this._getSelection().collapseToStart();
                            }
                        }
                    }
                }
            }
            
       
             
            var len = this.currentElement.length;
            for (var o = 0; o < len; o++) {
                if ((o + 1) != len) { //Skip the last one in the list
                    if (this.currentElement[o] && this.currentElement[o].nextSibling) {
                        if (this._isElement(this.currentElement[o], 'br')) {
                            this.currentElement[this.currentElement.length] = this.currentElement[o].nextSibling;
                        }
                    }
                }
            }
        }
};
YAHOO.widget.Editor.prototype.filter_safari = function(html) {
    if (this.browser.webkit) {
        //<span class="Apple-tab-span" style="white-space:pre">	</span>
        html = html.replace(/<span class="Apple-tab-span" style="white-space:pre">([^>])<\/span>/gi, '&nbsp;&nbsp;&nbsp;&nbsp;');
        html = html.replace(/Apple-style-span/gi, '');
        html = html.replace(/style="line-height: normal;"/gi, '');
        html = html.replace(/yui-wk-div/gi, '');
        html = html.replace(/yui-wk-p/gi, '');


        //Remove bogus LI's
        html = html.replace(/<li><\/li>/gi, '');
        html = html.replace(/<li> <\/li>/gi, '');
        html = html.replace(/<li>  <\/li>/gi, '');
        // RAMIUS - Do not do this - Bad code
        //Remove bogus DIV's - updated from just removing the div's to replacing /div with a break
        if (this.get('ptags')) {
         //   html = html.replace(/<div([^>]*)>/g, '<p$1>');
		 //   html = html.replace(/<\/div>/gi, '</p>');
        } else {
         //   html = html.replace(/<div>/gi, '<br>');
         //   html = html.replace(/<div([^>]*)>([ tnr]*)<\/div>/gi, '<br>');
		 //   html = html.replace(/<\/div>/gi, '');
        }
    }
    return html;
};
YAHOO.widget.Editor.prototype.invalidHTML = {
	html: true,
	body: true
};

// Override to fix list clean-up issues
// Copied from editor code and modified.
YAHOO.widget.Editor.prototype.filter_invalid_lists = function(html) {
		// Removed code that adds extra wrapping LIs.
		// Ensure single new line after each for HTML mode.
        html = html.replace(/<\/li>\n*/gi, "</li>\n");
        html = html.replace(/<\/ol>\n*/gi, "</ol>\n");
        html = html.replace(/<\/ul>\n*/gi, "</ul>\n");
        html = html.replace(/<ol>\n*/gi, "<ol>\n");
        html = html.replace(/<ul>\n*/gi, "<ul>\n");
        return html;
}

// Default removes all scripts. Copied from Editor.js.
YAHOO.widget.Editor.prototype._cleanIncomingHTML = function(html) {
    html = html.replace(/{/gi, 'RIGHT_BRACKET');
    html = html.replace(/}/gi, 'LEFT_BRACKET');

    html = html.replace(/<strong([^>]*)>/gi, '<b$1>');
    html = html.replace(/<\/strong>/gi, '</b>');   

    //replace embed before em check
    html = html.replace(/<embed([^>]*)>/gi, '<YUI_EMBED$1>');
    html = html.replace(/<\/embed>/gi, '</YUI_EMBED>');

    html = html.replace(/<em([^>]*)>/gi, '<i$1>');
    html = html.replace(/<\/em>/gi, '</i>');
    html = html.replace(/_moz_dirty=""/gi, '');
    
    //Put embed tags back in..
    html = html.replace(/<YUI_EMBED([^>]*)>/gi, '<embed$1>');
    html = html.replace(/<\/YUI_EMBED>/gi, '</embed>');
    if (this.get('plainText')) {
        html = html.replace(/\n/g, '<br>').replace(/\r/g, '<br>');
        html = html.replace(/  /gi, '&nbsp;&nbsp;'); //Replace all double spaces
        html = html.replace(/\t/gi, '&nbsp;&nbsp;&nbsp;&nbsp;'); //Replace all tabs
    }
    //Removing Script Tags from the Editor
    //html = html.replace(/<script([^>]*)>/gi, '<bad>');
    //html = html.replace(/<\/script([^>]*)>/gi, '</bad>');
    //html = html.replace(/&lt;script([^>]*)&gt;/gi, '<bad>');
    //html = html.replace(/&lt;\/script([^>]*)&gt;/gi, '</bad>');

    //Replace the line feeds
    html = html.replace(/\r\n/g, '<YUI_LF>').replace(/\n/g, '<YUI_LF>').replace(/\r/g, '<YUI_LF>');
    
    //Remove Bad HTML elements (used to be script nodes)
    html = html.replace(new RegExp('<bad([^>]*)>(.*?)<\/bad>', 'gi'), '');
    //Replace the lines feeds
    html = html.replace(/<YUI_LF>/g, '\n');
    return html;
};

/***********************************************************
 * Image Uploaded Plugin
 * 
 * - Overrides panel render, open action, and close action
 * 
 ***********************************************************/

var switchImageView = function(id, upload) { 
	if (upload) {
				
		$(id + '_stage1').style.display='block';
		$(id + '_stage2').style.display='none';
		$(id + '_stage3').style.display='none';			
	
	} else {
		$(id + '_stage1').style.display='none';
		$(id + '_stage2').style.display='none';
		$(id + '_stage3').style.display='block';			
	}

}

var linkImage = function(id) {

	var url = $( id + '_insertimage_url').value;
	if ( url == '' || !url.match('^http') ) return;
	
	if (url.indexOf("rte_image") > 0 ) {		
		var url_link = url.substring(0,url.lastIndexOf('/') + 1) + 'hi.' + url.substring(url.lastIndexOf('/')+1);
		$( id + '_insertimage_link').value = url_link; 
	} else {
		$( id + '_insertimage_link').value = url;
	}
	

}

YAHOO.widget.Editor.prototype.STR_IMAGE_PADDING = 'Margin';

YAHOO.widget.Editor.prototype.initImgUpload = function() {
	
	// Needed for panel
	var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event,
    Lang = YAHOO.lang;
	
	
	/***********************************************************
	 * _renderInsertImageWindow
	 * 
	 * Override default image panel render 
	 * Returns the body of the image panel.
	 * 
	 ***********************************************************/
	YAHOO.widget.Editor.prototype._renderInsertImageWindow = function() {

		this.STR_IMAGE_HERE = 'Enter a website address (URL) for an image';
		
		var el = this.currentElement[0];
		var body = document.createElement('div');
		body.className = 'rm-imageUploader';
		
		// Stage 1
		var stage1 = document.createElement('div');
		stage1.id = this.get('id') + '_stage1';
		stage1.className = 'rm-stage1';
		//stage1.style.display = 'none';
		var form_el = document.createElement('form');
		form_el.method="post";
		form_el.enctype="multipart/form-data";
		    	
		form_el.target="rm-yui-sndbx";
		form_el.id = this.get('id') + "_img_upload";
		
		var upload_fld = document.createElement('label');
		upload_fld.id = 'rm-RTE-file-select';
		upload_fld.setAttribute('for',this.get('id') + '_insertimage_file');
		upload_fld.innerHTML = '<strong>Upload:</strong> ';

		var upload_file = document.createElement('input');
		upload_file.type = 'file';
		upload_file.name = 'rte_image';
		upload_file.id = this.get('id') + '_insertimage_file';
		upload_file.className = 'rm-fileInput';
		upload_file.size = '30';
		$E.on(upload_file,'change',function(e){
			var src = e.target || e.srcElement;
			$('rm-fakeInput').value = src.value.replace(/^c:\\fakepath\\/gi,'');
		})

		var upload_fake = document.createElement('span');
		upload_fake.className = 'rm-fakefile';
		upload_fake.innerHTML = '<input class="rm-regInput" id="rm-fakeInput" /><span id="rm-fakeButton"></span>';

		var upload_options = document.createElement('span');
		upload_options.className = 'rm-optionUp';
		upload_options.innerHTML = 'or <a href="javascript:void(0);" onclick="switchImageView(\''+this.get('id')+'\',false);">use an image from a website</a> (URL)';

		upload_fld.appendChild(upload_file);
		upload_fld.appendChild(upload_fake);
		upload_fld.appendChild(upload_options);
        
        var goTbar = document.createElement('div');
        goTbar.id = this.get('id') + '_go';
        Dom.addClass(goTbar,"rm-go");
        
        var go_tbar = new YAHOO.widget.Toolbar(goTbar, {
        	buttonType: 'advanced',
        	buttons: [
        	            { type: 'button', label: 'Continue', value: 'submitimage' }
        	 ]
        });
        go_tbar.editor_el = el;
        
        form_el.appendChild(upload_fld);
        stage1.appendChild(form_el);
        
        stage1.appendChild(goTbar);
        
        body.appendChild(stage1);
        
        // Stage 2        
        var stage2 = document.createElement('div');
        stage2.id = this.get('id') + '_stage2';
        stage2.className = 'rm-stage2';
        stage2.style.display = 'none';
        stage2.innerHTML = '<div class="rm-imgUploading">Image Uploading...&nbsp;&nbsp;<a class="rm-cancelUpload" href="#" >Cancel</a>';
        body.appendChild(stage2);
        
        // Stage 3
        var stage3 = document.createElement('div');
        stage3.id = this.get('id') + '_stage3';
        stage3.className = 'rm-stage3';
        stage3.style.display = 'none';
        
        // Used to prevent submitting
        var stage3_frm = document.createElement('form');
        stage3_frm.id = this.get('id') + "_img_frm";
        
        $E.on(stage3_frm,'submit', function(e){$E.stopEvent(e);});
        
        var img_url = document.createElement('label');
        img_url.setAttribute('for', this.get('id') + '_insertimage_url');
        img_url.id = "rm-RTE-url-select";
        var img_url_fld = '<strong>' + this.STR_IMAGE_URL + ':</strong> <input class="rm-rteImageUrl" type="text" id="' + this.get('id') + '_insertimage_url" value="" size="40"><br /><span class="rm-optionUp">or <a href="javascript:void(0);" onclick="switchImageView(\''+this.get('id')+'\',true);">upload an image from your computer</a></span>';
        img_url.innerHTML = img_url_fld;        
        stage3_frm.appendChild(img_url);
        
        var tbarCont = document.createElement('div');
        tbarCont.id = this.get('id') + '_img_toolbar';
        

        var stage3_frm2 = document.createElement('form');
        stage3_frm2.id = this.get('id') + "_img_frm2";
        stage3_frm2.style.overflow = 'visible';
        
        var str2 = '<label for="' + this.get('id') + '_insertimage_title"><strong>' + this.STR_IMAGE_TITLE + ':</strong> <input type="text" id="' + this.get('id') + '_insertimage_title" value="" size="40"></label>';
        str2 += '<label for="' + this.get('id') + '_insertimage_link" id="rm-linkUrl"><strong>' + this.STR_LINK_URL + ':</strong> <input class="rm-linkInput" type="text" name="' + this.get('id') + '_insertimage_link" id="' + this.get('id') + '_insertimage_link" value=""></label>';
        str2 += '<div id="rm-newWindow"><input type="checkbox" name="' + this.get('id') + '_insertimage_target_" id="' + this.get('id') + '_insertimage_target" value="_blank" class="insertimage_target"><label id="rm-newLbl" for="' + this.get('id') + '_insertimage_target">' + this.STR_LINK_NEW_WINDOW + '</label><a href="javascript:void(0);" onclick="linkImage(\''+this.get('id')+'\');" id="rm-fullSize">Link to full-size image</a></label>';
        var div = document.createElement('div');
        div.innerHTML = str2;
        stage3_frm2.appendChild(div);
        
        stage3.appendChild(stage3_frm);
        stage3.appendChild(tbarCont);
        stage3.appendChild(stage3_frm2);
        
        body.appendChild(stage3);
        
        
        var o = {};
        Lang.augmentObject(o, this._defaultImageToolbarConfig); //Break the config reference
        
        var tbar = new YAHOO.widget.Toolbar(tbarCont, o);
        tbar.editor_el = el;
        this._defaultImageToolbar = tbar;
        
        var cont = tbar.get('cont');
        var hw = document.createElement('div');
        hw.className = 'yui-toolbar-group yui-toolbar-group-height-width height-width';
        hw.innerHTML = '<h3>Width:</h3>';
        hw.innerHTML += '<span tabIndex="-1"><input type="text" size="3" value="" id="' + this.get('id') + '_insertimage_width"> pixels</span>';
        cont.insertBefore(hw, cont.firstChild);

        
        Event.onAvailable(this.get('id') + '_insertimage_width', function() {
            Event.on(this.get('id') + '_insertimage_width', 'blur', function() {
                var value = parseInt(Dom.get(this.get('id') + '_insertimage_width').value, 10);
                if (value > 5) {
                   this._defaultImageToolbar.editor_el.style.width = value + 'px';
                }
            }, this, true);
            Event.on(this.get('id') + '_insertimage_width', 'keydown', function(e){
            	// Update width on enter, up or down arrows
            	var value = parseInt(Dom.get(this.get('id') + '_insertimage_width').value, 10);
	            if( e.keyCode == 13 ){
	            	Event.stopEvent(e);
	                if (value > 5) {
	                   this._defaultImageToolbar.editor_el.style.width = value + 'px';
	                }	
	            } else if( e.keyCode == 38 ){
	            	value++;
	            	Dom.get(this.get('id') + '_insertimage_width').value = value;
	            	this._defaultImageToolbar.editor_el.style.width = value + 'px';	
	            } else if( e.keyCode == 40 && value > 5 ){
	            	value--;
	            	Dom.get(this.get('id') + '_insertimage_width').value = value;
	            	this._defaultImageToolbar.editor_el.style.width = value + 'px';	
	            }
	            
	        }, this, true);
            
        }, this, true);
        /*
        Event.onAvailable(this.get('id') + '_insertimage_height', function() {
            Event.on(this.get('id') + '_insertimage_height', 'blur', function() {
                var value = parseInt(Dom.get(this.get('id') + '_insertimage_height').value, 10);
                if (value > 5) {
                    this._defaultImageToolbar.editor_el.style.height = value + 'px';
                    //Removed moveWindow call so the window doesn't jump
                    //this.moveWindow();
                }
            }, this, true);
        }, this, true);
		*/

        tbar.on('colorPickerClicked', function(o) {
            var size = '1', type = 'solid', color = 'black', el = this._defaultImageToolbar.editor_el;

            if (el.style.borderLeftWidth) {
                size = parseInt(el.style.borderLeftWidth, 10);
            }
            if (el.style.borderLeftStyle) {
                type = el.style.borderLeftStyle;
            }
            if (el.style.borderLeftColor) {
                color = el.style.borderLeftColor;
            }
            var borderString = size + 'px ' + type + ' #' + o.color;
            el.style.border = borderString;
        }, this, true);

        // Go Button action
        go_tbar.on('buttonClick', function(o) {
        	var value = o.button.value;
        	if( value == 'submitimage'){
        	
        		// form post
				
				this.uploading = true;        		
        		var id = this.get('id');
        		var this_form = $(this.get('id') + '_img_upload');

				Ramius.ajax.request(
					    "/rteUpload", {
						upload: true,
						form: this_form,
						method:'post',
						onUpload:function(ajax_resp){

						 	if ( ajax_resp.responseText.match(/ERROR<\/pre>$/i) || ajax_resp.responseText == "ERROR") {
						 		switchImageView(id , true);
						 	} else {
						 		var url = ajax_resp.responseText;

						 		if ( url.match(/^<pre/i)) {
						 			
						 			var idx = url.indexOf('>');  
						 			url = url.substring(idx+1,url.length - 6);
						 			
						 		}

						 		$( id + '_insertimage_url').value = url;
						 		linkImage(id);
						 		switchImageView(id , false);
						 		$( id + '_insertimage_url').focus();
						 		$( id + '_insertimage_url').blur();
						 		
						 		
							} 
							 
							this.uploading = false; 
						    
						},
						
						onError:function(ajax_resp){
							
							switchImageView(id , true);
							this.uploading = false; 
						},
						onFailure:function(ajax_resp){
							
							switchImageView(id , true);
							this.uploading = false; 
						}
				}); 
				
				$(id + '_stage1').style.display='none';
				$(id + '_stage2').style.display='block';
				$(id + '_stage3').style.display='none';			
						
				
        	}

        },this,true);
        
        tbar.on('buttonClick', function(o) {
            var value = o.button.value,
                el = this._defaultImageToolbar.editor_el,
                borderString = '';
            if (o.button.menucmd) {
                value = o.button.menucmd;
            }
            var size = '1', type = 'solid', color = 'black';

            /* All border calcs are done on the left border
                since our default interface only supports
                one border size/type and color */
            if (el.style.borderLeftWidth) {
                size = parseInt(el.style.borderLeftWidth, 10);
            }
            if (el.style.borderLeftStyle) {
                type = el.style.borderLeftStyle;
            }
            if (el.style.borderLeftColor) {
                color = el.style.borderLeftColor;
            }
            switch(value) {
                case 'bordersize':
                    if (this.browser.webkit && this._lastImage) {
                        Dom.removeClass(this._lastImage, 'selected');
                        this._lastImage = null;
                    }
                    tbar.selectButton(o.button.value);
                    borderString = parseInt(o.button.value, 10) + 'px ' + type + ' ' + color;
                    el.style.border = borderString;
                    if (parseInt(o.button.value, 10) > 0) {
                        tbar.enableButton('bordertype');
                        tbar.enableButton('bordercolor');
                    } else {
                        tbar.disableButton('bordertype');
                        tbar.disableButton('bordercolor');
                    }
                    break;
                case 'bordertype':
                    if (this.browser.webkit && this._lastImage) {
                        Dom.removeClass(this._lastImage, 'selected');
                        this._lastImage = null;
                    }
                    tbar.selectButton(o.button.value);
                    borderString = size + 'px ' + o.button.value + ' ' + color;
                    el.style.border = borderString;
                    break;
                case 'right':
                case 'left':
                    tbar.deselectAllButtons();
                    tbar.selectButton(o.button.value);
                    el.style.display = '';
                    el.align = o.button.value;
                    break;
                case 'inline':
                    tbar.deselectAllButtons();
                    tbar.selectButton(o.button.value);
                    el.style.display = '';
                    el.align = '';
                    break;
                case 'block':
                    tbar.deselectAllButtons();
                    tbar.selectButton(o.button.value);
                    el.style.display = 'block';
                    el.align = 'center';
                    break;
                case 'padding':
                    var _button = tbar.getButtonById(o.button.id);
                    tbar.selectButton(o.button.value);
                    el.style.margin = _button.get('label') + 'px';                    
                    break;
            }
            
            if (value !== 'padding') {
            	// pass in true to disable animation
                this.moveWindow(true);
            }
        }, this, true);

        if (this.get('localFileWarning')) {
            Event.on(this.get('id') + '_insertimage_link', 'blur', function() {
                var url = Dom.get(this.get('id') + '_insertimage_link');
                if (this._isLocalFile(url.value)) {
                    //Local File throw Warning
                    Dom.addClass(url, 'warning');
                    this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
                } else {
                    Dom.removeClass(url, 'warning');
                    this.get('panel').setFooter(' ');
                    //Adobe AIR Code
                    if ((this.browser.webkit && !this.browser.webkit3 || this.browser.air) || this.browser.opera) {                
                        this.get('panel').setFooter(this.STR_IMAGE_COPY);
                    }
                }
            }, this, true);
        }
        
        var update_img_src = function(rte){
        	var url = Dom.get(rte.get('id') + '_insertimage_url'),
        
	        el = rte.currentElement[0];
	
	        if (url.value && el) {
	            if (url.value == el.getAttribute('src', 2)) {
	                return false;
	            }
	        }
	        if (rte._isLocalFile(url.value)) {
	            //Local File throw Warning
	            Dom.addClass(url, 'warning');
	            rte.get('panel').setFooter(rte.STR_LOCAL_FILE_WARNING);
	        } else if (rte.currentElement[0]) {
	            Dom.removeClass(url, 'warning');
	            rte.get('panel').setFooter(' ');
	            //Adobe AIR Code
	            if ((rte.browser.webkit && !rte.browser.webkit3 || rte.browser.air) || rte.browser.opera) {                
	            	rte.get('panel').setFooter(rte.STR_IMAGE_COPY);
	            }
	            
	            if (url && url.value && (url.value != rte.STR_IMAGE_HERE)) {
	            	rte.currentElement[0].setAttribute('src', url.value);
	                var self = rte,
	                    img = new Image();
	
	                img.onerror = function() {
	                    url.value = self.STR_IMAGE_HERE;
	                    img.setAttribute('src', self.get('blankimage'));
	                    self.currentElement[0].setAttribute('src', self.get('blankimage'));
	                    //YAHOO.util.Dom.get(self.get('id') + '_insertimage_height').value = img.height;
	                    YAHOO.util.Dom.get(self.get('id') + '_insertimage_width').value = img.width;
	                };
	                var id = rte.get('id');
	                window.setTimeout(function() {
	                    //YAHOO.util.Dom.get(id + '_insertimage_height').value = img.height;
	                    YAHOO.util.Dom.get(id + '_insertimage_width').value = img.width;
	                    if (self.currentElement && self.currentElement[0]) {
	                        //if (!self.currentElement[0]._height) {
	                          //  self.currentElement[0]._height = img.height;
	                        //}
	                        if (!self.currentElement[0]._width) {
	                            self.currentElement[0]._width = img.width;
	                        }
	                    }
	                    //Removed moveWindow call so the window doesn't jump
	                    //self.moveWindow();
	                }, 800); //Bumped the timeout up to account for larger images..
	
	                if (url.value != rte.STR_IMAGE_HERE) {
	                    img.src = url.value;
	                }
	            }
	        }
        };
        
        Event.on(this.get('id') + '_insertimage_url', 'keydown', function(e){
            if( e.keyCode == 13 ){	            	
            	update_img_src(this);
            }            
        }, this, true);
        Event.on(this.get('id') + '_insertimage_url', 'blur', function(){update_img_src(this)}, this, true);

        this._windows.insertimage = {};
        this._windows.insertimage.body = body;
        //body.style.display = 'none';
        this.get('panel').editor_form.appendChild(body);
        this.fireEvent('windowInsertImageRender', { type: 'windowInsertImageRender', panel: this.get('panel'), body: body, toolbar: tbar });
       
        return body;
	};

	/***********************************************************
	 * _handleInsertImageClick
	 * 
	 * Override image panel open init
	 * 
	 ***********************************************************/
	YAHOO.widget.Editor.prototype._handleInsertImageClick = function() {
        if (this.get('limitCommands')) {
            if (!this.toolbar.getButtonByValue('insertimage')) {
                return false;
            }
        }
        this.on('afterExecCommand', function() {
            var el = this.currentElement[0],
                body = null,
                link = '',
                target = '',
                tbar = null,
                title = '',
                src = '',
                align = '',
                //height = 75,
                width = 75,
                padding = 5,
                oheight = 0,
                owidth = 0,
                blankimage = false,
                win = new YAHOO.widget.EditorWindow('insertimage', {
                    width: '415px'
                });

            if (!el) {
                el = this._getSelectedElement();
            }
            if (el) {
                win.el = el;
                if (el.getAttribute('src')) {
                    src = el.getAttribute('src', 2);
                    if (src.indexOf(this.get('blankimage')) != -1) {
                        src = this.STR_IMAGE_HERE;
                        el.style.display = 'block';
                        el.style.padding = '5px';
                        blankimage = true;
                    }
                }
                if (el.getAttribute('alt', 2)) {
                    title = el.getAttribute('alt', 2);
                }
                if (el.getAttribute('title', 2)) {
                    title = el.getAttribute('title', 2);
                }

                if (el.parentNode && this._isElement(el.parentNode, 'a')) {
                    link = el.parentNode.getAttribute('href', 2);
                    if (el.parentNode.getAttribute('target') !== null) {
                        target = el.parentNode.getAttribute('target');
                    }
                }
                //height = parseInt(el.height, 10);
                width = parseInt(el.width, 10);
                //if (el.style.height) {
                  //  height = parseInt(el.style.height, 10);
                //}
                if (el.style.width) {
                    width = parseInt(el.style.width, 10);
                }
                if (el.style.margin) {
                    padding = parseInt(el.style.margin, 10);
                }
                if (!blankimage) {
                    //if (!el._height) {
                      //  oheight = el._height;
                    //}
                    if (!el._width) {
                        el._width = width;
                    }
                    //oheight = el._height;
                    owidth = el._width;
                }
            }
            if (this._windows.insertimage && this._windows.insertimage.body) {
                body = this._windows.insertimage.body;
                this._defaultImageToolbar.resetAllButtons();
            } else {
                body = this._renderInsertImageWindow();
            }

            tbar = this._defaultImageToolbar;
            tbar.editor_el = el;
            

            var bsize = '0',
                btype = 'solid';

            if (el.style.borderLeftWidth) {
                bsize = parseInt(el.style.borderLeftWidth, 10);
            }
            if (el.style.borderLeftStyle) {
                btype = el.style.borderLeftStyle;
            }
            
            var bs_button = tbar.getButtonByValue('bordersize'),
                bSizeStr = ((parseInt(bsize, 10) > 0) ? '' : this.STR_NONE);
            bs_button.set('label', '<span class="yui-toolbar-bordersize-' + bsize + '">' + bSizeStr + '</span>');
            this._updateMenuChecked('bordersize', bsize, tbar);
            
            var bt_button = tbar.getButtonByValue('bordertype');
            bt_button.set('label', '<span class="yui-toolbar-bordertype-' + btype + '">asdfa</span>');
            this._updateMenuChecked('bordertype', btype, tbar);
            if (parseInt(bsize, 10) > 0) {
                tbar.enableButton(bt_button);
                tbar.enableButton(bs_button);
                tbar.enableButton('bordercolor');
            }

            if ((el.align == 'right') || (el.align == 'left')) {
                tbar.selectButton(el.align);
            } else if (el.style.display == 'block') {
                tbar.selectButton('block');
            } else {
                tbar.selectButton('inline');
            }
            if (parseInt(el.style.marginLeft, 10) > 0) {
                tbar.getButtonByValue('padding').set('label', ''+parseInt(el.style.marginLeft, 10));
            }
            if (el.style.borderSize) {
                tbar.selectButton('bordersize');
                tbar.selectButton(parseInt(el.style.borderSize, 10));
            }
            tbar.getButtonByValue('padding').set('label', ''+padding);



            win.setHeader(this.STR_IMAGE_PROP_TITLE);
            win.setBody(body);
            //Adobe AIR Code
            if ((this.browser.webkit && !this.browser.webkit3 || this.browser.air) || this.browser.opera) {                
                win.setFooter(this.STR_IMAGE_COPY);
            }
            
            this.openWindow(win);
            
             
            if ( src == this.STR_IMAGE_HERE ) {
            	switchImageView(this.get('id') , true);
	             
	            Dom.get(this.get('id') + '_insertimage_title').value = '';
	            Dom.get(this.get('id') + '_insertimage_url').value = ''; 
	            target = true;	            
	            Dom.get(this.get('id') + '_insertimage_file').value = '';
	            Dom.get('rm-fakeInput').value = '';
	            
	            	
            } else {
            	switchImageView(this.get('id') , false);
        	}
            
            Dom.get(this.get('id') + '_insertimage_url').value = src;
            Dom.get(this.get('id') + '_insertimage_title').value = title;
            Dom.get(this.get('id') + '_insertimage_link').value = link;
            Dom.get(this.get('id') + '_insertimage_target').checked = ((target) ? true : false);
            Dom.get(this.get('id') + '_insertimage_width').value = width;
           // Dom.get(this.get('id') + '_insertimage_height').value = height;

            /*
            if (((width != owidth)) && (!blankimage)) {
                var s = document.createElement('span');
                s.className = 'info';
                s.innerHTML = this.STR_IMAGE_ORIG_SIZE + ': ('+ owidth +' x ' + oheight + ')';
                if (Dom.get(this.get('id') + '_insertimage_width').nextSibling) {
                    var old = Dom.get(this.get('id') + '_insertimage_width').nextSibling;
                    old.parentNode.removeChild(old);
                }
                Dom.get(this.get('id') + '_insertimage_width').parentNode.appendChild(s);
            }
            */ 
            this.toolbar.selectButton('insertimage');
            var id = this.get('id');
            window.setTimeout(function() {
                try {
                    YAHOO.util.Dom.get(id + '_insertimage_url').focus();
                    if (blankimage) {
                        YAHOO.util.Dom.get(id + '_insertimage_url').select();
                    }
                } catch (e) {}
            }, 50);
        });
        
    };
    
	/***********************************************************
	 * _handleInsertImageWindowClose
	 * 
	 * Override the image panel closing actions
	 * 
	 ***********************************************************/
    YAHOO.widget.Editor.prototype._handleInsertImageWindowClose = function() {
        var url = Dom.get(this.get('id') + '_insertimage_url'),
            title = Dom.get(this.get('id') + '_insertimage_title'),
            link = Dom.get(this.get('id') + '_insertimage_link'),
            target = Dom.get(this.get('id') + '_insertimage_target'),
            el = arguments[0].win.el;

        if (url && url.value && (url.value != this.STR_IMAGE_HERE)) {
            el.setAttribute('src', url.value);
            el.setAttribute('title', title.value);
            el.setAttribute('alt', title.value);
            var par = el.parentNode;
            if (link.value) {
                var urlValue = link.value;
                if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
                    if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
                        //Found an @ sign, prefix with mailto:
                        urlValue = 'mailto:' + urlValue;
                    } else {
                        // :// not found adding
                        urlValue = 'http:/'+'/' + urlValue;
                    }
                }
                if (par && this._isElement(par, 'a')) {
                    par.setAttribute('href', urlValue);
                    if (target.checked) {
                        par.setAttribute('target', target.value);
                    } else {
                        par.setAttribute('target', '');
                    }
                } else {
                    var _a = this._getDoc().createElement('a');
                    _a.setAttribute('href', urlValue);
                    if (target.checked) {
                        _a.setAttribute('target', target.value);
                    } else {
                        _a.setAttribute('target', '');
                    }
                    el.parentNode.replaceChild(_a, el);
                    _a.appendChild(el);
                }
            } else {
                if (par && this._isElement(par, 'a')) {
                    par.parentNode.replaceChild(el, par);
                }
            }
        } else {
            //No url/src given, remove the node from the document
            el.parentNode.removeChild(el);
        }
        Dom.get(this.get('id') + '_insertimage_url').value = '';
        Dom.get(this.get('id') + '_insertimage_title').value = '';
        Dom.get(this.get('id') + '_insertimage_link').value = '';
        Dom.get(this.get('id') + '_insertimage_target').checked = false;
        Dom.get(this.get('id') + '_insertimage_width').value = 0;
        //Dom.get(this.get('id') + '_insertimage_height').value = 0;
        this._defaultImageToolbar.resetAllButtons();
        this.currentElement = [];
        this.nodeChange();
    };
	
	
};

/***********************************************************
 * _renderCreateLinkWindow
 * 
 * Override the link panel init.  Add form to prevent submit.
 * 
 ***********************************************************/
YAHOO.widget.Editor.prototype._renderCreateLinkWindow = function() {
	var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event,
    Lang = YAHOO.lang;
	
	var str = '<label for="' + this.get('id') + '_createlink_url"><strong>' + this.STR_LINK_URL + ':</strong> <input type="text" name="' + this.get('id') + '_createlink_url" id="' + this.get('id') + '_createlink_url" value=""></label>';
    str += '<label for="' + this.get('id') + '_createlink_target"><strong>&nbsp;</strong><input type="checkbox" name="' + this.get('id') + '_createlink_target" id="' + this.get('id') + '_createlink_target" value="_blank" class="createlink_target"> ' + this.STR_LINK_NEW_WINDOW + '</label>';
    str += '<label for="' + this.get('id') + '_createlink_title"><strong>' + this.STR_LINK_TITLE + ':</strong> <input type="text" name="' + this.get('id') + '_createlink_title" id="' + this.get('id') + '_createlink_title" value=""></label>';
    
    // Add form to prevent submitting parent.
    var form_el = document.createElement('form');
    form_el.id = this.get('id') + "_link_frm";
    
    var body = document.createElement('div');
    form_el.innerHTML = str;

    var unlinkCont = document.createElement('div');
    unlinkCont.className = 'removeLink';
    var unlink = document.createElement('a');
    unlink.href = '#';
    unlink.innerHTML = this.STR_LINK_PROP_REMOVE;
    unlink.title = this.STR_LINK_PROP_REMOVE;
    Event.on(unlink, 'click', function(ev) {
        Event.stopEvent(ev);
        this.unsubscribeAll('afterExecCommand');
        this.execCommand('unlink');
        this.closeWindow();
    }, this, true);
    unlinkCont.appendChild(unlink);
    form_el.appendChild(unlinkCont);
    body.appendChild(form_el);
    
    this._windows.createlink = {};
    this._windows.createlink.body = body;

    Event.on(body, 'keyup', function(e) {
        Event.stopPropagation(e);
    });
    this.get('panel').editor_form.appendChild(body);
    this.fireEvent('windowCreateLinkRender', { type: 'windowCreateLinkRender', panel: this.get('panel'), body: body });
    return body;
};


/***********************************************************
 * Wiki Page Links
 * 
 * Override the link panels for use with Wiki Pages.
 * 
 ***********************************************************/

YAHOO.widget.Editor.prototype.initWiki = function(pagelist,recentlist) {
	
	// Needed for panel
	var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event,
    Lang = YAHOO.lang;

	// AutoComplete Field data
	
	
	/**
	 *  JSON Format
	 *  [
	 *  	{'name':"page name", 'slug':"/wiki/pageslug"},
	 *  	{'name':"page name", 'slug':"/wiki/pageslug"}
	 *  ]
	 */ 
	
	var suggest_pages = new YAHOO.util.LocalDataSource(pagelist);
	suggest_pages.responseSchema.fields = ["name","slug"];
	
	var suggest_recent = new YAHOO.util.LocalDataSource(recentlist);
	suggest_recent.responseSchema.fields = ["name","slug"];
	
	var empty_url = 'http://...';
	
	// Track previous values when switching modes.
	var track = { "name": '',"url": empty_url,"external": empty_url };
	
	// Used to restore orginal existing link on exit.
	var value_set = { "name": '',"url": '',"external": '', "target":'' };
	
	
	/***********************************************************
	 * _renderCreateLinkWindow
	 * 
	 * Override the link panel init. Base html for the modal. 
	 * 
	 ***********************************************************/
	YAHOO.widget.Editor.prototype._renderCreateLinkWindow = function() {

		var link_modal = document.createElement('div');
		link_modal.id = this.get('id') + '_link_modal';
		
		/*************************************
		 * Existing Pages
		 ************************************/
	
		// Wiki Page Field
		
		var suggest_wrap = document.createElement('div');
		suggest_wrap.className = 'rm-rteLinkPageWrap';
		suggest_wrap.innerHTML = '<div class="rm-rteLinkNewMsg">Enter a title for the new page and follow the link created</div><label for="' + this.get('id') + '_wiki_page"><strong>Wiki Page:</strong></label>';
		
		var suggest_no_match = document.createElement('div');
		suggest_no_match.className = 'rm-rteLinkNoSuggest';
		suggest_no_match.innerHTML = 'Follow link created to add a new wiki page with this title';
		
		var suggest_input = document.createElement('input');
		suggest_input.setAttribute('type','text');
		suggest_input.name = this.get('id') + '_wiki_page';
		suggest_input.id = this.get('id') + '_wiki_page';
		
		var suggest_container = document.createElement('div');
		suggest_container.id = this.get('id') + '_wiki_suggest'
		suggest_container.className = 'rm-wikiSuggest';
		
		suggest_wrap.appendChild(suggest_input);
		suggest_wrap.appendChild(suggest_no_match);

		// Keep outside the form element - innerHTML causes unknown error in IE.
		link_modal.appendChild(suggest_container);
		

		// Init autocomplete
	    
		var id_prefix = this.get('id');
		var suggest;
    	$E.onAvailable(id_prefix + '_wiki_page', function(){
			suggest = new YAHOO.widget.AutoComplete(suggest_input, suggest_container, suggest_pages);
			
			// Override container positioning
			suggest.snapContainer = function() {
			    var oTextbox = this._elTextbox,
			        pos = $D.getXY(oTextbox);
			    pos[1] += $(oTextbox).offsetHeight - 1;
			    $D.setXY(this._elContainer,pos);
			};
			
			suggest_input.suggest = suggest;
			suggest.prehighlightClassName = "yui-ac-prehighlight";
			suggest.allowBrowserAutocomplete = false;
			suggest.animSpeed = 0.1;
			suggest.typeAhead = true;
			suggest.minQueryLength = 0;
			suggest.maxResultsDisplayed = 25;
			suggest.queryMatchContain = true;
			suggest.queryMatchContain = true;
			suggest.autoHighlight = false;
			
			suggest.suspend = false;
			
			suggest.formatResult = function(results, keyword, match){
	           	
				var name = results[0];
		        var index = name.toLowerCase().indexOf(keyword);
		        var prefix = name.substring(0,index);
		        var matching = name.substring(index, index+keyword.length);
		        var suffix = name.substring(index+keyword.length, name.length);
				
		        var markup = "<div class=\"rm-rteSuggestResult\">"
		        + " <span class=\"rm-suggestName\">" + prefix + "<span class=\"rm-suggestMatch\">" + matching + "</span>" + suffix 
		        + "</span></div>";
		        
		        return markup;
	           	
		    };
		    
		    
		    
		    // Action for selected page
		    suggest.itemSelectEvent.fire = function(self,item,data) {
		    	//$(id_prefix + '_wiki_page').value = data[0];
		    	$(id_prefix + '_createlink_url').value = data[1];		    	
		    };
		    
		    // Swap datasource when query exists
		    // Execute before datasource is queried
		    suggest.dataRequestEvent.fire = function(self , query , request){
		    	if( self.suspend ) return;
		    	if( query == 'undefined' || query == '' || query == null ){
		    		self.dataSource = suggest_recent;
		    	} else {
		    		self.dataSource = suggest_pages;
		    	}
		    }
		    
		    // No Matches
		    suggest.unmatchedItemSelectEvent.fire = function( self , selection ) {
		    	// Clear url field
		    	$(id_prefix + '_createlink_url').value = empty_url;
		    }

		    suggest.filterResults = function(sQuery, oFullResponse, oParsedResponse, oCallback) {

		    	// If AC has passed a query string value back to itself, grab it
		        if(oCallback && oCallback.argument && oCallback.argument.query) {
		            sQuery = oCallback.argument.query;
		        }
		        
		        var has_query = (sQuery && sQuery != "" && sQuery != "undefined");
		        
		        var oAC = oCallback.scope;
		        
		        // Only if a query string is available to match against
		        

	            // First make a copy of the oParseResponse
	            oParsedResponse = YAHOO.widget.AutoComplete._cloneObject(oParsedResponse);
	            
	            
	            var oDS = this,
	                allResults = oParsedResponse.results, // the array of results
	                filteredResults = [], // container for filtered results,
	                nMax = oAC.maxResultsDisplayed, // max to find
	                bMatchCase = (oDS.queryMatchCase || oAC.queryMatchCase), // backward compat
	                bMatchContains = (oDS.queryMatchContains || oAC.queryMatchContains); // backward compat
	                
	            // Loop through each result object...
	            for(var i=0, len=allResults.length; i<len; i++) {
	                var oResult = allResults[i];

	                // Grab the data to match against from the result object...
	                var sResult = null;
	                
	                // Result object is a simple string already
	                if(YAHOO.lang.isString(oResult)) {
	                    sResult = oResult;
	                }
	                // Result object is an array of strings
	                else if(YAHOO.lang.isArray(oResult)) {
	                    sResult = oResult[0];
	                
	                }
	                // Result object is an object literal of strings
	                else if(this.responseSchema.fields) {
	                    var key = this.responseSchema.fields[0].key || this.responseSchema.fields[0];
	                    sResult = oResult[key];
	                }
	                // Backwards compatibility
	                else if(this.key) {
	                    sResult = oResult[this.key];
	                }
	                
	                if(YAHOO.lang.isString(sResult)) {
	                    
	                    var sKeyIndex = (bMatchCase) ?
	                    sResult.indexOf(decodeURIComponent(sQuery)) :
	                    sResult.toLowerCase().indexOf(decodeURIComponent(sQuery).toLowerCase());

	                    // A STARTSWITH match is when the query is found at the beginning of the key string...
	                    if( !has_query || (!bMatchContains && (sKeyIndex === 0)) ||
	                    // A CONTAINS match is when the query is found anywhere within the key string...
	                    (bMatchContains && (sKeyIndex > -1))) {
	                        // Stash the match
	                        filteredResults.push(oResult);
	                    }
	                }
	                
	                // Filter no more if maxResultsDisplayed is reached
	                if(len>nMax && filteredResults.length===nMax) {
	                    break;
	                }
	            }
	            
	            oParsedResponse.results = filteredResults;

	            suggest_no_match.style.display = filteredResults.length < 1 ? 'block' : 'none';
	            
		        return oParsedResponse;
		    };
		    
		    $E.on(suggest_input,'click',function(){
		    	if( !suggest_input.suggest.isContainerOpen() ){
		    		suggest_input.suggest.sendQuery('');
		    	}
	    	});
		    
    	}, this);
		
		// URL Field
		
		var url_wrap = document.createElement('div');
		url_wrap.className = 'rm-rteLinkUrlWrap';
		url_wrap.innerHTML = '<label for="' + this.get('id') + '_createlink_url"><strong>URL:</strong></label>';
		
		var url_input = document.createElement('input');
		url_input.name = this.get('id') + '_createlink_url';
		url_input.id = this.get('id') + '_createlink_url';
		
		url_wrap.appendChild(url_input);
	    
		// New window checkbox
		
		var target_input = document.createElement('label');
		target_input.className = 'rm-rteLinkTarget';
		target_input.setAttribute('for',this.get('id') + '_createlink_target');
		target_input.innerHTML = '<input type="checkbox" name="' + this.get('id') + '_createlink_target" id="' + this.get('id') + '_createlink_target" value="_blank" class="createlink_target"> ' + this.STR_LINK_NEW_WINDOW ;
		

		// Mode Links
		
		var links = document.createElement('div');
		links.className = 'rm-rteLinkOptions';
		var form_id = this.get('id');
		// link actions
		var new_page_click = function(e){
			suggest.dataSource = new YAHOO.util.LocalDataSource([]);
			suggest.suspend = true;
			$(form_id + '_createlink_url').is_new_page = true;
			link_modal.className = 'rm-rteLinkNew';
			
			track.url = url_input.value;
			track.name = suggest_input.value;
			suggest.collapseContainer();			
			url_input.value = empty_url;
		};
		var ext_link_click = function(e){
			suggest.dataSource = new YAHOO.util.LocalDataSource([]);
			link_modal.className = 'rm-rteLinkExt';
			
			track.url = url_input.value;
			track.name = suggest_input.value;
			
			url_input.value = track.external;
			if( url_input.value == empty_url && !$hc(url_input,'rm-fieldDescription') ) $ac(url_input,'rm-fieldDescription');
			suggest_input.value = '';
			
		};
		
		var cancel_click = function(e){
			// change data src
			suggest.dataSource = suggest_recent;
			suggest.suspend = false;
			$(form_id + '_createlink_url').is_new_page = false;
			
			url_input.value = track.url;
			suggest_input.value = track.name;
			
			link_modal.className = '';
			
			suggest_input.focus();
			suggest_input.suggest.sendQuery(suggest_input.value);
		};
		var wiki_click = function(e){
			// change data src
			suggest.dataSource = suggest_recent;
			
			track.external = url_input.value;
			
			url_input.value = track.url;
			suggest_input.value = track.name;
			
			link_modal.className = '';

			suggest_input.focus();
			suggest_input.suggest.sendQuery(suggest_input.value);
		};
		
		var new_pg = document.createElement('span');		
		new_pg.innerHTML = 'New Wiki Page';
		new_pg.className = 'rm-rteNewPageLink';
		$E.on( new_pg, 'click', new_page_click );
		
		
		var ext_link = document.createElement('span');
		ext_link.innerHTML = 'External Link';
		ext_link.className = 'rm-rteExternalLink';
		$E.on( ext_link, 'click', ext_link_click );
		
		var cancel = document.createElement('span');
		cancel.innerHTML = 'Cancel';
		cancel.className = 'rm-rteCancelLink';
		$E.on( cancel, 'click', cancel_click );
		
		var wiki_pg = document.createElement('span');
		wiki_pg.innerHTML = 'Wiki Page Link';
		wiki_pg.className = 'rm-rteWikiPageLink';
		$E.on( wiki_pg, 'click', cancel_click );
		
		links.appendChild(new_pg);
		links.appendChild(wiki_pg);
		links.appendChild(ext_link);
		links.appendChild(cancel);
		
	    // Add form to prevent submitting parent.
	    var form_el = document.createElement('form');
	    form_el.id = this.get('id') + "_link_frm";
	    form_el.style.overflow = 'visible';
	    
	    // Buttons
	    var tbar_el = document.createElement('div');
	    tbar_el.id = this.get('id') + '_tbar';
        Dom.addClass(tbar_el,"rm-rteLinkButtons");
        
        var tbar = new YAHOO.widget.Toolbar(tbar_el, {
        	buttonType: 'advanced',
        	buttons: [
        	            { type: 'button', label: 'Link', value: 'addlink' },
        	            { type: 'button', label: 'Remove', value: 'removelink' }
        	 ]
        });
	    
        tbar.on('buttonClick', function(o) {
        	var value = o.button.value;
        	if( value == 'addlink' ) {
        		
        		// Process link and update value_set.  Close window will apply to element.
        		
        		var url = $(this.get('id') + '_createlink_url');
        		var target = $(this.get('id') + '_createlink_target');
        		var title = $(this.get('id') + '_wiki_page');

        		var is_new_page = $(this.get('id') + '_createlink_url').is_new_page 
    			|| (url && url.value && url.value == empty_url && title.value != null && title.value.length > 0 );

        		
        		if( is_new_page || ( url && url.value && url.value.indexOf(empty_url) != 0 ) ) {
        			var urlValue = url.value; 
        			if ( is_new_page ) { 
        				var alias = convToSixentCharset(title.value);
        				alias = cleanAlias(alias); 
        				urlValue = '/wiki/'+ alias;				 
        			} else { 
        				if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
        				    if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) {
        				        //Found an @ sign, prefix with mailto:
        				        urlValue = 'mailto:' + urlValue;
        				    } else {
        				        // :// not found adding
        				        if (urlValue.substring(0, 1) != '#') {
        				            urlValue = 'http:/'+'/' + urlValue;
        				        }
        				        
        				    }
        				}
        		    }
        			value_set.url = urlValue;	
        			value_set.target = target.checked ? target.value : '';
        			value_set.name = title.value != null ? title.value : '';

        		} else {
        			value_set = { "name": '', "url": '', "target": '' };
        		}
        		
        		this.unsubscribeAll('afterExecCommand');
        		this.closeWindow();
        	} else if( value == 'removelink') {
    	        this.unsubscribeAll('afterExecCommand');
    	        this.execCommand('unlink');
    	        this.closeWindow();        		
        	}
        	
        },this,true);
        
        var body = document.createElement('div');
	    form_el.appendChild(links);
	    form_el.appendChild(suggest_wrap);
	    form_el.appendChild(url_wrap);
	    form_el.appendChild(tbar_el);
	    form_el.appendChild(target_input);
        
        link_modal.appendChild(form_el);
	    body.appendChild(link_modal);
	    
	    
	    this._windows.createlink = {};
	    this._windows.createlink.body = body;

	    Event.on(url_input, 'blur', function() {
            var url = Dom.get(this.get('id') + '_createlink_url');
            if (this._isLocalFile(url.value)) {
                //Local File throw Warning
                Dom.addClass(url, 'warning');
                this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
            } else {
                Dom.removeClass(url, 'warning');
                this.get('panel').setFooter(' ');
            }
        }, this, true);
	    
	    $E.on(url_input,'focus',function(){	        		
    		if( $hc(url_input,'rm-fieldDescription') ){
    			$rc(url_input,'rm-fieldDescription');
    			url_input.value = '';
    		}
    	});
	    
	    Event.on(body, 'keyup', function(e) {
	        Event.stopPropagation(e);
	    });
	    this.get('panel').editor_form.appendChild(body);
	    this.fireEvent('windowCreateLinkRender', { type: 'windowCreateLinkRender', panel: this.get('panel'), body: body });

	    return body;

	};

	/***********************************************************
	 * _renderCreateLinkClick
	 * 
	 * Populates the link modal.  Add features for Wiki.
	 * 
	 ***********************************************************/
	YAHOO.widget.Editor.prototype._handleCreateLinkClick = function() {

		var el = this._getSelectedElement();
	    if (this._isElement(el, 'img')) {
	        this.STOP_EXEC_COMMAND = true;
	        this.currentElement[0] = el;
	        this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar });
	        this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this });
	        return false;
	    }
	    if (this.get('limitCommands')) {
	        if (!this.toolbar.getButtonByValue('createlink')) {
	            return false;
	        }
	    }
	    
	    this.on('afterExecCommand', function() {

	        var win = new YAHOO.widget.EditorWindow('createlink', {
	            width: '430px'
	        });
	        
	        var el = this.currentElement[0],
	            url = '',
	            title = '',
	            target = '',
	            localFile = false,
	            isExternal = false;
	        if (el) {
	            win.el = el;
	            if (el.getAttribute('href', 2) !== null) {
	                url = el.getAttribute('href', 2);
	                isExternal = url.length > 0 && url.indexOf('/wiki/') != 0;
	                if (this._isLocalFile(url)) {
	                    //Local File throw Warning
	                    win.setFooter(this.STR_LOCAL_FILE_WARNING);
	                    localFile = true;
	                } else {
	                    win.setFooter(' ');
	                }
	            }
	            if (el.getAttribute('title') !== null) {
	                title = el.getAttribute('title');
	            }
	            if (el.getAttribute('target') !== null) {
	                target = el.getAttribute('target');
	            }
	        }
	        var body = null;
	        if (this._windows.createlink && this._windows.createlink.body) {
	            body = this._windows.createlink.body;
	        } else {
	            body = this._renderCreateLinkWindow();
	        }
	
	        win.setHeader(this.STR_LINK_PROP_TITLE);
	        win.setBody(body);

			var suggest = $(this.get('id') + '_wiki_page').suggest;
			
			// Preserve original
			value_set = { "name": title, "url": url, "target": target };
			
			
			
			if( isExternal ){
				
				track = { "name": '',"url": empty_url,"external": url };
				
				$(this.get('id') + '_wiki_page').value = '';
				$(this.get('id') + '_createlink_url').value = url;
				$(this.get('id') + '_link_modal').className = 'rm-rteLinkExt';
				
			} else {
				
				track = { "name": title, "url": url.length > 0 ? url : empty_url,"external": empty_url };
				
				suggest.dataSource = suggest_recent;

				$(this.get('id') + '_link_modal').className = '';
			
				if( title.length > 0 ){	        
		        	$(this.get('id') + '_wiki_page').value = title;	        	
		        } else {
		        	var wiki_el = $(this.get('id') + '_wiki_page');
		        	wiki_el.value = '';
		        	suggest.dataSource = suggest_recent;
		        	
		        	Event.onAvailable(this.get('id') + '_wiki_page', function() {
		        		var focus_suggest = new Function(
		        				'try {'	                	
			                    + '$("' + this.get('id') + '_wiki_page' + '").focus();'
			                    + '$("' + this.get('id') + '_wiki_page' + '").suggest.sendQuery("");'			                    
			                + '} catch (e) {}'
			            );
			            window.setTimeout(focus_suggest, 50);
			        },this,true);
		        	
		        	
		        }
				
				if( url.length > 0 ){	        
		        	$(this.get('id') + '_createlink_url').value = url;	        
		        } else {
		        	var url_el = $(this.get('id') + '_createlink_url');	        	
		        	url_el.value = empty_url;
		        }
				
			}
	        

	        $(this.get('id') + '_createlink_target').checked = ((target) ? true : false);
	
	        Event.onAvailable(this.get('id') + '_createlink_url', function() {
	            
	            if (this._isLocalFile(url)) {
	                //Local File throw Warning
	                Dom.addClass(this.get('id') + '_createlink_url', 'warning');
	                this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING);
	            } else {
	                Dom.removeClass(this.get('id') + '_createlink_url', 'warning');
	                this.get('panel').setFooter(' ');
	            }
	            
	        }, this, true);

	        this.openWindow(win);
	
	    });

	};
	/***********************************************************
	 * _handleCreateLinkWindowClose
	 * 
	 * Executes when link modal is closed.  Add features for Wiki.
	 * 
	 ***********************************************************/
	YAHOO.widget.Editor.prototype._handleCreateLinkWindowClose = function() {

	    var el = arguments[0].win.el;
	    
		if( value_set.url && value_set.url.length > 0 ){	
			el.setAttribute('href', value_set.url);
			el.setAttribute('target', value_set.target);
			el.setAttribute('title', value_set.name);
		} else {
	        var _span = this._getDoc().createElement('span');
	        _span.innerHTML = el.innerHTML;
	        Dom.addClass(_span, 'yui-non');
	        el.parentNode.replaceChild(_span, el);
	    }
		
	    Dom.removeClass(url, 'warning');
	    $(this.get('id') + '_createlink_url').value = '';
	    $(this.get('id') + '_createlink_url').is_new_page = false;
	    $(this.get('id') + '_createlink_title').value = '';
	    $(this.get('id') + '_createlink_target').checked = false;
	    this.nodeChange();
	    this.currentElement = [];
	    
	};
	/** End of WikiLink **/
};


/***********************************************************
 * Compact Mode - Toolbar toggle
 * 
 * Toggles the additional toolbar options
 *  
 **********************************************************/
YAHOO.widget.Editor.prototype.initCompact = function() {
	
	var show_more = false;
	
	this.on('toolbarLoaded', function() {

		this.toolbar.on('togglemoreClick', function() {

			show_more = !show_more;
			
			var button = this.toolbar.getButtonByValue('togglemore');
			button.set('label', show_more ? 'Less' : 'More');
			
			var more_row = this.toolbar._buttonGroupList['morerow'].parentNode;
			var anim_conf = {};
			if( show_more ){
				more_row.style.visibility = 'visible';
				anim_conf = {height: { to: 27 }, opacity: {from: 0, to: 1}};
			} else {
				anim_conf = {height: { to: 0 }, opacity: {from: 1, to: 0}};
			}
			
			var anim_row = new YAHOO.util.Anim(more_row, anim_conf, .3, YAHOO.util.Easing.easeBoth);
			if( !show_more ){ 
				anim_row.onComplete.subscribe(function() {
					more_row.style.visibility = 'hidden';
				});
			}
			anim_row.animate();

		}, this, true);
		
	}, this, true);
}

/***********************************************************
 * Code Editor Plugin
 * 
 * - Swaps the view to show the textarea
 * - Syncs content when changing views
 *  
 **********************************************************/
YAHOO.widget.Editor.prototype.initCodeEditor = function() {
	
	this.on('toolbarLoaded', function() {

		this.toolbar.on('editcodeClick', function() {

			this.setCodeEdit(!this.html_editor);
		
			return false;

		}, this, true);

		this.on('cleanHTML', function(ev) {
			this.get('element').value = ev.html;
		}, this, true);
		
	}, this, true);
	
	// Update styling on textarea
	this.on('afterRender', function() {
		this.get("iframe").setStyle("position","absolute");
		var wrapper = this.get('editor_wrapper');
		wrapper.appendChild(this.get('element'));
		this.setStyle('width', '100%');
		this.setStyle('height', '100%');
		this.setStyle('visibility', '');
		this.setStyle('top', '');
		this.setStyle('left', '');
		this.setStyle('position', 'absolute');
		this.addClass('editor-hidden');
	}, this, true);
	
};

/***********************************************************
 * setCodeEdit(boolean enable)
 * 
 * External method to set code edit mode.
 * Useful for sync between full and normal modes
 * 
 ***********************************************************/
YAHOO.widget.Editor.prototype.setCodeEdit = function(enable) {

	var ta = this.get('element');
	var iframe = this.get('iframe').get('element');

	if( !enable ) {
		this.html_editor=false;
		this.toolbar.set('disabled', false);
		this.toolbar.selectButton('editcode');
		this.setEditorHTML(ta.value);
		if (!this.browser.ie) {
			this._setDesignMode('on');
		}
		$D.removeClass(iframe, 'editor-hidden');
		$D.addClass(ta, 'editor-hidden');	
		this._focusWindow();
	} else {			
		this.html_editor=true;
		this.cleanHTML();
		$D.addClass(iframe, 'editor-hidden');
		$D.removeClass(ta, 'editor-hidden');
		this.toolbar.set('disabled', true);
		this.toolbar.getButtonByValue('editcode').set('disabled', false);
		this.toolbar.getButtonByValue('fullmode').set('disabled', false);
		this.toolbar.selectButton('editcode');
	}

};

/*******************************************************
 * Fullscreen Mode
 * 
 * Creates a cloned editor using RamiusRTE.fullConfig
 * Content synchronized when changing between modes
 * 
 *******************************************************/

/*******************************************************
 * initFullEditClone( parent editor )
 * 
 * Creates a full mode editor linked to the parent
 * 
 *******************************************************/
 
YAHOO.widget.Editor.prototype.resize = function(event,editor) {
	try { 
	
	var toolbar_el = editor.toolbar.get('cont').parentNode.parentNode;
		
	var container = editor.get('element_cont');		
	var edit_el = $D.getElementsByClassName( 'first-child' , 'div' , container )[0];
	
	edit_el.style.height = '100%'; // don't use $D.style here. Triggers event in IE.
	var height = ($D.getViewportHeight() - toolbar_el.offsetHeight) + 'px';
	 
	$D.setStyle(editor.get('iframe'),'height', height);
	} catch ( ex ) {}
}
 
YAHOO.widget.Editor.prototype.initFullEditClone = function(parent) {
	// This is used internally to initialize the fullscreen clone.
	var parent_edit = parent;
	
	// Apply styles once rendered
	this.on('afterRender',function(){
			
		var toolbar_el = this.toolbar.get('cont').parentNode.parentNode;
		
		var container = this.get('element_cont');		
		var edit_el = $D.getElementsByClassName( 'first-child' , 'div' , container )[0];
		
		$D.setStyle(edit_el, 'zIndex', '99998');
		$D.setStyle(edit_el, 'position', 'fixed');
		$D.setStyle(edit_el, 'top', '0px');
		$D.setStyle(edit_el, 'left', '0px');
		$D.setStyle(edit_el, 'width', '100%');
		$D.setStyle(edit_el, 'background-color', '#FFFFFF');
		
		edit_el.style.height = '100%'; // don't use $D.style here. Triggers event in IE.
		var height = ($D.getViewportHeight() - toolbar_el.offsetHeight) + 'px';
		
		
		$D.setStyle(this.get('iframe').get('parentNode'),'height','100%');
		$D.setStyle(this.get('iframe'),'height', height); 
		
	}, this, true);
	
	this.on('editorContentLoaded',function(){
		// set initial content once ready
		this.setContent(parent_edit.getContent());
		this.get('element').value = parent_edit.get('element').value; 
		this.setCodeEdit(typeof(parent_edit.html_editor) == 'boolean' && parent_edit.html_editor);
	},this,true);
	
	// Always show full button pressed.
	this.on('afterNodeChange', function() { 
		this.toolbar.selectButton(this.toolbar.getButtonByValue('fullmode')); 
	}, this, true);
	
	// Update dimensions on resize
	this.on('heightChange',function(){
		// Correct height on each redraw
		var toolbar_el = this.toolbar.get('cont').parentNode.parentNode;
		$D.setStyle(this.get('iframe'),'height', ($D.getViewportHeight() - toolbar_el.offsetHeight) + 'px');		
	}, this, true);
	
	// Init mode button - Sync parent and hide full editor
	this.on('toolbarLoaded', function() {

		this.toolbar.selectButton(this.toolbar.getButtonByValue('fullmode'));
		
		this.toolbar.on('fullmodeClick', function() {
	
			parent_edit.setContent(this.getContent());
			parent_edit.get('element').value = this.get('element').value; 
			parent_edit.setCodeEdit(typeof(this.html_editor) == 'boolean' && this.html_editor);

			var container = this.get('element_cont');			
			// IE Fix - needs actual element			
			container = $D.get(container);
			
			container.style.display = 'none';
			$D.setStyle(document.body, 'overflow', '');

		}, this, true);

		// Refresh toolbar settings for code edit.
		if( this.html_editor ) {
			this.toolbar.set('disabled', true);
			this.toolbar.getButtonByValue('editcode').set('disabled', false);
			this.toolbar.getButtonByValue('fullmode').set('disabled', false);
			this.toolbar.selectButton('editcode');
		}
		
	}, this, true);
	
	
};

/*******************************************************
 * initFullEditor
 * 
 * Setup button to enter full mode.
 * Creates full mode editor if not already created.
 * 
 *******************************************************/
YAHOO.widget.Editor.prototype.initFullEditor = function() {
	// Set full edit button
	// Creates full edit clone when needed.
	 
	var full_editor;

	this.on('afterNodeChange', function() { 
		this.toolbar.deselectButton(this.toolbar.getButtonByValue('fullmode')); 
	}, this, true);

	this.on('toolbarLoaded', function() {

		this.toolbar.on('fullmodeClick', function() {
			
			
			if( !full_editor ){
				full_editor = RamiusRTE._initFull(this);
			} else {
				// Sync to full edit				
				full_editor.setContent(this.getContent());
				full_editor.get('element').value = this.get('element').value; 
				full_editor.setCodeEdit(typeof(this.html_editor) == 'boolean' && this.html_editor);
			}
			
			var container = full_editor.get('element_cont');
			// IE Fix - needs actual element			
			container = $D.get(container);

			container.style.display = 'block';
			$D.setStyle(document.body, 'overflow', 'hidden');

		}, this, true);

	}, this, true);

};

/********************************************************************************
 * Paste cleanup
 * 
 * Cleanup on paste
 * Based on: http://richtextcleanpaste.codeplex.com/
 * 
 * On Paste - pasteDetect determines if action is needed
 * pasteDetect opens modal if action is needed.
 * Modal then calls back to scrubPaste with specific action
 * 
 * If no action needed, execute scrubPaste with no action to clean up defaults
 * 
 ********************************************************************************/

YAHOO.widget.Editor.prototype.initPaste = function(){

	this.on('editorContentLoaded',function(){
		
		var doc = this._getDoc();

	    if ( this.browser.ie ) {
	        // IE events
		    $E.on(doc, 'dragstart', function(e){$E.stopEvent(e);});
		    $E.on(doc, 'dragend', function(e){$E.stopEvent(e);});
	    } 
	    	
	    $E.on(doc.body, 'beforepaste', function(e){$E.stopEvent(e);}, this, this);	    
	    this.on('editorKeyDown', this.pasteKeyDown, this, true);	    
	    $E.on(doc.body, 'paste', this.handlePaste, this, this);
	    
	},this,true);
	
	YAHOO.widget.Editor.prototype.handlePaste = function(e){

		var editor = this;
	
		if( this.pasting ){
		    var scrub = function(){
		    	editor.pasteDetect(e,editor);
		    };
		    setTimeout(scrub, 10);			
		} else {
			// Unsupported paste action.
			$E.stopEvent(e);
			
			var isMac = (navigator ? navigator.appVersion.indexOf('Mac') != -1 : false);
			
			var modal = ModalManager.getModal();

			var onShow = function(){					
				modal.getOverlay().style.zIndex = '99999';
				modal.getModal().style.zIndex = '99999';
			};
			modal.editor = editor;
			modal.openUrl('/support/misc/editor_paste.jsp?invalid=' + (isMac ? 'mac' : 'pc') + (editor.browser.ie ? '&context' : ''),'get',true);
    	
			//Adjust z-index for stacked modals (full screen pod edit).				
			setTimeout(onShow, 500);
		}
		this.pasting = false;
		
	};
	
	YAHOO.widget.Editor.prototype.handlePasteContext = function(e){

		var editor = this;

		var isTable = function(el){
			if( el ){
				if( el.tagName && el.tagName.toLowerCase() == 'table' ) return true;
				if (el.parentNode && el.parentNode.tagName) {
					if( el.parentNode.tagName.toLowerCase() == 'table' ) return true;
					else return isTable(el.parentNode);
				}
			}
			return false;			
		};
		
		var src_el = e.target || e.srcElement;
		
		// Ignore for table context menu.
		if( src_el && isTable(src_el) ) return;
	};
	
	YAHOO.widget.Editor.prototype.handleBeforePaste = function(e){
		// Wrap pasted in a temp container
	
		// Remove any existing container
		this.pasting = true;
		
    	var tmp = this._getDoc().getElementById('rm-scrub');
    	if ( tmp ){
    		if( tmp.innerHTML == '' || tmp.innerHTML == '&nbsp;' ){
    			tmp.parentNode.removeChild(tmp);
    		} else {
	    		tmp.removeAttribute('id');
	    		tmp.removeAttribute('style');
    		}
    	}
 		
        this._createCurrentElement('div');
        // IE 8 needs additional focus on node.
        this._selectNode(this.currentElement[0]);
        this.currentElement[0].id = 'rm-scrub';
        this.currentElement[0].innerHTML = '&nbsp;';
        this._selectNode(this.currentElement[0]);

	};
	YAHOO.widget.Editor.prototype.pasteKeyDown = function(e) {
		
		var editor = this;
	    var vkey = 86
	    var vInsertKey = 45
	    var isMac = (navigator ? navigator.appVersion.indexOf('Mac') != -1 : false);

	    // Check to see if CTRL + V is pressed
	    if ((!isMac && e.ev.keyCode == vkey && e.ev.ctrlKey) ||
	        (!isMac && e.ev.keyCode == vInsertKey && e.ev.shiftKey) ||
	        (isMac && e.ev.keyCode == vkey && e.ev.metaKey)) {
	    	
	    	editor.handleBeforePaste(e);

	    }
	};
	
	YAHOO.widget.Editor.prototype.pasteDetect = function(e,editor){

		var tmp = editor._getDoc().getElementById('rm-scrub');
	
		if( tmp ){

			tmp.style.display = 'inline';
		    var pasted = tmp.innerHTML;

		    var close_action = function() {
		    	editor.scrubPaste(e,editor);
		    	getRmModal().hide();
		    };
		    
		    // Detect formatted
		    if( pasted.match(/<[^>]*style=[^>]*>/gi) || pasted.match(/<[^>]*class=[^>]*>/gi) ) {
		    	
		    	var modal = ModalManager.getModal();
		    	
				var onShow = function(){					
					modal.getOverlay().style.zIndex = '99999';
					modal.getModal().style.zIndex = '99999';
				};
		    	modal.editor = editor;
		    	modal.openUrl('/support/misc/editor_paste.jsp?editor_id='+editor.get('id'),'get',true);
				modal.setModalCloseAction(close_action);
				
				//Adjust z-index for stacked modals (full screen pod edit).				
				setTimeout(onShow, 500);
				
		    } else {
		    	// Clean up paste wrapper and MS Office tags
		    	editor.scrubPaste(e,editor);
		    } 

		}
		
	};
	
	YAHOO.widget.Editor.prototype.scrubPaste = function(e,editor,action){
		var tmp = editor._getDoc().getElementById('rm-scrub');

		if( tmp ){

			var clean = tmp.innerHTML;

			if( clean && clean != '_' && clean != '' ){
			
				// Remove browser injected spaces and lines
				// Prevents clean-up from adding extra breaks and nbsp.
				clean = clean.replace(/[\n\r]/g,' ');
		    	clean = clean.replace(/<font[^>]*>[\s]*?<\/font>/gi, '');
		    	clean = clean.replace(/<span[^>]*>[\s]*?<\/span>/gi, '');
				
			    // Detect word 
			    if( clean.indexOf('MsoNormal') > 0 || clean.indexOf('<o:') > 0 || clean.indexOf('<w:') > 0 ) {			    	
			    	clean = editor.filter_msword(clean);
			    }
				
				if( action == 0 ){
					clean = editor.scrubStyles(clean);
				} else if( action == 1 ){
					// plain text
					clean = clean.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
					clean = clean.replace(/<(div|h.|li)[^>]*>/gi, '');
					clean = clean.replace(/<\/(div|h.|li)>/gi,this.browser.ie ? '<br>' : '\n');
										
					clean = Ramius.textUtils.unescapeHtml(clean);
					
					if( !this.browser.ie ){
						// Add line breaks back.
						clean = clean.replace(/\n/g,'<br>');
					}
				}	    
		    
				if ( !editor.browser.webkit ) {
			        // IE & Firefox
			        tmp.parentNode.removeChild(tmp);
			        editor.execCommand('inserthtml', clean);
			    } else {
			    	tmp.innerHTML = clean;
			        tmp.removeAttribute('style');
			        var marker = editor._getDoc().createElement('span');
			        marker.id = 'rm-scrubEnd';			        
			        tmp.appendChild(marker);
			        
			        var html = editor.getEditorHTML();
			        html = html.replace(/<div[^>]*id="rm-scrub"[^>]*>/gi, '');
			        html = html.replace(/<span[^>]*id="rm-scrubEnd"[^>]*>[\s]*<\/span><\/div>/gi, '');
			        editor.setEditorHTML(html);
			    }
				
			} else {
				tmp.parentNode.removeChild(tmp);
			}
		    
		}
	};
	
	YAHOO.widget.Editor.prototype.scrubStyles = function(html){
		html = html.replace( /<style[^>]*>[\s\S]*?<\/style>/gi, '');
		html = html.replace( /style\s*=\s*"[^"]*"/gi, '');
		html = html.replace( /class\s*=\s*"[^"]*"/gi, '');
		return html;
	};
	
	this.on('editorContentLoaded', function() {

		// Add context menu for IE only
		if( !this.browser.ie ) return;
		
	    var editMenuItems = [
	        { text: "Cut" },
	        { text: "Copy" },
	        { text: "Paste"}
	    ];

    	this.editMenu = new YAHOO.widget.ContextMenu("editMenu-" + this.get('id'), {
	        itemdata: editMenuItems,
	        clicktohide: true,
	        trigger: this._getDoc(), 
	        container: this.get('iframe').get('parentNode'),
	        lazyload: true,
	        editor: this
	    });

    	this.on('editorClick', function(){
    		// Editor traps clicks
    		// Hide context menu manually on custom editor click event.    		
    		if( this.editMenu.visible ) this.editMenu.hide();
    	},this,true);
    	
    	this.editMenu.triggerContextMenuEvent.subscribe( function(type,args){
    		// Set position based on click position    		
    		var event = args[0];
    		var editor_xy = $D.getXY(this.cfg.config.container.value);
    		this.pos_xy = [editor_xy[0] + event.clientX, editor_xy[1] +  event.clientY];
    	});
    	
    	this.editMenu.showEvent.subscribe( function(){
    		// Move to position set by context event.    		
    		if( typeof(this.parent) == 'undefined' ){
    			this.moveTo(this.pos_xy[0],this.pos_xy[1]);
    		}
    		// flag as visible.  clicking in the editor will close the menu when visible
    		var menu = this;
    		var setVisible = function(){
    			menu.visible = true;	
    		};
    		setTimeout(setVisible, 100);
    	});

    	this.editMenu.hideEvent.subscribe( function(){
    		this.visible = false;
    	});
    	
    	this.editMenu.subscribe("render", function(){    		
    		// Handle context menu
    		// Only subscribe root menu. Prevent each sub-menu from adding event.
    		if( typeof(this.parent) == 'undefined' ){
    			
    			this.subscribe("click", function(e, args){

			    	var menu_item = args[1],
			    	target = this.contextEventTarget, 
			    	table_cell,
			    	cell_idx = [-1,-1]; // cell_idx = [row,col] 
			    	var parent = menu_item.parent ? menu_item.parent : null;

			    	var editor = this.cfg.initialConfig.editor;
			    	var doc = editor._getDoc();
	    			// Menu selects
	    			switch(menu_item.index){
		    			case 0:     // Cut
		    				if( editor._getDoc().queryCommandSupported('cut') ){
		    					editor.execCommand('cut');
		    				}
		    				break;
		    			case 1:     // Copy
		    				if( editor._getDoc().queryCommandSupported('copy') ){
		    					editor.execCommand('copy');
		    				}
		    				break;
		    			case 2:     // Paste 
		    				if( editor._getDoc().queryCommandSupported('paste') ){
		    					editor.handleBeforePaste(e);
		    					editor.execCommand('paste');
		    				}
		    				break;
	    			}
			    	
			    },this,true);
    		}
    	}); 
	    
	}, this, true);
	
};

// MS Word filter
// Based off filter_msword.  Used for pasted selection.
// More aggressive than general cleanup.

YAHOO.widget.Editor.prototype.filter_msword = function(html){
	
	if (!this.get('filterWord')) {
        return html;
    }

    //Remove the ms o: tags
    html = html.replace(/<o:p>\s*<\/o:p>/g, '');
    html = html.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;');

    // Ramius modification - handle nested entries    
	//Remove the ms w: and o: tags
	
    // short hand entries
    html = html.replace( /<[wo]:[^>]*\/>\s*/gi, '');
    // full entries
    html = html.replace( /<[wo]:[^>]*>[\s\S]*?<\/[wo]:[^>]*>\s*/gi, '');
    // Left over nested entries    
    html = html.replace( /<\/?[wo]:[^>]*>\s*/gi, '');
    
    //Remove mso-? styles.
    html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, '');

    //Remove more bogus MS styles.
    html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, '');
    html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"");
    html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, '');
    html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"");
    html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"");
    html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" );
    html = html.replace( /\s*tab-stops:[^;"]*;?/gi, '');
    html = html.replace( /\s*tab-stops:[^"]*/gi, '');

    //Remove XML declarations
    html = html.replace(/<\\?\?xml[^>]*>\n*/gi, '');

    //Remove lang
    html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");

    //Remove language tags
    html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3");

    //Remove onmouseover and onmouseout events (from MS Word comments effect)
    html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3");
    html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3");
    
    
    // Ramius - Additional cleanup.

    // Left over XML blocks
    html = html.replace( /<xml[^>]*>\s*<\/xml>\s*/gi, '');

    // Left over empty condition blocks
    html = html.replace( /<!--\[if[^\]]*\]>\s*<!\[endif\]-->\s*/gi, '');
    
    // Local file links
    html = html.replace( /<link[^>]*href="file:\/\/localhost\/[^>]*>\s*/gi, '');
    
    // Clean fake lists - added nbsps and bullet characters
    html = html.replace( /<!--\[if\s!supportLists\]-->[\s\S]*?<!--\[endif\]-->\s*/gi, '');
        
    // All meta tags
    html = html.replace( /<meta[^>]*>\s*/gi, '');

    // Remove empty P tags and convert others to DIV
    html = html.replace( /<p[^>]*>&nbsp;<\/p>\s*/gi, '<br>');
    html = html.replace( /<p[^>]*>\s*<\/p>\s*/gi, '');
    html = html.replace( /<p/gi, '<div');
    html = html.replace( /<\/p>/gi, '</div>');  
    
    // Office 2011 comment blocks
    html = html.replace( /<!--[\s\S]*?\/\* Font Definitions \*\/[\s\S]*?-->\s*/gi,'');
    
    return html;
};

/*************************************************
 * Fix text selection for IE 9.
 * 
 * IE 9 now uses the proper range object
 * Override YUI method for setting the selected node
 *************************************************/
YAHOO.widget.Editor.prototype._selectNode = function(node, collapse) {
    if (!node) {
        return false;
    }
    var sel = this._getSelection(),
        range = null;

    // Ramius fix - No longer valid for IE 9. Use standard createRange.
    if (this.browser.ie && this.browser.ie < 9) {
//  if (this.browser.ie) {
        try { //IE freaks out here sometimes..
            range = this._getDoc().body.createTextRange();
            range.moveToElementText(node);
            range.select();
        } catch (e) {
        }
    } else if(this.browser.ie) {
    	// IE 9 support
    	sel = this._getDoc().getSelection();
    	sel.selectAllChildren(node);
    } else if (this.browser.webkit) {
        if (collapse) {
		    sel.setBaseAndExtent(node, 1, node, node.innerText.length);
        } else {
		    sel.setBaseAndExtent(node, 0, node, node.innerText.length);
        }
    } else if (this.browser.opera) {
        sel = this._getWindow().getSelection();
        range = this._getDoc().createRange();
        range.selectNode(node);
        sel.removeAllRanges();
        sel.addRange(range);
    } else {
        range = this._getDoc().createRange();
        range.selectNodeContents(node);
        sel.removeAllRanges();
        sel.addRange(range);
    }
    //TODO - Check Performance
    this.nodeChange();
};


/*******************************************************
 * Content update overrides
 * 
 * 
 *******************************************************/
YAHOO.widget.Editor.prototype.setContent = function(content) {
	this.setEditorHTML(content);
};
YAHOO.widget.Editor.prototype.getContent = function() {
	// backwards compat...
	return this.saveHTML();
};
YAHOO.widget.Editor.prototype.saveHTML = function() {

	if (this.html_editor) {
		var ta = this.get('element');
		this.setEditorHTML(ta.value);
	}

    var html = this.cleanHTML();
    if (this._textarea) {
        this.get('element').value = html;
    } else {
        this.get('element').innerHTML = html;
    }
    if (this.get('saveEl') !== this.get('element')) {
        var out = this.get('saveEl');
        if (Lang.isString(out)) {
            out = Dom.get(out);
        }
        if (out) {
            if (out.tagName.toLowerCase() === 'textarea') {
                out.value = html;
            } else {
                out.innerHTML = html;
            }
        }
    }

    return html;
};

/*******************************************************
 * Table Plugin
 * 
 * Based on:
 * http://garbageburrito.com/blog/entry/1070621/table-editor-for-yuis-rich-text-editor
 * 
 ******************************************************/
YAHOO.widget.Editor.prototype.initTableEditor = function() {
	
	this.tableMenu = null;

	// Static Table functions.
	// Add to prototype instead of each instance
	
	YAHOO.widget.Editor.prototype.Table = {
		
			/* Find Parent Table */	
			get: function(el) {
				if( !el ) return;
				if( el.tagName && el.tagName.toLowerCase() == 'table' ) return el;
				if (el.parentNode && el.parentNode.tagName) {
					if( el.parentNode.tagName.toLowerCase() == 'table' ) return el.parentNode;
					else return YAHOO.widget.Editor.prototype.Table.get(el.parentNode);		
				}
			},
			/* Create a new table */
			insert: function(el){
				// populate table element with content
				// use editor function to create initial table tag in the editor.
				
				el.setAttribute('cellpadding',0);
				el.setAttribute('cellspacing',0);
				el.style.borderCollapse = 'collapse';
				el.style.width = '100%';
							
				for( var i = 0; i < 3; i++){
					var row = el.insertRow(-1);
					for( var j = 0; j < 3; j++){
						row.insertCell(-1);	
					}
				}

			},
			/* Change Columns */
			columns: function(table,value){
				if( !table || table.tagName.toLowerCase() != 'table') return;
			
			    var row_count = table.getElementsByTagName('tr').length;
			    var col_count = table.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
	
			    if( value < col_count){
			    	for( var i = col_count - 1; i >= value; i-- ){
			    		var rows = table.getElementsByTagName('tr');
			    		for( var j = 0; j < rows.length; j++ ){
			    			rows[j].deleteCell(i);
			    		}
			    	}
			    } else if( value > col_count ){
			    	for( var i = col_count; i < value; i++ ){
			    		YAHOO.widget.Editor.prototype.Table.Column.insert(table,-1);
			    	}
			    }
			},
			
			/* Change Rows */
			rows: function( table, value ){
				var row_count = table.getElementsByTagName('tr').length;
				var col_count  = table.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
	
				if( value < row_count ){
					for( var i = row_count - 1; i >= value; i-- ){
						table.deleteRow(i);
					}
				} else if( value > row_count ){
					for( var i = row_count; i < value; i++ ){
						YAHOO.widget.Editor.prototype.Table.Row.insert(table,-1);
					}
				}
			},
			remove: function( table ){
				table.parentNode.removeChild(table);
			},
			border: function( table, width, style, color ){

				var w = width ? width + 'px' : (table.style ? table.style.borderWidth : '0px');
				var s = style || (table.style ? table.style.borderStyle : 'solid');
				var c = color ? '#' + color : (table.style ? table.style.borderColor : '#000000');

				var cell_val;

				if( w && w != '0px' ){
					var cell_val = w + ' ' + ( s || 'solid' ) + ' ' + ( c || '#000000' );

					$D.setStyle(table,'border-width',w);
					$D.setStyle(table,'border-style',s || 'solid');
					$D.setStyle(table,'border-color',c || '#000000');
					
					YAHOO.widget.Editor.prototype.Table.cellstyle(table,'border', cell_val ? cell_val : null );
					
				} else {

					$D.setStyle(table,'border-width','');
					$D.setStyle(table,'border-style','');
					$D.setStyle(table,'border-color','');						
					
					YAHOO.widget.Editor.prototype.Table.cellstyle(table,'border', null );
					YAHOO.widget.Editor.prototype.Table.cellstyle(table,'border-width', null );
					YAHOO.widget.Editor.prototype.Table.cellstyle(table,'border-style', null );
					YAHOO.widget.Editor.prototype.Table.cellstyle(table,'border-color', null );
					
				}
			},
			cellpadding: function( table, value ){
				var padding = value >= 0 ? value : parseInt(table.getAttribute('cellpadding'));
				
				if( padding > 0 ) table.setAttribute('cellpadding',value);
				else table.removeAttribute('cellpadding');
				
				YAHOO.widget.Editor.prototype.Table.cellstyle(table,'padding', padding > 0 ? padding + 'px' : null );
				
			},
			cellstyle: function(table, property, value){
				var cells = table.getElementsByTagName('td');
				
				if( cells && cells.length > 0 ){
					if( value == null ){
						if( cells[0].style && cells[0].style.removeProperty ){
							for(var i = 0; i < cells.length; i++ ){
								cells[i].style.removeProperty(property);
							}	
						} else if( cells[0].style ){
							// IE < 9
							$D.setStyle(cells,property,'');
						}
												
					} else {
						$D.setStyle(cells,property,value);
					}
				}				
			},
			
			// Row methods
			
			Row: {
					index: function( el ){
						if( el.tagName.toLowerCase() == 'tr' ) return el.rowIndex;
						return el.parentNode.rowIndex;
					},
					insert: function( table, idx ){
					    var col_count  = table.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
					    var row = table.insertRow(idx);
					    for( var j = 1; j <= col_count; j++ ){
					    	var cell = row.insertCell(-1);
					    	//cell.innerHTML = '&nbsp;';
					    }
					    // apply borders
					    YAHOO.widget.Editor.prototype.Table.border(table);
					    YAHOO.widget.Editor.prototype.Table.cellpadding(table);
					},
					remove: function( cell_el ){
						var table = YAHOO.widget.Editor.prototype.Table.get(cell_el);
						var idx = YAHOO.widget.Editor.prototype.Table.Row.index(cell_el);
						table.deleteRow(idx);
					}
			},
			
			// Column methods
			Column: {
					index: function( el ){
						return el.cellIndex;
					},
					insert: function( table, idx ){
						var rows = table.getElementsByTagName('tr');
			    		for (var j = 0; j < rows.length; j++ ){
			    			var cell = rows[j].insertCell(idx);
			    			//cell.innerHTML = '&nbsp;';
			    		}
					    // apply borders
					    YAHOO.widget.Editor.prototype.Table.border(table);
					    YAHOO.widget.Editor.prototype.Table.cellpadding(table);

					},
					remove: function( table, idx ){
						var rows = table.getElementsByTagName('tr');
			    		for( var j = 0; j < rows.length; j++ ){
			    			rows[j].deleteCell(idx);
			    		}
					}
			},
			
			// Cell Methods
			Cell: {
					/* Find Parent Cell */
					get: function(el) {
						if( !el ) return;
						if( el.tagName && el.tagName.toLowerCase() == 'td' ) return el;
						if (el.parentNode && el.parentNode.tagName) {
							if( el.parentNode.tagName.toLowerCase() == 'td' ) return el.parentNode;
							else return YAHOO.widget.Editor.prototype.Table.Cell.get(el.parentNode);		
						}
					}
			}
	};
	
	/** Toolbar Button Command **/
	this.cmd_inserttable = function(value) {

		var el;
		if( value && value.cell ){
			el = value.cell;
		} else {
			el = this._getSelectedElement();
		}
		
		var table = YAHOO.widget.Editor.prototype.Table.get(el);
			
	    if( table ) {
	        this.currentElement[0] = el;
	    } else {
    		var table = null;
    		
    		if ( el == this._getDoc().body) {
        		
                table = this._getDoc().createElement('table');
                YAHOO.widget.Editor.prototype.Table.insert(table);
                this._getDoc().body.appendChild(table);
                
            } else {

                this._createCurrentElement('table');
                table = this._getDoc().createElement('table');
                YAHOO.widget.Editor.prototype.Table.insert(table);
                
                this.currentElement[0].parentNode.replaceChild(table, this.currentElement[0]);
            }

    		// add break if at end of doc.
			if( table && table.parentNode ){
				var br = document.createElement('br');
				try{
					// IE 7 throws error here
					table.parentNode.appendChild(br);
				} catch(e){}
			}
    		
    		this.currentElement[0] = table.getElementsByTagName("td")[0];

    		this.tableMenu.cfg.setProperty("trigger", this._getDoc().getElementsByTagName('TABLE'));   		
	    }
	    
	    if( value && value.action == 'column' ){
	    	this._handleEditTableColumn(value);
	    } else {
	    	this._handleCreateTableClick(value);	
	    }

		return [false];
		
	};
	
	
	/***********************************************************
	 * _renderCreateTableWindow
	 * 
	 * Build table modal 
	 * 
	 ***********************************************************/
	
	// Pre-render panel
	// Needed for proper border toolbar rendering
	this.on('windowRender', function( win , panel ){
		this._renderCreateTableWindow();
	}, this, true );
	
	YAHOO.widget.Editor.prototype._renderCreateTableWindow = function(value) {

		var body = document.createElement('div');
		body.className = 'rm-tableEditor';
		
		body.innerHTML = '<form id="' + this.get('id') + '_table_form" class="yui-table-form">\n' + 
		'<div class="rm-tableEditorColumn">\n' + 
	    '<label for="rows"><strong>Rows:</strong><input type="textbox" name="rows" id="' + this.get('id') + '_table_rows" class="number" /></label>\n' +
	    '<label for="cols"><strong>Columns:</strong><input type="textbox" name="cols" id="' + this.get('id') + '_table_cols" class="number" /></label>\n' +
	    '</div>\n' + 
	    '<div class="rm-tableEditorColumn">\n' +
	    '<label for="width"><strong>Width:</strong><input type="textbox" name="width" id="' + this.get('id') + '_table_width" class="number"/><select id="' + this.get('id') + '_table_width_type" name="width_type"><option>%</option><option>px</option></select></label>\n' +
	    '<label for="padding"><strong>Cell Padding:</strong><input type="textbox" name="padding" id="' + this.get('id') + '_table_padding" class="number" /></label>\n' +
	    '</div></form>\n';
		
		var toolbarCont = document.createElement("div");
	    toolbarCont.id = "table_toolbar_" + this.get('id');
		
		var toolbarConfig = {
				buttonType: this._defaultToolbar.buttonType,				    	  
				buttons: [
				          { group: 'border', label: this.STR_IMAGE_BORDER + ':',
				            buttons: [
				              { type: 'select', label: 'Size', value: 'bordersize', 
				                menu: [
				                  { text: 'none', value: '0', checked: true },
				                  { text: '1px', value: '1' },
				                  { text: '2px', value: '2' },
				                  { text: '3px', value: '3' },
				                  { text: '4px', value: '4' },
				                  { text: '5px', value: '5' }
				                ]
				              },
				            { type: 'select', label: 'Line Style', value: 'bordertype', disabled: true, 
				              menu: [
				                { text: 'Solid', value: 'solid', checked: true },
				                { text: 'Dashed', value: 'dashed' },
				                { text: 'Dotted', value: 'dotted' }
				              ]
				            },
				            { type: 'color', label: 'Color', value: 'bordercolor', disabled: true }
				          ]
				        }
				    ]
			};
		
		
		this.tableToolbar = new YAHOO.widget.Toolbar(toolbarCont, toolbarConfig);
		
	    body.appendChild(toolbarCont);
	    
		this._windows.inserttable = {};
	    this._windows.inserttable.body = body;

	    $E.on(body, 'keyup', function(e) {
	        $E.stopPropagation(e);
	    });
	    
	    
	    this.get('panel').editor_form.appendChild(body);
	    this.fireEvent('windowCreateTableRender', { type: 'windowCreateTableRender', panel: this.get('panel'), body: body });
		
		return body;

	};
	
	/***********************************************************
	 * _renderCreateColumnWindow
	 * 
	 * Build table column modal 
	 * 
	 ***********************************************************/
	
	YAHOO.widget.Editor.prototype._renderCreateColumnWindow = function(value) {

		var body = document.createElement('div');
		body.className = 'rm-tableColumnEditor';
		body.innerHTML = '<form id="' + this.get('id') + '_table_col_form" class="yui-table-form">\n' +
	    '<div>\n' + 
	    '<label for="width"><strong>Width:</strong><input type="textbox" name="width" id="' + this.get('id') + '_table_col_width" class="number"/><select id="' + this.get('id') + '_table_col_width_type" name="width_type"><option>%</option><option>px</option></select></label>\n' +
	    '</div>\n' + 
	    '</form>\n';
	    
		this._windows.tablecolumn = {};
	    this._windows.tablecolumn.body = body;

	    $E.on(body, 'keyup', function(e) {
	        $E.stopPropagation(e);
	    });
	    
	    this.get('panel').editor_form.appendChild(body);
	    this.fireEvent('windowCreateColumnRender', { type: 'windowCreateColumnRender', panel: this.get('panel'), body: body });
		
		return body;
		
	};
	
	
	/***********************************************************
	 * _handleCreateTableClick
	 * 
	 * Initialize the table properties modal 
	 * 
	 ***********************************************************/	
	YAHOO.widget.Editor.prototype._handleCreateTableClick = function(value) {

		var el = this.currentElement[0];
		if (!el) el = this._getSelectedElement();
        
		var table = YAHOO.widget.Editor.prototype.Table.get(el);
		
		if (this.get('limitCommands')) {
	        if (!this.toolbar.getButtonByValue('createTable')) {
	            return false;
	        }
	    }
		
	    this.on('afterExecCommand', function() {

	        var win = new YAHOO.widget.EditorWindow('inserttable', {
	            width: '430px'
	        });
			win.setHeader("Table Properties");

			var cols = 3,
				rows = 2,
				padding = 0,
				border = 0,
				style = 'solid',
				width = 100,
				width_type = '%';
			
			cols = table.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
			rows = table.getElementsByTagName('tr').length;
			
			width = parseInt(table.style.width);
			width_type = table.style.width.indexOf('%') >= 0 ? '%' : 'px';

			border = parseInt(table.style.borderWidth) || 0;
			style = table.style.borderStyle || 'solid';
			
			padding = table.getAttribute('cellpadding') || 0;
			
			// Open modal
			if (this._windows.inserttable && this._windows.inserttable.body) {
                body = this._windows.inserttable.body;
            } else {
            	body = this._renderCreateTableWindow();
            }
			win.setBody(body);	            
			this.openWindow(win);
			
			// Set values
			$D.get(this.get('id') + '_table_rows').value = rows;
			$D.get(this.get('id') + '_table_cols').value = cols;
			$D.get(this.get('id') + '_table_width').value = width;
			$D.get(this.get('id') + '_table_padding').value = padding;
			
			$D.get(this.get('id') + '_table_width_type').selectedIndex = width_type == 'px' ? 1 : 0;
			
			// Field events
			$E.onAvailable(this.get('id') + '_table_rows', function() {
		    	$E.purgeElement(this.get('id') + '_table_rows');
	            $E.on(this.get('id') + '_table_rows', 'blur', function() {
	                var value = parseInt($D.get(this.get('id') + '_table_rows').value, 10);
	                if (value > 0) {
	                	YAHOO.widget.Editor.prototype.Table.rows(table, value);
	                }
	            }, this, true);
	            $E.on(this.get('id') + '_table_rows', 'keydown', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_rows').value, 10);
		            if( e.keyCode == 13 ){
		            	$E.stopEvent(e);
		                if (value > 0) {
		                	YAHOO.widget.Editor.prototype.Table.rows(table, value);
		                }	
		            } else if( e.keyCode == 38 ){
		            	value++;
		            	$D.get(this.get('id') + '_table_rows').value = value;
	                	YAHOO.widget.Editor.prototype.Table.rows(table, value);	
		            } else if( e.keyCode == 40 && value > 1 ){
		            	value--;
		            	$D.get(this.get('id') + '_table_rows').value = value;
	                	YAHOO.widget.Editor.prototype.Table.rows(table, value);	
		            }
		            
		        }, this, true);
	            
	        }, this, true);
			
			$E.onAvailable(this.get('id') + '_table_cols', function() {
		    	$E.purgeElement(this.get('id') + '_table_cols');
	            $E.on(this.get('id') + '_table_cols', 'blur', function() {
	                var value = parseInt($D.get(this.get('id') + '_table_cols').value, 10);
	                if (value > 0) {
	                	YAHOO.widget.Editor.prototype.Table.columns(table, value);
	                }
	            }, this, true);
	            $E.on(this.get('id') + '_table_cols', 'keydown', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_cols').value, 10);
		            if( e.keyCode == 13 ){
		            	$E.stopEvent(e);
		                if (value > 0) {
		                	YAHOO.widget.Editor.prototype.Table.columns(table, value);
		                }	
		            } else if( e.keyCode == 38 ){
		            	value++;
		            	$D.get(this.get('id') + '_table_cols').value = value;
	                	YAHOO.widget.Editor.prototype.Table.columns(table, value);	
		            } else if( e.keyCode == 40 && value > 1 ){
		            	value--;
		            	$D.get(this.get('id') + '_table_cols').value = value;
	                	YAHOO.widget.Editor.prototype.Table.columns(table, value);	
		            }
		            
		        }, this, true);
	            
	        }, this, true);
			
			$E.onAvailable(this.get('id') + '_table_padding', function() {
		    	$E.purgeElement(this.get('id') + '_table_padding');
	            $E.on(this.get('id') + '_table_padding', 'blur', function() {
	                var value = parseInt($D.get(this.get('id') + '_table_padding').value, 10);
	                if (value >= 0) {
	                	table.setAttribute('cellpadding',value);	                	
	                }
	            }, this, true);
	            $E.on(this.get('id') + '_table_padding', 'keydown', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_padding').value, 10);
		            if( e.keyCode == 13 ){
		            	$E.stopEvent(e);
		            	YAHOO.widget.Editor.prototype.Table.cellpadding(table, value);
		            } else if( e.keyCode == 38 ){
		            	value++;
		            	$D.get(this.get('id') + '_table_padding').value = value;
		            	YAHOO.widget.Editor.prototype.Table.cellpadding(table, value);	
		            } else if( e.keyCode == 40 && value > 0 ){
		            	value--;
		            	$D.get(this.get('id') + '_table_padding').value = value;
		            	YAHOO.widget.Editor.prototype.Table.cellpadding(table, value);	
		            }
		            
		        }, this, true);
	            
	        }, this, true);
			
			$E.onAvailable(this.get('id') + '_table_width', function() {
				
		    	$E.purgeElement(this.get('id') + '_table_width');
	            $E.on(this.get('id') + '_table_width', 'blur', function() {
	            	
	            	var type_el = $(this.get('id') + '_table_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
	                var value = parseInt($D.get(this.get('id') + '_table_width').value, 10);
	                if (value > 0) {
	                	table.style.width = value + type;
	                } else {
	                	table.style.width = '100%';
	                }
	            }, this, true);
	            $E.on(this.get('id') + '_table_width', 'keydown', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_width').value, 10);
	            	
	            	var type_el = $(this.get('id') + '_table_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
		            if( e.keyCode == 13 ){
		            	$E.stopEvent(e);
		            	if (value > 0) {
		                	table.style.width = value + type;
		                } else {
		                	$D.get(this.get('id') + '_table_width').value = '100';
		                	type_el.selectedIndex = 0;
		                	table.style.width = '100%';
		                }
		            } else if( e.keyCode == 38 ){		            	
		            	if (value > 0) {
		            		if( type != '%' || value < 100 ){
			            		value++;		            		
			            	}
		            		$D.get(this.get('id') + '_table_width').value = value;
		                	table.style.width = value + type;
		                } else {
		                	$D.get(this.get('id') + '_table_width').value = '100';
		                	type_el.selectedIndex = 0;
		                	table.style.width = '100%';
		                }
		            } else if( e.keyCode == 40 && value > 1 ){
		            	value--;
		            	$D.get(this.get('id') + '_table_width').value = value;
		            	table.style.width = value + type;	
		            }
		            
		        }, this, true);
	            $E.on(this.get('id') + '_table_width_type', 'change', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_width').value, 10);
	            	
	            	var type_el = $(this.get('id') + '_table_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
					if( type == '%' && ( value > 100 || value < 0 ) ){
						value = 100;
					}
					
					if (value > 0) {
						$D.get(this.get('id') + '_table_width').value = value;
	                	table.style.width = value + type;
	                }
		            
		        }, this, true);
	            
	        }, this, true);
			
			// Border toolbar init
			
			var toolbar = this.tableToolbar;
			
			var size_btn = toolbar.getButtonByValue('bordersize'),
			size_lbl = border > 0 ? '' : this.STR_NONE;
			size_btn.set('label', '<span class="yui-toolbar-bordersize-' + border + '">' + size_lbl + '</span>');
			this._updateMenuChecked('bordersize', border, toolbar);

			var type_btn = toolbar.getButtonByValue('bordertype');
			type_btn.set('label', '<span class="yui-toolbar-bordertype-' + style + '">Line Type</span>');
			this._updateMenuChecked('bordertype', style, toolbar);
			
			if (border > 0) {
				toolbar.enableButton(type_btn);
				toolbar.enableButton('bordercolor');
		    } else {
		    	toolbar.disableButton(type_btn);
		    	toolbar.disableButton('bordercolor');
		    }
			
			toolbar.removeListener('bordersizeClick');			
			toolbar.on('bordersizeClick', function(o) {

		        if (o.button.value == 0) {
		        	toolbar.disableButton("bordertype");
		        	toolbar.disableButton("bordercolor");			    	
			    	type_btn.set('label', '<span class="yui-toolbar-bordertype-solid">Line Type</span>');
			    	this._updateMenuChecked('bordertype', 'solid', toolbar);

		        } else {
		        	toolbar.enableButton("bordertype");
		        	toolbar.enableButton("bordercolor");		          
		        }
		        
		        YAHOO.widget.Editor.prototype.Table.border(table,o.button.value);

			},this,true);
			
			toolbar.removeListener('bordertypeClick');
			toolbar.on('bordertypeClick', function(o) {
				if (o.button.value == 0) {
					YAHOO.widget.Editor.prototype.Table.border(table,null,null);
				} else {
					YAHOO.widget.Editor.prototype.Table.border(table,null,o.button.value);
				}
			});
			
			toolbar.removeListener('colorPickerClicked');
			toolbar.on('colorPickerClicked', function(o) {
				YAHOO.widget.Editor.prototype.Table.border(table,null,null,o.color);
			});
      
	    });
		
	};
	
	
	/***********************************************************
	 * _handleEditTableColumn
	 * 
	 * Initialize the table properties modal 
	 * 
	 ***********************************************************/	
	YAHOO.widget.Editor.prototype._handleEditTableColumn = function(value) {

		var el = this.currentElement[0];
		if (!el) el = this._getSelectedElement();
        
		var table = YAHOO.widget.Editor.prototype.Table.get(el);
		var row = table.getElementsByTagName('TR')[0];
		var cell_idx = el.cellIndex;
		var top_cell = null;
		
		if( row && cell_idx >= 0 ){
			cells = row.getElementsByTagName('TD');
			if( cells.length > cell_idx ) top_cell = cells[cell_idx];
		}
		
		if( !top_cell ) return;
		
		if (this.get('limitCommands')) {
	        if (!this.toolbar.getButtonByValue('createTable')) {
	            return false;
	        }
	    }
		
	    this.on('afterExecCommand', function() {

	        var win = new YAHOO.widget.EditorWindow('tablecolumn', {
	            width: '300px'
	        });
			win.setHeader("Column Properties");

			var width = -1,
				width_type = '%';
			
			if( top_cell.style && top_cell.style.width ){
				width = parseInt(top_cell.style.width);
				width_type = top_cell.style.width.indexOf('%') >= 0 ? '%' : 'px';
			}
			// Open modal
			if (this._windows.tablecolumn && this._windows.tablecolumn.body) {
                body = this._windows.tablecolumn.body;
            } else {
            	body = this._renderCreateColumnWindow();
            }
			win.setBody(body);	            
			this.openWindow(win);
			
			// Set values
			$D.get(this.get('id') + '_table_col_width').value = width > 0 ? width : '';
			$D.get(this.get('id') + '_table_col_width_type').selectedIndex = width_type == 'px' ? 1 : 0;
			
			// Field events
			$E.onAvailable(this.get('id') + '_table_width', function() {
				
		    	$E.purgeElement(this.get('id') + '_table_col_width');
	            $E.on(this.get('id') + '_table_col_width', 'blur', function() {
	            	
	            	var type_el = $(this.get('id') + '_table_col_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
	                var value = parseInt($D.get(this.get('id') + '_table_col_width').value, 10);
	                if (value > 0) {
	                	top_cell.style.width = value + type;
	                } else {
	                	top_cell.style.width = '';
	                }
	            }, this, true);
	            $E.on(this.get('id') + '_table_col_width', 'keydown', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_col_width').value, 10);
	            	
	            	var type_el = $(this.get('id') + '_table_col_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
		            if( e.keyCode == 13 ){
		            	$E.stopEvent(e);
		            	if (value > 0) {
		            		top_cell.style.width = value + type;
		                } else {
		                	$D.get(this.get('id') + '_table_col_width').value = '';
		                	type_el.selectedIndex = 0;
		                	top_cell.style.width = '';
		                }
		            } else if( e.keyCode == 38 ){		            	
		            	if (value > 0) {
		            		if( type != '%' || value < 100 ){
			            		value++;		            		
			            	}
		            		$D.get(this.get('id') + '_table_col_width').value = value;
		            		top_cell.style.width = value + type;
		                } else {
		                	$D.get(this.get('id') + '_table_col_width').value = '';
		                	type_el.selectedIndex = 0;
		                	top_cell.style.width = '';
		                }
		            } else if( e.keyCode == 40 && value > 1 ){
		            	value--;
		            	$D.get(this.get('id') + '_table_col_width').value = value;
		            	top_cell.style.width = value + type;	
		            }
		            
		        }, this, true);
	            $E.on(this.get('id') + '_table_col_width_type', 'change', function(e){
	            	// Update on enter, up or down arrows
	            	var value = parseInt($D.get(this.get('id') + '_table_col_width').value, 10);
	            	
	            	var type_el = $(this.get('id') + '_table_col_width_type');
					var type = type_el && type_el.selectedIndex == 1 ? 'px' : '%';
	            	
					if( type == '%' && ( value > 100 || value < 0 ) ){
						value = 100;
					}
					
					if (value > 0) {
						$D.get(this.get('id') + '_table_col_width').value = value;
	                	top_cell.style.width = value + type;
	                }
		            
		        }, this, true);
	            
	        }, this, true);
			
	    });
		
	};
	
	
	/*** Context Menu ***/
	
	this.on('afterNodeChange', function() {
		this.tableMenu.cfg.setProperty("trigger", this._getDoc().getElementsByTagName('TABLE'));
	},this,true);
	
	this.on('editorContentLoaded', function() {
		
		try{
			this._getDoc().execCommand('enableInlineTableEditing',false,false);
		} catch(ex){}

	    var menuItems = [
	        { text: "Table",
	          submenu: {  
	        	  id: "sub_table_" + this.get('id'),  
	        	  lazyload: true,  
	        	  itemdata: [ 
	        	             "Edit Table",  
	        	             "Delete Table"  
	        	             ]  
	          }
	        },
	        { text: "Row",
	          submenu: {  
	        	  id: "sub_row_" + this.get('id'),  
	        	  lazyload: true,  
	        	  itemdata: [ 
	        	             "Insert Row Before",  
	        	             "Insert Row After",
	        	             "Delete Row"  
	        	             ]  
	          }
	        },
	        { text: "Column",
	          submenu: {  
	        	  id: "sub_column_" + this.get('id'),  
	        	  lazyload: true,  
	        	  itemdata: [ 
	        	             "Insert Column Before",  
	        	             "Insert Column After",
	        	             "Edit Column",
	        	             "Delete Column"  
	        	             ]  
	          }
	        }	      
	    ];

    	this.tableMenu = new YAHOO.widget.ContextMenu("tableMenu-" + this.get('id'), {
	        itemdata: menuItems,
	        clicktohide: true,
	        trigger: this._getDoc().getElementsByTagName('TABLE'), 
	        container: this.get('iframe').get('parentNode'),
	        lazyload: true,
	        editor: this
	    });	

    	this.on('editorClick', function(){
    		// Editor traps clicks
    		// Hide context menu manually on custom editor click event.    		
    		if( this.tableMenu.visible ) this.tableMenu.hide();
    	},this,true);
    	
    	this.tableMenu.triggerContextMenuEvent.subscribe( function(type,args){
    		// Set position based on click position
    		
    		var event = args[0];
    		var editor_xy = $D.getXY(this.cfg.config.container.value);

    		this.pos_xy = [editor_xy[0] + event.clientX, editor_xy[1] +  event.clientY];

    	});
    	
    	this.tableMenu.showEvent.subscribe( function(){
    		// Move to position set by context event.
    		
    		if( typeof(this.parent) == 'undefined' ){
    			this.moveTo(this.pos_xy[0],this.pos_xy[1]);
    		}
    		
    		// flag as visible.  clicking in the editor will close the menu when visible
    		var menu = this;
    		var setVisible = function(){
    			menu.visible = true;	
    		};
    		setTimeout(setVisible, 100);
    		
    	});
    	this.tableMenu.hideEvent.subscribe( function(){
    		this.visible = false;
    	});
    	
    	this.tableMenu.subscribe("render", function(){    		
    		// Handle context menu
    		// Only subscribe root menu. Prevent each sub-menu from adding event.
    		if( typeof(this.parent) == 'undefined' ){
    			
    			this.subscribe("click", function(e, args){

			    	var menu_item = args[1],
			    	target = this.contextEventTarget, 
			    	table_cell,
			    	cell_idx = [-1,-1]; // cell_idx = [row,col] 
			    	var parent = menu_item.parent ? menu_item.parent : null;

			    	var editor = this.cfg.initialConfig.editor;
			    	
		    		table_cell = YAHOO.widget.Editor.prototype.Table.Cell.get(target);
		    		table = YAHOO.widget.Editor.prototype.Table.get(target);
		    		cell_idx = [YAHOO.widget.Editor.prototype.Table.Row.index(table_cell), YAHOO.widget.Editor.prototype.Table.Column.index(table_cell) ];
		    		
		    		editor.currentElement[0] = table_cell;
		    		
		    		if( parent.id.indexOf('sub_row') == 0 ){
		    			switch(menu_item.index){
			    			case 0:     // Insert Row Before 
			    				YAHOO.widget.Editor.prototype.Table.Row.insert(table,cell_idx[0]);	    				
			    				break;
			    			case 1:     // Insert Row After 
			    				YAHOO.widget.Editor.prototype.Table.Row.insert(table,cell_idx[0]+1); 
			    				break;
			    			case 2:     // Delete Row 
			    				YAHOO.widget.Editor.prototype.Table.Row.remove(table,cell_idx[0]); 
			    				break;
		    			}
		    		} else if( parent.id.indexOf('sub_column') == 0 ){
		    			switch(menu_item.index){	
			    			case 0:     // Insert Column Before 
			    				YAHOO.widget.Editor.prototype.Table.Column.insert(table,cell_idx[1]); 
			    				break;
			    			case 1:     // Insert Column After 
			    				YAHOO.widget.Editor.prototype.Table.Column.insert(table,cell_idx[1]+1); 
			    				break;
			    			case 2:     // Edit Column 
			    				// Cell edit modal
			    				editor.execCommand('inserttable',{cell:table_cell, action: 'column'});
			    				break;
			    			case 3:     // Delete Column
			    				YAHOO.widget.Editor.prototype.Table.Column.remove(table,cell_idx[1]);
			    				break;
		    			}
		    		} else if( parent.id.indexOf('sub_table') == 0 ){
		    			switch(menu_item.index){
			    			case 0:     // Edit Table 
			    				// Edit table modal.
			    				editor.execCommand('inserttable',{cell:table_cell});
			    				break;
			    			case 1:     // Delete Table 
			    				YAHOO.widget.Editor.prototype.Table.remove(table); 
			    				break;
		    			}
		    		} else {
		    			// Root menu selects
		    			switch(menu_item.index){
			    			case 0:     // Edit Table
			    				editor.execCommand('inserttable',{cell:table_cell});
			    				break;
			    			case 1:     // Row 
			    				break;
			    			case 2:     // Edit Column 
			    				editor.execCommand('inserttable',{cell:table_cell, action: 'column'});
			    				break;
		    			}
		    		}
			    	
			    },this,true);
    		}
    	}); 
	    
	}, this, true);
	
};



