var oEditor	= null;
var oPopup	= null;
var richText_colorSelectorAction = null;

function richText_handleForeColorButton( oButton )
{
	richText_showColorPicker( oButton, "ForeColor" );
}

function richText_handleBackColorButton( oButton )
{
	richText_showColorPicker( oButton, "BackColor" );
}

//var oShadow;

function richText_showColorPicker( oButton, sAction )
{
	if ( oPopup == null )
		oPopup		= window.createPopup();
	var oPopBody	= oPopup.document.body;
	richText_colorSelectorAction = sAction;

	oPopBody.style.backgroundColor	= "transparent";

	var s = "";

	s = "<html><body scroll=no margin=0 border=0 style='padding:0;margin:0;border:none'>"
	s += "<link rel='stylesheet' href='/CAF.Web/PSC/Web/UI/RichTextEditor_ColorPicker.css' />";
	s += "	<table id='colorPicker' class='ColorPicker' border='0' cellpadding='0' cellspacing='0'>"
	s += "		<tr>"
	s += "			<td colspan='4' align='middle' style='width:100%;'>"
	s += "				<a class='color2' href='#' onclick=\"parent.colorPicker_select(this,'');\">"
	s += "				<span style='width: 100%;'>";

	if ( oButton.cmdID == "foreColor" )
		s += "Automatic";
	else if ( oButton.cmdID == "backColor" )
		s += "No Fill";
	else if ( oButton.cmdID == "tableBorderColor" )
		s += "Automatic";
	else
		s += oButton.DefaultColorCaption;

	s += "</span>"
	s += "				</a>"
	s += "			</td>"
	s += "		</tr><tr>"

	var iCol	= 0
	var iRows	= 2;
	var iCols	= 4;
	var vData	= oButton.data.split( "," );

	// Build the table of colors that you can click on...
	for ( var i = 0; i < vData.length; i++ )
	{
		if ( iCol >= iCols )
		{
			s += "</tr><tr>";
			iCol = 0;
			iRows++;
		}
		iCol++;

		s += "<td><a href='#' onclick=\"parent.colorPicker_select(this,'" + vData[i] + "');\" class='color'><span style='background-color:" + vData[i] + ";'></span></a></td>";
	}

	s += "	</tr></table>"
	s += "</body></html>";

	oPopup.document.write( s );

	var iWidth	= iCols * 24 + 4;
	var iHeight	= iRows * 23 + 4;
/*
	oShadow = document.createElement( "DIV" );
	oShadow.style.position			= "absolute";
	oShadow.style.backgroundColor	= "black";
	oShadow.style.filter			= "progid:DXImageTransform.Microsoft.Alpha( style=0,opacity=25);"
	oShadow.style.width				= iWidth + "px";
	oShadow.style.height			= iHeight + "px";
	oShadow.style.display			= "block";
	oShadow.style.top				= getRealTop( oButton ) + oButton.offsetHeight + 5;
	oShadow.style.left				= getRealLeft( oButton ) + 5;
	document.body.appendChild( oShadow );
*/
	oPopup.show( 0, oButton.offsetHeight, iWidth, iHeight, oButton );
}

function colorPicker_select( o, sColor )
{
//	oShadow.style.display = "none";
//	document.body.removeChild( oShadow );
	oPopup.hide();

	if ( typeof(richText_colorSelectorAction) == "function" )
	{
		richText_colorSelectorAction( sColor );
	}
	else
	{
		oEditor.setActive();
	//try { oEditor.focus(); } catch ( e ) { }

		if ( richText_colorSelectorAction == "tableBorderColor" )
			richText_tableBorderColorCallback( sColor );
		else
			document.execCommand( richText_colorSelectorAction, false, sColor );
	}
}

function RichTextEditorHeightValidator_EvaluateIsValid( val ) {
	var oEditor = document.body.all[ "RichTextEditor_" + val.controltovalidate ];

	if ( oEditor.disabled )
		return true;

	var	iMaxHeight		= new Number( val.MaxHeight );

	// If this editor has a maximum height...
	if ( iMaxHeight != -1 )
	{
		// Get the current height of the editor...
		var	iCurrentHeight	= oEditor.scrollHeight;

		if ( oEditor.offsetHeight > iCurrentHeight )
			iCurrentHeight = oEditor.offsetHeight;

		// Is it too big?
		var b = ( iCurrentHeight <= iMaxHeight )

		if ( val.GoodColor == "." )
		{
			val.GoodColor = oEditor.currentStyle.borderColor;
		}

		var sNewColor = ( b ? val.GoodColor : val.ErrorColor );

		if ( oEditor.currentStyle.borderColor != sNewColor )
			oEditor.style.borderColor = sNewColor;
			
		return b;
	}
	else
		return true;
}

