User:Yair rand/editor.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note: You may have to bypass your browser’s cache to see the changes. In addition, after saving a sitewide CSS file such as MediaWiki:Common.css, it will take 5-10 minutes before the changes take effect, even if you clear your cache.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.


/*

Things to do:
Make box look less ugly, and stop it from randomly disappearing
Fix all the other huge problems
Make the lower buttons work
Reduce the amount of repitition in the code

eh sploot
*/
var yreditboxexpand, yreditboxexpand2, yreditboxexpand3, yreditboxexpand4, defsidebuttons=[], enableYRExtraStuff = $.cookie("YRNewStuff"), isOpera = $.client.profile().name == 'opera';
jQuery(document).ready(function(){
if(mw.config.get('wgAction')=='view'&&(mw.config.get('wgNamespaceNumber')==0||mw.config.get('wgPageName')=="Wiktionary:Sandbox")&&!/&printable=yes|&diff=|&oldid=/.test(window.location.search) && !$.cookie("DisableYREdit") && !window.DisableYREdit ){
  var alldefsideboxes=[];
  for(var ols=document.getElementsByTagName('ol'), ii=0;ii<ols.length;ii++){
    if(ols[ii].className != "references"){
      for(var lis=ols[ii].getElementsByTagName('li'), i=0;i<lis.length;i++){
        if(lis[i].parentNode == ols[ii])
          alldefsideboxes.push(makedefsidebox(lis[i]));
        }
      }
    }
  window.adddefsideboxbutton = function(button, condition, removeButton, clickFunction, defaultHidden, specificButton){
    function defboxbuttonclick(from){
      from.parentNode.parentNode.style.display="none";
      yreditboxexpand3.firstChild.src='http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-ltr.png'; 
      yreditboxexpand3.parentNode.parentNode.style.backgroundColor="";
      from.style.display='none';
      }
    function y(x){
      x.onclick = function(){
        removeButton && defboxbuttonclick(x);
        clickFunction(x.parentNode.parentNode.parentNode.parentNode.parentNode);
        }
      if(defaultHidden){
        x.style.display='none';
        }
      }
    if(specificButton){
      if(condition?condition(specificButton.parentNode.parentNode.parentNode.parentNode):true){
        y(defaultHidden?specificButton.appendChild(button()):specificButton.insertBefore(button(),specificButton.getElementsByTagName('div')[0]||null));
        }
      }
    else{
      for(var i = 0; i < alldefsideboxes.length; i++){
        if(condition?condition(alldefsideboxes[i].parentNode.parentNode.parentNode.parentNode):true){
          y(defaultHidden?alldefsideboxes[i].appendChild(button()):alldefsideboxes[i].insertBefore(button(),alldefsideboxes[i].getElementsByTagName('div')[0]||null));
          }
        }
      }
    arguments[5] || defsidebuttons.push(arguments)
    }
  adddefsideboxbutton(function(){return newNode('li', newNode('a','Edit definition',{'style':"cursor: pointer; display:block; position:relative; "}))}, null, false, editdefinition);
  adddefsideboxbutton(function(){return newNode('li',newNode('a','Add example sentence',{style:"cursor: pointer; position:relative; display:block; "}))}, null, false, setupusexadder);
  if(enableYRExtraStuff){
    adddefsideboxbutton(function(){return newNode('li',newNode('a','Edit gloss',{'style':"cursor: pointer; display:block; position:relative; "}))}, function(q){cv=q;return q.className}, true, editgloss, true);
    adddefsideboxbutton(function(){return newNode('li',newNode('a','Add gloss',{'style':"cursor: pointer; display:block; position:relative; ", 'title':'Add a short summary of the definition'}))}, function(q){return !q.className}, true, addgloss, true);
    adddefsideboxbutton(function(){return newNode('li', newNode('a','Add quotation',{'style':"cursor: pointer; display:block; position:relative; "}))}, null, false, function(q){setupquoteadder(q)}, true);
    adddefsideboxbutton(function(){return newNode('li', newNode('a','Add synonyms',{'style':"cursor: pointer; display:block; position:relative; "}))}, function(q){return q.className}, false, function(q){setupnymadder(q, "Synonyms")}, true);
    adddefsideboxbutton(function(){return newNode('li', newNode('a','Add antonyms',{'style':"cursor: pointer; display:block; position:relative; "}))}, function(q){return q.className}, false, function(q){setupnymadder(q, "Antonyms")}, true);
    adddefsideboxbutton(function(){return newNode('li', {'style':'background-color: #CCC;', 'title':'Please add a gloss before adding synonyms.'}, newNode('a','Add synonyms',{'style':"cursor: pointer; display:block; position:relative;"}))}, function(q){return !q.className}, false, function(q){setupnymadder(q, "Synonyms")}, true);
    adddefsideboxbutton(function(){return newNode('li', {'style':'background-color: #CCC;', 'title':'Please add a gloss before adding antonyms.'}, newNode('a','Add antonyms',{'style':"cursor: pointer; display:block; position:relative;"}))}, function(q){return !q.className}, false, function(q){setupnymadder(q, "Antonyms")}, true);
    }
  
  if(window.setUpBoxToBeAdded && enableYRExtraStuff)
    mw.util.addPortletLink('p-tb', 'javascript:addPOSHeader()', 'Add part of speech');

}
})

