Difference between revisions of "MediaWiki:Common.js"

From DigiNet Wiki
Jump to: navigation, search
(Created page with "Any JavaScript here will be loaded for all users on every page load.: Most of it shamelessy grabbed from Wikimon.net, yes.: /************* General utility functions...")
 
(No difference)

Latest revision as of 13:46, 14 August 2014

/* Any JavaScript here will be loaded for all users on every page load. */
/* Most of it shamelessy grabbed from Wikimon.net, yes. */
 
/************* General utility functions *************/
 
 /* Test if an element has a certain class **************************************
 *
 * Description: Uses regular expressions and caching for better performance.
 * Maintainers: User:Mike Dillon, User:R. Koot, User:SG
 */
 
var hasClass = (function () {
    var reCache = {};
    return function (element, className) {
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
    };
 })();
 
 
function getElementsByClass (node, className, tagName) {
	if (node.getElementsByClassName && (tagName == undefined || tagName == null || tagName == '*')) return node.getElementsByClassName(className);
	var list = node.getElementsByTagName(tagName?tagName:'*');
	var array = new Array();
	var i = 0;
	for (i in list) {
		if (hasClass(list[i], className))
			array.push(list[i]);
	 }
	return array;
 }
 
/* Creates the method getElementsByClass, if unsupported from the browser */
if(!document.getElementsByClass) document.getElementsByClass = function(className) {
	return getElementsByClass(document, className, '*');
};
 
 
function getElementsByName (name, root) {
 if (root == undefined) root = document;
 var e = root.getElementsByTagName('*');
 var r = new Array();
 for (var i = 0; i < e.length; i++) {
	if (e[i].getAttribute('name') == name) r[r.length] = e[i];
 }
 return r;
}
 
 
 function getText (e) {
	 if (e.textContent) return e.textContent;
	  else if (e.innerText) return e.innerText;
	  else return null;
  }
 
 function setText (e, t) {
	 if (e.textContent) e.textContent = t;
	  else if (e.innerText) e.innerText = t;
	  else { e.textContent = t; e.innerText = t; } // entrambi nulli, non si può discriminare
	 return;
  }
 
 function appendText (e, t) {
	 if (e.textContent) e.textContent += t;
	  else if (e.innerText) e.innerText += t;
	  else { e.textContent = t; e.innerText = t; }
	 return;
  }
 
/* Create an Ajax request */
function createRequest () {
	if (window.XMLHttpRequest) { // Mozilla, Safari...
		return new XMLHttpRequest();
	 }
	 else if (window.ActiveXObject) { // IEmmerda
		return new ActiveXObject("Microsoft.XMLHTTP");
	 }
	return
 }
 
/* Returns the value of a cookie */
function getCookie(name) {
	if (document.cookie.length == 0) return null;
	var start = document.cookie.indexOf(name);
	if (start == -1) return null;
	start += name.length + 1;
	var end = document.cookie.indexOf(';', start);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(start,end));
 }
 
/* Adds a zero to the figures under 10 in the textual representation */
function addzero(n) {
	if (n<10) return '0' + n.toString();
	 else return n.toString();
 }
 
function addEvent(el, ev, f, capt) {
 if (capt == undefined) capt = false;
 if (el.addEventListener) el.addEventListener(ev, f, capt);
  else if (el.attachEvent) el.attachEvent('on' + ev, f);
 return;
}
 
function removeEvent(el, ev, f, capt) {
 if (capt == undefined) capt = false;
 if (el.removeEventListener) el.removeEventListener(ev, f, capt);
  else if (el.detachEvent) el.detachEvent('on' + ev, f);
 return;
}
 
 
var noFade = false;
function Fade (element, delay, i, rev, ratio) {
 if (noFade) return;
/* rev = sparizione; se !rev, ratio = opacità finale; se rev, ratio = opacità iniziale*/
 var start_time = new Date().getTime();
 var start_value = rev? ratio : 0;
 element.style.filter = "alpha(opacity=" + start_value * 100 + ")";
 element.style.opacity = start_value;
 if (!parseInt(element.style.width) && navigator.appName == "Microsoft Internet Explorer") element.style.width = element.offsetWidth + 'px';
 setTimeout(function() { Do()} , i);
 return;
 
 function Do() {
	 var cur_time = new Date().getTime();
	 var past_time = cur_time - start_time;
	 if (past_time >= delay) { /* ultima chiamata */
		var final_value = rev? 0 : ratio;
		element.style.filter = "alpha(opacity=" + final_value * 100 + ")";
		element.style.opacity = final_value;
		return;
	  }
	 var progress = past_time/delay;
	 var new_value = rev? ratio * (1 - progress) : ratio * progress;
	 element.style.filter = "alpha(opacity=" + new_value * 100 + ")";
	 element.style.opacity = new_value;
	 setTimeout(function() { Do(); } , i);
	 return;
	}
}
 
