User:KokoroSenshi/common.js

//

// // Replace mw-datatable class with wikitable class // Notes: //

console.log("|START 1-"); $("table.mw-datatable").addClass("TablePager"); console.log("|END 1---");

// // Toggle-able infobox ad placeholder // Notes: https://zeldawiki.org/index.php?title=MediaWiki:Vector.js&oldid=481538 //

console.log("|START---"); console.log("| Toggle-able infobox ad placeholder");

var elTogAd = document.createElement("li"); elTogAd.setAttribute("id","t-toggleinfoboxadspace");

var elTogAdLink = document.createElement("a"); elTogAdLink.textContent = "Toggle Infobox Adspace"; elTogAdLink.setAttribute("href", "javascript:toggleinfoboxadspace;"); elTogAdLink.setAttribute("title", "Show or hide the Infobox Adspace");

elTogAd.appendChild(elTogAdLink);

var elSpecialpages = document.getElementById("t-specialpages"); elSpecialpages.parentNode.insertBefore(elTogAd, elSpecialpages);

var namespace = mw.config.get("wgCanonicalNamespace"); var isContentNamespace = (namespace == "" || namespace == "Community"); if(isContentNamespace) { if ($(".infobox-curse-ad").length == 0){ //no infobox present (.infobox-curse-ad is used in the infobox tables) $("#mw-content-text").prepend(' Infobox Adspace  '); } else { //infobox present $(document).ready($(".infobox-curse-ad").append(' Infobox Adspace  ')); } }

function toggleinfoboxadspace{ elAdspace = document.getElementById("infobox-ad-placeholder"); elAdspace.style.display = ((elAdspace.style.display == 'none') ? '' : 'none'); }

console.log("| Done!"); console.log("|END--");

// // Fix not jumping to section after redirect on Chrome, etc. // Notes: http://stackoverflow.com/questions/10654244/chrome-bug-or-coding-error-anchor-id-links-within-destination-page-not-working#10655578 //       That is, Chrome is checking for anchor/id before it's load ed into the page //         (but only when arrive through redirect, for whatever reason...) //       Need to identify when the browser isn't jumping automatically - can't differentiate from user scrolling themselves, //         so instead for now check if page is Article#section and came from redirect page //

console.log("|START---"); console.log("| Fix not jumping to section");

$(document).ready(function {

console.log("| Document ready"); var loc = document.location, elContentSub;

if (loc.hash!==""      && (elContentSub = document.getElementById("contentSub").firstChild)      && elContentSub.getAttribute("class")==="mw-redirectedfrom"      /* document.body.scrollTop===0 */ ){ console.log("| Do the jump!"); document.location=loc; } else { console.log("| Didn't need to jump?"); };

console.log("|END-");

});

// // Add Special:ExpandTemplate shortcut to Sidebar //

console.log("|START---"); console.log("| Add Special:ExpandTemplate shortcut to Sidebar");

var elExp = document.createElement("li"); elExp.setAttribute("id","t-expandtemplates");

var elExpLink = document.createElement("a"); elExpLink.textContent = "Expand templates"; elExpLink.setAttribute("href", "/Special:ExpandTemplates"); elExpLink.setAttribute("title", "Expand templates and preview wikitext");

elExp.appendChild(elExpLink);

var elSpecialpages = document.getElementById("t-specialpages"); elSpecialpages.parentNode.insertBefore(elExp, elSpecialpages); console.log("| Done!"); console.log("|END--");

// // External wiki redirect prompt // Test to make a dialogue box ask whether to redirect when sent to soft redirect pages // Notes: .firstChild should have worked(?) but didn't?; console.log("| "+elSoftRedirect.children[0]); //An alternative //       http://stackoverflow.com/questions/18507839/order-of-evaluation-in-if-statement-in-javascript# //       http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons //       ... !== ""/*Also fails if not a string; won't convert to string to test*/ //       http://www.sitepoint.com/javascript-vs-jquery-html-collections/ //       Need return value of settimeout https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout#Example //       Just making sure http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3 //       http://stackoverflow.com/questions/1575141/make-div-100-height-of-browser-window //       Based on: http://rewdy.com/tools-files/leaveNotice/example.html // TODO: Move styles to css? //       Move notes to the talk page perhaps //       Convert the element creation to jQuery for maintainability? //       What should be converted to jQuery for compatibility? //

console.log("|START---"); console.log("| External wiki redirect prompt");

/* Get the element with the soft redirect text (null if none/not found) */ var elSoftRedirect = document.getElementById("softredirect"); console.log("| #softredirect: "+elSoftRedirect);

/* Check if softredirect page */ if (elSoftRedirect !== null) {

/* If soft redirect page */

console.log("| This is a softredirect");

//Get the elements that should have the article and wiki names var elArticleName = elSoftRedirect.firstElementChild, elWikiName   = elSoftRedirect.lastElementChild; console.log("| ArticleName element: " + elArticleName); console.log("|   WikiName element: " + elWikiName   );

//If destination article url exists if ( elArticleName !== null && elArticleName.hasAttribute("href") ) {

//Set the article name according to the html inside elArticleName: var strArticleName; if ( elArticleName.innerHTML !== "" ) { strArticleName = elArticleName.innerHTML; } else { strArticleName = "an article"; };

//Set the wiki name according to the html in elWikiName (no WikiName if target is special page): var strWikiName; if ( elWikiName !== null && elWikiName.innerHTML !== "" ) { strWikiName = elWikiName.innerHTML; } else if (false/*<- change this */) { /* See if a special page, that is, so WikiName but domain is zeldawiki */ } else { strWikiName = "another Wiki"; };

//Set the target URL to the one in elArticleName var targetURL = elArticleName.getAttribute("href"); console.log("| The destination URL: " + targetURL);

//Display the soft-redirect message box ConfirmRedirect(strArticleName, strWikiName, targetURL, 4e3);

} else { /* If somehow there is no URL to go to, do nothing */ console.log("| Error: No redirect destination URL found"); };

} else { /* If not a soft redirect page, do nothing */ console.log("| There's no softredirect"); }; console.log("|END-");

/* Show the message box, with links, timeout and fade ~ http://rewdy.com/tools-files/leaveNotice/example.html */ function ConfirmRedirect(Where, Domain, url, timeOut){ console.log("||---"); console.log("|| ConfirmRedirect function "); console.log("|| Heading to " + Where + " at/on " + Domain + " at " + url); console.log("|| Time before automatically redirects: " + timeOut);

//Darken the background var elDark document.body.appendChild(   elDark =       newElem( "div", "opacity: 0.3; position:fixed; top:0; left:0; width:100%; height:100%; background-color:#000;", "msg-dimmer" ) );

//Add the container var elContainer document.body.appendChild(   elContainer =       newElem( "div", "position:fixed; top:20%;/* ? */ top:20vh;/* 20% of viewport*/ left:0px; width:100%;", "msg-container" ) );  //Put the text box (empty) in the container var elBox elContainer.appendChild(   elBox =       newElem( "div", "width:460px; margin:0px auto; min-height:100px; background-color:rgb(29, 87, 139); border:5px solid #0B284F; text-align:center; padding:15px;border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px; -khtml-border-radius:10px; -icab-border-radius:10px; -o-border-radius:10px", "msg-box" ) );

//Add 2 lines of text and a cancel button to the textbox elBox.appendChild(   newElem( "p", null, "msg-l1", "The link you clicked will navigate you outside of " + wgSiteName, "wikitable" ) );

var elText2 elBox.appendChild(   elText2 =       newElem( "p", null, "msg-l2", "You will soon be navigated to:", "wikitable" ) );  //Set innerHTML text: elText2.innerHTML = elText2.innerHTML + ' '+document.getElementById("softredirect").innerHTML+' ';

//If deviating from default text, like altering links you can use the following: //Change the newElem text argument to: // "You will soon be navigated to "+Where //Use instead of the innerHTML text: // if (Domain !== "") elText2.textContent = elText2.textContent+" on "+Domain;

//Add the cancel instructions with cancel button to the textbox var elText3 elBox.appendChild(   elText3 =       newElem( "p", "line-height: 2.5em;", "msg-cancel", " or press the ESC key.", "wikitable" ) );  //Add the cancel button elText3.innerHTML = 'Stay here!'+elText3.innerHTML;

//This navigates to the target page after __ seconds; Stores the timer in goNavigate var goNavigate = setTimeout(     function  {        elText3.innerHTML = ' Loading... ';        window.location.href = url      },      timeOut /* param */    );

//https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent //https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key //https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#Example //http://stackoverflow.com/questions/3476000/javascript-key-handling-and-browser-compatibility ////jQuery is probably better for compatibility and ease in this case... if I understood how to use it here ////http://api.jquery.com/keyup/ // as long as jquery is with zeldawiki, scratchpad jquery will work. //$.sadfghj is the usual syntax? (after all, jquery is just abstraction, thus are functions, in javascript?). the contains #asdf for element asdf, document <-goes straight in not quotes, etc.

//When cancel is clicked or Esc pressed: // Cancels countdown and Esc key monitor, removes the message box $('#link-cancel').click(function {    beGone;    $('#msg-dimmer, #msg-container').remove;  }); $(document).bind('keyup', function (e) {   if (e.which == 27) {      beGone;      $('#msg-dimmer, #msg-container').remove;    };  }); //When page starts to unload on navigation, remove the countdown and Esc key monitor $(window).unload(function {    beGone;  }); }

//Create a simple html element // Use null for empty parameters function newElem(type, style, id, text, classes){ var elem = document.createElement(type); if (style  !== null){ elem.setAttribute("style",style);   }; if (id     !== null){ elem.setAttribute("id",id);         }; if (text   !== null){ elem.textContent = text;            }; if (classes !== null){ elem.setAttribute("class",classes); }; return elem; };

//Cancels countdown and Esc key monitor function beGone{ clearTimeout(goNavigate); $(document).unbind('keyup'); }

// // Automatic purge cache after new version upload aka reupload // Notes: Only perform if both this and the prev page were the reupload page then image page //       (in simplicity, just test for existence, though could be more efficient to match, then use the reupload page's image name //         in the search string for current url) //       Renavigate won't work + reload gives infinite loop + server purge isn't the issue so pointless //         //location = window.location.href;//window.location.reload(true); //       Something about the way Doin (user at stackoverflow) did it makes the onload/etc. work //       The file history uses a thumbnail (unless it's a small file) which is updated/generated after reupload(?); if file is //         small, then it won't create a thumbnail(?) //       So, only the non-thumb image is stuck in cache(?), so need to refresh that src only, but need to remove both main and //        most recent file history src.s also jic // Relating to Doin's code: //       http://stackoverflow.com/questions/3535996/jquery-javascript-functione-what-is-e-why-is-it-needed-what-does-it-ac# //       ////set iframe0.src after addEventListener? Though addEventListener then needs 'firstrun'(?) to not put back src.s early//// //       //Need the "window." ?//http://stackoverflow.com/questions/588040/window-onload-vs-document-onload // // nup?: http://www.satya-weblog.com/2010/04/how-to-delete-cached-file-on-client-side.html //       http://websistent.com/javascript-reload-image/ // // Ref: document.referrer    https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer //     .search( ... )        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search //     window.location.href  https://developer.mozilla.org/en-US/docs/Web/API/Window/location //     |                       https://developer.mozilla.org/en-US/docs/Web/API/Location //     wg stuff              https://www.mediawiki.org/wiki/Manual:Interface/JavaScript //     RegExp                https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions //     RegExp checker       http://www.regexr.com/ //     Tip: Use mozilla's scratchpad to debug js //      Works, once you replace the relevant stuff that scratchpad gives error //                           http://stackoverflow.com/questions/321865/how-to-clear-or-replace-a-cached-image#22430452 //                           http://stackoverflow.com/questions/1077041/refresh-image-with-a-new-one-at-the-same-url#22429796 //     loop                  http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript //     var.s ! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var //     Need the "window." ? http://stackoverflow.com/questions/588040/window-onload-vs-document-onload // // RegExp info: Encase like so / ... / ; the operations typically operate on preceding char; \ to escape; ? ops to 0 or 1 of; //             * ops to 0 or more of;. represents most characters; {1,5} ops to 1 ot 5 of; // // TODO: Make url checking better? //      Probably don't need to check if src exists if thisURL and prevURL are right (though jic, to not break the whole script?) //      Extra large images create a medium size thumbnail too! is that auto-updated/generated? I suppose I need to reverse-eng the //       image url/src in that case? //      Images of index 1 and 2 are the game image and license image, which usually but may not exist; thus, just loop to temp //       remove over all images to be safe? //

console.log("|---"); console.log("To avoid having to reupload, now that the validation definitely works, made a link to replace this user action"); if (location.href.search(/File=.*\..{1,5}/) != -1){ document.getElementById("n-mainpage").firstChild.innerHTML = 'CLICK OVER HERE CLICK OVER HERE CLICK OVER HERE CLICK OVER HERE' }; console.log("| Purge image cache after reupload - START"); //Get previous page URL (then later test if is a reupload page) prevURL = document.referrer; //Get previous url //It's possible for prevURL to be empty if not navigated through links, e.g. address bar/back-button, etc. so check this first(?): if (prevURL != "") { console.log("| The previous URL is: "+prevURL); var prevRE = /https?:\/\/zeldawiki\.org\/index\.php\?title=Special:Upload&wpDestFile=.*\..{1,5}&wpForReUpload=1.*/; //RegExp //Test if prevURL is a reupload page: if (prevURL.search(prevRE) != -1){ //If prevURL is a reupload page console.log("| The previous URL was a reuploading page"); //Get current URL + test if the image page that would follow after upload var thisURL = window.location.href; //Get current url console.log("| This URL is: "+thisURL); var thisRE = /https?:\/\/zeldawiki.org\/File:.*\..{1,5}/; //RegExp //Test if thisURL is an image page: if (thisURL.search(thisRE) != -1) { console.log("| This url is an image page"); console.log("| Time to refresh image cache:"); purgeImgCache; } else { console.log("| This url isn't an image page - END"); }; } else { console.log("| Previous url isn't (a) reupload page - END"); }; console.log("|---"); } else { console.log("| No previous url - END");console.log("|---"); };

function purgeImgCache{ console.log("||---"); console.log("|| Start Img cache purge, may not work in all situations");

//Find the imgs and their src.s var elBodyText = document.getElementById("mw-content-text"); //main body element that hold the actual page content console.log("|| "+elBodyText); var arrayImgEl = elBodyText.getElementsByTagName("img"); //Array of all img elements in the main body console.log("|| "+arrayImgEl); //Test if first img (main image/medium-thumbnail) has src then store it if ( arrayImgEl[0].hasAttribute("src") ){ var source0 = arrayImgEl[0].getAttribute("src"); //arrayImgEl[0].src retrieves full url instead btw }; //Test if first img (first image/small(?)-thumbnail in File History) has src then store it  if ( arrayImgEl[3].hasAttribute("src") ){ var source3 = arrayImgEl[3].getAttribute("src"); //arrayImgEl[3].src retrieves full url instead btw };

//Blank or remove the src.s to avoid issues when refreshing arrayImgEl[0].setAttribute("src",""); arrayImgEl[3].setAttribute("src",""); console.log("|| http://zeldawiki.org"+source0); //Create iframe, add it to the page, add the src.s var step = 0, iframe0 = window.document.createElement("iframe");//Need the "window." ?//http://stackoverflow.com/questions/588040/window-onload-vs-document-onload iframe0.style.display = "none"; //So it takes up no space window.parent.document.body.appendChild(iframe0);///document.body.appendChild(iframe0); //?

console.log("|| "+iframe0.contentWindow); //Should be about:blank, not null?

//Wait for load (only Doin's way works??) iframe0.addEventListener("load" ,refreshOrDone,false); iframe0.addEventListener("error",refreshOrDone,false); iframe0.src = source0; //"http://zeldawiki.org"+ function refreshOrDone{ if (!step) // "initial load just completed.  Note that it doesn't actually matter if this load succeeded or not!" {     step = 2; iframe0.contentWindow.location.reload(true); // "initiate forced-reload" }   else if (step===2)   // "forced re-load is done" {     arrayImgEl[0].setAttribute("src",source0); arrayImgEl[3].setAttribute("src",source3); console.log("|| loaded?"); if (iframe0.parentNode) iframe0.parentNode.removeChild(iframe0); }; }  //console.log("||---"); }

//