//-----------------------------------------------------------------------------
// Initialise global variables
var browser = navigator.userAgent.toLowerCase();
var isEditable = false;
var isGecko;
var isIE;
var isKonqueror;
var isSafari;
var imagegalleryloaded = 0;
var viewSource = 0;

// Set up the image array for keyword search filtering.
var imagesearchtimer = null;

//-----------------------------------------------------------------------------
// Check for browser compatibility.
function setupEditor()
{ 
	isIE = ((browser.indexOf("msie") != -1) && (browser.indexOf("opera") == -1) && (browser.indexOf("webtv") == -1)); 
	isGecko = (browser.indexOf("gecko") != -1);
	isSafari = (browser.indexOf("safari") != -1);
	isKonqueror = (browser.indexOf("konqueror") != -1);
 
	//-----------------------------------------------------------------------------
	// enable designMode if the browser is IE or Gecko based.
	if (document.getElementById && document.designMode && (isIE || isGecko)) {
		isEditable = true;
	} // End if.

} // End function.

//-----------------------------------------------------------------------------
// Function to reload the image gallery after a new image has been uploaded.
function reloadimagegallery (editor, wwwroot)
{
	if (imagegalleryloaded == 0) {
		imagegalleryloaded = 1;
	} else {
		insertImage (editor, true, wwwroot);
	} // End if.
} // End function.

//-----------------------------------------------------------------------------
// Function to remove images from the image gallery that do not match keyword.
function imagesearchfunction ()
{
	var i;
	var keyword = document.getElementById('imagegallerytextinput').value;
	var keywordregexp = eval('/' + keyword + '/i');
	var imagegalleryarray = document.getElementById('imagegallerythumbnails').childNodes;

	//------------------------------------------------------------------------------
	for (i = 0; i < imagegalleryarray.length; i++) {
		//------------------------------------------------------------------------------
		if (imagegalleryarray[i].nodeName.search(/div/i) != -1) {
			//------------------------------------------------------------------------------
			if ((keyword.length > 0) && (imagegalleryarray[i].id.search(keywordregexp) == -1)) {
				imagegalleryarray[i].style.display='none';
			//------------------------------------------------------------------------------
			} else {
				imagegalleryarray[i].style.display='block';
			} // End if.  
		} // End if.  
	} // End for.  
} // End function.

//-----------------------------------------------------------------------------
// Display popup to insert (or upload) an image.
function insertImage (editor, reloadifvisible, wwwroot)
{ 
	//------------------------------------------------------------------------------
	if ((document.getElementById('imgGallery').style.display == 'none')
			|| (reloadifvisible == true)) { 
		imagegalleryloaded = 0; // Clear loaded flag.

		document.getElementById('imgGallery').style.display='block';
		document.getElementById('imgGallery').style.background='#ffffff';
		document.getElementById('imgGallery').style.border='solid 1px #9ac';
		document.getElementById('imgGallery').style.float='left';
		document.getElementById('imgGallery').style.position='absolute';
		document.getElementById('imgGallery').style.height='66%';
		document.getElementById('imgGallery').style.width='90%'; 
		document.getElementById('imgGallery').style.left='32px'; 
		document.getElementById('imgGallery').style.top = '32px';

		document.getElementById('btnInsertImage').style.background='#ffffff';
		document.getElementById('btnInsertImage').style.border='solid 1px red';

		//------------------------------------------------------------------------------
		// Load the external file 'imagegallery.php'.
		// Use XMLHttpRequest for AJAX on Firefox/IceCat, Opera, Chrome, Safari, IE7+.
		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		//------------------------------------------------------------------------------
		// Use IE5/6 ActiveXObject for AJAX.
		} else {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} // End if.

		//------------------------------------------------------------------------------
		// Set up the state watching function for XMLHttpRequest.
		xmlhttp.onreadystatechange = function ()
		{
			//------------------------------------------------------------------------------
			// Respond to different Ready states:
			// 	0 == Un initialised; 1 == Request set up; 2 == Request sent;
			// 	3 == Request being processed; 4 == Request complete.
			if (xmlhttp.readyState < 4) {
				var loadingtext = '<p style="display:block;background:#ccffcc;text-align:center;"><img src="' + wwwroot + 'images/loading-spinner.gif" border="0"> Retrieving images...</p>';
				document.getElementById('imgGallery').innerHTML = loadingtext;
				//------------------------------------------------------------------------------
			} else { //if ((xmlhttp.readyState == 3) || (xmlhttp.readyState == 4))
				// Insert the gallery webpage as it is being loaded.
				document.getElementById('imgGallery').innerHTML = xmlhttp.responseText; 
			} // End if.
		} // End function.

		var url = wwwroot + "/imagegallery.php?editor=" + editor + "&height=" + document.getElementById('imgGallery').clientHeight + '&wwwroot=' + wwwroot;
		xmlhttp.open ("GET", url, true);
		xmlhttp.send (null);
						
	//------------------------------------------------------------------------------
	} else {
		document.getElementById('imgGallery').style.display='none';
		document.getElementById('btnInsertImage').style.background='inherit';
		document.getElementById('btnInsertImage').style.border='solid 1px #ffffcc';
	} // End if.
} // End function.

