/* @Packager.Header
<FileDescription>
	This is the first part of the "FCK" object creation. This is the main
	object that represents an editor instance.
</FileDescription>
<Author name="Frederico Caldeira Knabben" email="www.fckeditor.net" />
*/

var FCK_StartupValue ;

FCK.Events	= new FCKEvents( FCK ) ;
FCK.Toolbar	= null ;
FCK.HasFocus = false ;

FCK.StartEditor = function()
{
	this.TempBaseTag = FCKConfig.BaseHref.length > 0 ? '<base href="' + FCKConfig.BaseHref + '" _fcktemp="true"></base>' : '' ;

	// Setup the keystroke handler.
	var oKeystrokeHandler = FCK.KeystrokeHandler = new FCKKeystrokeHandler() ;
	oKeystrokeHandler.OnKeystroke = _FCK_KeystrokeHandler_OnKeystroke ;

	oKeystrokeHandler.SetKeystrokes( FCKConfig.Keystrokes ) ;

	// In IE7, if the editor tries to access the clipboard by code, a dialog is
	// shown to the user asking if the application is allowed to access or not.
	// Due to the IE implementation of it, the KeystrokeHandler will not work 
	//well in this case, so we must leave the pasting keys to have their default behavior.
	if ( FCKBrowserInfo.IsIE7 )
	{
		if ( ( CTRL + 86 /*V*/ ) in oKeystrokeHandler.Keystrokes )
			oKeystrokeHandler.SetKeystrokes( [ CTRL + 86, true ] ) ;

		if ( ( SHIFT + 45 /*INS*/ ) in oKeystrokeHandler.Keystrokes )
			oKeystrokeHandler.SetKeystrokes( [ SHIFT + 45, true ] ) ;
	}

	this.EditingArea = new FCKEditingArea( document.getElementById( 'xEditingArea' ) ) ;
	this.EditingArea.FFSpellChecker = false ;

	// Set the editor's startup contents
	this.SetHTML( this.GetLinkedFieldValue() ) ;
}

FCK.Focus = function()
{
	FCK.EditingArea.Focus() ;
}

FCK.SetStatus = function( newStatus )
{
	this.Status = newStatus ;

	if ( newStatus == FCK_STATUS_ACTIVE )
	{
		FCKFocusManager.AddWindow( window, true ) ;
		
		if ( FCKBrowserInfo.IsIE )
			FCKFocusManager.AddWindow( window.frameElement, true ) ;

		// Force the focus in the editor.
		if ( FCKConfig.StartupFocus )
			FCK.Focus() ;
	}

	this.Events.FireEvent( 'OnStatusChange', newStatus ) ;
}

// GetHTML is Deprecated : returns the same value as GetXHTML.
FCK.GetHTML = FCK.GetXHTML = function( format )
{
	// We assume that if the user is in source editing, the editor value must
	// represent the exact contents of the source, as the user wanted it to be.
	if ( FCK.EditMode == FCK_EDITMODE_SOURCE )
			return FCK.EditingArea.Textarea.value ;

	var sXHTML ;
	var oDoc = FCK.EditorDocument ;

	if ( FCKConfig.FullPage )
		sXHTML = FCKXHtml.GetXHTML( oDoc.getElementsByTagName( 'html' )[0], true, format ) ;
	else
	{
		if ( FCKConfig.IgnoreEmptyParagraphValue && oDoc.body.innerHTML == '<P>&nbsp;</P>' )
			sXHTML = '' ;
		else
			sXHTML = FCKXHtml.GetXHTML( oDoc.body, false, format ) ;
	}
	
	// Restore protected attributes.
	sXHTML = FCK.ProtectEventsRestore( sXHTML ) ;

	if ( FCKBrowserInfo.IsIE )
		sXHTML = sXHTML.replace( FCKRegexLib.ToReplace, '$1' ) ;

	if ( FCK.DocTypeDeclaration && FCK.DocTypeDeclaration.length > 0 )
		sXHTML = FCK.DocTypeDeclaration + '\n' + sXHTML ;

	if ( FCK.XmlDeclaration && FCK.XmlDeclaration.length > 0 )
		sXHTML = FCK.XmlDeclaration + '\n' + sXHTML ;

	return FCKConfig.ProtectedSource.Revert( sXHTML ) ;
}

FCK.UpdateLinkedField = function()
{
	FCK.LinkedField.value = FCK.GetXHTML( FCKConfig.FormatOutput ) ;
	FCK.Events.FireEvent( 'OnAfterLinkedFieldUpdate' ) ;
}

FCK.RegisteredDoubleClickHandlers = new Object() ;

FCK.OnDoubleClick = function( element )
{
	var oHandler = FCK.RegisteredDoubleClickHandlers[ element.tagName ] ;
	if ( oHandler )
		oHandler( element ) ;
}