function makedefsidebox(q)
{
var sploo, temptoberemoved, temptoberemoved2, theboxarrow
function c(){
  yreditboxexpand3.lastChild.style.display="none";
  yreditboxexpand3.firstChild.src='http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-ltr.png'; 
  yreditboxexpand3.parentNode.parentNode.style.backgroundColor="";
  }
q.insertBefore(
  newNode('span',{style:'position:absolute;'},
    sploo=newNode('span',newNode('img',{'style':'position:'+(isOpera?'relative;display:block':'absolute')+';','src':'http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-ltr.png'}),{style:'position:relative; display:block; left:-40px; ', 'mouseover':function(){
      if(yreditboxexpand3!=sploo){
        yreditboxexpand3 &&  c();
        yreditboxexpand3 = sploo;
        }
      clearTimeout(yreditboxexpand4);
      sploo.lastChild.style.display="block"; sploo.firstChild.src='http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-down.png';sploo.parentNode.parentNode.style.backgroundColor="#EEEEEE";
      
      },
    'mouseout':function(){
      if(yreditboxexpand3==sploo)
        yreditboxexpand4=setTimeout(c,500);
      }
    },newNode('div',{style:'border:1px solid #C0C0C0;background-color:#FFFFFF;position:'+(isOpera?'relative':'absolute')+';left:0px;z-index:1;display:none;padding-right:20px;padding-bottom:'+ (enableYRExtraStuff?15:0) +'px;width:175px;margin-top:'+(isOpera?0:15)+'px;'}))),q.firstChild)


var thebox=newNode('ul',{style:'list-style-type:none;list-style-image:none;margin-left:15px;'})
q.firstChild.lastChild.lastChild.appendChild(thebox)

if(q.className)
{
thebox.appendChild(newNode('li',newNode('a','Link here',{href:"#"+thebox.parentNode.parentNode.parentNode.parentNode.id})))
}

if(enableYRExtraStuff){
  thebox.appendChild(theboxarrow=newNode('div',{'style':'position:absolute;left:0px;bottom:0px;border-top:1px solid #C0C0C0;width:100%',mouseover:function(){theboxarrow.style.backgroundColor="#DDD";yreditboxexpand2=theboxarrow;yreditboxexpand=setTimeout(function(){expandbox(theboxarrow)},500);},mouseout:function(){theboxarrow.style.backgroundColor="#FFF";clearTimeout(yreditboxexpand);}},newNode('img',{src:'http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-down.png','style':'display:block;margin-left:auto;margin-right:auto;'})))
  }

if(defsidebuttons.length){
  for(var i = 0; i < defsidebuttons.length; i++){
    adddefsideboxbutton(defsidebuttons[i][0],defsidebuttons[i][1],defsidebuttons[i][2],defsidebuttons[i][3],defsidebuttons[i][4],thebox)
    }
  }

return thebox;

}

function expandbox(q)
{
if(yreditboxexpand2.nextSibling.style.display=="none"){
  for(var i=yreditboxexpand2.parentNode.lastChild; i!=yreditboxexpand2; i=i.previousSibling)
    i.style.display="list-item";
  yreditboxexpand2.firstChild.src="http://upload.wikimedia.org/wikipedia/commons/c/c4/Mediawiki_Vector_skin_arrow_up.png"
  }
else{
  for(var i=yreditboxexpand2.parentNode.lastChild; i!=yreditboxexpand2; i=i.previousSibling)
    i.style.display="none";
  yreditboxexpand2.firstChild.src="http://bits.wikimedia.org/w/extensions-1.17/WikiEditor/modules/images/toolbar/arrow-down.png"
  }
}

function setupusexadder(qq)
{
var x, y;
var usexform;
var findsubdef = qq.parentNode.parentNode.nodeName.toLowerCase()=="li"?"#":""
editor=new Editor()
findlang(qq.parentNode, function(findlang_){
  var findscript=(new LangMetadata()).getScripts(findlang_), selectedscript = findscript[0] || "Latn";
  if(qq.getElementsByTagName('dl')[0]&&qq.getElementsByTagName('dl')[0].parentNode==qq)
    x=qq.getElementsByTagName('dl')[0];
  else if(qq.getElementsByTagName('ul').length>1)
    qq.insertBefore(x=newNode('dl'),qq.getElementsByTagName('ul')[1]);
  else
    qq.appendChild(x=newNode('dl'));


x.appendChild(y=newNode('dd'))

new AdderWrapper(new Editor(), {
  'createForm':function(){
    var x, i=0, y=function(){selectedscript=this.value;usexform.getElementsByTagName('dd')[0].style.display=this.value=='Latn'?'none':'block'}
    if(findscript.length > 1){
      for(x=newNode('select', {'name':'script','change':y}); i < findscript.length; i++){
        x.appendChild(newNode('option',{'value':findscript[i]}, findscript[i]))
        }
      }
    else{
      x = newNode('input', {'name':'script', 'value': findscript[0] || "Latn", 'style':"width:50px;",'change':y})
      }
    return usexform=newNode('form',{'style':'display:inline;'},newNode('input',{'size':100,'name':'examplesentence'}), newNode('span',{'style':'display:'+(findscript.length == 1?"none":"inline")+";"},'Script: ', x), newNode('input',{'type':'submit','value':'Preview'}),newNode('input',{'type':'button','value':'Cancel',click:function(){usexform.style.display='none'}}),
newNode('dl',(findlang_=="en"?{'style':'display:none;'}:''),
	newNode('dd','Transliteration: ',((findscript[0] == 'Latn' || !findscript[0])?{'style':'display:none;'}:''),newNode('input',{'size':'100px',name:'transliteration'})),
	newNode('dd','Translation: ',newNode('input',{'size':'100px',name:'translation'}))
))},
'fields':{
'examplesentence':function(txt,error){
	return util.validateNoWikisyntax('example sentence', true)(txt, error) 
	},
'transliteration':function(txt,error){
	if(findlang_!="en"&&selectedscript!='Latn'){return util.validateNoWikisyntax('transliteration', true)(txt, error)};
	return '' },
'translation':function(txt,error){
	if(findlang_!="en"){return util.validateNoWikisyntax('translation', true)(txt, error)};
	return '' },
'script':util.validateNoWikisyntax('script',true)
},
'onsubmit':function(values,render){render(

(values.script=="Latn"?"''"+values.examplesentence+"''":"{{"+values.script+"|lang="+findlang_+"|''"+values.examplesentence+"''}}\n:''"+values.transliteration+"''")+(findlang_!="en"?"\n:''"+values.translation+"''":''),function(newhtml){

var findnumberofheaders=findnumberofheaders_(qq)
var findnumberofdefs=findnumberofdefs_(qq)
var usextobeadded=newNode('span')
usextobeadded.innerHTML=newhtml.replace(/<p>|<\/p>/g,'')
editor.addEdit({
edit:function(wikitext){wikitext=wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"[\\s\\S]*?)\n(?!#"+findsubdef+":)|$"),"$1\n#"+findsubdef+":"+(values.script=="Latn"?"''"+values.examplesentence+"''":"{{"+values.script+"|lang="+findlang_+"|''"+values.examplesentence+"''}}\n#"+findsubdef+"::''"+values.transliteration+"''")+(findlang_!="en"?"\n#"+findsubdef+"::''"+values.translation+"''":'')+"\n");
ccc=wikitext;return wikitext;},
redo:function(){usexform.parentNode.appendChild(usextobeadded);usextobeadded.style.display='block';usexform.style.display="none";y.style.display='block'},
undo:function(){usexform.parentNode.removeChild(usextobeadded);usexform.style.display="inline";},
summary:"+usex: "+values.examplesentence
},usextobeadded)

})}
}, y)
usexform.firstChild.focus()
})
}


