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.
// imports etc.

if (!jQuery) importScript('User:M/jquery.js');
/* debug - v0.3 - 6/8/2009 http://benalman.com/projects/javascript-debug-console-log/
 * Copyright (c) 2009 "Cowboy" Ben Alman. Licensed under the MIT license http://benalman.com/about/license/
 * With lots of help from Paul Irish! http://paulirish.com/
 */
window.debug=(function(){var c=this,e=Array.prototype.slice,b=c.console,i={},f,g,j=9,d=["error","warn","info","debug","log"],m="assert clear count dir dirxml group groupEnd profile profileEnd time timeEnd trace".split(" "),k=m.length,a=[];while(--k>=0){(function(n){i[n]=function(){j!==0&&b&&b[n]&&b[n].apply(b,arguments)}})(m[k])}k=d.length;while(--k>=0){(function(n,o){i[o]=function(){var q=e.call(arguments),p=[o].concat(q);a.push(p);h(p);if(!b||!l(n)){return}b.firebug?b[o].apply(c,q):b[o]?b[o](q):b.log(q)}})(k,d[k])}function h(n){if(f&&(g||!b||!b.log)){f.apply(c,n)}}i.setLevel=function(n){j=typeof n==="number"?n:9};function l(n){return j>0?j>n:d.length+j<=n}i.setCallback=function(){var o=e.call(arguments),n=a.length,p=n;f=o.shift()||null;g=typeof o[0]==="boolean"?o.shift():false;p-=typeof o[0]==="number"?o.shift():n;while(p<n){h(a[p++])}};return i})();

function logg(message) {
	debug.log(message);
	//if (console && console.log) console.log(message);
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) oldonload();
      func();
    }
  }
}

// =============== REWORD ===============
var rewordComment = (rewordComment? rewordComment:"---");
var qeSpecialSequences ={};
function rewordReplace(key, value) {
	qeSpecialSequences[key] = value;
}
rewordReplace("\\n","\n");

