Index: /MediaWiki/trunk/FCKeditor.body.php
===================================================================
--- /MediaWiki/trunk/FCKeditor.body.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditor.body.php	(revision 2388)
@@ -1,5 +1,21 @@
 <?php
+/**
+ * Options for FCKeditor
+ * [start with FCKeditor]
+ */
+define("RTE_VISIBLE", 1);
+/**
+ * Options for FCKeditor
+ * [show toggle link]
+ */
+define('RTE_TOGGLE_LINK', 2);
+/**
+ * Options for FCKeditor
+ * [show popup link]
+ */
+define('RTE_POPUP', 4);
 
 class FCKeditor_MediaWiki {
+	public $showFCKEditor;
 	private $count = array();
 	private $wgFCKBypassText = "";
@@ -78,5 +94,5 @@
 		*/
 		if ( (!$wgUser->getOption( 'showtoolbar' ) || $wgUser->getOption( 'riched_disable' ) || !$wgFCKEditorIsCompatible) ||
-				in_array($wgTitle->getNamespace(), $this->getExcludedNamespaces()) ||
+				in_array($wgTitle->getNamespace(), $this->getExcludedNamespaces()) || !($this->showFCKEditor & RTE_VISIBLE) ||
 				false !== strpos($pageEditor->textbox1, "__NORICHEDITOR__")
 			) {
@@ -269,4 +285,26 @@
 		global $wgFCKWikiTextBeforeParse;
 
+		if (!isset($this->showFCKEditor))
+		{
+			$this->showFCKEditor = 0;
+			if ( !$wgUser->getOption( 'riched_start_disabled' ) ) {
+				$this->showFCKEditor += RTE_VISIBLE;
+			}
+			if ( $wgUser->getOption( 'riched_use_popup' ) ) {
+				$this->showFCKEditor += RTE_POPUP;
+			}
+			if ( $wgUser->getOption( 'riched_use_toggle' ) ) {
+				$this->showFCKEditor += RTE_TOGGLE_LINK;
+			}
+		}
+
+		if( (!empty($_SESSION['showMyFCKeditor'])) && ($wgUser->getOption( 'riched_toggle_remember_state' )))
+		{
+			//clear RTE_VISIBLE flag
+			$this->showFCKEditor &= ~RTE_VISIBLE ;
+			//get flag from session
+			$this->showFCKEditor |= $_SESSION['showMyFCKeditor'] ;			
+		}
+	
 		if (!$wgUser->getOption( 'showtoolbar' ) || $wgUser->getOption( 'riched_disable' ) || !$wgFCKEditorIsCompatible) {
 			return true;
@@ -281,10 +319,13 @@
 		}
 
-		$options = new FCKeditorParserOptions();
-		$options->setTidy(true);
-		$parser = new FCKeditorParser();
-		$parser->setOutputType(OT_HTML);
 		$wgFCKWikiTextBeforeParse = $form->textbox1;
-		$form->textbox1 = $parser->parse($form->textbox1, $wgTitle, $options)->getText();
+		if ($this->showFCKEditor & RTE_VISIBLE)
+		{
+			$options = new FCKeditorParserOptions();
+			$options->setTidy(true);
+			$parser = new FCKeditorParser();
+			$parser->setOutputType(OT_HTML);
+			$form->textbox1 = $parser->parse($form->textbox1, $wgTitle, $options)->getText();
+		}
 
 		$printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css?$wgStyleVersion" );
@@ -317,28 +358,56 @@
 HEREDOC;
 
+		$script .= '<script type="text/javascript"> ';
 		if (!empty($userStyles)) {
-			$script .= '
-<script type="text/javascript"> 
-sEditorAreaCSS += ",'.implode(',', $userStyles).'";
-</script>';
-		}
-
+			$script .= 'sEditorAreaCSS += ",'.implode(',', $userStyles).'";';
+		}
+		$script .= '
+var showFCKEditor = '. $this->showFCKEditor .';
+var popup = false;		//pointer to popup document
+var firstLoad = true;
+var editorMsgOn = "'. wfMsg( 'textrichditor' ) .'";
+var editorMsgOff = "'. wfMsg( 'tog-riched_disable' ) .'";
+var editorLink = "'. (($this->showFCKEditor & RTE_VISIBLE)? wfMsg( 'tog-riched_disable' ): wfMsg( 'textrichditor' )) .'";		
+var saveSetting = '. ($wgUser->getOption( 'riched_toggle_remember_state' ) ?  1 : 0) .';
+var RTE_VISIBLE = '.RTE_VISIBLE.';
+var RTE_TOGGLE_LINK = '.RTE_TOGGLE_LINK.';
+var RTE_POPUP = '.RTE_POPUP.';
+
+
+var oFCKeditor = new FCKeditor( "wpTextbox1" ) ;
+
+//Set config
+oFCKeditor.BasePath = "'.$wgScriptPath.'/'.$wgFCKEditorDir.'/" ;
+oFCKeditor.Config["CustomConfigurationsPath"] = "'.$wgScriptPath.'/'.$wgFCKEditorExtDir.'/fckeditor_config.js" ;
+oFCKeditor.Config["EditorAreaCSS"] = "'.$wgScriptPath.'/'.$wgFCKEditorExtDir.'/css/fckeditor.css" ;
+oFCKeditor.ToolbarSet = "'. $wgFCKEditorToolbarSet .'" ; 
+oFCKeditor.ready = true;
+';
+		$script .= '</script>';
+		
+		$newWinMsg = wfMsg('rich_editor_new_window');
 		$script .= <<<HEREDOC
 <script type="text/javascript"> 
 
-// Remove the mwSetupToolbar onload hook to avoid a JavaScript error with FF.
-if ( window.removeEventListener )
-	window.removeEventListener( 'load', mwSetupToolbar, false ) ;
-else if ( window.detachEvent )
-	window.detachEvent( 'onload', mwSetupToolbar ) ;
-	
-mwSetupToolbar = function() { return false ; } ;
+//IE hack to call func from popup
+function FCK_sajax(func_name, args, target) {
+	sajax_request_type = 'POST' ;
+	sajax_do_call(func_name, args, function (x) {
+		// I know this is function, not object
+		target(x);
+		}
+	);
+}
 
 function onLoadFCKeditor()
 {
-	if ( document.getElementById('wpTextbox1') )
+	if (!(showFCKEditor & RTE_VISIBLE)) 
+		showFCKEditor += RTE_VISIBLE;
+	firstLoad = false;
+	realTextarea = document.getElementById('wpTextbox1');
+	if ( realTextarea )
 	{
 		var height = $wgFCKEditorHeight ;
-		
+		realTextarea.style.display = 'none';
 		if ( height == 0 )
 		{
@@ -362,14 +431,9 @@
 		
 		// Create the editor instance and replace the textarea.
-		var oFCKeditor = new FCKeditor('wpTextbox1') ;
-		oFCKeditor.BasePath = '$wgScriptPath/$wgFCKEditorDir/' ;
-		oFCKeditor.Config['CustomConfigurationsPath'] = '$wgScriptPath/$wgFCKEditorExtDir/fckeditor_config.js' ;
-		oFCKeditor.Config['EditorAreaCSS'] = "$wgScriptPath/$wgFCKEditorExtDir/css/fckeditor.css" ;
 		oFCKeditor.Height = height ;
-		oFCKeditor.ToolbarSet = '$wgFCKEditorToolbarSet' ;
 		oFCKeditor.ReplaceTextarea() ;
 		
 		// Hide the default toolbar.
-		document.getElementById('toolbar').style.cssText = 'display:none;' ;
+		document.getElementById('toolbar').style.display = 'none' ;
 		// do things with CharInsert for example
 
@@ -378,23 +442,22 @@
 			edittools_markup.style.display = 'none' ;
 		}
-		insertTags = function (tagOpen, tagClose, sampleText)
+		FCKeditorInsertTags = function (tagOpen, tagClose, sampleText, oDoc)
 		{
 			var txtarea;
 
-			if ( !(typeof(FCK) == "undefined") && !(typeof(FCK.EditingArea) == "undefined") )
+			if ( !(typeof(oDoc.FCK) == "undefined") && !(typeof(oDoc.FCK.EditingArea) == "undefined") )
 			{
-				txtarea = FCK.EditingArea.Textarea ;
-			}
-			else if (document.editform)
+				txtarea = oDoc.FCK.EditingArea.Textarea ;
+			}
+			else if (oDoc.editform)
 			{
 				// if we have FCK enabled, behave differently...
-				FCKarea = document.getElementById( oFCKeditor.InstanceName ) ;
-				if ( FCKarea.style.display == 'none' )
+				if ( showFCKEditor & RTE_VISIBLE )
 				{
-					SRCiframe = document.getElementById ('wpTextbox1___Frame') ;
+					SRCiframe = oDoc.getElementById ('wpTextbox1___Frame') ;
 					if ( SRCiframe )
 					{
 						if (window.frames[SRCiframe])
-							SRCdoc = window.frames[SRCiframe].document ;
+							SRCdoc = window.frames[SRCiframe].oDoc ;
 						else
 							SRCdoc = SRCiframe.contentDocument ;
@@ -415,5 +478,5 @@
 				else
 				{
-					txtarea = document.editform.wpTextbox1 ;
+					txtarea = oDoc.editform.wpTextbox1 ;
 				}
 			}
@@ -421,5 +484,5 @@
 			{
 				// some alternate form? take the first one we can find
-				var areas = document.getElementsByTagName( 'textarea' ) ;
+				var areas = oDoc.getElementsByTagName( 'textarea' ) ;
 				txtarea = areas[0] ;
 			}
@@ -427,19 +490,19 @@
 			var selText, isSample = false ;
 
-			if ( document.selection  && document.selection.createRange ) 
+			if ( oDoc.selection  && oDoc.selection.createRange ) 
 			{ // IE/Opera
 
 				//save window scroll position
-				if ( document.documentElement && document.documentElement.scrollTop )
-					var winScroll = document.documentElement.scrollTop ;
-				else if ( document.body )
-					var winScroll = document.body.scrollTop ;
+				if ( oDoc.documentElement && oDoc.documentElement.scrollTop )
+					var winScroll = oDoc.documentElement.scrollTop ;
+				else if ( oDoc.body )
+					var winScroll = oDoc.body.scrollTop ;
 
 				//get current selection
 				txtarea.focus() ;
-				var range = document.selection.createRange() ;
+				var range = oDoc.selection.createRange() ;
 				selText = range.text ;
 				//insert tags
-				checkSelectedText() ;
+				checkSelected();
 				range.text = tagOpen + selText + tagClose ;
 				//mark sample text as selected
@@ -453,8 +516,8 @@
 				range.select();
 				//restore window scroll position
-				if ( document.documentElement && document.documentElement.scrollTop )
-					document.documentElement.scrollTop = winScroll ;
-				else if ( document.body )
-					document.body.scrollTop = winScroll ;
+				if ( oDoc.documentElement && oDoc.documentElement.scrollTop )
+					oDoc.documentElement.scrollTop = winScroll ;
+				else if ( oDoc.body )
+					oDoc.body.scrollTop = winScroll ;
 
 			} 
@@ -500,41 +563,164 @@
 	}
 }
-addOnloadHook( onLoadFCKeditor ) ;
-</script>
+function checkSelected()
+{
+	if (!selText) {
+		selText = sampleText;
+		isSample = true;
+	} else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
+		selText = selText.substring(0, selText.length - 1);
+		tagClose += ' '
+	} 
+}
+function initEditor()
+{	
+	var toolbar = document.getElementById('toolbar') ;
+	//show popup or toogle link
+	if (showFCKEditor & (RTE_POPUP|RTE_TOGGLE_LINK)){
+		//add new toolbar before wiki toolbar
+		var fckTools = document.createElement('div');
+		fckTools.setAttribute('id', 'fckTools');
+		toolbar.parentNode.insertBefore( fckTools, toolbar );
+		
+		var SRCtextarea = document.getElementById( "wpTextbox1" ) ;
+		if (showFCKEditor & RTE_VISIBLE) SRCtextarea.style.display = "none";
+	}
+
+	if (showFCKEditor & RTE_TOGGLE_LINK)
+	{
+		fckTools.innerHTML='[<a class="fckToogle" id="toggle_wpTextbox1" href="javascript:void(0)" onclick="ToggleFCKEditor(\'toggle\',\'wpTextbox1\')">'+ editorLink +'</a>] ';
+	}
+	if (showFCKEditor & RTE_POPUP)
+	{
+		var style = (showFCKEditor & RTE_VISIBLE) ? 'style="display:none"' : "";
+		fckTools.innerHTML+='<span ' + style + ' id="popup_wpTextbox1">[<a class="fckPopup" href="javascript:void(0)" onclick="ToggleFCKEditor(\'popup\',\'wpTextbox1\')">{$newWinMsg}</a>]</span>';
+	}
+
+	if (showFCKEditor & RTE_VISIBLE)
+	{
+		if ( toolbar )		//insert wiki buttons
+		{
+			// Remove the mwSetupToolbar onload hook to avoid a JavaScript error with FF.
+			if ( window.removeEventListener )
+				window.removeEventListener( 'load', mwSetupToolbar, false ) ;
+			else if ( window.detachEvent )
+				window.detachEvent( 'onload', mwSetupToolbar ) ;
+			mwSetupToolbar = function() { return false ; } ;
+
+			for (var i = 0; i < mwEditButtons.length; i++) {
+				mwInsertEditButton(toolbar, mwEditButtons[i]);
+			}
+			for (var i = 0; i < mwCustomEditButtons.length; i++) {
+				mwInsertEditButton(toolbar, mwCustomEditButtons[i]);
+			}
+		}
+		onLoadFCKeditor();
+	}
+	return true;
+}
+addOnloadHook( initEditor );
+
 HEREDOC;
 
-/*
-$script .= <<<HEREDOC
-<script type="text/javascript">
-function showSource() {
-	var wp = document.getElementById("wpDiff");
-	var s = document.createElement("input");
-	s.type="submit";
-	s.value="Wiki2HTML";
-	s.name="Wiki2HTML";
-	s.onclick = function wiki2html() {
-		var oEditor = FCKeditorAPI.GetInstance('wpTextbox1');
-		WikiToHTML_Call();
-		return false;
-	}
-	wp.parentNode.insertBefore(s, wp.nextSibling);
-}
-
-var sajax_debug_mode = false;
-var sajax_request_type = "GET";
-
-function WikiToHTML_Result(result) {
-	var oEditor = FCKeditorAPI.GetInstance('wpTextbox1');
-	oEditor.SetHTML(result.responseText);
-}
-function WikiToHTML_Call() {
-	var oEditor = FCKeditorAPI.GetInstance('wpTextbox1');
-	sajax_do_call('wfSajaxWikiToHTML', [oEditor.GetHTML()], WikiToHTML_Result);
-}
-
-addOnloadHook(showSource);
-</script>
+if ($this->showFCKEditor & (RTE_TOGGLE_LINK | RTE_POPUP) ){
+	//add toogle link and handler
+	$script .= <<<HEREDOC
+
+function ToggleFCKEditor(mode, objId)
+{
+	var SRCtextarea = document.getElementById( objId ) ;
+	if(mode == 'popup'){
+		if (( showFCKEditor & RTE_VISIBLE) && ( FCKeditorAPI ))	//if FCKeditor is up-to-date
+		{
+			var oEditorIns = FCKeditorAPI.GetInstance( objId );
+			var text = oEditorIns.GetData( oEditorIns.Config.FormatSource );
+			SRCtextarea.value = text;			//copy text to textarea
+		}
+		FCKeditor_OpenPopup('oFCKeditor',objId);
+		return true;
+	}
+	
+	var oToggleLink = document.getElementById('toggle_'+ objId );
+	var oPopupLink = document.getElementById('popup_'+ objId );
+
+	if ( firstLoad )
+	{
+		// firstLoad = true => FCKeditor start invisible
+		if (oToggleLink) oToggleLink.innerHTML = "Loading...";
+		sajax_request_type = 'POST' ;
+		oFCKeditor.ready = false;
+		sajax_do_call('wfSajaxWikiToHTML', [SRCtextarea.value], function ( result ){
+			if ( firstLoad )	//still
+			{
+				SRCtextarea.value = result.responseText; //insert parsed text
+				onLoadFCKeditor();
+				if (oToggleLink) oToggleLink.innerHTML = editorMsgOff;
+				oFCKeditor.ready = true;
+			}
+		});
+		return true;
+	}
+	
+	if (!oFCKeditor.ready) return false;		//sajax_do_call in action
+	if (!FCKeditorAPI) return false;			//not loaded yet
+	var oEditorIns = FCKeditorAPI.GetInstance( objId );
+	var oEditorIframe  = document.getElementById( objId+'___Frame' );
+	var FCKtoolbar = document.getElementById('toolbar');
+	var bIsWysiwyg = ( oEditorIns.EditMode == FCK_EDITMODE_WYSIWYG );
+
+	//FCKeditor visible -> hidden
+	if ( showFCKEditor & RTE_VISIBLE)
+	{
+		var text = oEditorIns.GetData( oEditorIns.Config.FormatSource );
+		SRCtextarea.value = text;
+		if ( bIsWysiwyg ) oEditorIns.SwitchEditMode();		//switch to plain
+		var text = oEditorIns.GetData( oEditorIns.Config.FormatSource );
+		//copy from FCKeditor to textarea
+		SRCtextarea.value = text;
+		if (saveSetting)
+		{
+			sajax_request_type = 'GET' ;
+			sajax_do_call( 'wfSajaxToggleFCKeditor', ['hide'], function(){} ) ;		//remember closing in session
+		}
+		if (oToggleLink) oToggleLink.innerHTML = editorMsgOn;
+		if (oPopupLink) oPopupLink.style.display = '';
+		showFCKEditor -= RTE_VISIBLE;
+		oEditorIframe.style.display = 'none';
+		FCKtoolbar.style.display = '';
+		SRCtextarea.style.display = '';
+	}
+	//FCKeditor hidden -> visible
+	else
+	{
+		if ( bIsWysiwyg ) oEditorIns.SwitchEditMode();		//switch to plain
+		SRCtextarea.style.display = 'none';
+		//copy from textarea to FCKeditor
+		oEditorIns.EditingArea.Textarea.value = SRCtextarea.value
+		FCKtoolbar.style.display = 'none';
+		oEditorIframe.style.display = '';
+		if ( !bIsWysiwyg ) oEditorIns.SwitchEditMode();		//switch to WYSIWYG
+		showFCKEditor += RTE_VISIBLE; // showFCKEditor+=RTE_VISIBLE
+		if (oToggleLink) oToggleLink.innerHTML = editorMsgOff;
+		if (oPopupLink) oPopupLink.style.display = 'none';
+	}
+	return true;
+}
+
 HEREDOC;
-*/
+}
+
+if($this->showFCKEditor & RTE_POPUP){
+	$script .= <<<HEREDOC
+
+function FCKeditor_OpenPopup(jsID, textareaID)
+{
+	popupUrl = '${wgFCKEditorExtDir}/FCKeditor.popup.html';
+	popupUrl = popupUrl + '?var='+ jsID + '&el=' + textareaID;
+	window.open(popupUrl, null, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=1,dependent=yes');
+	return 0;
+}
+HEREDOC;
+}
+$script .= "</script>";
 
 		$wgOut->addScript($script);
@@ -545,4 +731,9 @@
 	public function onUserToggles( &$extraToggles ) {
 		$extraToggles[] = 'riched_disable';
+		$extraToggles[] = 'riched_start_disabled';
+		$extraToggles[] = 'riched_use_popup';
+		$extraToggles[] = 'riched_use_toggle';
+		$extraToggles[] = 'riched_toggle_remember_state';
+		
 		$extraToggles = array_merge($extraToggles, self::$nsToggles);
 		return true;
Index: /MediaWiki/trunk/FCKeditor.i18n.en.php
===================================================================
--- /MediaWiki/trunk/FCKeditor.i18n.en.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditor.i18n.en.php	(revision 2388)
@@ -20,3 +20,8 @@
 'tog-riched_disable_ns_category' => 'Disable rich editor within the "{{ns:Category}}" namespace',
 'tog-riched_disable_ns_category_talk' => 'Disable rich editor within the "{{ns:Category_talk}}" namespace',
+'rich_editor_new_window' => 'Open Rich editor in new window',
+'tog-riched_start_disabled' => 'Start with rich editor disabled',
+'tog-riched_use_popup' => 'Open rich editor in a popup',
+'tog-riched_use_toggle' => 'Use toggle to switch between wikitext and rich editor (replace textarea with rich editor)',
+'tog-riched_toggle_remember_state' => 'Remember last toggle state',
 );
Index: /MediaWiki/trunk/FCKeditor.i18n.pl.php
===================================================================
--- /MediaWiki/trunk/FCKeditor.i18n.pl.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditor.i18n.pl.php	(revision 2388)
@@ -3,4 +3,5 @@
 $messages = array(
 'textrichditor' => 'Rich Editor',
+'rich_editor_new_window' => 'Otwórz rich editor w nowym oknie',
 'tog-riched_disable' => 'Wyłącz Rich Editora',
 'tog-riched_disable_ns_main' => 'Wyłącz Rich Editora wewątrz głównej przestrzeni nazw',
@@ -20,3 +21,7 @@
 'tog-riched_disable_ns_category' => 'Wyłącz Rich Editora wewątrz przestrzeni nazw "{{ns:Category}}"',
 'tog-riched_disable_ns_category_talk' => 'Wyłącz Rich Editora wewątrz przestrzeni nazw "{{ns:Category_talk}}"',
+'tog-riched_start_disabled' => 'Rich editor domyślnie wyłączony',
+'tog-riched_use_popup' => 'Pozwól otwierać Rich Editor w okienku popup',
+'tog-riched_use_toggle' => 'Pozwól otwierać Rich Editor na żądanie (zastąpi domyślne pole textarea)',
+'tog-riched_toggle_remember_state' => 'Zapamiętuj ostatni stan Rich Editora',
 );
Index: /MediaWiki/trunk/FCKeditor.php
===================================================================
--- /MediaWiki/trunk/FCKeditor.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditor.php	(revision 2388)
@@ -64,5 +64,4 @@
     $wgFCKEditorHeight = "0"; // "0" for automatic ("300" minimum).
 }
-
 /**
  * Enable use of AJAX features.
@@ -76,4 +75,5 @@
 $wgAjaxExportList[] = 'wfSajaxSearchTemplateFCKeditor';
 $wgAjaxExportList[] = 'wfSajaxSearchSpecialTagFCKeditor';
+$wgAjaxExportList[] = 'wfSajaxToggleFCKeditor';
 
 $wgExtensionCredits['other'][] = array(
@@ -89,4 +89,9 @@
 
 $oFCKeditorExtension = new FCKeditor_MediaWiki();
+
 $oFCKeditorExtension->registerHooks();
 
+$wgDefaultUserOptions['riched_use_toggle'] = 1;
+$wgDefaultUserOptions['riched_start_disabled'] = 1;
+$wgDefaultUserOptions['riched_use_popup'] = 1;
+$wgDefaultUserOptions['riched_toggle_remember_state'] = 1;
Index: /MediaWiki/trunk/FCKeditor.popup.html
===================================================================
--- /MediaWiki/trunk/FCKeditor.popup.html	(revision 2388)
+++ /MediaWiki/trunk/FCKeditor.popup.html	(revision 2388)
@@ -0,0 +1,99 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+	<title>FCKeditor</title>
+	<script type="text/javascript">
+// #### URLParams: holds all URL passed parameters (like ?Param1=Value1&Param2=Value2)
+var FCKURLParams = new Object() ;
+
+var aParams = document.location.search.substr(1).split('&') ;
+for ( var i = 0 ; i < aParams.length ; i++ )
+{
+	var aParam = aParams[i].split('=') ;
+	var sParamName  = aParam[0] ;
+	var sParamValue = aParam[1] ;
+
+	FCKURLParams[ sParamName ] = sParamValue ;
+}
+
+// It is preferable to have the oFCKeditor object defined in the opener window,
+// so all the configurations will be there. In this way the popup doesn't need
+// to take care of the configurations "clonning".
+var popup = window.opener;
+var oFCKeditor = window.opener[ FCKURLParams[ 'var' ] ] ;
+oFCKeditor.Width	= '100%' ;
+oFCKeditor.Height	= '100%' ;
+oFCKeditor.Value	= popup.document.getElementById( FCKURLParams[ 'el' ] ).value ;
+
+function Ok()
+{
+	var oEditor = FCKeditorAPI.GetInstance( oFCKeditor.InstanceName ) ;
+	if ( oEditor.IsDirty() )
+	{
+		if ((window.opener.firstLoad == false) && (popup.FCKeditorAPI)) {		//already loaded
+			var parentOEditor = popup.FCKeditorAPI.GetInstance(FCKURLParams[ 'el' ]);
+			var parentIsWysiwyg = ( parentOEditor.EditMode == FCK_EDITMODE_WYSIWYG ) ;
+			var IsWysiwyg = ( oEditor.EditMode == FCK_EDITMODE_WYSIWYG ) ;
+			if ( !IsWysiwyg && parentIsWysiwyg ) 		//copy from PLAIN (popup) to WYSIWIG (parent)
+			{
+				parentOEditor.SwitchEditMode();	//switch to plain
+				var text = oEditor.GetData(parentOEditor.Config.FormatSource);
+				parentOEditor.SetHTML( text );
+			}
+			else if ( parentIsWysiwyg )
+			{
+				var text = oEditor.EditorDocument.documentElement.innerHTML;
+				parentOEditor.EditingArea.Start( text );
+			}
+			else
+			{
+				var text = oEditor.GetData(parentOEditor.Config.FormatSource);
+				parentOEditor.SetHTML( text );
+			}
+		}
+		window.opener.document.getElementById( FCKURLParams[ 'el' ] ).value = oEditor.GetData( true ) ;		// "true" means you want it formatted.
+	}
+	window.opener.focus() ;
+	window.close() ;
+	return true;
+}
+
+function Cancel()
+{
+	var oEditor = FCKeditorAPI.GetInstance( oFCKeditor.InstanceName ) ;
+	if ( oEditor.IsDirty() )
+	{
+		if ( !confirm( 'Are you sure you want to cancel? Your changes will be lost.' ) )
+			return ;
+	}
+
+	window.close() ;
+	return true;
+}
+
+	</script>
+</head>
+<body style="margin:0px 0px 10px;">
+	<table width="100%" cellspacing=0 cellpadding=0 height="100%">
+		<tr>
+			<td height="100%">
+				<div id="FCKdiv" style='width:100%;height:100%'></div>
+				<script type="text/javascript">
+document.write( '<input type="hidden" id="' + oFCKeditor.InstanceName + '" name="' + oFCKeditor.InstanceName + '" value="' + oFCKeditor._HTMLEncode( 'nic' ) + '" style="width:100%;display:none" />' ) ;
+
+popup.window.parent.FCK_sajax('wfSajaxWikiToHTML', [oFCKeditor.Value], function ( result ){
+	var FCKinput = document.getElementById( oFCKeditor.InstanceName );
+	FCKinput.value = (result.responseText);
+	document.getElementById( 'FCKdiv' ).innerHTML = oFCKeditor._GetConfigHtml() + oFCKeditor._GetIFrameHtml();
+});
+				</script>
+			</td>
+		</tr>
+		<tr valign="middle" height="40">
+			<td align="center" >
+				<input type="button" value="Ok" onclick="Ok();" style="width:120px" />
+				<input type="button" value="Cancel" onclick="Cancel();" />
+			</td>
+		</tr>
+	</table>
+</body>
+</html>
Index: /MediaWiki/trunk/FCKeditorParser.body.php
===================================================================
--- /MediaWiki/trunk/FCKeditorParser.body.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditorParser.body.php	(revision 2388)
@@ -154,5 +154,5 @@
 	 */
 	function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
-		global $wgContLang;
+		global $wgContLang, $wgUseTeX, $wgScriptPath;
 
 		wfProfileIn( __METHOD__ );
@@ -165,12 +165,9 @@
 
 		$elements = array_merge(
-		array( 'nowiki', 'gallery' ),
+		array( 'nowiki', 'gallery', 'math' ),
 		array_keys( $this->mTagHooks ) );
 		global $wgRawHtml;
 		if( $wgRawHtml ) {
 			$elements[] = 'html';
-		}
-		if( $this->mOptions->getUseTeX() ) {
-			$elements[] = 'math';
 		}
 
@@ -210,5 +207,8 @@
 						break;
 					case 'math':
-						$output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
+						if($wgUseTeX){		//normal render
+							$output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
+						}else				//show fakeimage
+							$output = '<img _fckfakelement="true" class="FCK__MWMath" _fck_mw_math="'.$content.'" src="'.$wgScriptPath.'/skins/common/images/button_math.png" />';
 						break;
 					case 'gallery':
@@ -307,4 +307,5 @@
 
 	function replaceInternalLinks( $text ) {
+		$text = preg_replace("/\[\[:(.*?)\]\]/", "[[RTECOLON$1]]", $text);	//change ':' => 'RTECOLON' in links
 		return parent::replaceInternalLinks($text);
 	}
@@ -374,4 +375,12 @@
 			foreach ($tags as $pos=>$type) {
 				$sum += $type;
+				if (!$pos) {
+					$opened = 0;
+					$closed = 0;
+				}
+				else {
+					$opened = substr_count($text, '[', 0, $pos);			//count [ 
+					$closed = substr_count($text, ']', 0, $pos);			//count ]
+				}
 				if ($sum == 1 && $lastSum == 0) {
 					$stringToParse .= strtr(substr($text, $startingPos, $pos - $startingPos), $strtr);
@@ -382,5 +391,9 @@
 					$inner = htmlspecialchars(strtr(substr($text, $startingPos, $pos - $startingPos + 19), $strtr));
 					$this->fck_mw_strtr_span['href="Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw"'] = 'href="'.$inner.'"';
-					$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = '<span class="fck_mw_template">'.str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner).'</span>';
+					if($opened <= $closed) {						// {{template}} is NOT in [] or [[]]
+						$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = '<span class="fck_mw_template">'.str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner).'</span>';
+					}else{
+						$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner);
+					}
 					$startingPos = $pos + 19;
 					$this->fck_mw_strtr_span_counter++;
