MediaWiki:Common.js

/* Any JavaScript here will be loaded for all users on every page load. */

function importScriptPage(page, server) { var url = '/index.php?title=' + encodeURIComponent(page.replace(/ /g, '_')).replace('%2F', '/').replace('%3A', ':') + '&action=raw&ctype=text/javascript'; if (typeof server == "string") url = (server.indexOf('://') == -1) ? 'http://' + server + '.wikia.com' + url : server + url; return importScriptURI(url); }

/* importScriptPage('ShowHide/code.js', 'dev'); */

function addPurgeButton { var theText = 'Refresh'; //default text, ala SMW if (typeof PurgeButtonText == "string") { theText = PurgeButtonText; }   if ((wgNamespaceNumber != 500 && wgNamespaceNumber != 502) || skin == 'oasis') { switch (skin) { case 'answers': /* forked from monaco, close enough, pass to monaco */ case 'awesome': /* you really shouldnt even have this value... */       case 'monaco_old': /* really, where are you getting these skin settings from... */       case 'monaco': $('#page_controls').append('' + theText + ''); break; case 'oasis': $('.wikia-menu-button > li > ul').append('' + theText + ''); break;

case 'uncyclopedia': /* monobook clone, pass to monobook */ case 'wowwiki': /* monobook clone, pass to monobook */ case 'lostbook': /* monobook clone, pass to monobook */ case 'monobook': $('#p-cactions > .pBody > ul').append('' + theText + ''); break; }   } }

if (wgNamespaceNumber >= 0 && wgNamespaceNumber < 400 && document.getElementById('ca-talk') == null) { /* addOnloadHook( addDiscussionTab ); */ }

function addDiscussionTab {

switch (skin) { case 'answers': /* forked from monaco, close enough, pass to monaco */ case 'awesome': /* you really shouldnt even have this value... */   case 'monaco_old': /* really, where are you getting these skin settings from... */   case 'monaco': $('#page_tabs').append(' Discussion'); break; case 'uncyclopedia': /* monobook clone, pass to monobook */ case 'wowwiki': /* monobook clone, pass to monobook */ case 'lostbook': /* monobook clone, pass to monobook */ case 'monobook': $('#p-cactions > .pBody > ul').append('<a href="/wiki/Talk:' + encodeURIComponent(wgPageName) + '" title="Discussion about the content page [alt-t]" accesskey="t">Discussion</a></li>'); break;

} }

function addDiscussionButton { var theText = 'Tech Talk'; //default text, ala SMW if (typeof DiscussionButtonText == "string") { theText = DiscussionButtonText; }

switch (skin) { case 'answers': /* forked from monaco, close enough, pass to monaco */ case 'awesome': /* you really shouldnt even have this value... */   case 'monaco_old': /* really, where are you getting these skin settings from... */   case 'monaco': $('#page_controls').append('<img src="/skins/common/blank.gif" class="sprite talk" /><a href="/wiki/Talk:' + encodeURIComponent(wgPageName) + '" rel="nofollow" title="Discussion about the layout">' + theText + '</a></li>'); break; case 'uncyclopedia': /* monobook clone, pass to monobook */ case 'wowwiki': /* monobook clone, pass to monobook */ case 'lostbook': /* monobook clone, pass to monobook */ case 'monobook': $('#p-cactions > .pBody > ul').append('<a href="/wiki/Talk:' + encodeURIComponent(wgPageName) + '" title="Technical Discussion">' + theText + '</a></li>'); break;

} }

if (wgNamespaceNumber >= 0 && wgNamespaceNumber < 400 && document.getElementById('ca-talk') == null) { addOnloadHook(addDiscussionButton); }