function RichTextEditorMaxLengthValidator_EvaluateIsValid( val ) {
	var oEditor = document.body.all[ "RichTextEditor_" + val.controltovalidate ];

	if ( oEditor.disabled )
		return true;

	var	iMaxLength		= new Number( val.MaxLength );

	// If this editor has a maximum height...
	if ( iMaxLength != -1 )
	{
		var sText = oEditor.innerText;
		
		// Is it too big?
		var b = ( sText.length <= iMaxLength );

		if ( val.GoodColor == "." )
		{
			val.GoodColor = oEditor.currentStyle.borderColor;
		}

		var sNewColor = ( b ? val.GoodColor : val.ErrorColor );

		if ( oEditor.currentStyle.borderColor != sNewColor )
			oEditor.style.borderColor = sNewColor;
			
		return b;
	}
	else
		return true;
}

function richTextListClick( sRTE, oList, sCmd )
{
	var sValue = "";
	
	if ( oList.options[ oList.selectedIndex ].value != "" )
		sValue = oList.options[ oList.selectedIndex ].value;
	else
		sValue = oList.options[ oList.selectedIndex ].innerText;
		  
	if ( sValue == "--" ) sValue = null;

	var oEditor = document.body.all[ "RichTextEditor_" + sRTE ];
	oEditor.setActive();
	//try { oEditor.focus(); } catch ( e ) { }

	if ( sCmd == "tableBorderSize" )
		richText_tableBorderSize( sValue );
	else
	{
		document.execCommand( sCmd, false, sValue );
		window.setTimeout( "updateToolbarButtons('" + sRTE + "');", 100 );
	}
}

function richTextButtonClick( sRTE, sButton, oButton )
{
	if ( oButton.className == "disabled" )
		return;

	oEditor = document.body.all[ "RichTextEditor_" + sRTE ];
	oEditor.setActive();
	//try { oEditor.focus(); } catch ( e ) { }
	
	if ( sButton == "createlink" )
		richText_CreateLink( oEditor );
	else if ( sButton == "selectAscii" )
		richText_SelectAscii();
	else if ( sButton == "spellcheck" )
		richText_SpellCheck( oEditor )
	else if ( sButton == "tableProperties" )
		richText_handleTableProperties( oEditor );
	else if ( sButton.substring( 0, 5 ) == "table" )
		richText_handleTableButton( sButton, oButton )
	else if ( sButton == "foreColor" )
		richText_handleForeColorButton( oButton );
	else if ( sButton == "backColor" )
		richText_handleBackColorButton( oButton );
	else if ( sButton == "insertImage" )
		richText_handleInsertImage( oButton );
	else if ( sButton == "uploadImage" )
		richText_handleUploadImage( oButton );
	else if ( sButton == "createAnchor" )
		richText_handleCreateAnchorButton( oButton );
	else if ( sButton == "insertNavDropDownList" )
		richText_handleCreateNavDropDownListButton( oEditor, oButton );
	else if ( sButton == "htmlMode" )
		richText_handleHtmlModeButton( sRTE, oEditor, oButton );
	else if ( sButton == "styleClean" )
		richText_handleStyleClean( oEditor );
	else if ( sButton == "imageProperties" )
		richText_handleImageProperties( oEditor );
	else
		document.execCommand( sButton );

	window.setTimeout( "updateToolbarButtons('" + sRTE + "');", 100 );
}

function richText_onSubmit( sRTE )
{
	var oEditor = document.body.all[ "RichTextEditor_" + sRTE ];
	
	// If the user is in "HTML Mode" we don't want to overwrite their changes...
	if ( oEditor != null && oEditor.InHtmlMode != "true" )
		document.body.all[ sRTE ].value = oEditor.innerHTML;
}

