MediaWiki:Common.js: Difference between revisions

From the Portal Wiki
Jump to navigation Jump to search
(f yeah jquery)
mNo edit summary
Line 117: Line 117:
chromeSize: 25, // This is the height (in pixels) of the chrome of YouTube's embedded video player. Update this whenever they release a new embedded video player
chromeSize: 25, // This is the height (in pixels) of the chrome of YouTube's embedded video player. Update this whenever they release a new embedded video player
maxWidth: 0.85, // Maximum fraction of the available width that the video may take
maxWidth: 0.85, // Maximum fraction of the available width that the video may take
infoboxes: ['.infobox', '.testchamber'], // Selectors of infobox-style boxes that should be deducted from the page's available width
ratioR: /ratio-(\d+)x(\d+)/i,
ratioR: /ratio-(\d+)x(\d+)/i,
widthsR: /widths((?:-\d+)+)/i,
widthsR: /widths((?:-\d+)+)/i,
Line 124: Line 125:
widths = widths[1].substr(1).split('-');
widths = widths[1].substr(1).split('-');
var availableWidth = $('#bodyContent').width();
var availableWidth = $('#bodyContent').width();
if($('.infobox').length) {
for(var i in youtubeHelper.infoboxes) {
availableWidth -= $('.infobox').width();
if($(youtubeHelper.infoboxes[i].length) {
availableWidth -= $(youtubeHelper.infoboxes[i]).width();
}
}
}
availableWidth *= youtubeHelper.maxWidth;
availableWidth *= youtubeHelper.maxWidth;

Revision as of 19:24, 29 May 2011

/* jQuery plugins */

/**
 * Cookie plugin
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/* End jQuery plugins */

/*BEGIN UTC CLOCK*/

/** additional monobook scripts **/
hookEvent( 'load', displayTimer );

/**** function displayTimer.js
 * by Patrick Westerhoff [poke]
 */
function displayTimer ()
{
  if ( typeof( timerDisplay ) !== 'undefined' && timerDisplay === false )
    return;
  
  var date;
  var timerParent = document.getElementById( 'p-personal' ).getElementsByTagName( 'ul' )[0];
  var timerLink   = document.createElement( 'a' );
  var timerObj    = document.createElement( 'li' );
  timerLink.href               = '/wiki/' + wgPageName + '?action=purge';
  timerLink.title              = 'Purge the server cache and update the contents of this page.'
  timerObj.id                  = 'pt-timer';
  timerObj.style.textTransform = 'none';
  timerObj.appendChild( timerLink );
  timerParent.insertBefore( timerObj, timerParent.firstChild );
  
  function actualizeUTC ()
  {
    timerDate           = new Date();
    timerLink.innerHTML = ( timerDate.getUTCHours()   < 10 ? '0' : '' ) + timerDate.getUTCHours()   + ':'
                        + ( timerDate.getUTCMinutes() < 10 ? '0' : '' ) + timerDate.getUTCMinutes() + ':'
                        + ( timerDate.getUTCSeconds() < 10 ? '0' : '' ) + timerDate.getUTCSeconds() + ' (UTC)';
  }
  
  function actualizeCustom ()
  {
    timerDate           = new Date();
    timerDate.setMinutes( timerDate.getMinutes() + timerDate.getTimezoneOffset() + timerTimezone * 60 );
    timerLink.innerHTML = ( timerDate.getHours()   < 10 ? '0' : '' ) + timerDate.getHours()   + ':'
                        + ( timerDate.getMinutes() < 10 ? '0' : '' ) + timerDate.getMinutes() + ':'
                        + ( timerDate.getSeconds() < 10 ? '0' : '' ) + timerDate.getSeconds()
                        + ' (UTC' + ( timerTimezone < 0 ? '' : '+' ) + timerTimezone + ')';
  }
  
  // start
  if ( typeof( timerTimezone ) !== 'number' )
  {
    actualizeUTC();
    setInterval( actualizeUTC, 1000 );
  }
  else
  {
    actualizeCustom();
    setInterval( actualizeCustom, 1000 );
  }
}
/*END UTC CLOCK*/

/* BEGIN SPOILER TOGGLER */
var spoilers = {
	enabled: true,
	text: null,
	nodes: null,
	imgOn: null,
	imgOff: null,
	toggle: function() {
		spoilers.set(!spoilers.enabled);
	},
	set: function(enabled) {
		spoilers.enabled = enabled;
		if(enabled) {
			spoilers.nodes.removeClass('spoiler-inline');
                        $(".spoiler-thumb").remove();
                        spoilers.nodes.find("img").show();
			$.cookie('spoilers', 'true', {expires: 31, path: '/'});
			spoilers.text.text(' Spoilers on');
			spoilers.imgOff.hide(0);
			spoilers.imgOn.show(0);
		} else {
			spoilers.nodes.addClass('spoiler-inline');
                        spoilers.nodes.find("img").hide();
                        spoilers.thumbNodes.each(function() { if($(this).find(".spoiler-text").length > 0) { $(this).find(".thumb, .thumbinner").append('<div class="spoiler-thumb"/>');} });
			$.cookie('spoilers', 'false', {expires: 31, path: '/'});
			spoilers.text.text(' Spoilers off');
			spoilers.imgOn.hide(0);
			spoilers.imgOff.show(0);
		}
	},
	init: function() {
		spoilers.nodes = $('.spoiler-text');
                spoilers.thumbNodes = $(".gallerybox, .thumb");
		spoilers.text = $('<div style="display:inline;"></div>');
		spoilers.imgOn = $('<img alt="" style="display:none;"/>').attr('src', 'http://portal.biringa.com/images/2/2b/Wheatley_spoils_you.png');
		spoilers.imgOff = $('<img alt="" style="display:none;"/>').attr('src', 'http://portal.biringa.com/images/e/ef/Wheatley_spoils_nothing.png');
		var wrapped = $('<li/>').append($('<span/>').append($('<a/>').append(spoilers.imgOn, spoilers.imgOff, spoilers.text)));
		wrapped.click(spoilers.toggle);
		$('#p-namespaces ul').append(wrapped);
		spoilers.set(!$.cookie('spoilers') || $.cookie('spoilers') == 'true');
	}
};
$(spoilers.init);
/* END SPOILER TOGGLER */

// EmbedVideo fixes
var youtubeHelper = {
	chromeSize: 25, // This is the height (in pixels) of the chrome of YouTube's embedded video player. Update this whenever they release a new embedded video player
	maxWidth: 0.85, // Maximum fraction of the available width that the video may take
	infoboxes: ['.infobox', '.testchamber'], // Selectors of infobox-style boxes that should be deducted from the page's available width
	ratioR: /ratio-(\d+)x(\d+)/i,
	widthsR: /widths((?:-\d+)+)/i,
	setSize:function() {
		var widths = youtubeHelper.widthsR.exec($(this).attr('class'));
		if(widths != null) {
			widths = widths[1].substr(1).split('-');
			var availableWidth = $('#bodyContent').width();
			for(var i in youtubeHelper.infoboxes) {
				if($(youtubeHelper.infoboxes[i].length) {
					availableWidth -= $(youtubeHelper.infoboxes[i]).width();
				}
			}
			availableWidth *= youtubeHelper.maxWidth;
			var intWidths = [];
			for(var w = 0; w < widths.length; w++) {
				intWidths[w] = parseInt(widths[w]);
			}
			intWidths.sort(function(a, b){return b - a;});
			for(var w = 0; w < intWidths.length; w++) {
				if(intWidths[w] <= availableWidth || w == intWidths.length-1) {
					youtubeHelper.setWidth(this, intWidths[w]);
					break;
				}
			}
		}
		else {
			youtubeHelper.setWidth(this, parseFloat(obj.attr('width')));
		}
	},
	hd:function() {
		var obj = $(this).children('object');
		if(!obj) return;
		if($(this).hasClass('hd-on')) {
			var playerUrl = obj.children('param[name="movie"]').attr('value') + '&hd=1';
			obj.children('param[name="movie"]').attr('value', playerUrl);
			obj.children('embed').attr('src', playerUrl);
			var resultHtml = $(this).html();
			$(this).html('').html(resultHtml);
		}
	},
	setWidth:function(youtube, width) {
		var obj = $(youtube).children('object');
		if(!obj) return;
		if($(youtube).hasClass('youtube-audio')) {
			obj.attr('width', width).attr('height', youtubeHelper.chromeSize); // Set <object> height
			obj.children('embed').attr('width', width).attr('height', youtubeHelper.chromeSize); // Set <embed> height
		}
		else {
			var ratio = youtubeHelper.ratioR.exec($(youtube).attr('class'));
			if(ratio != null) {
				ratio = parseFloat(ratio[1])/parseFloat(ratio[2]);
				var newHeight = Math.round(width / ratio + youtubeHelper.chromeSize).toString();
				obj.attr('width', width).attr('height', newHeight); // Set <object> height
				obj.children('embed').attr('width', width).attr('height', newHeight); // Set <embed> height
			}
		}
	},
	resizeTimer:null,
	resize:function() {
		if(youtubeHelper.resizeTimer != null) {
			clearTimeout(youtubeHelper.resizeTimer);
		}
		youtubeHelper.resizeTimer = setTimeout(youtubeHelper.onResize, 100);
	},
	onResize:function() {
		$('.youtubebox').each(youtubeHelper.setSize);
	},
	init:function() {
		$('.youtubebox').each(youtubeHelper.hd);
		$(window).resize(youtubeHelper.resize);
		youtubeHelper.onResize();
	}
};
$(youtubeHelper.init);

// Start overly-complicated collapsible tables
// Todo: jQuery this thing
 /** Collapsible tables *********************************************************
  *
  *  Description: Allows tables to be collapsed, showing only the header. See
  *               [[Wikipedia:NavFrame]].
  *  Maintainers: [[User:R. Koot]]
  */
 var hasClass = (function () {
    var reCache = {};
    return function (element, className) {
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
    };
 })(); 

 var autoCollapse = 2;
 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.rows;
 
     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" ) ) {
 
             /* only add button and increment count if there is a header row to work with */
             var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0];
             if (!HeaderRow) continue;
             var Header = HeaderRow.getElementsByTagName( "th" )[0];
             if (!Header) continue;
 
             NavigationBoxes[ tableIndex ] = Tables[i];
             Tables[i].setAttribute( "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.style.color = Header.style.color;
             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( "]" ) );
 
             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 );
         }
     }
 }
 