// Register objects that can handle double click operations.
FCK.RegisterDoubleClickHandler = function( handlerFunction, tag )
{
	FCK.RegisteredDoubleClickHandlers[ tag.toUpperCase() ] = handlerFunction ;
}

FCK.OnAfterSetHTML = function()
{
	FCKDocumentProcessor.Process( FCK.EditorDocument ) ;	
	FCKUndo.SaveUndoStep() ;

	FCK.Events.FireEvent( 'OnSelectionChange' ) ;
	FCK.Events.FireEvent( 'OnAfterSetHTML' ) ;
}

// Saves URLs on links and images on special attributes, so they don't change when 
// moving around.
FCK.ProtectUrls = function( html )
{
	// <A> href
	html = html.replace( FCKRegexLib.ProtectUrlsA	, '$1$4$2$3$5$2 _fcksavedurl=$2$3$5$2' ) ;

	// <IMG> src
	html = html.replace( FCKRegexLib.ProtectUrlsImg	, '$1$4$2$3$5$2 _fcksavedurl=$2$3$5$2' ) ;
	
	return html ;
}

// Saves event attributes (like onclick) so they don't get executed while
// editing.
FCK.ProtectEvents = function( html )
{
	return html.replace( FCKRegexLib.TagsWithEvent, _FCK_ProtectEvents_ReplaceTags ) ;
}

FCK.ProtectTags = function( html )
{
	// <meta> tags get executed, so if you have a redirect meta, the content
	// will move to the target page.
	var sTags = 'META' ;
	
	if ( FCKConfig.ProtectedTags.length > 0 )
		sTags += '|' + FCKConfig.ProtectedTags ;

	// IE doesn't support <abbr> and it breaks it. Let's protect it.
	if ( FCKBrowserInfo.IsIE )
		sTags += '|ABBR' ;
	
	var oRegex = new RegExp( '<(' + sTags + ')([ \>])', 'gi' ) ;
	html = html.replace( oRegex, '<FCK:$1$2' ) ;
		
	oRegex = new RegExp( '<\/(' + sTags + ')>', 'gi' ) ;
	html = html.replace( oRegex, '<\/FCK:$1>' ) ;
	
	return html ;
}

// Replace all events attributes (like onclick).
function _FCK_ProtectEvents_ReplaceTags( tagMatch )
{
	return tagMatch.replace( FCKRegexLib.EventAttributes, _FCK_ProtectEvents_ReplaceEvents ) ;
}