function editdefinition(qq)
{

Editor().withCurrentText(function(wikitext){
if(qq.YREditing){return}
qq.YREditing = true;
var findnumberofheaders=findnumberofheaders_(qq)
var findnumberofdefs=findnumberofdefs_(qq)
var temporarydefholder=qq.insertBefore(newNode('span',{'style':'display:none;'}),qq.childNodes[1].nodeName.toLowerCase()!="form"?qq.childNodes[1]:qq.childNodes[2])
while(qq.childNodes[3]&&qq.childNodes[3].nodeName!="DL"&&qq.childNodes[3].nodeName!="UL"&&qq.childNodes[3].nodeName!="OL"&&qq.childNodes[3].className!="HQToggle")
  temporarydefholder.appendChild(qq.childNodes[3]);
if(qq.childNodes[2]!=temporarydefholder)
  temporarydefholder.insertBefore(qq.childNodes[2],temporarydefholder.firstChild);
var defform
var olddef = wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"\\s?)"
),'').match(/^(\{\{senseid\|[^\}]*\}\})?\s?(.*)/)[2]
new AdderWrapper(new Editor(), {
'createForm':function(){return defform=newNode('form',{'style':'display:inline;'},
newNode('input',{'name':'definition','size':100,'value':olddef}),
newNode('input',{type:'submit',value:'Preview'}),
newNode('input',{type:'button',value:'Cancel',click:function(){temporarydefholder.style.display='inline';defform.style.display='none';qq.YREditing = false}})
)},
'fields':{'definition':function(txt,error){return txt||error("Please specify a definition.")}},
'onsubmit':function(values,render){
render(values.definition,function(newhtml){

editor=new Editor()
var findnumberofdefs=findnumberofdefs_(qq) // apparently this is sometimes necessary
var addedspan=newNode('span')
addedspan.innerHTML=newhtml
var updatecatscallback;
editor.addEdit({
edit:function(wikitext){
wikitext=wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"\\s?(\{\{senseid\\|[^\}]*\}\})*?)(?!{{senseid\\|).*"),"$1"+values.definition);
ccc=wikitext;
return wikitext},
redo:function(){
  defform.parentNode.insertBefore(addedspan,defform);
  defform.style.display=temporarydefholder.style.display='none';
  updatecatscallback = window.tabbedLanguages && updateCategories((defform.parentNode.parentNode.parentNode.nodeName.toLowerCase()=="li"?defform.parentNode.parentNode:defform).parentNode.parentNode.parentNode, values.definition, olddef)
  qq.YREditing = false;
  },
undo:function(){
  defform.parentNode.removeChild(addedspan);defform.style.display="inline";
  updatecatscallback && updatecatscallback();
  qq.YREditing = true;
  },
summary:"def: "+values.definition
},addedspan)


})


}
}, qq, qq.childNodes[1].nodeName.toLowerCase()!="form"?qq.childNodes[1]:qq.childNodes[2])

})

}

function findnumberofheaders_(tosearchfrom)
{
tosearchfrom=tosearchfrom.parentNode;
if(tosearchfrom.parentNode.nodeName.toLowerCase() == "li")
  tosearchfrom = tosearchfrom.parentNode.parentNode;
while(!tosearchfrom.nodeName.match(/^h\d$/i))
  tosearchfrom=tosearchfrom.previousSibling;
return Number(tosearchfrom.firstChild.getElementsByTagName('a')[0].href.match(/\d*$/))
}

function findnumberofdefs_(tosearchfrom)
{
var findnumberofdefs=0, tosearchfrom_, findnumberofsubdefs=0, findnumberofpredefs=0
// subdefinitions
if(tosearchfrom.parentNode.parentNode.nodeName.toLowerCase()=="li"){
  tosearchfrom_=tosearchfrom;
  while(tosearchfrom){
    if(tosearchfrom.nodeName.toLowerCase()=="li")
      findnumberofsubdefs+=1;
    tosearchfrom=tosearchfrom.previousSibling;
    }
  tosearchfrom=tosearchfrom_.parentNode.parentNode;
  }
// in case of any def lists before the current def list under the same header
tosearchfrom_=tosearchfrom.parentNode.previousSibling;
while(!tosearchfrom_.nodeName.match(/^h\d$/i)){
  if(tosearchfrom_.nodeName.toLowerCase()=="ol")
    findnumberofpredefs+=1;
  tosearchfrom_=tosearchfrom_.previousSibling
  }
// normal cases
while(tosearchfrom){
  if(tosearchfrom.nodeName.toLowerCase()=="li")
    findnumberofdefs++;
  tosearchfrom=tosearchfrom.previousSibling;
  }
return "([\\s\\S]*?\n#[\\s\\S]*?\n(?!#)){"+findnumberofpredefs+"}([\\s\\S]*?\n#(?![:*#])){"+findnumberofdefs+"}([\\s\\S]*?\n##(?![:*])){"+findnumberofsubdefs+"}"
}

