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();
186 Pager.prototype.showPageAt = function(r) {
187 if (this.itemCache[r] && this.itemCache[r - 9]) {
191 this.loadItems((r >= 49 ? r - 49 : 0), r);
195 Pager.prototype.showRecord = function(r) {
200 // Object to render user pages
201 function User(username) {
203 this.username = username;
204 this.baseFrag = username;
206 $$('[name=user.subscribelink]').each(Element.hide);
207 $$('[name=user.unsubscribelink]').each(Element.hide);
209 if (loginStatus.loggedIn) {
210 new Ajax.Request(baseURL + '/feedinfo/' + username, {
213 username: loginStatus.username
215 onSuccess: function(r) {
216 var json = r.responseText.evalJSON();
217 if (json.subscribed) {
218 $$('[name=user.subscribelink]').each(Element.hide);
219 $$('[name=user.unsubscribelink]').each(Element.show);
221 $$('[name=user.subscribelink]').each(Element.show);
222 $$('[name=user.unsubscribelink]').each(Element.hide);
228 new Ajax.Request(baseURL + '/info/' + username, {
230 onSuccess: function(r) {
231 var j = r.responseText.evalJSON();
233 this.itemCount = parseInt(j.record_count);
239 User.prototype = new Pager();
240 User.prototype.constructor = User;
242 User.prototype.show = function() {
243 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
247 $('rsslink').href = '/rss/' + this.username;
248 $$('[name=user.reflink]').each(function(e) {
249 e.href = '/#/ref/' + this.username;
251 $('usercontrols').show();
254 User.prototype.loadItems = function(from, to) {
256 if (from != undefined && to != undefined) {
257 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
260 url = baseURL + '/get/' + this.username;
263 new Ajax.Request(url, {
265 onSuccess: function(r) {
266 var records = r.responseText.evalJSON();
267 if (records && records.length > 0) {
268 records.each(function(v) {
270 mangleRecord(v, recordTemplate);
272 this.addItems(records);
274 this.pageStart = records[0].recInt;
278 onFailure: function(r) {
282 displayError('User not found');
287 function mangleRecord(record, template) {
288 record.recInt = parseInt(record.record);
290 var lines = record.data.split(/\r?\n/);
291 if (lines[lines.length - 1] == '')
296 var listMode = false;
297 lines.each(function(l) {
299 if (out[out.length - 1] == '<br>') {
300 out[out.length - 1] = '<p>';
302 if (out[out.length - 1] == '</li>') {
311 var pi = out.lastIndexOf('<p>');
313 out[pi] = '<p class="quote">';
314 l = l.replace(/^>\s*/, '');
319 var pi = out.lastIndexOf('<p>');
323 l = l.replace(/^\*\s*/, '');
328 var m = l.match(/^(=+)/);
329 var depth = m[1].length;
331 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
332 out.push('<h' + depth + '>');
333 endpush = '</h' + depth + '>';
337 // Sanitize HTML input
338 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
340 // Turn HTTP URLs into links
341 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
343 // Turn markdown links into links
344 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
346 // Turn *foo* into italics and **foo** into bold
347 l = l.replace(/(\s)\*\*([^*]+)\*\*(\s)/g, '$1<b>$2</b>$3');
348 l = l.replace(/(\s)\*([^*]+)\*(\s)/g, '$1<i>$2</i>$3');
350 // Turn refs and tags into links
351 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
352 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
362 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
365 record.data = out.join('');
366 record.date = (new Date(record.timestamp * 1000)).toString();
367 record.html = template.evaluate(record);
370 function displayError(msg) {
371 items.innerText = msg;
375 // Object for browsing tags
376 function Tag(type, tag) {
381 var url = baseURL + "/tag/";
385 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
386 this.baseFrag = '/tag/' + tag;
390 this.baseFrag = '/ref/' + tag;
393 alert('Invalid tag type: ' + type);
398 new Ajax.Request(url, {
400 onSuccess: function(r) {
401 var j = r.responseText.evalJSON();
403 var maxid = j.length - 1;
404 j.each(function(v, i) {
406 mangleRecord(v, tagRecordTemplate)
409 this.pageStart = j.length - 1;
413 onFailure: function(r) {
419 Tag.prototype = new Pager();
420 Tag.prototype.constructor = Tag;
422 Tag.prototype.show = function() {
423 var ctype = {ref: '@', tag: '#'}[this.type];
425 $$('[name=section]').each(function(v) {
426 v.update(' about ' + ctype + this.tag);
430 $('older_link').hide();
431 $('newer_link').hide();
434 $('usercontrols').hide();
438 // Pager for browsing subscription feeds
441 this.baseFrag = '/feed';
443 new Ajax.Request(baseURL + '/feed', {
446 username: loginStatus.username
448 onSuccess: function(r) {
449 var response = r.responseText.evalJSON();
451 var maxid = response.length - 1;
452 response.each(function(v, i) {
454 mangleRecord(v, tagRecordTemplate)
456 this.addItems(response);
457 this.pageStart = response.length - 1;
461 onFailure: function(r) {
466 Feed.prototype = new Pager();
467 Feed.prototype.constructor = Feed;
469 Feed.prototype.show = function() {
470 $$('[name=section]').each(function(v) {
471 v.update(' ' + loginStatus.username + "'s spycam");
475 $('older_link').hide();
476 $('newer_link').hide();
479 $('usercontrols').hide();
483 function postPopup() {
484 if (loginStatus.loggedIn) {
485 var post = $('post');
486 if (post.visible()) {
490 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
491 $('post.content').value = '@' + currentPager.username + ': ';
493 $('post.content').focus();
499 var username = $('signup.username').value;
500 var password = $('signup.password').value;
502 new Ajax.Request(baseURL + '/create', {
507 onSuccess: function(r) {
511 loginStatus.login(username, password);
513 onFailure: function(r) {
514 alert("Failed to create user");
519 function signup_cancel() {
524 function subscribe() {
525 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
528 username: loginStatus.username
530 onSuccess: function(r) {
531 var response = r.responseText.evalJSON();
532 if (response.status == 'success') {
533 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
534 $$('[name=user.subscribelink]').each(Element.hide);
535 $$('[name=user.unsubscribelink]').each(Element.show);
537 alert('Failed to subscribe. This is probably for the best');
540 onFailure: function(r) {
541 alert('Failed to subscribe. This is probably for the best');
546 function unsubscribe() {
547 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
550 username: loginStatus.username
552 onSuccess: function(r) {
553 var response = r.responseText.evalJSON();
554 if (response.status == 'success') {
555 alert("You come to your senses.");
556 $$('[name=user.subscribelink]').each(Element.show);
557 $$('[name=user.unsubscribelink]').each(Element.hide);
559 alert('You are unable to tear yourself away (because something failed on the server)');
562 onFailure: function(r) {
563 alert('You are unable to tear yourself away (because something failed on the server)');
568 var resizePostContentTimeout = null;
569 function resizePostContent() {
570 if (resizePostContentTimeout)
571 clearTimeout(resizePostContentTimeout);
572 resizePostContentTimeout = setTimeout(function() {
573 var c = $('post.content');
574 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
575 var m = c.value.match(/\r?\n/g);
581 c.style.height = (lines * 17) + "pt";
583 resizePostContentTimeout = null;
587 var tickerTimer = null;
588 var tickerHead, tickerTail;
590 function tickerFader(a, b, p) {
594 a.style.lineHeight = (100 * p) + '%';
596 b.style.opacity = p2;
597 b.style.lineHeight = (100 * p2) + '%';
604 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
605 tickerHead = tickerHead.nextSibling;
606 tickerTail = tickerTail.nextSibling;
607 if (tickerHead == null) {
609 loadLatest.delay(10);
613 function startTicker() {
615 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
619 // Show the first five
620 tickerHead = $('latest-posts').firstChild;
621 for (var i = 0; i < 10 && tickerHead; i++) {
623 tickerHead = tickerHead.nextSibling;
625 tickerTail = $('latest-posts').firstChild;
626 tickerTimer = setInterval(ticker, 5000);
629 function stopTicker() {
631 clearInterval(tickerTimer);
635 function loadLatest() {
636 new Ajax.Request(baseURL + '/latest.json', {
637 onSuccess: function(r) {
638 var j = r.responseText.evalJSON();
640 $('latest-tags').update();
641 j.tags.each(function(v) {
642 var a = new Element('a', {href: '/#/tag/' + v});
646 $('latest-tags').insert(a);
647 $('latest-tags').appendChild(document.createTextNode(' '));
650 $('latest-posts').update();
651 j.records.each(function(v) {
652 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
653 v.date = (new Date(v.timestamp * 1000)).toString();
654 var html = latestRecordsTemplate.evaluate(v);
655 $('latest-posts').insert(html);
662 function qlink(loc) {
665 } else if (this.href) {
666 location.hash = this.href;
675 function hashSwitch() {
678 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
680 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
681 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)$/)) {
682 currentPager = new Tag(m[1], m[2]);
684 } else if (m = location.hash.match(/^#\/feed/)) {
685 if (loginStatus.loggedIn) {
686 currentPager = new Feed();
689 location.href = baseURL;
691 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
692 if (!currentPager || currentPager.username != m[1])
693 currentPager = new User(m[1]);
695 loginStatus.update();
698 var r = parseInt(m[3]);
700 currentPager.showPageAt(r);
702 currentPager.showRecord(r);
705 currentPager.pageStart = currentPager.itemCount - 1;
706 currentPager.loadItems();
709 $$('[name=section]').each(function(v) { v.update('Welcome') });
713 $('newer_link').hide();
714 $('older_link').hide();
717 $('usercontrols').hide();
723 function hashCheck() {
724 if (location.hash != lastHash) {
725 lastHash = location.hash;
732 loginStatus = new LoginStatus();
734 lastHash = location.hash;
737 setInterval(hashCheck, 250);
739 document.body.observe('keyup', function(event) {
740 if (event.shiftKey && event.keyCode == '32') {
745 $('post.content').addEventListener('keyup', function(event) {
746 event.stopPropagation();