Jump to content

User:Intelligentsium/assess.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
if(wgNamespaceNumber==0 && wgAction == "view") addOnloadHook(addEvalTab)
 
function addEvalTab()
{
	var list = document.getElementById('p-cactions')
 
	if(!list) return
 
	list = list.childNodes[3].childNodes[1]
 
	var elt = document.createElement('li')
	elt.innerHTML = "<a id='caa_evaluation' href='javascript:launchEval()'>Evaluate</a>"
	list.appendChild(elt)
 
 
	try {if(alwaysEval){launchEval()}}
	catch(e){ }
}
 
 
//initialise les variables 
function initVars()
{	
     initEvalProjectNames()
 
	try {if(evalProjectNames){}}
	catch(e){ evalProjectNames = new Array() }
 
	evaluation = new Object() 
 
	evaluation.project = new Array()
	evaluation.class = new Array()
	evaluation.importance = new Array()
	evaluation.state = new Array()
	evaluation.box = new Array()
}
 
function launchEval()
{
	var req=new XMLHttpRequest()
	var div = document.getElementById('bodyContent')
	var dummy = new Date().getTime()
 
	if (document.URL.match(/&printable/))
	{
	    /* Printable version*/
	    return;
	}
 
 
	EvalDiv = document.getElementById('EvalDiv')
 
	if(!EvalDiv)
	{
	    EvalDiv = document.createElement('div')
	    EvalDiv.id = "EvalDiv"
	    EvalDiv.align="center"
	    div.parentNode.insertBefore(EvalDiv, div)
	}
 
	EvalDiv.innerHTML = "Loading talk page..."
 
	initVars()
 
	req.onreadystatechange = function()
	{
	    if(req.readyState == 4)
	    {
		if(req.status==200)
		{	
		    ExtractEvaluation(req.responseText)
 
		    AddMyProjects()
		    drawEvaluation()
		}
		else if(req.status==404) //The PDD does not exist
		{
		    AddMyProjects()
		    drawEvaluation()
		}
	    }//fin readyState == 4
	}
 
	req.open("GET","/w/index.php?title=Talk:" + encodeURIComponent(wgPageName)   + "&action=raw&_dum=" + dummy, true)
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
	req.send(null)
}
 
