
var CURRENT_LANG = 'pl';
function getGoogleUrl() {return '/googiespell/sendReq.php?lang=' + CURRENT_LANG;} 
function getStyle(element, property)
{
    if (window.getComputedStyle)
    {
        return window.getComputedStyle(element,null).getPropertyValue(property)
    }
    else if (element.currentStyle)
    {
        return element.currentStyle[property];
    }
}

/****
 GoogieSpell v1.5
   Google spell checker for your own web-apps :)
   Copyright Amir Salihefendic 2006
 AUTHOR
   4mir Salihefendic (http://amix.dk) - amix@amix.dk
 VERSION
	 1.5 02/02/06 00:05:53
 LICENSE
    LGPL (read more in LGPL.txt)
 SITE
   http://amix.dk/googiespell
****/
var REQUEST;

var ERROR_WINDOW; //The drop down thingie
//var LANGUAGE_WINDOW; //The drop down thingie
var EDIT_LAYER; //The layer where the suggestions are presented

var ORGINAL_TEXT;
var CURRENT_RESULTS;
var CURRENT_TEXT_AREA;
var CURRENT_ELM;

var TA_SCROLL_TOP = 0; //TA = TextArea
var EL_SCROLL_TOP = 0; // EL = EditLayer

/****
  Main call function
****/
function googieSpellCheck(elm, name) {
    var textarea = document.getElementById(name);
    TA_SCROLL_TOP = textarea.scrollTop;
    if(textarea) {
        //appendIndicator(elm);
        CURRENT_TEXT_AREA = textarea;
        CURRENT_ELM = elm;
        var CURRENT_TEXT_AREA_width = getStyle(textarea, 'width');
        var CURRENT_TEXT_AREA_height = getStyle(textarea, 'height');
        createEditLayer(CURRENT_TEXT_AREA_width, CURRENT_TEXT_AREA_height);

        createErrorWindow();
        document.getElementsByTagName("body")[0].appendChild(ERROR_WINDOW);

        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } 
        catch (e) { 
        }

        createRequest();
        ORGINAL_TEXT = textarea.value;
        REQUEST.open("POST", getGoogleUrl(), true);
        REQUEST.onreadystatechange = reqDone;
        //REQUEST.send(createXMLReq(ORGINAL_TEXT));
        REQUEST.send(ORGINAL_TEXT);
    }
}


/****
  Request specific functions
****/
function createXMLReq(text) {
  return '<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1"><text>' + text + '</text></spellrequest>';
}

function createRequest() {
  try {
    REQUEST = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      REQUEST = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        REQUEST = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        REQUEST = false;
      }
    }
  }

  if (!REQUEST)
    alert("Error initializing XMLHttpRequest!");
}

function parseResult(r_text) {
  var re_split_attr_c = /\w="\d+"/g;
  var re_split_text = /\t/g;

  var matched_c = r_text.match(/<c[^>]*>[^<]*<\/c>/g);
  var results = new Array();

  var wordsToIgnore = new Array('url', 'img', 'b', 'i', 'post', 'topic', 'size', 'Arial', 'Tahoma', 'chrome.pl', 'jabber.autocom.pl', 'jabberpl.org', 'Jabber', 'Jabbera');

  for(var i=0; i < matched_c.length; i++) {
      var item = new Array();

      //Get attributes
      item['attrs'] = new Array();
      var split_c = matched_c[i].match(re_split_attr_c);
      for(var j=0; j < split_c.length; j++) {
        var c_attr = split_c[j].split(/=/);
        item['attrs'][c_attr[0]] = parseInt(c_attr[1].replace('"', ''));
      }

      var word = ORGINAL_TEXT.substring(item['attrs']['o'], item['attrs']['o']+item['attrs']['l']).toLowerCase();
      var skipThisWord = false;
      for(var k=0; k < wordsToIgnore.length; k++) {
          if (wordsToIgnore[k].toLowerCase()==word) {
              skipThisWord = true;
              continue;
          }
      }
      if(skipThisWord) continue;

      //Get suggestions
      item['suggestions'] = new Array();
      var only_text = matched_c[i].replace(/<[^>]*>/g, "");
      var split_t = only_text.split(re_split_text);
      for(var k=0; k < split_t.length; k++) {
        if(split_t[k] != "")
          item['suggestions'].push(split_t[k]);
      }
      results.push(item);
  }
  return results;
}