$(createCollapseButtons);

// End collapsible tables

// PootTabs by User:WindPower~
// It puts tabs on pages.
var pootTabsHere = {
	animationsEnabled: $.support.opacity,
	getTab:function(poot, index) {
		return $(poot.children('.poot-tabs').children('ul').children('li')[parseInt(index)]);
	},
	changeTab:function(poot, index, duration, force) {
		if(index == parseInt(poot.attr('pootSelected')) && !force && duration) return;
		if(!pootTabsHere.animationsEnabled) {
			duration = 0;
		}
		poot.attr('pootSelected', index.toString());
		var babies = poot.children('.poot-tabs-content').children();
		babies.each(function() {
			$(this).fadeOut(duration, function(){
				$(this).removeClass('poot-tabs-selected');
			});
		});
		$(babies[index]).each(function() {
			$(this).fadeIn(duration, function(){
				$(this).addClass('poot-tabs-selected');
			});
		});
		var cowtabs = poot.children('.poot-tabs').children('ul').children('li');
		cowtabs.removeClass('poot-tabs-selected');
		$(cowtabs[index]).addClass('poot-tabs-selected');
		pootTabsHere.updatePoot(poot, $(babies[index]).height());
	},
	updatePoot:function(poot, babysize) {
		poot.find('.poot-tabs-titletext').html(poot.attr('originalTitle') + ' &mdash; ' + pootTabsHere.getTab(poot, poot.attr('pootSelected')).html());
		var bestHeight = Math.max(poot.children('.poot-tabs-content').height(), Math.max(poot.children('.poot-tabs').height(), babysize)).toString() + 'px';
		poot.children('.poot-tabs-content').css('height', bestHeight);
		if(poot.attr('vertical')) {
			poot.children('.poot-tabs').css('height', bestHeight);
		}
	},
	toggleCollapse:function(poot) {
		var pootLinkText = poot.children('.poot-tabs-showhide').text().split(';');
		var duration = pootTabsHere.animationsEnabled ? parseInt(poot.attr('pootslideduration')) : 0;
		if(poot.attr('pootcollapse') != 'true') {
			poot.attr('pootcollapse', 'true');
			poot.find('.poot-tabs-hidelink a').text(pootLinkText[0]);
			poot.children('.poot-tabs, .poot-tabs-content').slideUp(duration);
		}
		else {
			poot.attr('pootcollapse', '');
			poot.find('.poot-tabs-hidelink a').text(pootLinkText[1]);
			poot.children('.poot-tabs, .poot-tabs-content').slideDown(duration);
		}
	},
	delayHeight:function(poot, selected) {
		setTimeout(function() {
			poot.attr('pootselected', selected.toString());
			pootTabsHere.changeTab(poot, selected, 0, true);
			if(poot.hasClass('poot-tabs-collapsed')) {
				pootTabsHere.toggleCollapse(poot);
			}
		}, 100);
	},
	poot:function() {
		var dis = $(this);
		var ind = 0;
		dis.attr('originalTitle', dis.find('.poot-tabs-titletext').html());
		var selected = /poot-tabs-selected-(\d+)/i.exec(dis.attr('class'));
		if(selected) {
			pootTabsHere.delayHeight(dis, parseInt(selected[1])-1);
		}
		else {
			pootTabsHere.delayHeight(dis, 0);
		}
		var duration = dis.hasClass('poot-tabs-noanimations') ? 0 : 200;
		dis.attr('pootslideduration', dis.hasClass('poot-tabs-noanimations') ? '0' : '75');
		dis.children('.poot-tabs').children('ul').children('li').each(function(){
			var thisInd = ind;
			$(this).click(function(){
				pootTabsHere.changeTab(dis, thisInd, duration, false);
				$(this).blur();
				$(this).find('*').blur();
				return false;
			});
			ind++;
		});
		var isVertical = dis.hasClass('poot-tabs-vertical');
		dis.attr('pootvertical', isVertical ? 'true' : '');
		if(isVertical) {
			var teenie = dis.children('.poot-tabs').width().toString() + 'px';
			dis.children('.poot-tabs-content').css('margin-left', teenie);
		}
		dis.attr('pootcollapse', ''); // False
		dis.find('.poot-tabs-hidelink a').click(function(){
			pootTabsHere.toggleCollapse(dis);
			return false;
		});
	},
	init:function() {
		$('.poot-tabs-container').each(pootTabsHere.poot);
	}
};
$(pootTabsHere.init);
// End of PootTabs

