HRPG+

Improved Heroes RPG GUI

Устаревшая версия за 13.10.2015. Перейдите к последней версии.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey, Greasemonkey или Violentmonkey.

Для установки этого скрипта вам необходимо установить расширение, такое как Tampermonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например Tampermonkey.

Чтобы установить этот скрипт, вы должны установить расширение — менеджер скриптов.

(у меня уже есть менеджер скриптов, дайте мне установить скрипт!)

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

(у меня уже есть менеджер стилей, дайте мне установить скрипт!)

// ==UserScript==
// @name        HRPG+
// @namespace   HRPG
// @description Improved Heroes RPG GUI
// @include     http://heroesrpg.com/game.php*
// @include     http://www.heroesrpg.com/game.php*
// @version     1.1.6.9
// @grant       none
// ==/UserScript==
// channel dropdown, chat filter, infinite chat, stats and skills, modify names >:D, upload audio, fix gems, sound on death option, filter globals
// might need to overridetabtitle()
$('#chat1').prepend(/*`<input type="submit" value="Cancel Autobuy" onclick="javascript:autoDo = false;"></input> */
`Volume: <input id="volume" type="number" min="0" max="100" value="100" width="30" size="3"></input><br/>
<input type="checkbox" id="removeChatLines" ${window.localStorage.getItem('removeChatLines')=='true'?'checked':''}"></input> Remove chat lines <br/>
Nugget's Alerts: 
<input type="checkbox" id="riftAlerts" ${window.localStorage.getItem('riftAlerts')=='true'?'checked="checked"':''}"></input> Rift™ 
<input type="checkbox" id="riftTabTitle" ${window.localStorage.getItem('riftTabTitle')=='true'?'checked="checked"':''}"></input> Title 
<input type="checkbox" id="pingAlerts" ${window.localStorage.getItem('pingAlerts')=='true'?'checked="checked"':''}"></input> Ping™ 
<input type="checkbox" id="pingTabTitle" ${window.localStorage.getItem('pingTabTitle')=='true'?'checked="checked"':''}"></input> Title 
<input type="checkbox" id="clanAttentionAlerts" ${window.localStorage.getItem('clanAttentionAlerts')=='true'?'checked="checked"':''}"></input> Clan Attention™ 
<input type="checkbox" id="clanAttentionTabTitle" ${window.localStorage.getItem('clanAttentionTabTitle')=='true'?'checked="checked"':''}"></input> Title <br/>
Show: 
<input type="checkbox" id="showMain" ${window.localStorage.getItem('showMain')=='true'?'checked="checked"':''}"></input> Main 
<input type="checkbox" id="showClan" ${window.localStorage.getItem('showClan')=='true'?'checked="checked"':''}"></input> Clan 
<input type="checkbox" id="showTrade" ${window.localStorage.getItem('showTrade')=='true'?'checked="checked"':''}"></input> Trade 
<input type="checkbox" id="showGlobal" ${window.localStorage.getItem('showGlobal')=='true'?'checked="checked"':''}"></input> Globals 
<input type="checkbox" id="showClanGlobal" ${window.localStorage.getItem('showClanGlobal')=='true'?'checked="checked"':''}"></input> Clan Globals `);
//don't: calculate max autos, sell all accessories
$('#riftAlerts').change(function () {window.localStorage.setItem('riftAlerts',$('#riftAlerts').is(':checked'));});
$('#riftTabTitle').change(function () {window.localStorage.setItem('riftTabTitle',$('#riftTabTitle').is(':checked'));});
$('#pingAlerts').change(function () {window.localStorage.setItem('pingAlerts',$('#pingAlerts').is(':checked'));});
$('#pingTabTitle').change(function () {window.localStorage.setItem('pingTabTitle',$('#pingTabTitle').is(':checked'));});
$('#clanAttentionAlerts').change(function () {window.localStorage.setItem('clanAttentionAlerts',$('#clanAttentionAlerts').is(':checked'));});
$('#clanAttentionTabTitle').change(function () {window.localStorage.setItem('clanAttentionTabTitle',$('#clanAttentionTabTitle').is(':checked'));});
$('#removeChatLines').change(function () {window.localStorage.setItem('removeChatLines',$('#removeChatLines').is(':checked'));});
$('#volume').change(function () {window.localStorage.setItem('volume',$('#volume').val());});//TODO: check
$('#showMain').change(function () {window.localStorage.setItem('showMain',$('#showMain').is(':checked'));messageTypesVisible[0]=$('#showMain').is(':checked');chatVisibilityChanged();});
$('#showClan').change(function () {window.localStorage.setItem('showClan',$('#showClan').is(':checked'));messageTypesVisible[1]=$('#showClan').is(':checked');chatVisibilityChanged();});
$('#showTrade').change(function () {window.localStorage.setItem('showTrade',$('#showTrade').is(':checked'));messageTypesVisible[2]=$('#showTrade').is(':checked');chatVisibilityChanged();});
$('#showGlobal').change(function () {window.localStorage.setItem('showGlobal',$('#showGlobal').is(':checked'));messageTypesVisible[3]=$('#showGlobal').is(':checked');chatVisibilityChanged();});
$('#showClanGlobal').change(function () {window.localStorage.setItem('showClanGlobal',$('#showClanGlobal').is(':checked'));messageTypesVisible[4]=$('#showClanGlobal').is(':checked');chatVisibilityChanged();});
$('body').append('<script>Array.prototype.after = function (o){return this[this.indexOf(o)+1];}\nString.prototype.replaceAt = function(n, t) {return this.substring(0, n) + t + this.substring(n + 1);}</script>');

