1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
function escapeHtml(txt) {
if (!txt) { return ""; }
else { return $("<span>").text(txt).html(); }
}
// http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript
function linkify(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
return text.replace(exp,"<a href='$1'>$1</a>");
}
// http://snippets.dzone.com/posts/show/6995
var URLRegex = /^((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/i
var PicRegex = /\.(jpg|jpeg|png|gif|bmp)$/i;
function isImage(content) {
var match = URLRegex.exec(content);
sansParams = match && match[0].replace(/\?.*$/i, "");
return sansParams && PicRegex.test(sansParams);
}
function buildMsgContent(content) {
if (isImage(content)) {
return '<a href="' + content + '" target="_blank">'
+ '<img src="'+ content + '" /></a>';
} else {
return linkify(escapeHtml(content));
}
}
function buildMessageDiv(msg) {
var nick = escapeHtml(msg.nick);
return '<div class="msgDiv"><b><a href="/u/' + nick + ' ">' + nick + '</a>: </b>'
+ buildMsgContent(msg.content) + '</div>';
}
function buildGrowlDataAndPopDatShit(msg) {
var nick = escapeHtml(msg.nick);
nick = '<a href="/u/' + nick + ' " style="color:pink">' + nick + '</a>:'
var msg = buildMsgContent(msg.content)
growl(nick, msg)
}
function buildUserDiv(user) {
if (user.avatar) {
return '<div class="username"><a href="/u/' + escapeHtml(user.nick) + '">' +
'<img src="' + user.avatar + '" width="50" height="50">' +
escapeHtml(user.nick) + '</a></div>';
} else {
return '<div class="username"><a href="/u/' + escapeHtml(user.nick) + '">' +
escapeHtml(user.nick) + '</a></div>';
}
}
function handleMsgError(resp) {
var respText = resp.responseText ? resp.responseText.trim() : false;
if (respText == 'MUST_LOGIN') {
alert("Can't send message! Please login.");
} else if (respText) {
alert("Can't send message! (" + respText + ")");
} else {
alert("Can't send message!");
}
}
function submitMessage() {
var content = $.trim($('#msgInput').val());
if (content == '') { return; }
PostedMessages.push(content);
$('#msgInput').val('');
updateUI([{ 'nick': Nick, 'content': content}], null);
var onSuccess = function(json) {};
var onError = function(resp, textStatus, errorThrown) {
$('#msgInput, #msgSubmit').removeAttr('disabled');
handleMsgError(resp);
};
$.ajax({
type: 'GET',
timeout: 5000,
url: '/msg',
data: { 'room': Room, 'content': content },
cache: false,
dataType: 'json',
success: onSuccess,
error: onError
});
}
function ifEnter(fn) {
return function(e) {
if (e.keyCode == 13) { fn(); }
};
}
function isScrolledToBottom(div) {
return Math.abs(div.scrollTop - (div.scrollHeight - div.offsetHeight)) <= 3;
}
function scrollToBottom(div) {
div.scrollTop = div.scrollHeight;
}
// Give images time to start loading before scrolling.
// Needed until server knows size of images.
function delayedScrollToBottom(delay) {
setTimeout(scrollToBottom, delay, $('#messageList')[0]);
}
function updateUI(msgs, users) {
if (window['growlize'] && msgs !== null) {
$.map(msgs, buildGrowlDataAndPopDatShit)
}
else if (msgs !== null) {
var msgStr = $.map(msgs, buildMessageDiv).join('');
var wasScrolledToBottom = isScrolledToBottom($('#messageList')[0]);
$('#messageList').append(msgStr);
if (wasScrolledToBottom) {
delayedScrollToBottom(500);
}
}
if (users !== null) {
$("#userList").html($.map(users, buildUserDiv).join(''));
}
}
// A duplicate message is a message that was likely to have
// originated from this browser.
function isDuplicateMessage(m) {
if (m.nick != Nick || $.inArray(m.content, PostedMessages) == -1) {
return false;
}
var now = new Date().getTime();
return m.created_on - now < 5000;
}
function refresh() {
var onSuccess = function(json) {
try {
Timestamp = json.timestamp;
var messages = $.grep(
json.messages,
function(m) { return !isDuplicateMessage(m) });
updateUI(messages, json.users);
if (typeof UnseenMsgCounter !== 'undefined') {
UnseenMsgCounter += messages.length;
}
} catch(e) {
if (IsAdmin) {
alert("Exception in refresh");
console.log(e);
}
}
setTimeout(refresh, 1000);
};
var onError = function(resp, textStatus, errorThrown) {
if (IsAdmin) {
console.log(resp, textStatus, errorThrown);
}
setTimeout(refresh, 1000);
};
$.ajax({
type: 'GET',
timeout: 5000,
url: '/refresh',
data: { 'room': Room, 'since': Timestamp },
cache: false,
dataType: 'json',
success: onSuccess,
error: onError
});
}
function initChat() {
$('.msgDiv .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
$('#msgInput').keyup(ifEnter(submitMessage));
$('#msgSubmit').click(submitMessage);
delayedScrollToBottom(500);
setTimeout(refresh, 1000);
}
function initProfile() {
$('.logged-dump .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
var onSubmit = function(original_element, edit, old) {
edit = $.trim(edit);
if (edit == old) { return old };
// TODO: Prevent entering script tags
if (original_element == 'avatar' && edit.indexOf("<") != -1) {
return old;
}
$.ajax({
type: "GET",
timeout: 5000,
url: "/update-profile",
data: { 'attr': original_element, 'val': edit }
});
if (original_element == 'avatar') {
var s = '<img id="avatarPic" src="' + edit + '" width="150" />';
$('#avatarPic').replaceWith(s);
}
return escapeHtml(edit);
};
var opt = { 'default_text': 'Enter here!',
'callback': onSubmit,
'field_type': 'text',
'callbackShowErrors': false };
$('#avatar.editable').editInPlace(opt);
opt['field_type'] = 'textarea';
$('#contact.editable, #bio.editable').editInPlace(opt);
};
function initLog() {
$('.logged-dump .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
}
function growl(user, msg) {
$.gritter.add({
// (string | mandatory) the heading of the notification
title: user,
// (string | mandatory) the text inside the notification
text: msg
});
}
|