//

/*
 * Scriptus
 *
 * La foncion Scriptus servís a redigir sus wikipèdia de biais natural, 
 * per simple dobleclic e confimacion de salvagarda. 
 * La definicion en francés d'aqueste escript se tròba aicí : 
 * http://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Brouillons/interface_ajax
 *
 * Lo còde de l'escript es liurament inspirat del sistèma de modificacion-inline de l'Olivier Lance
 * http://olance.developpez.com/articles/web/javascript/modification-inline/
 *
 * Autors : ivo talvet (fr:user:Tavernier) , JoKerozen (fr:user:JoKerozen)
 * Data de darrièra revision : 20 d'octobre de 2007 - 0.1 (alpha) - foncionalitats basicas, non optimizadas
 * snapshot dempuèi http://fr.wikipedia.org/w/index.php?title=Wikip%C3%A9dia:Brouillons/interface_ajax/js&oldid=21985960
 */

function Scriptus() {
   if (!wgIsArticle) return; //se non editabla, sortida
   if (wgNamespaceNumber/2 != Math.round(wgNamespaceNumber/2)) return; //si impair (discussion), retorn
   if (  (wgPageName.search('Wikipèdia:La_Tavèrna') != -1)
       ||(wgPageName.search('Wikipèdia:Bulletin_dels_administrators') != -1)
       ||(document.getElementById("transfòrmaEnPaginaDeDiscussion"))
      ) return; //cas excepcionals de discussion dins ns par

   loadEventsScriptus();
}


function loadEventsScriptus() {

   var intro = getElementsByClass("firstHeading")[0];

   intro.className = "mw-headline firstHeading"; //coeréncia
   var sections = getElementsByClass("mw-headline");
   for each (var section in sections) {
       
       try {
       var hrefSection = getElementsByClass("editsection", section.parentNode)[0]
                        .getElementsByTagName('a')[0]
                        .getAttribute('href');
       } catch(e) {}
       if (section.className == "mw-headline firstHeading") {
           var numSection = 0; //firstHeading
       } 
       else {
       var numSection = hrefSection.replace(/.*section=([0-9]+)/g, '$1');
       }
       section.addEventListener("dblclick", findBlocScriptus(numSection), false);
   }
}


function findBlocScriptus(numSection) 
{
    return function()
    {
    if (document.getElementsByTagName('textarea').length) return;

    document.ou = numSection;


    var headers = new Array();
    headers['Cache-Control'] = 'no-cache, must-revalidate';
    headers['Pragma'] = 'no-cache';


    // quiti a cargar la pagina d'edit, autant o far aicí e recuperar wpTextbox1, que normalament es a jorn 

    if (document.ou == 0) {
    var demandeSection = ''
    } 
    else {
    var demandeSection = '&section=' + document.ou
    }

    var editFormSeek = wpajaxScriptus.http({ url: wgServer + wgScriptPath 
                                                  + '/index.php?title=' 
                                                  + encodeURIComponent(wgPageName) 
                                                  + '&action=edit' 
                                                  + demandeSection,
                                             async: false,
                                             headers: headers,
                                             });

    var parser = new DOMParser();

    var doc = parser.parseFromString(editFormSeek.responseText, 'application/xhtml+xml');

    var inputs = doc.getElementById('editform').getElementsByTagName('input');
    var editform = new Array();

    for (i=0; i<inputs.length; i++) {
      editform[inputs[i].name] = inputs[i].value;
    }

    // se plaça d'inputs hidden per "salvagardar" las infos que se aurà de besonh

    var titre = getElementsByClass('mw-headline firstHeading')[0]

    var wpTextbox1 = doc.getElementById('wpTextbox1').value;
    var hiddenTxt = document.createElement("input");
    hiddenTxt.type = "hidden";
    hiddenTxt.value = wpTextbox1;
    hiddenTxt.id = "hiddenTxt";
    titre.appendChild(hiddenTxt);

    var wpStarttime = encodeURIComponent(editform['wpStarttime']);
    var hiddenStarttime = document.createElement("input");
    hiddenStarttime.type = "hidden";
    hiddenStarttime.value = wpStarttime;
    hiddenStarttime.id = "hiddenStarttime";
    titre.appendChild(hiddenStarttime);

    var wpEdittime = encodeURIComponent(editform['wpEdittime']);
    var hiddenEdittime = document.createElement("input");
    hiddenEdittime.type = "hidden";
    hiddenEdittime.value = wpEdittime;
    hiddenEdittime.id = "hiddenEdittime";
    titre.appendChild(hiddenEdittime);

// test recuperation token autrement

    var wpEditToken = encodeURIComponent(editform['wpEditToken']);
    var hiddenEditToken = document.createElement("input");
    hiddenEditToken.type = "hidden";
    hiddenEditToken.value = wpEditToken;
    hiddenEditToken.id = "hiddenEditToken";
    titre.appendChild(hiddenEditToken);

    var wpSection = encodeURIComponent(editform['wpSection']);
    var hiddenSection = document.createElement("input");
    hiddenSection.type = "hidden";
    hiddenSection.value = wpSection;
    hiddenSection.id = "hiddenSection";
    titre.appendChild(hiddenSection);

    afficheBlocScriptus(editFormSeek);

    };
}