function UpdateTableHeaders { $("div.divTableWithFloatingHeader").each(function {        var originalHeaderRow = $(".tableFloatingHeaderOriginal", this);        var floatingHeaderRow = $(".tableFloatingHeader", this);        var offset = $(this).offset;        var scrollTop = $(window).scrollTop;        if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height)) {            floatingHeaderRow.css("visibility", "visible");            floatingHeaderRow.css("display", "table-row");

floatingHeaderRow.css("top", Math.min(scrollTop - offset.top, $(this).height - floatingHeaderRow.height) + "px");

floatingHeaderRow.css("width", $(this).width); // Copy cell widths from original header $("th", floatingHeaderRow).each(function (index) {                var cellWidth = $("th", originalHeaderRow).eq(index).css("width")+1;                $(this).css("width",cellWidth);            });

// Copy row width from whole table }       else { floatingHeaderRow.css("visibility", "hidden"); floatingHeaderRow.css("display", "none"); floatingHeaderRow.css("top", "0px"); }   }); }

$(document).ready(function {

var useFloatingHeaders = !(/MSIE (\d+\.\d+);/.test(navigator.userAgent)); if (typeof FloatingHeaders == "boolean") { useFloatingHeaders = FloatingHeaders; }

if (useFloatingHeaders) { $(".wikitable").each(function (index) {           var tableHeight = $(this).height;

if (tableHeight > $(window).height) { $(this).addClass("TableWithFloatingHeader"); }       });

$("table.TableWithFloatingHeader").each(function {            $(this).wrap("<div class=\"divTableWithFloatingHeader\" style=\"position:relative\"> ");

var originalHeaderRow = $("tr:first", this) $("th", originalHeaderRow).each(function (index) {               var cellWidth = $(this).width + 1;                $(this).width(cellWidth);            }); originalHeaderRow.before(originalHeaderRow.clone); var clonedHeaderRow = $("tr:first", this)

clonedHeaderRow.addClass("tableFloatingHeader unsortable "); clonedHeaderRow.css("position", "absolute"); clonedHeaderRow.css("top", "0px"); clonedHeaderRow.css("left", $(this).css("margin-left")); clonedHeaderRow.css("visibility", "hidden"); clonedHeaderRow.css("display", "none"); clonedHeaderRow.css("width", originalHeaderRow.width);

originalHeaderRow.addClass("tableFloatingHeaderOriginal unsortable "); });       UpdateTableHeaders;        $(window).scroll(UpdateTableHeaders);        $(window).resize(UpdateTableHeaders);

}; });

function ts_resortTable_fhs(lnk) {

var span = lnk.getElementsByTagName('span')[0]; var td = lnk.parentNode; var tr = td.parentNode; var column = td.cellIndex; var table = tr.parentNode; while (table && !(table.tagName && table.tagName.toLowerCase == 'table')) table = table.parentNode; if (!table) return; if (table.rows.length <= 1) return; if (ts_number_transform_table == null) { ts_initTransformTable; }   var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1); var itm = ""; for (var j = rowStart; j < table.rows.length - 1; j++) { var row = table.rows[j]; if ((" " + row.className + " ").indexOf(" unsortable ") < 0) { break; } else { rowStart = j + 1; }   }

for (var i = rowStart; i < table.rows.length; i++) { if (table.rows[i].cells.length > column) { itm = ts_getInnerText(table.rows[i].cells[column]); itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, ""); if (itm != "") break; }   }

var sortfn = ts_sort_generic; var preprocessor = ts_toLowerCase; if (/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test(itm)) { preprocessor = ts_dateToSortKey; }   else if (/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test(itm)) { preprocessor = ts_dateToSortKey; }   else if (/^\d\d[\/.-]\d\d[\/.-]\d\d$/.test(itm)) { preprocessor = ts_dateToSortKey; }   else if (/(^[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test(itm)) { preprocessor = ts_currencyToSortKey; }   else if (ts_number_regex.test(itm)) { preprocessor = ts_parseFloat; }   var reverse = (span.getAttribute("sortdir") == 'down'); var newRows = new Array; var staticRows = new Array; for (var j = rowStart; j < table.rows.length; j++) { var row = table.rows[j]; if ((" " + row.className + " ").indexOf(" unsortable ") < 0) { var keyText = ts_getInnerText(row.cells[column]); var oldIndex = (reverse ? -j : j); var preprocessed = preprocessor(keyText); newRows[newRows.length] = new Array(row, preprocessed, oldIndex); }       else staticRows[staticRows.length] = new Array(row, false, j - rowStart); }   newRows.sort(sortfn); var arrowHTML; if (reverse) { arrowHTML = '<img src="' + ts_image_path + ts_image_down + '" alt="&darr;"/>'; newRows.reverse; span.setAttribute('sortdir', 'up'); }   else { arrowHTML = '<img src="' + ts_image_path + ts_image_up + '" alt="&uarr;"/>'; span.setAttribute('sortdir', 'down'); }   for (var i = 0; i < staticRows.length; i++) { var row = staticRows[i]; newRows.splice(row[2], 0, row); }   for (var i = 0; i < newRows.length; i++) { if ((" " + newRows[i][0].className + " ").indexOf(" sortbottom ") == -1) table.tBodies[0].appendChild(newRows[i][0]); }   for (var i = 0; i < newRows.length; i++) { if ((" " + newRows[i][0].className + " ").indexOf(" sortbottom ") != -1) table.tBodies[0].appendChild(newRows[i][0]); }   var spans = getElementsByClassName(tr, "span", "sortarrow"); for (var i = 0; i < spans.length; i++) { spans[i].innerHTML = '<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/>'; }   span.innerHTML = arrowHTML;

if ((" " + tr.className + " ").indexOf(" tableFloatingHeaderOriginal ") >= 0) { $(".tableFloatingHeader", table).children.children("a").children(".sortarrow").html('<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/>'); var Span2 = $(".tableFloatingHeader", table).children("*:nth-child(" + (column + 1) + ")").children("a").children(".sortarrow").eq(0); Span2.html(arrowHTML); Span2.attr('sortdir', span.getAttribute("sortdir")) }   if ((" " + tr.className + " ").indexOf(" tableFloatingHeader ") >= 0) { $(".tableFloatingHeaderOriginal", table).children.children("a").children(".sortarrow").html('<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/>'); var Span2 = $(".tableFloatingHeaderOriginal", table).children("*:nth-child(" + (column + 1) + ")").children("a").children(".sortarrow").eq(0); Span2.html(arrowHTML); Span2.attr('sortdir', span.getAttribute("sortdir"))

}

if (ts_alternate_row_colors) { ts_alternate(table); } } function ts_makeSortable(table) { var firstRow; if (table.rows && table.rows.length > 0) { if (table.tHead && table.tHead.rows.length > 0) { firstRow = table.tHead.rows[table.tHead.rows.length - 1]; } else { firstRow = table.rows[0]; }   }    if (!firstRow) { return; }

// We have a first row: assume it's the header, and make its contents clickable links for (var i = 0; i < firstRow.cells.length; i++) { var cell = firstRow.cells[i]; var numclicks = 0; if ((' ' + cell.className + ' ').indexOf(' unsortable ') == -1) { cell.innerHTML += ' <a href="#" class="sortheader" ' + 'onclick="ts_resortTable_fhs(this);return false;">' + ' ' + '<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/> </a>';

if ((' ' + cell.className + ' ').indexOf(' sortable-asc ') > -1) { numclicks = 1; }           if ((' ' + cell.className + ' ').indexOf(' sortable-desc ') > -1) { numclicks = 2; }

if (numclicks > 0) { //alert(cell.className); //Create Array of All HTML Tags var allHTMLTags = cell.getElementsByTagName("*");

//Loop through all tags using a for loop for (itag = 0; itag < allHTMLTags.length; itag++) {

//Get all tags with the specified class name. if (allHTMLTags[itag].className == 'sortheader') {

for (clicked = 0; clicked < numclicks; clicked++) { ts_resortTable(allHTMLTags[itag]); }

}               }            }

}   }    if (ts_alternate_row_colors) { ts_alternate(table); } }