function addCell(line, html, bgcolor)
{
	var cell = line.insertCell(-1)
	cell.innerHTML = html
 
	if(bgcolor) cell.style.backgroundColor = "#" + bgcolor
 
	return cell
 
}
function htmlEncode(string)
{
	string = string.replace(/&/, '&amp;');
	string = string.replace(/>/, '&gt;');
	string = string.replace(/</, '&lt;');
	string = string.replace(/"/, '&quot;');
	return string
 
}
 
function getProjectAnchor(project)
{
     return '<a title="project:' + htmlEncode(project) + '" href="/wiki/project:' + encodeURIComponent(project) + '">' + project + '</a>'
}
 
function getRadioboxHtml(id, selected, n, prop, value)
{
	return "<input onclick='evaluation." + prop + "["+n+"]=\"" + value + "\"'  name='" + id + "' type='radio'" + (selected?" checked='true'/>":"/>")
}
 
 
function getCheckboxHtml(selected, n)
{
	return "<input onclick='evaluation.state["+n+"]=this.checked' type='checkbox'" + (selected?" checked='true'/>":"/>")
}
 
function addEvalLine(tab, project, av, im, state, n)
{
	var line = tab.insertRow(-1)
 
	addCell(line, getProjectAnchor(project))
	addCell(line, getCheckboxHtml(state, n))
	addCell(line, getRadioboxHtml(n+"a", av=="FA", n, "class", "FA"))
	addCell(line, getRadioboxHtml(n+"a", av=="A", n, "class", "A"))
	addCell(line, getRadioboxHtml(n+"a", av=="B", n, "class", "B"))
	addCell(line, getRadioboxHtml(n+"a", av=="C", n, "class", "C"))
                  addCell(line, getRadioboxHtml(n+"a", av=="Start", n, "class", "start"))
	addCell(line, getRadioboxHtml(n+"a", av=="Stub", n, "class", "stub"))
	addCell(line, getRadioboxHtml(n+"a", av=="?", n, "class", "?"))
	addCell(line, getRadioboxHtml(n+"i", im=="Top", n, "importance", "top"))
	addCell(line, getRadioboxHtml(n+"i", im=="High", n, "importance", "high"))
	addCell(line, getRadioboxHtml(n+"i", im=="Middle", n, "importance", "mid"))
	addCell(line, getRadioboxHtml(n+"i", im=="Low", n, "importance", "low"))
	addCell(line, getRadioboxHtml(n+"i", im=="?", n, "importance", "?"))
}
 
function drawEvaluation()
{
	var tab = document.createElement("table")
	var line = tab.insertRow(-1)
	var button  = document.createElement("button")
 
	addCell(line, "<b>Project</b>", "F8F8F8")
	addCell(line, "<b>Banner</b>", "F8F8F8")
	addCell(line, "<b>FA</b>", "6699FF")
	addCell(line, "<b>A</b>", "66FFFF")
	addCell(line, "<b>B</b>", "66FF66")
	addCell(line, "<b>C</b>", "FFFF66")
	addCell(line, "<b>Start</b>", "FFAA66")
	addCell(line, "<b>Stub</b>", "FF6666")
	addCell(line, "<b>?</b>", "F8F8F8")
	addCell(line, "<b>Top</b>", "FF00FF")
	addCell(line, "<b>High</b>", "FF88FF")
	addCell(line, "<b>Middle</b>", "FFCCFF")
	addCell(line, "<b>Low</b>", "FFEEFF")
	addCell(line, "<b>?</b>", "F8F8F8")
 
	for(var i=0; i<evaluation.project.length; i++)
		addEvalLine(tab, evaluation.project[i], evaluation.class[i], evaluation.importance[i], evaluation.state[i], i)
 
	tab.className = 'wikitable'
	tab.style.textAlign = 'center'
	tab.style.fontSize = '90%'
	EvalDiv.innerHTML = ''
	EvalDiv.appendChild(tab)
 
	button.textContent = "Assess!"
	button.onclick = setEvaluation
	button.id='EvalButton'
	EvalDiv.appendChild(button)
}
 
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;
 
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;
 
    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
 
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function"){
      throw new TypeError();
     }
    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }
 
    return res;
  };
}
 
function AddMyProjects()
{
 
	for(var i=0; i<evalProjectNames.length;i++)
	{
		if(evaluation.project.indexOf(evalProjectNames[i]) == -1)
		{
			var t = evaluation.project.length
 
			evaluation.project[t] = evalProjectNames[i]
			evaluation.class[t] = "?"
			evaluation.importance[t] = "?"
			evaluation.state[t] = false
		}
	}
 
}
 
