MediaWiki:Common.js

From Bulbapedia, the community-driven Pokémon encyclopedia.
Jump to navigationJump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* <pre> */
/* Any JavaScript here will be loaded for all users on every page load. */

/**** class CollapsibleTables.js
 * (c) 2008 by Patrick Westerhoff [poke]
 *
 * This class allows to make tables collapsible and adds a show/hide button to
 * affected tables. Tables which class attribute contains 'collapsible' or
 * 'expandable' are affected by this class and can be collapsed; the latter
 * automatically hides the content of all sections.
 * Header rows are used to divide the table into sections which can be collapsed
 * separately. By default the first row of the table is interpreted as a header
 * row, however this can be overwritten by adding 'collapsible' to the class
 * attribute of header rows. You can also hide a section individually by default
 * when in 'collapsible' mode by using 'expandable' as the row's class name
 * instead.
 */

function CollapsibleTables ()
{
  var classCollapsible = 'collapsible';
  var classExpandable  = 'expandable';
  var linkTextShow     = '[show]';
  var linkTextHide     = '[hide]';
  
  var reCollapsible    = new RegExp( '(?:\\s|^)' + classCollapsible + '(?:\\s|$)' );
  var reExpandable     = new RegExp( '(?:\\s|^)' + classExpandable  + '(?:\\s|$)' );
  var sections         = new Array();
  
  // link element
  var linkElement               = document.createElement( 'a' );
  linkElement.style.fontSize    = '85%';
  linkElement.style.fontWeight  = 'normal';
  linkElement.style.width       = '3em';
  linkElement.style.cssFloat    = 'right';
  linkElement.style.styleFloat  = 'right';
  linkElement.style.textAlign   = 'center';
  linkElement.style.marginLeft  = '1em';
  linkElement.style.padding     = '0px 3px';
  linkElement.href              = 'javascript:void(0);';
  
  initialize();
  
  /** private void initialize () :: initializes CollapsibleTables class **/
  function initialize ()
  {
    if ( mw.config.get("wgIsArticle") == false && window.location.href.indexOf( 'action=submit' ) < 0 )
      return;
    
    var docContent    = document.getElementById( 'bodyContent' ) || document.getElementById( 'article' ) || document.getElementById( 'mw_contentholder' );
    var tables        = docContent.getElementsByTagName( 'table' );
    var sectionId     = -1;
    var defaultStatus;
    
    for ( var i = 0, n = tables.length; i < n; i++ )
    {
      if ( reCollapsible.test( tables[i].className ) )
        defaultStatus = true;
      else if ( reExpandable.test( tables[i].className ) )
        defaultStatus = false;
      else
        continue;
      
      var tableRows    = tables[i].rows;
      var sectionFound = false;
      var status       = false;
      
      for ( var j = 0, m = tableRows.length; j < m; j++ )
      {
        if ( reCollapsible.test( tableRows[j].className ) )
          status = true;
        else if ( reExpandable.test( tableRows[j].className ) )
          status = false;
        else
        {
          if ( sectionFound )
          {
            sections[ sectionId ].content.push( tableRows[j] );
            tableRows[j].style.display = sections[ sectionId ].status ? '' : 'none';
          }
          
          continue;
        }
        
        var section     = new Object();
        section.header  = tableRows[j];
        section.content = new Array();
        section.status  = defaultStatus ? status : false;
        
        sections[ ++sectionId ] = section;
        sectionFound            = true;
        
        initHeaderRow( tableRows[j], sectionId, section.status );
      }
      
      if ( sectionFound == false )
      {
        var section       = new Object();
        section.header    = tableRows[0];
        section.content   = new Array();
        section.status    = defaultStatus;
        
        for ( var j = 1; j < tableRows.length; j++ )
        {
          section.content.push( tableRows[j] );
          tableRows[j].style.display = section.status ? '' : 'none';
        }
        
        sections[ ++sectionId ] = section;
        
        initHeaderRow( tableRows[0], sectionId, defaultStatus );
      }
    }
  }
  
  /** private void initHeaderRow ( headerRow, sectionId, sectionStatus ) :: adds show/hide button **/
  function initHeaderRow ( headerRow, sectionId, sectionStatus )
  {
    var lastCell, link;
    
    headerRow.id = 'collapsible-section_' + sectionId;
    lastCell     = headerRow.cells[ headerRow.cells.length - 1 ];
    link         = linkElement.cloneNode( false );
    link.onclick = toggleSection;
    link.appendChild( document.createTextNode( sectionStatus ? linkTextHide : linkTextShow ) );
    
    lastCell.insertBefore( link, lastCell.firstChild );
  }
  
  /** private void toggleSection () :: onclick event handler **/
  function toggleSection ()
  {
    var trHead  = this.parentNode.parentNode;
    var section = sections[ trHead.id.substr( 20 ) ];
    var content = section.content;
    var display = section.status ? 'none' : '';
      
    for ( var i = 0, n = content.length; i < n; i++ )
      content[i].style.display = display;
    
    section.status       = !section.status;
    this.firstChild.data = section.status ? linkTextHide : linkTextShow;
  }
}