function addgloss(qq)
{
var senseidform;
findlang(qq.parentNode,function(findlang_){
  editor=new Editor();
  new AdderWrapper(editor, {
    'createForm':function(){return senseidform=newNode('form',{'style':'display:inline; padding-right:20px;'},newNode('input',{'size':30,'name':'senseid'}),newNode('input',{'type':'submit','value':'Add'}),newNode('input',{'type':'button','value':'Cancel','click':function(){qq.removeChild(senseidform);qq.firstChild.getElementsByTagName('li')[2].style.display='list-item'}}),newNode('a', {href: '/wiki/Help:Glosses'}, 'Help?!'))},
    'fields':{'senseid': util.validateNoWikisyntax('gloss', true) },
    'onsubmit':function(values){
      var findnumberofheaders=findnumberofheaders_(qq)
      var findnumberofdefs=findnumberofdefs_(qq)
      senseidform.lastChild.innerHTML='';
      var nymB=qq.getElementsByTagName('li')[4]
      editor.addEdit({
        edit:function(wikitext){wikitext=wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+")"),"$1{{senseid|"+findlang_+"|"+values.senseid+"}}");
return ccc=wikitext;},
        redo:function(){
          senseidform.style.display="none";
          nymB.style.backgroundColor=nymB.nextSibling.style.backgroundColor="#FFFFFF";
          nymB.title=nymB.nextSibling.title=''
          },
        undo:function(){senseidform.style.display="inline";
          nymB.style.backgroundColor=nymB.nextSibling.style.backgroundColor="#CCCCCC";
          nymB.title='Please add a gloss before adding synonyms.';nymB.nextSibling.title='Please add a gloss before adding antonyms.'
          },
        summary:"+senseid: "+values.senseid
        })
      }
    }, qq, qq.childNodes[1])
  senseidform.firstChild.focus()
  window.tabbedLanguages && editor.withCurrentText(function(wikitext){
    wikitext=wikitext.match("=="+tabbedLanguages[currentLanguageTab]+"==\n[\\s\\S]+?(----|$)")[0];
    if(!wikitext)return;
    var senses='', matches=wikitext.match(/(\{\{sense\||\{\{trans-top\|)[^\}]+(?=\}\})/g)
    if(!matches)return;
    for(var ms=0;ms<matches.length;ms++){
      senses+="\n"+matches[ms].split("|")[1]
      }
    if(!senses)return;
    senseidform.firstChild.onkeyup = function(e){
      e=(e||event).keyCode;
      if(!(e>=33&&e<=40)&&e!=8&&e!=46&&e!=27&&e!=16&&this.value){
        if(senses.indexOf('\n'+this.value) > -1){
          if(this.setSelectionRange)
            this.setSelectionRange([this.value.length, this.value = senses.match(RegExp("\n"+this.value+"[^\n]*")).toString().substr(1)][0], this.value.length);
          else if(this.createTextRange){
            var z = this.createTextRange();
            z.moveEnd('character', 0-z.move('character', [this.value.length, this.value = senses.match(RegExp("\n"+this.value+"[^\n]*")).toString().substr(1)][0]) + this.value.length);
            z.select()
            }
          }
        }
      }
    })
  })
}

function editgloss(qq)
{

editor=new Editor()
editor.withCurrentText(function(wikitext){
  var findnumberofheaders=findnumberofheaders_(qq)
  var findnumberofdefs=findnumberofdefs_(qq)
  var senseidform;
  var oldsenseid;
  new AdderWrapper(editor, {
    'createForm':function(){
      var thisId = "a" + String(Math.random()).replace(".","")
      oldsenseid = wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"\\s?)"
),'').match(/^\{\{senseid\|[^\\|]*\|([^\}]*)/)[1]
      return senseidform=newNode('form',{'style':'display:inline; padding-right:20px; '},
        newNode('input',{'size':30,'name':'senseid','value':oldsenseid}),
        newNode('input',{'type':'checkbox','id':thisId,'name':'changematching',style:'display:'+(window.tabbedLanguages?'inline':'none')}),
        newNode('label',{'for':thisId,style:'display:'+(window.tabbedLanguages?'inline':'none')},'Edit matching glosses'),
        newNode('input',{'type':'submit','value':'Change'}),
        newNode('input',{'type':'button','value':'Cancel','click':function(){qq.firstChild.getElementsByTagName('li')[3].style.display='list-item';qq.removeChild(senseidform);}}),
        newNode('a', {href: '/wiki/Help:Glosses'}, 'Help?!')
        )
      },
    'fields':{
      'senseid': util.validateNoWikisyntax('gloss', true), 
      'changematching':'checkbox'
      },
    'onsubmit':function(values){
      var ttables=[], sensetemps=[], backups=[];
      if(values.changematching){
        ttables=jQuery(".NavHead", languageContainers[currentLanguageTab]).filter(function(){
          if(this.parentNode.getElementsByTagName("table")[0].className!="translations")
            return false;
          for(var i=0; i<this.childNodes.length;i++){
            if(this.childNodes[i].nodeType == 3 || this.childNodes[i].className == 'wt-edit-recurse'){
              return (this.childNodes[i].nodeValue||this.childNodes[i].innerHTML) == oldsenseid;
              }
            }
          })
        sensetemps=jQuery(".qualifier-content", languageContainers[currentLanguageTab]).filter(function(){
          return this.parentNode.nextSibling.nextSibling.className == "ib-colon" && this.innerHTML == oldsenseid;
          })
        }
      editor.addEdit({
        edit:function(wikitext){
          wikitext=wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"\\s?(\{\{senseid\\|[^\\|]*\\|))[^\}]*"),"$1"+values.senseid);
          if(values.changematching){
            var asd = wikitext.match('=='+tabbedLanguages[currentLanguageTab]+'==\n[\\s\\S]+?(\n==[^=]|$)');
            wikitext = wikitext.replace(asd[0], asd[0].replace(RegExp("\\{\\{(sense|trans-top)\\|"+oldsenseid+"\\}\\}","g"),"{\{$1\|"+values.senseid+"}}"))
            }
          return ccc=wikitext
          },
        redo:function(){
          senseidform.style.display="none";
          for(var i = 0; i < ttables.length; i++){
            backups.push(document.createDocumentFragment());
            while(ttables[i].childNodes[1]){
              backups[backups.length-1].appendChild(ttables[i].childNodes[1]);
              }
            ttables[i].appendChild(document.createTextNode(values.senseid))
            }
          for(var i = 0; i < sensetemps.length; i++){
            backups.push(document.createDocumentFragment());
            backups[backups.length-1].appendChild(sensetemps[i].firstChild);
            sensetemps[i].appendChild(document.createTextNode(values.senseid))
            }
          },
        undo:function(){
          senseidform.style.display="inline";
          for(var i = 0; i < ttables.length; i++){
            ttables[i].removeChild(ttables[i].childNodes[1]);
            ttables[i].appendChild(backups.shift())
            }
          for(var i = 0; i < sensetemps.length; i++){
            sensetemps[i].removeChild(sensetemps[i].firstChild)
            sensetemps[i].appendChild(backups.shift())
            }
          },
        summary:"senseid: "+values.senseid
        })
      }
    }, qq, qq.childNodes[1])
  senseidform.firstChild.focus()
  })
}