/* 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);   }; });

/** Collapsible tables ********************************************************* * * Description: Allows tables to be collapsed, showing only the header. See *              NavFrame. * Maintainers: User:R. Koot */

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.className = "collapseButton"; //Styles are declared in Common.css 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); }       else if (hasClass(NavigationBoxes[i], "innercollapse")) { var element = NavigationBoxes[i]; while (element = element.parentNode) { if (hasClass(element, "outercollapse")) { collapseTable(i); break; }           }        }    } }

addOnloadHook(createCollapseButtons);

/** Dynamic Navigation Bars (experimental) ************************************* * * Description: See NavFrame. * Maintainers: UNMAINTAINED */

// set up the words in your language var NavigationBarHide = '[' + collapseCaption + ']'; var NavigationBarShow = '[' + expandCaption + ']';

// shows and hides content and picture (if available) of navigation bars // Parameters: //    indexNavigationBar: the index of navigation bar to be toggled

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) { 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'; }       }        NavToggle.firstChild.data = NavigationBarHide; } }

// adds show/hide-button to navigation bars

function createNavigationBarToggleButton { var indexNavigationBar = 0; // iterate over all -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 isCollapsed = hasClass(NavFrame, "collapsed"); /*            * Check if any children are already hidden. This loop is here for backwards compatibility: * the old way of making NavFrames start out collapsed was to manually add style="display:none" * to all the NavPic/NavContent elements. Since this was bad for accessibility (no way to make            * the content visible without JavaScript support), the new recommended way is to add the class * "collapsed" to the NavFrame itself, just like with collapsible tables. */           for (var NavChild = NavFrame.firstChild; NavChild != null && !isCollapsed; NavChild = NavChild.nextSibling) { if (hasClass(NavChild, 'NavPic') || hasClass(NavChild, 'NavContent')) { if (NavChild.style.display == 'none') { isCollapsed = true; }               }            }            if (isCollapsed) { for (var NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling) { if (hasClass(NavChild, 'NavPic') || hasClass(NavChild, 'NavContent')) { NavChild.style.display = 'none'; }               }            }            var NavToggleText = document.createTextNode(isCollapsed ? NavigationBarShow : 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); }   } }

addOnloadHook(createNavigationBarToggleButton);

/* http://www.wowwiki.com/MediaWiki:Common.js */

function setCookie(c_name, value, expiredays) { var exdate = new Date; exdate.setDate(exdate.getDate + expiredays); document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString); }

function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end = document.cookie.length; return unescape(document.cookie.substring(c_start, c_end)); }   }    return ""; }

