User:Ryan Schmidt/Scripts/AjaxWatch.js

/** * AJAX watch feature version 1.0 * by Ryan Schmidt < http://strategywiki.org/wiki/User:Ryan_Schmidt > */

AjaxWatch = new function { //'Watch' listed twice so we don't need to do an extra if statement later on in getNextIndex this.message = ['Watch', 'Watching...', 'Unwatch', 'Unwatching...', 'Watch']; this.setup = function { var watch = document.getElementById('t-watch') || document.getElementById('t-unwatch'); if(!watch) return; addHandler(watch, 'click', AjaxWatch.watch); };	this.watch = function(e) { var evt = getEvent(e); var watch = getEventElement(evt); if(evt.preventDefault) evt.preventDefault; var href = watch.href; var ajax = getAjaxObject; var text = watch.innerHTML; var next = AjaxWatch.message[AjaxWatch.getNextIndex(text)]; watch.innerHTML = next; ajax.open('GET', href, true); ajax.onreadystatechange = function { if(this.readyState == 4) { var watch = document.getElementById('t-watch') || document.getElementById('t-unwatch'); watch = watch.getElementsByTagName('a')[0]; var text = watch.innerHTML; var next = AjaxWatch.message[AjaxWatch.getNextIndex(text)]; if(text == AjaxWatch.message[1]) { var action = 'added to'; watch.href = watch.href.replace(/action=watch$/, 'action=unwatch'); watch.parentNode.id = 't-unwatch'; } else { var action = 'removed from'; watch.href = watch.href.replace(/action=unwatch$/, 'action=watch'); watch.parentNode.id = 't-watch'; }				AjaxWatch.showMessage(wgPageName.replace('_', ' ')+' has been '+action+' your watchlist.'); watch.innerHTML = next; }		}		ajax.send(null); return false; };	this.getNextIndex = function(text) { for(var i=0; i<AjaxWatch.message.length; i++) { if(text == AjaxWatch.message[i]) { return i+1; }		}	};	this.showMessage = function(msg) { var div; var firstHeading = document.getElementsByTagName('h1')[0]; if(!(div = document.getElementById('ajaxwatch-box'))) { div = document.createElement('div'); div.className = 'header_box'; div.id = 'ajaxwatch-box'; div.innerHTML = ' ' + msg + ' '; firstHeading.parentNode.insertBefore(div, firstHeading); } else { div.innerHTML = ' ' + msg + ' '; }	}; };

addOnloadHook(function {	AjaxWatch.setup; });