var editor = function(){
	var _this = this;
	var _dsrteIframe = null;
	var _plugins = null;
	
	return {
		remove: function(){
			var id = _this.iframe.id;
			_dsrteIframe = null;
			//_plugins = null;
			_this.doc = null;
			_this.frame = null;
			_this.iframe = null;
			$( '#'+id+'-cmd .cmd' ).each( function() {
				$(this).unbind();
			});
			$('#dsrte-image-url-ok').unbind();
			$('#dsrte-image-ok').unbind();
			$('#dsrte-audio-url-ok').unbind();
			$('#dsrte-audio-ok').unbind();
		},
		setContent: function(tmpContent){
			//_this.doc.write( tmpContent );
		},
		init: function($content){
			var self = _this;
			_dsrteIframe = $('#dsrte:first')[0];
			_this.modified = false;
			_this.iframe = _dsrteIframe;
			_this.frame = _this.iframe.contentWindow;
			_this.doc = _this.iframe.contentDocument;

			//var editObjectModeFlag = HyperCities.mainMap.getAddMediaControl().getEditObjectMode();
			
			if (typeof($content) !== 'undefined' && $content !== null )
				_this.preloadedHtml = $content;
			else
				_this.preloadedHtml = "Type something here!";
			
			_this.doc.designMode = 'on';
			try {
				_this.doc.execCommand( 'useCSS', false, true );
			} 
			catch ( e ) 
			{};
				
			//TODO
			editor.CallAllPlugins( _this, 'OnLoad' );
			// Create document
			_this.doc.open();
			_this.doc.write( _this.preloadedHtml );
			_this.doc.close();
			//$( 'head', _this.doc ).append( '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><link rel="stylesheet" href="styles.css" style="text/css" />' );
			$( 'head', _this.doc ).append( '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' );
			$( 'body', _this.doc ).css( 'backgroundColor', '#ffffff' );

			/*
			if(editObjectModeFlag){
				$( 'body', _this.doc ).append(editObject.getContent());
				$('#dsrte').contents().find('object.audio').replaceBack('<img></img>','audio');
				$('#dsrte').contents().find('object.shockwave').replaceBack('<img></img>','shockwave');
			}*/
			
			_this.preloadedHtml = false;
			_this.doc.addEventListener( 'keypress', function( e ) {
				editor.OnKeyPress( e );
			}, true );
			// Add Resize handler if needed
			if ( $('#'+_this.iframe.id+'-resize').size() > 0 ) {
				new dsrteResizer( _this );
			}
			// Activate commands on panel
			editor.PreparePanel();
		},//end  of init function
		
		OnKeyPress: function( e ) {
			// Update document modification flag
			_this.modified = true;
			// Handle shortcut keys, if necessary
			if ( e.ctrlKey ) {

				var k = String.fromCharCode( e.charCode ).toLowerCase();
				var c = '';
				if ( k == ctrlb )
					c = 'bold';
				else if ( k == ctrli )
					c = 'italic';
				else if ( k == ctrlu )
					c = 'underline';
				else
					return;
					// Apply shortcut
					_this.frame.focus();
					_this.doc.execCommand( c, false, null );
					_this.frame.focus();
					// Stop event propagation for this shortcut
					e.preventDefault();
					e.stopPropagation();
			}
		},
		
		PreparePanel: function() {
			var dsrte = _this;
			var id = dsrte.iframe.id;
			// Handle command buttons
			$( '#'+id+'-cmd .cmd' ).each( function(){
				var $this = $( this );
				// css hover fix for IE
				// Call Plugins' PrepareCommand method
				var a = $this.attr( 'args' );
				var pnl = $( '#'+id+'-'+a );
				if ( editor.CallPlugin( dsrte, 'PrepareCommand', $this.attr( 'cmd' ), a, pnl, $this ) == false )
				{
					// special case - Insert HTML command is not implemented as a plugin!
					if ( a == 'html' )
					{
						$( '#'+id+'-html-ok' ).click( function() {
							dsrte.frame.focus();
							editor.PasteHTML( $( '#'+id+'-html-html' ).val() );
							dsrte.frame.focus();
							$( '#'+id+'-html' ).val( '' );
							pnl.slideUp();
						} );
					}
				}
				// Handle command click events
				$this.click( function() {
					var cmd = $this.attr( 'cmd' );
					var args = $this.attr( 'args' );
					var panel = $( '#'+dsrte.iframe.id+'-'+args );
					// Hide all open panels
					editor.hidePanels();
					// Execute command
					editor.CommandClick( $this, cmd, args, panel );
					// Update modification flag
					_this.modified = true;
					return false;
				} );
			});

			// Handle comboboxes
			$( '#'+dsrte.iframe.id+'-cmd select' ).each( function() {
				var $this = $(this);
				$this.change( function() {
					if ( this.selectedIndex > 0 ) {
						dsrte.doc.execCommand( $this.attr( 'cmd' ), false, this.value );
						dsrte.modified = true;
					}
					this.selectedIndex = 0;
					dsrte.frame.focus();
				});
			});
		},

		hidePanels : function() {
			$( _this.iframe ).parents( 'table:first' ).find( '.panel' ).hide();
		},
						
		PasteHTML : function( html ) {
			if ( _this.doc.selection ) {
				var rng = _this.doc.selection.createRange();
				rng.pasteHTML( html );
			} else {
				var rng = _this.frame.getSelection().getRangeAt(0);
				rng.deleteContents();
				rng.insertNode( $( html.indexOf( '<' ) == -1 ? '<span>'+html+'</span>' : html )[0] );
			}
		},
		
		CallPlugin :function( dsrte, func, command, arguments, panel, $this ) {
			return ( _plugins != null) && ( _plugins[command] != null) && ( _plugins[command][func] != null) && ( _plugins[command][func]( dsrte, arguments, panel, $this ) == true);
		},

		CommandClick : function( $this, cmd, args, panel ) {
			if ( editor.CallPlugin( _this, 'ExecuteCommand', cmd, args, panel ) == false ) {
				switch ( args ) {
					// Switch editor's text to normal text (show HTML tags)
					case 'text':
					$this.attr( 'args', 'wysiwyg' );
					var src = _this.doc.createTextNode( _this.doc.body.innerHTML );
					_this.doc.body.innerHTML = "";
					_this.doc.body.appendChild( src );
					break;
					// Switch editor's text to WYSIWYG view (HTML view)
					case 'wysiwyg':
					$this.attr( 'args', 'text' );
					var src = _this.doc.body.ownerDocument.createRange();
					src.selectNodeContents( _this.doc.body );
					_this.doc.body.innerHTML = src.toString();
					break;
					// Show Insert HTML panel
					case 'html':
					panel.slideToggle();
					break;
					// Execute internal browser command
					default:
					_this.doc.execCommand( cmd, false, '' );
					_this.frame.focus();
					break;
				}
			}
		},//end of Command Click function
		
		CallAllPlugins : function( dsrte, func, arguments ) {
			/*func = OnLoad*/
			if ( _plugins != null ) {

				$.each( _plugins, function( cmd, obj ) {
					if ( obj[func] != null )
					{
						obj[func]( dsrte, arguments );
					}
				} );
			}
		},
		
		RegisterPlugin : function( pluginObj, command ) {

			if ( _plugins == null )
			_plugins = {};
			_plugins[command] = pluginObj;
		},
		
		setupEditor: function($content) {
			HyperCities.mainMap.enableSync(false);
	
			$("#cmd-dsrte-bold").attr({"cmd":"bold"});
			$("#cmd-dsrte-italic").attr({"cmd":"italic"});
			$("#cmd-dsrte-underline").attr({"cmd":"underline"});
			$("#cmd-dsrte-justifyleft").attr({"cmd":"justifyleft"});
			$("#cmd-dsrte-justifycenter").attr({"cmd":"justifycenter"});
			$("#cmd-dsrte-justifyright").attr({"cmd":"justifyright"});
			$("#cmd-dsrte-insertunorderedlist").attr({"cmd":"insertunorderedlist"});
			$("#cmd-dsrte-insertorderedlist").attr({"cmd":"insertorderedlist"});
			$("#cmd-dsrte-fgcolor").attr({"cmd":"fgcolor","args":"forecolor"});
			$("#cmd-dsrte-bgcolor").attr({"cmd":"bgcolor","args":"hilitecolor"});
			$("#cmd-dsrte-fontsize").attr({"cmd":"fontsize"});
			$("#cmd-dsrte-image").attr({"cmd":"image","args":"image","path":"./uploadhandler.php"})    ;
			$("#cmd-dsrte-audio").attr({"cmd":"audio","args":"audio","path":"./uploadAudio.php"});
			$("#cmd-dsrte-source").attr({"cmd":"source","args":"text"});
			$("#cmd-dsrte-media").attr({"cmd":"media"});
			editor.init($content);
		},
		
		removeEditor: function() {
			editor.remove();
		}
	};
}(); //end of HC.editor


