// <nowiki>
// Licence : Domaine public

if(mw.config.get('wgNamespaceNumber')==14){ 
     addOnloadHook(BandeauxEbaucheBOT_AddLink);
}

function BandeauxEbaucheBOT_AddLink(){
     var OngletsCactions = document.getElementById('p-cactions').getElementsByTagName('ul');
     OngletsCactions.innerHTML += '<li><a href="javascript:BandeauxEbaucheBOT_OpenMenu();">Ébauche (bot)</a></li>';
}

function BandeauxEbaucheBOT_getScreenSize(){
     var HauteurEcran = 0;
     if( typeof( window.innerHeight ) == 'number' ) {
          HauteurEcran = parseInt(window.innerHeight);
     }else if( document.documentElement && document.documentElement.clientHeight ){
          HauteurEcran = parseInt(document.documentElement.clientHeight);
     }else if( document.body && document.body.clientHeight ){
          HauteurEcran = parseInt(document.body.clientHeight);
     }
     var LargeurEcran = 0;
     if( typeof( window.innerWidth ) == 'number' ) {
          LargeurEcran = parseInt(window.innerWidth);
     }else if( document.documentElement && document.documentElement.clientWidth ){
          LargeurEcran = parseInt(document.documentElement.clientWidth);
     }else if( document.body && document.body.clientWidth ){
          LargeurEcran = parseInt(document.body.clientWidth);
     }
     var ScreenSize = new Object();
     ScreenSize.H = HauteurEcran;
     ScreenSize.W = LargeurEcran;
     return ScreenSize;
}

function BandeauxEbaucheBOT_OpenMenu(){
    if(document.getElementById('BandeauxEbaucheBOT_Menu')) return;
     var ScreenSize = BandeauxEbaucheBOT_getScreenSize();
     var HauteurEcran = ScreenSize.H;
     var LargeurEcran = ScreenSize.W;
     var Menu = document.createElement('div');
     Menu.id='BandeauxEbaucheBOT_Menu';
     Menu.className = 'BandeauxEbaucheBOT_Menu';
     Menu.style.position='fixed';
     Menu.style.zIndex= 500;
     Menu.style.padding='5px';
     Menu.style.backgroundColor='white';
     Menu.style.border='3px double black';
     Menu.style.width= 'auto';
     document.body.appendChild(Menu);
     var MenuContent = ''
     + '<fieldset id="OptionsValue" ><legend>Modification des bandeaux d’ébauche</legend>'
     + '<table id="BandeauxEbaucheBOT_OptionsTable"><tr><td width="280px" valign="middle" align="center">'
     + '<label for="RemoveBandeau">Bandeaux à retirer</label>'
     + '</td><td valign="middle" align="center">'
     + '<label for="linkedModifs">Liaison</label>'
     + '</td><td width="280px" valign="middle" align="center">'
     + '<label for="RemoveBandeau">Bandeaux à ajouter</label>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" id="RemoveBandeau1" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr><tr><td valign="middle" align="center">'
     + '<input type="text" class="RemoveBandeau" value="" size="40"/>'
     + '</td><td valign="middle" align="center">'
     + '<input type="checkbox" class="linkedModifs" style="cursor:pointer;" />'
     + '</td><td valign="middle" align="center">'
     + '<input type="text" class="AddBandeau" value="" size="40"/>'
     + '</td></tr></table></fieldset>'
     + '<center id="OptionsButtons" >'
     + '<input type="checkbox" id="SousCats" style="cursor:pointer;" />'
     + '<label for="SousCats">Traiter les sous-catégories ?</label>'
     + '&nbsp;&nbsp;'
     + '<input type="checkbox" id="Autoconfirm" style="cursor:pointer;" />'
     + '<label for="Autoconfirm">Publier sans confirmation manuelle ?</label>'
     + '&nbsp;&nbsp;'
     + '<input type="checkbox" id="AutoWatch" style="cursor:pointer;" />'
     + '<label for="AutoWatch">Suivre les pages modifiées ?</label>'
     + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
     + '<input type="button" style="cursor:pointer;" '
     + ' value="OK" title="Appliquer" '
     + ' onclick="BandeauxEbaucheBOT_GetOptions(true);" onselect="BandeauxEbaucheBOT_GetOptions(true);"/>'
     + '&nbsp;&nbsp;'
     + '<input type="button" style="cursor:pointer;" '
     + ' value="Fermer" title="Fermer le menu" '
     + ' onclick="BandeauxEbaucheBOT_CloseMenu();" onselect="BandeauxEbaucheBOT_CloseMenu();"/>'
     + '</center>';
     Menu.innerHTML = MenuContent;
     PositionGauche = parseInt((LargeurEcran-Menu.clientWidth)/2) ;
     PositionHaut = parseInt((HauteurEcran-Menu.clientHeight)/3) ;
     Menu.style.left=PositionGauche + 'px';
     Menu.style.top=PositionHaut + 'px'; 
     document.getElementById("RemoveBandeau1").focus();
}

 
function BandeauxEbaucheBOT_CloseMenu(){
     var Menu = document.getElementById('BandeauxEbaucheBOT_Menu');
     if(Menu) Menu.parentNode.removeChild(Menu);
}