window.Array.prototype.after = function (o){return this[this.indexOf(o)+1];}
window.String.prototype.replaceAt = function(n, t) {return this.substring(0, n) + t + this.substring(n + 1);}

//window.autoDo = true;

$('#bright_select').append('<option value="0">Boosts</option>');

window.tabTitleChanged = false;

$(window).on('focus', function() { resetTitle(); tabTitleChanged = false;});

window.displayAutosRemaining = function(autos) { if(!tabTitleChanged) { if(autos > 0) { document.title = 'Heroes RPG ('+autos+' Autos)'; } else { document.title = 'Heroes RPG (END OF AUTO)'; } } }

window.id = 1;
window.boost = 0;
window.name = '';
window.yourName = $('#s_cname')[0].textContent;

window.rarityNum = new Object();
window.rarityNum.common = 1;
window.rarityNum.uncommon = 2;
window.rarityNum.rare = 3;
window.rarityNum.epic = 4;
window.rarityNum.legendary = 5;

window.command = new Object();
window.command.c = 'Posts <message> to clan chat.'
window.command.t = 'Posts <message> to trade chat.'
window.command.double = 'Shows length of double and haste remaining.'
window.command.haste = 'Shows length of double and haste remaining.'
window.command.commands = 'Shows a list of commands.'
window.command.command = 'Shows information about <commandname>.'
window.command.profile = 'Shows profile of <username>.'
window.command.who = 'Shows basic information of <username>.'
window.command.misc = 'Shows battles and quests of <username>.'
window.command.crafting = 'Shows crafting levels of <username>.'
window.command.gathering = 'Shows gathering levels of <username>.'
//window.command.pick = 'Picks <number> <rarity> chests.'
//window.command.pickall = 'Picks all <rarity> chests.'
//window.command.buyboost = 'Buys <number> <name> boosts.'
//window.command.buyauto = 'Buys <number> autos.'

window.hideableMessageTypes = ['main, .emote','clan','trade','global','clanglobal'];
window.messageTypesVisible = [window.localStorage.getItem('showMain')||true,window.localStorage.getItem('showClan')||true,window.localStorage.getItem('showTrade')||true,window.localStorage.getItem('showGlobal')||true,window.localStorage.getItem('showClanGlobal')||true];

window.chatVisibilityChanged = function(){
	var filter = '';
	for(var i = 0; i < hideableMessageTypes.length; i++){
		if(!messageTypesVisible[i]) { filter = filter + `.${hideableMessageTypes[i]}, ` }
	}
	$('tr','#chat_table1').show().filter($(filter.slice(0,filter.length - 2))).hide();
}

//Start Showdown

window.g_list_level = 0;

window.makeHtml = function(text) {
	g_urls = [];
	g_titles = [];
	g_html_blocks = [];
	text = text.replace(/~/g,"~T");
	text = text.replace(/\$/g,"~D");
	text = text.replace(/\r\n/g,"\n");
	text = text.replace(/\r/g,"\n");
	text = _Detab(text);
	text = text.replace(/^[ \t]+$/mg,"");
	text = _HashHTMLBlocks(text);
	text = _StripLinkDefinitions(text);
	text = _RunBlockGamut(text);
  text = _RunSpanGamut(text);
	text = _UnescapeSpecialChars(text);
	text = text.replace(/~D/g,"$$");
	text = text.replace(/~T/g,"~");
	return text;
}