//-----------------------------------------------------------------------------
// Display popup (javascript default) to add link.
function insertLink(editor)
{
	var linkLocation = prompt("Enter a URL:", "http://");

	if ((linkLocation != null) && (linkLocation != "")) {
		formatText (editor, 'createlink', linkLocation);
	} // End if.
} // End function.

//-----------------------------------------------------------------------------
// # # # Javascript function dislpayEditor will create the textarea.  
function displayEditor(editorname, html, width, height, wwwroot) // # # #
{
	//------------------------------------------------------------------------------
	// Enable rich edit mode.
	if (isEditable) {
		document.write('<div style="position:relative;width:' + width + ';">');
		document.write('<div id="editToolbar" class="editToolbar" style="width:100%;">');
		document.write('<span>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'bold\', \'\')"><img id="btnBold" src="' + wwwroot + 'images/editor/btnBold.png"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'italic\', \'\')"><img src="' + wwwroot + 'images/editor/btnItalic.png" id="btnItalic"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'underline\', \'\')"><img src="' + wwwroot + 'images/editor/btnUnderline.png" id="btnUnderline"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'strikethrough\', \'\')"><img src="' + wwwroot + 'images/editor/btnStrikethrough.png" id="btnStrikethrough"></a>');
		document.write('</span>');
		document.write('<span>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'justifyleft\', \'\')"><img src="' + wwwroot + 'images/editor/btnLeft.png" id="btnLeft"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'justifycenter\', \'\')"><img id="btnCenter" src="' + wwwroot + 'images/editor/btnCenter.png"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'justifyright\', \'\')"><img id="btnRight" src="' + wwwroot + 'images/editor/btnRight.png"></a>');
		document.write('</span>');
		document.write('<span>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'undo\', \'\')"><img id="btnUndo" src="' + wwwroot + 'images/editor/btnUndo.png"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'redo\', \'\')"><img id="btnRedo" src="' + wwwroot + 'images/editor/btnRedo.png"></a>');
		document.write('</span>');
		document.write('<span>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'insertunorderedlist\', \'\')"><img src="' + wwwroot + 'images/editor/btnUnorderedList.png" id="btnUnorderedList"></a>');
		document.write('<a href="javascript:formatText(\'' + editorname + 'Editor\', \'insertorderedlist\', \'\')"><img id="btnOrderedList" src="' + wwwroot + 'images/editor/btnOrderedList.png"></a>');
		document.write('</span>');
		document.write('<span>');
		document.write('<a href="javascript:insertImage(\'' + editorname + 'Editor\', false, \'' + wwwroot + '\')"><img id="btnInsertImage" src="' + wwwroot + 'images/editor/btnInsertImage.png"></a>');
		document.write('<a href="javascript:insertLink(\'' + editorname + 'Editor\')"><img id="btnCreateLink" src="' + wwwroot + 'images/editor/btnCreateLink.png"></a>');
		document.write('<a href="javascript:showSource(\'' + editorname + 'Editor\')"><img id="btnShowSource" src="' + wwwroot + 'images/editor/btnShowSource.png"></a>');
		document.write('</div>');
		document.write('<iframe id="' + editorname + 'Editor" name="' + editorname + 'Editor" width="100%" height="' + height + '" style="background:#ffffff;"></iframe>'); 
		document.write('<div id="imgGallery" style="display:none;"></div>');
		document.write('</div>');

		document.getElementById(editorname + 'Editor').value = html;

		// create a hidden field that will hold everything that is typed in the textarea
		document.writeln('<input type="hidden" id="' + editorname + '" name="' + editorname + '" value="">');
		// call function designer
		designer(editorname + 'Editor', html);
	} else {
		// If not rich editing capable then fall back to a standard textarea editor.
		document.writeln('<textarea name="' + editor + '" id="' + editor + '" cols="39" rows="10">' + html + '</textarea>');
	} // End if.
} // End function. # # #

