User:Scott.wheeler/relatedarticles.js

function JSONP(url)

{

this.url = url;

this.headTag = document.getElementsByTagName("head").item(0);

this.scriptId = 'JscriptId' + JSONP.scriptCounter++;

}

JSONP.scriptCounter = 1;

JSONP.prototype.buildScriptTag = function ()

{

this.script = document.createElement("script");

this.script.setAttribute("type", "text/javascript");

this.script.setAttribute("charset", "utf-8");

this.script.setAttribute("src", this.url);

this.script.setAttribute("id", this.scriptId);

}

JSONP.prototype.removeScriptTag = function ()

{

this.headTag.removeChild(this.script);

}

JSONP.prototype.addScriptTag = function ()

{

this.headTag.appendChild(this.script);

}

var RelatedArticles =

{

titles: null

}

RelatedArticles.fetch = function()

{

if(mw.config.get('wgPageName').indexOf(":") >= 0 || mw.config.get('wgPageName') == "Main_Page")

{

return;

}

var url = "http://pedia.directededge.com/api.fcgi" +

"?format=json&jsonp=RelatedArticles.callback&topic=" + encodeURI(mw.config.get('wgPageName'));

var request = new JSONP(url);

request.buildScriptTag();

request.addScriptTag();

}

RelatedArticles.callback = function(titles)

{

RelatedArticles.titles = titles;

if(window.addEventListener)

{

window.addEventListener("load", RelatedArticles.insert, false);

}

else if(window.attachEvent)

{

window.attachEvent("onload", RelatedArticles.insert);

}

else

{

throw "No event to attach to.";

}

}

RelatedArticles.insert = function()

{

var column = document.getElementById("column-one");

var search = document.getElementById("p-search");

if(!column || !search)

{

throw "Could not find column and search elements.";

}

var related = document.createElement("div");

related.setAttribute("class", "portlet");

column.insertBefore(related, search);

var label = document.createElement("h5");

label.appendChild(document.createTextNode("related articles"));

related.appendChild(label);

var pBody = document.createElement("div");

pBody.setAttribute("class", "pBody");

related.appendChild(pBody);

var list = document.createElement("ul");

pBody.appendChild(list);

var prefix = "http://en.wikipedia.org/wiki/";

for(var i = 0; i < RelatedArticles.titles.length; i++)

{

var li = document.createElement("li");

list.appendChild(li);

var link = document.createElement("a");

li.appendChild(link);

link.setAttribute("href", prefix + escape(RelatedArticles.titles[i]));

link.appendChild(document.createTextNode(RelatedArticles.titles[i]));

}

}

RelatedArticles.fetch();