function afficheBlocScriptus(contengut) {


    var texte = gml_XMLParse(contengut.responseText);

    if (document.ou == 0) {
        var bloc = getElementsByClass('mw-headline firstHeading')[0];
    } 
    else {
        var bloc = getElementsByClass('mw-headline')[document.ou].parentNode;
    }

    var form = document.createElement("form");
    form.className = 'ajaxedit';
    form.name = 'ajaxEditForm';
    form.method = 'get';
    form.action = "javascript:envoye2BlocScriptus();"; //redondant ? (non en cas de tòca entrada sus l'input de resumit) 

    var ajaxTxtarea = document.getElementById('hiddenTxt');
    var wpTextbox1 = ajaxTxtarea.value;

    var textarea = document.createElement("textarea");
    textarea.className = "ajaxTextarea";
    var lines = wpTextbox1.split(/\n/).length;
    var nbchars = wpTextbox1.length;

    textarea.appendChild(document.createTextNode(wpTextbox1));
    form.appendChild(textarea);

    var summary = document.createElement("input");
    summary.type = "Text";
    summary.name = "wpSummary";
    summary.id = "wpSummary"
    summary.value="Resumissetz vòstras modificacions"
    form.appendChild(summary);

    var save = document.createElement("input");
    save.type = "button";
    save.value = "Mandar"
    form.appendChild(save);

    var preview = document.createElement("input");
    preview.type = "button";
    preview.value = "Previsualizacion"
    form.appendChild(preview);

    var annuler = document.createElement("input");
    annuler.type = "button";
    annuler.value = "Anullar"
    form.appendChild(anullar);




    bloc.appendChild(form); 

    var largeur = form.offsetWidth;
    var colones = largeur*10/75;
    var nblines = nbchars/colones+lines;
    textarea.rows = nblines;

    save.addEventListener("click", envoye2BlocScriptus, false);
    annuler.addEventListener("click", annuleScriptus, false);
    preview.addEventListener("click", previsualisationScriptus, false);
}

function annuleScriptus() {

    if (document.ou == 0) {
        var bloc = getElementsByClass('mw-headline firstHeading')[0];
    } 
    else {
        var bloc = getElementsByClass('mw-headline')[document.ou].parentNode;
    }

    var form = getElementsByClass('ajaxedit')[0]
    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'))
    }
    var oldform = bloc.removeChild(form);


}

