User:Writ Keeper/Scripts/autoping.js

textboxHasGottenFocus = false; previousIndex = 0; prefixArray=["@User:","@[[User:","[[User:","[[User:"," [[User:"]; suffixArray=[": ","]]","]]","]]","]] "]; if(typeof teahouseNotified == "undefined") {	teahouseNotified = false; }

$(document).ready(function {	if(mw.config.get("wgAction") == "edit" && document.URL.indexOf("section") >= 0)	{		var uniqueUserNames = new Object;		var regex = /\[\[User:([^|#\/\]]+)/g;		var regexResult=$("#wpTextbox1").val.match(regex);		if(regexResult != null)		{			for(i = 0; i < regexResult.length; i++)			{ 				uniqueUserNames[regexResult[i].substr(7).replace("_", " ")] = "1";			}			$("#wpSummaryLabel").before(' Select a user to ping: ' + Object.keys(uniqueUserNames).join("  ") + '  ');			$("#pingMenu").after(' @Foo:  @Foo  Foo  bar  (hidden)  ');			$("#wpTextbox1").focus(function{textboxHasGottenFocus = true;});			previousIndex = $("#wpTextbox1").val.length;			$("#pingMenu").change(function {				if(this.selectedIndex > 0) {					var pingStyle = $("#pingStyleMenu").prop("selectedIndex"); if(pingStyle < 0 || pingStyle > 4) {						pingStyle = 0; }					var pingPrefix = prefixArray[pingStyle] + $(this).val; var pingPipe = $(this).val; var pingSuffix = suffixArray[pingStyle]; if(pingStyle == 4) {						pingPipe = ""; }					else {						pingPrefix += "|"; if(pingStyle == 3) {							pingPipe = "piped text"; }					}					//if mw.toolbar api is available, use that to insert the ping if(typeof mw.toolbar != "undefined") {						if(pingStyle == 3) {								mw.toolbar.insertTags(pingPrefix,pingSuffix,pingPipe); }						else {							mw.toolbar.insertTags(pingPrefix + pingPipe + pingSuffix, "", ""); }					}					else {						//This section of code adapted from Ryan and Maximilian Ruta's answer at http://stackoverflow.com/questions/1891444/cursor-position-in-a-textarea-character-index-not-x-y-coordinates var el = $("#wpTextbox1").get(0); var pos = 0; //if the textbox hasn't gotten focus yet, or since the last ping, we default to the end of the last ping (or just the end). if we don't handle this specifically, things get weird if(!textboxHasGottenFocus) {							pos = previousIndex; }						else if('selectionStart' in el) {							pos = el.selectionStart; } else if('selection' in document) {							el.focus; var Sel = document.selection.createRange; var SelLength = document.selection.createRange.text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; }						//end attribution $("#wpTextbox1").val($("#wpTextbox1").val.substr(0, pos) + pingPrefix + pingPipe + pingSuffix + $("#wpTextbox1").val.substr(pos)); previousIndex = ($("#wpTextbox1").val.substr(0, pos) + pingPrefix + pingPipe + pingSuffix).length; textboxHasGottenFocus = false; }					teahouseNotified = true; }			});		}	} });