/*
 * QPreview
 * 
 * Permet una previsualizacion rapida sens recargar la pagina
 * Aficha : * lo tèxt provesit pel servidor
             * las categorias e interwikis emulats en local
 * Aficha pas : * la previsualizacion del resumit
                   * los modèls utilizats
                   * autres daquòses rares coma las colors GeSHi (còde de programacion colorat)
 * Atencion : las categorias e interwikis son emulats localament e pòdon de còps èsser incorrèctes
 * (mancants se son incluses dins un modèl, afichats alara que son dins un includeonly, etc.)
 * 
 * Autor inicial : en:Alex Smotrov sus en:User:Alex Smotrov/qpreview.js,
 *  completat per fr:Seb35 per afichar los interwikis e las categorias
 * Data de la darrièra revision : 21 de novembre de 2007
 */

// Còde :

Illustration
var qPreviewLang = '|aa|ab|af|ak|als|am|an|ang|ar;العربية|arc|as|ast|av|ay|az;Azərbaycan|ba|bar|bat-smg|be|be-x-old|bg;Български|bh|bi|bm|bn;বাংলা|bo|bpy;ইমার ঠার/বিষ্ণুপ্রিয়া মণিপুরী|br;Brezhoneg|bs;Bosanski|bug|bxr|ca;Català|cbk-zam|cdo|ce|ceb;Cebuano|ch|cho|chr|chy|closed-zh-tw|co|cr|cs;Česky|csb|cu|cv|cy;Cymraeg|da;Dansk|de;Deutsch|diq|dv|dz|ee|el;Ελληνικά|eml|en;English|eo;Esperanto|es;Español|et;Eesti|eu;Euskara|fa;فارسی|ff|fi;Suomi|fiu-vro|fj|fo|fr;Français|frp|fur|fy|ga|gd|gl;Galego|glk|gn|got|gu|gv|ha|hak|haw|he;עברית|hi;हिन्दी|ho|hr;Hrvatski|hsb|ht|hu;Magyar|hy|hz|ia|id;Bahasa Indonesia|ie|ig|ii|ik|ilo|io;Ido|is;Íslenska|it;Italiano|iu|ja;日本語|jbo|jv;Basa Jawa|ka;ქართული|kab|kg|ki|kj|kk|kl|km|kn|ko;한국어|kr|ks|ksh|ku|kv|kw|ky|la;Latina|lad|lb;Lëtzebuergesch|lbe|lg|li|lij|lmo;Lumbaart|ln|lo|lt;Lietuvių|lv;Latviešu|map-bms|mg|mh|mi|mk;Македонски|ml|mn|mo|mr;मराठी|ms;Bahasa Melayu|mt|mus|my|mzn|na|nah|nan|nap;Nnapulitano|nds;Plattdüütsch|nds-nl|ne|new;नेपाल भाषा|ng|nl;Nederlands|nn;Norsk (nynorsk)|no;Norsk (bokmål)|nov|nrm|nv|ny|oc|om|or|os|pa|pag|pam|pap|pdc|pi|pih|pl;Polski|pms|ps|pt;Português|qu|rm|rmy|rn|ro;Română|roa-rup|roa-tara|ru;Русский|ru-sib|rw|sa|sc|scn;Sicilianu|sco|sd|se|sg|sh;Srpskohrvatski / Српскохрватски|si|simple;Simple English|sk;Slovenčina|sl;Slovenščina|sm|sn|so|sq;Shqip|sr;Српски / Srpski|ss|st|su;Basa Sunda|sv;Svenska|sw|ta;தமிழ்|te;తెలుగు|tet|tg|th;ไทย|ti|tk|tl|tlh|tn|to|tokipona|tpi|tr;Türkçe|ts|tt|tum|tw|ty|udm|ug|uk;Українська|ur|uz|ve|vec|vi;Tiếng Việt|vls|vo;Volapük|wa|war|wo|wuu|xal|xh|yi|yo|za|zea|zh;中文|zh-classical|zh-min-nan|zh-yue|zu|';