// Replace an event attribute with its respective __fckprotectedatt attribute.
// The original event markup will be encoded and saved as the value of the new
// attribute.
function _FCK_ProtectEvents_ReplaceEvents( eventMatch, attName )
{
	return ' ' + attName + '_fckprotectedatt="' + eventMatch.ReplaceAll( [/&/g,/'/g,/"/g,/=/g,/</g,/>/g,/\r/g,/\n/g], ['&apos;','&#39;','&quot;','&#61;','&lt;','&gt;','&#10;','&#13;'] ) + '"' ;
}

FCK.ProtectEventsRestore = function( html )
{
	return html.replace( FCKRegexLib.ProtectedEvents, _FCK_ProtectEvents_RestoreEvents ) ;
}

function _FCK_ProtectEvents_RestoreEvents( match, encodedOriginal )
{
	return encodedOriginal.ReplaceAll( [/&#39;/g,/&quot;/g,/&#61;/g,/&lt;/g,/&gt;/g,/&#10;/g,/&#13;/g,/&apos;/g], ["'",'"','=','<','>','\r','\n','&'] ) ;
}

FCK.IsDirty = function()
{
	return ( FCK_StartupValue != FCK.EditorDocument.body.innerHTML ) ;
}

FCK.ResetIsDirty = function()
{
	if ( FCK.EditorDocument.body )
		FCK_StartupValue = FCK.EditorDocument.body.innerHTML ;
}

FCK.SetHTML = function( html )
{
	this.EditingArea.Mode = FCK.EditMode ;

	if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
	{	
		html = FCKConfig.ProtectedSource.Protect( html ) ;
		html = FCK.ProtectEvents( html ) ;
		html = FCK.ProtectUrls( html ) ;
		html = FCK.ProtectTags( html ) ;

		// Firefox can't handle correctly the editing of the STRONG and EM tags. 
		// We must replace them with B and I.
		if ( FCKBrowserInfo.IsGecko )
		{
			html = html.replace( FCKRegexLib.StrongOpener, '<b$1' ) ;
			html = html.replace( FCKRegexLib.StrongCloser, '<\/b>' ) ;
			html = html.replace( FCKRegexLib.EmOpener, '<i$1' ) ;
			html = html.replace( FCKRegexLib.EmCloser, '<\/i>' ) ;
		}
//		else if ( FCKBrowserInfo.IsIE )
//		{
//			// IE doesn't support <abbr> and it breaks it. Let's protect it.
//			html = html.replace( FCKRegexLib.AbbrOpener, '<FCK:abbr$1' ) ;
//			html = html.replace( FCKRegexLib.AbbrCloser, '<\/FCK:abbr>' ) ;
//		}

		var sHtml = '' ;

		if ( FCKConfig.FullPage )
		{
			// The HTML must be fixed if the <head> is not available.
			if ( !FCKRegexLib.HeadOpener.test( html ) )
			{
				// Check if the <html> is available.
				if ( !FCKRegexLib.HtmlOpener.test( html ) )
					html = '<html dir="' + FCKConfig.ContentLangDirection + '">' + html + '</html>' ;
				
				// Add the <head>.
				html = html.replace( FCKRegexLib.HtmlOpener, '$&<head></head>' ) ;
			}
			
			// Save the DOCTYPE.
			FCK.DocTypeDeclaration = html.match( FCKRegexLib.DocTypeTag ) ;
			
			if ( FCKBrowserInfo.IsIE )
				sHtml = FCK._GetBehaviorsStyle() ;
			else if ( FCKConfig.ShowBorders ) 
				sHtml = '<link href="' + FCKConfig.FullBasePath + 'css/fck_showtableborders_gecko.css" rel="stylesheet" type="text/css" _fcktemp="true" />' ;

			sHtml += '<link href="' + FCKConfig.FullBasePath + 'css/fck_internal.css' + '" rel="stylesheet" type="text/css" _fcktemp="true" />' ;

			// Attention: do not change it before testing it well (sample07)!		: @Packager.RemoveLine
			// This is tricky... if the head ends with <meta ... content type>,		: @Packager.RemoveLine
			// Firefox will break. But, it works if we include the temporary		: @Packager.RemoveLine
			// links as the last elements in the HEAD.								: @Packager.RemoveLine
			sHtml = html.replace( FCKRegexLib.HeadCloser, sHtml + '$&' ) ;

			// Insert the base tag (FCKConfig.BaseHref), if not exists in the source.
			// The base must be the first tag in the HEAD, to get relative			: @Packager.RemoveLine
			// links on styles, for example.										: @Packager.RemoveLine
			if ( FCK.TempBaseTag.length > 0 && !FCKRegexLib.HasBaseTag.test( html ) )
				sHtml = sHtml.replace( FCKRegexLib.HeadOpener, '$&' + FCK.TempBaseTag ) ;
		}
		else
		{
			sHtml =
				FCKConfig.DocType +
				'<html dir="' + FCKConfig.ContentLangDirection + '"' ;
			
			// On IE, if you are use a DOCTYPE differenft of HTML 4 (like
			// XHTML), you must force the vertical scroll to show, otherwise
			// the horizontal one may appear when the page needs vertical scrolling.
			if ( FCKBrowserInfo.IsIE && !FCKRegexLib.Html4DocType.test( FCKConfig.DocType ) )
				sHtml += ' style="overflow-y: scroll"' ;
			
			sHtml +=
				'><head><title></title>' +
				_FCK_GetEditorAreaStyleTags() +
				'<link href="' + FCKConfig.FullBasePath + 'css/fck_internal.css' + '" rel="stylesheet" type="text/css" _fcktemp="true" />' ;

			if ( FCKBrowserInfo.IsIE )
				sHtml += FCK._GetBehaviorsStyle() ;
			else if ( FCKConfig.ShowBorders ) 
				sHtml += '<link href="' + FCKConfig.FullBasePath + 'css/fck_showtableborders_gecko.css" rel="stylesheet" type="text/css" _fcktemp="true" />' ;

			sHtml += FCK.TempBaseTag ;
			sHtml += '</head><body>' ;
			
			if ( FCKBrowserInfo.IsGecko && ( html.length == 0 || FCKRegexLib.EmptyParagraph.test( html ) ) )
				sHtml += GECKO_BOGUS ;
			else
				sHtml += html ;
			
			sHtml += '</body></html>' ;
		}

		this.EditingArea.OnLoad = _FCK_EditingArea_OnLoad ;
		this.EditingArea.Start( sHtml ) ;
	}
	else
	{
		// Remove the references to the following elements, as the editing area
		// IFRAME will be removed.
		FCK.EditorWindow	= null ;
		FCK.EditorDocument	= null ; 
	
		this.EditingArea.OnLoad = null ;
		this.EditingArea.Start( html ) ;
		
		// Enables the context menu in the textarea.
		this.EditingArea.Textarea._FCKShowContextMenu = true ;

		// Removes the enter key handler.
		FCK.EnterKeyHandler = null ;

		// Listen for keystroke events.
		FCK.KeystrokeHandler.AttachToElement( this.EditingArea.Textarea ) ;
		
		this.EditingArea.Textarea.focus() ;
	}

	if ( FCKBrowserInfo.IsGecko )
		window.onresize() ;
}

function _FCK_EditingArea_OnLoad()
{
	// Get the editor's window and document (DOM)
	FCK.EditorWindow	= FCK.EditingArea.Window ;
	FCK.EditorDocument	= FCK.EditingArea.Document ;

	FCK.InitializeBehaviors() ;

	// Create the enter key handler
	if ( !FCKConfig.DisableEnterKeyHandler )
		FCK.EnterKeyHandler = new FCKEnterKey( FCK.EditorWindow, FCKConfig.EnterMode, FCKConfig.ShiftEnterMode ) ;

	// Listen for keystroke events.
	FCK.KeystrokeHandler.AttachToElement( FCK.EditorDocument ) ;

	FCK.OnAfterSetHTML() ;

	// Check if it is not a startup call, otherwise complete the startup.
	if ( FCK.Status != FCK_STATUS_NOTLOADED )
		return ;

	// Save the startup value for the "IsDirty()" check.
	FCK.ResetIsDirty() ;
	
	FCK.SetStatus( FCK_STATUS_ACTIVE ) ;
}

function _FCK_GetEditorAreaStyleTags()
{
	var sTags = '' ;
	var aCSSs = FCKConfig.EditorAreaCSS ;
	
	for ( var i = 0 ; i < aCSSs.length ; i++ )
		sTags += '<link href="' + aCSSs[i] + '" rel="stylesheet" type="text/css" />' ;
	
	return sTags ;
}

function _FCK_KeystrokeHandler_OnKeystroke( keystroke, keystrokeValue )
{
	if ( FCK.Status != FCK_STATUS_COMPLETE )
		return ;

	if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
	{
		if ( keystrokeValue == 'Paste' )
			return !FCK.Events.FireEvent( 'OnPaste' ) ;
	}
	else
	{
		// In source mode, some actions must have their default behavior.
		if ( keystrokeValue.Equals( 'Paste', 'Undo', 'Redo', 'SelectAll' ) )
			return false ;
	}

	// The return value indicates if the default behavior of the keystroke must
	// be cancelled. Let's do that only if the Execute() call explicitelly returns "false".
	var oCommand = FCK.Commands.GetCommand( keystrokeValue ) ;
	return ( oCommand.Execute.apply( oCommand, FCKTools.ArgumentsToArray( arguments, 2 ) ) !== false ) ;
}

// # Focus Manager: Manages the focus in the editor.
var FCKFocusManager = FCK.FocusManager = new Object() ;
FCKFocusManager.IsLocked = false ;
FCK.HasFocus = false ;

FCKFocusManager.AddWindow = function( win, sendToEditingArea )
{
	var oTarget ;
	
	if ( FCKBrowserInfo.IsIE )
		oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ;
	else
		oTarget = win.document ;
	
	FCKTools.AddEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ;
	FCKTools.AddEventListener( oTarget, 'focus', sendToEditingArea ? FCKFocusManager_Win_OnFocus_Area : FCKFocusManager_Win_OnFocus ) ;
}

FCKFocusManager.RemoveWindow = function( win )
{
	if ( FCKBrowserInfo.IsIE )
		oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ;
	else
		oTarget = win.document ;

	FCKTools.RemoveEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ;
	FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus_Area ) ;
	FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus ) ;
}

FCKFocusManager.Lock = function()
{
	this.IsLocked = true ;
}

FCKFocusManager.Unlock = function()
{
	if ( this._HasPendingBlur )
		FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ;
		
	this.IsLocked = false ;
}

FCKFocusManager._ResetTimer = function()
{
	this._HasPendingBlur = false ;

	if ( this._Timer )
	{
		window.clearTimeout( this._Timer ) ;
		delete this._Timer ; 
	}
}

function FCKFocusManager_Win_OnBlur()
{
	if ( typeof(FCK) != 'undefined' && FCK.HasFocus )
	{
		FCKFocusManager._ResetTimer() ;
		FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ;
	}
}

function FCKFocusManager_FireOnBlur()
{
	if ( FCKFocusManager.IsLocked )
		FCKFocusManager._HasPendingBlur = true ;
	else
	{
		FCK.HasFocus = false ;
		FCK.Events.FireEvent( "OnBlur" ) ;
	}
}

function FCKFocusManager_Win_OnFocus_Area()
{
	FCK.Focus() ;
	FCKFocusManager_Win_OnFocus() ;
}

function FCKFocusManager_Win_OnFocus()
{
	FCKFocusManager._ResetTimer() ;

	if ( !FCK.HasFocus && !FCKFocusManager.IsLocked )
	{
		FCK.HasFocus = true ;
		FCK.Events.FireEvent( "OnFocus" ) ;
	}
}