function findlang(tosearchfrom, callback)
{
var tosearchfrom_, findlang__
if(tosearchfrom.parentNode.nodeName.toLowerCase() == "li")
  tosearchfrom=tosearchfrom.parentNode.parentNode;
if(tosearchfrom.parentNode.className=="languageContainer"){
  if(tosearchfrom.parentNode.id=="Englishcontainer")
    return callback("en");
  }
else{
  tosearchfrom_=tosearchfrom;
  while(tosearchfrom_.nodeName.toLowerCase()!="h2")
    tosearchfrom_=tosearchfrom_.previousSibling;
  if(tosearchfrom_.lastChild.innerHTML=="English")
    return callback("en");
  }
tosearchfrom_=tosearchfrom;
while(tosearchfrom_ && !/^h\d$/i.test(tosearchfrom_.nodeName) && tosearchfrom_.className!="fakeheader")
  tosearchfrom_=tosearchfrom_.previousSibling;
while(tosearchfrom_ && tosearchfrom_.nodeName.toLowerCase()!="p" && tosearchfrom_.className!="fakeheader")
  tosearchfrom_=tosearchfrom_.nextSibling;
if(tosearchfrom_&&tosearchfrom_.className!="fakeheader"&&tosearchfrom_.firstChild&&(tosearchfrom_.firstChild.lang||(tosearchfrom_.firstChild.firstChild&&tosearchfrom_.firstChild.firstChild.lang)||(tosearchfrom_.firstChild.firstChild&&tosearchfrom_.firstChild.firstChild.firstChild&&tosearchfrom_.firstChild.firstChild.firstChild.lang)))
{return callback(tosearchfrom_.firstChild.lang||tosearchfrom_.firstChild.firstChild.lang||tosearchfrom_.firstChild.firstChild.firstChild.lang)}

if(tosearchfrom.parentNode.className=="languageContainer")
  findlang__ = tosearchfrom.parentNode.id.split("container")[0];
else{
  while(tosearchfrom.nodeName.toLowerCase()!="h2")
    tosearchfrom=tosearchfrom.previousSibling;
  findlang__ = (findlang__=tosearchfrom.getElementsByTagName("span")[1]).innerText || findlang__.textContent
  }

	window.languagecodefinder_preload = window.languagecodefinder_preload || mw.loader.getScript('https://en.wiktionary.org/w/index.php?title=User:Yair_rand/languagecodefinder.js&action=raw&ctype=text/javascript');

	window.languagecodefinder_preload.always( function() {
		window.languagenametocode && languagenametocode[findlang__] && callback(languagenametocode[findlang__])
	});
}