function reqDone() {
  if (REQUEST.readyState == 4)
    if(REQUEST.status == 200) {
      var r_text = REQUEST.responseText;
      if(r_text.match(/<c.*>/) != null) {
          var results = parseResult(r_text);
          //Before parsing be sure that errors were found
          CURRENT_RESULTS = results;
          showErrorsInIframe(results);

//          document.getElementById('googie_change_lang').style.display = "none";
          //Change link text to resume
          CURRENT_ELM.title = "Wznów edycję";
          CURRENT_ELM.onclick = resumeEditing;
          CURRENT_ELM.className = "googie_check_spelling_ok";
          EDIT_LAYER.scrollTop = EL_SCROLL_TOP;
      }
      else {
          //No spelling error found
          CURRENT_ELM.title = "Sprawdź pisownie";
          CURRENT_ELM.onclick = function(e) { googieSpellCheck(CURRENT_ELM, CURRENT_TEXT_AREA.id);};
          alert("Nie znaleziono błędów w pisowni :)!");
      }
    }
}



/****
 Error window (the drop-down window)
****/
//Set up the error window
function createErrorWindow() {
    ERROR_WINDOW = document.createElement("div");
    ERROR_WINDOW.className = "googie_window";
}

function hideErrorWindow() {
    ERROR_WINDOW.style.visibility = "hidden";
}


function showErrorWindow(elm, id) {
    var abs_pos = absolutePosition(elm);
    abs_pos.y -= EDIT_LAYER.scrollTop;
    ERROR_WINDOW.style.visibility = "visible";
    ERROR_WINDOW.style.top = (abs_pos.y+20) + "px";
    ERROR_WINDOW.style.left = (abs_pos.x) + "px";
    ERROR_WINDOW.innerHTML = "";

    //Build up the result list
    var table = document.createElement('table');
    table.className = 'googie_list';
    var list = document.createElement('tbody');

    var suggestions = CURRENT_RESULTS[id]['suggestions'];
    var offset = CURRENT_RESULTS[id]['attrs']['o'];
    var len = CURRENT_RESULTS[id]['attrs']['l'];

    if(suggestions.length == 0) {
        var row = document.createElement('tr');
        var item = document.createElement('td');
        var dummy = document.createElement('span');
        item.appendChild(document.createTextNode("Brak podpowiedzi :("));
        row.appendChild(item);
        list.appendChild(row);
    }

    for(i=0; i < suggestions.length; i++) {
        var row = document.createElement('tr');
        var item = document.createElement('td');
        var dummy = document.createElement('span');
        dummy.innerHTML = suggestions[i];
        item.appendChild(document.createTextNode(dummy.innerHTML));
        
        var correctError = function (l_elm) {
            var old_value = elm.innerHTML;
            var new_value = l_elm.innerHTML;

            elm.style.color = "green";
            elm.innerHTML = l_elm.innerHTML;
            hideErrorWindow();

            //Update the ORGINAL_TEXT
            var part_1 = ORGINAL_TEXT.substring(0, offset);
            var part_2 = ORGINAL_TEXT.substring(offset+len);
            ORGINAL_TEXT = part_1 + new_value + part_2;
            var add_2_offset = new_value.length - old_value.length;
            for(var j=0; j < CURRENT_RESULTS.length; j++) {
                //Don't edit the offset of the current item
                if(j != id && j > id){
                    CURRENT_RESULTS[j]['attrs']['o'] += add_2_offset;
                }
            }

            //Update to the new length
            CURRENT_RESULTS[id]['attrs']['l'] = new_value.length;
        };

        item.onclick = function(e) {correctError(getEventElm(e))};
        item.onmouseover = function(e) { getEventElm(e).className = "googie_list_onhover"; };
        item.onmouseout = function(e) { getEventElm(e).className = "googie_list_onout"; };
        row.appendChild(item);
        list.appendChild(row);
    }
    //Close button
    var close_row = document.createElement('tr');
    var close = document.createElement("td");
    close.appendChild(document.createTextNode("Zamknij"));
    close.onclick = function() { hideErrorWindow()};
    close.className = "googie_list_close";
    close_row.appendChild(close);
    list.appendChild(close_row);
    
    var insertOrt = function () {
        var old_value = elm.innerHTML;
        var new_value = '[ort]'+old_value+'[/ort]';

        elm.innerHTML = new_value;
        hideErrorWindow();

        //Update the ORGINAL_TEXT
        var part_1 = ORGINAL_TEXT.substring(0, offset);
        var part_2 = ORGINAL_TEXT.substring(offset+len);
        ORGINAL_TEXT = part_1 + new_value + part_2;
        var add_2_offset = new_value.length - old_value.length;
        for(var j=0; j < CURRENT_RESULTS.length; j++) {
            //Don't edit the offset of the current item
            if(j != id && j > id){
                CURRENT_RESULTS[j]['attrs']['o'] += add_2_offset;
            }
        }

        //Update to the new length
        CURRENT_RESULTS[id]['attrs']['l'] = new_value.length;
    };

    var prec = ORGINAL_TEXT.substring(offset-5, offset);
    if (prec.toLowerCase() != '[ort]')
    {
        var ort_row = document.createElement('tr');
        var ort = document.createElement("td");
        ort.appendChild(document.createTextNode("Ort!"));
        ort.className = "googie_list_ort";
        ort.onclick = function() { insertOrt()};
        ort_row.appendChild(ort);
        list.appendChild(ort_row);
    }

    table.appendChild(list);
    ERROR_WINDOW.appendChild(table);
}