/**
* Retrieve current editing HTML.
*
* @return
*   HTML string
*//*
editor.prototype.getDoc = function() {

return typeof( this.preloadedHtml ) == 'string' ? this.preloadedHtml : this.doc.body.innerHTML;
};*/

/**
* Set current editing HTML.
*
* @param String html
*   HTML string to apply to this document
* @return
*   Nothing
*//*
editor.prototype.setDoc = function( html ) {

if ( typeof( this.preloadedHtml ) == 'string' )
this.preloadedHtml = html;
else
this.doc.body.innerHTML = html;
};*/




/**
* Handle command button click for built-in and plugins' commands.
*
* @param jQuery $this
*   jQuery object of command div clicked
* @param String cmd
*   Command identifier
* @param String args
*   Additional command arguments
* @param jQuery panel
*   jQuery object of associated panel
*/

/**
* Register a new Plugin class with dsRTE.
* It is recommended to call this function before creating a dsRTE instance so the OnLoad event
* may also be called.
*
* @param Object pluginObj
*   Plugin instance.
* @param String command
*   command related to this plugin
*/
/*dsRTE.RegisterPlugin = function( pluginObj, command ) {

if ( dsRTE.plugins == null )
dsRTE.plugins = {};

dsRTE.plugins[command] = pluginObj;
};*/

