// Copyright 2003-2004, Cross Language Inc., All Rights Reserved.
//
// Project: webtranser
// File:    $Id: dblclickdict.js,v 1.1 2008/05/22 07:04:15 jumoriya Exp $
// Author:  Brodie Thiesfield
// Summary: Provide dictionary lookup on the word selected by a left double click
//
// NOTES:
//  * the body tag attribute 'ondblclick' should be set to call this like:
//      <body ondblclick="onDblClickDictLookup(event)">

// target maximum number of characters to return as the selection. The actual number
// of characters may exceed this as the selection code always returns a word boundary.
var g_nMaxSelectionLen = 30; 



// ----------------------------------------------------------------------------
// onDblClickDictLookup()
//  Double click handler for the main body.
//
// Parameters:
//  e   Event   Event object for this handler
//
// Return:
//  false   Don't continue normal processing of this event
//
function onDblClickDictLookup(e) 
{
  showPopupDict(e);
  return false;
}

// ----------------------------------------------------------------------------
// showPopupDict()
//  Get the selected word and show the popup dictionary window for it.
//
// Parameters:
//  none
//
// Return:
//  true      Dictionary lookup attempted
//  false     No dictionary lookup was attempted (e.g. no word selected)
//
function showPopupDict(e)
{
	//alert("showPopupDict");
  // get the current word
  var strWord = getCurrentSelection(e); 
  if ( !strWord || strWord.length < 1 ) 
  {
    return false;
  }

  // get the appropriate EID to use for this word
  //TODO: determine the correct EID
  var strEid = g_strEid;  
  
  g_bDblClk = false;

  // NOTE:
  // Quick and dirty plural stemming has been removed as it is English specific. It 
  // is the job of the engine to stem the word if necessary when looking it up in the
  // dictionary.
  //
  // do cheap plural stemming
  //strWord = fixWord( strWord, /(le)s$/ );                 // girdles -> girdle
  //strWord = fixWord( strWord, /([aeiou][^aeiou]e)s$/ );   // estimates -> estimate
  //strWord = fixWord( strWord, /([cg]e)s$/ );              // faces -> face, gauges -> gauge
  //strWord = fixWord( strWord, /([^aeioucs])e?s$/ );       // most words are like this, e.g., dogs -> dog, fishes -> fish 
  //strWord = strWord.replace( /ies$/, 'y' );               // flies -> fly

  // show the popup
  lookupDict( strEid, strWord );
  return true;
}

// ----------------------------------------------------------------------------
// lookupDict()
//  Lookup the selected word in the dictionary
//
// Parameters:
//  a_strEid    EID to use
//  a_strWord   Word to lookup
//
// Return:
//  nothing
//
function lookupDict( a_strEid, a_strWord )
{
//  var strUrl = 'http://dic.yahoo.co.jp/bin/dsearch?p=' + urlEncode( a_strWord ) + '&stype=1&dtype=1';
//  var strUrl = 'dictlookup.php?eid=' + a_strEid + '&text=' + urlEncode( a_strWord );
//  var oPopup = window.open( strUrl, 'dblClickDict' );
//  oPopup.focus();

//  2005/01/05
	var f = window.document.ydicForm;
	f.stype.value = 1;
	f.dtype.value = 1;
	f.p.value = a_strWord;
	f.enc.value = "utf-8";
	f.target = "dic";
	f.method = "get";
	f.submit();

//  2005/01/07
	//var strUrl = 'http://rd.yahoo.co.jp/dic/redirect_from_translation/?http://dic.yahoo.co.jp/bin/dsearch?stype=1&dtype=1&enc=utf-8&p=' + urlEncode( a_strWord );
	// window.open( strUrl, 'dic' );
}

// ----------------------------------------------------------------------------
// getCurrentSelection()
//  Get the currently selected text from the document.
//
// Parameters:
//  none
//
// Return:
//  string    Selected text
//

function getCurrentSelection(e) 
{
  // get the currently selected text
  var strText = '';
  if ( ctw_is.mac && ctw_is.ie5up )
  {
    strText = '' + document.getSelection(); 
  }
  else if ( window.getSelection ) 
  {
    strText = '' + window.getSelection(); 
  } 
  else if ( document.selection && document.selection.createRange ) 
  { 
    var range = document.selection.createRange(); 
    if (range) 
    {
      // ensure that we aren't taking a selection from inside a text
      // input field. This is extremely annoying to the user.
      var el = range.parentElement();
//      var el = range.parentNode();
			
      while ( el && el.tagName != 'TEXTAREA' && el.tagName != 'INPUT' )
      {
        el = el.parentElement;
//        el = el.parentNode;
      }
      if ( !el )
      {
        strText = range.text; 
      }
    }
  }
  if ( !strText || !strText.length ) 
  {
    return '';
  }

  // trim the string and replace all internal whitespace with 
  // single spaces
  //strText = strText.replace( /^\s*(.*?)\s*$/, '$1' );
  //strText = strText.replace( /\s+/g, ' ' );
  
  // truncate the text at the maximum selection length and trim back to the last space
  // where possible, otherwise trim it forward at the next space (always return the 
  // selection at a word break)
  if ( strText.length > g_nMaxSelectionLen )
  {
    var nLastChar = strText.lastIndexOf( ' ', g_nMaxSelectionLen );
    if ( nLastChar == -1 )
    {
      nLastChar = strText.indexOf( ' ', g_nMaxSelectionLen );
    }
    if ( nLastChar != -1 )
    {
      strText = strText.substr( 0, nLastChar );
    }
  }
  
  return strText;
}