function qPreviewButton()
{
 sauv = document.getElementById('wpSave');
 if(!sauv) return;
 if(!document.getElementById('p-lang'))
 {
  newDiv = document.createElement('div');
  newDiv.id = 'p-lang';
  newDiv.setAttribute('class', 'portlet');
  newDiv.style.display = 'none';
  newDiv.innerHTML = '<h5>Autras lengas</h5><div class="pBody"><ul></ul></div>';
  toolbox = document.getElementById('p-tb');
  toolbox.parentNode.insertBefore(newDiv, toolbox.nextSibling);
 }
 if(!document.getElementById('catlinks'))
 {
  div = document.getElementsByTagName('div');
  for(i=0; i<div.length; i++)
  {
   if(div[i].className == 'printfooter')
   {
    newDiv = document.createElement('div');
    newDiv.id = 'catlinks';
    newDiv.style.display = 'none';
    div[i].parentNode.insertBefore(newDiv, div[i].nextSibling);
    break;
   }
  }
 }
 newBtn = document.createElement('input');
 newBtn.type = 'button';
 newBtn.value = 'QPreview';
 newBtn.onclick = qPreview;
 newBtn.id = 'btnQPreview';
 sauv.parentNode.insertBefore(newBtn, sauv.nextSibling);
}
addOnloadHook(qPreviewButton);

