﻿//
// SharpSpell v3.0 - Copyright (c) 2006 Tachyon Labs (tachyon-labs.com)
//
// Real-time spell-as-you-type for the web spell checker.
// For more information, visit http://www.tachyon-labs.com/sharpspell/
//

var SharpSpellDialog = { };

var SharpSpellDialog_parentWindow;
var SharpSpellDialog_parentText;
var SharpSpellDialog_spellDiv;
var SharpSpellDialog_currentElement;
var SharpSpellDialog_lastElement;
var SharpSpellDialog_responseDiv;
var SharpSpellDialog_currentTextArea;
var SharpSpellDialog_changes = [ ];
var SharpSpellDialog_objectsToCheck;
var SharpSpellDialog_currentArrayIndex = 0;                                          

SharpSpellDialog.getNextTextArea = function () 
{
    var lastTA = SharpSpellDialog_currentTextArea;
    SharpSpellDialog_currentTextArea = SharpSpellDialog_objectsToCheck[SharpSpellDialog_currentArrayIndex];
    SharpSpellDialog_currentArrayIndex++;
    if (!SharpSpellDialog_currentTextArea) {
        SharpSpellDialog_currentTextArea = lastTA;
        return false;
    } else {
        return true;
    }
};

SharpSpellDialog.Init = function()
{
    top.resizeTo(document.getElementById("MainTable").clientWidth, document.getElementById("MainTable").clientHeight + 30);
    
    SharpSpell.addEvent(document.getElementById("btnCancel"), "click", 
                        function() 
                        { 
                            window.close(); 
                        }
             );
    SharpSpell.addEvent(document.getElementById("lstSuggestions"), "change", 
                        function() 
                        { 
                            document.getElementById('txtReplaceWord').value = document.getElementById('lstSuggestions').value; 
                        }
            );
    SharpSpell.addEvent(document.getElementById("btnOk"), "click", 
                        function(e) 
                        { 
                            SharpSpellDialog.appendChange();
                            SharpSpellDialog.commitChanges();

			                window.close();
			                
			                // prevent the event from bubbling
			                e = (e) ? e : window.event;
			                e.cancelBubble = true;
                            if (e.preventDefault) { e.preventDefault(); }
                            return false;
                        }
            );
            
           
    SharpSpell.addEvent(document.getElementById("btnReplace"), "click", 
                        function(e) 
                        { 
                            if (SharpSpellDialog_currentElement) {
                                SharpSpellDialog_currentElement.className = "SharpSpell_Misspelling_Corrected";
			                    SharpSpellDialog_currentElement.firstChild.nodeValue = document.getElementById('txtReplaceWord').value;
			                    SharpSpellDialog.SelectNextWord(SharpSpellDialog_currentElement);
			                }
			                
			                // prevent the event from bubbling
			                e = (e) ? e : window.event;
			                e.cancelBubble = true;
                            if (e.preventDefault) { e.preventDefault(); }
                            return false;
                        }
            );

    SharpSpell.addEvent(document.getElementById("btnAddToDic"), "click", 
                        function(e) 
                        { 
                            if (SharpSpellDialog_currentElement) {
                                SharpSpell.addWordToDictionary(SharpSpellDialog_currentElement.firstChild.nodeValue);
			                    SharpSpellDialog.SelectNextWord(SharpSpellDialog_currentElement);
			                }
		                					              
			                // prevent the event from bubbling
			                e = (e) ? e : window.event;
			                e.cancelBubble = true;
                            if (e.preventDefault) { e.preventDefault(); }
                            return false;
                        }
            );


    SharpSpell.addEvent(document.getElementById("btnIgnore"), "click", 
                        function(e) 
                        { 
			                if (SharpSpellDialog_currentElement) {
			                    SharpSpellDialog.SelectNextWord(SharpSpellDialog_currentElement);
			                }
			                
			                // prevent the event from bubbling
			                e = (e) ? e : window.event;
			                e.cancelBubble = true;
                            if (e.preventDefault) { e.preventDefault(); }
                            return false;
                        }
            );		    

	if (parent.window.dialogArguments) {
		SharpSpellDialog_parentWindow = parent.window.dialogArguments;
	} else if (top.opener) {
		SharpSpellDialog_parentWindow = top.opener;
    }

    SharpSpellDialog_objectsToCheck = SharpSpellDialog_parentWindow.SharpSpellDialog_objectsToCheck;
    
    SharpSpellDialog.getNextTextArea();
    
    SharpSpellDialog_parentText = SharpSpellDialog_currentTextArea.value;
    SharpSpellDialog_spellDiv = document.getElementById("SpellDiv");
    SharpSpellDialog_responseDiv = document.createElement("div");
    
    // init the spellcheck
    SharpSpellDialog.doSpellCheck();    
};

