SUEditor

By Onyxstone Last update Nov 24, 2009 — Installed 2,763 times. Daily Installs: 23, 6, 7, 14, 6, 12, 9, 15, 20, 9, 10, 19, 8, 12, 13, 13, 30, 43, 58, 20, 131, 83, 28, 9, 14, 96, 97, 40, 45, 82, 27, 8

There are 42 previous versions of this script.

Add Syntax Highlighting (this will take a few seconds, probably freezing your browser while it works)

// ==UserScript==
// @name           SUEditor
// @namespace      http://onyxstone.stumbleupon.com/
// @description    WYSIWYG Rich text editor for stumbleupon, works on most pages including blog, forum ,contact. 
// @include        http://*.stumbleupon.com/*
// @version        0.1.8
// @author         (onyxstone) http://onyxstone.stumbleupon.com/
// @license        (c) ONYXSTONE ( http://onyxstone.stumbleupon.com/ )
// @resource css_file        http://onyxstone.webs.com/Scripts/SUEditor_0_1_6/ui_style.css
// @resource css_iframe_file http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/iframe.css
// @resource icons_file      http://onyxstone.webs.com/Scripts/SUEditor_0_1_6/icons.png
// @resource colors          http://onyxstone.webs.com/Scripts/SUEditor_0_1_6/colors.txt
// @resource blockstyle      http://onyxstone.webs.com/Scripts/SUEditor_0_1_6/block.css
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/jquery.js
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/imageForm.js
// @resource imageForm_css   http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/imageForm.css
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/button.js
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_6/select.js
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/contextmenu.js
// @require                  http://onyxstone.webs.com/Scripts/SUEditor_0_1_8/range.js
// ==/UserScript==


/*
*    Icons used :
*    > <a href="http://www.pinvoke.com/">Fugue icons by Yusuke Kamiyamane</a><br />
*    > <a href="http://www.famfamfam.com/archive/silk-icons-thats-your-lot/">famfamfam icons [Silk set] by Mark James</a><br />
*/

//*****************************Updater*******************************

var thisVersion = '0.1.8';
var updaterWait = setInterval( checkUpdates , 400 );


$('<script id="sueditor-updater" type="text/javascript" src="http://onyxstone.webs.com/Scripts/Updaters/sueditor_version.js" />').appendTo('body');


function checkUpdates() {
 var newVersion =  unsafeWindow.sueditor_version;
 if( newVersion ) {
     clearInterval( updaterWait );

     if( newVersion != thisVersion ) {
       if( !$( '#sueditor-updates' )[0] )
       $( 'li.addSite' )
       .before( '<li class="btnWhite" id="sueditor-updates" style=""><font style="color:red;">SUEditor Update Available! <a href="'+ unsafeWindow.sueditor_version_info +'">Install</a> </font></li>');


     }
     else {}
 }
}

//***************************Storage***********************************


var storage = {
    setItem : function( key , value ) {
            if( unsafeWindow.localStorage )
                unsafeWindow.localStorage.setItem( key , value );
    },
    getItem : function( key  ) {
            if( unsafeWindow.localStorage )
                return unsafeWindow.localStorage.getItem( key  );
    }

}


//*****************************Disable Styles*******************************

var link = $('link[href^="/css/global_su.css"]')[0];
if( link ) {
link.sheet.cssRules.item( 264 ).style.paddingLeft = '0px';
link.sheet.cssRules.item( 283 ).style.cssText = 'padding-left:0px;';
}

$('#addContent').css({ height: 'auto' })





var colors = GM_getResourceText( 'colors' );
var web_named_colors = colors.split('\n');


var css_file = GM_getResourceText( 'css_file' );
var css_iframe_file = GM_getResourceText( 'css_iframe_file' );
var icons_file = GM_getResourceURL( 'icons_file' );
var blockStyle = GM_getResourceText( 'blockstyle' );

GM_addStyle( css_file );