function qPreview()
{
 var qPreviewLanguage = wgServer.match(/.*\/\/(commons|incubator|meta|species|wikimediafoundation|www)/i) ? '' : wgServer.match(/.*\/\/([a-z-]*)\./i)[1];
 var divPreview = document.getElementById('wikiPreview');
 if (!divPreview) return;
 var btnQPreview = document.getElementById('btnQPreview');
 btnQPreview.value = 'Paciéncia…';
 var qPreviewEnd = false;
 qPreviewTextbox = document.getElementById('wpTextbox1').value;
 if(document.editform.wpSection.value == 'new') qPreviewTextbox = '== '+document.editform.wpSummary.value+" ==\n"+qPreviewTextbox;
 qPreviewAjax1 = sajax_init_object();
 qPreviewAjax2 = sajax_init_object();
 
 // Tractament del tèxt
 qPreviewAjax1.open('POST', document.editform.action+'&live', true);
 Boundary = '--------p1415';
 qPreviewAjax1.setRequestHeader('Content-Type', 'multipart/form-data; boundary='+Boundary);
 PostData = '--' + Boundary
  + '\nContent-Disposition: form-data; name="wpTextbox1"\n\n'
  + qPreviewTextbox + '\n--'+Boundary;
 if (qPreviewAjax1.overrideMimeType) qPreviewAjax1.overrideMimeType('text/html');
 qPreviewAjax1.onreadystatechange = function()
 {
  if (qPreviewAjax1.readyState != 4) return;
  html = qPreviewAjax1.responseText;
  html = html.replace(/<br style="clear: both;" \/>/,'').replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'"').replace(/&amp;/g,'&').replace(/&apos;/g,"'");
  divPreview.innerHTML = html;
  if(qPreviewEnd) btnQPreview.value = 'QPreview';
  qPreviewEnd = true;
 };
 qPreviewAjax1.send(PostData);
 
 // Tractament de las categorias
 reg1 = new RegExp(' ','g'); reg2 = new RegExp('\\|.*');
 regexCat = new RegExp('\\[\\[ *(?:Categoria|Category) *: *(.*)\\]\\]', 'gi');
 qPreviewCat = qPreviewTextbox.match(regexCat);
 if(!qPreviewCat) { document.getElementById('catlinks').style.display = 'none'; if(qPreviewEnd) btnQPreview.value = 'QPreview'; qPreviewEnd = true; }
 else
 {
  qPreviewTemp = '';
  for(i=0;i<qPreviewCat.length;i++)
  {
   qPreviewCat[i] = 'Categoria:'+qPreviewCat[i].replace(regexCat, '$1').replace(reg2, '');
   if(qPreviewCat[i] == 'Categoria:') qPreviewCat.splice(i--, 1);
   else qPreviewTemp += qPreviewCat[i]+'|';
  }
  if(qPreviewTemp)
  {
   qPreviewAjax2.open('GET', wgServer+'/w/api.php?action=query&format=xml&prop=info&redirects&titles=' + qPreviewTemp.substr(0, qPreviewTemp.length-1), true);
   qPreviewAjax2.onreadystatechange = function()
   {
    if(qPreviewAjax2.readyState != 4) return;
    qPreviewTemp = '';
    xmlDoc = qPreviewAjax2.responseXML;
    normalized = xmlDoc.getElementsByTagName('normalized');
    if(normalized.length) normalized = normalized[0].getElementsByTagName('n');
    redirects = xmlDoc.getElementsByTagName('redirects');
    if(redirects.length) redirects = redirects[0].getElementsByTagName('r');
    pages = xmlDoc.getElementsByTagName('pages')[0].getElementsByTagName('page');
    for(i=0; i<qPreviewCat.length; i++)
    {
     cat = qPreviewCat[i];
     missing = false;
     redirect = false;
     for(j=0; j<normalized.length; j++) if(normalized[j].getAttribute('from') == cat) { cat = normalized[j].getAttribute('to'); break; }
     for(j=0; j<pages.length; j++) if(pages[j].getAttribute('title') == cat && pages[j].getAttribute('missing') == '') { missing = true; break; }
     for(j=0; j<redirects.length; j++) if(redirects[j].getAttribute('from') == cat) { redirect = redirects[j].getAttribute('to'); break; }
     qPreviewTemp += '<span dir="ltr"><a href="/wiki/'+cat.replace(reg1, '_')+'" title="'+cat+'"'+(missing ? ' class="new"' : '')+(redirect ? ' style="font-style:italic;"' : '')+'>'+cat.replace(/Categoria:(.*)/, '$1')+'</a></span> • ';
    }
    qPreviewTemp = '<p class="catlinks"><a href="/wiki/Categoria:Acuèlh" title="Categoria:Acuèlh">Categoria'+(pages.length > 1 ? 's' : '')+' </a>: '+qPreviewTemp.substr(0, qPreviewTemp.length-5)+'</p>';
    document.getElementById('catlinks').innerHTML = qPreviewTemp;
    document.getElementById('catlinks').style.display = 'block';
    if(qPreviewEnd) btnQPreview.value = 'QPreview';
    qPreviewEnd = true;
   };
   qPreviewAjax2.send(null);
  }
  else { document.getElementById('catlinks').style.display = 'none'; if(qPreviewEnd) btnQPreview.value = 'QPreview'; qPreviewEnd = true; }
 }
 
 // Tractament dels interwikis
 qPreviewIw = '';
 reg3 = new RegExp('\\|'); reg4 = new RegExp('(.*)]'); reg5 = new RegExp(';(.*)');
 regexIw = new RegExp('\\[\\[ *(\\w{2,12}) *: *(.*)\\]\\]', 'gi');
 result = qPreviewTextbox.match(regexIw);
 if(!result) { document.getElementById('p-lang').style.display = 'none'; return; }
 for(i=0;i<result.length;i++)
 {
  r1 = result[i].replace(regexIw, '$1');
  r2 = result[i].replace(regexIw, '$2').replace(reg1, '_');
  r3 = qPreviewLang.search(RegExp('\\|'+r1+'(?:;|\\|)', 'i'));
  if(r1 == qPreviewLanguage) { r3 = -1; qPreviewIw += '<li class="interwiki-'+r1+'"><b>Atencion</b> : lenga <b><u><i>'+r1+'</i></u></b> en interwiki</li>'; }
  if(r3 != -1) { r3 = qPreviewLang.substr(r3+1).replace(reg3,']'); r3 = reg4.exec(r3)[1]; qPreviewIw += '<li class="interwiki-'+r1+'"><a href="//'+r1+'.wikipedia.org/wiki/'+r2+'">'+(r3.indexOf(';')!=-1 ? reg5.exec(r3)[1] : 'Lenga \''+r1+'\'')+'</a></li>'; }
 }
 document.getElementById('p-lang').getElementsByTagName('ul')[0].innerHTML = qPreviewIw;
 if(qPreviewIw) document.getElementById('p-lang').style.display = 'block';
 else document.getElementById('p-lang').style.display = 'none';
}
//Fin del còde