var RadE_HasRules = false;
if (typeof(RadEditorCommandList) == "undefined")
{
	RadEditorCommandList = new Array();
}

RadEditorCommandList["MOSSRightToLeft"] = function(commandName, editor, oTool)
{
    Telerk_MOSS_SetDirectionOfSelection(editor,"rtl");
}

RadEditorCommandList["MOSSLeftToRight"] = function(commandName, editor, oTool)
{
    Telerk_MOSS_SetDirectionOfSelection(editor,"ltr");
}

RadEditorCommandList["MOSSHelp"] = function(commandName, editor, oTool)
{
    HelpWindowKey('WCMHTMLEditor');
}

RadEditorCommandList["ToggleSource"] = function(commandName, editor, oTool)
{
    //todo: call the source dialog as the MOSS editor does
    editor.SetMode(2);
}

RadEditorCommandList["MOSSInsertTable"] = function(commandName, editor, oTool)
{
    //todo: change the dialog to use the moss default (after firefox is fixed)
    editor.Fire("TableWizard");
}

RadEditorCommandList["MOSSImageManager"] = function(commandName, editor, oTool)
{
    var docEditor = editor.Document;
    var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	//you can set the default library here:
	configObj.DefaultAssetImageLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.ManageHyperlink=false;
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var imageAssetObj=new ImageAsset("");
	var selectionType= null;
	if (docEditor.selection)
		selectionType = docEditor.selection.type;
	if (selectionType !=null && selectionType=="Control")
	{
		elemToReplace=RadE_GetCurrentElement(docEditor);
		if (elemToReplace==null) {return;}
	}
	//check here if editor.iframe should be used??
	var elemImage=RTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, elemToReplace, new Array("IMG"));
    if(!elemImage)
	{
		bInserting=true;
		elemImage=docEditor.createElement("IMG");
		elemImage.border=0;
	}
	configObj.ReturnCallback=function(newAssetUrl, newAssetText, currentConfig, dialogReturnedData)
	{
		if (dialogReturnedData)
		{
			if (elemToReplace !=null)
			{
				elemToReplace.replaceNode(elemImage);
				return;
			}
			else if (bInserting)
			{
				var selection=docEditor.selection;
				if (selection !=null)
				{
					var textRange=selection.createRange();
					if (textRange !=null)
					{
   						var tempDiv = docEditor.createElement("DIV");
           		        tempDiv.appendChild(elemImage);
		                textRange.pasteHTML(tempDiv.innerHTML);
					}
				}
				else
				{
				    //if we cannot get the selection, use the editor paste function instead
					var tempDiv = docEditor.createElement("DIV");
            		tempDiv.appendChild(elemImage);
			        editor.PasteHtml(tempDiv.innerHTML);
				}
			}
		}
	}
	var dialogReturnedData=imageAssetObj.LaunchModalDialogOnElement(configObj, elemImage, true, !bInserting );
}