function BandeauxEbaucheBOT_GetOptions(First){
     var Options = new Object();
     Options.SousCats = (document.getElementById("SousCats").checked ? true : false);
     Options.Autoconfirm = (document.getElementById("Autoconfirm").checked ? true : false);
     Options.AutoWatch = (document.getElementById("AutoWatch").checked ? true : false);
     Options.Changes = new Array();
     var Table = document.getElementById("BandeauxEbaucheBOT_OptionsTable");
     var TRs = Table.getElementsByTagName("tr");
     for(var a=0,l=TRs.length;a<l;a++){
          var TR = TRs;
          var RemoveBandeau = getElementsByClassName(TR, 'input', 'RemoveBandeau');
          var AddBandeau = getElementsByClassName(TR, 'input', 'AddBandeau');
          var linkedModifs = getElementsByClassName(TR, 'input', 'linkedModifs');
          if(!RemoveBandeau || !AddBandeau || !linkedModifs ) continue;
          RemoveBandeau = RemoveBandeau.value;
          AddBandeau = AddBandeau.value;
          if(!RemoveBandeau && !AddBandeau) continue;
          linkedModifs = (linkedModifs.checked ? true : false);
          Options.Changes.push({"RemoveBandeau":RemoveBandeau,"AddBandeau":AddBandeau,"linkedModifs":linkedModifs}); 
     }
     if(Options.Changes.length==0) return;
     Options.APIlimit = ( (mw.config.get('wgUserGroups').indexOf("sysop")!=-1)||(mw.config.get('wgUserGroups').indexOf("bot")!=-1) ? 4999 : 499 );
     Options.categorylist = new Array(mw.config.get('wgPageName'));
     Options.pagelist = new Array();
     Options.noincludecategories = new Array();
     Options.first = true;
     if(First) BandeauxEbaucheBOT_Run(Options);
     else BandeauxEbaucheBOT_RunAgain(Options);
}

function BandeauxEbaucheBOT_UpdateMenu(Options){
     var Menu = document.getElementById('BandeauxEbaucheBOT_Menu');
     if(!Menu) return;
     var CatList = document.createElement('fieldset');
     CatList.id = 'BandeauxEbaucheBOT_MenuCats'
     var CatListContent = ''
     + '<legend>Sélectionner les catégories à prendre en compte</legend>'
     + '<div id="BandeauxEbaucheBOT_MenuCatsList" style="max-height:250px;overflow-y:auto;">'
     + '<ul>'
     var AllCats = Options.categorylist;
     for(var a=0,l=AllCats.length;a<l;a++){
          CatListContent += '<li style="white-space:nowrap">'
          + '<input type="checkbox" checked="checked" value="'+AllCats+'" class="CatListCheckbox" />'
          + '&nbsp;'+AllCats.split(mw.config.get('wgFormattedNamespaces')+':').join("")
          + '</li>'
     }
     CatListContent += '</ul></div>';
     CatList.innerHTML = CatListContent;
     var CatButtons = document.createElement('center');
     var CatButtonsContent = ''
     + '<input type="button" style="cursor:pointer;" '
     + ' value="OK" title="Appliquer" '
     + ' onclick="BandeauxEbaucheBOT_GetOptions(false);" onselect="BandeauxEbaucheBOT_GetOptions(false);"/>'
     + '&nbsp;&nbsp;'
     + '<input type="button" style="cursor:pointer;" '
     + ' value="Fermer" title="Fermer le menu" '
     + ' onclick="BandeauxEbaucheBOT_CloseMenu();" onselect="BandeauxEbaucheBOT_CloseMenu();"/>'
     CatButtons.innerHTML = CatButtonsContent;
     var OptionsValue = document.getElementById("OptionsValue");
     if(OptionsValue) OptionsValue.style.display = "none";
     var OptionsButtons = document.getElementById("OptionsButtons");
     if(OptionsButtons) OptionsButtons.style.display = "none";
     Menu.appendChild(CatList);
     Menu.appendChild(CatButtons);
     var ScreenSize = BandeauxEbaucheBOT_getScreenSize();
     var HauteurEcran = ScreenSize.H;
     var LargeurEcran = ScreenSize.W;
     PositionGauche = parseInt((LargeurEcran-Menu.clientWidth)/2) ;
     PositionHaut = parseInt((HauteurEcran-Menu.clientHeight)/3) ;
     Menu.style.left=PositionGauche + 'px';
     Menu.style.top=PositionHaut + 'px'; 
}

