Jump to content

User:Endo999/dictionarylookup1.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// this javascript isolates the text word under the 
//cursor when it rests on a word for 1.5 seconds
// works in Firefox 1,2.0,3 and IE 6.0,7,8, chrome
// works in Windows Safari, and Opera
// does not work in Konqueror(that I know of, code is disabled for Konqueror)
// with the Google language javascript api this does dictionary lookup
// in several languages.
// the word isolated  is translated
// and the translation is placed back in the new window
// on IE, Firefox, chrome, and Epiphany a cursor place over
// selected text (up to 500 characters) will use
// that text

// author: endo999
// author: Paul Cheffers
// email: paul@securecottage.com
// 2008
// 
// this webpage is placed in the public domain by the author


// the default languages(the from language is redundant as Google guesses 
// the language) but SCLanguageDefaultTo is important is you are porting
// to another Wikipedia Language

// the following variables need to be set in the calling javascript routine
// this gives a gadget manager the ability to set the literals and defaults
// of the system to the languages they wish


// default from and to language
/*
var SCLanguageDefaultTo = 'en';
var SCLanguageDefaultFrom='pt-PT';
*/


// default literals for system
// must be set in calling javascript routine
/*
var SCstrSource = "Source";
var SCstrLanguage = "Language";
var SCstrGoogle = "Google";
var SCstrCloseWindow = "Close Window";
var SCstrSelectLanguage = "Select language (from | to)";
var SCstrWikipedialanguage = "Wikipedia language";
var SCstrDictionary = "Dictionary";
var SCstrWikipedia = "Wikipedia";
var SCstrPopupHelp = "GoogleTrans help?";
var SCstrTurnOffPopups = "Turn GoogleTrans off?";
var SCstrTurnOnPopups = "Turn GoogleTrans on?";
var SCstrTranslationPopups ="GoogleTrans";
var SCstrOff = " (off)";
var SCstrOn = " (on)";
var SCstrChangeOptions = "Change options for GoogleTrans";
var SCstrTranslatePage = "Google: translate page?";
var SCstrHelpUrl = 
"http://en.wikipedia.org/w/index.php?title=User:Endo999/dictionarylookuphelp.html&ctype=text/html"; 
var SCstrSingleWord = "Translation of single words";
var SCstrSelectedText = "Translation of selected text (> 500 characters)";
var SCstrKonqueror = "This feature is not supported on Konqueror";
var SCstrTextTooLarge =  "Text element too large to parse!";

var SCstrTextTooLarge =  "Text element too large to parse!";
var SCPopupBackgroundColor = "beige";

*/
// set this in main gadget file
// restrictive environments don't like wikipedia.org to set cookies with
//document.domain = "wikipedia.org"



var SCSourcestrlength = SCstrSource.length + SCstrGoogle + 2;
var SCMinLength = 22;

var SCgooglereference1 = 
//'<span onMouseover="javascript:SCdonthide=true;">' +
'<small class="SCyWindow">'+ SCstrSource +':<a href="#" ' +
'onMouseover="javascript:SCdonthide=true;" ' +
'onclick="javascript:window.open(\'';
var SCgooglereference1a =
'\')">' + SCstrGoogle + '</a></small> ';

var SCgooglereference2 = 
'<a class="SCxWindow" href="javascript:SCdonthide=false;SChidespan(\'';

var SCgooglereference3 = '\')">X</a>';




var SClanguageprompt1 = 
'<small class="SCxTranslation"><a ' + 'href="javascript:SCmakevisiblelanguagechange()" ' +
'onMouseover="javascript:SCdonthide=true;" ' +
'>';

var SClanguageprompt2 =
'</a></small>&nbsp;';


var SClabel="";
var SCtext="";


var SCtranslate="FrenchToEnglish";
var SCtranslateFrom = SCLanguageDefaultFrom;
var SCtranslateTo = SCLanguageDefaultTo;
var SCTooManyTextElements=250;

var SCdonthide = false; // for change of language
var SCwindows = 0; // number of yellow windows
var SCMaxwindows = 1; // max number of yellow windows

var SCscreenWidth = 0, SCscreenHeight = 0;
var SCwrheight=250, SCwrwidth=300;
var SCscrOfX = 0, SCscrOfY = 0;
var SCWikihtml="", SCDicthtml="";
var SCbInsertSpan=false;
var SCalttranslate="";
var SCWikipedialanguage="en.wikipedia.org";
var SCshowwrad = false;
var SCbIsIE = false;
var SCbIsKonqueror = false;
var SCbIsOpera = false;
var SCbIsMozilla = false;
var SCdebug = false;
var SCclientX=0;
var SCclientY=0;
var SCposx = 0;  // position of cursor
var SCposy = 0;
var SCPosYAdjust = 42; // if over link with title drop popup window a little
var SCpposx = -1; // previous position of cursor
var SCpposy = -1;
var SCsrcElement=null;
var SCbIsKonquerorEvent=false;
var SCbMouseClicked=false;
var SChInterval = null;
//var SCMaxWordLength = 50;
var SCselectedText = "";
var SCrangeCurx = 0;
var SCrangeCury = 0;
var SCrangeCurx1 = 0;
var SCrangeCury1 = 0;
var SCselectionarray = new Array();
var SCselectionstart = new Array();
var SCselectionend = new Array();
var SCselectionarrayposition = new Array();
var SCselection = new Array();
var SCMaxWordLength=495;
var SCIeRange;
var SCSelectionType;
var SCbIsWordInSelection=false;
var SCTranslationPopups=true;
var SCbIsChrome=false;
var SCShiftKey=false;

if(SCPersistantLoad("TranslationPopups") == "1")
   SCTranslationPopups = true;
else SCTranslationPopups = false;



if(navigator.appVersion.match(/MSIE/i))
{
  SCbIsIE = true;
  
}
var SCbIsSafari = false;
if(navigator.appVersion.match(/Safari/i))
{
  SCbIsSafari = true;
}
if(navigator.appVersion.match(/Chrome/i))
{
  SCbIsSafari = false;
  SCbIsChrome = true;
}

if(navigator.appVersion.match(/Konqueror/i))
{
  SCbIsKonqueror = true;
}
if(navigator.appName.match(/Opera/i))
{
  SCbIsOpera = true;
}
if(navigator.appName.match(/Netscape/i))
{
  SCbIsMozilla = true;
}


var SCnn=(document.layers)?true:false;
var SCie=(document.all)?true:false;