RadEditorCommandList["MOSSLinkManager"] = function(commandName, editor, oTool)
{
    var docEditor = editor.Document;
    var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	configObj.DefaultAssetImageLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var linkAsset=new LinkAsset("");
	var innerLinkHTML=null;
	linkAsset.ManageLinkDisplayText=false;
	var elemLink=RTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, RadE_GetCurrentElement(docEditor), new Array("A"));	
	if( !elemLink )
	{
		bInserting=true;
		elemLink=docEditor.createElement("A");
		if (elemLink==null) {    return; }
		var selectionType= null;
		if (docEditor.selection)
			selectionType = docEditor.selection.type;
		if (selectionType !=null && selectionType=="Control")
		{
			elemToReplace=RadE_GetCurrentElement(docEditor);
			if (elemToReplace==null) {return;}
		}
	}
	else
	{
		innerLinkHTML=elemLink.innerHTML;
	}
	configObj.ReturnCallback=function(newAssetUrl, newAssetText, currentConfig, dialogReturnedData)
	{
		if (dialogReturnedData)
		{
			if(innerLinkHTML && innerLinkHTML !="")
			{
				elemLink.innerHTML=innerLinkHTML;
			}
			else if(elemLink.innerHTML=="")
			{
				if(linkAsset.AssetText && linkAsset.AssetText !="")
				{
					elemLink.innerText=linkAsset.AssetText
				}
				else
				{
					elemLink.innerText=linkAsset.AssetUrl;
				}
			}
			if (elemToReplace !=null)
			{
				elemToReplace.applyElement(elemLink);
				linkAsset.FixupIconsAndEmptyAnchors(elemLink)
				return;
			}
			else if (bInserting)
			{
				var selection=docEditor.selection;
				if (selection !=null)
				{
					var textRange=selection.createRange();
					if (textRange !=null)
					{
						var text=textRange.text;
						if (text && text !="" && !text.match(/^\s+$/))
						{
							textRange.execCommand("Unlink");
							elemLink.innerHTML=textRange.htmlText;
							linkAsset.FixupIconsAndEmptyAnchors(elemLink)
						}
						//outerHTML is IE only.
						//textRange.pasteHTML(elemLink.outerHTML);
						var tempDiv = docEditor.createElement("DIV");
            		    tempDiv.appendChild(elemLink);
			            textRange.pasteHTML(tempDiv.innerHTML);
					}
				}
				else
				{
				    //if we cannot get the selection, use the editor paste function instead
					var tempDiv = docEditor.createElement("DIV");
            		tempDiv.appendChild(elemLink);
			        editor.PasteHtml(tempDiv.innerHTML);
				}
			}
			else
			{
				linkAsset.FixupIconsAndEmptyAnchors(elemLink)
			}
		}
	}
	linkAsset.LaunchModalDialogOnElement(configObj, elemLink, true, !bInserting );
}

RadEditorCommandList["MOSSTemplateManager"] = function (commandName, editor, oTool)
{
    if (!RadE_HasRules)
    {
        RTE2_InstantiateStaticSafeHtmlRules();
        RadE_HasRules = true;
    }
    var docEditor = editor.Document;
    var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var fragmentId=null;
	var elemViewToEdit=RTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, RadE_GetCurrentElement(docEditor), new Array("SPAN"));
	if ((elemViewToEdit !=null) && (elemViewToEdit.id==g_strRTE2ReusableFragmentCommonToken))
	{
		fragmentId=elemViewToEdit.getAttribute("fragmentid");
	}
	var dialogInput=new Object();
	dialogInput.fragmentId=fragmentId;
	var callback=function(dialogOutput)
	{
		if ((dialogOutput !=null) && (dialogOutput.fragmentView !=null))
		{
			var selection=docEditor.selection;
			if (selection !=null)
			{
				if (selection.type=="Control")
				{
					var controlRange=selection.createRange();
					if (controlRange !=null)
					{
						controlRange.execCommand("Delete");
					}
				}
				if (selection.type !="Control")
				{
					var textRange=selection.createRange();
					if (textRange !=null)
					{
		                var safeHtmlDocument=RadE_CreateTemporaryDocument();
		                safeHtmlDocument.body.innerHTML=dialogOutput.fragmentView;
		                var elements=RTE2_GetAllElements(safeHtmlDocument);
		                //setting these to hardcoded values since they are not passed in the params[] array yet.
		                var instanceVariables = new Object();
                        instanceVariables.EditorOpenFromWebPart = false;
                        instanceVariables.DisableCustomStyles = false;
		                RTE2_ApplyContentFilters(elements, instanceVariables);
						textRange.pasteHTML(dialogOutput.fragmentView);
						RTE2_AlterReusableFragmentHighlights(docEditor.body, "ms-reusableTextView");
					}
				}
			}
			else
			{
			    editor.PasteHtml(dialogOutput.fragmentView);
			    RTE2_AlterReusableFragmentHighlights(docEditor.body, "ms-reusableTextView");
			}
		}
	};
	var dialogUrl=params["CurrentWebBaseUrl"]+"/_layouts/ReusableTextPicker.aspx";
	commonShowModalDialog(dialogUrl, "dialogHeight:600px; dialogWidth:800px; center:yes; resizable:yes; scroll:no; status:no;", callback, dialogInput);
}

/* support functions */
function RadE_GetCurrentElement(docEditor)
{
	var selection=docEditor.selection;
	if (selection==null) {return null;}
	var range=selection.createRange();
	if (range==null) {return null;}
	if (selection.type.toLowerCase()=="control")
	{
		if (range.length !=1) {return null;}
		return range.item(0);
	}
	else
	{
		var elemParent=range.parentElement();
		if (elemParent !=null)
		{
			if (docEditor.body.contains(elemParent))
			{
				return elemParent;
			}
		}
	}
	return null;
}