var font_families =  
['Arial',
'Courier New',
'Georgia',
'Times New Roman',
'Verdana',
'Trebuchet MS',
'Lucida Sans',
'sans-serif',
'serif',
'monospace',
'cursive',
'fantasy'];



GM_addStyle(".ToolbarButton span.icon{ background-image:url('" +  icons_file + "')}");





var mode;

var contextMenu;



function initialize() {

 var tareas = $('textarea');
 //GM_log( '\n' + tareas.length );

 if( tareas.length === 1 ) {
     createEditorInstance( tareas[0].form );
 }
 
       var edits = $('a.edit');
       edits.bind( 'click' , function(e) {
               createEditorInstance( $( e.target )
               .parents( 'div.text' ).find( 'form' ) );   
       });
       
       $('a.addSite').bind('click', function( e ) {

            createEditorInstance( $('#addContent').find( 'form' ) );
       });
}


function createEditorInstance( form ) {
var button = $( form ).find( 'input[type="submit"]' );
if( !button[0] ) button = $( form ).find( 'a.submit' );
if( !button[0] ) button = $( form ).find( 'input[name="submit"]' );
var textarea = $( form ).find( 'textarea' );

if( textarea[0] && !textarea.attr('haseditor') && button[0] ) {
    var oEditor = new Editor();
          oEditor.Textarea = textarea;
          oEditor.Button   = button;
          oEditor.createEditorBase();
          textarea.attr('haseditor',true);
 }
}






var Commands = {
  'bold' : [0,"Make this text *b o l d* " ],
  'italic': [1,"Make this text *i t a l i c* " ],
 'strikethrough': [2,"Line-through text" ],
 'underline': [3,"Underline text" ],
 'insertimage': [8,'Create new image from URL' ],
 'createlink': [9,'Create new link' ],
 'unlink': [10,'Remove link'],
 'inserthtml': [11,'Insert HTML'],
 'removeformat': [12,'Remove text formatting'],
 'spellcheck': [15,"Toggle Spell Check"],
 'forecolor': [13,'Text color'],
 'hilitecolor': [14,'Hiliter'],
 'subscript': [23,"Subscript text"] , 
 'superscript': [24,"Superscript text"],
 'insertorderedlist': [22,"Insert numbered list"],
 'insertunorderedlist': [21,"Insert bulleted list"],
 'indent': [16,"Indent"],
 'outdent': [17,"Outdent"],
 'justifycenter': [4,'Center'],
 'justifyleft': [5,'Align text to left'],
 'justifyright': [6,'Align text to right'],
 'justifyfull': [7,'Align - justify'],
 'createbox': [17,'Create box around a post'],
 'visualmode' :[20,'Switch to Visual Mode'],
 'restore' : [23,"Restore Saved Post"],
 'morebuttons' : [2, 'Show more buttons'],
 'source' : [19, "Show source"],
 //
 'textshadow' : [18, "Text Shadow"],
 'blockstyle' : [24, "Toggle block view"],
 'cleancode' : [25, "Clean code"]
};

var Groups = {
    'v0' : [ 
             ['source'],
             ['restore'],
             ['bold','italic','strikethrough','underline'],
             ['justifycenter','justifyleft','justifyright','justifyfull'],
             ['insertimage','createlink','unlink','inserthtml','removeformat'],
             ['forecolor','hilitecolor'],
             ['morebuttons']
           ],
    'v1' : [['spellcheck'],
            ['indent','outdent'],
            ['createbox','textshadow','blockstyle']
//,['subscript','superscript']
            ],
    's0' : [['visualmode'],
            ['cleancode']]


};




var s ='';
for( var i in Commands ) {

s+='\nbutton[command="' + i + '"] span.icon {background-position: -' + Commands[i][0]*16 + 'px 0px;}';
}

GM_addStyle( s );




