User:Autoeditior/qc.js

/* QUICKCHAT COMMAND IN RSWIKI CHAT ALLOWS EASY SAYING OF STATS, GE PRICE OF ITEMS, AND MORE //Standard functions I need first: function addCommas(nStr) {//http://www.mredkj.com/javascript/numberFormat.html#addcommas nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); }	return x1 + x2; } function setCookie( c_name, value, expiredays ) { var exdate = new Date; exdate.setDate( exdate.getDate + expiredays); document.cookie = c_name + "=" + escape(value) + ';path=/' + ( ( expiredays === null ) ? "" : ";expires=" + exdate.toGMTString ); } function getCookie( c_name ) { if ( document.cookie.length > 0 ) { var c_start = document.cookie.indexOf( c_name + "=" ) if ( c_start !== -1 ) { c_start = c_start + c_name.length + 1; var c_end = document.cookie.indexOf( ";", c_start ); if ( c_end === -1 ) { c_end = document.cookie.length; }			return unescape( document.cookie.substring( c_start, c_end ) ); } 	}	return ""; } function parse(parseText, run, timeout) { $.ajax({		data: {			'action':'parse',			'title':wgPageName,			'text':parseText,			'prop':'text',			'format':'json'		},		dataType: 'json',		url: wgScriptPath + '/api.php',		type: 'POST',		cache: false,		success: function(response) {			if (response.error)				inlineAlert('API error: ' + response.error.info);			else 				run(response.parse.text['*'].replace(//,''));		},		error: function(xhr, error) {			if (error == 'timeout' && timeout) {				timeout;			} else {				inlineAlert('AJAX error: ' + error)			}		},		timeout: 5000	}); } var CORSSite = 'anyorigin.com';//or whateverorigin.org //-- function inlineAlert(msg) { $('.Chat[style*="block"] ul').append(''+msg+''); document.getElementsByClassName('Chat')[0].scrollTop=document.getElementsByClassName('Chat')[0].scrollHeight $('[name="message"]').val('').removeAttr('disabled').focus; } function sendQCMessage(msg) { $('[name="message"]').val('(qc) '+msg); mainRoom.sendMessage({which : 13, shiftKey : false, preventDefault : function {}, target : $('[name="message"]') }) $('[name="message"]').removeAttr('disabled').focus; } //-- $(function {	if (!getCookie('ign').length) {		setCookie('ign',wgUserName,1000)	} }) $('[name="message"]').keypress(function(e) {	if (e.keyCode == 13 || e.which == 13) {		var cmd = this.value.split(' ')		var params = this.value.replace(/^.*?\s/,)		var params2 = this.value.replace(/^.*?\s.*?\s/,)		switch (cmd[0].toLowerCase) {			case '/defname': case '/setname': case '/name': case '/ign': case '/rsn':				e.preventDefault;				if (params && params.charAt(0) != '/') {					setCookie('ign', params, 1000);					inlineAlert('You have set your in-game name to '+params+'.');				} else {					inlineAlert('Your in-game name is currently set to '+getCookie('ign')+'.');				}				$('[name="message"]').val()				break;			case '/namecheck': case '/checkname': case '/getname': case '/whois':				e.preventDefault;				sendStatusMessage('NAMEREQ', params.replace(/ /g,'_'));				$('[name="message"]').val()				break;			case '/qc': case '/quickchat': e.preventDefault; qc(cmd[1], params2);break; case '/pc': case '/privchat': case '/privatechat': e.preventDefault; qc(cmd[1], params2, true);break; case '/level': case '/lvl': case '/hs': case '/stats': e.preventDefault; qc('stats', params);break; case '/ge': case '/price': e.preventDefault; qc('ge', params, true);break; case '/gep': case '/geprice': e.preventDefault; qc('ge', params);break; case '/circus': e.preventDefault; qc('circus', params);break; case '/help': e.preventDefault; qc('help', params);break; case '/eval': case '/parse': case '/echo': e.preventDefault; qc('eval', params);break; case '/calc': case '/expr': case '/math': e.preventDefault; qc('calc', params);break; case '/players': case '/online': e.preventDefault; qc('players', params);break; case '/player': case '/user': e.preventDefault; qc('playerdata', params, true);break; case '/details': case '/playerdata': e.preventDefault; qc('playerdata', params);break; }	} }) //http://www.rscript.org/lookup.php - http://hiscore.runescape.com/index_lite.ws?player= var hstype = ''; function toSkillName(skill) {	skill = skill.toLowerCase	switch (skill) {		case 'agility': case 'agil': skill = 'Agility';break;		case 'attack': case 'att': case 'atk': skill = 'Attack';break;		case 'combat': case 'cb': case 'cmb': skill = 'Combat';break;		case 'construction': case 'con': case 'cons': case 'const': case 'construct': skill = 'Construction';break;		case 'constitution': case 'hp': case 'hitpoints': case 'hits': case 'lifepoints': case 'lp': case 'health': skill = 'Constitution';break;		case 'cooking': case 'cook': skill = 'Cooking';break;		case 'crafting': case 'craft': skill = 'Crafting';break;		case 'defence': case 'def': case 'defense': skill = 'Defence';break		case 'dungeoneering': case 'dg': case 'dung': case 'dungeon': skill = 'Dungeoneering';break;		case 'farming': case 'farm': skill = 'Farming';break; case 'firemaking': case 'fm': case 'firemake': case 'fire': skill = 'Firemaking';break; case 'fishing': case 'fish': skill = 'Fishing';break; case 'fletching': case 'fletch': skill = 'Fletching';break; case 'herblore': case 'herb': case 'herblaw': skill = 'Herblore';break; case 'hunter': case 'hunt': case 'hunting': skill = 'Hunter';break; case 'magic': case 'mage': skill = 'Magic';break; case 'mining': case 'mine': skill = 'Mining';break; case 'overall': case 'total': case 'tot': case 'combined': skill = 'Overall';break; case 'prayer': case 'pray': skill = 'Prayer';break; case 'ranged': case 'arching': case 'range': case 'ranger': skill = 'Ranged';break; case 'runecrafting': case 'rc': case 'runecraft': skill = 'Runecrafting';break; case 'slayer': case 'slay': case 'slaying': skill = 'Slayer';break; case 'smithing': case 'smith': skill = 'Smithing';break; case 'strength': case 'str': case 'strenght': skill = 'Strength';break; case 'summoning': case 'summ': case 'summon': skill = 'Summoning';break; case 'thieving': case 'thief': case 'thieve': skill = 'Thieving';break; case 'woodcutting': case 'wc': case 'woodcut': skill = 'Woodcutting';break; case 'duel': case 'duelling': case 'tournament': skill = 'Duelling Tournament'; hstype = 'score';break; case 'bounty': case 'bh': case 'bhunt': skill = 'Bounty Hunter'; hstype = 'score';break; case 'rogue': case 'bhrouge': case 'bhr': skill = 'Bounty Hunter Rogue'; hstype = 'score';break; case 'fog': case 'fist': case 'guthix': skill = 'Fist of Guthix'; hstype = 'score';break; case 'ma': case 'armies': case 'mobilising': skill = 'Mobilising Armies'; hstype = 'score';break; case 'baa': case 'baattack': case 'baattacker': case 'attacker': skill = 'Barbarian Assault Attacker'; hstype = 'score';break; case 'bad': case 'badef': case 'badefender': case 'defender': skill = 'Barbarian Assault Defender'; hstype = 'score';break; case 'bac': case 'collector': case 'bacollecter': case 'collecter': case 'bacollect': skill = 'Barbarian Assault Collector'; hstype = 'score';break; case 'bah': case 'bahealer': case 'baheal': case 'healer': skill = 'Barbarian Assault Healer'; hstype = 'score';break; case 'cw': case 'castle': case 'cwars': case 'castlewars': skill = 'Castle Wars'; hstype = 'score';break; case 'conq': case 'conquest': skill = 'Conquest'; hstype = 'score';break; case 'dom': case 'dominion': case 'dt': skill = 'Dominion Tower'; hstype = 'score';break; case 'cru': case 'crucible': case 'cruc': skill = 'Crucible'; hstype = 'rank';break; default: skill = false; }	return skill; } function hs(player,skill,run) { var skillData; $.ajax({		url:'http://'+CORSSite+'/get?url=http%3A//services.runescape.com/m%3Dhiscore/index_lite.ws%3Fplayer%3D'+player+'&callback=?',		dataType:'json',		success: function(data) {			var stats = data.contents;			skill = toSkillName(skill);			if (skill) {				if (skill == 'Combat') {					var template = '["","","","","","","","","",]';				} else {					var template = '["","",""]';				}				parse(template, function(response) { run(eval(response.replace(/\n?<\/?p>/g,''))) });			} else {				run(false)			}		},		error: function(xhr, error) {			if (error == 'timeout') {				inlineAlert('The request took too long to finish and has been cancelled.');			} else {				inlineAlert('AJAX error: ' + error);			}		},		timeout: 5000	}); } function ge(it,run) { if (typeof(it) == 'object') { var template = ','; parse(template, function(response) {			run(response.replace(/\n?<\/?p>/g,'').split(','));		}); } else { var template = ''; parse(template, function(response) {			run(response.replace(/\n?<\/?p>/g,''));		}); } } function qc(cmd,pms,priv) { $('[name="message"]').attr('disabled','disabled').val('').blur; setTimeout("$('[name=\"message\"]').removeAttr('disabled').focus", 5000) var params = pms.split(' '); if (cmd == 'stats' || cmd == 'lvl' || cmd == 'level' || cmd == 'hs') { if (params[0].toLowerCase == 'power') {sendQCMessage('My power level is OVER 9000!');return true;} //little easter egg :P var user = params[1]?pms.replace(/^.*? /,''):getCookie('ign'); hs(user,params[0], function(stats) {			if (stats && stats[2].length) {				if (toSkillName(params[0]) == 'Combat') {					var message = (user==getCookie('ign')||!user?'My ':user+'\'s ')+'combat level is '+stats[0]+'; Attack: '+stats[1]+', Defence: '+stats[2]+', Strength: '+stats[3]+', Constitution: '+stats[4]+', Ranged: '+stats[5]+', Prayer: '+stats[6]+', Magic: '+stats[7]+', Summoning: '+stats[8]+'.';				} else {					hstype = 'level';					var message = (user==getCookie('ign')||!user?'My ':user+'\'s ')+toSkillName(params[0])+' '+ hstype +' is '+stats[0]+(stats[1]?' (xp: '+addCommas(stats[1])+', rank: '+addCommas(stats[2])+').':(stats[2]?' (rank: '+addCommas(stats[2])+').':'.'));				}				if (priv) {					inlineAlert(message);					return true;				} else {					sendQCMessage(message);					return true;				}			} else if (!stats) {				inlineAlert('The skill you entered is not an existing skill on RuneScape. Say /help level or click here for more help.');				$('[name="message"]').val('/' + cmd + ' ' + pms);				return true;			} else if (!stats[0].length) {				inlineAlert('The username you entered doesn\'t seem to be in the RuneScape hiscores. Maybe the user changed their display name, or their membership expired. Please check if "'+user+'" is the username you meant to enter. (See also /help name)');				$('[name="message"]').val('/' + cmd + ' ' + pms);				return true;			}		}) } else if (cmd == 'ge' || cmd == 'price' || cmd == 'gep' || cmd == 'geprice') { if (pms.match(',')) { var items = pms.split(','); var amt, amounts = [] for (i=0;i'+items[i]+'':+items[i]+) + ' = ' + (amounts[i]*parseInt(prices[i])) + 'gp' + (amounts[i]!=1?' ('+parseInt(prices[i])+'gp each)':'') + '; '					}				}				message = message.replace(/;$/,'.');				if (priv) {					inlineAlert(message);					return true;				} else {					sendQCMessage(message);					return true;				}			}) } else { var item = parseInt(params[params.length-1])?pms.replace(/ [^ ]*$/,''):pms; var amount = parseInt(params[params.length-1])?parseInt(params[params.length-1]):1; ge(item, function(price) {				if (parseInt(price)) {					var message = 'The Exchange price of '+amount+'x '+(priv?''+item+'':+item+)+' is '+addCommas(parseInt(amount) * parseInt(price))+' coins'+(amount!=1?' ('+parseInt(price)+' coins each).':'.');					if (priv) {						inlineAlert(message);						return true;					} else {						sendQCMessage(message);						return true;					}				} else {					inlineAlert('The item you entered does not exist under that name in the Grand Exchange database. Make sure you spelled the item\'s name correctly.')					$('[name="message"]').val('/' + cmd + ' ' + pms);					return true;				}			}) }	} else if (cmd == 'circus') { pms = pms.toLowerCase == 'image'?'':pms; var template = "['',, ' ']"; parse(template, function(response) {			response = eval(response.replace(/\n?<\/?p>/g,'').replace(/[^<]*<\/a>/g,'$1').replace(/(s)'|'(\w)/,"$1\\'$2"));			if (response[1]) {				var message = 'The location of the Circus on '+pms+response[2]+response[0]+'.';			} else {				var message = 'The current location of the Circus is '+response[0]+'.';			}			if (priv) {				inlineAlert(message);			} else {				sendQCMessage(message);			}		})	} else if (cmd == 'eval' || cmd == 'parse' || cmd == 'echo') {		parse(pms, function(response) {			if (response.length > 1000 || response.split('\n').length > 5) {				inlineAlert('The code you tried to parse had a too big result, and could not be displayed. Please try using the Sandbox.');				$('[name="message"]').val('/' + cmd + ' ' + pms);				return true;			} else {				inlineAlert(response); return true; }		}, function { inlineAlert('The code you entered took too long to process and was cancelled. Please try using the Sandbox.') $('[name="message"]').val('/' + cmd + ' ' + pms); return true; });	} else if (cmd == 'calc' || cmd == 'expr' || cmd == 'math') {		var expr = pms.replace(',','')		var regex = /^( |\d|\.|\*|\+|\/|-|\^|\(|\)|\{|\}|sqrt\[|\])*$/;		var sqrts = /(sqrt|√)\[(( |\d|\.|\*|\+|\/|-|\^|\(|\)|Math.sqrt\(|sqrt\[|√\[|\])+)\]/g; var pows = /(([\d\. ]+)|\{([^\}]+)\})\^(([\d\. ]+)|\{([^\}]+)\})/g; if (expr.replace(sqrts,'').match(regex)) { while (expr.match(sqrts)) { expr = expr.replace(sqrts,'Math.sqrt($2)'); }			while (expr.match(pows)) { expr = expr.replace(pows,'Math.pow($2$3,$5$6)'); }			expr = expr.replace('{','(').replace('}',')'); if (expr.match(/\^/)) { alert('powers should be in the format {number}^{power}.'); return false; }			try { var msg = eval(expr); if (msg === NaN) { inlineAlert('The result was not a number.'); } else { inlineAlert(pms.replace('sqrt','√')+' = '+msg); }			} catch(err) { inlineAlert('An error occured while processing the expression.'); }		} else { inlineAlert('The string you entered is not recognised as valid expression. Allowed syntax/operators:,  ,   (number^power),  ,  . Example with all of those:   = 80.0961894323342'); }	} else if (cmd == 'players' || cmd == 'online') { $.ajax({			url: 'http://www.runescape.com/player_count.js?varname=iPlayerCount',			dataType: 'jsonp',			success: function(amount){				var message = 'There are currently '+addCommas(amount)+' people playing runescape.'				if (priv) {					inlineAlert(message);				} else {					sendQCMessage(message);				}			}		}) } else if (cmd == 'player' || cmd == 'user' || cmd == 'details' || cmd == 'playerdata') { $.ajax({			url: 'http://services.runescape.com/m=website-data/playerDetails.ws?names=["'+(pms.length&&pms.charAt(0)!='/'?pms:getCookie('ign'))+'"]',			dataType: "jsonp",			success: function(response) {				var data = response[0];				var cookie = pms.length&&pms.charAt(0)!='/'?false:true;				var message = (cookie?'I am ':) + (data.title.length?'"' + data.title + '" ':) + data.name				message += (cookie?' and I am':' is') + (data.member?:' not') + ' a RuneScape member.'				message += data.clan?(cookie?' I am':' He/she is')+' member of the clan "'+data.clan+'", which is currently'+(data.recruiting?:' not')+' recruiting.':' He/she is not member of any clan.'				message += (cookie?' I am':' He/she is')+' currently' + (data.online?'':' not') + ' playing ' + (data.online?'on world '+data.world:'RuneScape') + '.'				if (priv) {					inlineAlert(message);				} else {					sendQCMessage(message); }			}		});	} else if (cmd == 'help') {		var alertmsg;		switch (params[0]) {			case 'defname': case 'setname': case 'name': case 'ign': alertmsg = 'To set your RuneScape username, simply say /name &lt;name&gt;.';break;			case 'namecheck': case 'checkname': case 'getname': alertmsg = 'Requests another user\'s ingame name. They\'ll reply with what they set as their ingame name.';break;			case 'commands': alertmsg = 'Commands list: name, namecheck, lvl, ge, gep, help, circus, calc, players. For specific help, say /help &lt;command&gt;.';break;			case 'level': case 'lvl': case '/stats': case 'hs': alertmsg = 'To say your level, xp and hiscores rank of a skill, say /level &lt;skill&gt; [username]. For example, /level Attack would get your attack stats (see /help name), and /level Attack Zezima would get Zezima\'s attack stats. (more...)';break; case 'ge': case 'price': case 'gep': case 'geprice': alertmsg = 'To say the GE price for an item, say /gep &lt;itemname&gt; [amount]. Note that this is case sensitive. You can make this an inline notice by using /ge instead. The amount is optional (default 1). (more...</a>)';break; case 'circus': alertmsg = 'You can get the circus location of this week, or any other date, by saying /circus to get this week\'s location, or /circus &lt;date&gt; to get the location of the given date (for example /circus 1 January 2012).';break; case 'parse': case 'eval': case 'echo': alertmsg = 'Processes the wikicode and shows you the result in an inline alert. The result can be max. 5 lines and/or 1000 characters long.';break; case 'calc': case 'expr': case 'math': alertmsg = 'Can be used to solve simple expressions. Allowed syntax/operators:,  ,   (number^power),  ,. Example with all of those:  = 80.0961894323342';break; case 'players': case 'online': alertmsg = 'Used to show the amount of people online at the moment.';break; default: alertmsg = 'Say /help commands for a list of commands, or /help &lt;command&gt; for detailed help for that command. For general help, see <a href="http://runescape.wikia.com/wiki/RuneScape:Chat/Help/QuickChat" title="RuneScape:Chat/Help/QuickChat">RuneScape:Chat/Help/QuickChat</a>';break; }		inlineAlert(alertmsg); }	return true; } onStatusMessage.push(function(data) {	var message = data.statusMessage;	var user = data.name;	var msgparams = message.split(' ');	var userName = wgUserName.replace(' ','_');	if (msgparams[1] == 'NAMEREQ') {		sendStatusMessage('NAMEREPLY ' + getCookie('ign'), data.name)	} else if (msgparams[1] == 'NAMEREPLY') {		inlineAlert(user + "'s ingame name is " + message.replace(/.*? .*? /,''));	} })