/*
 * FCKeditor - The text editor for internet
 * Copyright (C) 2003 Frederico Caldeira Knabben
 *
 * Licensed under the terms of the GNU Lesser General Public License
 * (http://www.opensource.org/licenses/lgpl-license.php)
 *
 * For further information go to http://www.fredck.com/FCKeditor/ 
 * or contact fckeditor@fredck.com.
 *
 * fck_actions.js: Actions called by the toolbar.
 *
 * Authors:
 *   Frederico Caldeira Knabben (fckeditor@fredck.com)
 */

function SetFocus()
{
	if (BrowserInfo.IsIE55OrMore)
		objContent.DOM.focus() ;
	else
		objContent.focus() ;
}

function decCommand(cmdId, cmdExecOpt, url)
{
	var status = objContent.QueryStatus(cmdId) ;
	
	if ( status != DECMDF_DISABLED && status != DECMDF_NOTSUPPORTED )
	{
		if (cmdExecOpt == null) cmdExecOpt = OLECMDEXECOPT_DODEFAULT ;
		objContent.ExecCommand(cmdId, cmdExecOpt, url) ;
	}
	SetFocus() ;
}

function docCommand(command)
{
	objContent.DOM.execCommand(command) ;
	SetFocus();
}

function doStyle(command)
{
	var oSelection = objContent.DOM.selection ;
	var oTextRange = oSelection.createRange() ;
	
	if (oSelection.type == "Text")
	{
		decCommand(DECMD_REMOVEFORMAT);
		if (!FCKFormatBlockNames) loadFormatBlockNames() ;
		doFormatBlock( FCKFormatBlockNames[0] );	// This value is loaded at CheckFontFormat()
 
		//var oFont = document.createElement("FONT") ;
		var oFont = document.createElement("SPAN id=\"customstyle\"") ;
		oFont.innerHTML = oTextRange.htmlText ;
		
		var oParent = oTextRange.parentElement() ;
		var oFirstChild = oFont.firstChild ;
		
		if (oFirstChild.nodeType == 1 && oFirstChild.outerHTML == oFont.innerHTML && 
				(oFirstChild.tagName == "SPAN"
				|| oFirstChild.tagName == "FONT"
				|| oFirstChild.tagName == "P"
				|| oFirstChild.tagName == "DIV"))
		{
			oParent.className = command.value ;
		}
		else
		{
			oFont.className = command.value ;
			oTextRange.pasteHTML( oFont.outerHTML ) ;
		}
	}
	else if (oSelection.type == "Control" && oTextRange.length == 1)
	{
		var oControl = oTextRange.item(0) ;
		oControl.className = command.value ;
	}
	
	command.selectedIndex = 0 ;
	
	SetFocus();
}

function doFormatBlock(combo)
{
	if (combo.value == null || combo.value == "")
	{
		if (!FCKFormatBlockNames) loadFormatBlockNames() ;
		objContent.ExecCommand(DECMD_SETBLOCKFMT, OLECMDEXECOPT_DODEFAULT, FCKFormatBlockNames[0]);
	}
	else
		objContent.ExecCommand(DECMD_SETBLOCKFMT, OLECMDEXECOPT_DODEFAULT, combo.value);
	
	SetFocus();
}

function doFontName(combo)
{
	if (combo.value == null || combo.value == "")
	{
		// TODO: Remove font name attribute.
	}
	else
		objContent.ExecCommand(DECMD_SETFONTNAME, OLECMDEXECOPT_DODEFAULT, combo.value);
	
	SetFocus();
}

function doFontSize(combo)
{
	if (combo.value == null || combo.value == "")
	{
		// TODO: Remove font size attribute (Now it works with size 3. Will it work forever?)
		objContent.ExecCommand(DECMD_SETFONTSIZE, OLECMDEXECOPT_DODEFAULT, 3);
	}
	else
		objContent.ExecCommand(DECMD_SETFONTSIZE, OLECMDEXECOPT_DODEFAULT, parseInt(combo.value));
	
	SetFocus();
}

function dialogImage()
{	
	var html = FCKShowDialog("dialog/imagine/image/imagine_image.asp?project=" + config.Project + "&group=" + config.Vestiging, window, 545, 449);
	// The response is the IMG tag HTML
	if (html) insertHtml(html) ;
	SetFocus() ;
}

function dialogImageProperties()
{	
	// Gets the document DOM
	var oDOM = window.objContent.DOM ;
	
	// Gets the image if there is one selected.
	var image ;
	var sel = oDOM.selection.createRange();	
	if (oDOM.selection.type != 'Text') 
	{
		if (sel.length == 1) 
		{
			if (sel.item(0).tagName == "IMG") image = sel.item(0);
		}
	}
	
	src = image.getAttribute("src",2);	
	imageID = getImageFromSrc(src);
	
	FCKShowDialog("dialog/imagine/image/imagine_options.asp?project=" + config.Project + "&mode=1&image=" + imageID, objContent, 430, 520);
	SetFocus() ;
}