window._StripLinkDefinitions = function(text) {
	var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
		function (wholeMatch,m1,m2,m3,m4) {
			m1 = m1.toLowerCase();
			g_urls[m1] = _EncodeAmpsAndAngles(m2);
			if (m3) { return m3+m4; } else if (m4) { g_titles[m1] = m4.replace(/"/g,"&quot;"); 			}
			return "";
		});
	return text;
}

window._HashHTMLBlocks = function(text) {
	text = text.replace(/\n/g,"\n\n");
	block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
	block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
	text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
	text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
	text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
	text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
	text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
	text = text.replace(/\n\n/g,"\n");
	return text;
}

window.hashElement = function(wholeMatch,m1) {
	blockText = m1;
	blockText = blockText.replace(/\n\n/g,"\n");
	blockText = blockText.replace(/^\n/,"");
	blockText = blockText.replace(/\n+$/g,"");
	blockText = "~K" + (g_html_blocks.push(blockText)-1).toString() + "K";
	return blockText;
}

window._RunBlockGamut = function(text) {
	text = _DoHeaders(text);
	var key = hashBlock("<hr />");
	text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
	text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
	text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
	text = _DoLists(text);
	text = _DoCodeBlocks(text);
	text = _DoBlockQuotes(text);
	text = _HashHTMLBlocks(text);
	text = _FormParagraphs(text);
	return text;
}

_FormParagraphs = function(text, doNotUnhash) {
	text = text.replace(/^\n+/g,'');
	text = text.replace(/\n+$/g,'');
	grafs = text.split(/\n{2,}/g);
	grafsOut = new Array();
	end = grafs.length;
	for (i = 0; i < end; i++) {
		str = grafs[i];
		if (str.search(/~K(\d+)K/g) >= 0) { grafsOut.push(str); }
		else if (str.search(/\S/) >= 0) {
			str = _RunSpanGamut(str);
			str = str.replace(/^([ \t]*)/g,'');
			grafsOut.push(str);
		}
	}
  end = grafsOut.length;
	  for (i=0; i<end; i++) {
	    while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
		    var blockText = g_html_blocks[RegExp.$1];
			    blockText = blockText.replace(/\$/g,"$$$$");
			    grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
	    }
	  }
	return grafsOut.join('/n/n');
}

window._RunSpanGamut = function(text) {
	text = _DoCodeSpans(text);
	text = _EscapeSpecialCharsWithinTagAttributes(text);
	text = _EncodeBackslashEscapes(text);
	text = _DoImages(text);
	text = _DoAnchors(text);
	text = _DoAutoLinks(text);
	text = _EncodeAmpsAndAngles(text);
	text = _DoItalicsAndBold(text);
	text = text.replace(/  +\n/g," <br />\n");
	return text;
}

window._EscapeSpecialCharsWithinTagAttributes = function(text) {
	var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
	text = text.replace(regex, function(wholeMatch) {
		var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
		tag = escapeCharacters(tag,"\\`*_");
		return tag;
	});
	return text;
}

window._DoAnchors = function(text) {
	text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
	text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
	text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
	return text;
}

window.writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
	if (m7 == undefined) m7 = "";
	var whole_match = m1;
	var link_text   = m2;
	var link_id	 = m3.toLowerCase();
	var url		= m4;
	var title	= m7;
	if (url == "") {
		if (link_id == "") { link_id = link_text.toLowerCase().replace(/ ?\n/g," "); }
		url = "#"+link_id;
		if (g_urls[link_id] != undefined) {
			url = g_urls[link_id];
			if (g_titles[link_id] != undefined) { title = g_titles[link_id]; }
		}
		else { if (whole_match.search(/\(\s*\)$/m)>-1) { url = ""; } else { return whole_match; } }
	}
	url = escapeCharacters(url,"*_");
	var result = "<a href=\"" + url + "\"";
	if (title != "") {
		title = title.replace(/"/g,"&quot;");
		title = escapeCharacters(title,"*_");
		result +=  " title=\"" + title + "\"";
	}
	result += ">" + link_text + "</a>";
	return result;
}

window._DoImages = function(text) {
	text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
	text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
	return text;
}

window.writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
	whole_match = m1;
	alt_text    = m2;
	link_id	    = m3.toLowerCase();
	url		      = m4;
	title	      = m7;
	if (!title) title = "";
	if (url == "") {
		if (link_id == "") { link_id = alt_text.toLowerCase().replace(/ ?\n/g," "); }
		url = "#"+link_id;
		if (g_urls[link_id] != undefined) {
			url = g_urls[link_id];
			if (g_titles[link_id] != undefined) { title = g_titles[link_id]; }
		}
		else { return whole_match; }
	}
	alt_text = alt_text.replace(/"/g,"&quot;");
	url = escapeCharacters(url,"*_");
	var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
  title = title.replace(/"/g,"&quot;");
  title = escapeCharacters(title,"*_");
  result +=  " title=\"" + title + "\"";
  result += " />";
  return result;
}

window._DoHeaders = function(text) {
	text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
		function(wholeMatch,m1){return hashBlock("<h1>" + _RunSpanGamut(m1) + "</h1>");});
	text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
		function(matchFound,m1){return hashBlock("<h2>" + _RunSpanGamut(m1) + "</h2>");});
	text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
		function(wholeMatch,m1,m2) {
			var h_level = m1.length;
			return hashBlock("<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">");
		});
	return text;
}

window._ProcessListItems;

window._DoLists = function(text) {
	text += "~0";
	var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
	if (g_list_level) {
		text = text.replace(whole_list,function(wholeMatch,m1,m2) {
			var list = m1;
			var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
			list = list.replace(/\n{2,}/g,"\n\n\n");;
			var result = _ProcessListItems(list);
			result = result.replace(/\s+$/,"");
			result = "<"+list_type+">" + result + "</"+list_type+">\n";
			return result;
		});
	} else {
		whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
		text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
			var runup = m1;
			var list = m2;
			var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
			var list = list.replace(/\n{2,}/g,"\n\n\n");;
			var result = _ProcessListItems(list);
			result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
			return result;
		});
	}
	text = text.replace(/~0/,"");
  return text;
}

