var spellcheck_results = {};
var spellcheck_in_progress = false;

function spellcheck_check( textarea_id )
{

	// Reset all divs, in case no words were incorrectly spelled before
	document.getElementById('spellcheckerror_' + textarea_id).style.display = 'none';
	document.getElementById('spellcheckignoreword_' + textarea_id).style.display = '';
	document.getElementById('spellchecksuggestions_heading_' + textarea_id).style.display = '';
	document.getElementById('spellcheckwordlist_' + textarea_id).style.display = '';

	var text = document.getElementById(textarea_id).value;
	
	var xmlhttprequest = create_XMLHttpRequest();
	
	var parameters = 'text=' + escape(text);
	xmlhttprequest.open('POST', '/ajax/spellcheck', true);
	xmlhttprequest.setRequestHeader("Content-length", parameters.length);
	xmlhttprequest.setRequestHeader("Connection", "close");
	xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	xmlhttprequest.onreadystatechange = function()
	{
		if( xmlhttprequest.readyState == 4 || xmlhttprequest.readyState == 0 )
		{
			if ( xmlhttprequest.status == 200 )
			{
				var xmldoc = xmlhttprequest.responseXML;
	
				var words = xmldoc.getElementsByTagName('word');
	
				var suggestions = document.getElementById('spellcheckSuggestions_' + textarea_id);
	
				var word_count = 0;
	
				if ( words.length > 0 )
				{
					spellcheck_in_progress = false;
				}
				
				spellcheck_results[textarea_id] = { 'current': 0, 'words': new Array() };
	
				for( var i = 0; i < words.length; i++ )
				{
					var word = words[i];
	
					var word_value = word.getAttribute('value');
					
					if( word.getAttribute('correct') == 'FALSE' )
					{
						spellcheck_results[textarea_id]['words'][word_count] = {
							'word': word_value,
							'start': parseInt(word.getAttribute('start')),
							'end': parseInt(word.getAttribute('end'))
						};
	
						spellcheck_results[textarea_id]['words'][word_count]['suggestions'] = new Array();
	
						var suggestions = word.getElementsByTagName('suggestion');
	
						for( var s_i = 0; s_i < suggestions.length; s_i++ )
						{
							spellcheck_results[textarea_id]['words'][word_count]['suggestions'][s_i] = suggestions[s_i].textContent ? suggestions[s_i].textContent : suggestions[s_i].text;
						}
	
						word_count++;
					}
				}
	
				spellcheck_update(textarea_id);
			}
			else
			{
				document.getElementById('spellcheckerror_' + textarea_id).style.display = '';
				document.getElementById('spellcheckerror_' + textarea_id).innerHTML = '<span style="font-size: 13px">An error has occured when trying to connect to the spellcheck. Error code: ' + xmlhttprequest.status + '</span>';
				document.getElementById('spellcheckignoreword_' + textarea_id).style.display = 'none';
				document.getElementById('spellchecksuggestions_heading_' + textarea_id).style.display = 'none';
				document.getElementById('spellcheckwordlist_' + textarea_id).style.display = 'none';
			}
		}
	}
	
	
	this.spellcheck_check_timeout = function()
	{
		if ( spellcheck_in_progress == true )
		{
			document.getElementById('spellcheckerror_' + textarea_id).style.display = '';
			document.getElementById('spellcheckerror_' + textarea_id).innerHTML = 'The spell check request has timed out,  retrying.';
			document.getElementById('spellcheckignoreword_' + textarea_id).style.display = 'none';
			document.getElementById('spellchecksuggestions_heading_' + textarea_id).style.display = 'none';
			document.getElementById('spellcheckwordlist_' + textarea_id).style.display = 'none';
			spellcheck_check(textarea_id);
			
			spellcheck_in_progress = false;
			clearInterval(spellcheck_progress_checker);
		}
	}

	xmlhttprequest.send(parameters);
	spellcheck_in_progress = true;
	spellcheck_progress_checker = setInterval(this.spellcheck_check_timeout, 30000);
	
}




function spellcheck_update( textarea_id )
{
	var suggestions_el = document.getElementById('spellcheckSuggestions_' + textarea_id);
	suggestions_el.innerHTML = '';

	var current = spellcheck_results[textarea_id]['current'];
	if( spellcheck_results[textarea_id]['words'][current] != undefined )
	{
		var results = spellcheck_results[textarea_id]['words'][current];

		document.getElementById('spellcheckWord_' + textarea_id).innerHTML = results['word'];

		for( var i = 0; i < results['suggestions'].length; i++ )
		{
			var suggestion_el = document.createElement('a');
			suggestion_el.href = '#';
			suggestion_el.onclick = spellcheck_make_change_onclick_function(textarea_id, results['suggestions'][i]);
			suggestion_el.innerHTML = results['suggestions'][i];
			suggestions_el.appendChild(suggestion_el);
			if( i != (results['suggestions'].length - 1) )
			{
				suggestions_el.appendChild(document.createTextNode(', '));
			}
		}

		textarea_select_range(document.getElementById(textarea_id), results['start'], results['end']);
	}
	else
	{
		document.getElementById('spellcheckWord_' + textarea_id).innerHTML = '';
		if( window['spellcheck_complete_' + textarea_id] != undefined )
		{
			document.getElementById('spellcheckerror_' + textarea_id).style.display = '';
			document.getElementById('spellcheckerror_' + textarea_id).innerHTML = '<b>No misspellings found.</b>';
			document.getElementById('spellcheckignoreword_' + textarea_id).style.display = 'none';
			document.getElementById('spellchecksuggestions_heading_' + textarea_id).style.display = 'none';
			document.getElementById('spellcheckwordlist_' + textarea_id).style.display = 'none';

		}
	}
}

function spellcheck_make_change_onclick_function( textarea_id, new_word )
{
	return function() {
		spellcheck_change(textarea_id, new_word);
		return false;
		};
}

function spellcheck_change( textarea_id, new_word )
{
	var current = spellcheck_results[textarea_id]['current'];
	var results = spellcheck_results[textarea_id]['words'][current];
	textarea_replace_range(document.getElementById(textarea_id), results['start'], results['end'], new_word);

	var offset = results['word'].length - new_word.length;

	for( var i = current; i < spellcheck_results[textarea_id]['words'].length; i++ )
	{
		spellcheck_results[textarea_id]['words'][i]['start'] -= offset;
		spellcheck_results[textarea_id]['words'][i]['end'] -= offset;
	}

	spellcheck_results[textarea_id]['current']++;

	spellcheck_update(textarea_id);
}

function spellcheck_ignore( textarea_id )
{
	spellcheck_results[textarea_id]['current']++;
	spellcheck_update(textarea_id);
}

function spellcheck_reset( textarea_id )
{

}

function textarea_select_range( textarea, start, end )
{
	if( textarea.setSelectionRange != undefined )
	{
		textarea.setSelectionRange(start, end);
		textarea.focus();
	}
	else
	{
		var range = textarea.createTextRange();
		range.collapse(true);
		range.moveEnd('character', end);
		range.moveStart('character', start);
		range.select();
	}
}

function textarea_replace_range( textarea, start, end, new_text )
{
	textarea.value = textarea.value.substring(0, start) + new_text + textarea.value.substring(end, textarea.value.length);
	textarea_select_range(textarea, start, start + new_text.length);
}
