Wikizionario:Monobook.js/Utils.js

Da Wikizionario, il dizionario a contenuto aperto.

//

//Questa variabile contiene il nome del browser utilizzato. Molto utile per evitare problemi
// di incompatibilita' tra la varie funzioni Javascript
// Si autovalorizza. Le sottovariabili da usare sono "BrowserDetect.browser", "BrowserDetect.version"
// e "BrowserDetect.OS"
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)    {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {     string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {        // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {         // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

// Grazie a [[:en:User:Topaz]]
function xmlhttpreq()
{
  if (window.XMLHttpRequest)
    xmlhttpobj = new XMLHttpRequest()
  else
  {
    try
    {
      xmlhttpobj = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        xmlhttpobj = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        xmlhttpobj = null;
      }
    }
  }
  return xmlhttpobj;
}

// Grazie a [[:en:User:Topaz]]
function doreq(url,postdata,headers)
{
  var req = xmlhttpreq();
  req.open(postdata?"POST":"GET", url, false);
  for(header in headers)
    req.setRequestHeader(header,headers[header]);
  req.send(postdata||null);
  return req;
}

// Grazie a [[:en:User:Topaz]]
function setpagecontent(pagename,content,summary,watch)
{
  var prelimresp = doreq("/w/index.php?title="+pagename+"&action=submit");
  var edittime = prelimresp.responseText.match(/\<input type='hidden' value="(\d+)" name="wpEdittime" \/\>/)[1];
  var edittoken = prelimresp.responseText.match(/\<input type='hidden' value="([0-9a-f]+\\?)" name="wpEditToken" \/\>/)[1];
  doreq("/w/index.php?title="+pagename+"&action=submit",
      "wpEdittime="+edittime+
      "&wpEditToken="+edittoken+
      "&wpTextbox1="+escape(content)+
      "&wpSummary="+escape(summary)+
      (watch?"&wpWatchthis=on":"")+
      "&wpSection=&wpSave=Save+page",
      {"Content-Type":"application/x-www-form-urlencoded"});
}

// Grazie a [[:en:User:Topaz]]
function getpagecontent(pagename)
{
  var req = doreq("/w/index.php?title="+pagename+"&action=edit");
  var content = req.responseText.match(/\<textarea[\w\W]*?\>([\w\W]*?)\<\/textarea\>/)[1];
  content = content.replace(/\&lt\;/gi, "<");
  content = content.replace(/\&gt\;/gi, ">");
  content = content.replace(/\&quot\;/gi, "\"");
  content = content.replace(/\&amp\;/gi, "&");
  return content;
}

// Recupera il valore di un cookie
function GetCookie(name)
{
  var cookie = ' ' + document.cookie;
  var search = ' ' + name + '=';
  var setStr = '';
  var offset = 0;
  var end = 0;
  offset = cookie.indexOf(search);
  if (offset != -1)
  {
    offset += search.length;
    end = cookie.indexOf(';', offset)
    if (end == -1)
      end = cookie.length;
    setStr = cookie.substring(offset, end);
    setStr = setStr.replace(/\\+/g, ' ');
    setStr = decodeURIComponent(setStr);
  }
  return(setStr);
}

// Setta il valore di un cookie
function SetCookie(name, value, expires, path, domain, secure)
{
  var cookie = name + '=' + encodeURIComponent(value);
  if (expires != null)
    cookie += '; expires=' + expires
  if (path != null)
    cookie += '; path=' + path;
  if (domain != null)
    cookie += '; domain=' + domain;
  if (secure != null)
    cookie += '; secure';
  document.cookie = cookie;
}

// Crea un nuovo portlet e lo aggiunge dopo "strumenti"
function createPortlet(id,title)
{
   var newPortlet = document.createElement('div');
   newPortlet.innerHTML = "<div class='portlet' id='"+id+"'><h5>"+title+"</h5><div class='pBody'><ul></ul></div>";
   document.getElementById("p-tb").parentNode.insertBefore(newPortlet, document.getElementById("p-tb").nextSibling);
}

//Aggiunge qualcosa ad un portlet.
//PARAMS:
//*  id: id del portlet.
//* obj: L'oggetto da aggiungere
function addToPortlet(id, obj)
{
    var f = document.getElementById(id);

    f = f.getElementsByTagName("div")[0];
    f.appendChild(obj);
}

//Elimina un Node
function RemoveNode(id)
{
    var node = document.getElementById(id);
    node.parentNode.removeChild(node);
}

// Aggiunge un generico tab
function addlilink(tabs, url, name, id)
{
    var na = document.createElement('a');
    na.href = url;
    na.appendChild(document.createTextNode(name));
    var li = document.createElement('li');
    li.id = id;
    li.appendChild(na);
    tabs.appendChild(li);
    return li;
}

// Aggiunge un tab come menu
function addlimenu(tabs, name, id)
{
    var na = document.createElement('a');
    na.href = '#';
    var mn = document.createElement('ul');
    na.appendChild(document.createTextNode(name));
    var li = document.createElement('li');
    li.id = id;
    li.className = 'tabmenu';
    li.appendChild(na);
    li.appendChild(mn);
    tabs.appendChild(li);
    return li;
}

// recupera un parametro dall'URL
function getParam(name)
{
  if(location.search)
  {
    for(var x in location.search.substring(1).split('&'))
    {
      var eq = x.indexOf('=');
      if(x.substring(0, eq) == name) return x.substring(eq + 1);
    }
  }
  return '';
}

//Aggiunge un pulsante generico alla Toolbar
function addToolbarButton(id, href, src, alt, title)
{
  var toolbar = document.getElementById("toolbar");
  var today = new Date();
  var anno= today.getYear()+1900;
  var mese = arrayMese[today.getMonth()];

  var tmp = document.createElement("a");
  tmp.id = id;
  tmp.href = href;
  var imag = document.createElement("img");
  imag.setAttribute('src', src);
  imag.setAttribute('alt', alt);
  imag.setAttribute('title', title);
  tmp.appendChild(imag);
  toolbar.appendChild(tmp);
}

//Aggiunge del testo alla pagina
//text: testo da aggiungere
//summary: oggetto della modifica
//n: 0=aggiungi in cima; 1=aggiungi in coda
function addText(text, summary, n)
{
   // copia il frame di wikEd (http://en.wikipedia.org/wiki/User:Cacycle/wikEd.js) nella wpTextbox1 textarea
   if (typeof(wikEdUseWikEd) != 'undefined')
      if (wikEdUseWikEd == true)
         WikEdUpdateTextarea();

  wpTextbox1=document.getElementById("wpTextbox1");
  if (n == 0)
    wpTextbox1.value=text + "\n" +wpTextbox1.value;
  else
    wpTextbox1.value=wpTextbox1.value + text;
  summ=document.getElementById("wpSummary");
  summ.value=summ.value+summary;

   // copia la wpTextbox1 textarea nel frame di wikEd 
   if (typeof(wikEdUseWikEd) != 'undefined')
      if (wikEdUseWikEd == true)
         WikEdUpdateFrame();
}

//Aggiunge del testo alla pagina (nella posizione del cursore)
//myValue: testo da aggiungere
//summary: oggetto della modifica
//myValue2: se non e'  vuoto il testo diventa  <myValue><testo evidenziato><myValue2>
//                  se e' vuoto il <testo evidenziato> viene sostituito da <myValue>
//offset: prima di uscire, di quanti caratteri devo spostare il cursore rispetto al punto di partenza?
function addTextAtCursor(myValue,summary,myValue2,offset)
{
   wpTextbox1=document.getElementById("wpTextbox1");
   // se stiamo usando anche il wikEd sfrutto la sua funzione per la sostituzione del testo
   var wikEdited="no";
   if (typeof(wikEdUseWikEd) != 'undefined')
      if (wikEdUseWikEd == true)
      {
         insertTags(myValue, myValue2, "");
         wikEdSummaryText.value = wikEdSummaryText.value+summary;
         wikEdited="yes";
      }

   //se e' stato usato wikEd abbiamo gia' finito
   if (wikEdited=="yes") return;

   //ricorda la posizione del cursore
   var curPos=getCurPos();
   var selDim=0;
   //IE e Opera support
   if (document.selection)
   {
      wpTextbox1.focus();
      sel = document.selection.createRange();
      selDim = sel.text.length;
      if (myValue2=="")
         sel.text = myValue;
      else
      {
         //la selezione partira' dalla fine del primo tag
         curPos += myValue.length;

         // piccola aggiustatina per Opera
         if (BrowserDetect.browser == "Opera")
            curPos -= selDim;
            
         sel.text = myValue + sel.text + myValue2;
      }
   }
   //MOZILLA/NETSCAPE support
   else if (wpTextbox1.selectionStart || wpTextbox1.selectionStart == '0') 
   {
      // ricorda la posizione dello scroll della textarea
      var scrollTop, scrollLeft;
      if (wpTextbox1.type == 'textarea' && typeof wpTextbox1.scrollTop != 'undefined')
      {
         scrollTop = wpTextbox1.scrollTop;
         scrollLeft = wpTextbox1.scrollLeft;
      } 

      var startPos = wpTextbox1.selectionStart;
      var endPos = wpTextbox1.selectionEnd;
      selDim = endPos - startPos;
     
      if (myValue2=="")
      {
         wpTextbox1.value = wpTextbox1.value.substring(0, startPos)
         + myValue
         + wpTextbox1.value.substring(endPos, wpTextbox1.value.length);
      }
      else
      {
         curPos += myValue.length; //la selezione partira' dalla fine del primo tag
         wpTextbox1.value = wpTextbox1.value.substring(0, startPos)
         + myValue + wpTextbox1.value.substring(startPos,endPos) + myValue2
         + wpTextbox1.value.substring(endPos, wpTextbox1.value.length);
      }
      
      // torna alla posizione di scroll di partenza
      if (typeof scrollTop != 'undefined')
      {
         wpTextbox1.scrollTop = scrollTop;
         wpTextbox1.scrollLeft = scrollLeft;
      } 
   }
   else
      wpTextbox1.value += myValue;

   summ=document.getElementById("wpSummary");
   summ.value=summ.value+summary;
   
   // Setta la posizione del cursore aggiungendo l'offset
   if (offset == null) offset=0;
   setCurPos(curPos+offset,curPos+offset+selDim);
}

function getCurPos()
{
   wpTextbox1=document.getElementById("wpTextbox1");
   wpTextbox1.focus(); // altrimenti lo 'stored_range' si rifersce al testo esterno alla finestra 
var CaretPos = 0;

   //Opera Support
   if (BrowserDetect.browser == "Opera")
   {
      var Sel = document.selection.createRange ();
Sel.moveStart ('character', -wpTextbox1.value.length);
CaretPos = Sel.text.length;
   }
   // IE Support
else if (document.selection)
   {
      // IE non possiede metodi per recuperare la posizione del cursore in una textarea
      // Quello che segue e' un metodo scamuzzo creato per aggirare il problema

      // La selezione corrente
      var range = document.selection.createRange();

      // la usaremo ome selezine 'farlocca'
      var stored_range = range.duplicate();

      // Seleziona tutto il testo
      stored_range.moveToElementText(wpTextbox1);

      // Ora sposta il termine del 'farlocco' al punto finale della selezione originale
      stored_range.setEndPoint('EndToEnd', range);

      // Ora calcola il punto iniziale e finale
      CaretPos = stored_range.text.length - range.text.length;

      // Il punto finale e', al momento, inutile
      //element.selectionEnd = element.selectionStart + range.text.length;
      
      // Non so perche', ma questo metodo conta doppio i caratteri '\n'
      // Bisogna taroccare il risultato per renderlo esatto
      conteggioCR = 0; // conta i 'Carriage Return'

      for (var i=0;i<CaretPos;i++)
         if (wpTextbox1.value.charAt(i) == '\n')
            conteggioCR++;

      CaretPos -= conteggioCR; //aggiusta la posizione della selezione

   }
// Firefox support
else if (wpTextbox1.selectionStart || wpTextbox1.selectionStart == '0')
CaretPos = wpTextbox1.selectionStart;

   return (CaretPos);
}

function setCurPos(newPos,newPos2)
{
   wpTextbox1=document.getElementById("wpTextbox1");

   if (wpTextbox1.createTextRange)
   {
var range = wpTextbox1.createTextRange();
range.collapse(true);
range.moveEnd('character', newPos2);
range.moveStart('character', newPos);
range.select();
   }
   else if (wpTextbox1.setSelectionRange)
   {
      wpTextbox1.focus();
      wpTextbox1.setSelectionRange(newPos, newPos2);
   }
}
//