Index: /MediaWiki/trunk/FCKeditorSajax.body.php
===================================================================
--- /MediaWiki/trunk/FCKeditorSajax.body.php	(revision 2387)
+++ /MediaWiki/trunk/FCKeditorSajax.body.php	(revision 2388)
@@ -156,4 +156,18 @@
 	$parser->setOutputType(OT_HTML);
 
+	wfSajaxToggleFCKeditor('show');		//FCKeditor was switched to visible
 	return $parser->parse($wiki, $wgTitle, $options)->getText();
 }
+function wfSajaxToggleFCKeditor($data) {
+	global $wgFCKEditorSaveUserSetting;
+
+	if($data == 'show'){
+		$_SESSION['showMyFCKeditor'] = RTE_VISIBLE;	//visible last time
+	}
+	else {
+		$_SESSION['showMyFCKeditor'] = 0;	//invisible
+	}
+	return "SUCCESS";
+}
+
+
Index: /MediaWiki/trunk/fckeditor_config.js
===================================================================
--- /MediaWiki/trunk/fckeditor_config.js	(revision 2387)
+++ /MediaWiki/trunk/fckeditor_config.js	(revision 2388)
@@ -37,5 +37,5 @@
 
 FCKConfig.EditorAreaStyles = '\
-.FCK__MWTemplate, .FCK__MWRef, .FCK__MWSpecial, .FCK__MWReferences, .FCK__MWNowiki, .FCK__MWIncludeonly, .FCK__MWNoinclude, .FCK__MWOnlyinclude, .FCK__MWGallery \
+.FCK__MWTemplate, .FCK__MWRef, .FCK__MWSpecial, .FCK__MWReferences, .FCK__MWMath, .FCK__MWNowiki, .FCK__MWIncludeonly, .FCK__MWNoinclude, .FCK__MWOnlyinclude, .FCK__MWGallery \
 { \
 	border: 1px dotted #00F; \
@@ -65,4 +65,10 @@
 { \
 	background-image: url(' + FCKConfig.PluginsPath + 'mediawiki/images/icon_nowiki.gif); \
+	width: 66px; \
+	height: 15px; \
+} \
+.FCK__MWMath \
+{ \
+	background-image: url(' + FCKConfig.PluginsPath + 'mediawiki/images/icon_math.gif); \
 	width: 66px; \
 	height: 15px; \
Index: /MediaWiki/trunk/mw12/FCKeditorParser_OldPP.body.php
===================================================================
--- /MediaWiki/trunk/mw12/FCKeditorParser_OldPP.body.php	(revision 2387)
+++ /MediaWiki/trunk/mw12/FCKeditorParser_OldPP.body.php	(revision 2388)
@@ -155,5 +155,5 @@
 	 */
 	function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
-		global $wgContLang;
+		global $wgContLang, $wgUseTeX, $wgScriptPath;
 
 		wfProfileIn( __METHOD__ );
@@ -166,12 +166,9 @@
 
 		$elements = array_merge(
-		array( 'nowiki', 'gallery' ),
+		array( 'nowiki', 'gallery', 'math' ),
 		array_keys( $this->mTagHooks ) );
 		global $wgRawHtml;
 		if( $wgRawHtml ) {
 			$elements[] = 'html';
-		}
-		if( $this->mOptions->getUseTeX() ) {
-			$elements[] = 'math';
 		}
 
@@ -211,5 +208,8 @@
 						break;
 					case 'math':
-						$output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
+						if($wgUseTeX){		//normal render
+							$output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
+						}else				//show fakeimage
+							$output = '<img _fckfakelement="true" class="FCK__MWMath" _fck_mw_math="'.$content.'" src="'.$wgScriptPath.'/skins/common/images/button_math.png" />';
 						break;
 					case 'gallery':
@@ -308,4 +308,5 @@
 
 	function replaceInternalLinks( $text ) {
+		$text = preg_replace("/\[\[:(.*?)\]\]/", "[[RTECOLON$1]]", $text);	//change ':' => 'RTECOLON' in links
 		return parent::replaceInternalLinks($text);
 	}
@@ -375,4 +376,12 @@
 			foreach ($tags as $pos=>$type) {
 				$sum += $type;
+				if (!$pos) {
+					$opened = 0;
+					$closed = 0;
+				}
+				else {
+					$opened = substr_count($text, '[', 0, $pos);			//count [ 
+					$closed = substr_count($text, ']', 0, $pos);			//count ]
+				}
 				if ($sum == 1 && $lastSum == 0) {
 					$stringToParse .= strtr(substr($text, $startingPos, $pos - $startingPos), $strtr);
@@ -383,5 +392,9 @@
 					$inner = htmlspecialchars(strtr(substr($text, $startingPos, $pos - $startingPos + 19), $strtr));
 					$this->fck_mw_strtr_span['href="Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw"'] = 'href="'.$inner.'"';
-					$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = '<span class="fck_mw_template">'.str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner).'</span>';
+					if($opened <= $closed) {						// {{template}} is NOT in [] or [[]]
+						$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = '<span class="fck_mw_template">'.str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner).'</span>';
+					}else{
+						$this->fck_mw_strtr_span['Fckmw'.$this->fck_mw_strtr_span_counter.'fckmw'] = str_replace(array("\r\n", "\n", "\r"),"fckLR",$inner);
+					}
 					$startingPos = $pos + 19;
 					$this->fck_mw_strtr_span_counter++;
Index: /MediaWiki/trunk/plugins/mediawiki/dialogs/link.html
===================================================================
--- /MediaWiki/trunk/plugins/mediawiki/dialogs/link.html	(revision 2387)
+++ /MediaWiki/trunk/plugins/mediawiki/dialogs/link.html	(revision 2388)
@@ -73,4 +73,7 @@
 		bLinkEqualsName = true ;
 
+	if ( sHRef.toLowerCase().StartsWith( 'rtecolon' ) )
+		sHRef = ":" + sHRef.substring(8) ;
+			
 	GetE('txtUrl').value = sHRef ;
 }