function SCkeyUp(e) 
{ 
var evt=(e)?e:(window.event)?window.event:null; 
if(evt)
{ 
  var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
 if (e.shiftKey==1)
    SCShiftKey = true;
 else SCShiftKey = false;
} 

function SCkeyDown(e) 
{ 
var evt=(e)?e:(window.event)?window.event:null; 
if(evt)
{ 
  var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
 if (e.shiftKey==1)
    SCShiftKey = true;
 else SCShiftKey = false;

if(key == 27 && SCdebug == false) // escape key
{
 // SCdebug = true; 
 // SCdeleteEvents();
}
else if(key == 27 && SCdebug == true)
{
//  SCdebug = false;
//  SCcreateEvents();
}
} 
 
function SCdeleteEvents()
{
document.onkeydown=null;

document.onmousedown = null;

document.body.onmousemove = null;

document.body.onmouseout = null;

}
function SCeventhook(hook,func)
{
if(document.addEventListener)
	document.addEventListener(hook, func, false);
else
	document.attachEvent("on" + hook, func);

}
function SCcreateEvents()
{
SCeventhook("keyup",SCkeyUp);
SCeventhook("keydown",SCkeyDown);
SCeventhook("mousedown",SCcaptureMousedown);
SCeventhook("mousemove",SCcaptureMousemove);
SCeventhook("mouseout",SCcaptureMouseout);
}

var shiftkeyneeded = SCPersistantLoad('shiftkeyneeded');
if(shiftkeyneeded == "0")
   SCShiftKeyNeeded = false;
else SCShiftKeyNeeded = true;


var SCpersistlangFrom = SCPersistantLoad('languageFrom');
if(SCpersistlangFrom != "")
   SCtranslateFrom = SCpersistlangFrom;
var SCpersistlangTo = SCPersistantLoad('languageTo');
if(SCpersistlangTo != "")
   SCtranslateTo = SCpersistlangTo;
   
var SCwikilang = SCPersistantLoad('Wikipedialanguage');
if(SCwikilang != "")
   SCWikipedialanguage = SCwikilang;
else SCPersistantSave('Wikipedialanguage',SCWikipedialanguage);

SChInterval = setInterval("SCinterval()",1000);


var SCbIsOutsideClientArea = false;

function SCcaptureMouseout(evt)
{
    SCbIsOutsideClientArea = true;
    SCbMouseClicked = false;
}

var SClastposx=0;
var SClastposy=0;
var SCbInSCInterval = false;

function SCinterval()
{

 if(SCbIsKonqueror)
   return; // current dont work on Konqueror

 try {
 if(SCbInSCInterval)
    return;
 SCbInSCInterval = true;
    

 if(SCbIsMozilla)
 {
   if(SCsrcElement && 
      SCsrcElement.toString().match(/HTMLHtmlElement/i))
     SCbIsOutsideClientArea = true;

 }

 if(SCbIsKonqueror||SCbIsOpera)
 {
   if(SCsrcElement && 
      SCsrcElement.toString().match(/HTMLBodyElement/i))
     SCbIsOutsideClientArea = true;
   else SCbIsOutsideClientArea = false;
 }
 else
 if(SCbIsIE)
 {
    SCgetScrollXY();
    SCScreenSize();
    if(SCposx > SCscreenWidth+SCscrOfX-4 ||
       SCposy > SCscreenHeight+SCscrOfY-4)
       SCbIsOutsideClientArea = true;

 }
 var mes = document.getElementById("SCmessage");
  if(mes && SCsrcElement)
    mes.innerHTML = bIsOutsideClientArea + ":" +
     SCbMouseClicked + ":" +
     SCposx+","+SCposy+"::"+SCsrcElement.toString();


var posx = SCpposx - SCposx;
if(posx < 0) posx = - posx;
var posy = SCpposy - SCposy;
if(posy < 0) posy = - posy;


if(!SCbMouseClicked && posx < 4 &&
   posy < 4 
 && !document.getElementById(SCcurrentLink))
{
    if(SCsrcElement &&
       !(SClastposx == SCposx
        && SClastposy == SCposy)
        && !SCbIsOutsideClientArea
      )
    {
     SCFindElementUnderMouseOver(SCsrcElement);
     if(!SCShiftKeyNeeded)
     {
       SClastposx = SCposx;
       SClastposy = SCposy;
     }
     
    }
}
else if(document.getElementById(SCcurrentLink)
      &&
       (posx > 4 || posy > 4)
      && !SCbIsOutsideClientArea
       )

     SChidespan(SCcurrentLink);


  if(!SCdonthide && !SCbMouseClicked)
  {
    SCpposx = SCposx;
    SCpposy = SCposy;
  }
  SCbInSCInterval = false;
  } catch(e) {SCbInSCInterval = false; }
}


function SCcaptureMousemove(evt)
{
   SCbIsOutsideClientArea = false;

   SCFindPositionOfMouseClick(evt);
   var posx = SCposx - SCpposx;
   var posy = SCposy - SCpposy;
   if(posx < 0) posx = - posx;
   if(posy < 0) posy = - posy;
  
   if(!(posx < 4 && posy < 4))
     SCbMouseClicked = false;
}

// capture right mouse click

function SCcaptureMousedown(evt)
{
var mouseClick;


if(evt) mouseClick = evt.which;
else mouseClick = window.event.button;

if(/*mouseClick == 1 &&*/ SCbIsOutsideClientArea==false)
{
  SCbMouseClicked = true;
}

}
//http://www.quirksmode.org/js/events_properties.html
function SCFindPositionOfMouseClick(e) {
	SCposx = 0;
	SCposy = 0;
        
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
                
                
		SCposx = e.pageX;
		SCposy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
             if(1==1)
             {
        
        
                SCclientX=e.clientX;
                SCclientY=e.clientY;

		SCposx = e.clientX +  document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		SCposy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
              }
              else
              {
                SCposx = window.event.x+document.body.scrollLeft;
                SCposy = window.event.y+document.body.scrollTop;
              }      
	}
	// SCposx and SCposy contain the mouse position relative to the document
       

	if (e.target) 
        {
         SCsrcElement = e.target;
        }
	else if (e.srcElement) 
        {
         SCsrcElement = e.srcElement;
        }

}


// find the element under the mouse click
// see http://www.quirksmode.org/js/events_properties.html
function SCFindElementUnderMouseOver(targ) {

        if(!targ)
          return;
        if(!SCTranslationPopups)
          return;
        if(SCShiftKeyNeeded && SCShiftKey == false)
          return;
        

	if (targ.nodeType == 3) // defeat Safari bug
        {
		targ = targ.parentNode;
        }
 
        if(targ.nodeName == "TEXTAREA" ||
           targ.nodeName == "INPUT")
             return; // if input area just return
        
         // only scan through text elements
         var SelectionNode=null;
         var SelectionOffset=null;
         var SelectionAnchorNode = null;
         var SelectionAnchorOffset=null;
         var children = targ.childNodes;
         var ntextchildren = 0;

         for(i=0;i<children.length;i++)
         {
   		if(children.item(i).nodeType == 3)
                     ntextchildren++;
         }
         // if there are too many text elements to parse just return
         
         if(ntextchildren > SCTooManyTextElements)
         {
             window.status = SCstrTextTooLarge;
             return;
         }
         
         if(!(SCbIsIE||SCbIsOpera) && window.getSelection)
         {
         
	 var userSelection = window.getSelection();
         SCselectedText = userSelection.toString();
         SelectionNode = userSelection.focusNode;
         SelectionOffset = userSelection.focusOffset;
         SelectionAnchorNode = userSelection.anchorNode;
         SelectionAnchorOffset = userSelection.anchorOffset;

         for(i=0;i<children.length;i++)
         {
           /*
           if(userSelection.containsNode(children[i],false))
            SCselection[i] = true;
           else
           */
           
           if(userSelection.containsNode(children[i],true))
           {
              SCselectionarray[i] = new Array();
              SCselectionstart[i] = -1;
              SCselectionend[i] = -1;
              SCAreWordsInSelection(userSelection,SCselectionarray[i],
              children[i],i)
              SCselection[i] = false;
           }
           else 
           {
              SCselectionarray[i] = new Array();
              SCselection[i] = false;
              SCselectionstart[i] = -1;
              SCselectionend[i] = -1;
           }
         }
         }
         else if(SCbIsIE)
         {
            SCIeRange = document.selection.createRange();
            SCIeRange1 = SCIeRange.duplicate();
            SCSelectionType = document.selection.type;
         }
         
         /*
         var userSelection="";
         if(!SCbIsIE && window.getSelection)
         {
	   userSelection = window.getSelection();
         }
         */
         for(i=0;i<children.length;i++)
         {

             if(children.item(i).nodeType == 3)
             {
                 var bBreak = false;
               
                 if(SCfindwordin(targ,children.item(i),i)==true) bBreak = true;


                 if(bBreak) break;

               
             }
       
            
         }
           if(SelectionNode && window.getSelection && window.getSelection.toString()!="")
           {
              try {
              var userSelection = window.getSelection();
              if(userSelection)
              {

                userSelection.collapse(SelectionAnchorNode,SelectionAnchorOffset);
                userSelection.extend(SelectionNode,SelectionOffset);
              }
              } catch(e) { }
             
           }
         //  else if(SCbIsIE)
         //     SCIeRange1.select();
         
        

}

// parent is tag, child must be text node
// 1) separate child text element into
//    a) SCleft span of all words left of current 
//    b) SCcurrent: span of current word
//    c) SCright: span of all words right of current word
// 2) do binarylookup-like search of SCcurrent
//    span to see if it is over the cursor position
// 


function SCfindwordin(parent,child,childindex)
{

         

         var debug = SCdebug;

         SCbIsWordInSelection = false;
                 
         var words = child.nodeValue.split(/[\s\r\n]+/);
         var delimiter = " ";
         var firstcharacter = "";
         var lastcharacter = "";

         // put a limit on the size of the text element: 4000 words
         
         if(words.length > 4000)
         {
             window.status = SCstrTextTooLarge;
             return false;
         }


  // if a selection text item then we dont have to do 
  // the search, we can proceed from here
  // if Wikipedia then dont do
  // only check here if IE
  if(typeof SCtranslateFrom != "undefined" &&
     SCtranslateFrom != "Wikipedia")
 {
  
 
  if(SCbIsIE)
  {
     SCselectedText = SCNotTooBigAndInSelection(parent,child,words);    
     if(SCselectedText != "")
     {
       SCbIsWordInSelection = true;
       SCSetInLink(SCselectedText,parent,child,mid,delimiter,words,false);
       return true;
     }
  }
  }


    

         if(child.nodeValue.substring(0,1).match(/[\s\r\n]/))
            firstcharacter = delimiter;
         if(child.nodeValue.match(/[\s\r\n]$/))
            lastcharacter = delimiter;

         // if language is Chinese, split every letter
         // not on whitespace, as above
         if(typeof SCtranslateFrom != "undefined"
            && ((SCtranslateFrom.match("zh","i") || SCtranslateFrom == "ja")||
               (SCtranslateFrom == "Wikipedia" &&
                (SCalttranslateFrom.match("zh","i")
                || SCalttranslateFrom == "ja"
                )))
              )
        {
            var tempnodeValue = child.nodeValue;
            tempnodeValue.replace(/[\s\r\n]+/," ");
            words = tempnodeValue.split("");
         //   words = child.nodeValue.split("");
            delimiter = "";
        }

         // no sense in searching
         if(words.length <= 0)
            return false;


         var html1="",html2="",currentword="";
         var i,j;

         var high = words.length;
         var mid = Math.floor(high/2);
         var low = 0;
         var oldmid = -1;
         
         var iRepetition = 0;

 
         while(1)
         {

            if(oldmid == mid)
               break; // have failed, don't repeat
            if(++iRepetition > 20)
               break; // no element is that large
            if(typeof words[mid] == "undefined")
               break; // have failed, don't repeat

            html1 = firstcharacter; // usually nil

            // create SCleft text string
            /*
            for(j=0;j<mid;j++)
            {
               html1 += words[j] + delimiter;
            }
            */
            if(mid > 0)
            {
               html1 += words.slice(0,mid).join(delimiter);
               html1 += delimiter;
            }

            // create SCright text string
            /*
            html2 = "";
            for(j=mid+1;j<words.length;j++)
            {
               html2 += words[j] + 
               ((j!=words.length-1)?
                  delimiter:"");
            }
            */
            if(mid+1 < words.length)
            {
              html2 = words.slice(mid+1,words.length).join(delimiter);
              if(html2 != "")
                 html2 += lastcharacter;
            }
           
            // SCcurrent text string
            currentword = words[mid];
            if(html2 != "")
               currentword += delimiter;

            if(html2 == "" && lastcharacter != "")
               currentword += lastcharacter;
     
            // sometimes words[mid] is nil
            // if the case just back up one and continue
           if(currentword == delimiter) // ie, space after period
            {
               if(debug)    alert("resetting currentword");
               if(mid<high)
               {
                 mid++;
                 if(oldmid == mid)
                    oldmid-=2;
               }
               else break;
               continue;
            }
          

            var left = document.createElement('SPAN');
            left.setAttribute("id","SCleft");
            
         
            var right = document.createElement('SPAN');
            right.setAttribute("id","SCright");
            
         
            var current = document.createElement('SPAN');
            current.setAttribute("id","SCcurrent");
           
            
            var str1 = document.createTextNode(html1);
            var str2 = document.createTextNode(html2);
            var str3 = document.createTextNode(currentword);
            left.appendChild(str1);
            right.appendChild(str2);
            current.appendChild(str3);



            // replace child text region with
            // left,current, and right span elements
            // TO GET CURSOR POSITIONING
            
           
            
            parent.replaceChild(right,child);
            parent.insertBefore(current,right);
            parent.insertBefore(left,current);
            

            

            var SCcurrent = document.getElementById("SCcurrent");
            var SCleft = document.getElementById("SCleft");
            var SCright = document.getElementById("SCright");

            if(debug)
           {
      // debugging code
            SCcurrent.style.backgroundColor = "yellow";
            SCleft.style.backgroundColor="red";
            SCright.style.backgroundColor="orange";
           }
            var Curx = SCfindPosX(SCcurrent);
            var Cury = SCfindPosY(SCcurrent);
            var Curx1 = Curx + SCcurrent.offsetWidth;
            var Cury1 = Cury + SCcurrent.offsetHeight;

            var Leftx = SCfindPosX(SCleft);
            var Lefty = SCfindPosY(SCleft);
            var Leftx1 = Leftx + SCleft.offsetWidth;
            var Lefty1 = Lefty + SCleft.offsetHeight;

            var Rightx = SCfindPosX(SCright);
            var Righty = SCfindPosY(SCright);
            var Rightx1 = Rightx + SCright.offsetWidth;
            var Righty1 = Righty + SCright.offsetHeight;

// special processing for IE
           
            var bInsertForIE = false;
            var bUpForIE = false;
            var bDownForIE = false;
            var bBreakForIE = false;
   
            if(SCbIsIE)
            {

               
               var sElem = "";
               sElem = SCcurrent.componentFromPoint(
                       SCclientX,SCclientY);
              
               if(sElem == "")
               {
                 bInsertForIE = true;
               }
               else
               {
                 var sElem1 = "";
                 var sElem2 = "";
                 sElem1 = SCleft.componentFromPoint(
                       SCclientX,SCclientY);
                 sElem2 = SCright.componentFromPoint(
                       SCclientX,SCclientY);
                 
                 if(sElem1 == "outside" &&
                    sElem2 == "outside")
                   bBreakForIE=true;
                 if(sElem1 == "")
                   bUpForIE = true;
                 if(sElem2 == "")
                   bDownForIE = true;
               }
 
            }

  if(debug)
{

  alert(Curx+","+Curx1+":"+Cury+","+Cury1+"::"+SCposx+","+SCposy +
      ":::" + high+","+mid+","+low);

  alert(Lefty+","+Lefty1+":"+Righty+","+Righty1+"::"+SCposx+","+SCposy +
      ":::" + high+","+mid+","+low);
  
}
            var currentHeight = SCcurrent.offsetHeight;
            var currentWidth = SCcurrent.offsetWidth;

            

            parent.removeChild(right);
            parent.removeChild(current);
            parent.replaceChild(child,left);
           // parent.replaceChild(child,span1);
           



     // if cursor below whole element then fail
            if(1==0 && SCposy > Righty1 && Righty < Righty1 &&
               Lefty1 != Righty1
              )
             {
               if(debug)alert("left break");
               break;
             }
    //  if cursor before whole element then fail
            if(1==0 &&SCposy < Lefty && Lefty < Lefty1)
            {
              if(debug)alert("right break");
               break;
            }
           
            if(bBreakForIE)
               break;
            
            oldmid = mid;

            var SCbCursorOverSelection=false;
            if(!SCbIsIE&&!SCbIsOpera)
            {
              
               if(SCselection[childindex] == true)
               {
                 SCbCursorOverSelection=true;
               
               }
               else if(SCselectionarray[childindex].length>=mid &&
                  SCselectionarray[childindex][mid] == true)
               {
                 SCbCursorOverSelection=true;
                 
               }
               
              
            }


            if((SCposx >= Curx && SCposx <= Curx1 
              && SCposy >= Cury && SCposy <= Cury1) ||
                 bInsertForIE)
            {
              
               var linkText = words[mid];

               if(!SCbIsIE && SCbCursorOverSelection && SCtranslateFrom != "Wikipedia")
               {
                   linkText = SCselectedText;
                   SCbIsWordInSelection = true;
               }
	       
               SCSetInLink(linkText,parent,child,mid,delimiter,words,true);
               
               return true;
            }
            if(bUpForIE)
            {
               high = mid;
               mid = Math.floor((low + high)/2);
            }
            else if(bDownForIE)
            {
               low = mid;
               mid = Math.floor((low + high)/2);
            }
            else
            if(Cury > SCposy) // go up in element
            {
               high = mid;
               mid = Math.floor((low + high)/2);
            }
            else if(Cury1 < SCposy) // go down in element
            {
               low = mid;
               mid = Math.floor((low + high)/2);
            }
            else if(SCposx < Curx) // go up in element
            {
               high = mid;
               mid = Math.floor((low + high)/2);
            }
            else if(SCposx > Curx1)  // go down in element
            {
               low = mid;
               mid = Math.floor((low + high)/2);
            }
      
         }
     return false;
          
}
var SCindex = 0;  // for ids of translation windows
// put the translation window near the cursor point
var SCcurrentLink = "";
var SClinkword = "";
function SCSetInLink(word,parent,child,wordindex,delimiter,words,bIsSearchDone)
{
  
  if(SCwindows >= SCMaxwindows)
     return;
  SCwindows++;

  var linkname = "SC" + (++SCindex);
  SCcurrentLink = linkname;
  SClinkword = word;

  if(word.length > SCMaxWordLength)
  {
    word = word.substring(0,SCMaxWordLength);
    word += "...";
  }
  if((SCtranslateFrom == "ja" ||
     SCtranslateFrom.match("zh","i")) &&
     !SCbIsWordInSelection
    )
  //   && SCtranslateTo != "en")
  {//ch|ja to non en language
       // translate to next punctuation mark
	var i;
	var wordlist="";
        var beginindex = (wordindex > 0)?wordindex-1:0;
        var endindex = words.length-1;
	for(i=beginindex;i<=endindex;i++)
	{
		if(words[i].match(/\s/))
		  break;
		wordlist += words[i];
	}
	word = wordlist;
       
   }

  var str1 = document.createTextNode(word);

  var a1 = document.createElement("DIV");

  a1.setAttribute("id",linkname); 
  if(!SCbIsIE)
  	a1.setAttribute("class","SCPopup");
  else a1.className = "SCPopupIE";
  if(!SCbIsIE) 
  {
    a1.setAttribute("onMousedown",'SChidespan("' + linkname + '")');
  }
  a1.setAttribute("onMouseover","SCdonthide=true;");
  a1.setAttribute("onMouseout","SCdonthide=false;");

  
  SCbInsertSpan = false;
 
  if(SCtranslateFrom != "Wikipedia")
  {
     a1.appendChild(str1);
     SCWikihtml = SCWikipediaLink(wordindex,delimiter,words).innerHTML;
     SCDicthtml = "";
     
  }
  else
  {  a1.appendChild(SCWikipediaLink(wordindex,delimiter,words));
    SCWikihtml="";
    SCDicthtml=word;
   if(!SCbIsIE) 
   {
            a1.setAttribute("onMousedown","");
            a1.firstChild.setAttribute("onMousedown","");
   }
  
  }

  
  var thebody = document.getElementsByTagName("BODY");
//  var html = document.getElementsByTagName("HTML");
   
    
      var item = document.getElementById("SCitem");
      if(item)
        item.appendChild(a1);
      
    

    if(SCtranslateFrom == "Wikipedia")
    {
       SCsetLanguageDefault("wikipedialanguageoptions",
                       "Wikipedialanguage")
    
    }
 
  // cursorposition is absolute, positioning of 
  // webpage elements may upset translation window 
  // positioning, so append this window to body.
 
  // position window
  SCPositionPopup(linkname,true);
  
  if(SCtranslateFrom != "Wikipedia")
  {
    var theword = word;
    if((SCtranslateFrom.match("zh","i")
      || SCtranslateFrom == "ja")
      && !SCbIsWordInSelection
      )
    {
      var currword = word;
      var beginindex = (wordindex > 0)?wordindex-1:0;
      var endindex = (wordindex < words.length-1)?
                      wordindex+1:wordindex;
      var numwords = endindex - beginindex;
      if(numwords == 2)
        theword += " " + words[beginindex]+currword +" "+currword + words[endindex];
      else if(numwords == 1 && beginindex == wordindex)
        theword += " " + currword + words[endindex]; 
      else if(numwords == 1 && endindex == wordindex)
        theword += " " + words[beginindex] + currword;

      beginindex = wordindex;
      // we use cedit and edict for english stuff
      if(SCtranslateTo == "en"&&1==0)
      {
	endindex = (wordindex+10 < words.length)?
			wordindex+10:words.length-1;
	var i;
	var wordlist="";
	for(i=beginindex;i<=endindex;i++)
	{
		if(words[i].match(/[\r\n\s]/))
		break;
		wordlist += words[i];
	}
	if(i-beginindex > 2)
		theword += " " + wordlist;
      }
      else 
      {//ch|ja to non en language
       // translate to next punctuation mark
	var i;
	var wordlist="";
        endindex = words.length-1;
	for(i=beginindex;i<=endindex;i++)
	{
		if(words[i].match(/\s/))
		  break;
                words[i] = words[i].replace(/\'/g,"\u0026#39;");
        	words[i] = words[i].replace(/\"/g,"\u0026quot;");
		wordlist += words[i];
	}
		theword = wordlist;
       
      }
    }
    SCasyncGet(linkname, theword);
  }
  
}

// is the current element in a link and does this link have a title?
function SCIsSrcElementInALink()
{
   if(!SCsrcElement)
      return false;
   

   if(SCsrcElement.nodeName.match(/^a$/i)
      && ((SCsrcElement.getAttribute("title") != null &&
          SCsrcElement.getAttribute("title") != "")
          ||
          typeof popupVersion != "undefined")
         )
      return true;

   var Elem = SCsrcElement;

   while(Elem.parentNode)
   {
      if(Elem.nodeName.match(/^a$/i)
      && ((Elem.getAttribute("title") != null &&
          Elem.getAttribute("title") != "")
          ||
          typeof popupVersion != "undefined")
         )
      return true;

      Elem = Elem.parentNode;
   }
   return false;
   
}

function SCPositionPopup(linkname,bAdjust)
{
  var a2 = document.getElementById(linkname);
  var thebody = document.getElementsByTagName("BODY");

  var posyadjust = 0;
  var posxadjust = 0;

  var bAdjustPosition = SCIsSrcElementInALink();

  if(bAdjustPosition && typeof popupVersion != "undefined" && bAdjust)
      posyadjust = -SCPosYAdjust;
  else if(bAdjustPosition)
      posyadjust = SCPosYAdjust;
 
  if(a2 && a2.style)
  {
    
    if(SCbIsIE)
    {
      // for ie
      // body overflow needs to be set

    //  a2.style.position = "absolute";
      a2.style.left = SCposx;
      a2.style.top = SCposy + posyadjust;

      a2.onMouseover=new Function("SCdonthide=true;");
      a2.onMouseout=new Function("SCdonthide=false;");

	// if in ie the initial span goes over the right
        // side of screen
	var doclength = SCfinddoclength(a2);
	var a2overflow = (SCposx+a2.scrollWidth+1) - doclength;
        
	if(a2overflow > 0)
	{
	  var newposx =  SCposx - a2overflow;
//	  a2.style.position="absolute";
	  a2.style.left = newposx;
	  a2.style.top=SCposy + posyadjust;
       
	}
    }
    else
    {
        // a2 element returns 0 for following function
        var doclength = SCfinddoclength(thebody[0]);
        
	var a2overflow = (SCposx+a2.scrollWidth+1) - doclength;
	if(a2overflow > 0)
	{
	  var newposx =  SCposx - a2overflow;
//	  a2.style.position="absolute";
	  a2.style.left = newposx + "px";
	  a2.style.top=(SCposy + posyadjust) + "px";
//    
	}
      else
      {
          a2.style.left = (SCposx) + "px";
          a2.style.top = (SCposy + posyadjust) + "px";
      }
     

    }
//    a2.style.display="block";
      
  }

}

// after translation window has been left clicked
// remove it
function SChidespan(id)
{
  
 
  if(SCdonthide)
    return; // so change of language can be done
  
  try
  {
  
  SCwindows--;
  if(SCwindows < 0) SCwindows = 0;
  
  var ob = document.getElementById(id);
  //alert(ob.innerHTML)
  if(SCbIsOpera && !ob)
     alert("ob not found");
  if(SCbIsOpera && 1==0)
  {
     ob = document.getElementById("SCitem");
	// delete all children
	while(ob.childNodes.length>0)
	{
	ob.removeChild(ob.childNodes[0]);
	}
  }
  else
  {
    var styl = ob.style;
    styl.display = "none";
  
  if(ob && ob.parentNode)
     ob.parentNode.removeChild(ob);
  else
     if(SCbIsOpera) alert("maybe no parentnode");
  }
  }
  catch(err)
  {
    if(SCbIsOpera)
      alert("unable to hide " + id);
  }
  
  // clear the html
  SCWikihtml = "";
  SCDicthtml = "";
  

}
function SCfinddoclength(obj)
{
        var ScrollBarOffset = 0;
        if(SCbIsIE)
        {
            ScrollBarOffset = 20;
        }

	if(SCbIsOpera)
          return window.innerWidth;
        else
          return document.body.clientWidth-ScrollBarOffset; // minus the scroll bar if IE

	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			
			obj = obj.offsetParent;
		}
        
	}
       
        return obj.offsetWidth;

}
// code from http://www.quirksmode.org/js/findpos.html
function SCfindPosX(obj)
{
	var curleft = 0;
        if(!obj)
           return 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
{
		curleft += obj.x;
}
	return curleft;
}
// code from http://www.quirksmode.org/js/findpos.html
function SCfindPosY(obj)
{
	var curtop = 0;
        if(!obj)
           return 0;
        
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
        {
		curtop += obj.y;
        }
	return curtop;
}

// place meaning within translation window
function SCInsertTranslation(translatedword)
{
	// var translatedword = SCrequest.responseText;
        
        
	 var translation = translatedword.split("|");
	// translation[0] id of window
	// translation[1] word
	// translation[2] translated word
		  
          var meaning = translation[2];
	  if(meaning == '\n')
	     meaning = "NOT FOUND!!";
          meaning = meaning.replace(/\\u0026#39;/gi,"'");
          meaning = meaning.replace(/\\u0026quot;/gi,'"');

          
          if(SCtranslateFrom == "Wikipedia" && !SCbInsertSpan)
          {
            SCDicthtml = meaning;
            return;
          }
          SCbInsertSpan = true;
          // SCbInsertSpan = false;

          var ob = document.getElementById(translation[0]);
	  if(ob)
	  {
			
		try{
                          
                     var span1 = document.createElement("SPAN");
                     var newid = "x" + translation[0];
                     span1.setAttribute("id",newid);
                          
                     span1.innerHTML = 
                             meaning;
		     if(SCbIsIE)
                     {
                         var newfunction = new Function("SCdonthide=false;");
                         span1.onmouseout = newfunction; 
                         var newfunction1 = new Function("SCdonthide=true;");
                         span1.onmouseover = newfunction1; 
                     }
                          
		     ob.replaceChild(span1,ob.firstChild);

                     var span2 = document.getElementById(newid);
 		     var bIsInLink = SCIsSrcElementInALink();
                     var pixelstring = "px";
                     if(SCbIsIE)
                         pixelstring = "";

                     // the following code handles the IE 
                     // case where the yellow window goes
                     // to the right of the body
                    if(!SCbIsSafari)
                     {
                     var doclength = SCfinddoclength(span2.parentNode);
                     var span2overflow = (SCposx+span2.scrollWidth+1) - doclength;
                  
                     if(span2overflow > 0)
                     {
                       
                       var newposx =  SCposx - span2overflow;
                       span2.parentNode.style.position="absolute";
                       span2.parentNode.style.left = newposx;
                       span2.parentNode.style.top=SCposy;
		       if(bIsInLink && typeof popupVersion == "undefined")
                          span2.parentNode.style.top = (SCposy + SCPosYAdjust) + pixelstring;
                     }
                    }
                   
                    if(bIsInLink && typeof popupVersion != "undefined")
                    {
                       span2.parentNode.style.top = (SCposy - span2.parentNode.offsetHeight) + pixelstring;
                    }

		   }
		catch(err)
		{
		  alert("unable to set innerHTML");
		}
	}
        //else alert("no id:" + translatedword);

}

// issue Google Ajax request

function SCasyncGet(id,word)
{
   var languagepath = "en|fr";
   // consult SCtranslate for language translation
   if(typeof SCtranslateFrom != "undefined"
      && typeof SCtranslateTo != "undefined"
     )
   {
       languagepath = SCtranslateFrom + "|" + 
                      SCtranslateTo;
   }
   
   var persistantlanguagepathFrom = SCPersistantLoad('languageFrom');
   var persistantlanguagepathTo = SCPersistantLoad('languageTo');

   

   if(persistantlanguagepathFrom != "" &&
      persistantlanguagepathTo != "")
        languagepath = persistantlanguagepathFrom + 
             "|" + persistantlanguagepathTo;
   if(languagepath=="Wikipedia")
        languagepath = "en|fr";

//   if(languagepath == "Wikipedia")
//   {
//   }
//   else
   {
     // google limits to 500 characters of translation
     if(word.length > SCMaxWordLength)
        word = word.substring(0,SCMaxWordLength);
     var bIsSelectedText = "NO";
     if(SCbIsWordInSelection)
         bIsSelectedText = "YES";

     SCgoogleLookup(word,id);
   }
}
function SCreplaceHtml(obj,newhtml)
{
 while(obj.childNodes.length>0)
 {
   obj.removeChild(obj.childNodes[0]);
 }
 var newspan = document.createElement("SPAN");
 newspan.innerHTML = newhtml
 obj.appendChild(newspan);
}
function SClanguageChange(obj,id)
{
 var langoptions = 
 obj.options[
     obj.selectedIndex
     ].value;
 if(id.match(/From/))
 {
   SCtranslateFrom = langoptions;
   SCPersistantSave('languageFrom',SCtranslateFrom);
 }
 else if(id.match(/To/))
 {
   SCtranslateTo = langoptions;
   SCPersistantSave('languageTo',SCtranslateTo);
 }
// SCtranslate = langoptions;

 //SCdonthide = false;
 //SChidespan(SCcurrentLink);
}
function SCwikipedialanguageChange(obj)
{
 var langoptions = 
 obj.options[
     obj.selectedIndex
     ].value;
 SCWikipedialanguage = langoptions;
 SCPersistantSave('Wikipedialanguage',SCWikipedialanguage);
 var objWiki = document.getElementById(SCcurrentLink);
 if(!objWiki)
 {
   alert("objWiki failed: " + SCcurrentLink);
   
 }
 
 var arrLinks = objWiki.getElementsByTagName("A");
 var i;
 for(i=0;i<arrLinks.length;i++)
 {
   var theonclick = arrLinks[i].getAttribute("onclick");
  
   if(!theonclick)
      continue;

   if(theonclick.toString().match(/^(.*)..\.wikipedia\.org\?(.*)$/mi))
   {
     
      var newonclick =
       RegExp.$1 +
          SCWikipedialanguage +".wikipedia.org" + '?' + RegExp.$2;
    
     
      if(SCbIsIE)
      {
         
         
         if(newonclick.match(/\{(\s*javascript:)?(.*)\}/mi) ||
            newonclick.match(/(javascript:)?(.*)/mi))
         {
           
           var newfunction = new Function("return " + RegExp.$2 + ";");
           arrLinks[i].onclick = newfunction; 
         }
      }
      else
         arrLinks[i].setAttribute("onclick",newonclick);
   }
 } 
}
function SCSettings()
{
  var linkname = "SC" + (++SCindex);
  SCcurrentLink = linkname;

  var str1 = document.createTextNode("");
  var a1 = document.createElement("DIV");
  a1.setAttribute("id",linkname); 
  if(!SCbIsIE) // firefox accepts these attributes
                    // ie does not
  {
    a1.setAttribute("onMousedown",'SChidespan("' + linkname + '")');
    a1.setAttribute("class","SCPopup");
    /*
    a1.setAttribute("style","text-decoration:none;background-color:" + SCPopupBackgroundColor + ";border: 1px solid blue;position:absolute;font-size:14pt;z-index:9999;overflow:visible;display:none;line-height:normal;");
  */
  }
  
  if(SCbIsIE) 
  {
       a1.className="SCPopupIE";
  //   a1.setAttribute("href",'javascript:SChidespan("' + linkname +  '")');
  }
  a1.setAttribute("onMouseover","SCdonthide=true;");
  a1.setAttribute("onMouseout","SCdonthide=false;");

  a1.appendChild(str1); 
   if(!SCbIsIE) 
   {
            a1.setAttribute("onMousedown","");
           // a1.firstChild.setAttribute("onMousedown","");
   }
  var thebody = document.getElementsByTagName("BODY");
//  var html = document.getElementsByTagName("HTML");
   
      var item = document.getElementById("SCitem");
      if(item)
        item.appendChild(a1);
      SCPositionPopup(linkname,false);

      SCmakevisiblelanguagechange();    
}
function SCHideSettings()
{
  SCdonthide=false;
  SCPersistantSave('TranslationPopups',(SCTranslationPopups)?"1":"0");
  var popsid = document.getElementById("ca-TransPopsId");
  if(!popsid)
      return;
  
  var anchor1 = popsid.getElementsByTagName( "a" )[0];
  if(!anchor1)
     return;

  var text1; 
  if(SCTranslationPopups)
    text1 = document.createTextNode(SCstrTranslationPopups  + SCstrOn);
  else 
    text1 = document.createTextNode(SCstrTranslationPopups + SCstrOff);
  

 // delete text from anchor in tab
 while(anchor1.childNodes.length>0)
 {
   anchor1.removeChild(anchor1.childNodes[0]);
 }
 // replace text in anchor in tab
 anchor1.appendChild(text1);
   
  SChidespan(SCcurrentLink);
}
function SCSaveShiftKeyNeeded()
{
   SCPersistantSave("shiftkeyneeded",SCShiftKeyNeeded?"1":"0");
}
var SCnewhtml = "";
function SCmakevisiblelanguagechange()
{

var obj = document.getElementById(SCcurrentLink);
if(!obj)
{
  alert("unable to get object: SCmakevisiblelanguagechange " + SCcurrentLink);
  return;
}
SCdonthide = true;



var persistantlanguageFrom = SCPersistantLoad('languageFrom');
if(persistantlanguageFrom == "")
   persistantlanguageFrom = SCLanguageDefaultFrom;
var persistantlanguageTo = SCPersistantLoad('languageTo');
if(persistantlanguageTo == "")
   persistantlanguageTo = SCLanguageDefaultTo;


var newhtml = 

'<a class="SCxWindow" href="javascript:SCdonthide=false;SChidespan(\'' +
SCcurrentLink +
'\')">X</a>' +

'<small><a href="javascript:;"' +
' style="text-decoration:underline;" ' +
' onclick="javascript:SCTranslationPopups=' +
((SCTranslationPopups)?"false":"true") + 
';SCHideSettings();">' +
((SCTranslationPopups)?SCstrTurnOffPopups:
SCstrTurnOnPopups) +
'</a>' + 
'&nbsp;&nbsp;<a style="text-decoration:underline" href="javascript:;"  onclick="javascript:window.open(\''+SCstrHelpUrl+'\');">' + SCstrPopupHelp+'</a>'+
'<br><a href="javascript:;"' +
' style="text-decoration:underline;" ' +
' onclick="javascript:SCShiftKeyNeeded=' +
((SCShiftKeyNeeded)?"false":"true") +
';SCSaveShiftKeyNeeded()' +
';SCHideSettings();">' +
SCstrShiftKeyNeeded +
((SCShiftKeyNeeded)?SCstrOff:SCstrOn) +
'</a></small>' +
'<br>&nbsp;&nbsp;' + 
'<small>' + SCstrSelectLanguage + '</small><br>' +
'<SELECT name="languageoptionsFrom" id="languageoptionsFrom"' +
 'onchange="SClanguageChange(this,\'languageFrom\')"' +
' onMouseover="javascript:SCdonthide=true;" class="SChidestuff">' +
//' onMouseout="javascript:SCdonthide=false;">' +
 SCnewoptions + 
'</select>' +
'<SELECT name="languageoptionsTo" id="languageoptionsTo"' +
 'onchange="SClanguageChange(this,\'languageTo\')">' +
' onMouseover="javascript:SCdonthide=true;">' +
//' onMouseout="javascript:SCdonthide=false;">' +
 SCnewoptions + 
'</select>&nbsp;&nbsp;<br><small>' +
SCstrSingleWord + SCstrOn + '<br>' +
SCstrSelectedText + ((SCbIsIE || (SCbIsMozilla&&!(SCbIsOpera||SCbIsKonqueror )))?SCstrOn:SCstrOff) +
((SCbIsKonqueror)?SCstrKonqueror + '<br>' : '') +
'<br>'
;
 var newspan = document.createElement("DIV");


  newspan.setAttribute("onMouseover","javascript:SCdonthide=true;");
  if(SCbIsIE)
  {
     newspan.onmouseover = new Function("SCdonthide=true;");
  }
 newspan.innerHTML = newhtml;

 var i;
 
 while(obj.childNodes.length>0)
 {
   obj.removeChild(obj.childNodes[0]);
 }
 
 
// obj.replaceChild(newspan,obj.firstChild);
  obj.appendChild(newspan);

if(SCbIsSafari) 
   obj.setAttribute("onMousedown","");
 
// obj.innerHTML = newhtml;
   SCsetLanguageDefault("languageoptionsFrom","languageFrom");
   SCsetLanguageDefault("languageoptionsTo","languageTo");

  
 
}

function SCsetLanguageDefault(id,key)
{
  var i;
  var obj = document.getElementById(id);
  if(!obj)
      return;
  
  var defaultlanguage = SCPersistantLoad(key);
  if(defaultlanguage == "")
  {
     
//     if(typeof SCtranslate == "undefined")
     {
        if(key.match(/From/))
          defaultlanguage = SCLanguageDefaultFrom;
        else if(key.match(/To/))
          defaultlanguage = SCLanguageDefaultTo;
    
     }
//     else defaultlanguage = SCtranslate;
  }
 
 if(!obj || (obj && !obj.options))
  {
     alert("setLanguageDefault: bad object passed!" +
      id + ":" +
      key);
  }
  for(i=0;i<obj.options.length;i++)
  {
     obj.options[i].selected = false;
     if(obj.options[i].value.match(defaultlanguage,"i"))
     {
        obj.options[i].selected = true; 
        
     }
  }
 
  if(SCbIsSafari)
  {
     obj.setAttribute("style","text-decoration:underline");
  }
}


function SCPersistantSave(key,value)
{
/*
   if(SCbIsIE)
       SCUserDataSave(key,value);
   else if(typeof globalStorage != "undefined") 
       SCGlobalStorageSave(key,value);
   else */
   SCsetcookieVal(key,value);
}
function SCPersistantLoad(key)
{
   /*
   if(SCbIsIE)
       return SCUserDataLoad(key);
   else if(typeof globalStorage != "undefined") 
       return SCGlobalStorageLoad(key);
   else */
    return SCgetcookieVal(key);
 
}

function SCUserDataSave(key,value)
{
  SCPersistElement.setAttribute(key,value);
  SCPersistElement.save("oXMLStore");
}
function SCUserDataLoad(key)
{
  SCPersistElement.load("oXMLStore");
  var retc = SCPersistElement.getAttribute(key);
  if(retc == null)
    retc = "";
  return retc;
}
function SCGlobalStorageSave(key,value)
{
  if(globalStorage)
  {
    eval ("globalStorage['www.securecottage.com']." +
          key + "='" + value + "'");
  }
}
function SCGlobalStorageLoad(key)
{
  var retc = "";
  if(globalStorage)
  {
     retc =     eval ("globalStorage['wikipedia.org']." +
          key );
     if (retc == null)
        return "";
     
     return retc.value;
     
  }
  return "";
}
function SCsetcookieVal(cookieKey,cookieValue)
{
   var ExpireDate = new Date();
   ExpireDate.setYear(ExpireDate.getYear() + 1910);

   document.cookie =  cookieKey + '=' + cookieValue + 
          "; path=/; " 
        //  + "domain=" + document.domain + "; " 
          + "expires=" + ExpireDate.toGMTString();
  

}
function SCgetcookieVal(cookieName)
{
  
  var aCookie = "";
  var thisCookie;
  
  
  aCookie = document.cookie;
  thisCookie = aCookie.split("; ");

  var i;
  var retCookie = "";
  for(i=0;i<thisCookie.length;i++)
  {
     if(cookieName == thisCookie[i].split("=")[0].substring(0,cookieName.length))
     {
           retCookie = thisCookie[i].split("=")[1];
           break;
     }
  }
  
  return retCookie;

}
function SCwikichange(obj)
{
  var parobj = document.getElementById(SCcurrentLink);
  if(parobj && SCWikihtml != "")
  {
     SCalttranslateFrom = SCtranslateFrom;
     SCalttranslateTo = SCtranslateTo;
     SCtranslateFrom = "Wikipedia";
     SCDicthtml = parobj.innerHTML;
     if(SCbIsIE||SCbIsSafari)
        SCreplaceHtml(parobj,SCWikihtml);
     else
        parobj.innerHTML = SCWikihtml;
    SCsetLanguageDefault("wikipedialanguageoptions",
                       "Wikipedialanguage")

   if(SCbIsSafari) 
            parobj.setAttribute("onMousedown","");

  //  SChidewradd();
  }
}
function SCdictionarychange(obj)
{
  var parobj = document.getElementById(SCcurrentLink);
  
  if(parobj && SCDicthtml != "")
  {
     SCtranslateFrom = SCalttranslateFrom;
     SCtranslateTo = SCalttranslateTo;
     SCtranslateFrom = SCPersistantLoad('languageFrom');
     SCtranslateTo = SCPersistantLoad('languageTo');

     if(SCtranslateFrom == "")
         SCtranslateFrom = SCLanguageDefaultFrom;
     if(SCtranslateTo == "")
         SCtranslateTo = SCLanguageDefaultTo;

     SCWikihtml = parobj.innerHTML;
     if(SCbIsIE||SCbIsSafari)
       SCreplaceHtml(parobj,SCDicthtml);
     else
       parobj.innerHTML = SCDicthtml;

     if(parobj && !SCbIsIE)
     {
        parobj.setAttribute("onMousedown",'SChidespan("' + SCcurrentLink + '")');
     }

     if(!SCbInsertSpan)
     {
      
       SCasyncGet(SCcurrentLink,SCDicthtml);
       SCbInsertSpan=true;
      
     }
    
  }
}

function SCWikipediaLink(wordindex,delimiter,words)
{
  var i,j;
  
  var newhtml = 
'<span ' +
' onMouseover="javascript:SCdonthide=true;"' +
' onMouseout="javascript:SCdonthide=false;">' +
'<a href="javascript:SCmakevisiblelanguagechange()"' +
' style="text-decoration:underline"' +
' onMouseover="javascript:SCdonthide=true;"' +
'>' +
'Wikipedia</a>';

  newhtml +=
  '&nbsp;&nbsp;<a href="javascript:SCdictionarychange(this)"' +
' style="text-decoration:underline"' +
' onMouseover="javascript:SCdonthide=true;"' +
'>' +
'Dictionary?</a>';
  newhtml += 
'<br><small>Wikipedia language</small><br>' +
'<SELECT name="Wikipedialanguageoptions" id="wikipedialanguageoptions"' +
 'onchange="SCwikipedialanguageChange(this)">' +
' onMouseover="javascript:SCdonthide=true;"' +
'>' +
SCnewoptions +
'</select><br>';

  var numwords=4;
  if((SCtranslateFrom.match("zh","i") 
      || SCtranslateFrom == "ja"
     )
       ||
     (SCtranslateFrom == "Wikipedia" && 
      (SCalttranslateFrom.match("zh","i") ||
       SCalttranslateFrom == "ja"
        ))
     )
      numwords = 10;

  var wordindexend = wordindex + numwords;
  if(wordindexend > words.length-1)
     wordindexend = words.length-1;
  for(i=wordindex;i<=wordindexend;i++)
  {
     var linktext = "";
     for(j=wordindex;j<=i;j++)
     {
        var theword="";
        if(words[j].match(/^(.*)\'s$/))
           theword = RegExp.$1;
        else theword = words[j];
        theword = theword.replace(/\'/g,"\u0026#39;");
        theword = theword.replace(/\"/g,"\u0026quot;");
        linktext += theword;
        if(j<i)
          linktext += delimiter;
     }
     newhtml += '<br><a ' +
'onMouseover="javascript:SCdonthide=true;" ' +
 ' href="javascript:SCdonthide=false;SChidespan(\'' + SCcurrentLink + '\');" ' +
 'onclick=\'javascript:window.open(\"http://' +
SCWikipedialanguage.substring(0,2) + '.wikipedia.org?go=Go&search=' +
     encodeURIComponent(linktext) + '\")\'>' + linktext + '</a>';
     
  }
  newhtml +='<br><a href="javascript:SCdonthide=false;SChidespan(' + '\'' + SCcurrentLink +'\')"><small>Close Window</small></a></span>';

  var newspan = document.createElement("SPAN");
  newspan.innerHTML = newhtml;
  return newspan;
}
//http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function SCScreenSize() {
  
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    SCscreenWidth = window.innerWidth;
    SCscreenHeight = window.innerHeight;

  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    SCscreenWidth = document.documentElement.clientWidth;
    SCscreenHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    SCscreenWidth = document.body.clientWidth;
    SCscreenHeight = document.body.clientHeight;
  }
 
}
//http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function SCgetScrollXY() {
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    SCscrOfY = window.pageYOffset;
    SCscrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    SCscrOfY = document.body.scrollTop;
    SCscrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    SCscrOfY = document.documentElement.scrollTop;
    SCscrOfX = document.documentElement.scrollLeft;
  }

}
// is the current cursor position inside 
// a selected area.  The selected area must be 
// within one node and be on the same line
// only works for IE

function SCNotTooBigAndInSelection(theparent,thechild)
{
  if(!SCbIsIE)
      return "";
  var retWordList = SCIsInSelection(theparent,thechild);
  if(retWordList == "" || retWordList == null)
      return "";
  var retWordArray = retWordList.split(/[\r\n\s]+/);
  return retWordList;
}
// only works for IE
function SCIsInSelection(theparent,thechild)
{
var returnSelectedText="";
var debug = false;
var userSelection;


if(SCbIsIE) // IE
{
  var debug=false;
 
  if(SCSelectionType.match(/none/i)||SCSelectionType == ""||SCSelectionType == null)
    return "";
 
  if(SCSelectionType.match(/text/i))
  {
    var range = SCIeRange;
    var s = range.text;
    var collection = range.getClientRects();
    var i;
    for(i=0;i<collection.length;i++)
    {
       var leftt = collection[i].left +
           document.body.scrollLeft+
           document.documentElement.scrollLeft;
       var rightt =  collection[i].right +
           document.body.scrollLeft+
           document.documentElement.scrollLeft;
       var topp = collection[i].top +
           document.body.scrollTop+
           document.documentElement.scrollTop;
       var bottomm = collection[i].bottom +
           document.body.scrollTop+
           document.documentElement.scrollTop;

    if(SCposx >= leftt
    && SCposx <= rightt
    && SCposy >= topp
    && SCposy <= bottomm
    )
       return s;
  if(debug)
       alert(collection[i].left+"-"+collection[i].right+"_"+
             collection[i].top +"_"+collection[i].bottom+"__"+
        leftt+":"
       + ":" + rightt + ":" +
       ":"+document.body.scrollLeft +":"+
           document.documentElement.scrollLeft +
       ":"+topp+":"
        +bottomm+":"+":"
         +document.body.scrollTop+":" +
        document.documentElement.scrollTop +":"
       +SCposx+":"+SCposy);
    }


    return "";
   }

  }

}
function SCgetRangeObject(selectionObject) 
{
	 // Safari!
		var range = document.createRange();
		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
		return range;
	
}
function SCAreWordsInSelection(userSelection,SCselectionarray,child,childindex)
{
  
  var range = SCgetRangeObject(userSelection);
  var str = child.nodeValue;
  if(str == "" || str == null)
    return;
  var delimiter = /^[\r\n ]+/
  var delimiter1 = /^\S+/;
  var bNoSpace = false;
  if(SCtranslateFrom.match("zh","i") ||
     SCtranslateFrom == "ja")
  {
    bNoSpace = true;
  }
  SCselectionstart[childindex] = -1;
  SCselectionend[childindex] = -1;
  var range1 = document.createRange();

  var i,j,k;
  for(i=0,j=0;i<str.length;i++)
  {
    
    if(SCisPointInRange(range,range1,child,i))
    {
       if(SCselectionstart[childindex] == -1)
         SCselectionstart[childindex] = i;
       SCselectionend[childindex] = i;
    }
    
    if(str.substring(i).match(delimiter))
      continue;
    else
    { 
      if(SCisPointInRange(range,range1,child,i))
      {
        SCselectionarray[j] = true;
      }
      else SCselectionarray[j] = false;
      j++;
    }
    k=i;
    for(k=i;!bNoSpace && k<str.length;k++)
    {
      if(SCisPointInRange(range,range1,child,k))
        SCselectionend[childindex] = k;
      if(!str.substring(k).match(delimiter1))
        break;
    }
    i=k;
    
      
  }
}
function SCOldAreWordsInSelection(userSelection,SCselectionarray,child,childindex)
{
  var range = SCgetRangeObject(userSelection);
  var str = child.nodeValue;
  if(str == "" || str == null)
    return;
  var delimiter = /^[\r\n ]+/
  var delimiter1 = /^\S+/;
  var bNoSpace = false;
  if(SCtranslateFrom.match("zh","i") ||
     SCtranslateFrom == "ja")
  {
    bNoSpace = true;
  }
  SCselectionstart[childindex] = -1;
  SCselectionend[childindex] = -1;
  var range1 = document.createRange();

  var i,j,k;
  for(i=0,j=0;i<str.length;i++)
  {
    
    if(range.isPointInRange(child,i))
    {
       if(SCselectionstart[childindex] == -1)
         SCselectionstart[childindex] = i;
       SCselectionend[childindex] = i;
    }
    
    if(str.substring(i).match(delimiter))
      continue;
    else
    { 
      if(range.isPointInRange(child,i))
      {
        SCselectionarray[j] = true;
      }
      else SCselectionarray[j] = false;
      j++;
    }
    k=i;
    for(k=i;!bNoSpace && k<str.length-1;k++)
    {
      if(!str.substring(k+1).match(delimiter1))
        break;
    }
    i=k;
    if(range.isPointInRange(child,i))
      SCselectionend[childindex] = i;
      
  }
}

function SCisPointInRange(range,range1,child,i)
{

    if(SCbIsMozilla)
       return range.isPointInRange(child,i);

    range1.setStart(child,i);
    range1.setEnd(child,i);
    if(range.compareBoundaryPoints(Range.START_TO_START,range1) <= 0 &&
       range.compareBoundaryPoints(Range.END_TO_END,range1) >= 0)
       return true;
    else return false;
}

function SCgoogleLookup(text,label) 
{
      SClabel = label;
      SCtext = text;

      SCgoogletranslate =
       "http://translate.google.com/translate?hl=en" + "&tl=" + SCtranslateTo +"&u=" +
          encodeURIComponent(document.location.href);

       
          google.language.translate(text, "", SCtranslateTo, 
            function(result) {  
            
            if (result.translation||result.error) 
       { 
       var nbspstr = "";
       var i;
       var SClanguagestrlength = SCGetGoogleLanguage(SCtranslateTo).length + 10;
       if(SClanguagestrlength < SCSourcestrlength)
          SClanguagestrlength = SCSourcestrlength+10;
       if(result.translation)
       {
       for(i=result.translation.length;i<SClanguagestrlength;i++)
       {  
            nbspstr+="&nbsp;";
       }
       }

       var pretranslatedword = "";
       if(SClinkword.split(/\s/).length == 1)
           pretranslatedword = SClinkword + ": ";

       var insertstring = SClabel + '|' + SCtext + '|' +
      SClanguageprompt1 +  '->' +   SCGetGoogleLanguage(SCtranslateTo) + 	    SClanguageprompt2 + 
  SCgooglereference2 +
      SClabel + SCgooglereference3 + 
      '<div class="SCxText">' +
      
      ((result.translation)?
            (pretranslatedword + result.translation)
            :result.error.message) + nbspstr +'</div>' +
      '<div><br>' +
      SCgooglereference1 + 
      SCgoogletranslate +
      SCgooglereference1a
      + '</div>'
      ;

             SCInsertTranslation(insertstring); 

       }
      
          }); 
    
} 


SCScreenSize();
function SCGetGoogleLanguage(lcode)
{
  var l;
  for (l in google.language.Languages)
  {
     if(lcode == google.language.Languages[l])
       return l; 
  }
  return "undefined";
}

function SCMakeGoogleLanguages()
{
 var l;
 var lcode;
 var newoptions = "";
 for (l in google.language.Languages)
 {
   lcode = google.language.Languages[l];
   if(google.language.isTranslatable(lcode))
   {
      if(!l.match(/UNKNOWN/i)) 
        newoptions += 
      '<option value="' + lcode + '">' + l + '</option>'+"\n";
   }

 }

  
  SCnewoptions = newoptions;
}



SCScreenSize();

addOnloadHook(
    function () {
        SCcreateEvents();
    }
);
addOnloadHook(
    function () {
        var bPops = SCPersistantLoad('TranslationPopups');
        
        var title = SCstrTranslationPopups;
        if(bPops == "1" || bPops == "")
        {
           SCTranslationPopups = true;
           title += SCstrOn;
           if(bPops == "")
              SCPersistantSave('TranslationPopups','1');
        }
        else
        {
           SCTranslationPopups = false;
           title += SCstrOff;
        }
    //    SCMakeGoogleLanguages();
        addPortletLink('p-cactions',"javascript:SCSettings()", title, "ca-TransPopsId", SCstrChangeOptions, "");
    }
);