/*************************************************************************
    Spellify - spellify.js v1.0

    Copyright (c) 2006-2007 Nikola Kocic. (www.spellify.com, www.nikolakocic.com)
	
    Powered by Google(tm) spell checker.
   
    ***********************************************************************
	
    This file is part of Spellify.

    Spellify is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Spellify is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Spellify.  If not, see <http://www.gnu.org/licenses/>
	
/*******************************************************************************************************************************
*  Language Settings: 
*  
*  Set the corresponsding language value, i.e. eng for English, to the "lang" variable declared immediately below.
*		English 	- eng
*	 	Dansk		- da
*		Deutsch 	- de
*		Suomi		- fi
*		Français	- fr
*		Nederlands 	- nl
*		Español 	- es
*		Italiano 	- it
*		Polski 		- pl
*  		Português 	- pt
*		Svenska 	- sv
*/
var lang = 'eng';									//default language setting
/*******************************************************************************************************************************/
var maxTimeAfterLastStrokeT = 1750;							//value in milliseconds before spell check occurs
var optionalLeftOffset = 35;								//optional left position offset for loader div
var optionalTopOffset = 0;								//optional top position offset for corrections div
/*************************************DO NOT CHANGE BELOW***********************************************************************/
var defUrl  = '/beijing/spellify/spellify/spellify.php';
var ignoreClassName = 'spellify_ignore'
var http_requestT;
var http_responseT;
var requestMethod = 'POST';
var timerE = 0;
var timerIDE=0;//setTimeout('checkTimer2()',5000);
var txtObject;
var correctionsBody;
var correctionsContainer;
var loaderDiv;
var spellifyDiv;
var isIE = (navigator.userAgent.indexOf('MSIE')>=0 && document.all) ? true : false;
var iw=new Array();
var iwc=0;
/********************************************************************************************************************************/

/**
Array.prototype.contains = function ( needle ) {
 for (i in this) { 
if (this[i] == needle) return true; 
} 
return false; 
}
**/


function setCookie(name, value, expires) { 
try {

//document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString()); 
document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expires.toGMTString(); 
} catch (err) {}
} 



function getCookie (name) { 
//try {
var dc = document.cookie; 
var cname = name + "="; 

if (dc.length > 0) { 
  begin = dc.indexOf(cname); 
  if (begin != -1) { 
    begin += cname.length; 
    end = dc.indexOf(";",begin);
    if (end == -1) end = dc.length;
    return unescape(dc.substring(begin, end));
  } 
} 
//} catch (err) {}
return null;
}





function GoogCorrection(offset, length, suggestions)
{
	//Fields
	this._offset = offset;
	this._length = length;
	this._suggestions = suggestions;
	
	//Properties
	this.getOffset = function(){
		return this._offset;
	}
	this.getLength = function(){
		return this._length;
	}
	this.getSuggestions = function(){
		return this._suggestions;
	}
}

function XmlDocumentLoader(xml)
{
	//Fields
	this._xml = xml;
	this._xmlDoc = null;
	
	//Methods
	this.Create = function(){
		try
		{
			if(this._xml == '' || this._xml == null)
			{
				alert('XML string cannot be empty or null');
			}
			else
			{
				//if internet explorer
				if (window.ActiveXObject)
			    {
				 	 this._xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				  	 this._xmlDoc.async ="false";
				  
					  //try to load xml from file
					 this._xmlDoc.loadXML(this._xml);
			    }
				else
			    {
					var parser=new DOMParser();
					this._xmlDoc=parser.parseFromString(this._xml,"text/xml");
			    }
			}
			
			return this._xmlDoc;
		}
		catch(e)
		{
			alert(e.name + '\n' + e.message);
		}
	}
}