window._ProcessListItems = function(list_str) {
	g_list_level++;
	list_str = list_str.replace(/\n{2,}$/,"\n");
	list_str += "~0";
	list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
		function(wholeMatch,m1,m2,m3,m4){
			var item = m4;
			var leading_line = m1;
			var leading_space = m2;
			if (leading_line || (item.search(/\n{2,}/)>-1)) { item = _RunBlockGamut(_Outdent(item)); }
			else {
				item = _DoLists(_Outdent(item));
				item = item.replace(/\n$/,""); // chomp(item)
				item = _RunSpanGamut(item);
			}
			return  "<li>" + item + "</li>\n";
		}
	);
	list_str = list_str.replace(/~0/g,"");
  g_list_level--;
	return list_str;
}

window._DoCodeBlocks = function(text) {
	text += "~0";
	text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
		function(wholeMatch,m1,m2) {
			var codeblock = m1;
			var nextChar = m2;
			codeblock = _EncodeCode( _Outdent(codeblock));
			codeblock = _Detab(codeblock);
			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
			codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
			return hashBlock(codeblock) + nextChar;
		}
	);
	text = text.replace(/~0/,"");
	return text;
}

window.hashBlock = function(text) {
	text = text.replace(/(^\n+|\n+$)/g,"");
	return "~K" + (g_html_blocks.push(text)-1).toString() + "K";
}

window._DoCodeSpans = function(text) {
	text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
		function(wholeMatch,m1,m2,m3,m4) {
			var c = m3;
			c = c.replace(/^([ \t]*)/g,"");	// leading whitespace
			c = c.replace(/[ \t]*$/g,"");	// trailing whitespace
			c = _EncodeCode(c);
			return m1+"<code>"+c+"</code>";
		});
	return text;
}

window._EncodeCode = function(text) {
	text = text.replace(/&/g,"&amp;");
	text = text.replace(/</g,"&lt;");
	text = text.replace(/>/g,"&gt;");
	text = escapeCharacters(text,"\*_{}[]\\",false);
	return text;
}

window._DoItalicsAndBold = function(text) {
	text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
		"<strong>$2</strong>");
	text = text.replace(/(\w)_(\w)/g, "$1~E95E$2")
	text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
		"<em>$2</em>");
	return text;
}

window._DoBlockQuotes = function(text) {
	text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
		function(wholeMatch,m1) {
			var bq = m1;
			bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0");
			bq = bq.replace(/~0/g,"");
			bq = bq.replace(/^[ \t]+$/gm,"");
			bq = _RunBlockGamut(bq);
			bq = bq.replace(/(^|\n)/g,"$1  ");
			bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm,
				function(wholeMatch,m1) {
					var pre = m1;
					pre = pre.replace(/^  /mg,"~0");
					pre = pre.replace(/~0/g,"");
					return pre;
				});
			return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
		});
	return text;
}

window._EncodeAmpsAndAngles = function(text) {
	text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
	text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
	return text;
}

window._EncodeBackslashEscapes = function(text) {
	text = text.replace(/\\(\\)/g,escapeCharacters_callback);
	text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
	return text;
}

window._DoAutoLinks = function(text) {
  text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
	text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
		function(wholeMatch,m1) {
			return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
		}
	);
	return text;
}

window._EncodeEmailAddress = function(addr) {
	function char2hex(ch) {
		var hexDigits = '0123456789ABCDEF';
		var dec = ch.charCodeAt(0);
		return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
	}
	encode = [
		function(ch){return "&#"+ch.charCodeAt(0)+";";},
		function(ch){return "&#x"+char2hex(ch)+";";},
		function(ch){return ch;}
	];
	addr = "mailto:" + addr;
	addr = addr.replace(/./g, function(ch) {
		if (ch == "@") { ch = encode[Math.floor(Math.random()*2)](ch); } else if (ch !=":") {
			r = Math.random();
			ch =  (r > .9  ?	encode[2](ch):r > .45 ?	encode[1](ch):encode[0](ch));
		}
		return ch;
	});
	addr = "<a href=\"" + addr + "\">" + addr + "</a>";
	addr = addr.replace(/">.+:/g,"\">");
	return addr;
}

window._UnescapeSpecialChars = function(text) {
	text = text.replace(/~E(\d+)E/g,
		function(wholeMatch,m1) {
			var charCodeToReplace = parseInt(m1);
			return String.fromCharCode(charCodeToReplace);
		}
	);
	return text;
}

window._Outdent = function(text) {
	text = text.replace(/^(\t|[ ]{1,4})/gm,"~0");
	text = text.replace(/~0/g,"")
	return text;
}

