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.
7 var recordTemplate = new Template(
8 '<div class="record">#{data}<div class="info">Posted #{date}</div></div>'
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}</div></div>'
13 var latestRecordsTemplate = new Template(
14 '<div class="record"><a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
24 // Object to keep track of login status
25 function LoginStatus() {
27 document.cookie.split(/;\s+/).each(function(v) {
29 cookies[kv[0]] = kv[1];
31 if (cookies.auth && cookies.username) {
33 this.username = cookies.username;
35 this.loggedIn = false;
41 LoginStatus.prototype.login = function(username, password) {
42 new Ajax.Request(baseURL + '/login', {
47 onSuccess: function(r) {
48 var j = r.responseText.evalJSON();
49 if (j && j.status == 'success') {
51 this.username = username;
52 document.cookie = "username=" + username;
53 $('login.password').value = '';
56 alert("Could not log in");
57 $('login.username').focus();
60 onFailure: function(r) {
61 alert("Could not log in");
62 $('login.username').focus();
67 LoginStatus.prototype.logout = function() {
68 new Ajax.Request(baseURL + '/logout', {
70 username: this.username
72 onSuccess: function(r) {
73 this.loggedIn = false;
74 document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
78 document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
81 LoginStatus.prototype.update = function() {
83 $('userlink').href = '/#' + this.username;
84 $('userlink').update('@' + this.username);
85 $('reflink').href = '/#/ref/' + this.username;
95 LoginStatus.prototype.post = function(msg) {
97 alert("You are not logged in!");
101 new Ajax.Request(baseURL + '/put', {
103 username: this.username,
106 onSuccess: function(r) {
107 var j = r.responseText.evalJSON();
108 if (j && j.status == 'success') {
109 $('post.content').value = '';
110 if (location.hash != '#' + this.username) {
111 qlink(this.username);
113 currentPager.itemCount++;
114 currentPager.pageStart = null;
115 currentPager.loadItems();
118 alert('Post failed!');
121 onFailure: function(r) {
122 alert('Post failed!');
128 // Base object for paged data
130 this.itemsPerPage = 10;
133 Pager.prototype.initPager = function() {
134 this.itemCache = new Hash();
135 this.pageStart = null;
138 Pager.prototype.olderPage = function() {
139 if (this.pageStart >= this.itemsPerPage) {
140 qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
144 Pager.prototype.newerPage = function() {
145 if (this.pageStart + this.itemsPerPage < this.itemCount) {
146 qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
150 Pager.prototype.addItems = function(items) {
151 items.each(function(v) {
152 if (!this.itemCache[v.id])
153 this.itemCache[v.id] = v;
157 Pager.prototype.displayItems = function() {
158 if (this.pageStart == undefined)
159 this.pageStart == this.itemCount - 1;
162 if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
163 var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
164 for (var i = this.pageStart; i >= end; i--) {
165 items.insert(this.itemCache[i].html);
168 items.insert("There doesn't seem to be anything here!");
171 if (this.pageStart < this.itemCount - 1) {
172 $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
173 $('newer_link').show();
175 $('newer_link').hide();
178 if (this.pageStart >= 10) {
179 $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
180 $('older_link').show();
182 $('older_link').hide();
185 document.body.scrollTo();
188 Pager.prototype.showPageAt = function(r) {
189 var end = (r - 9 > 0 ? r - 9 : 0);
190 if (this.itemCache[r] && this.itemCache[end]) {
194 this.loadItems((r >= 49 ? r - 49 : 0), r);
198 Pager.prototype.showRecord = function(r) {
203 // Object to render user pages
204 function User(username) {
206 this.username = username;
207 this.baseFrag = username;
209 $$('[name=user.subscribelink]').each(Element.hide);
210 $$('[name=user.unsubscribelink]').each(Element.hide);
212 if (loginStatus.loggedIn) {
213 new Ajax.Request(baseURL + '/feedinfo/' + username, {
216 username: loginStatus.username
218 onSuccess: function(r) {
219 var json = r.responseText.evalJSON();
220 if (json.subscribed) {
221 $$('[name=user.subscribelink]').each(Element.hide);
222 $$('[name=user.unsubscribelink]').each(Element.show);
224 $$('[name=user.subscribelink]').each(Element.show);
225 $$('[name=user.unsubscribelink]').each(Element.hide);
231 new Ajax.Request(baseURL + '/info/' + username, {
233 onSuccess: function(r) {
234 var j = r.responseText.evalJSON();
236 this.itemCount = parseInt(j.record_count);
242 User.prototype = new Pager();
243 User.prototype.constructor = User;
245 User.prototype.show = function() {
246 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
250 $('rsslink').href = '/rss/' + this.username;
251 $$('[name=user.reflink]').each(function(e) {
252 e.href = '/#/ref/' + this.username;
254 $('usercontrols').show();
257 User.prototype.loadItems = function(from, to) {
259 if (from != undefined && to != undefined) {
260 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
263 url = baseURL + '/get/' + this.username;
266 new Ajax.Request(url, {
268 onSuccess: function(r) {
269 var records = r.responseText.evalJSON();
270 if (records && records.length > 0) {
271 records.each(function(v) {
273 mangleRecord(v, recordTemplate);
275 this.addItems(records);
277 this.pageStart = records[0].recInt;
281 onFailure: function(r) {
285 displayError('User not found');
290 function mangleRecord(record, template) {
291 record.recInt = parseInt(record.record);
293 var lines = record.data.split(/\r?\n/);
294 if (lines[lines.length - 1] == '')
299 var listMode = false;
300 lines.each(function(l) {
302 if (out[out.length - 1] == '<br>') {
303 out[out.length - 1] = '<p>';
305 if (out[out.length - 1] == '</li>') {
313 // Put quoted material into a special paragraph
315 var pi = out.lastIndexOf('<p>');
317 out[pi] = '<p class="quote">';
318 l = l.replace(/^>\s*/, '');
322 // Sanitize HTML input
323 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
325 // Turn HTTP URLs into links
326 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
328 // Turn markdown links into links
329 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
331 // Turn *foo* into italics and **foo** into bold
332 l = l.replace(/(\W|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
333 l = l.replace(/(\W|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
335 // Turn refs and tags into links
336 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
337 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
339 // Create lists when lines begin with *
342 var pi = out.lastIndexOf('<p>');
346 l = l.replace(/^\*\s*/, '');
351 // Create headers when lines begin with =
353 var m = l.match(/^(=+)/);
354 var depth = m[1].length;
356 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
357 out.push('<h' + depth + '>');
358 endpush = '</h' + depth + '>';
370 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
375 record.data = out.join('');
376 record.date = (new Date(record.timestamp * 1000)).toString();
377 record.html = template.evaluate(record);
380 function displayError(msg) {
381 items.innerText = msg;
385 // Object for browsing tags
386 function Tag(type, tag) {
391 var url = baseURL + "/tag/";
395 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
396 this.baseFrag = '/tag/' + tag;
400 this.baseFrag = '/ref/' + tag;
403 alert('Invalid tag type: ' + type);
408 new Ajax.Request(url, {
410 onSuccess: function(r) {
411 var j = r.responseText.evalJSON();
413 var maxid = j.length - 1;
414 j.each(function(v, i) {
416 mangleRecord(v, tagRecordTemplate)
419 this.pageStart = j.length - 1;
420 this.itemCount = j.length;
424 onFailure: function(r) {
430 Tag.prototype = new Pager();
431 Tag.prototype.constructor = Tag;
433 Tag.prototype.show = function() {
434 var ctype = {ref: '@', tag: '#'}[this.type];
436 $$('[name=section]').each(function(v) {
437 v.update(' about ' + ctype + this.tag);
441 $('older_link').hide();
442 $('newer_link').hide();
445 $('usercontrols').hide();
449 // Pager for browsing subscription feeds
452 this.username = loginStatus.username;
453 this.baseFrag = '/feed';
455 new Ajax.Request(baseURL + '/feed', {
458 username: loginStatus.username
460 onSuccess: function(r) {
461 var response = r.responseText.evalJSON();
463 var maxid = response.length - 1;
464 response.each(function(v, i) {
466 mangleRecord(v, tagRecordTemplate)
468 this.addItems(response);
469 this.pageStart = response.length - 1;
470 this.itemCount = response.length;
474 onFailure: function(r) {
479 Feed.prototype = new Pager();
480 Feed.prototype.constructor = Feed;
482 Feed.prototype.show = function() {
483 $$('[name=section]').each(function(v) {
484 v.update(' ' + loginStatus.username + "'s spycam");
488 $('older_link').hide();
489 $('newer_link').hide();
492 $('usercontrols').hide();
496 function postPopup() {
497 if (loginStatus.loggedIn) {
498 var post = $('post');
499 if (post.visible()) {
503 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
504 $('post.content').value = '@' + currentPager.username + ': ';
506 $('post.content').focus();
512 var username = $('signup.username').value;
513 var password = $('signup.password').value;
515 new Ajax.Request(baseURL + '/create', {
520 onSuccess: function(r) {
524 loginStatus.login(username, password);
526 onFailure: function(r) {
527 alert("Failed to create user");
532 function signup_cancel() {
537 function subscribe() {
538 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
541 username: loginStatus.username
543 onSuccess: function(r) {
544 var response = r.responseText.evalJSON();
545 if (response.status == 'success') {
546 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
547 $$('[name=user.subscribelink]').each(Element.hide);
548 $$('[name=user.unsubscribelink]').each(Element.show);
550 alert('Failed to subscribe. This is probably for the best');
553 onFailure: function(r) {
554 alert('Failed to subscribe. This is probably for the best');
559 function unsubscribe() {
560 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
563 username: loginStatus.username
565 onSuccess: function(r) {
566 var response = r.responseText.evalJSON();
567 if (response.status == 'success') {
568 alert("You come to your senses.");
569 $$('[name=user.subscribelink]').each(Element.show);
570 $$('[name=user.unsubscribelink]').each(Element.hide);
572 alert('You are unable to tear yourself away (because something failed on the server)');
575 onFailure: function(r) {
576 alert('You are unable to tear yourself away (because something failed on the server)');
581 var resizePostContentTimeout = null;
582 function resizePostContent() {
583 if (resizePostContentTimeout)
584 clearTimeout(resizePostContentTimeout);
585 resizePostContentTimeout = setTimeout(function() {
586 var c = $('post.content');
587 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
588 var m = c.value.match(/\r?\n/g);
594 c.style.height = (lines * 17) + "pt";
596 resizePostContentTimeout = null;
600 var tickerTimer = null;
601 var tickerHead, tickerTail;
603 function tickerFader(a, b, p) {
607 a.style.lineHeight = (100 * p) + '%';
609 b.style.opacity = p2;
610 b.style.lineHeight = (100 * p2) + '%';
617 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
618 tickerHead = tickerHead.nextSibling;
619 tickerTail = tickerTail.nextSibling;
620 if (tickerHead == null) {
622 loadLatest.delay(10);
626 function startTicker() {
628 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
632 // Show the first five
633 tickerHead = $('latest-posts').firstChild;
634 for (var i = 0; i < 10 && tickerHead; i++) {
636 tickerHead = tickerHead.nextSibling;
638 tickerTail = $('latest-posts').firstChild;
639 tickerTimer = setInterval(ticker, 5000);
642 function stopTicker() {
644 clearInterval(tickerTimer);
648 function loadLatest() {
649 new Ajax.Request(baseURL + '/latest.json', {
650 onSuccess: function(r) {
651 var j = r.responseText.evalJSON();
653 $('latest-tags').update();
654 j.tags.each(function(v) {
655 var a = new Element('a', {href: '/#/tag/' + v});
657 a.onclick = "return qlink()";
659 $('latest-tags').insert(a);
660 $('latest-tags').appendChild(document.createTextNode(' '));
663 $('latest-posts').update();
664 j.records.each(function(v) {
665 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
666 v.date = (new Date(v.timestamp * 1000)).toString();
667 var html = latestRecordsTemplate.evaluate(v);
668 $('latest-posts').insert(html);
675 function qlink(loc) {
678 } else if (event && event.target) {
679 location.href = event.target.href;
688 function hashSwitch() {
691 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
693 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
694 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
695 if (!currentPager || currentPager.type != m[1] || currentPager.tag != m[2])
696 currentPager = new Tag(m[1], m[2]);
700 var r = parseInt(m[3]);
701 currentPager.showPageAt(r);
703 } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
704 if (loginStatus.loggedIn) {
705 if (currentPager && currentPager.username != loginStatus.username)
706 currentPager = new Feed();
709 var r = parseInt(m[3]);
710 currentPager.showPageAt(r);
713 location.href = baseURL;
715 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
716 if (!currentPager || currentPager.username != m[1])
717 currentPager = new User(m[1]);
719 loginStatus.update();
722 var r = parseInt(m[3]);
724 currentPager.showPageAt(r);
726 currentPager.showRecord(r);
729 currentPager.pageStart = currentPager.itemCount - 1;
730 currentPager.loadItems();
733 $$('[name=section]').each(function(v) { v.update('Welcome') });
737 $('newer_link').hide();
738 $('older_link').hide();
741 $('usercontrols').hide();
747 function hashCheck() {
748 if (location.hash != lastHash) {
749 lastHash = location.hash;
756 loginStatus = new LoginStatus();
758 lastHash = location.hash;
761 setInterval(hashCheck, 250);
763 document.body.observe('keyup', function(event) {
764 if (event.shiftKey && event.keyCode == 32) {
769 $('post.content').addEventListener('keyup', function(event) {
770 event.stopPropagation();