var Editor = function( params ) {
this.InstanceName = 'noname';
if(params) {
  this.params = params;
  this.Textarea = params.textarea;
  this.Button   = params.button;
  
  this.InstanceName = this.Textarea[0].id;
  }
this.Buttons = {};
this.visual = true;
this.currentToolbar = 0;

this.openWindows = 
{
   imageForm : null,
   contextMenu : null,
   styleWindow : null
}
  
}


Editor.prototype.$ = 

function Editor_$( str ) {
         return $( str , this.EditorBox );
}

Editor.prototype.createEditorBase = 

function Editor_createEditorBase() {

if( !contextMenu ) contextMenu = new ContextMenu();



    textarea = this.Textarea;
    button   = this.Button;
    before = textarea;
    
    if( mode === "blog") {
        $('#submit_buttom')[0].type = "button";
        window.wrappedJSObject._post_blog_entry 
          = window.wrappedJSObject.post_blog_entry;
          oThis = this;
        window.wrappedJSObject.post_blog_entry = 
        function() {
          oThis.submitToTextarea();
          window.wrappedJSObject._post_blog_entry();
        }
       }
    
    else {
      
      if( button[0].tagName == "INPUT"){
      
      

      button[0].type = 'button'
      
button.bind('click', 
this , function(e) {

          e.data.submitToTextarea();

          e.target.type = 'submit';
          e.target.click();
          

  });
  }
  else {
  
  this.FalseButton = $( '<' + button[0].tagName + ' />'  )
      .val( button.val() )
      .html( button.html() )
      .addClass( button[0].className )

      .bind('click',this,function(e) {
          e.data.submitToTextarea();
          e.data.Button.click();

      })
      .insertBefore( button );
      
      button.hide();
  }

      
    
    }

var html = 
'<div class="editor-toolbars">' +
      '<div class="visual-toolbars">' +
            '<div class="editor-toolbar v0 btnWhite" />' +
            '<div class="editor-toolbar v1 btnWhite" style="display:none;" />' +
      '</div>' +
      '<div class="source-toolbars" style="display:none;">' +
            '<div class="editor-toolbar s0 btnWhite" />' +
      '</div>' +
'</div>'+
'<iframe class="editor-iframe" style="display:none;" />';


        this.EditorBox = $( '<div class="EditorBox"  />').insertBefore( textarea.hide() ).html( html );          
        

       this.bottomBox = $( '<div class="editor-bottom-buttons" />')
                      .insertAfter( textarea );
                      
       this.previewBtn = $('<input type="button" fn="Preview" class="btnWhite" value="Preview > " />').appendTo( this.bottomBox ).bind( 'click' , this , this.handleEvt );



    this.Iframe    = this.find('editor-iframe' );


    var d = storage.getItem( 'SUE_secondToolbar'  );
    
    this.find( 'v1').css( 'display' , d )

    

    
    this.Iframe.bind( 'load', this, Editor_handleIframeLoad )
          .attr('src','about:blank')
          .css({width:'100%'}).show()
          .adjust = function () {
            this[0].style.width = this[0].parentNode.clientWidth - 5 + 'px';

            if( this[0].contentDocument.body.scrollHeight > 150 )
              this[0].style.height = 
                this[0].contentDocument.body.scrollHeight+'px';
            else 
              this[0].style.height = '150px';
      }
      
  this.populate();

}