var noSlide = false;
function Slide(element, param, final_value, final_size, delay, i) {
 if (noSlide) return;
 /* NB: Il valore finale deve avere la stessa unità di misura di quello iniziale! */
 var start_time = new Date().getTime();
 var unit = 'px';
 if (typeof(final_value) == 'string') {
	 final_value = final_value.split(/\D/);
	 if (final_value.length > 1) unit = final_value[1];
	 final_value = parseFloat(final_value[0]);
  }
 var start_value = Get();
 var sub = (start_value > final_value)? true : false;
 var diff = Math.abs(start_value - final_value);
 var start_size;
 if (param == 'top' || param == 'bottom') start_size = element.parentNode.offsetHeight;
  else if (param == 'left' || param == 'right')	start_size = element.parentNode.offsetWidth;
 var diff_size = Math.abs(start_size - final_size);
 setTimeout( function() {Do(); } , i);
 return;
 
 function Do() {
	 var cur_time = new Date().getTime();
	 var past_time = cur_time - start_time;
	 if (past_time >= delay) { /* ultima chiamata */
		Set(final_value);
	 if (param == 'top' || param == 'bottom') element.parentNode.style.height = final_size + unit;
	  else if (param == 'left' || param == 'right') element.parentNode.style.width = final_size + unit;		
		return;
	  }
	 var progress = diff * past_time/delay;
	 new_value = (sub)? start_value - progress : start_value + progress;
	 Set(new_value);
	 new_size = (sub)? start_size - diff_size * past_time/delay: start_size + diff_size * past_time/delay;
	 if (param == 'top' || param == 'bottom') element.parentNode.style.height = new_size + unit;
	  else if (param == 'left' || param == 'right') element.parentNode.style.width = new_size + unit;
	 setTimeout(function() { Do(); } , i);
	 return;
 }
 
 function Get() {
	var ret;
	switch (param) {
		case 'top':
		 ret = element.style.top;
		 break;
		case 'bottom':
		 ret = element.style.bottom;
		 break;
		case 'left':
		 ret = element.style.left;
		 break;
		case 'right':
		 ret = element.style.right;
		 break;
		default:
		 return false;
	}
	if (/em/i.test(ret)) return parseFloat(ret);
	return (/\d+/.test(ret))? parseInt(ret) : 0;
  }
 
 function Set(v) {
	switch (param) {
		case 'top':
		 element.style.top = v + unit;
		 return;
		case 'bottom':
		 element.style.bottom = v + unit;
		 return;
		case 'left':
		 element.style.left = v + unit;
		 return;
		case 'right':
		 element.style.right = v + unit;
		 return;
		default:
		 return false;
	}
  }
}
 