window._Detab = function(text) {
	text = text.replace(/\t(?=\t)/g,"    ");
	text = text.replace(/\t/g,"~A~B");
	text = text.replace(/~B(.+?)~A/g,
		function(wholeMatch,m1,m2) {
			var leadingText = m1;
			var numSpaces = 4 - leadingText.length % 4;
			for (var i=0; i<numSpaces; i++) leadingText+=" ";
			return leadingText;
		}
	);
	text = text.replace(/~A/g,"    ");
	text = text.replace(/~B/g,"");
	return text;
}

window.escapeCharacters = function(text, charsToEscape, afterBackslash) {
	var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
	if (afterBackslash) { regexString = "\\\\" + regexString; }
	var regex = new RegExp(regexString,"g");
	text = text.replace(regex,escapeCharacters_callback);
	return text;
}

window.escapeCharacters_callback = function(wholeMatch,m1) {
	var charCodeToEscape = m1.charCodeAt(0);
	return "~E"+charCodeToEscape+"E";
}

//End Showdown

/*window.goToChannel = function(channel) {
	$('#chat1, #chat10, #chat50, #chat100').hide();
	$('#chat' + channel).show();
	chatview = channel;
	if(channel == 1) { chatcount1 = 0; }
	else if(channel == 10) { chatcount10 = 0; }
	else if(channel == 100) { refreshBoosts(); }
	$('#chatcount'+channel).html(null);
}*/

window.boosts = ['Battle Exp', 'Gold', 'Attribute', 'Battle SP', 'Gathering Exp', 'Gathering SP', 'Drop'];
window.gemTypes = ['Ruby', 'Emerald', 'Diamond', 'Sapphire', 'Amethyst'];
window.gemRarities = ['Fractured', 'Chipped', 'Dull', 'Clouded', 'Bright', 'Glowing', 'Radiant', 'Flawless', 'Perfect', 'Priceless'];
window.gemRarityBoosts = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100];

window.underscorify = function(s){
	return s.toLowerCase().replace(' ','_');
}

window.addCreditBoost = function(id,name) {
	$.post('upgrade.php', {mod:'boosts'}, function(data){
		var current = parseFloat($('#' + underscorify(name)).text());
	  var percentage = $('td',$('tr',data.v)[id+1])[1].textContent.split(' ')[0];
    current += parseFloat(percentage.slice(0,percentage.length-1));
		$('#' + underscorify(name)).text(current);
  }, 'json');
}


window.addClanBoost = function(id,name) {
	$.post('clan.php', {mod:'buildinglist', id:id+10}, function(data){
    var current = parseFloat($('#' + underscorify(name)).text());
		current += parseFloat($(data.v)[5].textContent.split(' ')[2]) * (id==7?3:10);
		$('#' + underscorify(name)).text(current);
  }, 'json');
}