function BandeauxEbaucheBOT_RunAgain(Options){
     var MenuCats = document.getElementById('BandeauxEbaucheBOT_MenuCatsList');
     if(!MenuCats) return;
     var CatList = getElementsByClassName(MenuCats, 'input', 'CatListCheckbox');
     for(var a=0,l=CatList.length;a<l;a++){
          if(!CatList.ckecked) Options.noincludecategories.push(CatList.value);
          else Options.pagelist.push(CatList.value);
     }
     Options.first = false;
     BandeauxEbaucheBOT_Run(Options);
}


function BandeauxEbaucheBOT_Run(Options){   
      if(!Options.categorycontinue) Options.categorycontinue = '';
      if(!Options.categoryCount) Options.categoryCount = 0;
      var NouvelleRequete = sajax_init_object()
      var AdresseRequete = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?format=xml&action=query&list=categorymembers'
                         + '&cmlimit='+Options.APIlimit
                         + '&cmtitle=' + encodeURIComponent(Options.categorylist) 
                         + Options.categorycontinue;
      NouvelleRequete.open("GET", AdresseRequete, true);
      NouvelleRequete.onreadystatechange = function() {
            if(NouvelleRequete.readyState != 4 || NouvelleRequete.status != 200) return;
            var ElementTraitement = NouvelleRequete.responseXML;
            var Pages = ElementTraitement.getElementsByTagName('cm');
            for(a=0;a<Pages.length;a++){
                  var PageNamespace = parseInt(Pages.getAttribute('ns'));
                  if((PageNamespace!=0)&&(PageNamespace!=1)&&(PageNamespace!=14)) continue;
                  var TitrePage = Pages.getAttribute('title');
                  TitrePage = TitrePage.split(mw.config.get('wgFormattedNamespaces') + ':').join("");
                  if((TitrePage.indexOf(mw.config.get('wgFormattedNamespaces') + ':')!=-1)&&(Options.SousCats)){
                        if(Options.categorylist.indexOf(TitrePage)==-1 && Options.noincludecategories.indexOf(TitrePage)==-1) Options.categorylist.push(TitrePage);
                  }else if(TitrePage.indexOf(mw.config.get('wgFormattedNamespaces') + ':')==-1){
                        if(Options.pagelist.indexOf(TitrePage)==-1) Options.pagelist.push(TitrePage);
                   }
            } 
            var MustContinue = ElementTraitement.getElementsByTagName('cmcontinue');
            if(MustContinue){
                  Options.categorycontinue = "&cmcontinue="+encodeURIComponent(MustContinue.fistChild.getAttribute("cmcontinue"));
                  BandeauxEbaucheBOT_Run(Options);
            }else{
                  Options.categoryCount = (Options.categoryCount+1)
                  Options.categorycontinue = "";
                  var NewCategory = Options.categorylist;
                  if(NewCategory){
                        BandeauxEbaucheBOT_Run(Options);
                  }else{
                        if(Options.first && Options.SousCats) BandeauxEbaucheBOT_UpdateMenu(Options);
                        else BandeauxEbaucheBOT_SortList(Options);
                  }
            }
      }
      NouvelleRequete.send(null);
}


var BandeauxEbaucheBOT_SortedPageInCategory = new Array();
var BandeauxEbaucheBOT_SortedPageInCategoryCount = 0;