function updateToolbarButtons( sRTE )
{
	var oEditor	= document.body.all[ "RichTextEditor_" + sRTE ];
	var oData	= document.body.all[ sRTE ];
	
	if ( oEditor == null || oData == null )
		return;
		
	var oRange	= document.selection.createRange();
	
	if ( typeof( oData.Validators ) != "undefined" && oData.Validators != null )
	{
		for ( var i = 0; i < oData.Validators.length; i++ ) {
			ValidatorValidate( oData.Validators[ i ] );
		}
	}

	var oToolbar	= document.body.all[ "RichTextEditor_" + sRTE + "_Toolbar" ];
	if ( oToolbar != null )
	{
		var oButtons	= oToolbar.all.tags( "a" );
		
		for ( var i = 0; i < oButtons.length; i++ )
		{
			var oButton = oButtons[ i ];
			var sCmdID = oButton.cmdID;
			
			if ( sCmdID == "htmlMode" )
				sCmdID = null;
			if ( sCmdID == "insertNavDropDownList" )
				sCmdID = null;
			
			if ( sCmdID != null && sCmdID != "" )
			{
				oButton.className = "";
				
				var bEnabled	= true;
				var bOn			= false;
				
				if ( sCmdID.substring( 0, 5 ) == "table" && sCmdID != "tableInsert" )
				{
					var oSel		= document.selection.createRange();
					var oTable		= null;
					if ( oSel.parentElement )
						oTable  = richText_findElement( oSel.parentElement(), "TABLE" );
					bEnabled = ( oTable != null );
				}
				else if ( sCmdID == "imageProperties" )
				{
					oRange.type	= document.selection.type;
					var oEl;

					if ( oRange.parentElement )
						oEl  = _CUtil_GetElement( oRange.parentElement(), "IMG" );
					else
						oEl  = _CUtil_GetElement( oRange.item( 0 ), "IMG" );
					
					bEnabled = ( oEl != null );
				}
				else
				{
					if ( sCmdID == "tableInsert" )
						sCmdID = "InsertImage";
					else if ( sCmdID == "createAnchor" )
						sCmdID = "createlink";
					else if ( sCmdID == "uploadImage" )
						sCmdID = "InsertImage";

					var oContainer = oRange;

					// For some reason, the "undo" and "redo" buttons don't work when you query the range object...
					if ( sCmdID == "undo" || sCmdID == "redo" )
						oContainer = document;

					try {
						if ( ! oContainer.queryCommandEnabled( sCmdID ) )
							bEnabled = false;
						else if ( oContainer.queryCommandValue( sCmdID ) )
							bOn = true;
					} catch ( e ) { }
				}

				if ( oEditor.InHtmlMode == "true" )
					bEnabled = false;

				if ( ! bEnabled )
					oButton.className = "disabled";
				else if ( bOn && oButton.noToggle != "true" )
					oButton.className = "buttonOn";
			}
		}
	
		var oLists = oToolbar.all.tags( "select" );

		for ( var i = 0; i < oLists.length; i++ )
		{
			var oList	= oLists[ i ];
			var sCmdID	= oList.cmdID;
			
			if ( sCmdID != null && sCmdID != "" )
			{
				oList.className = "";
				
				var bEnabled		= true;
				var sCommandValue	= "";
				
				if ( sCmdID.substring( 0, 5 ) == "table" && sCmdID != "tableInsert" )
				{
					var oSel		= document.selection.createRange();
					var oTable		= null;
					if ( oSel.parentElement )
						oTable  = richText_findElement( oSel.parentElement(), "TABLE" );
					bEnabled = ( oTable != null );
					
					if ( oTable != null )
						sCommandValue = oTable.border;
				}
				else
				{
					bEnabled		= oRange.queryCommandEnabled( sCmdID );
					sCommandValue	= oRange.queryCommandValue( sCmdID );
					
					if ( sCmdID == "formatBlock" )
					{
						if ( sCommandValue == "Heading 1") sCommandValue = "<h1>";
						if ( sCommandValue == "Heading 2") sCommandValue = "<h2>";
						if ( sCommandValue == "Heading 3") sCommandValue = "<h3>";
						if ( sCommandValue == "Heading 4") sCommandValue = "<h4>";
						if ( sCommandValue == "Heading 5") sCommandValue = "<h5>";
						if ( sCommandValue == "Heading 6") sCommandValue = "<h6>";
					}
				}

				if ( oEditor.InHtmlMode == "true" )
					bEnabled = false;

				oList.disabled = ! bEnabled;
				
				var bFound = false;
				for ( var j = 0; j < oList.options.length; j++ )
				{
					var oOption = "";
					if ( oList.options[ j ].value != "" )
						oOption = oList.options[ j ].value;
					else
						oOption = oList.options[ j ].innerText	
						
					if ( oOption == sCommandValue )
					{
						oList.selectedIndex = j;
						bFound = true;
						break;
					}
				}
				if ( ! bFound )
					oList.selectedIndex = 0;
			}
		}
	}
}