function setupnymadder(qq,nymtype)
{
var passtheseheaders="Usage notes|Inflection|Conjugation|Declension|Quotations", nymtypelist=["Synonyms","Antonyms","Hypernyms","Hyponyms","Meronyms","Holonyms"]
for(var x=0;nymtypelist[x]!=nymtype;x++)
  passtheseheaders+="|"+nymtypelist[x];
if(qq.parentNode.parentNode.nodeName.toLowerCase() == "li")
  qq=qq.parentNode.parentNode;
var findnumberofheaders=findnumberofheaders_(qq)
var findnumberofdefs=findnumberofdefs_(qq.parentNode.getElementsByTagName('li')[0])
for(var findheaderlevel=qq.parentNode;!/^h\d$/i.test(findheaderlevel.nodeName);findheaderlevel=findheaderlevel.previousSibling);
findheaderlevel = Number(findheaderlevel.nodeName.match(/\d/));
var senseidencoded=[]
editor=new Editor()
editor.withCurrentText(function(wikitext){

  // Find nym header, or add it if it doesn't exist
  var qqq = qq.parentNode;
  
  while(!((qqq.className=="fakesubheader"||/h\d/i.test(qqq.nodeName))&&!qqq.innerHTML.match(passtheseheaders)||qqq.className=="printfooter"||qqq.className=="fakeheader"||qqq.className=="catlinks")){qqq=qqq.nextSibling}
  if(!qqq.innerHTML.match(nymtype)){
    qqq=qqq.parentNode.insertBefore(newNode('div',{'class':'fakesubheader'},newNode('h'+(findheaderlevel+1),nymtype)),qqq);
    }
  // relevant vars: 
  //  findheaderlevel is the the headerlevel of the most recent header above the ol
  //  qq is still the li itself
  //  qqq is the (possibly newly added) nym header
  
  
  // find all relevant senseids, make an array of them, the whole template in each
  var senseid = wikitext.replace(
    RegExp(
      "(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+")"
    ),'').replace(/\n\n[\s\S]*$/,'').match(/\{\{senseid\|[^\\|]*\|[^\}]*/g)
  
  if(!senseid){alert("No glosses were found. Click \"Add gloss\" to attach a gloss to the definition before adding "+nymtype.toLowerCase()+".");return}
  
  // run through senseids, checking for a corresponding span id'd nymtype-langcode-id, adding them encased in an li in a soon-to-be-parsed temp variable if not found, otherwise suppressing new form creation
  temp=""
  var nymformexists=[]
  for(var i = 0; i < senseid.length; i++)
  {
    if(document.getElementById(senseidencoded[i]=nymtype+"-"+encodeURIComponent(senseid[i].split("|")[1]+"-"+senseid[i].split("|")[2]).replace(/%20/g,'_').replace(/%3A/g,':').replace(/%/g,'.')))
    {nymformexists[i]=true}
    else
    {temp+="* {"+"{sense|"+senseid[i].split("|")[2]+"}} <span id='"+nymtype+"-"+senseid[i].split("|")[1]+"-"+senseid[i].split("|")[2]+"'></span>\n"}

  }
  JsMwApi().page(mw.config.get('wgPageName')).parseFragment(temp,function(res){
      var qqqq=newNode('span')
      qqqq.innerHTML=res
      qqqq=qqq.parentNode.insertBefore(qqqq.firstChild,qqq.nextSibling) // the ul containing the form-holder spans, right below the nym header
      for(var i = 0; i < senseid.length; i++){
        if(!nymformexists[i]){
          setupnymadder2(i,senseid,wikitext)
        }
      }
      if(qqqq.getElementsByTagName && qqqq.getElementsByTagName('li').length==0){qqqq.parentNode.removeChild(qqqq)}
      scroll(0,jQuery(qqq).offset().top)
    }
  )

}
)

function setupnymadder2(i,senseid,wikitext)
{

var nymtype2=nymtype.slice(0,-1).toLowerCase()
var x = document.getElementById(senseidencoded[i]);

var theform
new AdderWrapper(editor, {
  'createForm':function(){return theform=newNode('form',{'style':'display:inline;'},newNode('input',{'name':'nym'}),newNode('input',{'value':'Add','type':'submit'}))},
  'fields':{'nym': util.validateNoWikisyntax(nymtype2, true) },
  'onsubmit':function(values,render){
      theform.getElementsByTagName('input')[0].value=""
      var firstnym = !theform.parentNode.parentNode.getElementsByTagName('a')[0]
      var addedwikitext=(firstnym?'':', ')+"{"+"{l|"+senseid[i].split("|")[1]+"|"+values.nym+"}}"
      render(addedwikitext,function(res2){
        var nodeToInsert=newNode('span')
        nodeToInsert.innerHTML=res2
        editor.addEdit({
            edit:function(wikitext){
// unindent

findnumberofdefs=findnumberofdefs_(qq.parentNode.getElementsByTagName('li')[0])

if(wikitext.substr(wikitext.length-1,1) != "\n"){
  wikitext+="\n"
  }

if(!wikitext.replace(RegExp("(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+")"),'').replace(RegExp("(\n(=|\\{\\{subst:=\\}\\})={"+(findheaderlevel-1)+"}[^=][\\s\\S]*$)"),'').match(RegExp(nymtype+"={"+findheaderlevel+"}")))
{
  wikitext=wikitext.replace(RegExp(
"(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"[\\s\\S]*?(\n(?=(\\{\\{subst:=\\}\\}|=)=+(?=[^=])(?!("+passtheseheaders+")))|$))"),"$1{"+"{subst:=}}==="+(findheaderlevel==4?"=":"")+nymtype+(findheaderlevel==4?"=":"")+"====\n\n")
}



if(firstnym){
  var passthesesenseids = [];
  for(var ii = 0; ii < i; ii++){
    passthesesenseids.push("\\* \\{\\{sense\\|"+senseid[ii].split("|")[2]+"\\}\\}")
    }
  wikitext=wikitext.replace(RegExp("(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"[\\s\\S]*?="+nymtype+"=+[\\s\\S]*?\n"+(passthesesenseids.length>0?"(?!("+passthesesenseids.join("|")+")))":")")),"$1* {"+"{sense|"+senseid[i].split("|")[2]+"}} "+addedwikitext+"\n")
}
else
{wikitext=wikitext.replace(RegExp("(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}[\\s\\S]*?="+nymtype+"=+[\\s\\S]*?\\{\\{sense\\|"+senseid[i].split("|")[2]+"\\}\\}.*)"),"$1"+addedwikitext)}



return ccc=wikitext;

              },
            redo:function(){theform.parentNode.parentNode.insertBefore(nodeToInsert,theform.parentNode)},
            undo:function(){theform.parentNode.parentNode.removeChild(nodeToInsert)},
            summary:"+"+nymtype2+" [["+values.nym+"]]"
          },nodeToInsert)
        }
      )
    }
  }, x
)



// sort the lis
var passthesesenseids = [];
for(var ii = 0; ii < i; ii++){
  passthesesenseids.push(senseid[ii].split("|")[2])
  }
for(var xx=x.parentNode.parentNode.nextSibling;xx.nextSibling && !/h\d/i.test(xx.nodeName) && xx.className!="fakesubheader" && xx.nodeName.toUpperCase() != "UL";xx=xx.nextSibling);
if(xx.nodeName.toUpperCase() == "UL"){
  var xxx = xx.getElementsByTagName('li')
  for(var xxxx=xxx.length; xxxx--;){
    var xxxxx = xxx[xxxx].getElementsByTagName("span")[3]
    if(xxxxx && xxxxx.innerHTML == senseid[i].split("|")[2]){
      x.parentNode.parentNode.removeChild(x.parentNode); xxx[xxxx].appendChild(x); break;
      }
    if(xxxxx && passthesesenseids.length && RegExp(passthesesenseids.join("|")).test(xxxxx.innerHTML)){
      xxx[xxxx+1]?xx.insertBefore(x.parentNode,xxx[xxxx]):xx.appendChild(x.parentNode); break;
      }
    }
  if(xxxx == -1){
    xx.insertBefore(x.parentNode, xx.firstChild)
    }
  }

}


}

function setupquoteadder(q)
{
  findlang(q.parentNode, function(findlang_){
    var z;
    if($(".HQToggle a", q)[0]){
      z = $(">ul", q)[0];
      if(z.style.display=='none'){
        $(".HQToggle a", q).click();
        }
      }
    else{
      z = q.appendChild(document.createElement("ul"))
      }
    var zz=z.appendChild(document.createElement("li")), quoteform;
    var findsubdef = q.parentNode.parentNode.nodeName.toLowerCase()=="li"?"#":"", editor=new Editor();
    new AdderWrapper(editor, {
      'createForm': function(){
        return quoteform = newNode('form',{'style':'display:inline;'},'Year: ',newNode('input',{'name':'year','size':4}),' Author: ',newNode('input',{'name':'author','size':20}),' Source title: ',newNode('input',{'name':'source','size':20}),' Publisher: ',newNode('input',{'name':'publisher','size':20}),' Page(s): ',newNode('input',{'name':'page','size':5}), newNode('dl', newNode('dd', 'Quotation: ', newNode('input', {'name':'quotation','size':40}),newNode('input',{'type':'submit','value':'Preview'}),newNode('input',{'type':'button','value':'Cancel','click':function(){z.removeChild(zz)}}),newNode('dl',{'style':'display:'+(findlang_=="en"?"none":"block")},newNode('dd', 'Translation: ',newNode('input',{'size':40,'name':'translation'}))))))
        },
      'fields':{
        'quotation':util.validateNoWikisyntax('quotation', true),
        'year':util.validateNoWikisyntax('year', true),
        'author':function(t){return t},
        'source':function(t){return t?", ''"+t+"''":''},
        'publisher':function(t){return t?", "+t:''},
        'page':function(t){return t?(/\-/.test(t)?"pages "+t:"page "+t):t},
        'translation':function(t){return t}
        },
      'onsubmit':function(values, render){
        var topline = "'''"+values.year+"'''"+(values.author?", "+values.author:'')+values.source+values.publisher+(values.page?", "+values.page:'')
        render(topline + "\n:" + values.quotation + (values.translation?"\n:"+values.translation:""), function(newhtml){
          var findnumberofheaders=findnumberofheaders_(q), findnumberofdefs=findnumberofdefs_(q), quotetobeadded=newNode('span',{'style':'display:block;'});
          quotetobeadded.innerHTML=newhtml.replace(/\<p\>|\<\/p\>/g,'');
          editor.addEdit({
            'edit':function(wikitext){
return ccc=wikitext.replace(RegExp("(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}"+findnumberofdefs+"[\\s\\S]*?)\n(?!#"+findsubdef+"[:\*])|$"), "$1\n#"+findsubdef+"*"+topline+"\n#"+findsubdef+"*:"+values.quotation+(values.translation?"\n#"+findsubdef+"*:"+values.translation:'')+'\n')
},
            'redo':function(){quoteform.style.display='none'; quotetobeadded.style.display='block'; zz.appendChild(quotetobeadded)},
            'undo':function(){quoteform.style.display='inline';zz.removeChild(quotetobeadded)},
            'summary':'+quote: "'+values.quotation+'"- '+values.source
            },quotetobeadded)
          })
        }
      }, zz)
  })
}


function addPOSHeader(cancelhover)
{
if(!document.onmousemove){
editor=new Editor()
var headerLevel = (window.languageContainers&&languageContainers[currentLanguageTab]&&languageContainers[currentLanguageTab].firstChild) || bodyContent.firstChild;
var ii;
var temp, temp_;
var theform;
var findnumberofheaders;
var addedwikitext;
var prefakeheaders;
var currentFocus;
var poslist = '\nNoun\nVerb\nAdjective\nAdverb\nPronoun\nConjunction\nInterjection\nPreposition\nProper noun\nArticle\nPrepositional phrase\nAcronym\nAbbreviation\nInitialism\nContraction\nPrefix\nSuffix\nSymbol\nLetter\nLigature\nIdiom\nPhrase\nNumber\nNumeral\nCardinal number\nOrdinal number\nCardinal numeral\nOrdinal numeral\nPersonal pronoun\nDeterminer\nDemonstrative determiner\nClitic\nInfix\nInterfix\nAffix\nCircumfix\nCircumposition\nCounter\nKanji\nKanji reading\nHanja reading\nHirigana letter\nKatakana letter\nPinyin\nHan character\nHanzi\nHanja\nProverb\nExpression\nParticle\nInfinitive particle\nPossesive adjective\nPostposition\nPhrasal verb\nParticiple\nGerund\nInterrogative auxiliary verb\nPronominal adverb\nAdnominal\nAbstract pronoun\nConjunction particle\nCombining form\nRoot\nPinyin syllable\nSyllable\nHirigana character\nKatakana character\nJyutping syllable\nGismu\nLujvo\nBrivla\nClassifier\nPredicative\nMeasure word\nCorrelative\nPreverb\nPrenoun\nNoun stem\nNoun class\nCombined-kana character\nCmavo\n';
while(headerLevel.nextSibling){
  if(/^h[34]$/i.test(headerLevel.nodeName)&&!/Etymology|Pronunciation|Alternative\sforms/.test(headerLevel.innerHTML)){
    headerLevel = headerLevel.nodeName.toLowerCase();
    break;
    }
  headerLevel = headerLevel.nextSibling
  }

currentBoxToBeAdded = newNode('div',{'style':'position:fixed;top:500px;'})
new AdderWrapper(editor, {
createForm : function(){
  return theform = newNode('form',
    currentFocus = newNode('input',{'style':'font-size: 0.8em;font-size: '+((headerLevel == 'h3')?'132%':'116%')+';font-weight: bold;font-family: sans-serif;width:auto;','rows':1,'name':'pos',focus:function(){currentFocus = this}}),
    newNode('input',{'type':'submit','value':'Preview'}),
    newNode('input',{'type':'button','value':'Cancel',click:function(){theform.style.display='none';hoverNewPOS(null);document.onmousemove = null;document.body.style.cursor = '';}}),
    newNode('br'),
    newNode('input',{'style':'width:300px;font-family:monospace;','name':'inflline',focus:function(){currentFocus = this}}),
    newNode('ol',newNode('li',newNode('input',{'size':100,'disabled':'disabled'})))
  )},
fields:{
  'pos':function(txt,error){return poslist.indexOf('\n'+txt+'\n')>-1?txt:error('Please select a valid part of speech.')},
  'inflline':function(txt,error){return txt||"{"+"{infl}}"}},
onsubmit: function(values,render){
  addedwikitext = '{'+'{subst:=}}=='+(headerLevel=='h4'?'=':'')+values.pos+(headerLevel=='h4'?'=':'')+'===\n'+values.inflline
  hoverNewPOS(null);
  document.onmousemove = null;
  document.body.style.cursor = '';
  render(addedwikitext,function(res){
    theform.style.display='none'
    temp=document.createDocumentFragment();
    temp.appendChild(temp_=newNode('div',{'class':'fakeheader'}));
    temp_.innerHTML=res;
    temp.appendChild(newNode('ol',newNode('li',' ')));
    theform.parentNode.insertBefore(temp,theform);
    
    prefakeheaders=0
    findnumberofheaders = theform.previousSibling.previousSibling;
    while(true){
      if(findnumberofheaders.previousSibling){
        findnumberofheaders = findnumberofheaders.previousSibling;
        if(/h[2-6]/i.test(findnumberofheaders.nodeName)){
          findnumberofheaders = Number(findnumberofheaders.firstChild.getElementsByTagName('a')[0].href.split("section=")[1]);
          break;
          }
        findnumberofheaders.className=='fakeheader' && prefakeheaders++;
        }
      else{
        findnumberofheaders.parentNode.insertBefore(newNode('h2',languageHeaderEditButtons[currentLanguageTab].cloneNode(true),{'style':'display:none;'}),findnumberofheaders);
        }
      }
  
    var updatecatscallback;
    editor.addEdit({
      'edit':function(wikitext){return ccc=wikitext.replace(RegExp("(^[\\s\\S]*?((^|\n)=[\\s\\S]*?){"+findnumberofheaders+"}([\\s\\S]*?\n\\{\\{subst:\\=\\}\\}=="+(headerLevel=='h4'?'=':'')+"[^=]){"+prefakeheaders+"}[\\s\\S]*?(?=(\n=|\n----|\n\\{\\{subst:\\=\\}\\}=="+(headerLevel=='h4'?'=':'')+"[^=]|$)))"),"$1\n"+addedwikitext+"\n\n# {{rfdef}}\n")},
      'redo':function(){
        theform.style.display='none';theform.parentNode.insertBefore(temp,theform);
        updatecatscallback = window.tabbedLanguages && updateCategories(theform.parentNode, addedwikitext)},
      'undo':function(){
        theform.style.display='block';temp.appendChild(temp_);temp.appendChild(theform.previousSibling);
        updatecatscallback && updatecatscallback()},
      'summary':'+pos '+values.pos
      },temp_)
  
    makedefsidebox(theform.previousSibling.firstChild)
    editdefinition(theform.previousSibling.firstChild)
  
    editor.withCurrentText(function(){
      theform.previousSibling.getElementsByTagName('input')[0].value='';
      theform.previousSibling.getElementsByTagName('input')[0].focus()
      })
    })}
},currentBoxToBeAdded)

cancelhover || setUpBoxToBeAdded();
theform.firstChild.focus()
function hoverNewPOS(thefunction){
  for(var ii = bodyContent.getElementsByTagName(headerLevel), i = 0; i < ii.length; i++){
    if(!/^Etymology|Pronunciation|Alternative\sforms$/.test(ii[i].lastChild.innerHTML))
      (ii[i].parentNode.className=='fakeheader'?ii[i].parentNode:ii[i]).onmouseover = thefunction;
    }
  if(window.tabbedLanguages){
    for(var i = 0; i < languageContainers.length; i++)
      languageContainers[i].lastChild.onmouseover = thefunction;
    }
  else{
    ii = bodyContent.getElementsByTagName('hr');
    for(var i = 0; i < ii.length; i++)
      ii[i].onmouseover = thefunction;
    }
  }
function hoverNewPOS_(){
  currentBoxToBeAdded.style.display='none';
  this.parentNode.insertBefore(theform,this);
  currentFocus.focus();
  }

cancelhover || hoverNewPOS(hoverNewPOS_);

// autocomplete pos field
theform.firstChild.onkeydown = function(e){
  if((e||event).keyCode==9){theform.getElementsByTagName("input")[3].focus();return false}
  }
theform.firstChild.onkeyup = function(e){
  if(this.value.charAt(0)!=this.value.charAt(0).toUpperCase())
    this.value = this.value.charAt(0).toUpperCase() + this.value.substr(1);
  e=(e||event).keyCode;
  if(!(e>=33&&e<=40)&&e!=8&&e!=46&&e!=27&&e!=16&&this.value){
    if(poslist.indexOf('\n'+this.value) > -1){
      if(this.setSelectionRange)
        this.setSelectionRange([this.value.length, this.value = poslist.match(RegExp(this.value+"[^\n]*"))][0], this.value.length);
      else if(this.createTextRange){
        var z = this.createTextRange();
        z.moveEnd('character', 0-z.move('character', [this.value.length, this.value = poslist.match(RegExp(this.value+"[^\n]*"))][0]) + this.value.length);
        z.select()
        }
      }
    }
  }

}
}

function updateCategories(container, newvalue, oldvalue)
{
  var addedCategories=[], removedCategories=[]
  JsMwApi()({action:"parse",prop:"categorieshtml",title:wgPageName,text:newvalue}, function(r){
    var e=r.parse.categorieshtml['*'].match(/\<span.*?\/span\>/g)
    var d=container.lastChild;
    var f=document.createElement('div');
    for(var i = 0; e && i < e.length; i++){
      f.innerHTML=e[i];
      if(d.innerHTML.indexOf(f.firstChild.innerHTML) == -1){
        addedCategories.push(d.insertBefore(f.lastChild, d.lastChild))
        d.insertBefore(document.createTextNode(' | '), d.lastChild)
        }
      }
    oldvalue && JsMwApi()({action:"parse",prop:"categorieshtml",title:wgPageName,text:oldvalue}, function(o){
      e=o.parse.categorieshtml['*'].match(/\<span.*?\/span\>/g)
      for(var i = 0; e && i < e.length; i++){
        f.innerHTML=e[i];
        if(r.parse.categorieshtml['*'].indexOf(f.firstChild.innerHTML) == -1 && d.innerHTML.indexOf(f.firstChild.innerHTML) != -1){
          var spans = d.getElementsByTagName('span')
          for(var ii = 0; ii < spans.length; ii++){
            if(spans[ii].firstChild.innerHTML == f.firstChild.firstChild.innerHTML){
              removedCategories.push(spans[ii]);
              spans[ii].style.display='none';
              d.removeChild(spans[ii].nextSibling)
              break;
              }
            }
          }
        }
      })
    })
  return function(){
    for(var i = 0; i < addedCategories.length; i++){
      container.lastChild.removeChild(addedCategories[i].nextSibling);container.lastChild.removeChild(addedCategories[i])
      }
    for(var i = 0; i < removedCategories.length; i++){
      removedCategories[i].style.display = 'inline'; 
      container.lastChild.insertBefore(document.createTextNode(' | '), removedCategories[i].nextSibling)
      }
    } 
}

jQuery(document).ready(function(){
  	if(document.getElementById('YRDefsideboxes-disable-button'))
	{
		document.getElementById('YRDefsideboxes-disable-button').innerHTML = ""
		var toggle = newNode('span', {click: function ()
		{
			if( $.cookie("DisableYREdit") ){
				$.cookie("DisableYREdit", null,{path:"/"})
				toggle.innerHTML = "Disable"
			}
			else{
				$.cookie("DisableYREdit",1,{expires:60,path:"/"})
				toggle.innerHTML = "Enable"
			}
		} }, ($.cookie("DisableYREdit")?"Enable":"Disable"))
 
		document.getElementById('YRDefsideboxes-disable-button').appendChild(toggle);
	}
  })