/****
  Edit layer (the layer where the suggestions are stored)
****/
function createEditLayer(width, height) {
    EDIT_LAYER = document.createElement("div");
    EDIT_LAYER.className = "googie_edit_layer";
    EDIT_LAYER.style.width = width;
    EDIT_LAYER.style.height = height;
}


function resumeEditing(e) {
//    document.getElementById('googie_change_lang').style.display = "inline";

    EL_SCROLL_TOP = EDIT_LAYER.scrollTop;
    var elm = getEventElm(e);
    elm.innerHTML = "Sprawdź pisownie";
    elm.onclick = function(e) { googieSpellCheck(elm, CURRENT_TEXT_AREA.id);};
    hideErrorWindow();

    //Remove the EDIT_LAYER
    EDIT_LAYER.parentNode.removeChild(EDIT_LAYER);

    CURRENT_TEXT_AREA.value = ORGINAL_TEXT;
    CURRENT_TEXT_AREA.style.display = "block";
    CURRENT_ELM.className = "googie_check_spelling_link";

    CURRENT_TEXT_AREA.scrollTop = TA_SCROLL_TOP;

    elm.onmouseout = null;
}

function createErrorLink(text, id) {
    var elm = document.createElement('span');
    elm.className = "googie_link";
    elm.onclick = function () { showErrorWindow(elm, id); };
    elm.innerHTML = text;
    return elm;
}

function showErrorsInIframe(results) {
  var output = document.createElement("div");
  output.style.textAlign = "left";
  var pointer = 0;
  for(var i=0; i < results.length; i++) {
      var offset = results[i]['attrs']['o'];
      var len = results[i]['attrs']['l'];
      
      var part_1 = document.createElement('span');
      part_1.innerHTML = ORGINAL_TEXT.substring(pointer, offset).replace(/\n/g, "<BR>").replace(/ /g, "&nbsp;");
      output.appendChild(part_1);
      pointer += offset - pointer;

      output.appendChild(createErrorLink(ORGINAL_TEXT.substr(offset, len), i));
      pointer += len;
  }
  //Insert the rest of the orginal text
  var part_2 = document.createElement('span');
  part_2.innerHTML = ORGINAL_TEXT.substr(pointer, ORGINAL_TEXT.length).replace(/\n/g, "<BR>").replace(/ /, "&nbsp;");
  output.appendChild(part_2); 

  EDIT_LAYER.appendChild(output);

  //Hide text area
  CURRENT_TEXT_AREA.style.display = 'none';

  CURRENT_TEXT_AREA.parentNode.insertBefore(EDIT_LAYER, CURRENT_TEXT_AREA);
}


/****
 Misc. functions
****/
function Position(x, y) {
    this.x = x;
    this.y = y;
}	

//Get the absolute position of menu_slide
function absolutePosition(element) {
    //Create a new object that has elements y and x pos...
    var posObj = new Position(element.offsetLeft, element.offsetTop);

    //Check if the element has an offsetParent - if it has .. loop until it has not
    if(element.offsetParent) {
        var temp_pos =	absolutePosition(element.offsetParent);
        posObj.x += temp_pos.x;
        posObj.y += temp_pos.y;
    }

    return posObj;
}

function getEventElm(e)
{
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
    return targ;
}

function appendIndicator(elm) {
  var img = document.createElement('img');
  img.src = '/googiespell/indicator.gif';
  img.style.textDecoration = "none";
  elm.appendChild(img);
}