// AJAX RC var ajaxPages = new Array("Special:RecentChanges"); var ajaxRCOverride = false; var rcTimer; var doRefresh = true; var rcRefresh = 60000; ajaxRCCookie = (getCookie("ajaxRC") == "on" || ajaxRCOverride) ? true : false;

function ajaxRC { appTo = ($("#WikiaPageHeader").length) ? $("#WikiaPageHeader") : $(".firstHeading"); appTo.append(' <span style="font-size: xx-small; border-bottom: 1px dotted; border-bottom-color: #6D0D00; cursor:help;" title="Enable auto-refreshing page loads">AJAX: <input type="checkbox" id="ajaxToggle"> <img src="http://images1.wikia.nocookie.net/sacredseasons2/images/d/d0/Ajaxrc_progressbar.gif" border="0" alt="AJAX operation in progress" /> '); $("#ajaxRCprogress").bind("ajaxSend", function {        $(this).show;    }).bind("ajaxComplete", function  {        $(this).hide;    }); $("#ajaxToggle").click(toggleRC); $("#ajaxRCprogress").hide; $("#ajaxToggle").attr("checked", ajaxRCCookie); if (ajaxRCCookie) loadRCData; }

function toggleRC { if ($("#ajaxToggle").attr("checked") == true) { setCookie("ajaxRC", "on", 30); doRefresh = true; loadRCData; } else { setCookie("ajaxRC", "off", 30); doRefresh = false; clearTimeout(rcTimer); } }

function loadRCData { cC = ($("#WikiaArticle").length) ? "#WikiaArticle" : "#bodyContent"; $(cC).load(location.href + " " + cC, function (data) {       if (doRefresh) rcTimer = setTimeout("loadRCData;", rcRefresh);    }); }

// portal switch var ptabs;

function doPortals { cTab = $("#mptabs>strong").prevAll.length + 1; ptabs = $("#mptabs>*"); ptabs.css("cursor", "pointer"); ptabs.click(function (event) {       event.preventDefault;        target = $(event.target);        if (target.parent.not("#mptabs").html) target = target.parent;        sp = target.prevAll.length;        ptabs.eq(cTab - 1).children("*").removeClass("activetab").addClass("inactivetab");        $("#portal" + cTab).hide;        cTab = sp + 1;        ptabs.eq(sp).children("*").removeClass("inactivetab").addClass("activetab");        $("#portal" + cTab).show;    }); }

dil = new Array;

function findDupImages(gf) { output = ""; url = "/api.php?action=query&generator=allimages&prop=duplicatefiles&gailimit=500&format=json"; if (gf) url += "&gaifrom=" + gf; $.getJSON(url, function (data) {       if (data.query) {            pages = data.query.pages;            for (pageID in pages) {                dils = "," + dil.join;                if (dils.indexOf("," + pages[pageID].title) == -1 && pages[pageID].title.indexOf("File::") == -1 && pages[pageID].duplicatefiles) {                    output += " <a href='/" + pages[pageID].title + "'>" + pages[pageID].title + "</a> \n<ul>\n";                    for (x = 0; x < pages[pageID].duplicatefiles.length; x++) {                        output += "<a href='/File:" + pages[pageID].duplicatefiles[x].name + "'>File:" + pages[pageID].duplicatefiles[x].name + "</a></li>\n";                        dil.push("File:" + pages[pageID].duplicatefiles[x].name.replace(/_/g, " "));                    }                    output += "</ul>\n\n"                }            }            $("#mw-dupimages").append(output); if (data["query-continue"]) setTimeout("findDupImages('" + data["query-continue"].allimages.gaifrom + "');", 5000); }   }); }

$(function {     for (x in ajaxPages) {        if (wgPageName == ajaxPages[x] && $("#ajaxToggle").length == 0) ajaxRC;    }    if (wgNamespaceNumber >= 0 && !window.PurgeButtonsLoaded && document.getElementById('control_purge') == null) {        addOnloadHook(addPurgeButton);    }    var PurgeButtonsLoaded = true; // prevent duplicate running (but not dupe buttons from outside this code) });