function GoogSpellingCorrectionLoader(xmlSrc)
{
	//Fields
	this._xmlDoc = null;
	this._xml = xmlSrc;
	this._c_suggestions = new Array();
	this.isIE = (navigator.userAgent.indexOf('MSIE')>=0 && document.all) ? true : false;
	
	//Methods
	this.Load = function(){
		  xmlDocLoader = new XmlDocumentLoader(this._xml);
		  this._xmlDoc = xmlDocLoader.Create();
	}
	this.Parse = function(){
		try
		{
			var C = this._xmlDoc.getElementsByTagName("c");
			
			if(C.length == 0)
				return;
				
			for(i=0;i<C.length;i++)
			{
				var correctionOffset = C[i].getAttribute("o");
				var correctionLength = C[i].getAttribute("l");
				
				if(!this.IsNodeText(C[i]))
					return;
				else
				{
					var correctionCollection = C[i].childNodes[0].nodeValue.split("	");
					
					this._c_suggestions[i] = new GoogCorrection(correctionOffset, correctionLength, correctionCollection);
				}
			}
		}
		catch(e)
		{
			alert(e.name + '\n' + e.message);
		}
	}
	
	this.IsNodeText = function (node){
			return (this.isIE) ? ((node.text == '') ? false : true) : ((node.textContent == '') ? false : true);
	}
	
	//Properties
	this.getCSuggestions = function(){
		return this._c_suggestions;
	}
}

function ClearTextBox(txtObjectId)
{
	///////////////document.getElementById(txtObjectId).value = '';
	///////////////ResetCorrectionsContainer();
}