function getImageFromSrc(src)
{	
	bIsGIF = false;
	sValue = "";
	thumnailQueryString = "path"		
	if( src.indexOf( thumnailQueryString ) == -1 )
		thumnailQueryString = "source"
	src = src.substring(src.indexOf( thumnailQueryString ) + thumnailQueryString.length + 1);		
	nEndIndex = src.indexOf(".jpg");
	if(nEndIndex == -1) nEndIndex = src.indexOf(".png");
	if(nEndIndex == -1) { 
		nEndIndex = src.indexOf(".gif");		
		if(nEndIndex != -1)	bIsGIF = true;		
	}
	if(nEndIndex == -1) alert('Fout: Kan bestandsextensie niet achterhalen!\nZie regel 164 in fck_actions.js.');
	
	if(bIsGIF) {
		nStartIndex = src.lastIndexOf("/") + 1;
		sValue = src.substring(nStartIndex,nEndIndex);	
	}
	else
		sValue = src.substring(0,nEndIndex);	
	return sValue;
}

function dialogTable(searchParentTable)
{
	if (searchParentTable)
	{
		var oRange  = objContent.DOM.selection.createRange() ;
		var oParent = oRange.parentElement() ;
		
		while (oParent && oParent.nodeName != "TABLE")
		{
			oParent = oParent.parentNode ;
		}
		
		if (oParent && oParent.nodeName == "TABLE")
		{
			var oControlRange = objContent.DOM.body.createControlRange();
			oControlRange.add( oParent ) ;
			oControlRange.select() ;
		}
		else
			return ;
	}

	FCKShowDialog("dialog/imagine/table/imagine_table.asp?project=" + config.Project, objContent, 380, 240);	
	SetFocus() ;
}

function dialogTableCell()
{
	FCKShowDialog("dialog/imagine/table/imagine_tablecell.asp?project=" + config.Project, objContent, 220, 310);
	SetFocus() ;
}

function dialogLink()
{
	if (checkDecCommand(DECMD_HYPERLINK) != OLE_TRISTATE_GRAY)
	{
		//window.open("dialog/imagine/link/imagine_link.asp?project=" + config.Project + "&group=" + config.Vestiging);
		FCKShowDialog("dialog/imagine/link/imagine_link.asp?project=" + config.Project + "&group=" + config.Vestiging, objContent, 420, 266);
		SetFocus() ;
	}
}

// insertHtml(): Insert HTML at the current document position.
function insertHtml(html)
{
	if (objContent.DOM.selection.type.toLowerCase() != "none")
		objContent.DOM.selection.clear() ;
	objContent.DOM.selection.createRange().pasteHTML(html) ; 
	SetFocus() ;
}

function foreColor()
{
	var color = FCKShowDialog("dialog/fck_selcolor.html", window, 370, 270);
	if (color) objContent.ExecCommand(DECMD_SETFORECOLOR,OLECMDEXECOPT_DODEFAULT, color) ;
	SetFocus();
}

function backColor()
{
	var color = FCKShowDialog("dialog/fck_selcolor.html", window, 370, 270);
	if (color) objContent.ExecCommand(DECMD_SETBACKCOLOR,OLECMDEXECOPT_DODEFAULT, color) ;
	SetFocus();
}

function insertSpecialChar()
{
	var html = FCKShowDialog("dialog/fck_specialchar.html", window, 400,320);
	if (html) insertHtml(html) ;
	SetFocus() ;
}

function insertSmiley()
{
	var html = FCKShowDialog("dialog/fck_smiley.html", window, config.SmileyWindowWidth, config.SmileyWindowHeight) ;
	if (html) insertHtml(html) ;
	SetFocus() ;
}