if ( mw.config.get("wgIsArticle") || window.location.href.indexOf( 'action=submit' ) > -1 )
{
   CollapsibleTables();
} 

function formatDate(t)
{
	var month = new Array();
	month[0] = 'January';
	month[1] = 'February';
	month[2] = 'March';
	month[3] = 'April';
	month[4] = 'May';
	month[5] = 'June';
	month[6] = 'July';
	month[7] = 'August';
	month[8] = 'September';
	month[9] = 'October';
	month[10] = 'November';
	month[11] = 'December';
	
	y = t.getUTCFullYear();
	M = t.getUTCMonth();
	D = t.getUTCDate();
	h = t.getUTCHours();
	m = t.getUTCMinutes();
	s = t.getUTCSeconds();
	
	if (h > 0 || m > 0 || s > 0)
	{
		hms = '';
		
		if (s > 10)
			hms = ':' + s;
		else if (s > 0)
			hms = ':0' + s;
		
		if (m > 10)
			hms = ':' + m + hms;
		else if (m > 0)
			hms = ':0' + m + hms;
			
		if (h > 12)
			hms = (h - 12) + hms + ' PM';
		else if (h > 0)
			hms = h + hms + ' AM';
		else
			hms = '12' + hms + ' AM';
		
		return hms + ', ' + month[M] + ' ' + D + ', ' + y;
	} else {
		return month[M] + ' ' + D + ', ' + y;
	}
}

function formatTime(h, m, s)
{
	var o = '';
	
	if (h != 1)
	{
		o = h + ' hours ';
	} else {
		o = '1 hour ';
	}
	
	if (m != 1)
	{
		o += m + ' minutes ';
	} else {
		o += '1 minute ';
	}
	
	if (s != 1)
	{
		o += s + ' seconds';
	} else {
		o += '1 second';
	}
	
	return o;
}

function updateClocks()
{
	var t = new Date();

	setTimeout(updateClocks, 1000);
	
	D = t.getUTCDate();
	M = t.getUTCMonth();
	y = t.getUTCFullYear();
	h = t.getUTCHours();
	m = t.getUTCMinutes();
	s = t.getUTCSeconds();

	t = Date.UTC(y, M, D, h, m, s);

	t = (T - t) / 1000;
	
	if (t < 0 && t > -86400 && (h > 0 || m > 0 || s > 0))
	{
		document.getElementById('countdown-big').innerHTML = 'Today';
		document.getElementById('countdown-small').innerHTML = '';
		document.getElementById('countdown-target').innerHTML = 'is ' + formatDate(new Date(T + tzOffset)) + ' ' + tz;
		
		return;
	} else if (t < 0) {
		document.getElementById('countdown-big').innerHTML = 'Past';
		document.getElementById('countdown-target').innerHTML = formatDate(new Date(T + tzOffset)) + ' ' + tz;	
		
		return;
	}
	
	D = Math.floor(t / 86400.0);
	h = Math.floor(t % 86400.0 / 3600.0);
	m = Math.floor(t % 3600.0 / 60.0);
	s = Math.floor(t % 60.0)

	if (D == 1)
	{
		document.getElementById('countdown-big').innerHTML = '1 day';
	} else if (D == 0) {
		document.getElementById('countdown-big').innerHTML = '';
	} else {
		document.getElementById('countdown-big').innerHTML = D + ' days';
	}
	
	document.getElementById('countdown-small').innerHTML = formatTime(h, m, s);
}