function CreateRequest()
{
	if(window.XMLHttpRequest)
	{
		http_requestT = new XMLHttpRequest();
			
		if (http_requestT.overrideMimeType) 
		{
			http_requestT.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject)  // IE
	{
		try 
		{
			http_requestT = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		 {
			try 
			{
				http_requestT = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
				 
			}
		}
	}
//alert('setting ajax spell');
	if (!http_requestT) {
		 //alert('Cannot create XMLHTTP instance');
		 return false;
	}
}

function helloo() {
  alert('helloo');
}

function InitializeSpellify()
{
//alert('initi');
	correctionsBody = document.getElementById('correctionsBody');
	correctionsContainer = document.getElementById('correctionsContainer');
	//loaderDiv = document.getElementById('loaderDiv');
	spellifyDiv = document.getElementById('spellify');
		
	var inputFields = document.getElementsByTagName('INPUT');
	var textareas = document.getElementsByTagName('TEXTAREA');
	
	if(spellifyDiv && correctionsBody && correctionsContainer) // && loaderDiv)
	{
		for(var i=0;i<inputFields.length;i++)
		{
			if(inputFields[i].className.match(ignoreClassName) == null && inputFields[i].type == "text")
			{
				inputFields[i].blur();
				inputFields[i].onkeydown  = SetCorrectionContainerPosition;
				inputFields[i].onkeyup    = Capture_Key;
				inputFields[i].onkeypress = Capture_Key;
				inputFields[i].onfocus    = SetCorrectionContainerPosition;
				inputFields[i].onpaste	  = CheckTimer2;
			}
		}
		
		for(var i=0;i<textareas.length;i++)
		{
			if(textareas[i].className.match(ignoreClassName) == null)
			{
				textareas[i].blur();
				textareas[i].onkeydown  = SetCorrectionContainerPosition;
				textareas[i].onkeyup    = Capture_Key;
				textareas[i].onkeypress = Capture_Key;
				textareas[i].onfocus    = SetCorrectionContainerPosition;
				textareas[i].onpaste	= CheckTimer2;
///textareas[i].onChange	= CheckTimer;
			}
		}
		
		CreateRequest();
///setInterval('CheckTimer2()',12000);

	}
}

function SetCorrectionContainerPosition(e){
	/////////////////////ResetCorrectionsContainer();
	txtObject = getEventSrc(e);
	///////////////////////PositionCorrectionsContainer();
}

function getEventSrc(e) {
  if( !e || (!e.srcElement && !e.target) ) { e = window.event; }
  return src = (e && e.srcElement)? e.srcElement :
      (e && e.target)? e.target : false;
}

//Resets the corrections container
function ResetCorrectionsContainer(){
	/////////////////////correctionsBody.innerHTML = '';
	////////////////////correctionsContainer.style.display = 'none';
}

function Capture_Key(e){	
WYSIWYG.updateTextArea('text');
		if(typeof window.event!="undefined"){
			e=window.event;
		}
		
		switch(e.type)
		{
			case "keydown" : 
				if ((e.keyCode >= 8 && e.keyCode < 32) || (e.keyCode > 32 && e.keyCode < 44))
				{
					//loaderDiv.style.display = 'none';
				}
				else
				{
					/////////////////ResetCorrectionsContainer();
				}

				ResetTimer8();
				break;
								
			case "keyup" :
				if(e.keyCode == 8)
				{
					//////////if(txtObject.value == '')
					{
						/////////////////////loaderDiv.style.display = 'none';
						/////////////////////Effect.Fade('correctionsContainer');
					}
//else {CheckTimer();}
				}
				if(e.keyCode == 16)
				{
					///if(!isTextSelected())
						///CheckTimer();
				}
				break;
				
			case "keypress" :
				if( (e.keyCode > 8 && e.keyCode < 32) || (e.keyCode > 32 && e.keyCode < 44))
				{
					ResetTimer8();
				}
				else
				{
					if(!isTextSelected()) {
//if (timerIDE==null) (timerIDE=setTimeout('checkTimer2()',5000);}
//						else 
{ResetTimer8();} //CheckTimer();
}
				}
				break;
			default:
				break;
		}
}

function isTextSelected()
{
	if(isIE)
	{
		var range = document.selection.createRange();
		return (range.text.length > 0) ? true : false;
	}
	else
	{
		return (txtObject.selectionStart < txtObject.selectionEnd) ? true : false;
	}
}

function CheckTimer() {
  //alert('ct'); 
  ResetTimer8();
}

function CheckTimer8() {ResetTimer8();}

function CheckTimer2()
{}

function checkIt() {
	///if(timerE >= maxTimeAfterLastStrokeT)
	{

//alert(WYSIWYG.getCP()); 

//WYSIWYG.blurit();

WYSIWYG.updateTextArea('text');
WYSIWYG.updateTextArea('comment');
WYSIWYG.updateTextArea('comments');
var ss='';

try {ss=document.getElementById('text').value;} catch (err10) {}
try {ss=document.getElementById('comment').value;} catch (err10) {}
try {ss=document.getElementById('comments').value;} catch (err10) {}

//alert(ss);
/***/
var jk=0;
for (jk=0;jk<25;jk++) {
var u=ss.indexOf('<SPAN style="COLOR: red" name="red">');
if (u>=0) {
var v=ss.indexOf('</SPAN>',u);
if (v>0) {
var s1=ss.substr(0,v);
var s2=ss.substr(v+7,ss.length-v-7);
ss=s1+s2;
}
ss=ss.replace('<SPAN style="COLOR: red" name="red">','');
}
}
/***/

WYSIWYG.uwe(ss);
WYSIWYG.updateTextArea('text');
WYSIWYG.updateTextArea('comment');
WYSIWYG.updateTextArea('comments');



//alert('in chk');
////WYSIWYG.updateTextArea('text');
////var 
try {ss=document.getElementById('text').value;} catch (err11) {}
try {ss=document.getElementById('comment').value;} catch (err11) {}
try {ss=document.getElementById('comments').value;} catch (err11) {}

ss='<![CDATA['+ss+']]>';

//ss=ss.replace(/(<([^>]+)>)/ig,"");
//ss=ss.replace('&nbsp;',' ');

//alert(ss+'#');
		///timerE = 0;
		///ResetTimer();
		///loaderDiv.style.display = 'block';
		makeRequestR('?lang=' + lang, ss); //txtObject.value);
			
		return;
	}
		
	///if(timerE < maxTimeAfterLastStrokeT)
	{
	///	timerE = timerE + 10;
	///	timerIDE = setTimeout(CheckTimer, 50)
	}
}

function ResetTimer8()
{
		//timerE = 0;
		clearTimeout(timerIDE);
  timerIDE=setTimeout('CheckTimer2()',2500);
}

function PositionCorrectionsContainer()
{	
		var leftPos = getLeftPos(txtObject);
		var topPos  = getTopPos(txtObject);
		correctionsContainer.style.left = leftPos  + 'px';
		correctionsContainer.style.top = topPos + txtObject.offsetHeight + optionalTopOffset + 'px';			
		
		///loaderDiv.style.left = leftPos + txtObject.offsetWidth +  optionalLeftOffset + 'px';
		///loaderDiv.style.top = topPos + 'px';
//alert(leftPos + txtObject.offsetWidth +  optionalLeftOffset);
//alert(topPos);
}

function getTopPos(obj)
{		
	  var newPos = obj.offsetTop;
	  while((obj = obj.offsetParent) != null)
	  {
	  	if(obj.tagName!='HTML')
		{
	  		newPos += obj.offsetTop;
	  		if(isIE)
			{
				newPos+=obj.clientTop;
			}
	  	}
	  } 
	  return newPos;
}

function getLeftPos(obj)
{	  
	  var newPos = obj.offsetLeft;
	  while((obj = obj.offsetParent) != null)
	  {
	  	if(obj.tagName!='HTML')
		{
	  		newPos += obj.offsetLeft;
	  		if(isIE)
			{
				newPos+=obj.clientLeft;
			}
	  	}
	  }
	  return newPos;
}

function makeRequestR(parameters, svalue) {
		http_requestT.onreadystatechange = GetResponseR;
		http_requestT.open(requestMethod, defUrl + parameters, true);
			
		data = '<?xml version="1.0" encoding="utf-8" ?>';
		data +='<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>';
		data += svalue;
		data += '</text></spellrequest>';
		
		http_requestT.send(data);
}

function GetResponseR(){
	if (http_requestT.readyState == 4) 
	{
		  if (http_requestT.status == 200) {
			http_responseT = http_requestT.responseText;
			
			loader = new GoogSpellingCorrectionLoader(http_responseT);
			loader.Load();
			loader.Parse();
			
			DisplaySuggestions(loader.getCSuggestions());
			
			loader = null;
			
			////////////////loaderDiv.style.display = 'none';
			///////////////correctionsContainer.style.display = 'none';
			///////////////Effect.Appear('correctionsContainer');
			
			CreateRequest();

		  }
		  else 
		  {
			//alert('There was a problem with the request'+http_requestT.status+' '+http_requestT.responseText);
			////////////////////////loaderDiv.style.display = 'none';
		  }
	 }
}	

function DisplaySuggestions(contentArray)
{
//alert('1');
/**/
var iw2=getCookie('buzzziw'); //alert(iw2);
if ((iw2!=null) && (iw2!='')) {
iw3=iw2.split("|");
for (var ijj=0;ijj<iw3.length;ijj++) {
  var inn=false;
  for (var kk=0;kk<iw.length;kk++) {
    if (iw[kk]==iw3[ijj]) inn=true;
  }
  if (!inn) iw[iwc]=iw3[ijj]; iwc++;
}
}
/**/

WYSIWYG.updateTextArea('text');

//alert('2');
		  correctionsBody.innerHTML = '';
		  if(contentArray.length == 0)
		  {
		  		correctionsBody.innerHTML = '<span class=\"noerrortext\">No obvious errors</span>';
		  }
		  else
		  {
//alert('3 '+contentArray.length);
			  for(i=contentArray.length-1; i>=0; i--)
			  {				  
			  	  var googCorrection = contentArray[i];
				  
				  var soffset = googCorrection.getOffset();
				  var slength = googCorrection.getLength();
				  
				  var spanSummaryLine = document.createElement('span');
				  spanSummaryLine.setAttribute('id', 'summaryline_' + String(i));
				  
				  var spanSuggestionCollection = document.createElement('span');
				  spanSuggestionCollection.setAttribute('id', 'spancollection_' + String(i));
				  spanSuggestionCollection.setAttribute('class', 'description');
				  
//var th = document.createElement('table');
//correctionsBody.appendChild(th);

				  var suggestionArray = googCorrection.getSuggestions();
var ss='';
try {ss=document.getElementById('text').value;} catch (err44) {}
try {ss=document.getElementById('comment').value;} catch (err44) {}
try {ss=document.getElementById('comments').value;} catch (err44) {}

var incorrectWord = ss.substring(soffset, parseInt(slength) + parseInt(soffset));

var cc=0; var bb=0;
for (cc=0;cc<iw.length;cc++) {
  iwd = iw[cc].replace("\'", "'");
  if (iwd===incorrectWord) bb=1;
}
if (bb==0) {

//ss=ss.replace(/(<([^>]+)>)/ig,"");


//var ss=document.getElementById('text').value;
//ss=ss.replace(/(<([^>]+)>)/ig,"");
var slen=ss.length;
//alert(slen);

var off=parseInt(soffset);
var len=parseInt(slength);

var s1b=ss.substr(0,off+len);
var s2b=ss.substr(off+len,slen-off-len);
ss=s1b+'</SPAN>'+s2b;

slen=ss.length;
var s1=ss.substr(0,off);
var s2=ss.substr(off,slen-off);
///WYSIWYG.uwe(s1+'<span name="red" style="color:red">'+s2);
ss=s1+'<span name="red" style="color:red">'+s2;

WYSIWYG.uwe(ss);

try {WYSIWYG.updateTextArea('text');} catch (err66) {}
try {WYSIWYG.updateTextArea('comment');} catch (err66) {}
try {WYSIWYG.updateTextArea('comments');} catch (err66) {}

				 // var incorrectWord = txtObject.value.substring(soffset, parseInt(slength) + parseInt(soffset));
				 // var incorrectWord = ss.substring(soffset, parseInt(slength) + parseInt(soffset));
				  
//WYSIWYG.blu(soffset,soffset+slength);
//WYSIWYG.insertHTML('<span style="color:red">###</span>');

				  for(j=0; j<suggestionArray.length;j++)
				  {
						var suggestionSpan = document.createElement('span'); 
						var suggestion = suggestionArray[j];
						
						var re = /'/g;
						var suggestionRep = suggestion.replace(re, "\\'");
						var incorrectWordRep = incorrectWord.replace(re, "\\'");
						
						suggestionSpan.innerHTML = "<a class = \"correction\" href=\"javascript:void(0);\" onclick=\"ApplyCorrection(" + "'" + suggestionRep + "', '" + incorrectWordRep + "', 'summaryline_" + String(i) + "'" + ")\">" + suggestion + "</a>&nbsp;&nbsp;";						
						//spanSuggestionCollection.insertBefore(suggestionSpan,spanSuggestionCollection.firstChild);
spanSuggestionCollection.appendChild(suggestionSpan);
				  }

	
var inw = incorrectWord.replace(re, "\\'");

				  spanSummaryLine.innerHTML =  '<span style="float:left;width:80px;" class=\"correctiontext\">' + incorrectWord + "&nbsp;&nbsp;&nbsp;&nbsp;</span>" + spanSuggestionCollection.innerHTML + "<span style=\"font-weight: bold; font-size: 11pt;\">&nbsp;</span>&nbsp;&nbsp;<a class = \"ignore\" href=\"javascript:void(0);\" onclick=\"ignoreC('" + inw + "')\">ignore</a>" + "<br />";
				  correctionsBody.insertBefore(spanSummaryLine,correctionsBody.firstChild);
}
			   }
		   } 
}

function ApplyCorrection(chosenSuggestion, incorrectWord, summaryLineRef)
{
WYSIWYG.updateTextArea('text');
var ss='';
try {ss=document.getElementById('text').value;} catch (err72) {}
try {ss=document.getElementById('comment').value;} catch (err72) {}
try {ss=document.getElementById('comments').value;} catch (err72) {}

//ss=ss.replace(/(<([^>]+)>)/ig,"");
		  var currentTextFieldVal = ss; //txtObject.value;
		  incorrectWord = incorrectWord.replace("\'", "'");
		 /// txtObject.value = currentTextFieldVal.replace(incorrectWord, chosenSuggestion);
WYSIWYG.uwe(currentTextFieldVal.replace(incorrectWord, chosenSuggestion));
		 /// IgnoreCorrection(summaryLineRef);
  CheckTimer2();
checkIt();
}

function ignoreC(s) {
  iw[iwc]=s; iwc++; CheckTimer2(); checkIt();
  var exp = new Date(); //set new date object 
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 2000)); //set it 30 days ahead 
var iw2='';
for (var ij=0;ij<iw.length;ij++) {
  iw2=iw2+iw[ij]+'|';
}
  setCookie("buzzziw",iw2,0); //exp);
}

function IgnoreCorrection(summaryLineRef)
{
	  correctionsBody.removeChild(document.getElementById(summaryLineRef));
	  
	  var nodeCount = getCorrectionCount();
	  
	  if(nodeCount == 0)
	  {
	  	  ////////////////////correctionsContainer.style.display = 'none';
	  }
 CheckTimer2(); checkIt();
}

function getCorrectionCount()
{
	return document.getElementById('correctionsBody').childNodes.length;
}


if(window.addEventListener)
	window.addEventListener('load', InitializeSpellify, false);
else if(window.attachEvent)
	window.attachEvent('onload', InitializeSpellify);