(function() { //closure

var $=jQuery;
addLoadEvent(enableQuickEditing); // can't use jquery onload due to importScript() lag

qeTextSel="";
function enableQuickEditing() {
	//if (window.location.href.indexOf("index.php") != -1) return;
	if(wgNamespaceNumber < 0) return;
	updateData(); //TODO: make lazy
	
	$("body").mouseup(releaseSelection);
	$("body").mousedown(updateCursor);
	$("body").mousemove(updateCursor);
}

//that you insert on this page could contain malicious content capable of compromising //for testing

function updateCursor(e) {
	logg("updating cursor");
	if (qeTextSel==getSelectedText() && e.ctrlKey) return;
	if (! e.ctrlKey) {
		$("#bodyContent").css("background","");
		return; // ignore ctrl not held
	}

	logg("updating cursor - valid");
	var xqeTextSel = getSelectedText();
	var xqeHtmlSel = getSelectedHtml();
	var text = (xqeHtmlSel==xqeTextSel?xqeTextSel:xqeHtmlSel);
	if (xqeTextSel.length > 5) {
		logg("updating cursor >5");
		var first = qeText.indexOf(text);
		var second = qeText.indexOf(text, first+1);
		var bgColor="";
		if (first!=-1 && second==-1) {
			bgColor = "#efe"; // 'crosshair';
		} else {
			bgColor = second==-1?"#fee":"#ffe"; //(second==-1?'help':'move');
		}
		$("#bodyContent").css("background",bgColor);
	}
	//var newText=getSelectedText();
}

function releaseSelection(e){
	logg("released");
	if (qeTextSel==getSelectedText()) return; //ignore stray mouse clicks
	if (! e.ctrlKey) return; // ignore ctrl not held

	logg("released - valid");

	qeTextSel = getSelectedText();
	qeHtmlSel = getSelectedHtml();
	if (qeTextSel.length > 5) {
		
		logg("released >5");
		if (qeHtmlSel==qeTextSel) {
			tryToEdit(qeTextSel);
		} else {
			tryToEdit(qeHtmlSel);
		}
	}
};

function getSelectedText(){ 
    if(window.getSelection){return window.getSelection().toString(); 
    } else if(document.getSelection){return document.getSelection(); 
    } else if(document.selection){return document.selection.createRange().text; 
    } 
}
function getSelectedHtml(){ // returns translated HTML
    if(window.getSelection){
	var frag = window.getSelection().getRangeAt(0).cloneContents()
	var $div = $("<div/>").append(frag);
	$div.children("a").each( function() {
		var $this = $(this);
		var text = $this.text();
		var ref = $this.attr("href").toLowerCase(); // TODO try both?
		ref = ref.split("_").join(" ");
		ref = ref.split("/wiki/").join("");
		//alert(text+"\n"+ref);
		$this.removeAttr("title");
		$this.removeAttr("class");
		$this.removeAttr("href");
		if (text!=ref) $this.attr("title32",ref).attr("matchscrap673","99688");
		});
		
	var trans = $div.get(0).innerHTML;
	trans = trans.split("<a>").join("[[");
	trans = trans.split("</a>").join("]]");
	trans = trans.split("<i>").join("''");
	trans = trans.split("</i>").join("''");
	trans = trans.split("<b>").join("'''");
	trans = trans.split("</b>").join("'''");
	trans = trans.split("<a title32=\"").join("[[");
	trans = trans.split("\" matchscrap673=\"99688\">").join("|");
	return trans;
    } else if(document.getSelection){ 
        return document.getSelection(); 
    } else if(document.selection){ 
        return document.selection.createRange().htmlText; 
    } 
}

function updateData() {

	$.getJSON(wgScriptPath+"/api.php?action=query&prop=revisions&titles="+wgPageName+"&rvprop=timestamp|user|comment|content&format=json",
		function(data){
			$.each(data.query.pages, function(i,item){
				qeText = item.revisions[0]["*"];
				qeTimestamp = item.revisions[0]["timestamp"];
			});
		});
}



function tryToEdit(text) {
	var first = qeText.indexOf(text);
	var second = qeText.indexOf(text, first+1);
	
	logg("trying to edit");
	if (first!=-1 && second==-1) {
		var replacement = prompt("Changing:\n <" + text + ">",text); //alert(newText);
		if (replacement==null) return;

		for (var key in qeSpecialSequences) {
			replacement = replacement.split(key).join(qeSpecialSequences[key]);
		}
		var edsum="";
		if (replacement.indexOf("~~"+"~~")!= -1) {
			edsum = "reply ";
			// TODO: perhaps display "[the first 10/20 characters]..." of the inserted comment.
		} else {
			var esIndex= replacement.indexOf(rewordComment);
			if(esIndex!= -1) {
				edsum += replacement.substring(esIndex+rewordComment.length);
				replacement = replacement.substring(0,esIndex);	
			} else {
			        edsum += "'"+text+"' → '"+replacement+"' ";
                        }
		}
		edsum += "(using [[User:M/Reword|Reword]])";

		$.getJSON(wgScriptPath + "/api.php?action=query&prop=info|revisions&intoken=edit&titles="+wgPageName+"&rvprop=timestamp|user&format=json", function(data){
			$.each(data.query.pages, function(i,item){
				qeToken = item.edittoken;
				var latestTimestamp = item.revisions[0]["timestamp"];
                                
                                if(latestTimestamp != qeTimestamp)
                                {
                                  var latestUser = item.revisions[0]["user"];
                                  alert("Reword not completed, the page has been modified by User:" + latestUser);
				  window.location.reload(true); //updateData();
			          history.go(0);
				  window.location.href=window.location.href;
				  updateData();
                                  return; // SEME
                                }

		                var newText = qeText.replace(text,replacement);
				
$.post("/w/api.php", { action: "edit", title: wgPageName, notminor:"", summary:edsum, text:newText, basetimestamp:qeTimestamp, token:qeToken, format:"json" },
					function(data) {
						alert(data);
						window.location.reload(true); //updateData();
						history.go(0);
						window.location.href=window.location.href;
						updateData();
					});
			});
		});
	} else {
		var out = "";
		out+=  second==-1?"(not found/couldn't parse)":"(not unique)";
		alert(out +"\n"+ qeTextSel+"\n"+qeHtmlSel+"\n"+text + "\n(text, html, wikitext)\n" + first + " " + second+"\n first found, second found.");
	}
}
})();