Editor.prototype.find = function( className ){
    return this.EditorBox.find('.' + className );
}
Editor.prototype.populate = function(){
     
     for( var i in Commands ) {
          this.Buttons[i] = 
          createButton( i ,  Commands[i][1] )
          .bind( 'click' , this ,  this.handleToolbar );

     }
     
     this.Buttons['source'] 
     //= createButton( 'source' ,  "Show source" )
        //.bind( 'click' , this ,  this.handleToolbar )
        .append('<span class="text">Source</span>');
        
     this.Buttons['restore'].append('<span class="text">Restore</span>');
 this.Buttons['visualmode'].append('<span class="text">Visual</span>');    
this.Buttons['morebuttons'].html('<span class="text">More..</span>');
this.Buttons['createbox'].html('<span class="text" style="margin-top: -4px;">Boxify</span>');
     
     for( var name in Groups ) {
          for( var a=0;a<Groups[name].length;a++) {

               var group = $('<div class="btnGroup" />')
                   .appendTo( this.find( name ) )
                   .addClass( 'group'+ a);
               for( var value = 0; value<Groups[name][a].length ; value ++) {
                    this.Buttons[Groups[name][a][value]]
                    .appendTo( group );
               }
          }
          this.find( name ).append( '<div class="clear" />');
     }
     
  var color = new ColorMenuButton( 'forecolor', 'Text color' );

              color.bind( this ,  this.handleToolbar );

              this.Buttons['forecolor'].replaceWith( color.base );
              this.Buttons['forecolor'] = color;
              
  var color = new ColorMenuButton( 'hilitecolor' , 'Hiliter color' );

              color.bind( this ,  this.handleToolbar );

              this.Buttons['hilitecolor'].replaceWith( color.base );
              this.Buttons['hilitecolor'] = color;
              
   var color = new ColorMenuButton( 'textshadow' , 'Text shadow' );

              color.bind( this ,  this.handleToolbar );

              this.Buttons['textshadow'].replaceWith( color.base );
              this.Buttons['textshadow'] = color;


  var select = new Select();
  this.find('v1').prepend( select.base );
  select.attr( 'command' , 'fontname' )
        .bind( this , this.handleToolbar ).setLabel( 'font name' );
  
  for( i=0;i<font_families.length;i++) {
  	 var ff = font_families[i];
  	 select.item( ff , ff , 'font-family:' + ff );
  }
  
  
  
  this.Buttons['fontname'] = select;
  
  var select = new Select();
  this.find('v1').prepend( select.base );
  select.attr( 'command' , 'fontsize' ).setLabel( 'font size' )
        .bind( this , this.handleToolbar );
   
  for( var i=1;i<8;i++) {
    select.item( i , "Size "+i, 'font-size:'+i*5+'pt;' );
  }
  
  this.Buttons['fontsize'] = select;
  

  
}



Editor.prototype.basicCommand = function( com , val ) {
   try {
       this.Doc.execCommand( com , false , val );
   }
   catch( e ) {
          GM_log( e );
   }
}


Editor.prototype.getRange = 
function Editor_getRange() {
         var sel = this.Iframe[0].contentWindow.getSelection();
         var range = sel.getRangeAt( 0 );
         range = extRange( range );
         return range;
}

//Editor.prototype.cmd_testCommand = Editor_cmd_testCommand;



Editor.prototype.handleEvt = 
function Editor_handleEvt( e ) {

         var fn = $( e.target ).attr('fn');
         var _this = e.data;
         
         if( HandleEvt[fn] ) 
             HandleEvt[fn].apply( _this , [] );
         
}


var HandleEvt = {

    'Preview' : function( ) {
              this.submitToTextarea();
	      
              this.preview( this.Textarea.val().br() );
    
    }

}


Editor_handleIframeLoad = function( e ) {
  e.data.iframeReady();
}