// ----------------------------------------------------------------------------
// urlEncode()
//  Replacement function for escape() to correctly encode a string using utf-8
//  URL encoding (RFC1738) in all browsers. If escape() is used, IE codes the
//  string using the unicode %uXXXX encoding instead of a utf-8 encoding which
//  isn't correctly decoded in PHP.
//
//  Source derived from: 
//      Ronen Botzer, http://www.zend.com/codex.php?id=839&single=1
//
// Parameters:
//  strText   string    Text to encode
//
// Return:
//  string    Encoded text
//
function urlEncode( a_strText ) 
{
  nLen = a_strText.length;
  strResult = new String();
  oCharOrd = new Number();
  for ( i = 0; i < nLen; i++) 
  {
    oCharOrd = a_strText.charCodeAt(i);
    if (    ( oCharOrd >= 65 && oCharOrd <= 90  ) 
         || ( oCharOrd >= 97 && oCharOrd <= 122 ) 
         || ( oCharOrd >= 48 && oCharOrd <= 57  ) 
         || ( oCharOrd == 33 ) 
         || ( oCharOrd == 36 ) 
         || ( oCharOrd == 95 ) ) 
    {
      // this is alphanumeric or $-_.+!*'(), which according to RFC1738 we don't escape
      strResult += a_strText.charAt(i);
    }
    else 
    {
      strResult += '%';
      if ( oCharOrd > 255 ) 
      {
        strResult += 'u';
      }
      strHexVal = oCharOrd.toString(16);
      if ( (strHexVal.length) % 2 == 1 ) 
      {
        strHexVal = '0' + strHexVal;
      }
      strResult += strHexVal;
    }
  }
  return strResult;
} 



// NOTE: 
// Only used by plural stemming code
function fixWord( a_strWord, a_re )
{
  a_re.exec( a_strWord );
  a_strWord = a_strWord.replace( a_re, RegExp.$1 );
  return a_strWord;
}

var g_bDblClk = false;
var g_strQuery;

// NOTE: 
// The following code was designed to allow arbitrary selections of text from the document
// and to look that up in the dictionary. We are not using this code anymore and are instead
// just relying on the standard double click mechanism in the browser.
// 
// If this code is reinserted, then the following note is relevant...
//  * browsersniff.js must be included before this script

function installEventHandlers()
{
  if ( ctw_is.nav )
  {
    // Netscape Navigator
    window.captureEvents( Event.DBLCLICK | Event.MOUSEUP | Event.KEYDOWN );
    //window.onDblClick = dblClickHandler;
		//window.document.onDblClick = dblClickHandler;
    //window.onKeyDown  = keyDownHandler;
    //window.onMouseUp  = mouseUpHandler;
    //window.document.body.ondblclick = dblClickHandler;
  }
  else if ( ctw_is.ie )
  {
    //alert( 'installEventHandlers;ie;start' );
    
    // Microsoft Internet Explorer
    //window.document.ondblclick = dblClickHandler;
    //document.onkeydown  = keyDownHandler;
    if ( ctw_is.mac && ctw_is.ie5up )
    {
      document.ondblclick = dblClickHandler;
      document.onmouseup  = mouseUpHandler;
    }
  }
}

function dblClickHandler(e)
{
  // Set global variable.
  g_bDblClk = true;
  if ( ctw_is.mac && ctw_is.ie5up )
  {
    return;
  }
  // If selection is set now, pop up the dictionary window.
  showPopupDict(e);
  
  return true;
}

function keyDownHandler(e)
{ 
  if ( !g_strQuery && document.forms.length > 0 )
  {
    g_strQuery = document.forms[0].query.value;
  }
 
  if ( (ctw_is.nav && e.which == 13) || (ctw_is.ie && event.keyCode == 13) ) 
  {
    // User hit carriage return while reading
    // the page.  Search on selected text.
    // Make sure the form value hasn't changed.  
    // If it's different, search on the form value instead.
    var strText = getCurrentSelection(); 
    if ( strText.length && document.forms.length > 0 && g_strQuery == document.forms[0].query.value )
    {
      document.forms[0].query.value = strText;
      document.forms[0].submit();
    }
    else
    {
      showPopupDict();
    }
  } 

  // Continue normal processing for this keystroke.
  return true;
} 

function mouseUpHandler(e)
{
//  alert( 'mouseUpHandler' );

  // If selection is only set here on double-click, pop up the dictionary now.
  if ( g_bDblClk ) 
    showPopupDict();
  return true;
} 