//-----------------------------------------------------------------------------
// Change toolbar state button.
function updateToolbar (editor)
{
	//-----------------------------------------------------------------------------
	// Update the <strong> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('bold')) {
		document.getElementById('btnBold').style.background='#ffffff';
		document.getElementById('btnBold').style.border='solid 1px red';
	} else {
		document.getElementById('btnBold').style.background='inherit';
		document.getElementById('btnBold').style.border='solid 1px #ffffcc';
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <em> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('italic')) {
		document.getElementById('btnItalic').style.background='#ffffff';
		document.getElementById('btnItalic').style.border='solid 1px red';
	} else {
		document.getElementById('btnItalic').style.background='inherit';
		document.getElementById('btnItalic').style.border='solid 1px #ffffcc';
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <underline> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('underline')) {
		document.getElementById('btnUnderline').style.background='#ffffff';
		document.getElementById('btnUnderline').style.border='solid 1px red';
	} else {
		document.getElementById('btnUnderline').style.background='inherit';
		document.getElementById('btnUnderline').style.border='solid 1px #ffffcc';
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <left> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('justifyleft')) {
		document.getElementById('btnLeft').style.background='#ffffff';
		document.getElementById('btnLeft').style.border='solid 1px red';
	} else {
		document.getElementById('btnLeft').style.background='inherit';
		document.getElementById('btnLeft').style.border='solid 1px #ffffcc';
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <center> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('justifycenter')) {
		document.getElementById('btnCenter').style.background='#ffffff';
		document.getElementById('btnCenter').style.border='solid 1px red';
	} else {
		document.getElementById('btnCenter').style.background='inherit';
		document.getElementById('btnCenter').style.border='solid 1px #ffffcc';
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <right> toolbar button.
	if (document.getElementById(editor).contentWindow.document.queryCommandState('justifyright')) {
		document.getElementById('btnRight').style.background='#ffffff';
		document.getElementById('btnRight').style.border='solid 1px red';
	} else {
		document.getElementById('btnRight').style.background='inherit';
		document.getElementById('btnRight').style.border='solid 1px #ffffcc';
	} // End if.
} // End function.  

//-----------------------------------------------------------------------------
// this is designer function that enables designMode
// and writes default text to the text area
function designer(editor, html)
{
	var mainContent= "<html id=" + editor + "><head></head><body>" + html + "</body></html>" ;
	// assign the frame(textarea) to the edit variable using that frames id
	var edit = document.getElementById(editor).contentWindow.document;
	// write the content to the textarea
	edit.write(mainContent);
	edit.close();
	// enable the designMode	
	edit.designMode =  "On" ;
	edit.execCommand("styleWithCSS", false, false); // Use HTML tags rather than CSS.

	//-----------------------------------------------------------------------------
	// Add function to update formatting buttons to reflect style under cursor.
	if (document.addEventListener) {
		edit.addEventListener('keyup', function(){updateToolbar(editor)}, true);
		edit.addEventListener('mouseup', function(){updateToolbar(editor)}, true); 
		edit.addEventListener('onupdate', function(){updateToolbar(editor)}, true);
	//-----------------------------------------------------------------------------
	} else if (document.attachEvent) {
		document.getElementById(editor).attachEvent('keyup', updateToolbar);
		document.getElementById(editor).attachEvent('mousemove', updateToolbar);
	} // End if.  
} // End function.