function BandeauxEbaucheBOT_SortList(Options){
      var PagesTemp = Options.pagelist.sort();
      var SortedPageInCategory = new Array();
      for(var a=0;a<PagesTemp.length;a++){
           if(PagesTemp!=PagesTemp){
                 SortedPageInCategory.push(PagesTemp);
           }
      }
      Options.pagelist = SortedPageInCategory;
      var PopContent = 'Nombre de pages à vérifier : ' + Options.pagelist.length + '.';
      Options.pageCount = 0
      var Pop = confirm(PopContent);
      if(Pop) BandeauxEbaucheBOT_AddBandeau(Options); 
      else BandeauxEbaucheBOT_CloseMenu();      
}

function BandeauxEbaucheBOT_AddNextBandeau(Options){
      Options.pageCount++
      BandeauxEbaucheBOT_AddBandeau(Options);
}

function BandeauxEbaucheBOT_AddBandeau(Options){
      var Page = Options.pagelist;
      if(!Page){ alert('Travail terminé'); window.location.reload(); }
      var url = mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=' + encodeURIComponent(Page) + '&action=edit&section=0';
      var NouvelleRequete = sajax_init_object();      
      NouvelleRequete.open("GET", url, true);
      NouvelleRequete.onreadystatechange = function() {
            if(NouvelleRequete.readyState != 4 || NouvelleRequete.status != 200) return;
            while(document.body.firstChild){ document.body.removeChild(document.body.firstChild); }
            var ElementTraitement = document.createElement('div');
            document.body.appendChild(ElementTraitement);
            ElementTraitement.innerHTML = NouvelleRequete.responseText; 
            var TextArea = document.getElementById('wpTextbox1');
            if(!TextArea){ alert(url); return; }                  

            var OldText = TextArea.value;
            if((OldText.indexOf('#REDIRECT')!=-1)||(OldText.indexOf('#redirect')!=-1)||(OldText=='')){
                  BandeauxEbaucheBOT_AddNextBandeau(Options); 
                  return;
            }
            var NewValues = BandeauxEbaucheBOT_reallyAddBandeau(Options, OldText);
            if(!NewValues) return;
            var TexteFinal = NewValues.Text;
            var Sommaire = NewValues.Comment;
            var SommaireFinal = Sommaire + ' ; (])'
            document.getElementById('wpTextbox1').value = TexteFinal;
            document.getElementById('wpSummary').value = SommaireFinal;
            document.getElementById('wpMinoredit').checked = "checked";
            document.getElementById('wpWatchthis').checked = (Options.AutoWatch ? "checked" : false);
            //document.editform.submit();

            if(!Options.Autoconfirm){
                  var SurEtCertain = confirm('Sommaire : ' + Sommaire);
                  if(!SurEtCertain){
                        var SurEtCertainBis = confirm('Page suivante ?');
                        if(!SurEtCertainBis){
                              window.location.reload();
                              return;
                        }else{
                              BandeauxEbaucheBOT_AddNextBandeau(Options);
                              return;
                        }
                  }
            }
            var action = document.getElementById("editform").action;
            var boundary = '--------123xyz';
            var data = '';
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpTextbox1"\n\n' + TexteFinal + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpSection"\n\n' + document.editform.wpSection.value + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpSummary"\n\n' + SommaireFinal + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpMinoredit"\n\n' + document.editform.wpMinoredit.value + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpWatchthis"\n\n' + document.editform.wpWatchthis.value + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpStarttime"\n\n' + document.editform.wpStarttime.value + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpEdittime"\n\n' + document.editform.wpEdittime.value + '\n'
            data += '--' + boundary + '\nContent-Disposition: form-data; name="wpEditToken"\n\n' + document.editform.wpEditToken.value + '\n'
            var ajaxSubmit = sajax_init_object();
            ajaxSubmit.open('POST', action, true);
            ajaxSubmit.setRequestHeader('Content-Type', 'multipart/form-data; boundary='+boundary);
            ajaxSubmit.onreadystatechange = function(){
                  if (ajaxSubmit.readyState != 4) return;
                  while(document.body.firstChild){document.body.removeChild(document.body.firstChild);}
                  var ElementTraitementBis = document.createElement('div');
                  document.body.appendChild(ElementTraitementBis);
                  ElementTraitementBis.innerHTML = ajaxSubmit.responseText; 
                  if(!document.getElementById("editform")){
                        BandeauxEbaucheBOT_AddNextBandeau(Options);
                  }else{
                        var DeuxiemeEssai = confirm('Problème !\n\nRéessayer ?');
                        if(DeuxiemeEssai) BandeauxEbaucheBOT_AddBandeau(Options);         
                  }
            }
            ajaxSubmit.send(data + '--' + boundary);
      }
      NouvelleRequete.send(null);
}
function BandeauxEbaucheBOT_reallyAddBandeau(Options, OldText){
      var Changes = Options.Changes;
      var EbaucheRegExp = new RegExp('\\{\\{( |_)*(e|é|E|É)bauche( |_)*\\|+\\}\\}(\n)*', 'g');
      var OldEbaucheMatch = OldText.match(EbaucheRegExp);
      var AllParams = new Array();
      var EbaucheIndex = -1;
      if(OldEbaucheMatch!=null){
            EbaucheIndex = OldText.indexOf(OldEbaucheMatch);
            for(var a=0,l=OldEbaucheMatch.length;a<l;a++){
                  var AllParamsInThisTemplate = OldEbaucheMatch.split("|");   
                  for(var m=1,p=AllParamsInThisTemplate.length;m<p;m++){
                        var ThisParam = AllParamsInThisTemplate;
                        if(!ThisParam) continue;
                        ThisParam = ThisParam.replace(/(\||\})/g, "");
                        ThisParam = ThisParam.replace(/_/g, " ");
                        ThisParam = ThisParam.replace(/^ /g, "");
                        ThisParam = ThisParam.replace(/ $/g, "");                              
                        if(ThisParam && AllParams.indexOf(AllParams)==-1) AllParams.push(ThisParam);
                  }
                  OldText = OldText.replace(OldEbaucheMatch, "");
            }
      }
      var OldParams = AllParams;
      for(var a=0,l=Options.Changes.length;a<l;a++){
            var ThisChangeOptions = Options.Changes;
            var RemoveBandeau = ThisChangeOptions.RemoveBandeau;
            var AddBandeau = ThisChangeOptions.AddBandeau;
            var linkedModifs = ThisChangeOptions.linkedModifs;
            if(AddBandeau && RemoveBandeau){
                  var paramIndex = AllParams.indexOf(RemoveBandeau);
                  if(linkedModifs){                        
                        if(paramIndex!=-1) AllParams.splice(paramIndex, 1, AddBandeau);
                        else if(RemoveBandeau=="*" && AllParams.length!=0) AllParams = new Array(AddBandeau)
                  }else{
                        if(paramIndex!=-1) AllParams.splice(paramIndex, 1);
                        if(RemoveBandeau=="*") AllParams = new Array(AddBandeau);
                        else if(AllParams.indexOf(AddBandeau)==-1) AllParams.push(AddBandeau);
                  }
            }else if(AddBandeau){
                  if(AllParams.indexOf(AddBandeau)==-1) AllParams.push(AddBandeau);
            }else if(RemoveBandeau){
                  var paramIndex = AllParams.indexOf(RemoveBandeau);
                  if(paramIndex!=-1) AllParams.splice(paramIndex, 1);
                  else if(RemoveBandeau=="*") AllParams = new Array();
            }
      }
      if(AllParams===OldParams){
            BandeauxEbaucheBOT_AddNextBandeau(Options);
            return false;
      }
      var BOT = ( (mw.config.get('wgUserGroups').indexOf("bot")!=-1) ? ' ' : '');
      var Sommaire = BOT+'Modification automatique de {{Ébauche}} : "'+OldParams.join("|")+'" →‎ "'+AllParams.join("|")+'"';      
      var NouveauModele = "{{Ébauche|$1}}\n";
      NouveauModele = NouveauModele.split("$1").join(AllParams.join("|"));
      if(AllParams.length==0) NouveauModele = "";
      if(EbaucheIndex==-1){
            EbaucheIndex = 0; // todo : Trouver le point où insérer un nouveau bandeau (après bandeau d'homonymie)
      }
      var NewText = OldText.substring(0,EbaucheIndex)+NouveauModele+ OldText.substring(EbaucheIndex,OldText.length);
      var Result = new Object();
      Result.Text = NewText;
      Result.Comment = Sommaire;
      return Result;
}

// </nowiki>