function document.onselectionchange()
{
	try	{
		var oSel		= document.selection.createRange();
		var oElement	= null;

		if ( document.selection.type == "Control" )
			oElement = oSel.item( 0 );
		else
			oElement = oSel.parentElement();
			
		for ( var o = oElement; o != null; o = o.parentElement )
			if ( o.className == "RichTextEditor" )
				updateToolbarButtons( o.id.substring( "RichTextEditor_".length ) );
	} catch ( e ) { }
}

function richText_handleTableButton( sButton, oButton )
{
	var oSel	= document.selection.createRange();

	if ( sButton == "tableInsert" )
	{
		var oTable = document.createElement("TABLE");
		var oRow = oTable.insertRow();
		oRow.insertCell(); oRow.insertCell();
		oRow = oTable.insertRow();
		oRow.insertCell(); oRow.insertCell();
		
		var oParent = oSel.parentElement();
		if ( ! richText_isContentEditable( oParent ) )
			return;
		
		oSel.parentElement().appendChild( oTable );
	}

	// Row
	else if ( sButton == "tableDeleteRow" )
	{
		var oTR		= _CUtil_GetElement( oSel.parentElement(), "TR" )
		if ( ! richText_isContentEditable( oTR ) )
			return;

		oTR.parentElement.parentElement.deleteRow( oTR.sectionRowIndex );
	}
	else if ( sButton == "tableInsertRowBefore" )
	{
		var oTR		= _CUtil_GetElement( oSel.parentElement(), "TR" )
		if ( ! richText_isContentEditable( oTR ) )
			return;

		var oNewRow	= oTR.parentElement.parentElement.insertRow( oTR.sectionRowIndex );
		for ( var i = 0; i < oTR.cells.length; i++ )
			oNewRow.insertCell();
	}
	else if ( sButton == "tableInsertRowAfter" )
	{
		var oTR		= _CUtil_GetElement( oSel.parentElement(), "TR" )
		if ( ! richText_isContentEditable( oTR ) )
			return;

		var oNewRow	= oTR.parentElement.parentElement.insertRow( oTR.sectionRowIndex + 1 );
		for ( var i = 0; i < oTR.cells.length; i++ )
			oNewRow.insertCell();
	}
	
	// Column
	else if ( sButton == "tableDeleteColumn" )
	{
		var oTable	= _CUtil_GetElement( oSel.parentElement(), "TABLE" )
		var oTD		= _CUtil_GetElement( oSel.parentElement(), "TD" )
		var iCol	= oTD.cellIndex;
		if ( ! richText_isContentEditable( oTable ) )
			return;
		
		for ( var i = 0; i < oTable.rows.length; i++ )
			if ( oTable.rows[ i ].cells.length > iCol )
				oTable.rows[ i ].deleteCell( iCol );
	}
	else if ( sButton == "tableInsertColumnBefore" )
	{
		var oTable	= _CUtil_GetElement( oSel.parentElement(), "TABLE" )
		var oTD		= _CUtil_GetElement( oSel.parentElement(), "TD" )
		var iCol	= oTD.cellIndex;
		if ( ! richText_isContentEditable( oTable ) )
			return;

		for ( var i = 0; i < oTable.rows.length; i++ )
			if ( oTable.rows[ i ].cells.length > iCol )
				oTable.rows[ i ].insertCell( iCol );
	}
	else if ( sButton == "tableInsertColumnAfter" )
	{
		var oTable	= _CUtil_GetElement( oSel.parentElement(), "TABLE" )
		var oTD		= _CUtil_GetElement( oSel.parentElement(), "TD" )
		var iCol	= oTD.cellIndex;
		if ( ! richText_isContentEditable( oTable ) )
			return;

		for ( var i = 0; i < oTable.rows.length; i++ )
			if ( oTable.rows[ i ].cells.length > iCol )
				oTable.rows[ i ].insertCell( iCol + 1 );
	}

	// Borders
	else if ( sButton == "tableBorderColor" )
	{
		richText_showColorPicker( oButton, "tableBorderColor" );
	}
}

function richText_tableBorderColorCallback( sColor )
{
	var oSel		= document.selection.createRange();
	var oTable		= null;
	
	if ( oSel.parentElement )
		oTable  = richText_findElement( oSel.parentElement(), "TABLE" );
	else
		oTable  = richText_findElement( oSel.item(0), "TABLE" );

	if ( oTable != null )
	{
		if ( oTable.border == 0 )
			oTable.border = 1;
			
		oTable.borderColor = sColor;
	}
}