/************* Application Functions ***************/
// ============================================================
// BEGIN Dynamic Navigation Bars (experimental)
// This script is from Wikipedia. For author attribution, please see http://en.wikipedia.org/w/index.php?title=MediaWiki:Common.js&action=history
 
 /** Collapsible tables *********************************************************
  *
  *  Description: Allows tables to be collapsed, showing only the header. See
  *               [[Wikipedia:NavFrame]].
  *  Maintainers: [[User:R. Koot]]
  */
 
 var autoCollapse = 0; // maximum number of visible bars
                       // By default, when loading a page
 var collapseCaption = "hide";
 var expandCaption = "show";
 
 function collapseTable( tableIndex )
 {
     var Button = document.getElementById( "collapseButton" + tableIndex );
     var Table = document.getElementById( "collapsibleTable" + tableIndex );
 
     if ( !Table || !Button ) {
         return false;
     }
 
     var Rows = Table.getElementsByTagName( "tr" ); 
 
     if ( Button.firstChild.data == collapseCaption ) {
         for ( var i = 1; i < Rows.length; i++ ) {
             Rows[i].style.display = "none";
         }
         Button.firstChild.data = expandCaption;
     } else {
         for ( var i = 1; i < Rows.length; i++ ) {
             Rows[i].style.display = Rows[0].style.display;
         }
         Button.firstChild.data = collapseCaption;
     }
 }
 
 function createCollapseButtons()
 {
     var tableIndex = 0;
     var NavigationBoxes = new Object();
     var Tables = document.getElementsByTagName( "table" );
 
     for ( var i = 0; i < Tables.length; i++ ) {
         if ( hasClass( Tables[i], "collapsible" ) && !Tables[i].id) {
             NavigationBoxes[ tableIndex ] = Tables[i];
             Tables[i].id = "collapsibleTable" + tableIndex;
 
             var Button     = document.createElement( "span" );
             var ButtonLink = document.createElement( "a" );
             var ButtonText = document.createTextNode( collapseCaption );
 
             Button.style.styleFloat = "right";
             Button.style.cssFloat = "right";
             Button.style.fontWeight = "normal";
             Button.style.textAlign = "right";
             Button.style.width = "6em";
 
             ButtonLink.setAttribute( "id", "collapseButton" + tableIndex );
             ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
             ButtonLink.appendChild( ButtonText );
 
             Button.appendChild( document.createTextNode( "[" ) );
             Button.appendChild( ButtonLink );
             Button.appendChild( document.createTextNode( "]" ) );
 
             var Header = Tables[i].getElementsByTagName( "tr" )[0].getElementsByTagName( "th" )[0];
             /* only add button and increment count if there is a header row to work with */
             if (Header) {
                 Header.insertBefore( Button, Header.childNodes[0] );
                 tableIndex++;
             }
         }
     }
 
     for ( var i = 0;  i < tableIndex; i++ ) {
         if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
             collapseTable( i );
         }
     }
 }
 
 /** Dynamic Navigation Bars (experimental) *************************************
  *
  *  Description: See [[Wikipedia:NavFrame]].
  *  Maintainers: UNMAINTAINED
  */
 
  // set up the words in your language
  var NavigationBarHide = '[' + collapseCaption + ']';
  var NavigationBarShow = '[' + expandCaption + ']';
 
  // set up max count of Navigation Bars on page,
  // if there are more, all will be hidden
  // NavigationBarShowDefault = 0; // all bars will be hidden
  // NavigationBarShowDefault = 1; // on pages with more than 1 bar all bars will be hidden
  var NavigationBarShowDefault = autoCollapse;
 
  // shows and hides content and picture (if available) of navigation bars
  // Parameters:
  //     indexNavigationBar: the index of navigation bar to be toggled
var noNavSlide = true;
function toggleNavigationBar(indexNavigationBar)  {
     var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
     var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
 
     if (!NavFrame || !NavToggle) {
         return false;
     }
 
     // if shown now
     if (NavToggle.firstChild.data == NavigationBarHide) {
		 if (!hasClass(NavFrame, 'no-slide') && !noNavSlide) NavSlide(NavFrame, true);
		 else {
			 for (
					 var NavChild = NavFrame.firstChild;
					 NavChild != null;
					 NavChild = NavChild.nextSibling
				 ) {
				 if ( hasClass( NavChild, 'NavPic' ) ) {
					 NavChild.style.display = 'none';
				 }
				 if ( hasClass( NavChild, 'NavContent') ) {
					 NavChild.style.display = 'none';
				 }
			 }
		 }
     NavToggle.firstChild.data = NavigationBarShow;
 
     // if hidden now
     } else if (NavToggle.firstChild.data == NavigationBarShow) {
         for (
                 var NavChild = NavFrame.firstChild;
                 NavChild != null;
                 NavChild = NavChild.nextSibling
             ) {
             if (hasClass(NavChild, 'NavPic')) {
                 NavChild.style.display = 'block';
             }
             if (hasClass(NavChild, 'NavContent')) {
                 NavChild.style.display = 'block';
             }
         }
		 if (!hasClass(NavFrame, 'no-slide') && !noNavSlide) NavSlide(NavFrame, false);
     NavToggle.firstChild.data = NavigationBarHide;
     }
  }
 
var NavigationBarSlideDelay = 600;
var NavigationBarSlideInterval = 70;
var NavigationBarFadeDelay = 400;
var NavigationBarFadeInterval = 70;
 