// Start test chamber infobox flicker
infoboxFlicker = {
	setOn:function(infobox, isOn) {
		if(isOn) {
			infobox.removeClass('testchamber-off');
		} else {
			infobox.addClass('testchamber-off');
		}
	},
	setDisplay1:function(infobox, isOn) {
		if(isOn) {
			infobox.removeClass('testchamber-display1-off');
		} else {
			infobox.addClass('testchamber-display1-off');
		}
	},
	setDisplay2:function(infobox, isOn) {
		if(isOn) {
			infobox.removeClass('testchamber-display2-off');
		} else {
			infobox.addClass('testchamber-display2-off');
		}
	},
	flicker:function() { // Step 0: Start off
		var infobox = $(this);
		infoboxFlicker.setOn(infobox, false);
		infoboxFlicker.setDisplay1(infobox, false);
		infoboxFlicker.setDisplay2(infobox, false);
		setTimeout(function() { // Step 1: Switch on, no details
			infoboxFlicker.setOn(infobox, true);
			setTimeout(function() { // Step 2: Switch back off
				infoboxFlicker.setOn(infobox, false);
				setTimeout(function() { // Step 3: Switch back on, still no details
					infoboxFlicker.setOn(infobox, true);
					setTimeout(function() { // Step 4: Display top half
						infoboxFlicker.setDisplay1(infobox, true);
						setTimeout(function() { // Step 5: Display bottom half
							infoboxFlicker.setDisplay2(infobox, true);
						}, 200);
					}, 200);
				}, 340);
			}, 66);
		}, 1000);
	},
	init:function() {
		$('.testchamber').each(infoboxFlicker.flicker);
	}
};
$(infoboxFlicker.init);
// End test chamber infobox flicker

// Collapsible diffs
$(function() {
	$('.diff-name-text').click(function() {
		$(this).parent().children('.diff-contents').toggle();
	});
});

// Google Analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22928841-2']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();