function startCountdown()
{
	document.getElementById('countdown-target').innerHTML = 'to ' + formatDate(new Date(T + tzOffset)) + ' ' + tz;
	document.getElementById('countdown').style.display = 'block';
	updateClocks();
}

// Webmaster staff icons
$(document).ready(function () {
 if(
 window.location.href.indexOf("/wiki/User:") == -1
 ) {
 if(
  window.location.href.indexOf("/wiki/User_talk:") == -1
  ) {
 return;
  }
 };

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="stafflink-WM" style="float:right; display:none;"><a href="/wiki/Bulbapedia:Webmasters" title="This user is a Webmaster of Bulbagarden."><img src="//cdn2.bulbagarden.net/media/upload/0/01/IconBPWebmaster.png"></a></div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

// Leadership Board staff icons
$(document).ready(function () {
 if(
 window.location.href.indexOf("/wiki/User:") == -1
 ) {
 if(
  window.location.href.indexOf("/wiki/User_talk:") == -1
  ) {
 return;
  }
 };

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="stafflink-LB" style="float:right; display:none;"><a href="/wiki/Bulbapedia:Leadership_Board" title="This user is a member of the Bulbapedia Leadership Board."><img src="//cdn2.bulbagarden.net/media/upload/e/ef/IconBPLeadershipBoard.png"></a></div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

// Administrator staff icons
$(document).ready(function () {
 if(
 window.location.href.indexOf("/wiki/User:") == -1
 ) {
 if(
  window.location.href.indexOf("/wiki/User_talk:") == -1
  ) {
 return;
  }
 };

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="stafflink-AD" style="float:right; display:none;"><a href="/wiki/Bulbapedia:Administrators" title="This user is a Bulbapedia Administrator."><img src="//cdn2.bulbagarden.net/media/upload/8/81/IconBPAdministrator.png"></a></div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

// Junior Administrator staff icons
$(document).ready(function () {
 if(
 window.location.href.indexOf("/wiki/User:") == -1
 ) {
 if(
  window.location.href.indexOf("/wiki/User_talk:") == -1
  ) {
 return;
  }
 };

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="stafflink-JA" style="float:right; display:none;"><a href="/wiki/Bulbapedia:Junior_Administrators" title="This user is a Bulbapedia Junior Administrator."><img src="//cdn2.bulbagarden.net/media/upload/5/5f/IconBPJuniorAdministrator.png"></a></div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

// This will add an [edit] link at the top of all pages except preview pages and the main page
// by User:Pile0nades (blatantly stolen from Wikipedia by User:The dark lord trombonator

// Add an [edit] link to pages
$(document).ready(function () {
 // if this is preview page or generated page, stop
 if(
 document.getElementById("wikiPreview") ||
 document.getElementById("histlegend‎") ||
 document.getElementById("difference‎") ||
 document.getElementById("watchdetails") ||
 document.getElementById("ca-viewsource") ||
 window.location.href.indexOf("/wiki/Special:") != -1
 ) {
 if(window.location.href.indexOf("&action=edit&section=0") != -1) {
 document.getElementById("wpSummary").value = "/* Intro */ ";
 }
 return;
 };

 // get the page title
 var pageTitle = mw.config.get('wgPageName');

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="editsection">[<a href="/w/index.php?title='+encodeURIComponent(pageTitle)+'&action=edit&section=0" title="Edit first section: '+pageTitle+'">edit top of page</a>]</div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

// This will add an [+] (new section) link at the top of all pages except preview pages and the main page... because some people are having trouble finding it or something
// Roughly edited from the above section by User:The dark lord trombonator

// Add an [+] link to pages
$(document).ready(function () {
 // if this is preview page or generated page, stop
 if(
 document.getElementById("wikiPreview") ||
 document.getElementById("histlegend‎") ||
 document.getElementById("difference‎") ||
 document.getElementById("watchdetails") ||
 document.getElementById("ca-viewsource") ||
 document.getElementById("article") ||
 window.location.href.indexOf("/wiki/Special:") != -1
 ) {
 if(window.location.href.indexOf("&action=edit&section=0") != -1) {
 document.getElementById("wpSummary").value = "/* Intro */ ";
 }
 return;
 };

 // get the page title
 var pageTitle = mw.config.get('wgPageName');

 // create div and set innerHTML to link
 var divContainer = document.createElement("div");
 divContainer.innerHTML = '<div class="editsectionnew">[<a href="/w/index.php?title='+encodeURIComponent(pageTitle)+'&action=edit&section=new" title="Start new section: '+pageTitle+'">+</a>]</div>';

 // insert divContainer into the DOM below the h1
 if(window.location.href.indexOf("&action=edit") == -1) {
 document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]);
 }

});

 // Checks if page has the parts of a countdown, then starts it if it does

 if(document.getElementById('countdown') && document.getElementById('countdown-big') && document.getElementById('countdown-small') && document.getElementById('countdown-target')) {
    startCountdown();
}

/**
ClickToggle instructions:
1. Toggle objects are declared as: <div class="clicktoggle" data-type="set" data-for="1,2"> This will toggle Content 2 of Group 1 </div>
     -> data-type="set" makes all other elements of a group invisible and the clicked one visible.
     -> data-type="toggle" toggles the visibility of all elements in a group. Visible becomes invisible and vice versa.
2. Target objects (that can be made visible or invisible) are declared as: <div class="clicktoggle-target" data-group="1" data-target="2"> This is Content 2 of Group 1 </div>
     (Any tag can be used in place of <div>, including table rows and columns. There can be several targets with the same content number.)
**/
function clickToggleInit() { // (c) Buoysel
    $(document).find('.clicktoggle').each( function () {
        var id = $(this).data('for').split(',');
        var type = $(this).data('type');
        var group = id[0];
        var target = id[1];
        if ($(this).attr('style') === undefined) $(this).attr('style', '');
        if ($(this).data('active-style') !== undefined) {
            $(this).data('inactive-style', $(this).attr('style'));
            if ($(this).hasClass("clicktoggle-active")) {
                $(this).attr('style', $(this).data('active-style'));
            }
        }
        
        $(this).click(function() {
            if (type == 'toggle') {
                if ($(this).hasClass('clicktoggle-active')) {
                    $(this).removeClass("clicktoggle-active");
                    if ($(this).data('inactive-style') !== undefined) {
                        $(this).attr('style', $(this).data('inactive-style'));
                    }
                } else {
                    $(this).addClass("clicktoggle-active");
                    if ($(this).data('active-style') !== undefined) {
                        $(this).attr('style', $(this).data('active-style'));
                    }
                }
            } else if (type == 'set') {
                $(this).addClass("clicktoggle-active");
                $(document).find('.clicktoggle').each( function () {
                    var id2 = $(this).data('for').split(',');
                    if (group == id2[0]) {
                        $(this).removeClass("clicktoggle-active");
                        if ($(this).data('inactive-style') !== undefined) {
                            $(this).attr('style', $(this).data('inactive-style'));
                        }
                    }
                    if (group == id2[0] && target == id2[1]) {
                        $(this).addClass("clicktoggle-active");
                        if ($(this).data('active-style') !== undefined) {
                            $(this).attr('style', $(this).data('active-style'));
                        }
                    }
                });
            }
            
            $(document).find('.clicktoggle-target').each( function () {
                var group2 = $(this).data('group');
                var target2Arr = $(this).data('target').split(',');
                if (group == group2) {
                    if (type == 'toggle') {
                        if (jQuery.inArray( target, target2Arr ) !== -1) {
                            if ($(this).css('display') == 'none')
                                $(this).css('display', '');
                            else
                                $(this).css('display', 'none');
                        }
                    } else if (type == 'set') {
                        if (jQuery.inArray( target, target2Arr ) !== -1) {
                            $(this).css('display', '');
                        } else {
                            $(this).css('display', 'none');
                        }
                    }
                }
            });
        });
    });
}

$(function() {
    clickToggleInit();
});

/* </pre> */