/**
* Internal use.
* Call a plugin's method to perform a specific action.
* If the Plugin implements the called function, it MUST RETURN TRUE!
* Otherwise, processing will continue and the results may be undefined.
*
* @param Object dsrte
*   dsRTE object
* @param String func
*   Plugin function to execute
* @param String command
*   Command to execute (plugin-registered)
* @param String arguments
*   Command argumetns to pass to plugin
* @param jQuery panel
*   jQuery object of associated command panel (only for PrepareCommand call)
* @param jQuery $this
*   jQuery object of command div
* @return
*   True if command was handled, False otherwise
*/
/*editor.CallPlugin = function( dsrte, func, command, arguments, panel, $this ) {

return (dsRTE.plugins != null) && (dsRTE.plugins[command] != null) && (dsRTE.plugins[command][func] != null) && (dsRTE.plugins[command][func]( dsrte, arguments, panel, $this ) == true);
};*/

/**
* Call all registered plugins to perform some action.
*
* @param Object dsrte
*   dsRTE object
* @param String func
*   Plugin function to execute
* @param String arguments
*   Command arguments to pass to plugin
* @return
*   Nothing
*/

/*dsRTE.CallAllPlugins = function( dsrte, func, arguments ) {

if ( dsRTE.plugins != null ) {

$.each( dsRTE.plugins, function( cmd, obj ) {

if ( obj[func] != null )
obj[func]( dsrte, arguments );
} );
}
};*/


