fac5371b391d381553a849bf3111b27783b53555
[blerg.git] / www / js / blerg.js
1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2  * BSD-style license.  Please see the COPYING file for details.
3  */
4
5 // Config
6 var baseURL = '';
7 var recordTemplate = new Template(
8     '<div class="record">#{data}<div class="info">Posted #{date}. <a href="' + baseURL + '/\##{author}/#{record}" onclick="return qlink()">[permalink]</a> <a href="#" onclick="postPopup(\'@#{author}/#{record}: \'); return false">[reply]</a></div></div>'
9 );
10 var tagRecordTemplate = new Template(
11     '<div class="record">#{data}<div class="info">Posted by <a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> on #{date}. <a href="' + baseURL + '/\##{author}/#{record}" onclick="return qlink()">[permalink]</a> <a href="#" onclick="postPopup(\'@#{author}/#{record}: \'); return false">[reply]</a></div></div>'
12 );
13 var latestRecordsTemplate = new Template(
14     '<div class="record"><a class="author ref" href="' + baseURL + '/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
15 );
16
17 // Page elements
18 var items;
19
20 // Other globals
21 var currentPager;
22 var loginStatus;
23
24 // Object to keep track of login status
25 function LoginStatus() {
26     var cookies = {};
27     document.cookie.split(/;\s+/).each(function(v) {
28         kv = v.split('=');
29         cookies[kv[0]] = kv[1];
30     });
31     if (cookies.auth && cookies.username) {
32         this.loggedIn = true;
33         this.username = cookies.username;
34         this.requestFeedStatus();
35         this.feedStatusUpdateInterval = setInterval(this.requestFeedStatus.bind(this), 900000);
36     } else {
37         this.loggedIn = false;
38         this.username = null;
39     }
40     this.update();
41 }
42
43 LoginStatus.prototype.login = function(username, password) {
44     new Ajax.Request(baseURL + '/login', {
45         parameters: {
46             username: username,
47             password: password
48         },
49         onSuccess: function(r) {
50             var j = r.responseText.evalJSON();
51             if (j && j.status == 'success') {
52                 this.loggedIn = true;
53                 this.username = username;
54                 document.cookie = "username=" + username;
55                 $('login.password').value = '';
56                 this.requestFeedStatus();
57                 this.feedStatusUpdateInterval = setInterval(this.requestFeedStatus.bind(this), 900000);
58                 this.update();
59             } else {
60                 alert("Could not log in");
61                 $('login.username').focus();
62             }
63         }.bind(this),
64         onFailure: function(r) {
65             alert("Could not log in");
66             $('login.username').focus();
67         }
68     });
69 }
70
71 LoginStatus.prototype.logout = function() {
72     new Ajax.Request(baseURL + '/logout', {
73         parameters: {
74             username: this.username
75         },
76         onComplete: function(r) {
77             this.loggedIn = false;
78             document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
79             this.update();
80             clearInterval(this.feedStatusUpdateInterval);
81         }.bind(this)
82     });
83     document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
84 }
85
86 LoginStatus.prototype.update = function() {
87     if (this.loggedIn) {
88         $('userlink').href = baseURL + '/#' + this.username;
89         $('userlink').update('@' + this.username);
90         $('reflink').href = baseURL + '/#/ref/' + this.username;
91         $('login').hide();
92         $('logout').show();
93     } else {
94         $('post').hide();
95         $('login').show();
96         $('logout').hide();
97     }
98 }
99
100 LoginStatus.prototype.post = function(msg) {
101     if (!this.loggedIn) {
102         alert("You are not logged in!");
103         return;
104     }
105
106     new Ajax.Request(baseURL + '/put', {
107         parameters: {
108             username: this.username,
109             data: msg
110         },
111         onSuccess: function(r) {
112             var j = r.responseText.evalJSON();
113             if (j && j.status == 'success') {
114                 $('post.content').value = '';
115                 if (location.hash != '#' + this.username) {
116                     qlink(this.username);
117                 } else {
118                     currentPager.itemCount++;
119                     currentPager.reload();
120                 }
121             } else {
122                 alert('Post failed!');
123             }
124         }.bind(this),
125         onFailure: function(r) {
126             alert('Post failed!');
127         }
128     });
129 }
130
131 LoginStatus.prototype.requestFeedStatus = function() {
132     new Ajax.Request('/feedinfo', {
133         parameters: { username: this.username },
134         onSuccess: function(r) {
135             var j = r.responseText.evalJSON();
136             if (j['new'] > 0) {
137                 $('newFeedMessages').update('(' + j['new'] + ' new)');
138             } else {
139                 $('newFeedMessages').update('');
140             }
141         }
142     });
143 }
144
145 // Base object for paged data
146 function Pager() {
147     this.itemsPerPage = 10;
148     this.itemCache = new Hash();
149     this.pageStart = null;
150 }
151
152 Pager.prototype.updateState = function(m) {
153     return false;
154 }
155
156 Pager.prototype.show = function() {
157     items.show();
158 }
159
160 Pager.prototype.hide = function() {
161     items.hide();
162     items.update();
163     $('newer_link').hide();
164     $('older_link').hide();
165 }
166
167 Pager.prototype.olderPage = function() {
168     if (this.pageStart >= this.itemsPerPage) {
169         qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
170     }
171 }
172
173 Pager.prototype.newerPage = function() {
174     if (this.pageStart + this.itemsPerPage < this.itemCount) {
175         qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
176     }
177 }
178
179 Pager.prototype.addItems = function(items) {
180     items.each(function(v) {
181         if (!this.itemCache[v.id])
182             this.itemCache[v.id] = v;
183     }.bind(this));
184 }
185
186 Pager.prototype.displayItems = function() {
187     if (this.pageStart == undefined)
188         this.pageStart == this.itemCount - 1;
189     items.update();
190
191     if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
192         var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
193         for (var i = this.pageStart; i >= end; i--) {
194             items.insert(this.itemCache[i].html);
195         }
196     } else {
197         items.insert("There doesn't seem to be anything here!");
198     }
199
200     if (this.pageStart < this.itemCount - 1) {
201         $('newer_link').href = baseURL + '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
202         $('newer_link').show();
203     } else {
204         $('newer_link').hide();
205     }
206
207     if (this.pageStart >= 10) {
208         $('older_link').href = baseURL + '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
209         $('older_link').show();
210     } else {
211         $('older_link').hide();
212     }
213
214     document.body.scrollTo();
215 }
216
217 Pager.prototype.reload = function() {
218     this.pageStart = null;
219     this.loadItems(null, null, Pager.prototype.showPageAt.bind(this, this.itemCount - 1));
220 }
221
222 Pager.prototype.showPageAt = function(r) {
223     var end = (r - 9 > 0 ? r - 9 : 0);
224     if (this.itemCache[r] && this.itemCache[end]) {
225         this.pageStart = r;
226         this.displayItems();
227     } else {
228         this.loadItems((r >= 49 ? r - 49 : 0), r, Pager.prototype.showPageAt.bind(this, r));
229     }
230 }
231
232 Pager.prototype.showRecord = function(r) {
233     if (this.itemCache[r]) {
234         $('older_link').hide();
235         $('newer_link').hide();
236         items.update(this.itemCache[r].html);
237     } else {
238         this.loadItems(r, r, Pager.prototype.showRecord.bind(this, r));
239     }
240 }
241
242 Pager.prototype.loadItems = function(from, to, continuation) { }
243
244 function displayError(msg) {
245     items.innerText = msg;
246 }
247
248
249 // Object for browsing tags
250 function Tag(m) {
251     Pager.call(this);
252     this.type = m[1];
253     this.tag = m[2];
254     this.pageStart = parseInt(m[3]);
255
256     var url = baseURL + "/tag/";
257     switch(this.type) {
258     case 'tag':
259         //url += '%23';
260         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
261         this.baseFrag = '/tag/' + this.tag;
262         break;
263     case 'ref':
264         url += '%40';
265         this.baseFrag = '/ref/' + this.tag;
266         break;
267     default:
268         alert('Invalid tag type: ' + this.type);
269         return;
270     }
271     url += this.tag;
272
273     new Ajax.Request(url, {
274         method: 'get',
275         onSuccess: function(r) {
276             var j = r.responseText.evalJSON();
277             if (j) {
278                 var maxid = j.length - 1;
279                 j.each(function(v, i) {
280                     v.id = maxid - i;
281                     mangleRecord(v, tagRecordTemplate)
282                 });
283                 this.addItems(j);
284                 if (!this.pageStart)
285                     this.pageStart = j.length - 1;
286                 this.itemCount = j.length;
287             }
288             this.displayItems();
289         }.bind(this),
290         onFailure: function(r) {
291             this.displayItems();
292         }.bind(this)
293     });
294
295 }
296 Tag.prototype = new Pager();
297 Tag.prototype.constructor = Tag;
298
299 Tag.prototype.updateState = function(m) {
300     if (this.type != m[1] || this.tag != m[2])
301         return false;
302
303     this.pageStart = parseInt(m[3]) || this.itemCount - 1;
304     this.displayItems();
305
306     return true;
307 }
308
309 Tag.prototype.show = function() {
310     Pager.prototype.show.call(this);
311
312     var ctype = {ref: '@', tag: '#'}[this.type];
313
314     $$('[name=section]').each(function(v) {
315         v.update(' about ' + ctype + this.tag);
316     }.bind(this));
317 }
318
319
320 // Pager for browsing subscription feeds
321 function Feed(m) {
322     Pager.call(this);
323     this.username = loginStatus.username;
324     this.baseFrag = '/feed';
325     this.pageStart = parseInt(m[1]);
326
327     new Ajax.Request(baseURL + '/feed', {
328         method: 'post',
329         parameters: {
330             username: loginStatus.username
331         },
332         onSuccess: function(r) {
333             var response = r.responseText.evalJSON();
334             if (response) {
335                 var maxid = response.length - 1;
336                 response.each(function(v, i) {
337                     v.id = maxid - i;
338                     mangleRecord(v, tagRecordTemplate)
339                 });
340                 this.addItems(response);
341                 if (!this.pageStart)
342                     this.pageStart = response.length - 1;
343                 this.itemCount = response.length;
344                 loginStatus.requestFeedStatus();
345             }
346             this.displayItems();
347         }.bind(this),
348         onFailure: function(r) {
349             this.displayItems();
350         }.bind(this)
351     });
352 }
353 Feed.prototype = new Pager();
354 Feed.prototype.constructor = Feed;
355
356 Feed.prototype.updateState = function(m) {
357     this.pageStart = parseInt(m[1]) || this.itemCount - 1;
358     this.displayItems();
359
360     return true;
361 }
362
363 Feed.prototype.show = function() {
364     Pager.prototype.show.call(this);
365     $$('[name=section]').each(function(v) {
366         v.update(' ' + loginStatus.username + "'s spycam");
367     }.bind(this));
368 }
369
370
371 function postPopup(initial) {
372     if (loginStatus.loggedIn || initial) {
373         var post = $('post');
374         if (post.visible()) {
375             post.hide();
376         } else {
377             post.show();
378             if (initial) {
379                 $('post.content').value = initial;
380             } else if (!$('post.content').value && currentPager.username && currentPager.username != loginStatus.username) {
381                 $('post.content').value = '@' + currentPager.username + ': ';
382             }
383             $('post.content').focus();
384         }
385     }
386 }
387
388 function signup() {
389     var username = $('signup.username').value;
390     var password = $('signup.password').value;
391
392     new Ajax.Request(baseURL + '/create', {
393         parameters: {
394             username: username,
395             password: password
396         },
397         onSuccess: function(r) {
398             $('signup').hide();
399             qlink(username);
400
401             loginStatus.login(username, password);
402         },
403         onFailure: function(r) {
404             alert("Failed to create user");
405         }
406     });
407 }
408
409 function signup_cancel() {
410     $('signup').hide();
411     urlSwitch();
412 }
413
414 function passwd() {
415     var old_password = $('passwd.old_password').value;
416     var new_password = $('passwd.new_password').value;
417
418     new Ajax.Request(baseURL + '/passwd', {
419         parameters: {
420             username: loginStatus.username,
421             password: old_password,
422             new_password: new_password
423         },
424         onSuccess: function(r) {
425             if (r.responseJSON.status == 'success') {
426                 alert('Password changed');
427                 passwd_cancel();
428             } else {
429                 alert('Password change failed.  Your password has NOT been changed.');
430             }
431         },
432         onFailure: function(r) {
433             alert('Password change error');
434         }
435     });
436 }
437
438 function passwd_cancel() {
439     $('passwd').hide();
440     $('navigation').show();
441     urlSwitch();
442 }
443
444 function subscribe() {
445     new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
446         method: 'post',
447         parameters: {
448             username: loginStatus.username
449         },
450         onSuccess: function(r) {
451             var response = r.responseText.evalJSON();
452             if (response.status == 'success') {
453                 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
454                 $$('[name=user.subscribelink]').each(Element.hide);
455                 $$('[name=user.unsubscribelink]').each(Element.show);
456             } else {
457                 alert('Failed to subscribe. This is probably for the best');
458             }
459         },
460         onFailure: function(r) {
461             alert('Failed to subscribe. This is probably for the best');
462         }
463     });
464 }
465
466 function unsubscribe() {
467     new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
468         method: 'post',
469         parameters: {
470             username: loginStatus.username
471         },
472         onSuccess: function(r) {
473             var response = r.responseText.evalJSON();
474             if (response.status == 'success') {
475                 alert("You come to your senses.");
476                 $$('[name=user.subscribelink]').each(Element.show);
477                 $$('[name=user.unsubscribelink]').each(Element.hide);
478             } else {
479                 alert('You are unable to tear yourself away (because something failed on the server)');
480             }
481         },
482         onFailure: function(r) {
483             alert('You are unable to tear yourself away (because something failed on the server)');
484         }
485     });
486 }
487
488 var tickerTimer = null;
489 var tickerHead, tickerTail;
490
491 function tickerFader(a, b, p) {
492     var p2 = 1 - p;
493
494     a.style.opacity = p;
495     a.style.lineHeight = (100 * p) + '%';
496
497     b.style.opacity = p2;
498     b.style.lineHeight = (100 * p2) + '%';
499     if (p == 1.0)
500         b.hide();
501 }
502
503 function ticker() {
504     tickerHead.show();
505     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
506     tickerHead = tickerHead.nextSibling;
507     tickerTail = tickerTail.nextSibling;
508     if (tickerHead == null) {
509         stopTicker();
510         loadLatest.delay(10);
511     }
512 }
513
514 function startTicker() {
515     stopTicker();
516     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
517         elem.hide();
518     }
519
520     // Show the first five
521     tickerHead = $('latest-posts').firstChild;
522     for (var i = 0; i < 10 && tickerHead; i++) {
523         tickerHead.show();
524         tickerHead = tickerHead.nextSibling;
525     }
526     tickerTail = $('latest-posts').firstChild;
527     tickerTimer = setInterval(ticker, 5000);
528 }
529
530 function stopTicker() {
531     if (tickerTimer)
532         clearInterval(tickerTimer);
533     tickerTimer = null;
534 }
535
536 function loadLatest() {
537     new Ajax.Request(baseURL + '/latest.json', {
538         method: 'GET',
539         onSuccess: function(r) {
540             var j = r.responseText.evalJSON();
541
542             $('latest-tags').update();
543             j.tags.each(function(v) {
544                 var a = new Element('a', {href: baseURL + '/#/tag/' + v});
545                 a.insert('#' + v);
546                 a.onclick = "return qlink()";
547                 a.className = 'ref';
548                 $('latest-tags').insert(a);
549                 $('latest-tags').appendChild(document.createTextNode(' '));
550             });
551
552             $('latest-posts').update();
553             j.records.each(function(v) {
554                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
555                 v.date = (new Date(v.timestamp * 1000)).toString();
556                 var html = latestRecordsTemplate.evaluate(v);
557                 $('latest-posts').insert(html);
558             });
559             startTicker();
560         }
561     });
562 }
563
564 function ExternalURLPost(m) {
565     this.title = decodeURIComponent(m[1]).replace(']','').replace('[','');
566     this.url = decodeURIComponent(m[2]);
567 }
568
569 ExternalURLPost.prototype.show = function() {
570     $('post.content').value = '[' + this.title + '](' + this.url + ')';
571     $('post').show();
572 }