function richText_tableBorderSize( iSize )
{
	var oSel		= document.selection.createRange();
	var oTable		= null;
	
	if( iSize == null || (iSize < 0 && iSize > 10))
		iSize = 0;
	
	if ( oSel.parentElement )
		oTable  = richText_findElement( oSel.parentElement(), "TABLE" );
	else
		oTable  = richText_findElement( oSel.item(0), "TABLE" );

	if ( oTable != null )
	{
		if(iSize == 0)
		{
			oTable.border = iSize;
			oTable.className = "NoBorder";
		}
		else
		{
			oTable.border = iSize;
		}
	}
}

function richText_findElement( oStart, sTag )
{
	while ( true )
	{
		if ( oStart == null )
			break;
		
		if ( oStart.tagName == sTag )
			break;
			
		if ( oStart.tagName == "DIV" && oStart.className == "RichTextEditor" && oStart.contentEditable == "true" )
			return null;

		oStart = oStart.parentElement;
	}

	return oStart;
}

function richText_isContentEditable( o )
{
	for ( var oParent = o; oParent != null; oParent = oParent.parentElement )
		if ( oParent.contentEditable == "true" )
			return true;

	return false;
}

function richText_handleCreateAnchorButton( oButton )
{
	var sAnchor		= "";
	var oSel		= document.selection.createRange();
	var oA			= null;
	
	if ( oSel.parentElement )
		oA  = _CUtil_GetElement( oSel.parentElement(), "A" )
	else
		oA  = _CUtil_GetElement( oSel.item(0), "A" )

	if ( oA != null )
		sAnchor = oA.name;

	sAnchor = prompt( "Please enter the name of the anchor:", sAnchor );
	
	// If no text is selected...
	if ( oSel.parentElement && ( oSel.text == "" ) )
	{
		var oParent = oSel.parentElement();
		
		// If we are already inside of a hyperlink...
		if ( oParent.tagName == "A" )
		{
			// Select the hyperlink...
			oSel.moveToElementText( oParent );
			oSel.select();
		}

		// If we aren't inside of anything that has text...
		if ( oParent.innerText != "" )
			// If some text is around, select some of it...
			oSel.expand( "word" );

		oSel.select();
	}

	// If the user didn't click "cancel"...
	if ( sAnchor != null )
	{
		if ( sAnchor == "" )
			oSel.execCommand( "unlink" );
		else
			oSel.execCommand( "createBookmark", false, sAnchor );
	}
}

function richText_CreateLink( editor ) {
	var oSel	= document.selection.createRange();
	oSel.type	= document.selection.type;
	moSelection	= oSel;

	var	sType		= oSel.type;
	var bImg		= false;
	var sUrl		= "";
	var bNewWindow	= false;
	var oEl;

	if ( oSel.parentElement ) {
		oEl  = _CUtil_GetElement( oSel.parentElement(), "A" )
	} else {
		oEl  = _CUtil_GetElement( oSel.item(0), "A" )
		bImg = ( oSel.item(0).tagName == "IMG" );
	}

	if ( oEl )
	{
		sUrl		= oEl.href;
		bNewWindow	= ( oEl.target.toLowerCase() == "_blank" );
		
		var i = sUrl.indexOf( "#" );
		if ( i != -1 )
		{
			var sFile			= sUrl.split( '?' )[ 0 ].split( '#' )[ 0 ].toLowerCase();
			var sCurrentFile	= location.href.split( '?' )[ 0 ].split( '#' )[ 0 ].toLowerCase();;
			var sMatch			= sCurrentFile.substring( sCurrentFile.length - sFile.length ).toLowerCase();

			if ( sMatch == sFile )
				sUrl = "#" + sUrl.split( '#' )[ 1 ];
		}
	}

	// Build a string array with all of the internal anchors and pass it to the dialog box...
	var sAnchors		= new Array();
	var iAnchorCount	= -1;
	var oAs				= editor.all.tags( "A" );
	for ( var i = 0; i < oAs.length; i++ )
	{
		if ( oAs[ i ].name != null && oAs[ i ].name  != "" )
		{
			iAnchorCount++;
			sAnchors[ iAnchorCount * 2 + 0 ] = oAs[ i ].innerText;
			sAnchors[ iAnchorCount * 2 + 1 ] = oAs[ i ].name;
		}
	}

	var iAttachmentContainer = giNodeID;
	if ( iAttachmentContainer < 0 )
	{
		try {
			iAttachmentContainer = GetAttachmentContainerNodeID();
		} catch ( e ) { }
	}

	var sDialog = gsUrl + "?Template=InsertLink.aspx&URL=" + escape( sUrl )
		+ "&NewWindow=" + bNewWindow
		+ "&AttachmentContainer=" + iAttachmentContainer;
	sDialog = gsAppRoot + "CAF.Web/Dialogs/dialog.aspx?title=Insert%20Link&url=" + escape( sDialog );
	var vReturn = window.showModalDialog(
		sDialog,
		sAnchors,
		"dialogHeight: 450px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: no; status: No; scroll: no;"
	);

	// If the user returned a link...
	if ( typeof( vReturn ) != "undefined" )
		_CLinkPopupRenderer_AddLink( vReturn );
}

