var DOUBLE_CLICK_INTERVAL = 350; // milliseconds
var SELECTION_HACK_DELAY = 150; // milliseconds
var checkingDoubleClick = false;

function clickHandler(ev) {
  if (checkingDoubleClick) {
    checkingDoubleClick = false;
    triggerPopupDict();
  }
  else {
    checkingDoubleClick = true;
    setTimeout("clickHandlerTimeout()", DOUBLE_CLICK_INTERVAL);
  }
  return true;
}

function clickHandlerTimeout() {
  checkingDoubleClick = false;
}

function doubleClickHandler(ev) {
  if (checkingDoubleClick) {
    // browser supports double click events
    checkingDoubleClick = false;
    triggerPopupDict();
  }
  return true;
}

function triggerPopupDict() {
  if(mselect() != "") {
    // on most browsers, just open the dictionary right away:
    PopupDict();
  }
  else {
    // on certain browsers, wait until the selection is handled: 
    setTimeout("PopupDict()", SELECTION_HACK_DELAY);
  }
}

if ((window.captureEvents) && (parseInt(navigator.appVersion) < 5)) {
  // running an old version of Netscape:
  window.captureEvents(Event.MOUSEUP);
  window.onmouseup = clickHandler;
}
else {
  document.onclick = clickHandler;
  document.ondblclick = doubleClickHandler;
}

function PopupDict()
{
  var word = mselect(); 
  if (!word || !word.length) return; 

  dslpopupurl = "./sndadictp4frames.php?searchtype=full&dtext=all&sset=1&fset=20&printset=20&dregion=entry&query=" + word;
  textwindow = window.open(dslpopupurl, "textwindow");
  textwindow.focus();
}

function mselect () 
{
  var str = "";
  if (self.document.getSelection) {
    str = self.document.getSelection(); 
  }
  else if (self.document.selection && self.document.selection.createRange) {
      var range = self.document.selection.createRange(); 
      if (range) str = range.text; 
  } 
  if (!str) {
    return "";
  }

  /* Truncate string at 30 characters. */ 
  max = 30; 
  if (str.length > max)
  {
    str = str.substr (0, max);
    var iEnd = str.length - 1;
    while (iEnd > 0)
    {
      ch = str.charAt (iEnd);
      /* Stop when the character you just removed was a blank */ 
      if (ch == ' ') {break;}
      iEnd--;
    }
    str = str.substring (0, iEnd); 
  }
  /* Remove tabs, newlines. */ 
  /* (Don't use /[nt]/, to avoid Netscape bomb) */
  /* Remove ^M's which Netscape adds between lines */
  re=/\cM/g;
  str = str.replace (re,' ');
  re=/\n/g;
  str = str.replace (re,'');
  re=/\t/g;
  str = str.replace (re,'');

  /* Remove double spaces */ 
  re=/\s\s/g;
  len=str.length;
  oldlen=len+1;
  while (len < oldlen)
  {
    str = str.replace (re,' ');
    oldlen = len;
    len = str.length;
  }
  return str;
}

function Tweak(word, re) {
  re.exec(word);
  word = word.replace(re, RegExp.$1);
  return word;
}