function ExtractEvaluation(discussion)
{
	var modeles
 
	discussion = " "  + discussion
	modeles = discussion.split(/\{\{[W|w]ikiproject /)
	modeles.shift()
 
     for(var i=0;i<modeles.length;i++)
     {
          try
          {    
     		modeles[i] = modeles[i].split("}}")[0]
     		var temp = modeles[i].split("|")
     		evaluation.project[i] = temp[0]
     		evaluation.class[i] = "?"
     		evaluation.importance[i] = "?"
 
               if(temp.length >= 2) getOldEval(temp[1], i)
               if(temp.length >= 3) getOldEval(temp[2], i)
               if(temp.length >= 4) getOldEval(temp[3], i)
 
     		evaluation.state[i] = true
     	}
          catch(e){}
     }
}
 
function cleanclass(val)
{
     if(val=="A") return "A"
     if(val=="B") return "B"
     if(val=="C") return "C"
     if(val=="start") return "start"
     if(val=="stub") return "stub"
 
     return "?"
}
 
 
function cleanImportance(val)
{
     if(val.toLowerCase()=="top") return "top"
     if(val.toLowerCase()=="high") return "high"
     if(val.toLowerCase()=="mid") return "mid"
     if(val.toLowerCase()=="low") return "low"
 
     return "?"
}
 
function getOldEval(str,i)
{
     var params = str.split("=")
 
     if(params[0]=="importance") evaluation.importance[i] = cleanImportance(params[1])
     else if(params[0]=="class") evaluation.class[i] = cleanclass(params[1])
     else if(params[0]=="box") evaluation.box[i] = params[1]
 
}
 
 
 
function setEvaluation()
{
     document.getElementById("EvalButton").disabled = true
     wpEditPage("Talk:" + wgPageName, {}, editFoo, saveFoo, {})
}
 
function editFoo(text, summary, doc, data)
{
     summary = "[[User:Maloq/Evaluation|Évaluation]]: "
 
     for(var i=0;i<evaluation.project.length;i++)
     {
          text = process(i , text)
          summary = summary + getSummary(i)
     }
 
          toto = 2
    	return { wpTextbox1: text, wpSummary: summary, data: data };
}
 
function saveFoo()
{
     document.getElementById("EvalButton").disabled = false
}
 
function getSummary(i)
{
     if (evaluation.state[i]) return  "(" +  evaluation.project[i] + "|" + evaluation.class[i]+ "|" + evaluation.importance[i] + ") "
     else return ""
}
function process(i, text)
{
     var regtxt = "/\\{\\{[W|w]ikiproject " + evaluation.project[i] + "[^\\}]*\\}\\}/"
     var newtxt = "{{Wikiproject "+evaluation.project[i]+"|class="+evaluation.class[i]+"|importance="+evaluation.importance[i]
 
    if(evaluation.box[i]) newtxt+="|box="+evaluation.box[i]
    newtxt+="}}"
 
     if(text.toLowerCase().indexOf("{{wikiproject " + evaluation.project[i].toLowerCase()) != -1)
     {
          if(evaluation.state[i]) text = eval("text.replace(" + regtxt + ",'" + newtxt + "')")
          else text = eval("text.replace(" + regtxt + ",'')")
     }
     else
     {
          if(evaluation.state[i]) text = newtxt + "\n" + text
     }
 
     return text
}  
 
 
 
/////////////////////////////////////////////////////////from tichou
 
 
 
// URL encode
if (typeof(wpURLEncode) == "undefined") {
  wpURLEncode = function(string) {
    if (!string) return "";
    return string.replace(/ /g, "_").replace(/[\x00-\x2C\x3B-\x40\x5B-\x5E\x60\x7B-\uFFFF]/g,
      function (match) {
        var c = match.charCodeAt(0);
        var s = new Array();
        if (c < 0x80) s.push(c);
        else if (c < 0x0800) s.push(c >>  6 | 0xC0, c & 0x3F | 0x80);
        else if (c < 0x010000) s.push(c >> 12 | 0xE0, c >>  6 & 0x3F | 0x80, c & 0x3F | 0x80);
        else if (c < 0x110000) s.push(c >> 18 | 0xF0, c >> 12 & 0x3F | 0x80, c >>  6 & 0x3F | 0x80, c & 0x3F | 0x80);
        for (var i = 0, len = s.length; i < len; i++)
          s[i] = (s[i] < 16 ? "%0" : "%") + s[i].toString(16).toUpperCase();
        return s.join("");
      });
  }
}
 
// getElementById
if (typeof(getElementById) == "undefined") {
  getElementById = function(id) {
    var element = null;
    if (this.id == id) {
      element = this;
      element.getElementsByClassName = document.getElementsByClassName;
    }
    for (var child = this.firstChild; !element && child; child = child.nextSibling)
      if (child.nodeType == 1) {
        child.getElementById = getElementById;
        element = child.getElementById(id);
      }
    return element;
  }
}
 
// HTTP
if (typeof(httpRequest) == "undefined") {
  httpRequest = function(url, options, data) {
    // options.async
    // options.method
    // options.headers
    // options.content
    // options.onSuccess(request,data)
    // options.onFailure(request,data)
    var request;
    try {
      request = new XMLHttpRequest();
    } catch(e) {
      try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          request = false;
        }
      }
    }
 
    if (request) {
      request.onreadystatechange = function() {
        if (request.readyState == 4)
          httpComplete(request, options, data);
      };
      request.open(options.method ? options.method : "GET", url, options.async == false ? false : true);
      if (options.headers) {
        for (var field in options.headers)
          request.setRequestHeader(field, options.headers[field]);
      }
      request.send(options.content ? options.content : null);
    }
    return request;
  }
}
 