window.addGemBoost = function(id,name) {
	$.post('displayr.php', {mod:1}, function(data) {
    var array = $('a',data.html);
  	for(var i = 0; i < array.length; i++){
	  	if(array[i].id!='') { continue; }
  		if(array[i].href.match(/:(.*)\(/)[1] == 'viewItem'){
		  	$.post('misc.php', {mod:'viewitem', id:parseInt(array[i].href.match(/\((.*)\)/)[1])}, function(data) {
	  			var values = $.map($('td',data.v),function(data){return data.textContent;});
          var sockets = values.after('Sockets');
			  	for(var j = 0; j < sockets; j++) {
						var gem = values.after(`S${j+1}:`);
	  				var words = gem.split(' ');
	          if(gemTypes.indexOf(words[1]) + 1 == id) {
							var current = parseFloat($('#' + underscorify(name)).text());
							current += parseFloat(gemRarityBoosts[gemRarities.indexOf(words[0])])/10;
							$('#' + underscorify(name)).text(current);
						}
			  	}
		  	}, 'json');
	  	}
  	  if(array[i].href.match(/:(.*)\(/)[1] == 'viewAccessory'){
	  		$.post('http://heroesrpg.com/misc.php', {mod:'viewaccessory', id:array[i].href.match(/\((.*)\)/)[1]}, function(data) {
	        var array = $.map($('td',data.v),function(data){return data.textContent;});
	    		gem = array[array.length - 1].slice(5);
	  			if(gem != 'Unequip To Socket'){
				  	var words = gem.split(' ');
			  		if(gemTypes.indexOf(words[1]) + 1 == id){
		    		  var bonus = array[array.length - 2];
	  			    bonus = bonus.slice(1,bonus.length - 1);
							var current = parseFloat($('#' + underscorify(name)).text());
					    current += parseFloat(gemRarityBoosts[gemRarities.indexOf(words[0])])/10 * (1 + parseFloat(bonus)/100);
							$('#' + underscorify(name)).text(current);
				  	}
			  	}
		  	}, 'json');
      }
  	}
	}, 'json');
}

window.refreshBoosts = function(){
  option = $('#boost_select').val();
	var boostHtml = '';
	for(var id = 0; id < boosts.length - 1; id++){
	  boost = 0;
	  name = boosts[id];
		$('#' + underscorify(name)).html('0');
		if(option == 1 || option == 4) addCreditBoost(parseInt(id)+1,name);
		if(option == 2 || option == 4) addClanBoost(parseInt(id)+1,name);
		if(option == 3 || option == 4) addGemBoost(parseInt(id)+1,name);
	}
	$('#' + underscorify(boosts[boosts.length-1])).html('0');
	if(option == 2 || option == 4) addClanBoost(boosts.length,boosts[boosts.length-1]);
}

/*window.maxAutos = function(credits) {
  //return credits = 10*Math.floor(autos/10)*(Math.floor(autos/10)-1) + 10*((autos/10)%1)*(Math.floor(autos/10))- 30
}*/

window.chatLine = function(msg,$class){
	$('#chat_table1').prepend('<tr class="'+$class+'" id="ct1_tr'+(chatid1)+'"><td>'+msg+'</td></tr>');
  chatid1++;
}

window.linkify = function(safeContent) {
	return ` ${safeContent} `.replace(/(?!.*\.\..*|.*\/\..*)\s+([^\s<>\(\)]+\.[^\s<>\(\)]+)\s+/gi, function(match, p1, string) {
    var address = /[a-z]+:\/\//.test(p1) ? p1 : 'http://' + p1;
    p1 = p1.replace(/^https?:\/\//, '');
		return ' <a href="'+ address + '" target="_blank">' +p1 + '</a> ';
  });
};

window.send_chat = function(){
  //autoDo = true;
  msg = chatInputElem.val();
  if(msg.toLowerCase() == '/commands'){
    chatLine('<font color="BBFFBB">/c &lt;message&gt;, /t &lt;message&gt;, /double, /haste /commands, /command &lt;commandname&gt;</font>');//TODO: profile, misc, gathering, crafting, who
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/command ')){
    commandName=msg.slice(9);
    chatInputElem.val('');
    chatLine(`<font color="BBFFBB">/${commandName}: ${command[commandName].replace('<','&lt;').replace('>','&gt')}</font>`);
    return;
  }
/*  if(msg.toLowerCase().startsWith('/buyboost ')){
    vars = msg.slice(10).split(' ');
    chatInputElem.val('');
    id = boosts[vars[0]];
    amount = Math.min(vars[1],$('#s_credits')[0].textContent/50);
    while (autoDo && amount > 0){
      amount--;
      spendCredits(id,'boost');
    }
    return;
  }
  if(msg.toLowerCase().startsWith('/buyauto ')){
    amount = Math.min(msg.slice(9),$('#s_credits')[0].textContent);
    chatInputElem.val('');
    while (autoDo && amount > 0){
      amount--;
      spendCredits(id,'boost');
    }
    return;
  }
  if(msg.toLowerCase().startsWith('/pick ')){
    vars = msg.slice(6).split(' ');
    rarity = rarityNum[vars[0]];
    chatInputElem.val('');
    if (rarity == undefined) return;
    $('#center_select').val(5);
    centerSelect();
    $('#craft_select')[0].selectedIndex = 4;
    craftSelect();
    console.log(rarity);
    amount = Math.min($('tr','#lockpicking-table')[parseInt(rarity)].childNodes[1].textContent,vars[1]);
    while (autoDo && amount > 9){
      amount -= 10;
      craftPickLock(rarity,2);
    }
    while (autoDo && amount > 0){
      amount--;
      craftPickLock(rarity,1);
    }
    return;
  }
  if(msg.toLowerCase().startsWith('/pickall ')){
    rarity=rarityNum[msg.slice(9)];
    chatInputElem.val('');
    if (rarity == undefined) return;
    $('select#center_select')[0].selectedIndex = 3;
    centerSelect();
    $('select#craft_select')[0].selectedIndex = 4;
    craftSelect();
    while (autoDo && $('tr','#lockpicking-table')[parseInt(rarity)].childNodes[1].textContent > 9) craftPickLock(rarity,2);
    while (autoDo && $('tr','#lockpicking-table')[parseInt(rarity)].childNodes[1].textContent > 0) craftPickLock(rarity,1);
    return;
  }*/
  if(msg.startsWith('/profile ')){
    viewPlayer(msg.slice(9));
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/who ')){
    $.post('misc.php', {mod:'viewplayer', id:msg.slice(5)}, function(data) {
      array = $.map($('td',$('table',data.v).find('tbody')[0]),function(n){return n.textContent;});
      name = array.after('Name:');
			online = false;
			line1 = `<font color="BBFFBB"><a href="javascript:m('${name}');">${name}</a> - ${$('a',data.v)[0].outerHTML} - Level ${array.after('Level:')} - ${array.after('Nobility Rank:')} - `;
			line2 = ` - <a href="javascript:viewPlayer('${name}')">Profile</a></font>`;
      $.post('misc.php', {mod:'playersonlinelist'}, function(data) { 
        if($.map($('td',data.v),function(n){return n.textContent;}).indexOf(name) != -1) {
					chatLine(line1.concat('[ONLINE]').concat(line2));
				} else {
					chatLine(line1.concat('<font color="#FFBBBB">[OFFLINE]</font>').concat(line2));
				}
      }, 'json');
    }, 'json');
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/misc ')){
    $.post('misc.php', {mod:'viewplayer', id:msg.slice(6)}, function(data) {
      array = $.map($('td',$('table',data.v).find('tbody')[0]),function(n){return n.textContent;});
      name = array.after('Name:');
      chatLine(`<font color="BBFFBB"><a href="javascript:m('${name}');">${name}</a> - Battles: ${array.after('Battles:')} - Battle Quests: ${array.after('Battle Quests:')} - TS Quests ${array.after('TS Quests:')}</font>`);
    }, 'json');
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/crafting ')){
    $.post('misc.php', {mod:'viewplayer', id:msg.slice(6)}, function(data) {
      array = $.map($('td',$('table',data.v).find('tbody')[0]),function(n){return n.textContent;});
      name = array.after('Name:');
      chatLine(`<font color="BBFFBB"><a href="javascript:m('${name}');">${name}</a> - Forging: ${array.after('Forging:')} - Leatherworking: ${array.after('Leatherworking:')} - Enchanting: ${array.after('Enchanting:')} - Lockpicking: ${array.after('Lockpicking:')} - Jewelcrafing: ${array.after('Jewelcrafting:')}</font>`);
    }, 'json');
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/gathering ')){
    $.post('misc.php', {mod:'viewplayer', id:msg.slice(6)}, function(data) {
      array = $.map($('td',$('table',data.v).find('tbody')[0]),function(n){return n.textContent;});
      name = array.after('Name:');
      chatLine(`<font color="BBFFBB"><a href="javascript:m('${name}');">${name}</a> - Hunting: ${array.after('Hunting:')} - Mining: ${array.after('Mining:')} - Woodcutting: ${array.after('Woodcutting:')} - Quarrying: ${array.after('Quarrying:')}</font>`);
    }, 'json');
    chatInputElem.val('');
    return;
  }
  if(msg.toLowerCase().startsWith('/g ')){msg.replaceAt(2,'c');}
  $.post('chat.php', {mod:'send', msg:msg}, function(data) {
    if(!data.err) {
      if(data.addignore) {ignored.push(data.addignore);}
      if(data.remignore) {ignored.splice(ignored.indexOf(data.remignore, 1));}
      chatInputElem.val('');
      chatinactivity = 0;
      update_chat(0);
    } else { displayError(data.err); }
  }, 'json');
}

window.bRightSelect = function() {
  mod = $('#bright_select').val();
	if(mod == 0){
	  $('#bright_content').html('<table><tr><td align="center"><select id="boost_select" onchange="javascript:refreshBoosts();"><option value="1">Credit</option><option value="2">Clan</option><option value="3">Equipment</option><option value="4">Total</option></select></td></tr></table><table id="boosts"></table>');
		for(var i = 0; i < boosts.length; i++){
			$('#boosts').append(`<tr><td>${boosts[i]}:</td><td id="${underscorify(boosts[i])}"></td><td>%</td></tr>`);
		}
		refreshBoosts();
	}
	$.post('displayr.php', {mod:mod}, function(data) {
		$('#bright_content').html(data.html);
	}, 'json');
}

window.possibleClanAttentionAlert = function(name, message, mode){
	$.post('clan.php', {mod:'members'}, function(data){
		var coLeader = false;
    var indexOfCl = data.v.indexOf(name)+name.length+4;
		if(data.v.slice(indexOfCl,indexOfCl+4) == '[CL]') {coLeader = true};
		if(data.v.slice(indexOfCl,indexOfCl+3) == '[L]') {coLeader = true};
		if(coLeader && mode == 'audio'){audio = new Audio('http://cdn.rawgit.com/somebody1234/misc-files/master/alert.mp3');audio.volume=parseFloat($('#volume')[0]).value/100; audio.play();}
		if(coLeader && mode == 'title'){document.title=`${name}: ${message}`;}
  }, 'json');
}

window.update_chat = function(initiate) {
  stopActivityTimer();
  startActivityTimer();
  $.post('chatupdate2.php', {initiate:initiate}, function(data) {
    if(data.c) {
      $.each(data.c, function(i, item) {
        if($.inArray(data.c[i].uid, ignored) < 0) {
          var chat_table = 1;
					var $class = '';
					var msg = '';
					data.c[i].message = makeHtml(linkify(data.c[i].message));
					  if(data.c[i].type == 1) { $class = 'main'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' '+genStatus(data.c[i].status)+'<a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>';
					  if($('#pingAlerts')[0].checked && msg.contains(yourName)){audio = new Audio('http://cdn.rawgit.com/somebody1234/misc-files/master/bell.mp3');audio.volume=parseFloat($('#volume')[0]).value/100; audio.play();}
						if($('#pingTabTitle')[0].checked && msg.contains(yourName)){ document.title = 'Your name has been mentioned.'; tabTitleChanged = true;}}
          else if(data.c[i].type == 0) { $class = 'chaterror'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #FF8888">'+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 5) { $class = 'ref'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #55AA55">'+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 10) { $class = 'global'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #88FF88">Global: '+data.c[i].message+'</span>';
            if($('#riftAlerts')[0].checked && data.c[i].message == '<span style="color: #CC66CC">A Rift will open in 5 minutes!</span>') {audio = new Audio('http://cdn.rawgit.com/somebody1234/misc-files/master/foghorn.mp3');audio.volume=parseFloat($('#volume')[0].value)/100; audio.play();}
						if($('#riftAlerts')[0].checked && data.c[i].message == `<span style="color: #CC66CC">A Rift has opened! The Rift will close in 10 minutes!</span> [<a href="javascript:enterRift()">Enter Rift</a>]`) {audio = new Audio('http://cdn.rawgit.com/somebody1234/misc-files/master/rumble.mp3');audio.volume=parseFloat($('#volume')[0].value)/100; audio.play();}
						if($('#riftTabTitle')[0].checked && data.c[i].message == '<span style="color: #CC66CC">A Rift will open in 5 minutes!</span>') {document.title = 'A rift is opening.'; tabTitleChanged = true;}
						if($('#riftTabTitle')[0].checked && data.c[i].message == `<span style="color: #CC66CC">A Rift has opened! The Rift will close in 10 minutes!</span> [<a href="javascript:enterRift()">Enter Rift</a>]`) {document.title = 'A Rift has opened.'; tabTitleChanged = true;}}
          else if(data.c[i].type == 1000) { $class = 'clan'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' <span style="color: #FFFF00">[Clan] <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>';
						if($('#clanAttentionAlerts')[0].checked && data.c[i].message.startsWith('ATTENTION: ')){possibleClanAttentionAlert(data.c[i].cname, data.c[i].message,'audio');}
						if($('#clanAttentionTabTitle')[0].checked && data.c[i].message.startsWith('ATTENTION: ')){possibleClanAttentionAlert(data.c[i].cname, data.c[i].message,'title');}}
          else if(data.c[i].type == 1001) { $class = 'clanglobal'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #FFFF00">Clan Global: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 20) { $class = 'newbie'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' <span style="color: #9999FF">[Newbie] <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 30) { $class = 'staff'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' <span style="color: #FF9933">[Staff] <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 55) { $class = 'trade'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' <span style="color: #00BB00">[Trade] <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 50) { $class = 'pmto'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #FF7171">Message Received: <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 51) { $class = 'pmfrom'; msg = '<span class="time">['+data.c[i].time+']</span> <span style="color: #F59292">Message Sent: <a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; }
          else if(data.c[i].type == 2) { $class = 'emote'; msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' <i>* '+genStatus(data.c[i].status)+'<a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a> '+data.c[i].message+'</span></i>'; }
          else if(data.c[i].type == 99) { $class = 'log'; msg = '<span class="time">['+data.c[i].time+']</span> '+data.c[i].message; chat_table = 10; }
          else if(data.c[i].type == 101) { msg = '<span class="time">['+data.c[i].time+']</span> '+genrank(data.c[i].nrank, data.c[i].prank)+' '+genStatus(data.c[i].status)+'<a href="javascript:m(\''+data.c[i].cname+'\');">'+data.c[i].cname+'</a>: '+data.c[i].message+'</span>'; chat_table = 50; }
          if(chat_table == 10) {
            $('#chat_table10').prepend('<tr id=\"ct10_tr'+(chatid10)+'\"><td>'+msg+'</td></tr>');
            chatid10++;
            if(chatview != 10) { chatcount10++; $('#chatcount10').html(' ('+chatcount10+')'); }
            if(initiate == 0 && $('#removeChatLines')[0].checked) { $('#ct10_tr'+(chatid10-chatsize)).remove(); }
          }
          else if(chat_table == 50) {
            $('#chat_table50').prepend('<tr id=\"ct50_tr'+(chatid50)+'\"><td>'+msg+'</td></tr>');
            chatid50++;
            if(initiate == 0 && $('#removeChatLines')[0].checked) { $('#ct50_tr'+(chatid50-chatsize)).remove(); }
          }
          else {
            chatLine(msg,$class);
            if(chatview != 1) { chatcount1++; $('#chatcount1').html(' ('+chatcount1+')'); }
            if(initiate == 0 && $('#removeChatLines')[0].checked) { $('#ct1_tr'+(chatid1-chatsize)).remove(); }
          }
        }
        if(data.fl) {window.location = 'http://www.heroesrpg.com';}
      });
    }
    stopActivityTimer();
    clearTimeout(chattimer);
    if(chatinactivity < 20) {
      chatinactivity++;
      chattimer = setTimeout(function() {
        update_chat(0);
      }, 5000);
    } else {
      chattimer = setTimeout(function() {
        update_chat(0);
      }, 9000);
    }
  }, 'json');
}