function _CUtil_GetElement(oEl,sTag) {
	while ( oEl != null && oEl.tagName != sTag )
		oEl = oEl.parentElement;

	return oEl
}

// Launches the spell checker for the given RichTextEditor...
function richText_SpellCheck( oEditor )
{
	var sDialog			= gsAppRoot + "CAF.Web/Dialogs/SpellChecker.aspx";
	sDialog				= gsAppRoot + "CAF.Web/Dialogs/dialog.aspx?title=Spell%20Check&url=" + escape( sDialog );

	var oArgs		= new Object();
	oArgs.text		= oEditor.innerHTML;

	var vReturn = window.showModalDialog(
		sDialog,
		oArgs,
		"dialogHeight: 500px; dialogWidth: 650px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;"
	);

	if ( typeof( vReturn ) != "undefined" && vReturn != null )
	{
		oEditor.innerHTML = vReturn.text;
		return true;
	}

	return false;
}

function richText_handleCreateNavDropDownListButton( oEditor, oButton )
{
	var oDDL	= null;
	var oSel	= document.selection.createRange();
	
	if ( document.selection.type == "Control" )
	{
		oDDL	= oSel.item( 0 );

		// If we found a control, but it's not a drop down list, forget about it...
		if ( oDDL.tagName != "SELECT" )
		{
			var oTextRange = document.body.createTextRange();
			oTextRange.moveToElementText( oDDL );
			oTextRange.collapse( false );
			oTextRange.select();

			oSel = oTextRange;
			oDDL = null;
		}
	}
	else
	{
		oSel.collapse( false );
		oSel.select();
	}

	// Build a string array with all of the internal anchors and pass it to the dialog box...
	var sAnchors		= new Array();
	var iAnchorCount	= -1;
	var oAs				= oEditor.all.tags( "A" );
	for ( var i = 0; i < oAs.length; i++ )
	{
		if ( oAs[ i ].name != null && oAs[ i ].name  != "" )
		{
			iAnchorCount++;
			sAnchors[ iAnchorCount * 2 + 0 ] = oAs[ i ].innerText;
			sAnchors[ iAnchorCount * 2 + 1 ] = oAs[ i ].name;
		}
	}

	var oArguments			= new Object();
	oArguments.dropDownList	= oDDL;
	oArguments.anchors		= sAnchors;
	oArguments.gsUrl		= gsUrl;
	oArguments.gsAppRoot	= gsAppRoot;

	var sDialog			= gsAppRoot + "CAF.Web/Dialogs/EditNavDropDownList.htm";
	var o = new Date();
	sDialog += "?Now=" + o.getTime();

	sDialog				= gsAppRoot + "CAF.Web/Dialogs/dialog.aspx?title=Edit%20Quick%20Find&url=" + escape( sDialog );

	var vReturn = window.showModalDialog(
		sDialog,
		oArguments,
		"dialogHeight: 500px; dialogWidth: 650px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;"
	);

	if ( typeof( vReturn ) != "undefined" && vReturn != null )
	{
		var oSel	= document.selection.createRange();
		
		if ( oDDL == null )
		{
			document.execCommand( "InsertSelectDropdown" );
			oSel	= document.selection.createRange();
			oDDL	= oSel.item( 0 );
		}
		
		if ( oDDL.tagName == "SELECT" )
		{
			// Delete all of the current items...
			while ( oDDL.options.length > 0 )
				oDDL.remove( 0 );

			var oSelectOne		= document.createElement( "option" );
			oSelectOne.text		= "Select One";
			oSelectOne.value	= "";
			oDDL.add( oSelectOne );

			// Add the new items to the list...
			for ( var i = 0; i < vReturn.length; i++ )
			{
				var oOption		= document.createElement( "option" );
				oOption.text	= vReturn[ i ].text;
				oOption.value	= vReturn[ i ].value;
				oDDL.add( oOption );
			}

			// Add the javascript that will navigate the browser whenever the user clicks on an item...
			oDDL.onchange = "var sValue = this.options[ this.selectedIndex ].value;if ( sValue != '' ){var sTarget = '_self';if ( sValue.indexOf(';') != -1 ){sTarget = sValue.split(';',2)[0];sValue = sValue.split(';',2)[1];}if (sTarget=='') sTarget = '_self';window.open( sValue, sTarget );}this.selectedIndex = 0;";
		}
	}
/*	
	
	var sValue = this.options[ this.selectedIndex ].value;
	if ( sValue != '' )
	{
			var sTarget				= '_self';
			if ( sValue.indexOf(';') != -1 )
			{
				sTarget				= sValue.split(';',2)[0];
				sValue				= sValue.split(';',2)[1];
			}
			if (sTarget=='') sTarget = '_self';
			window.open( sValue, sTarget );
	}
	this.selectedIndex = 0;
*/
}

