User:Endo999/dictionarylookup11.js

// 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 // works in Windows Safari, and Opera // does not work in 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, Firsfox, and Epiphany a cursor place over // selected text (up to 500 characters) will use // that text

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

// SCtranslateFrom and SCtranslateTo, if set, will set the language translation. // the default is english to french // this can be reset by global variables at top of program

var SCDefaultLanguageTo="fr"; var SCDefaultLanguageFrom="en";

document.domain = "wikipedia.org"

var SCgooglereference1 = ' ' + ' Source: Google ' + ' Close Window  '; var SClanguageprompt1 = ' ';

var SClanguageprompt2 = ' ';

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

var SCtranslate="FrenchToEnglish"; var SCtranslateFrom = SCDefaultLanguageFrom; var SCtranslateTo = SCDefaultLanguageTo;

var SCurl1 = "www.securecottage.com"; //var SCurl1 = "192.168.1.40/cottage";

var SCurl = "http://" + SCurl1 + "/cgi-bin/translate11.cgi";

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="es.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 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;

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

var SCnewoptions = ' Arabic Bulgarian Chinese Croatian Czech Danish Dutch English Finnish French <option ' + 'value="de">German <option ' + 'value="el">Greek <option ' + 'value="hi">Hindi <option ' + 'value="it">Italian <option ' + 'value="ja">Japanese <option ' + 'value="ko">Korean <option ' + 'value="no">Norwegian <option ' + 'value="pl">Polish <option ' + 'value="pt">Portuguese <option ' +  'value="ro">Romanian <option ' + 'value="ru">Russian <option ' + 'value="es">Spanish <option ' + 'value="sv">Swedish ';