if (typeof(httpComplete) == "undefined") {
  httpComplete = function(request, options, data) {
    if (request.status >= 200 && request.status < 300) {
      if (options.onSuccess) {
        var contentType = request.getResponseHeader("Content-Type");
        var regex = new RegExp(/^([^\/]+\/[^;]+).*/);
        contentType = contentType.replace(regex, "$1");
        if (contentType == "text/html") {
          var doc = document.createElement("div");
          doc.innerHTML = request.responseText;
          doc.getElementsByClassName = document.getElementsByClassName;
          doc.getElementById = getElementById;
          options.onSuccess(doc, data);
        } else if (contentType == "text/xml") {
          var xml = null;
          if (navigator.appName == "Microsoft Internet Explorer") {
            xml = new ActiveXObject("Microsoft.XMLDOM");
            xml.async = false;
            xml.loadXML(request.responseText);
          } else if (window.DOMParser) {
            xml = new DOMParser();
            xml = xml.parseFromString(request.responseText, 'text/xml');
          }
          options.onSuccess(xml, data);
        } else {
          options.onSuccess(request, data);
        }
      }
    } else if (options.onFailure) {
      options.onFailure(request, data);
    } else {
      alert(request.statusText);
    }
  }
}
 
// Edit WP page
if (typeof(wpEditPage) == "undefined") {
  wpEditPage = function(title, params, editFunction, saveFunction, data) {
    var url = wgServer + wgScriptPath + '/index.php?title=' + wpURLEncode(title)
            + '&action=edit';
 
    for (var name in params)
      url += '&' + name + '=' + wpURLEncode(params[name]);
 
    var options = { onSuccess: wpSavePage };
 
    data.title = title;
    data.editFunction = editFunction;
    data.saveFunction = saveFunction;
 
    httpRequest(url, options, data);
  }
}
 
// Save WP page
if (typeof(wpSavePage) == "undefined") {
  wpSavePage = function(doc, data) {
    var inputs = doc.getElementById('editform').getElementsByTagName('input');
    var editform = new Array();
    for (var i = 0, len = inputs.length; i < len; i++) 
    {
    	var value = inputs[i].value
    	if(inputs[i].type != "checkbox" || inputs[i].checked) 
		   	editform[inputs[i].name] = value;
    }
 
    var wpTextbox1 = doc.getElementById('wpTextbox1').value;
    var wpSummary = editform['wpSummary'];
 
    var regex = new RegExp(/var wgArticleId = "(\d+)";(?:\n.*)*var wgCurRevisionId = "(\d+)";/m);
    var match = regex.exec(doc.textContent);
    if (match) {
      data.pageId = match[1];
      data.curRevId = match[2];
    }
 
    var edit = data.editFunction(wpTextbox1, wpSummary, doc, data);
 
    if (typeof(edit.error) == "undefined") { 
      editform['wpTextbox1'] = edit.wpTextbox1;
      editform['wpSummary'] = edit.wpSummary;
 
      var params = [ 'wpTextbox1', 'wpSummary', 'wpSection',
                     'wpStarttime', 'wpEdittime', 'wpEditToken', 'wpSave' ];
 
      if(editform['wpWatchthis']) params.push('wpWatchthis')
      var content = params.map(function(name) { return name + '=' + encodeURIComponent(editform[name]); }).join("&");
 
      var url = wgServer + wgScriptPath + '/index.php?title=' + wpURLEncode(data.title)
              + '&action=submit';
 
      var headers = new Array();
      headers['Content-Type'] = 'application/x-www-form-urlencoded';
 
      var options = { method: 'POST', headers: headers, content: content, onSuccess: data.saveFunction };
 
      data = edit.data;
 
      httpRequest(url, options, data);
    } else {
      edit.error(edit.data);
    }
  }
}
 
var wpfunctions = 1;
var alwaysEval = false;

function initEvalProjectNames()

{

evalProjectNames=new Array(); 

evalProjectNames.push("Animals") 

evalProjectNames.push("Fishes")

        evalProjectNames.push("Mammals")

        evalProjectNames.push("Plants")

        evalProjectNames.push("Amphibians and Reptiles")

}