function richText_handleHtmlModeButton( sRTE, oEditor, oButton )
{
	var oHTML = document.body.all[ sRTE ];

	if ( oButton.className == "buttonOn" )
	{
		oButton.className		= "";
		oEditor.innerHTML		= oHTML.value;
		oHTML.style.display		= "none";
		oEditor.style.display	= "block";
		oEditor.InHtmlMode		= "false";
	}
	else
	{
		oButton.className		= "buttonOn";
		
		var unformatedHTML		= oEditor.innerHTML;
		var currentStringIndex;
		var nextStringIndex;
		var newString;
		var tabCounter = 0;
		var tabs;

        for ( var i=0; i < unformatedHTML.length; i++)
        { 
            currentStringIndex      = unformatedHTML.charAt(i);
            nextStringIndex         = unformatedHTML.charAt(i + 1);
			
			if ( currentStringIndex == "<" && nextStringIndex != "/" )
			{
			     for( var x=0; x < tabCounter; x++)
			        tabs = tabs + "    ";
			     
			    // check for nulls, if any then set empty string 
			    if ( tabs == null )
			        tabs = ""; 
			    if ( newString == null )
			        newString = "";    
			     
			    tabCounter = tabCounter + 1;
				newString = newString + "\n" + tabs + currentStringIndex;
				tabs = "";  
			}
			else if ( currentStringIndex == "<" && nextStringIndex == "/" )
			{
				tabCounter = tabCounter - 1;
				for( var x = 0; x < tabCounter; x++)
			        tabs = tabs + "    ";
			        
			    // check for nulls, if any then set empty string     
			    if ( tabs == null )
			        tabs = "";  
			    if ( newString == null )
			        newString = "";
			        
				newString = newString + "\n" + tabs + currentStringIndex;
				tabs = "";
			}
			else
				newString = newString + currentStringIndex;
        }
        
		oEditor.style.display	= "none";
		oHTML.style.display		= "block";

		// Check for nulls, if any then set empty string 
		if ( newString == null || newString == "undefined" )
		    newString = "";
		    
		oHTML.value             = newString;
		oEditor.InHtmlMode		 = "true";
	}
}

function richText_handleInsertImage( oButton )
{
	var sDialog = "?WebDavAction=findResourceDialog";
	var sImageGallery = "";

	// If an image gallery WAS specified...
	if ( sImageGallery != "" )
	{
		sDialog = gsUrl + "/" + sImageGallery + "/?Template=Browse.aspx&filter=file&TopMostSegment=-1&ViewMode=Image";
		sDialog = gsAppRoot + "CAF.Web/Dialogs/dialog.aspx?url=" + escape( sDialog );
	}

	var vReturn = window.showModalDialog(
		sDialog,
		"Dialog Box Arguments # 2",
		"dialogHeight: 400px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;"
	);
	
	if ( typeof( vReturn ) != "undefined" )
	{
		var sUrl = "{" + vReturn.Guid + "}";

		oEditor.setActive();
	//try { oEditor.focus(); } catch ( e ) { }
		document.execCommand( "InsertImage", false, sUrl );
	}
}

function richText_handleUploadImage( oButton )
{
	var sDialog = "upload.aspx?uploadtype=image&OnlyImages=true&NodeID=" + giNodeID;

	sDialog = gsAppRoot + "CAF.Web/dialogs/dialog.aspx?title=Upload%20Image&url=" + escape( sDialog );
	var vReturn = window.showModalDialog(
		sDialog,
		"Dialog Box Arguments # 3",
		"dialogHeight: 200px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: no; status: No; scroll: no;"
	);

	// If the user uploaded a file...
	if ( typeof( vReturn ) != "undefined" )
	{
		var sUrl = gsName + "/{" + vReturn.Guid + "}";

		oEditor.setActive();
	//try { oEditor.focus(); } catch ( e ) { }
		document.execCommand( "InsertImage", false, sUrl );
	}
}