function FCKShowDialog(pagePath, args, width, height)
{
//	window.open(pagePath);
	return showModalDialog(pagePath, args, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;help:no;scroll:no;status:no");
	// Useful in case some debugging is needed!	
//	 var oWindow = window.open(pagePath, "temp")
//	 oWindow.focus();
}

function about()
{
	FCKShowDialog("dialog/fck_about.html", window, 460, 290);
}

function pastePlainText()
{
	
	var sText = HTMLEncode( clipboardData.getData("Text") ) ;
	sText = sText.replace(/\n/g,'<BR>') ;
	insertHtml(sText) ;
}

function pasteFromWord()
{
	cleanAndPaste( GetClipboardHTML() ) ;	
	if (BrowserInfo.IsIE55OrMore)
		cleanAndPaste( GetClipboardHTML() ) ;
	else if ( confirm( lang["NotCompatiblePaste"] ) )
		decCommand(DECMD_PASTE) ;
}

function cleanAndPaste( html )
{
	// Remove all SPAN tags
	html = html.replace(/<\/?SPAN[^>]*>/gi, "" );
	// Remove all H tags
	html = html.replace(/<\/?H[^>]*>/gi, "" );	
	// Remove all FONT tags
	html = html.replace(/<\/?FONT[^>]*>/gi, "" );		
	// Remove all IMG tags
	html = html.replace(/<\/?IMG[^>]*>/gi, "" );	
	// Remove all BLOCKQUOTE tags
	html = html.replace(/<\/?BLOCKQUOTE[^>]*>/gi, "" );	
	// Remove all INPUT tags
	html = html.replace(/<\/?INPUT[^>]*>/gi, "" );		
	// Remove Class attributes
	html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Style attributes
	html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3") ;
	// Remove BgColor attributes
	html = html.replace(/<(\w[^>]*) bgcolor=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Lang attributes
	html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Width attributes
	html = html.replace(/<(\w[^>]*) width=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Background attributes
	html = html.replace(/<(\w[^>]*) background=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	// Remove Target attributes
	html = html.replace(/<(\w[^>]*) target=([^ |>]*)([^>]*)/gi, "<$1$3") ;	
	// Set target=_blank for all A tags attributes
	html = html.replace(/<A/gi, "<A target=_blank" );	
	// Remove XML elements and declarations
	html = html.replace(/<\\?\?xml[^>]*>/gi, "") ;
	// Remove Tags with XML namespace declarations: <o:p></o:p>
	html = html.replace(/<\/?\w+:[^>]*>/gi, "") ;
	// Replace the &nbsp;
	html = html.replace(/&nbsp;/, " " );
	// Transform <P> to <DIV>
	var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ;	// Different because of a IE 5.0 error
	html = html.replace( re, "<div$2</div>" ) ;
	
	insertHtml( html ) ;
}

function GetClipboardHTML()
{
	var oDiv = document.getElementById("divTemp")
	oDiv.innerHTML = "" ;
	
	var oTextRange = document.body.createTextRange() ;
	oTextRange.moveToElementText(oDiv) ;
	oTextRange.execCommand("Paste") ;
	
	var sData = oDiv.innerHTML ;
	oDiv.innerHTML = "" ;
	
	return sData ;
}

function HTMLEncode(text)
{
	text = text.replace(/&/g, "&amp;") ;
	text = text.replace(/"/g, "&quot;") ;
	text = text.replace(/</g, "&lt;") ;
	text = text.replace(/>/g, "&gt;") ;
	text = text.replace(/'/g, "&#146;") ;

	return text ;
}

function showTableBorders()
{
	objContent.ShowBorders = !objContent.ShowBorders ;
	SetFocus() ;
}

function showDetails()
{
	objContent.ShowDetails = !objContent.ShowDetails ;
	SetFocus() ;
}

var FCKFormatBlockNames ;

function loadFormatBlockNames()
{
	var oNamesParm = new ActiveXObject("DEGetBlockFmtNamesParam.DEGetBlockFmtNamesParam") ;
	objContent.ExecCommand(DECMD_GETBLOCKFMTNAMES, OLECMDEXECOPT_DODEFAULT, oNamesParm);
	var vbNamesArray = new VBArray(oNamesParm.Names) ;

	FCKFormatBlockNames = vbNamesArray.toArray() ;
}

function doZoom( sizeCombo ) 
{
	if (sizeCombo.value != null || sizeCombo.value != "")
		objContent.DOM.body.runtimeStyle.zoom = sizeCombo.value + "%" ;
}

function insertList( type )
{
	var oDoc = objContent.DOM ;
	if ( !config.UseBROnCarriageReturn || oDoc.queryCommandState( 'InsertOrderedList' ) || oDoc.queryCommandState( 'InsertUnorderedList' ) )
	{
		if ( type == 'ul' )
			decCommand( DECMD_UNORDERLIST ) ;
		else
			decCommand( DECMD_ORDERLIST ) ;
	}
	else
	{
		insertHtml('<' + type + '><li id="____tempLI">.</li></' + type + '>') ;
		
		var oLI = oDoc.getElementById( '____tempLI' ) ;
		oLI.removeAttribute("id") ;
		
		var oRange = oDoc.selection.createRange() ;
		oRange.moveToElementText( oLI ) ;
		oRange.findText( '.' ) ;
		oRange.select() ;
		oDoc.selection.clear() ;
	}
}

//function to perform spell check
function SpellCheck() 
{
	try {
		var tmpis = new ActiveXObject( "ieSpell.ieSpellExtension" ) ;
		tmpis.CheckAllLinkedDocuments( objContent );
	}
	catch(exception) {
		if( exception.number == -2146827859 )
		{
			if ( confirm( "Spell checker not installed. Do you want to download it now?" ) )
				window.open( config.SpellCheckerDownloadUrl , "SpellCheckerDownload" );
		}
		else
			alert("Error Loading ieSpell: Exception " + exception.number);
	}
}
