// 2006 Chris Pyper

// Grab text and fire off request to server
function spellCheck()
{
	debug('spellCheck('+EDITORUSERLANGUAGE+')', 'info');

	if(!docSourceClone || !docSourceOrig)
		return false;

	if(docSourceOrig && docSourceOrig.tagName == 'IMG')
		return false;

	var text = docSourceClone.innerHTML;

    var xmlReq = newXMLHTTPRequest(SPELLCHECKBASEURL, "POST", spellCheckReturned);
    var postData = "mode=AJAX&req=SpellCheck"
                 + "&xcache=" + getRandom()
                 + "&text=" + encodeHtml(text)
				 + "&language=" + EDITORUSERLANGUAGE;

    xmlReq.send(postData);
}

// Spell Check corrections cache
var correctionArray = new Array();

// Receive request, parse xml, cache corrections, highlight corrections
function spellCheckReturned(xmlResponse,textResponse)
{
	debug('spellCheckReturned()', 'info');

	var xmlDoc = xmlResponse;

	if(!xmlDoc)
	{
		debug('spellCheckReturned() - Error no XML Doc returned', 'error');
		return false;
	}

	xmlDoc.async = false;

	var correctionNodes = xmlDoc.getElementsByTagName("correction");
	
	if(correctionNodes.length < 1)
	{
    	debug('spellCheckReturned() - Error no correction nodes found', 'warn');
		return false;
	}

	for(var i=0; i< correctionNodes.length; ++i)
	{
		var wordNode = correctionNodes[i].getElementsByTagName("word");

		if(wordNode.length < 1)
			continue;

		var word = wordNode[0].firstChild.nodeValue;

		var suggestionNodes = correctionNodes[i].getElementsByTagName("suggestion");
		var suggestionArray = new Array();

		for(var j=0; j < suggestionNodes.length; ++j)
		{
			var suggestion = suggestionNodes[j].firstChild.nodeValue;
			suggestionArray[j] = suggestion;
		}

		correctionArray[word] = suggestionArray;
	}

	removeSpellCheckHighlighting();

	if(docSourceClone && docSourceOrig && docSourceOrig.tagName != 'IMG')
	{
		var checked = docSourceClone.innerHTML;

		for(var word in correctionArray)
		{
			currentWord = word;

			// I would like to thank Rudy Desjardins for his help with this regular expression.  His great contribution to this project
			// made spell check possible for all of us.
			var re = new RegExp("(^|\\s|[\\.,;:\\?\\!])" + word + "($|\\s|[\\.,;:\\?\\!])");

			var suggestionBox = generateSpellCheckSpan(word);
			while(re.test(checked))
				checked = checked.replace(re, "$1" + suggestionBox.innerHTML + "$2");
		}

		docSourceClone.innerHTML = checked;
	}

	return true;
}

// Reference to last clicked on correction
var currentWordCorrectionDocRef = false;

// Show suggestions for highlighted word
function showSuggestions(docRef)
{
	debug('showSuggestions', 'info');

	if(correctionArray[docRef.innerHTML])
		corrections = correctionArray[docRef.innerHTML];
	else
		return false;

	currentWordCorrectionDocRef = docRef;

	correctionTable = document.createElement('table');
    correctionTBody = document.createElement('tbody');

    for(var i=0; i < corrections.length && i < MAXCORRECTIONS; ++i)
    {
        var tr = document.createElement('tr');
        var td = document.createElement('td');

		td.onclick = makeCorrection;

		td.innerHTML = corrections[i];

        tr.appendChild(td);
        correctionTBody.appendChild(tr);

		tr.onmouseover = correctionOnMouseOver;
		tr.onmouseout  = correctionOnMouseOut;
    }

    correctionTable.appendChild(correctionTBody);

	correctionTable.cellPadding = '0';
    correctionTable.cellSpacing = '0';
    correctionTable.border      = '0';

    var pos = findPos(docRef);

    var x = pos[0];
    var y = pos[1];

    // Compensate for positioning of iframe
    if(!ie)
    {
        var iframePos = findPos(iframe);
        x = x + iframePos[0];
        y = y + iframePos[1];
    }

	addClass(correctionTable, 'correctionTable');

    correctionTable.style.left  = x;
    correctionTable.style.top   = y + docRef.offsetHeight;
    correctionTable.style.width = docRef.offsetWidth;

	document.getElementById('spellCheck').innerHTML = '';
	document.getElementById('spellCheck').appendChild(correctionTable);
}

// Fancy pants mouse effects
function correctionOnMouseOver(e)
{
	var docRef = getDOMfromEventObject(getEventObject(e));
	addClass(docRef, 'correctionOnMouseOver');
}

// Remove fancy pants mouse effects
function correctionOnMouseOut(e)
{
	var docRef = getDOMfromEventObject(getEventObject(e));
	removeClass(docRef, 'correctionOnMouseOver');
}

// Make the correcion
function makeCorrection(e)
{
	debug('makeCorrection()', 'info');

	var word = getDOMfromEventObject(getEventObject(e)).innerHTML;

	var replacement = document.createTextNode(word);
	currentWordCorrectionDocRef.parentNode.replaceChild(replacement, currentWordCorrectionDocRef);
	document.getElementById('spellCheck').innerHTML = '';
}

function removeCorrection(docRef)
{
	debug('removeCorrection()', 'info');
	
	var word = docRef.innerHTML;
	
	var replacement = document.createTextNode(word);
	docRef.parentNode.replaceChild(replacement, docRef);
	document.getElementById('spellCheck').innerHTML = '';
}

// Find pos, good method used offset, works everytime, courtesy of quirksmode
function findPos(obj)
{
	debug('findPos', 'info');

	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

// Generate the highlight span for the correction
function generateSpellCheckSpan(word)
{
	debug('generateSpellCheckSpan', 'info');

	var errorSpan = document.createElement('span');
	addClass(errorSpan, 'spellCheckWord');

	errorSpan.innerHTML = word;
	addClass(errorSpan, 'spellingError');

	// Mozilla does not support outerHTML properties, so wrap in temporary div to create another layer
	var tempDiv = document.createElement('div');
	tempDiv.appendChild(errorSpan);

	return tempDiv;
}