SharpSpellDialog.SelectNextWord = function ( el )
{
    if (document.getElementById(el.nextId))
    {
        SharpSpellDialog.SelectWord (document.getElementById(el.nextId));
    }
    else
    {
        SharpSpellDialog.spellCheckComplete();
    }
};

SharpSpellDialog.RewireEvents = function () 
{
    var userdic, ignore;
    userdic = SharpSpell.getUserDictionary();
    ignore = SharpSpell.getUserIgnoreList();
    
    var myInstance = this;
    var arrElements = SharpSpell.getElementsByClassName(SharpSpellDialog_responseDiv, "a", "SharpSpell_Misspelling");
    var j = 0;
    for(var i=0; i<arrElements.length; i++){
        if (userdic.indexOf("|" + arrElements[i].innerHTML.toLowerCase() + "|") == -1 && ignore.indexOf("|" + arrElements[i].innerHTML.toLowerCase() + "|") == -1)
        {
            j++;
            var node = SharpSpellDialog.highlightWord(SharpSpellDialog_spellDiv, arrElements[i]);
            node.id = 'SharpSpell_Misspelling_' + j;
            node.nextId = 'SharpSpell_Misspelling_' + (j + 1);
		    SharpSpell.addEvent(node, "click", function (e) { SharpSpellDialog.WordSelectedEvent( (e) ? e : window.event ); return false; } );
        }
        else
        {
            arrElements[i].className = "";
        }
    }
    
    if (!j)
    {
        SharpSpellDialog.spellCheckComplete();
    }
    else
    {
        // select the first misspelling by default
        SharpSpellDialog.SelectWord(document.getElementById("SharpSpell_Misspelling_1"));	        
    }
};

SharpSpellDialog.highlightWord = function (node, wordObj)
{    
    var self = this;
    var word = wordObj.innerHTML;
    var suggestions = wordObj.getAttribute("suggestions");
    var index = wordObj.getAttribute("index");
    var charPos = 0;

    for (var c = node.firstChild; c; c = c.nextSibling) {
        if (c.nodeType == 3 || (c.firstChild && c.firstChild.nodeType == 3)) 
        {
            if (c.nodeType == 3) 
            {
                node = c;
            }
            else if (c.firstChild.nodeType == 3)
            {
                node = c.firstChild;
            }
            else
            {
                continue;
            }

            if ((node.nodeValue.length>0 && charPos <= index) && (charPos + node.nodeValue.length >= index))
            {
                // word in this node
                var start = index - charPos;
                var pn, nv, docWordVal, before, after, hiword, hiwordtext;
                pn = node.parentNode;
                nv = node.nodeValue;
                before = document.createTextNode(nv.substr(0,start));
		        docWordVal = nv.substr(start,word.length);
		        if (docWordVal != word) { return; }
		        after = document.createTextNode(nv.substr(start+word.length));
		        hiwordtext = document.createTextNode(docWordVal);
		        hiword = document.createElement("a");
		        hiword.className = "SharpSpell_Misspelling";
		        hiword.setAttribute("suggestions", suggestions);
		        hiword.setAttribute("index", index);
		        hiword.appendChild(hiwordtext);

		        pn.insertBefore(before,node);
		        pn.insertBefore(hiword,node);
		        pn.insertBefore(after,node);
		        pn.removeChild(node);
		        return hiword; 
            }
        }
        charPos += SharpSpell.getTextInternal(c, false).length;
    }
};

SharpSpellDialog.spellCheckComplete = function() 
{
	SharpSpellDialog.appendChange();
    if (!SharpSpellDialog.getNextTextArea()) {
        SharpSpellDialog_changes.pop();
	    alert('Spell check complete!');
	} else {
        SharpSpellDialog_parentText = SharpSpellDialog_currentTextArea.value;
        SharpSpellDialog.doSpellCheck();
	}      	
};

SharpSpellDialog.appendChange = function() 
{
    var change = { };
    change.object = SharpSpellDialog_currentTextArea;
    change.text = SharpSpell.getTextInternal(SharpSpellDialog_spellDiv, false);
    SharpSpellDialog_changes.push(change);
};

SharpSpellDialog.commitChanges = function()
{
    var change;
    while ((change = SharpSpellDialog_changes.pop()))
    {
        change.object.value = change.text;
		if (change.object.SharpSpell_Refresh) {
            change.object.SharpSpell_Refresh();
        }
    }
};