if(navigator.appVersion.match(/MSIE/i)) { SCbIsIE = true; } var SCbIsSafari = false; if(navigator.appVersion.match(/Safari/i)) { SCbIsSafari = 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 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(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("keydown",SCkeyDown); SCeventhook("mousedown",SCcaptureMousedown); SCeventhook("mousemove",SCcaptureMousemove); SCeventhook("mouseout",SCcaptureMouseout); }

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; function SCinterval { try { if(SCbIsOpera||SCbIsKonqueror) {  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)     ) {    SCFindElementUnderMouseOver(SCsrcElement); SClastposx = SCposx; SClastposy = SCposy;

} } else if(document.getElementById(SCcurrentLink)     &&       (posx > 4 || posy > 4)      && !SCbIsOutsideClientArea       )

SChidespan(SCcurrentLink);

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

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 (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; if(!(SCbIsIE||SCbIsSafari||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) {             var userSelection = window.getSelection; if(userSelection) {             userSelection.collapse(SelectionAnchorNode,SelectionAnchorOffset); userSelection.extend(SelectionNode,SelectionOffset); }          }         //  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 = "";

// 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 == "zh-CN" || SCtranslateFrom == "ja")|| (SCtranslateFrom == "Wikipedia" &&               (SCalttranslateFrom == "zh-CN" || 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; }

// create SCright text string html2 = ""; for(j=mid+1;j<words.length;j++) {              html2 += words[j] + ((j!=words.length-1)?                 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&&!SCbIsSafari&&!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 = ""; function SCSetInLink(word,parent,child,wordindex,delimiter,words,bIsSearchDone) { if(SCwindows >= SCMaxwindows) return; SCwindows++;

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

if(word.length > SCMaxWordLength) {   word = word.substring(0,SCMaxWordLength); word += "..."; } if((SCtranslateFrom == "ja" || SCtranslateFrom == "zh-CN") &&    !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("A"); a1.setAttribute("id",linkname); if(!SCbIsIE) // firefox accepts these attributes // ie does not {   a1.setAttribute("onMousedown",'SChidespan("' + linkname + '")'); a1.setAttribute("style","text-decoration:none;background-color:yellow;border: 1px solid blue;position:absolute;font-size:14pt;z-index:9999;overflow:visible;display:none;line-height:normal;"); } if(SCbIsIE) // ie needs a direct link a1.setAttribute("href",'javascript: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); if(SCtranslateFrom != "Wikipedia") {   var theword = word; if((SCtranslateFrom == "zh-CN" || 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; wordlist += words[i]; }		theword = wordlist; }   }    SCasyncGet(linkname, theword); } }

function SCPositionPopup(linkname) { var a2 = document.getElementById(linkname); var thebody = document.getElementsByTagName("BODY"); if(a2 && a2.style) {   if(SCbIsIE) {     // for ie      // body overflow needs to be set a2.style.left = SCposx; a2.style.top = SCposy; a2.style.position = "absolute"; a2.style.backgroundColor="yellow"; a2.style.border="1px solid blue"; a2.style.textDecoration="none"; a2.style.fontSize="14pt"; a2.style.zIndex="9999"; a2.style.overflow="visible"; a2.style.display="block"; a2.style.width="auto"; a2.style.lineHeight="normal"; 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; }   }    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 + "px"; //   	}      else {         a2.style.left = (SCposx) + "px"; a2.style.top = (SCposy) + "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 && 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); } }  catch(err) {  // alert("unable to hide " + id); } // clear the html SCWikihtml = ""; SCDicthtml = "";

} function SCfinddoclength(obj) {	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; ob.replaceChild(span1,ob.firstChild);

var span2 = document.getElementById(newid);

// 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; }                   }		   }		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";

googleLookup(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(/\{(.*)\}/mi) ||            newonclick.match(/(.*)/mi)) {          var newfunction = new Function("return " + RegExp.$1 + ";"); 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("A"); a1.setAttribute("id",linkname); if(!SCbIsIE) // firefox accepts these attributes // ie does not {   a1.setAttribute("onMousedown",'SChidespan("' + linkname + '")'); a1.setAttribute("style","text-decoration:none;background-color:yellow;border: 1px solid blue;position:absolute;font-size:14pt;z-index:9999;overflow:visible;display:none;line-height:normal;"); } if(SCbIsIE) // ie needs a direct link 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);

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("Translation Popups - ON"); else text1 = document.createTextNode("Translation Popups - OFF");

// 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); } var SCnewhtml = ""; function SCmakevisiblelanguagechange {

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

var newspan = document.createElement("SPAN");

var persistantlanguageFrom = SCPersistantLoad('languageFrom'); if(persistantlanguageFrom == "") persistantlanguageFrom = SCDefaultLanguageFrom; var persistantlanguageTo = SCPersistantLoad('languageTo'); if(persistantlanguageFrom == "") persistantlanguageFrom = SCDefaultLanguageTo;

var newhtml = ' <a href="javascript:;"' + ' style="text-decoration:underline;" ' + ' onclick="javascript:SCTranslationPopups=' + ((SCTranslationPopups)?"false":"true") + ';SCHideSettings;">' + ((SCTranslationPopups)?"Turn Off Popups?": "Turn On Popups?") + '</a> ' + ' ' + ' Select language(From|To) ' + '<SELECT name="languageoptionsFrom" id="languageoptionsFrom"' + 'onchange="SClanguageChange(this,\'languageFrom\')">' + ' onMouseover="javascript:SCdonthide=true;">' + //' onMouseout="javascript:SCdonthide=false;">' + SCnewoptions + ' ' + '<SELECT name="languageoptionsTo" id="languageoptionsTo"' + 'onchange="SClanguageChange(this,\'languageTo\')">' + ' onMouseover="javascript:SCdonthide=true;">' + //' onMouseout="javascript:SCdonthide=false;">' + SCnewoptions + ' ' +

' <a href="javascript:SCdonthide=false;SChidespan(' + '\'' + SCcurrentLink + '\')' + '"> Close Window </a>' 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 = SCDefaultLanguageFrom; else if(key.match(/To/)) defaultlanguage = SCDefaultLanguageTo; } //    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 == defaultlanguage) {       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 = SCDefaultLanguageFrom; if(SCtranslateTo == "") SCtranslateTo = SCDefaultLanguageTo;

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;"' + ' onMouseout="javascript:SCdonthide=false;">' + 'Wikipedia</a>';

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

var numwords=4; if((SCtranslateFrom == "zh-CN" || SCtranslateFrom == "ja" )      ||     (SCtranslateFrom == "Wikipedia" && (SCalttranslateFrom == "zh-CN" ||      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]; linktext += theword; if(j<i) linktext += delimiter; }    newhtml += ' <a ' + 'onMouseover="javascript:SCdonthide=true;" ' + 'onMouseout="javascript:SCdonthide=false;" ' + ' 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 +=' <a href="javascript:SCdonthide=false;SChidespan(' + '\'' + SCcurrentLink +'\')"> Close Window </a> ';

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 == "zh-CN" ||    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 == "zh-CN" ||    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 googleLookup(text,label) {     SClabel = label; SCtext = text; google.language.detect(text, function(result) {       if (!result.error && result.language) {           google.language.translate(text, result.language, SCtranslateTo, function(result) { if (result.translation) {       var insertstring = SClabel + '|' + SCtext + '|' + SClanguageprompt1 + SCtranslateFrom + ':' + SCtranslateTo + SClanguageprompt2 + SCgooglereference1 + SClabel + SCgooglereference2 + result.translation; SCInsertTranslation(insertstring); }         });         }        }); }

SCScreenSize;

addOnloadHook(   function  {        SCcreateEvents;    } ); addOnloadHook(   function  {        var bPops = SCPersistantLoad('TranslationPopups');        var title = "Translation Popups";        if(bPops == "1" || bPops == "")        {           SCTranslationPopups = true;           title += " - ON";           if(bPops == "")              SCPersistantSave('TranslationPopups','1');        }        else        {           SCTranslationPopups = false;           title += " - OFF";        }        addPortletLink('p-cactions',"javascript:SCSettings", title, "ca-TransPopsId", "Change Options for Translation Popups", "");    } );