function richText_handleStyleClean( oEditor )
{
	for ( var i = oEditor.all.length - 1; i >= 0; i-- )
	{
		var o = oEditor.all[ i ];

		if ( o.tagName == "O:P" || o.tagName == "/O:P"
			|| o.scopeName != "HTML" )
		{
			o.parentElement.removeChild( o );
		}
		
		// Try to remove these tags...			
		if ( o.tagName == "FONT"
			|| o.tagName == "SPAN"
			|| o.tagName.substring( 0, 1 ) == "H" )
		{
			try 
			{ 
				o.outerHTML = o.innerHTML;
			} 
			catch ( e ) 
			{ 	
				//alert("Failure on Second tags -> " + e.value);	
			}
		}
		
		try
		{
			o.style.cssText = "";
			
			if(o.className.length > 0)
			{
				o.attributes.removeNamedItem( "class" );
			}
		}
		catch( ex )
		{
			//alert("Failed to remove 3rd tags");
		}
	}
}

function richText_handleImageProperties( oEditor )
{
	var oSel	= document.selection.createRange();
	oSel.type	= document.selection.type;
	var oEl;

	if ( oSel.parentElement ) {
		oEl  = _CUtil_GetElement( oSel.parentElement(), "IMG" )
	} else {
		oEl  = _CUtil_GetElement( oSel.item(0), "IMG" )
	}
	
	if ( oEl == null )
		return;

	var sDialog = "/caf.web/psc/web/ui/RichTextEditor_Image.htm";
	var oArgs = new Object();
	oArgs.image = oEl;

	sDialog = gsAppRoot + "CAF.Web/dialogs/dialog.aspx?title=Image%20Properties&url=" + escape( sDialog );
	var vReturn = window.showModalDialog(
		sDialog,
		oArgs,
		"dialogHeight: 300px; dialogWidth: 400px; edge: Raised; center: Yes; help: No; resizable: no; status: No; scroll: no;"
	);

	oEditor.setActive();
}

function richText_SelectAscii()
{		
	var vReturn = richText_showDialog( location.pathname + '?template=~/caf.web/dialogs/ASCII_Select.aspx&amp;NoDefaultPage=true',320,400,'Select ASCII');
	if ( typeof( vReturn ) != "undefined" && vReturn != null )
	{
		var oSel	= document.selection.createRange();
		oSel.pasteHTML( "<span>" + vReturn.Character + "</span>" );	
	}
}

function richText_showDialog( sDialog, iHeight, iWidth, sTitle )
{
	sDialog += ( sDialog.indexOf( "?" ) == -1 ) ? "?" : "&";
	sDialog = sDialog + "NodeID=" + giNodeID;

	if ( iHeight == null ) iHeight = 400;
	if ( iWidth  == null ) iWidth  = 500;


	sDialog = gsAppRoot + "CAF.Web/dialogs/dialog.aspx?url=" + escape( sDialog );
	if ( typeof( sTitle ) != "undefined" && sTitle != null ) sDialog += "&Title=" + escape( sTitle );

	var vReturn = window.showModalDialog(
		sDialog,
		"Dialog Box Arguments # 2",
		"dialogHeight: " + iHeight + "px; dialogWidth: " + iWidth + "px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;"
	);
	return vReturn;
}

function richText_handleTableProperties( oEditor )
{
	var oSel	= document.selection.createRange();
	oSel.type	= document.selection.type;
	var oCell, oTable;

	if ( oSel.parentElement )
		oCell  = _CUtil_GetElement( oSel.parentElement(), "TD" )
	else
		oCell  = _CUtil_GetElement( oSel.item(0), "TD" )
	
	if ( oCell == null )
	{
		if ( oSel.parentElement )
			oTable  = _CUtil_GetElement( oSel.parentElement(), "TABLE" )
		else
			oTable  = _CUtil_GetElement( oSel.item(0), "TABLE" )
	}
	else
		oTable = oCell.parentElement.parentElement.parentElement;

	var sDialog = "/caf.web/psc/web/ui/RichTextEditor_Table.htm";
	var oArgs = new Object();
	oArgs.cell	= oCell;
	oArgs.table	= oTable;

	sDialog = gsAppRoot + "CAF.Web/dialogs/dialog.aspx?title=Table%20Properties&url=" + escape( sDialog );
	var vReturn = window.showModalDialog(
		sDialog,
		oArgs,
		"dialogHeight: 500px; dialogWidth: 400px; edge: Raised; center: Yes; help: No; resizable: no; status: No; scroll: no;"
	);

	oEditor.setActive();
}