Editor.prototype.iframeReady = function Editor_iframeReady() {

    this.Textarea.hide();


    this.Doc = this.Iframe[0].contentDocument;

    var spellcheck = storage.getItem( 'SUE_spellcheck' );
    eval( 'spellcheck=' + spellcheck );

	this.Doc.body.spellcheck = spellcheck;

    //comp_style = getStyle( document.body );
    
    var comp_style;
    var wrapper = $( '#wrapperContent' )[0];
    ( wrapper ) ? comp_style = getStyle( wrapper )
    : comp_style = getStyle( document.body );
    
    //var font_size = comp_style.fontSize;
    var text_color = comp_style.color;

    var background = comp_style.backgroundColor;
    var font_family = comp_style.fontFamily;

    
    this.DocStylesheet  
    = $("<style class='IframeStylesheet' type='text/css' />" )
    .appendTo( $( 'head' , this.Doc  )  );
    
    

      
    
    
    doc_style_css = 
    "body{background:transparent" + 
    "; color:"           + text_color  +
    "; font-family: "    + font_family +
   // "; font-size:"       + font_size   + ";}";
    //"; font-size: 12px;}";
	"; }"

    var textlinks = document.getElementsByClassName('textlink');
    var a;
    for( var i=0;i<textlinks.length; i++) {
      ch = textlinks[i].firstChild
      if( ch && ch.nodeName == 'A' ) {
        a = ch;
        break
        }
      
    }
    
    if( a ) {
      var link_color = getStyle( a ).color;
      doc_style_css+="a{color:" + link_color + " !important;}"; 
      doc_style_css+="a{text-decoration: none!important;}";
    }
    else {
      var link_color = getStyle( document.getElementsByTagName('a')[0] ).color;
      doc_style_css+="a{color:" + link_color + " !important;}"; 
      doc_style_css+="a{text-decoration: none!important;}";
    }

    
    this.DocStylesheet.html( css_iframe_file + '' + doc_style_css );
	
    
	
	this.blockStyle = $( '<style id="blockStyle" type="text/css" />')
		.appendTo( $( this.Doc ).find('head') )
		.text( blockStyle ).attr('disabled',true);

    this.setHTML();
    
    
    this.Doc.designMode = 'on';
    $( this.Doc ).bind('mousedown',this,function( e ) {
      e.data.Iframe.adjust();
      $('div.context-menu').hide();
    });
    $( this.Doc ).bind('keyup',this,function( e ) {
      e.data.Iframe.adjust();
    });  

    $( this.Doc ).bind('contextmenu',this,function( e ) {

      var t = e.target;
      if( t.tagName != "BODY" && t.tagName != "HTML" ) {
          e.originalEvent.preventDefault();
          
          contextMenu.show( e.data , t , e.clientX , e.clientY );
      }
    }); 
}



Editor.prototype.handleToolbar = 
function Editor_handleToolbar( e ) {
	var t = $( e.target );
	var className = t.attr( 'className' );
	var command = t.attr( 'command' );
	var value = t.val();
	var type = e.type;
	var _this = e.data;

	
	var noCSS = ['bold','italic','underline'];
	
	
	if( type == 'click' ) {
		
		if( handleToolbar[command] ) {
			handleToolbar[command].apply( _this , [value , e.target ] );
		}
		else {
			( noCSS.indexOf( command ) > -1 ) ? _this.Doc.execCommand( 'styleWithCSS' , false , false ) :
																		_this.Doc.execCommand( 'styleWithCSS' , false , true );
    			_this.Doc.execCommand( command , false , value );
		}


	}
	
	else if( type == "change" ) {
    if( handleToolbar[command] ) 
			handleToolbar[command].apply( _this , [ value, e.target ] );
		
		else 
		_this.Doc.execCommand( command , false , value );	
	}
	
}



var handleToolbar = {
 	'createlink' : function() {
	   		data = prompt('Enter link URL \n' +
			'( e.g. "http://google.com/" ) ');
			if (data && data != "") 
				this.Doc.execCommand('createlink', false, data);
	   },
	   
	   'insertimage' : function( value, target ) {

				xy = findPos( target );
				
				imageForm.setPosition( xy[0]-150 , xy[1] )
        .open( null , this );
				//.onSubmit( function( e ) {
         //          console.log( e.data.form.data );
        //} , this );
				
		},
		
		'inserthtml'  : function() {
		data = prompt('Enter HTML code \n' +
				'( e.g. "<font color="red">Some text</font>" ) ');
				if (data && data != "") 
					this.Doc.execCommand('inserthtml', false, data);
		},
		
	   'morebuttons' : function() {

			this.find('v1').toggle();
			var display = this.find('v1')[0].style.display;
			storage.setItem( 'SUE_secondToolbar' , display );
		},
		
		'source'  : function() {
			this.toggleView();
		},
		
		'visualmode' : function() {
			this.toggleView();
		},
		
		'spellcheck'  : function() {
			sp = this.Doc.body.spellcheck;
			( sp ) ? sp = false : sp = true;
			this.Doc.body.spellcheck =  sp ;
			storage.setItem('SUE_spellcheck', sp);
		},
		
		'createbox' : function() {
			this.cmd_createbox();
		},
		
		 'restore' :function() {
		  var conf = confirm('Do you really want to restore last text ?\n This one will be replaced !');
		  if( conf )
			    $( this.Doc.body ).html( storage.getItem('SUE_emergencySave') );
		},
		
		'textshadow' : function( value ) {
		     //this.cmd_testCommand();
		     this.Command( 'textshadow' , value );
		},
		
		'blockstyle' : function() {
		     this.toggleBlockStyle();
		}
	
	
}
Editor.prototype.DOMApplyCommand = DOMApplyCommand;