function NavSlide (NavFrame, close) {
/* close = chiusura */
 for (var NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling) {
	if ( hasClass( NavChild, 'NavPic' ) || hasClass( NavChild, 'NavContent') ) Slide(NavChild);
	}
	return;
 
 function Slide (element) {
 	 if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.userAgent[navigator.userAgent.indexOf("MSIE") + 5]) >= 8) return;
	 var fade = !hasClass(NavFrame, 'no-fade');
	 var start_time = new Date().getTime() + NavigationBarFadeDelay * ((close && fade)? 1.1 : 0);
	 var size = element.offsetHeight;
	 var start_value = close? 0: 0 - size;
	 var final_value = close? 0 - size : 0;
	 element.style.marginTop = start_value + 'px';
	 element.style.width = 'auto';
	 if (fade) {
		 if (close) Fade(element, NavigationBarFadeDelay, NavigationBarFadeInterval, true, 0.7);
		  else {
			element.style.filter = "alpha(opacity=0)";
			element.style.opacity = 0;
		  }
	  }
	 setTimeout(function() { Do(); } , NavigationBarSlideInterval + NavigationBarFadeDelay * ((close && fade)? 1.1 : 0));
	 return;
 
	 function Do() {
		 var cur_time = new Date().getTime();
		 var past_time = cur_time - start_time;
		 if (past_time >= NavigationBarSlideDelay) {
			element.style.marginTop = final_value + 'px';
			if (!close && fade) Fade(element, NavigationBarFadeDelay, NavigationBarFadeInterval, false, 1);
			if (close) element.style.display = 'none';
			return;
		  }
		 var progress = past_time/NavigationBarSlideDelay;
		 var new_value = close? final_value * progress : start_value * (1 - progress);
		 element.style.marginTop = new_value + 'px';
		 setTimeout(function() { Do(); } , NavigationBarSlideInterval);
		 return;
		}
 }
}
 
  // adds show/hide-button to navigation bars
  function createNavigationBarToggleButton()
  {
     var indexNavigationBar = 0;
     // iterate over all < div >-elements 
     var divs = document.getElementsByTagName("div");
     for(
             var i=0; 
             NavFrame = divs[i]; 
             i++
         ) {
         // if found a navigation bar
         if (hasClass(NavFrame, "NavFrame")) {
 
             indexNavigationBar++;
             var NavToggle = document.createElement("a");
             NavToggle.className = 'NavToggle';
             NavToggle.setAttribute('id', 'NavToggle' + indexNavigationBar);
             NavToggle.setAttribute('href', 'javascript:toggleNavigationBar(' + indexNavigationBar + ');');
 
             var NavToggleText = document.createTextNode(NavigationBarHide);
             NavToggle.appendChild(NavToggleText);
             // Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked)
             for(
               var j=0; 
               j < NavFrame.childNodes.length; 
               j++
             ) {
               if (hasClass(NavFrame.childNodes[j], "NavHead")) {
                 NavFrame.childNodes[j].appendChild(NavToggle);
               }
             }
             NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
         }
     }
     // if more Navigation Bars found than Default: hide all
     if (NavigationBarShowDefault < indexNavigationBar) {
         for(
                 var i=1; 
                 i<=indexNavigationBar; 
                 i++
         ) {
             toggleNavigationBar(i);
         }
     }
 
  }
 
 /** Code for replacing the Username ([[template:USERNAME]]) *******************************
  * Inserts user name into <span id="insertusername"></span>
  * By [[wikia:User:Splarka|Splarka]]
  */
 var disableUsernameReplace = false;
 function UserNameReplace() {
	if (disableUsernameReplace) return;
	var list = getElementsByClass(document.getElementsByTagName('body')[0], "insertusername", 'span');
	if (list.length < 1) return;
	if (wgUserName) {
		for (var i=0; UserName = list[i]; i++) {
			setText(UserName, wgUserName);
		 }
		return;
	 }
	var defaultText = "<Your Name>";
	var userpage = document.getElementById("pt-anonuserpage");
	if (userpage != null) {
		var IP = getText(userpage.getElementsByTagName('a')[0]);
		if (IP == null) return;
		for (var i=0; UserName = list[i]; i++) {
			if (getText(UserName) == defaultText)
				setText(UserName, IP);
		 }
		return;
	 }
	var httpRequest;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	    httpRequest = new XMLHttpRequest();
	 } else if (window.ActiveXObject) { // IE
	    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	 }
	var id = setTimeout(function() { httpRequest.abort();}, 30000);
	httpRequest.onreadystatechange = function () {
		if (httpRequest.readyState != 4) return;
		clearTimeout(id);
		if (httpRequest.status != 200) return;
		if (httpRequest.responseXML == null)  return;
		var IP = httpRequest.responseXML.getElementsByTagName('userinfo')[0].getAttribute("name");
		if (IP == null) return;
		for (var i=0; UserName = list[i]; i++) {
			if (getText(UserName) == defaultText)
				setText(UserName, IP);
		 }
		return;
	 }
	httpRequest.open('GET', wgServer + wgScriptPath + "/api.php?action=query&meta=userinfo&format=xml", true);
	httpRequest.send('');
	return;
 }
 
 /** Code for replacing the Username ([[template:USERNAME]]) *******************************
  * Inserts user name into <span id="insertusername"></span>
  * By [[wikia:User:Splarka|Splarka]]
  */
 var disableUsernameReplace = false;
 function UserNameReplace() {
	if (disableUsernameReplace) return;
	var list = getElementsByClass(document.getElementsByTagName('body')[0], "insertusername", 'span');
	if (list.length < 1) return;
	if (wgUserName) {
		for (var i=0; UserName = list[i]; i++) {
			setText(UserName, wgUserName);
		 }
		return;
	 }
	var defaultText = "<tuo nome>";
	var userpage = document.getElementById("pt-anonuserpage");
	if (userpage != null) {
		var IP = getText(userpage.getElementsByTagName('a')[0]);
		if (IP == null) return;
		for (var i=0; UserName = list[i]; i++) {
			if (getText(UserName) == defaultText)
				setText(UserName, IP);
		 }
		return;
	 }
	var httpRequest;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	    httpRequest = new XMLHttpRequest();
	 } else if (window.ActiveXObject) { // IE
	    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	 }
	var id = setTimeout(function() { httpRequest.abort();}, 30000);
	httpRequest.onreadystatechange = function () {
		if (httpRequest.readyState != 4) return;
		clearTimeout(id);
		if (httpRequest.status != 200) return;
		if (httpRequest.responseXML == null)  return;
		var IP = httpRequest.responseXML.getElementsByTagName('userinfo')[0].getAttribute("name");
		if (IP == null) return;
		for (var i=0; UserName = list[i]; i++) {
			if (getText(UserName) == defaultText)
				setText(UserName, IP);
		 }
		return;
	 }
	httpRequest.open('GET', wgServer + wgScriptPath + "/api.php?action=query&meta=userinfo&format=xml", true);
	httpRequest.send('');
	return;
 }
 