@@ -178,4 +181,6 @@
 {
 	var sUri = GetE('txtUrl').value ;
+	if (sUri.StartsWith( ':' ) )
+		sUri = sUri.replace(/:/, "rtecolon");
 	var sInnerHtml ;
 
Index: /MediaWiki/trunk/plugins/mediawiki/dialogs/math.html
===================================================================
--- /MediaWiki/trunk/plugins/mediawiki/dialogs/math.html	(revision 2387)
+++ /MediaWiki/trunk/plugins/mediawiki/dialogs/math.html	(revision 2388)
@@ -92,14 +92,27 @@
 function UpdateImageFromAjax( response )
 {
+	oEditor.FCKUndo.SaveUndoStep() ;
+
 	if ( !oMathImage )
+	{
 		oMathImage = FCK.CreateElement( 'IMG' ) ;
+		oMathImage.className = 'FCK__MWMath' ;
+		oMathImage.src = FCKConfig.PluginsPath + 'mediawiki/images/icon_math.gif' ;
+	}
 	else
-		oEditor.FCKUndo.SaveUndoStep() ;
+	{
+		if ( response.responseText )
+		{
+			oMathImage.src = response.responseText ;
+			SetAttribute( oMathImage, "_fcksavedurl", response.responseText ) ;
+		}
+		else
+		{
+			oMathImage.src = FCKConfig.PluginsPath + 'mediawiki/images/icon_math.gif' ;
+		}
+	}
 	
 	SetAttribute( oMathImage, "_fck_mw_math", GetE('xTemplateRaw').value.Trim() ) ;
 	SetAttribute( oMathImage, "_fckfakelement", 'true' ) ;
-
-	oMathImage.src = response.responseText ;
-	SetAttribute( oMathImage, "_fcksavedurl", response.responseText ) ;
 
 	// Call it using setTimeout to avoid a strange behavior in Firefox.
Index: /MediaWiki/trunk/plugins/mediawiki/fckplugin.js
===================================================================
--- /MediaWiki/trunk/plugins/mediawiki/fckplugin.js	(revision 2387)
+++ /MediaWiki/trunk/plugins/mediawiki/fckplugin.js	(revision 2388)
@@ -91,11 +91,16 @@
 	if ( oToolbarButton.SourceView && (FCK_EDITMODE_SOURCE == FCK.EditMode) )
 	{
+		if ( !window.parent.popup )
+			var oDoc = window.parent;
+		else
+			var oDoc = window.parent.popup;
+
 		switch (oToolbarButton.CommandName) 
 		{
-			case 'Bold' 		: window.parent.insertTags ('\'\'\'', '\'\'\'', 'Bold text') ; CMode = true ; break ;
-			case 'Italic' 		: window.parent.insertTags ('\'\'', '\'\'', 'Italic text') ; CMode = true ; break ;
-			case 'Underline' 	: window.parent.insertTags ('<u>', '</u>', 'Underlined text') ; CMode = true ; break ;
-			case 'StrikeThrough': window.parent.insertTags ('<strike>', '</strike>', 'Strikethrough text') ; CMode = true ; break ;
-			case 'Link' 		: window.parent.insertTags ('[[', ']]', 'Internal link') ; CMode = true ; break ;
+			case 'Bold' 		: oDoc.FCKeditorInsertTags ('\'\'\'', '\'\'\'', 'Bold text', document) ; CMode = true ; break ;
+			case 'Italic' 		: oDoc.FCKeditorInsertTags ('\'\'', '\'\'', 'Italic text', document) ; CMode = true ; break ;
+			case 'Underline' 	: oDoc.FCKeditorInsertTags ('<u>', '</u>', 'Underlined text', document) ; CMode = true ; break ;
+			case 'StrikeThrough': oDoc.FCKeditorInsertTags ('<strike>', '</strike>', 'Strikethrough text', document) ; CMode = true ; break ;
+			case 'Link' 		: oDoc.FCKeditorInsertTags ('[[', ']]', 'Internal link', document) ; CMode = true ; break ;
 		}
 	}
@@ -360,4 +365,9 @@
 								var isWikiUrl = !( href.StartsWith( 'mailto:' ) || /^\w+:\/\//.test( href ) ) ;
 								stringBuilder.push( isWikiUrl ? '[[' : '[' ) ;
+							}
+							if (href.toLowerCase().StartsWith( 'rtecolon' ))		//change 'rtecolon=' => ':' in links
+							{
+								stringBuilder.push(':');
+								href = href.substring(8);
 							}
 							stringBuilder.push( href ) ;
@@ -767,14 +777,25 @@
 (function()
 {
+	if (window.parent.showFCKEditor & (2|4))				//if popup or toggle link
+	{
+		var original_ULF = FCK.UpdateLinkedField ;
+		FCK.UpdateLinkedField = function(){
+			if (window.parent.showFCKEditor & 1)			//only if editor is up-to-date
+			{
+				original_ULF.apply();
+			}
+		}
+	}
 	var original = FCK.SwitchEditMode ;
-
+	window.parent.oFCKeditor.ready = true;
 	FCK.SwitchEditMode = function()
 	{
 		var args = arguments ;
-
+		window.parent.oFCKeditor.ready = false;
 		var loadHTMLFromAjax = function( result )
 		{
 			FCK.EditingArea.Textarea.value = result.responseText ;
 			original.apply( FCK, args ) ;
+			window.parent.oFCKeditor.ready = true;
 		}
 		var edittools_markup = parent.document.getElementById ('editpage-specialchars') ;
@@ -784,5 +805,4 @@
 			// Hide the textarea to avoid seeing the code change.
 			FCK.EditingArea.Textarea.style.visibility = 'hidden' ;
-
 			var loading = document.createElement( 'span' ) ;
 			loading.innerHTML = '&nbsp;Loading Wikitext. Please wait...&nbsp;' ;
@@ -797,6 +817,10 @@
 
 			// Use Ajax to transform the Wikitext to HTML.
-			window.parent.sajax_request_type = 'POST' ;
-			window.parent.sajax_do_call( 'wfSajaxWikiToHTML', [FCK.EditingArea.Textarea.value], loadHTMLFromAjax ) ;
+			if( window.parent.popup ){
+				window.parent.popup.parent.FCK_sajax( 'wfSajaxWikiToHTML', [FCK.EditingArea.Textarea.value], loadHTMLFromAjax ) ;
+			}
+			else{
+				window.parent.FCK_sajax( 'wfSajaxWikiToHTML', [FCK.EditingArea.Textarea.value], loadHTMLFromAjax ) ;
+			}
 		}
 		else {
@@ -805,4 +829,5 @@
 				edittools_markup.style.display = '' ;
 			}
+			window.parent.oFCKeditor.ready = true;
 		}
 	}
@@ -814,5 +839,5 @@
 	// Templates and magic words.
 	var aSpans = document.getElementsByTagName( 'SPAN' ) ;
-
+	
 	var eSpan ;
 	var i = aSpans.length - 1 ;
@@ -863,4 +888,19 @@
 		}
 	}
+
+	// Math tags without Tex.
+	var aImgs = document.getElementsByTagName( 'IMG' ) ;
+	var eImg ;
+	i = aImgs.length - 1 ;
+	while ( i >= 0 && ( eImg = aImgs[i--] ) )
+	{
+		var className = null ;
+		switch ( eImg.className )
+		{
+			case 'FCK__MWMath' :
+				eImg.src = FCKConfig.PluginsPath + 'mediawiki/images/icon_math.gif' ;
+			break ;
+		}
+	}
 	
 	// InterWiki / InterLanguage links
@@ -874,4 +914,15 @@
 			 a.href = ":" + a.title ;
 			 a.setAttribute( '_fcksavedurl', ":" + a.title ) ;
+		}
+		else
+		{
+			if (a.href.toLowerCase().StartsWith( 'rtecolon' ))
+			{
+				a.href = ":" + a.href.substring(8);
+				if (a.innerHTML.toLowerCase().StartsWith( 'rtecolon' ))
+				{
+					a.innerHTML = a.innerHTML.substring(8);
+				}			
+			}			
 		}
 	}