Editor.prototype.Command = function( name , value ){
                         if( !this.busy && value.length > 0 ) {
                             this.busy = true;
                             try {
                                 editorCommands[name].apply( this , [value] );
                             } catch( e ) { 
                               GM_log( '\nERROR ' + name + '  ' + value 
                               + '\n' + e.toString() );
                               };
                             this.busy = false;
                         }
}

var editorCommands = {
    'textshadow' : function( value ) {
       this.DOMApplyCommand( '<font style="text-shadow: 1px 2px 2px '+ value +';" />' );
    }

}

Editor.prototype.toggleBlockStyle = function(){

   ( this.blockStyle.attr('disabled') ) ? this.blockStyle.attr('disabled', false )
   :this.blockStyle.attr('disabled', true );
   
}


Editor.prototype.toggleView = function(){
	if (this.visual === true) {
		this.Iframe.hide();
		imageForm.close();
		this.setSource();

		this.find('visual-toolbars').hide();
		this.find('source-toolbars').show();

		this.Textarea.show();
		this.visual = false;
	}
	else {
		this.Iframe.show();
		this.setHTML();

    this.find('visual-toolbars').show();
		this.find('source-toolbars').hide();
		
		this.Textarea.hide();
		this.visual = true;
	}
}





Editor.prototype.submitToTextarea =
 
function Editor_submitToTextarea() {

    
    if( this.visual == true )
        this.setSource();
     
     pr = processHTML( this.Textarea.attr('value') ); 

     pr = pr.replace( /\<br\>/ , '\n' );

      
     this.Textarea.attr('value',pr);
     storage.setItem('SUE_emergencySave',pr)  ;  
}

Editor.prototype.setSource =

function Editor_setSource(){

  var html = this.Doc.body.innerHTML;
  if( html == '<br>' ) html = ''; 
  html = html.replace( /\<br\>/g , '\n' );
  this.Textarea.attr('value', html); 

  adjustSrc( this.Textarea );
}

Editor.prototype.setHTML =

function Editor_setHTML() {
  //source = this.Textarea.attr('value').br() ;

  //_source = source.replace( /\n/g , '<br />');

  this.Doc.body.innerHTML = this.Textarea.attr('value').br();

}

//***********


String.prototype.br = function() {
                    var newstr = this.replace( /\n/g , '<br />' );
                    return newstr;
}
String.prototype.unbr = function() {
                    var newstr = this.replace( /\<br\>/g , '\n' );
                    return newstr;
}

//*****************


Editor.prototype.preview =

