/** Extra functions that are useful when writing Javascript code
    to integrate with a tinymce instance **/

/*
 * Insert a Zedcore-CMS template tag into the document in the current tinyMCE instance
 * Tag is inserted either at the current cursor position or around the selected text.
 * 
 * P.S. Internet Explorer smells of poo. Every other browser remembers the tinyMCE cursor position when it loses focus
 * but IE forgets it.
 * 
 */

/* IE smells of poo and loses the tinyMCE cursor position when the tinyMCE instance loses focus.
 	To get around this we save the cursor position when we lose focus and restore it when we regain
 	focus.
*/ 	

var tinyMCE_selection_bookmark = false;

function zcHandleTinyMCEEvent(e)
{
	if(e.type == 'beforedeactivate')	// TinyMCE throws this event before it looses focus. 
	{
		tinyMCEinst = tinyMCE.getInstanceById('mce_editor_0');
		tinyMCE_selection_bookmark = tinyMCEinst.selection.getBookmark();	
	}	
}


function TinyMCE2_InsertTemplateTag(sTagName, bRequireClosingTag, sDefaultContents)
{
	sOpenTag = '<$'+sTagName+'>';
	sCloseTag = '<$/'+sTagName+'>';
	sSelfClosingTag = '<$'+sTagName+'/>';	/* ZC templates don't recognise self closing tags */

	tinyMCEinst = tinyMCE.getInstanceById('mce_editor_0');
	/* Restore the cursor position for IE */
	if (tinyMCE_selection_bookmark)
	{
		tinyMCEinst.selection.moveToBookmark(tinyMCE_selection_bookmark);
	}		
			
	sSelectedText = tinyMCEinst.selection.getSelectedText();
	if (bRequireClosingTag && (sSelectedText == '' || !sSelectedText))
		sTagContents = sDefaultContents;
	else
		sTagContents = sSelectedText;
	
	if (sTagContents == '')
		tinyMCE.execInstanceCommand('mce_editor_0','mceInsertContent',false,sOpenTag);
	else if (sSelectedText == '')
		tinyMCE.execInstanceCommand('mce_editor_0','mceInsertContent',false,sOpenTag+sTagContents+sCloseTag);
	else
		tinyMCE.execInstanceCommand('mce_editor_0','mceReplaceContent',false,sOpenTag+sTagContents+sCloseTag);
}