function envoye2BlocScriptus() {

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Resumissetz vòstras modificacions")) wpSummary = ""; 

    // recuperation des champ hidden

    var wpEdittime = document.getElementById('hiddenEdittime').value;
    var wpEditToken = document.getElementById('hiddenEditToken').value;
    var wpStarttime = document.getElementById('hiddenStarttime').value;

    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var seguit = '&wpWatchthis=1';
    } else {
      var seguit = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPedit = wpajaxScriptus.http({ url: wgServer + wgScriptPath + '/index.php?title=' 
                                 + encodeURIComponent(wgPageName) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')}); 
    apresModifScriptus();
}



function previsualisationScriptus() {

    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'));
    }

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Resumissetz vòstras modificacions")) wpSummary = ""; 

    // recuperacion dels camps hidden

    var wpEdittime = document.getElementById('hiddenEdittime').value;
    var wpEditToken = document.getElementById('hiddenEditToken').value;
    var wpStarttime = document.getElementById('hiddenStarttime').value;

    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var seguit = '&wpWatchthis=1';
    } else {
      var seguit = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPpreview = wpajaxScriptus.http({ url: wgServer + wgScriptPath + '/index.php?title=' 
                                 + encodeURIComponent(wgPageName) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + '&wpPreview=Prévisualisation'
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')});

    var parser = new DOMParser();

    var previewRetour = parser.parseFromString(document.HttpWPpreview.responseText, 'application/xhtml+xml');
    var previewHtml = previewRetour.getElementById('wikiPreview');
    var previewDiv = document.createElement("div");
    previewDiv = previewHtml;

    var titre = previewDiv.getElementsByTagName('h2')[0];

    var Aretirer = previewDiv.getElementsByTagName('div')[0];
    previewDiv.removeChild(Aretirer);

    var form = getElementsByClass('ajaxedit')[0];
 
    previewDiv = form.parentNode.parentNode.insertBefore(previewDiv, form.parentNode.nextSibling);
    previewDiv.style.border = "2px solid #FF8080";
    previewDiv.style.backgroundColor = "#FCFFE5";
    titre.style.color = "#FF8080";

    var fermeturePreview = document.createElement("span");
    fermeturePreview.style.fontSize = "xx-small";
    fermeturePreview.style.fontWeight = "normal";
    fermeturePreview.style.cssFloat = "none";
    fermeturePreview = titre.appendChild(fermeturePreview);
    fermeturePreview.innerHTML = '<a href="javascript:var temporari = document.getElementById(\'wikiPreview\').parentNode.removeChild(document.getElementById(\'wikiPreview\'));" title="Tampar la previsualizacion">tampar</a>'; //levar l'innerHTML

}

function apresModifScriptus() {

    annuleScriptus();

    var parser = new DOMParser();

    var doc = parser.parseFromString(document.HttpWPedit.responseText, 'application/xhtml+xml');
    var entirepage = doc.getElementById('bodyContent');
    var bodycontent = document.getElementById('bodyContent');
    var bodyparent = bodycontent.parentNode;
    var oldBody = bodyparent.removeChild(bodycontent);
    var newbody = document.createElement("div");
    newbody = entirepage;
    bodyparent.appendChild(newbody);

//   for(var i=0; i < onloadFuncts.length; i++) { onloadFuncts[i](); }
// test

	for (var i = 0; i < onloadFuncts.length; i++) {
		onloadFuncts[i]();
	}


}

var wpajaxScriptus = { // dempuèi http://fr.wikipedia.org/wiki/Utilisateur:EDUCA33E/LiveRC.js
  http: function(bundle) {
    // mandatory: bundle.url
    // optional:  bundle.async
    // optional:  bundle.method
    // optional:  bundle.headers
    // optional:  bundle.data
    // optional:  bundle.onSuccess (xmlhttprequest, bundle)
    // optional:  bundle.onFailure (xmlhttprequest, bundle)
    // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
    var xmlhttp;
        try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false}
 
    if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
          wpajaxScriptus.httpComplete(xmlhttp,bundle);
        }
      }
      xmlhttp.open(bundle.method ? bundle.method : "GET",bundle.url,bundle.async == false ? false : true);
      if (bundle.headers) {
        for (var field in bundle.headers)
          xmlhttp.setRequestHeader(field,bundle.headers[field]);
      }
      xmlhttp.send(bundle.data ? bundle.data : null); 
    }

    return xmlhttp;
  },
 
  httpComplete: function(xmlhttp,bundle) {

    if (xmlhttp.status == 200 || xmlhttp.status == 302) {
      if (bundle.onSuccess) {
        bundle.onSuccess(xmlhttp,bundle);
      } else if (bundle.onFailure) {
      bundle.onFailure(xmlhttp,bundle);
      } else {
      // A activer en debug mode ?
      if (xmlhttp.statusText != "OK") alert(xmlhttp.statusText);
      }
    }
  }
};

// Parser
if (document.implementation.createDocument) {
  var gml_xmlparser = new DOMParser();
}
 
function gml_XMLParse(string) {
  if (document.implementation.createDocument) {
    return gml_xmlparser.parseFromString(string, "text/xml");
  }
  return null;
}

addLoadEvent(Scriptus);
//