function Editor_preview( source ) {
    var mode = this.checkMode();

    switch( mode ) {
    case 'add_new_blog' :

         if( !$( '#addContent-preview' )[0] ) {
             $('#addContent').after('<li class="listLi blog"><div class="text"><h4><a href="">Preview</a></h4><p class="showReview">Created <span class="timestamp"><a href="">00:00am</a></span><span class="separator">.</span></p><div id="addContent-preview" class="review">[REVIEW]</div></div></li>');     
         }
         $( '#addContent-preview' ).html( source );
   break;
   
   case 'edit_blog' : 
        this.EditorBox.parents('div.text').find('div.review').html( source );
        //var xy = findPos( this.EditorBox.parents('div.text')[0] );
        //window.scroll( xy[0] , xy[1] );
        break;
        
   case 'contact' :
        if( !$( '#contact-preview' )[0] ) {
             $('ul#msgListContainer').prepend('<li class="listLi" id="contact-preview" ><div class="text"><p><a href="#" class="username">Preview</a>: <span class="message" >[PREVIEW]</span></p><ul class=""><li class="right last"><p class="date">00:00am</p></li></ul></div><span class="img"><a href=""><img  width="64" title="Preview" alt="preview" src="http://cdn.stumble-upon.net/images/nopic2_60x60.jpg"/></a></span></li>');     
         }
         $( '#contact-preview' ).find('span.message').html( source );

         $( '#contact-preview' ).find('a.username').text( usrname() );
         $( '#contact-preview' ).find('span.img img').attr('src' , usrpic());
   break;
   case 'forum':
        ch = $('form[action="#end"]').prev('table').children('tbody')[0].lastChild.previousSibling;

        if( !$( '#forum-preview' )[0] ) {
        $( ch )
        .after('<tr><td colspan="3"><hr style="margin-bottom: 0px;" class="bg"/></td></tr><tr id="forum-preview"><td valign="top" align="center" class="lightbg pdgTopSm pdgBottomSm"><img class="usrid" hspace="8" border="0" src=""/><br/><span class="mini"></span></td><td width="100%" valign="top" style="vertical-align: top;" class="lightbg pdgBottomSm"><table width="100%" cellspacing="0" cellpadding="2"><tbody><tr><td><a name="end"/><a class="usrname" href="#" target="_top">[USERNAME]</a></td><td align="right" style="text-align: right;"><span class="date"><b>00:00</b></span></td></tr><tr><td colspan="2" class="post-content">[POSTEXT]</td></tr></tbody></table><br/><br style="font-size: 4px;"/></td></tr>');
 }
 $( '#forum-preview' ).find('.post-content').html( source );
 $( '#forum-preview' ).find('.usrname').text( usrname() );
 $( '#forum-preview' ).find('.usrid').attr( 'src' , usrpic() );
   break;
   }
         return source;
}

function usrname(){
return $('a[href="/favorites/"]')[0].textContent.match( /Hi\s(.+)/ )[1];
}
function usrid(){
var id =  $('input[name="auth_user"]').val();
if( !id ) id = document.body.innerHTML.match(/\&uid\=(\d+)/)[1];
return id;
}
function usrpic(){
var id = usrid();
var str = '';
( id ) ? str = 'http://cdn.stumble-upon.com/superminipics/' + id + '.jpg'
: str = 'http://cdn.stumble-upon.net/images/nopic2_60x60.jpg';
return str;
}



Editor.prototype.checkMode =

function Editor_checkMode() {
         if( this.EditorBox.parents( '#addContent' ).length > 0 )
             return 'add_new_blog';
         else if( this.EditorBox.parents( 'div.editReview' ).length > 0 )
              return 'edit_blog';
         if( $('#msgContent')[0] )
             return 'contact';
         if( $('#posttext')[0] )
             return 'forum';
}

Editor.prototype.cmd_createbox = 

function Editor_cmd_createbox ( value ) {
    css = "border: 1px solid gray; -moz-border-radius: 8px; -moz-box-shadow: 0px 0px 3px 1px gray; padding: 10px; margin: 4px; text-align: justify;"
    
    var ul = this.Doc.createElement( 'div' );
    ul.className = "_box"
    ul.setAttribute('style' , css );

    if(  this.Doc.body.firstChild.className != '_box' ) 
      $( this.Doc.body ).wrapInner(ul);
  
}


Editor.prototype.normalize = function() {
	this.Doc.body.normalize();
	return this;
}