//-----------------------------------------------------------------------------
// Change the editable area to plain text or the other way around,
// depending on if the HTML source is already being viewed.
function showSource (editor)
{
	var html;
	var mainField;

	// first we assign the content of the textarea to the variable mainField
	mainField = document.getElementById(editor).contentWindow;

	//-----------------------------------------------------------------------------
	// Choose to display either HTML source or rich text.
	if (viewSource) {
		// Revert from HTML source view.
		// Convert visual space to actual spaces.
		mainField.document.body.innerHTML = mainField.document.body.innerHTML.replace(/<br>/g, '\n').replace(/\&nbsp\;/g, ' ');
		html = mainField.document.body.ownerDocument.createRange();
		html.selectNodeContents(mainField.document.body);
		mainField.document.body.innerHTML = html.toString();
		viewSource = 0;
	} else {
		// Display HTML source.
		html = document.createTextNode(mainField.document.body.innerHTML);
		mainField.document.body.innerHTML = "";
		html = mainField.document.importNode(html,false);
		mainField.document.body.appendChild(html);
		// Preserve line breaks and spacing.
		mainField.document.body.innerHTML = mainField.document.body.innerHTML.replace(/\n/g, '<br>').replace(/  /g, '&nbsp '); 
		viewSource = 1;
	} // End if.

	//-----------------------------------------------------------------------------
	// Update the <html> (Show Source) toolbar button.
	if (viewSource) {
		document.getElementById('btnShowSource').style.background='#ffffff';
		document.getElementById('btnShowSource').style.border='solid 1px red';
	} else {
		document.getElementById('btnShowSource').style.background='inherit';
		document.getElementById('btnShowSource').style.border='solid 1px #ffffcc';
	} // End if.  
} // End function.

//-----------------------------------------------------------------------------
// Insert a non-specific block of text.
function insertText (editor, text)
{
	var mainField;

	// First we assign the content of the textarea to the variable mainField
	mainField = document.getElementById(editor).contentWindow;

	// Attempt to insert text the Opera/Gecko (and compatibles) way.
	if (mainField.getSelection()) {
		var sel = mainField.getSelection(); 
		var start = sel.getRangeAt(0);
		var fragment = start.createContextualFragment(text);
		start.insertNode(fragment);
	// Otherwise try to insert text the IE way.
	} else if (mainField.selection) {
		mainField.focus(); 
		var range = mainfield.selection.createRange();
		range.text = text;
		mainField.focus();
	} // End if.
} // End function.

//-----------------------------------------------------------------------------
// To execute command we will use javascript function formatText. 
function formatText(editor, command, option)
{
	var mainField;

	// first we assign the content of the textarea to the variable mainField
	mainField = document.getElementById(editor).contentWindow;
	// then we will use execCommand to execute the option on the textarea making sure the textarea stays in focus
	try {
		mainField.focus();
		mainField.document.execCommand(command, false, option);

		// Check if the cursor is within any formatted area.
		if (mainField.document.queryCommandState(command)) {
			updateToolbar (editor); // Update the toolbar.
		} // End if.

		mainField.focus();
	} catch (e) {
		// No action on error.
	} // End try/catch.
} // End function.

//-----------------------------------------------------------------------------
function updateText(editor)
{
	if (!isEditable) return;
	// assign the value of the textarea to the hidden field. 
	var hiddenField = document.getElementById(editor);
	hiddenField.value = document.getElementById(editor + 'Editor').contentWindow.document.body.innerHTML;
} // End function.