SharpSpellDialog.doSpellCheck = function () 
{

	while (SharpSpellDialog_spellDiv.firstChild) { SharpSpellDialog_spellDiv.removeChild(SharpSpellDialog_spellDiv.firstChild); } 
    SharpSpellDialog_spellDiv.appendChild(document.createTextNode("Spell check in progress. Please wait."));
    
    var xmlhttp = SharpSpell.createXMLHTTP();
    
    xmlhttp.open( "POST" , "/sharpspell.ashx" + location.search );
    xmlhttp.onreadystatechange =
        function () 
        {   
	        if (xmlhttp.readyState == 4) {
	        
		        while (SharpSpellDialog_spellDiv.firstChild) { SharpSpellDialog_spellDiv.removeChild(SharpSpellDialog_spellDiv.firstChild); }  
                var lines = SharpSpellDialog_parentText.split("\n");
                for (var i = 0; i < lines.length; i++) 
                {
                    SharpSpellDialog_spellDiv.appendChild(document.createTextNode(lines[i].replace(" ", "\u00a0")));
                    SharpSpellDialog_spellDiv.appendChild(document.createElement("br"));
                }
		        
		        SharpSpellDialog_responseDiv.innerHTML = xmlhttp.responseText;
		        SharpSpellDialog.RewireEvents();
	        }
        };
    xmlhttp.send( SharpSpellDialog_parentText );
};

// called when a new misspelling is selected
SharpSpellDialog.WordSelectedEvent = function ( ev )
{ 
	var e;
    if (ev.target) { e = ev.target; }
    if (ev.srcElement) { e = ev.srcElement; }
    ev.cancelBubble = true;
    if (ev.preventDefault) { ev.preventDefault(); }
    
    SharpSpellDialog.SelectWord(e);
};

SharpSpellDialog.SelectWord = function( e )
{
	// save the current element
	SharpSpellDialog_lastElement = SharpSpellDialog_currentElement;
	if (SharpSpellDialog_lastElement && SharpSpellDialog_lastElement.className == "SharpSpell_Misspelling_Selected") 
	{
        SharpSpellDialog_lastElement.className = "SharpSpell_Misspelling";
    }
    else if (SharpSpellDialog_lastElement && SharpSpellDialog_lastElement.className == "SharpSpell_Misspelling_Corrected_Selected") 
    {
        SharpSpellDialog_lastElement.className = "SharpSpell_Misspelling_Corrected";
    }
    
    SharpSpellDialog_currentElement = e;
    if (SharpSpellDialog_currentElement.className == "SharpSpell_Misspelling")
        { SharpSpellDialog_currentElement.className = "SharpSpell_Misspelling_Selected"; }
    else if (SharpSpellDialog_currentElement.className == "SharpSpell_Misspelling_Corrected")
        { SharpSpellDialog_currentElement.className = "SharpSpell_Misspelling_Corrected_Selected"; }
    
    // clear the list of suggestions
    var suggList = document.getElementById('lstSuggestions');	      
    for ( var x = suggList.options.length; x >= 0; x--) {
        suggList.options[x] = null;
    }
    
    // get the list of suggestions contained in the 'suggestions' attribute of the element
    var suggestions = e.getAttribute("suggestions").split(";");
    
    // add the suggestions to the list box
    for( var i = 0; i < suggestions.length; i++ )
    {     
        suggList.options[suggList.options.length] = new Option(suggestions[i],suggestions[i]);
    }
    
    if (suggestions[0]) 
    {
        document.getElementById('txtReplaceWord').value = suggestions[0];
        suggList.options[0].selected = true;
    } else {
        document.getElementById('txtReplaceWord').value = e.innerHTML;
    }        

    SharpSpellDialog_spellDiv.scrollTop = SharpSpellDialog_currentElement.offsetTop;
    SharpSpellDialog_spellDiv.scrollLeft = SharpSpellDialog_currentElement.offsetLeft;
    
    return false;
};

SharpSpellDialog.Show = function (elements, lcid) 
{
    if (lcid == null) { lcid = 1033; }
    if (!elements || elements == "*") { elements = document.getElementsByTagName("TEXTAREA"); }
    SharpSpellDialog_objectsToCheck = elements;
    window.open(SharpSpell.SupportPath + 'dialog.htm?lcid=' + lcid,'SharpSpell', 'status=0,width=200px,height=200px,top=200px,left=200px');
    return false;
};