Editor.prototype.range = function() {
var range = this.Iframe[0].contentWindow.getSelection().getRangeAt( 0 );
return extRange( range );

}

Editor.prototype.insertImage = insertImage;






function processHTML( string ) {

  var temorary_container = document.createElement('div');
  temorary_container.innerHTML = string;
  var spans = temorary_container.getElementsByTagName('span');

  
  
  for(var i=0;i<spans.length;i++) {
    if( spans[i].nodeName == "SPAN" ) 
  
      retagNode( spans[i] , 'font' );
  }
  
 /*var sups = temorary_container.getElementsByTagName('sup');
  for( var i=0;i<sups.length;i++) {
    var newsup = retagNode( sups[i] , 'font' );
    $$( newsup ).style('vertical-align: super; font-size: smaller;');
  }
  
  var subs = temorary_container.getElementsByTagName('sub');
  for( var i=0;i<subs.length;i++) {
    var newsub = retagNode( subs[i] , 'font' );
    $$( newsub ).style('vertical-align: sub; font-size: smaller;');
  }*/
  
  var divs = temorary_container.getElementsByTagName('div');
  for( var i=0;i<divs.length;i++) {
    var newnode = retagNode( divs[i] , 'ul' );

  }
  
  bgMatch = /url\(\s*([^\'\(\)]+)\s*\)/;
  
  result = temorary_container.innerHTML;
  var c = 0;
  for( var i=0; i<result.length; i++  ){
         var match = result.match( bgMatch );
         if( !match ) break;
         else {
              var url = match[1];
              var bg = match[0];
              result = result.replace( bg , "url(\'" + url + "\')" );
         }
  }       

  return result;
  
}

function retagNode( node , tag ) {
    var newnode = node.ownerDocument.createElement(tag);
    
    //copy children
    for(var j=0;j< node.childNodes.length;j++ ) {
      newnode.appendChild( node.childNodes[j].cloneNode( true ) );
    }
    
    //copy attributes
    for( var k=0; k<node.attributes.length; k++ ) {
      a = node.attributes[k];
      $( newnode ).attr( a.nodeName , a.nodeValue );    
    }
    
    
    style_attr = $( node ).attr('style');
    $( newnode ).attr('style', style_attr );
    node.parentNode.replaceChild( newnode , node );
    
    return newnode;
    
  }
  


function adjustEditor( iframe ) {

  iframe.style.width = iframe.parentNode.clientWidth - 5 + 'px';

  if( doc.body.scrollHeight > 150 )
    iframe.style.height = doc.body.scrollHeight+'px';
  else 
    iframe.style.height = '150px';
}

function adjustSrc( textarea ) {
  textarea[0].style.width = '100%';
  if( textarea[0].scrollHeight > 100 )
    textarea[0].style.height = textarea[0].scrollHeight+'px';
  else 
    textarea[0].style.height = '100px';
}

function getStyle( el , node ) {
  style = window.getComputedStyle( el ,'');
  if( node ) style = style[node];
  return style;
}

function bodyDOMAttrModified(e){

  lastEditLocation = 'editor'; 
  $(iframe).attr('modified',true);


}

function bodyDOMCharacterDataModified(e){

  lastEditLocation = 'editor'; 
  $(iframe).attr('modified',true);

  iframe.adjust();

}

function sourceDOMCharacterDataModified(e){

  lastEditLocation = 'source'; 

  adjustSrc();
  setHTML();
}

function clear( parent ) {
createDiv( parent , 'os_clear' );
}





function addStyle( id , html ) {
  var st = document.getElementById( id );
  if( !st ) {
    var st = document.createElement('style');
    st.type = 'text/css';
    st.id = id;
    $('head')[0].appendChild( st );
  }
  
  st.innerHTML = html;
  
}



function createListener( fn , scope ) {
  var newf = function( e ) {
    fn.call( scope, e );
  }
  return newf;
}

initialize();