User:Robyn Grayson/chat.js

/* ChatPlugins */ var ChatPlugins = { release: { version: 1.1, branch: "Stable" },	models: { feature: function(id, name, access, script) { this.enabled = false; this.id = id; this.name = name; this.access = access; this.script = script; },		alert: function(text) { newInlineAlert = new models.InlineAlert; newInlineAlert.attributes.text = text; mainRoom.model.chats.add(newInlineAlert); },		command: function(command, script) { this.command = command; this.script = script; }	},	features: {}, settings: { release: { version: 1.0, branch: "Stable" },		icons: { staffIcon: "http://img1.wikia.nocookie.net/__cb20140626173406/gamedezyner/images/6/60/StaffIcon.png", modIcon: "http://img1.wikia.nocookie.net/__cb20140626173343/gamedezyner/images/8/89/ModIcon.png" },		sounds: { pingSound: "https://notificationsounds.com/soundfiles/9461cce28ebe3e76fb4b931c35a169b0/file-sounds-1044-inquisitiveness.mp3" },		features: { pings: true }	},	save: function { ChatPlugins.settings.features.pings = ChatPlugins.features.pings.enabled; api.functions.editPage("User:" + wgUserName + "/ChatPlugins.js", JSON.stringify(ChatPlugins.settings)); },	load: function { new ChatPlugins.models.alert("Welcome to Chat Plugins 1.0!"); pagecontents = api.functions.getPageContents("User:" + wgUserName + "/ChatPlugins.js"); if (pagecontents == "error") { new ChatPlugins.models.alert("There seems to be something wrong with your settings file, or it doesn't exist yet. Default settings have been saved."); ChatPlugins.save; } else { ChatPlugins.settings = JSON.parse(pagecontents); ChatPlugins.features.pings.enabled = ChatPlugins.settings.features.pings; ChatPlugins.features.pings.words = ChatPlugins.settings.pings; }		pagecontents = api.functions.getPageContents("MediaWiki:ChatPluginsSettings.js"); if (pagecontents != "error") { wikicustom = JSON.parse(pagecontents); if (typeof(wikicustom.settings) != "object") { new ChatPlugins.models.alert("This wiki has a custom settings page, but it is broken."); } else { ChatPlugins.settings.icons = wikicustom.settings.icons; //Load Wiki-specific icons ChatPlugins.settings.sounds = wikicustom.settings.sounds; //Load Wiki-specific sounds new ChatPlugins.models.alert("This wiki has custom settings and they have been applied."); }		}	} }; // Call API function callAPI(data, method, callback) { data.format = 'json'; $.ajax({		data: data,		dataType: 'json',		url: wgScriptPath + '/api.php',		type: method,		success: function(response) {			if (response.error) showError('API error: ' + response.error.info);			else callback(response);		},		error: function(xhr, error) {			showError('AJAX error: ' + error);		}	}); } //Inline-mod tools function scrollToBottom { var chat = document.getElementById('Chat_' + mainRoom.roomId); chat.scrollTop = chat.scrollHeight; } ChatPlugins.features.modIcons = new ChatPlugins.models.feature(null, "Mod Icons", 0, function(chat) {	var time = new Date;	var hours = time.getHours;	var minutes = time.getMinutes;	var seconds = time.getSeconds;	if (hours < 10) hours = '0' + hours;	if (minutes < 10) minutes = "0" + minutes;	if (seconds < 10) seconds = "0" + seconds;	mainRoom.viewDiscussion.chatUL.children.last.children(".message").attr('msg-source', chat.attributes.text);	mainRoom.viewDiscussion.chatUL.children.last.children(".message").attr('msg-time', hours + ':' + minutes + ':' + seconds);	var icon = ;		mainRoom.viewDiscussion.chatUL.children.last.children('.message').hover(function { thistarget = this; username = $(thistarget).parent.attr("data-user"); timestamp = $(thistarget).attr('msg-time'); message = $(thistarget).attr('msg-source'); $(thistarget).append(' Quote '); $(thistarget).children('.inline-quote').click(function(e) {			if (e.shiftKey) {				$('.message textarea').val($('.message textarea').val + '[' + timestamp + '] ' + username + ": " + message.replace(/^\/me/, "* " + username) + '\n');			} else {				$('.message textarea').val('[' + timestamp + '] ' + username + ": " + message.replace(/^\/me/, "* " + username) + '\n');				scrollToBottom;			}			$(".message textarea").focus;		}); }, function { $(this).children('.inline-quote').remove; }); }); //Bind function to chat updates setTimeout(function {	mainRoom.model.chats.bind('afteradd', ChatPlugins.features.modIcons.script, mainRoom.viewDiscussion); }, 15000);

importScriptPage('User:Robyn Grayson/chat.js', 'clockwork-planet'); importScriptPage('ChatNotifications/code.js', 'dev'); importScriptPage('ChatScript', 'gmods-hideout'); importScriptPage('ChatButtonsCollectionDeluxe.js', 'dev'); importScriptPage('MediaWiki:ChatEditTools/code2.js', 'dev'); importScriptPage('MediaWiki:CustomChatPings/code.js', 'dev'); importScriptPage('MediaWiki:CapsFirst/code.js', 'dev'); importScriptPage('MessageBlocker/code.js', 'dev'); importScriptPage('LightBlock/code.js', 'dev'); importScriptPage('MediaWiki:FaviconNotifier/code.js', 'dev'); $('[name="message"]').keypress(function (e) {   if (e.which == 32 || e.which == 13) {        switch (this.value) {        case '/greet':            this.value = 'Hiya, welcome to the ' + wgSiteName + ' chat!';            break;        case '/logs':            this.value = 'You can view the chat logs here.';            break;            case '/emotes':            this.value = 'You can view the emoticons here.';            break;        case '/tou':            this.value = 'Wikia\'s Terms of Use can be found here.';            break;         case '/shrug':            this.value = '¯\\_(ツ)_/¯';            break;                    }        var test = "/google";        if (this.value.indexOf(test) > -1 && this.value.indexOf(test) < 8) {            var query = this.value.replace('/google ', '');            query = query.replace(/ /g, "+"); this.value = "http://www.lmgtfy.com/?q=" + query; }   } });

(function($, mw) {	if (wgCanonicalSpecialPageName != 'Chat' || window.PrivateHistoryInit) return;	window.PrivateHistoryInit = true;	// Check if the browser supports the feature we'll mostly use here	if (!window.localStorage) {		// Since the user is already running a stone-age browser, better check if console.log is a thing.		if (console && console.log)			console.log('Your browser does not support localStorage; exiting PrivateHistory...');		return;	}	var PrivateHistory = {		avatars: {},		indexes: {},		complete: [],		Unix: {			small: function(n) {				return Number(n.toString.slice(0, -4));			},			big: function(n) {				return Number(n.toString + '000');			}		},		loadMessages: function(usrs, key, privateRoom) {			var script = PrivateHistory,			arr = JSON.parse(localStorage.getItem(key)),			users = [wgUserName].concat(usrs),			old = privateRoom.model.chats.models.map(function(e) { var a = e.attributes; if (a.isScriptAddition) return false; var b = script.Unix.small(a.timeStamp), c = a.text, d = usrs.indexOf(a.name) + 1; return [b, c, d]; }).filter(Boolean);			arr = arr.concat(old).map(function(el, i, a) { return a.map(function(e) {return JSON.stringify(e);}).lastIndexOf(JSON.stringify(el)) != i ? null : el; }).filter(Boolean);			var $ul = privateRoom.viewDiscussion.chatUL;			if (privateRoom.model.chats.models.length == arr.length)				return;			else				console.log(privateRoom.model.chats.models.length, arr.length);			while (privateRoom.model.chats.models[0])				privateRoom.model.chats.remove(privateRoom.model.chats.models[0]);			var oArr = Infinity;			if (arr.length > 50) {				oArr = arr.length;				var idx = script.indexes,				k = usrs.join('|');				idx[k] = idx[k] || 0;				idx[k] += 50;				arr = arr.slice(-script.indexes[k]);			}			for (var i in arr) {				var item = arr[i],				time = item[0],				text = item[1],				name = users[item[2]],				main = mainRoom.model.users.findByName(name);				if (!script.avatars[name])					console.log(name, users, item[2]);				privateRoom.model.chats.add( new models.ChatEntry({						timeStamp: script.Unix.big(time),						avatarSrc: script.avatars[name] || (main ? main.attributes.avatarSrc : ''),						name: name,						text: text,						isScriptAddition: true					}) );			}			if (privateRoom.model.chats.models.length >= oArr)				script.complete.push(usrs.join('|'));		},		init: function {			var script = this;			var mainUsers = mainRoom.model.users.models;			for (var i in mainUsers) {				var a = mainUsers[i].attributes;				script.avatars[a.name] = a.avatarSrc;			}			mainRoom.model.users.bind('add', function(usr) { var a = usr.attributes; script.avatars[a.name] = a.avatarSrc; });			// Bind function to Private chat updates			mainRoom.model.privateUsers.bind('add', function(u) { var name = u.attributes.name, PMId = u.attributes.roomId, privateRoom = mainRoom.chats.privates[PMId]; function initRoom { if (!privateRoom.model.users.models.length) return; clearInterval(interval); var usrs = privateRoom.model.privateRoom.attributes.users.map(function(n) {						if (n == mw.config.get('wgUserName')) return null;						return n;					}).filter(Boolean).sort, key = 'PrivateHistory-' + usrs.join('|'), privateHistory = localStorage.getItem(key), afterChat = function(chat) { var attrs = chat.attributes; if (attrs.isInlineAlert || attrs.isScriptAddition) return; var time = script.Unix.small(attrs.timeStamp), user = usrs.indexOf(attrs.name) + 1, text = attrs.text, value = JSON.parse(localStorage.getItem(key)), push = [time, text, user]; if (value.indexOf(push) == -1) value.push(push); localStorage.setItem(key, JSON.stringify(value)); },					scroll = function(e) { if (e.target.scrollTop < 500 && script.complete.indexOf(usrs.join('|')) === -1) script.loadMessages(usrs, key, privateRoom); };					if (privateHistory === null) localStorage.setItem(key, '[]'); else script.loadMessages(usrs, key, privateRoom); privateRoom.viewDiscussion.chatDiv[0].addEventListener('scroll', scroll, {passive: true}); privateRoom.model.chats.models.forEach(afterChat); privateRoom.model.chats.bind('afteradd', afterChat); }				var interval = setInterval(initRoom, 50); });		}	};	var interval = setInterval(function { if (!window.mainRoom) return; clearInterval(interval); PrivateHistory.init; }, 250);	window.PrivateHistory = PrivateHistory; })(window.jQuery, window.mediaWiki);