/* Class that adds' target = '_blank' "to link */
function target_blank () {
 var tags = getElementsByClass(document.getElementsByTagName('body')[0], "target-blank");
 if (tags == null) return;
 var i, j, links;
 for (i=0; i < tags.length; i++) {
	links = tags[i].getElementsByTagName('a');
	for (j=0; j < links.length; j++) links[j].target = '_blank';
 }
 return;
}
 
/* View notes as tooltip */
/* by Sanjilops - http://nonciclopedia.wikia.com/wiki/Utente:Sanjilops */
var disablereftooltip = false;
function ref_tooltip () {
 if (disablereftooltip) return;
 var refs = getElementsByClass(document.getElementById('bodyContent'), "reference", 'sup');
 if (!refs) return;
 for (var i = 0; i < refs.length; i++) Do(refs[i]);
 return;
 
 function Do (ref) {
	var span = document.createElement('span');
	var id = ref.id.substr('cite_ref-'.length);
	span.className = "reference-tt";
	span.id = "cite_tt-" + id;
	var li = document.getElementById('cite_note-' + id.replace(/_(\d+)-\d+$/, '-$1'));
	if (!li) return;
	var temp = li.innerHTML;
	temp = temp.split(/^.+a href=\"#cite_ref-.+\" title=\"\">.+?<\/a>(<\/sup>)? /);
	span.innerHTML = (temp.length)? temp[temp.length - 1] : temp;
	if (ref.offsetLeft < document.getElementById('bodyContent').offsetWidth/2) span.style.left = (ref.offsetWidth - 1) + 'px';
	 else span.style.right =  (ref.offsetWidth - 1) + 'px';
	temp = getText(span);
	temp = temp.length * 12;
	span.style.width = (temp < 400)? temp + 'px' : "400px";
	ref.appendChild(span);
	return;
 }
}