if (typeof(RadEditor) == "undefined")
{
	RadEditor = function () {};
}

RadEditor.EncodeUrl = function(url)
{
	if (window.encodeURIComponent)
	{
		return encodeURIComponent(url);
	}
	
	if (window.escape)
	{
		return escape(url);	
	}
	
	return url;
}

function GetDialogArguments(editor, commandName)
{
	var args = editor.GetDialogParameters(commandName);
	var argStr = "";
	for (var item in args)
	{
		argStr += "&" + item + "=" + RadEditor.EncodeUrl(args[item]);
	}
	return argStr;
}

function Telerk_MOSS_SetDirectionOfSelection(editor, strDirection)
{
    var rngSelection=editor.GetSelection();
	var strTagNames;
	strTagNames="|H1|H2|H3|H4|H5|H6|P|PRE|TD|DIV|BLOCKQUOTE|DT|DD|TABLE|HR|IMG|BODY|TR|UL|OL|";
	if (rngSelection.GetParentElement())
	{
		var elemSelectionParent=rngSelection.GetParentElement();
		while ((elemSelectionParent !=null) && (strTagNames.indexOf("|"+elemSelectionParent.tagName+"|")==-1))
		{
			elemSelectionParent=elemSelectionParent.parentElement;
		}
		if (elemSelectionParent)
		{
			Telerik_MOSS_SetDirectionOnElement(elemSelectionParent, strDirection);
		}
	}
}

function Telerik_MOSS_SetDirectionOnElement(element, strDirection)
{
	if ("ltr"==strDirection)
	{
		element.dir="ltr";
		element.align="left";
	}
	else if ("rtl"==strDirection)
	{
		element.dir="rtl";
		element.align="right";
	}
}

function RadE_CreateTemporaryDocument()
{
    // creating a temporary document for storing template content
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);	
    iframe.src = 'about:blank';
    iframe.frameBorder = '0';
    iframe.style.width = "0px";
    iframe.style.height = "0px";				
    var doc = iframe.contentWindow.document;
    doc.open();
    doc.writeln('<head><style></style></head><body></body>');
    doc.close();
    if (!doc.body)
    {
        var oBody = doc.createElement("body");			
        doc.appendChild(oBody);
    }
    if (doc.getElementsByTagName("head").length < 1)
    {	
        var oHead = doc.createElement("head");
        oHead.style.visibility = "hidden";
        doc.body.parentNode.insertBefore(oHead, doc.body);
    }
    return doc;
}

/*
//:
function RTE2_EditImageOrLinkProperties(strBaseElementID)
{
	var docEditor=RTE_GetEditorDocument(strBaseElementID);
	if (docEditor==null) return;
	RTE_RestoreSelection(strBaseElementID);
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=strBaseElementID;
	configObj.DefaultAssetLocation=RTE2_GetDialogParameter(strBaseElementID, "DefaultAssetLocation");
	configObj.DefaultAssetImageLocation=RTE2_GetDialogParameter(strBaseElementID, "DefaultAssetImageLocation");
	configObj.CurrentWebBaseUrl=RTE2_GetDialogParameter(strBaseElementID, "CurrentWebBaseUrl");
	configObj.AllowExternalUrls=RTE2_ShouldAllowExternalUrls(strBaseElementID);
	configObj.ReturnCallback=function()
	{
		RTE_GiveEditorFocus(strBaseElementID);
	}
	var bInserting=false;
	var elemToReplace=null;
	var elemImageToEdit=RTE_GetNearestContainingElementOfType(strBaseElementID, "IMG");
	if ( elemImageToEdit )
	{
		var imageAsset=new ImageAsset("");
		configObj.ManageHyperlink=false;
		imageAsset.LaunchModalDialogOnElement(configObj, elemImageToEdit, true, true );
	}
	else
	{
		var elemLinkToEdit=RTE_GetNearestContainingElementOfType(strBaseElementID, "A");
		if( elemLinkToEdit )
		{
			var linkAsset=new LinkAsset("");
			linkAsset.ManageLinkDisplayText=false;
			linkAsset.LaunchModalDialogOnElement(configObj, elemLinkToEdit, true, true );
		}
	}
}

*/
