This repository has been archived by the owner on Aug 4, 2019. It is now read-only.
/
setup.js
585 lines (517 loc) · 21 KB
/
setup.js
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/* -------------------- JQUERY EXTENSIONS ----------------------- */
// Detect if an input/textarea has focus.
// Usage:
// if ($("...").is(":focus")) {
// ...
// }
jQuery.extend(jQuery.expr[':'], {
focus: function(element) {
return element === document.activeElement;
}
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", readCookie('_xsrf'));
}
}
});
/* ---------------- JEDITABLE - CUSTOM TEXTAREA WITH AUTOGROW ----------------- */
$.editable.addInputType('autogrow', {
element: function(settings, original) {
var textarea = $('<textarea />');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else {
textarea.width(settings.width);
}
$(this).append(textarea);
return(textarea);
},
plugin: function(settings, original) {
var elemId = $(this).parent().attr('id');
var width;
switch(elemId) {
case 'curPlaylistTitle':
width = 380;
break;
case 'curPlaylistDesc':
width = 460;
break;
default:
width = $(this).width();
break;
}
$('textarea', this).width(width).autogrow(settings.autogrow);
}
});
/* --------------------------- SETUP FUNCTIONS --------------------------- */
// Set up keyboard shortcuts in a cross-browser manner
// Tested in Firefox, Chrome, Safari.
// Keyboard events are a mess: http://www.quirksmode.org/js/keys.html
function setupKeyboardShortcuts() {
// Handle the display of Keyboard shortcuts colorbox
$('a[href="#helpBox"]').click(function(e) {
e.preventDefault();
$.get('/partial/colorbox_help.html').success(function(markup) {
$.colorbox($.extend({
html: markup,
open: true
}, appSettings.colorbox));
});
});
// Handle the actual keyboard shortcuts
$('input, textarea').live('focus', function(event) {
keyEvents = false;
});
$('input, textarea').live('blur', function(event) {
keyEvents = true;
});
$(document).bind('cbox_open', function() {
colorboxOpen = true;
});
$(document).bind('cbox_closed', function() {
colorboxOpen = false;
});
$(window).keydown(function(event) {
var k = event.which;
var pressed1 = true;
var pressed2 = true;
// Disablable events
if (keyEvents && !event.altKey && !event.ctrlKey && !event.metaKey) {
switch(k) {
// Playback control
case 39: case 40: // down, right
player.playNextSong(true);
break;
case 37: case 38: // up, left
player.playPrevSong(true);
break;
case 32: // space
player.playPause();
break;
case 187: case 61: // +, + on Fx
player.increaseVolume();
break;
case 189: case 109: // -, - on Fx
player.decreaseVolume();
break;
case 86: // v
player.toggleVideo();
break;
case 83: // s
player.toggleShuffle();
break;
case 82: // r
player.toggleRepeat();
break;
// Playlist editing
case 74: // j
player.moveCurSongDown();
break;
case 75: // k
player.moveCurSongUp();
break;
// Navigation
case 78: // n
$('#navNewPlaylist').click();
break;
case 70: // f
$('#navSearch').trigger('click');
break;
case 191: // ?
$('#navShortcuts').trigger('click');
break;
// Fun
case 76: // l
if ($('#playlist .playing').length) {
player.highlightSong('.playing', '#playlistDiv');
}
break;
case 66: // b
showHideUI();
break;
case 65: // a
if (!model.playlist || !model.playlist.songs ||
!model.playlist.songs.length) {
return;
}
var song = model.playlist.songs[player.songIndex];
this.tts(cleanSongTitle(song.t)+', by '+song.a);
break;
default:
pressed1 = false;
break;
}
} else {
pressed1 = false;
}
// Non-disablable events
// These keyboard events will always get captured (even when textboxes are focused)
switch (k) {
case 27: // escape
if (colorboxOpen) {
return;
}
if (browser.viewStack.length > 1) {
browser.pop();
}
break;
default:
pressed2 = false;
break;
}
// If we executed a keyboard shortcut, prevent the browser default event from happening
if (pressed1 || pressed2) {
event.preventDefault();
}
});
}
function setupFBML() {
window.fbAsyncInit = function() {
FB.init({
appId : appSettings.fbAppId, // App ID
channelUrl : '//'+window.location.host+'/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}
function setupUploader(formElem) {
$(formElem).fileUpload({
url: '/upload',
onProgress: function (event, files, index, xhr, handler) { }, // TODO: Show upload progress
onLoad: function (event, files, index, xhr, handler) {
var json;
if (typeof xhr.responseText !== undefined) {
json = $.parseJSON(xhr.responseText);
} else {
// Instead of an XHR object, an iframe is used for legacy browsers:
json = $.parseJSON(xhr.contents().text());
}
onNewPlaylistResponse(json);
},
initUpload: function (event, files, index, xhr, handler, callBack) {
// Don't perform an upload immediately.
// We call callBack() once the user submits the form.
$(formElem).data('callBack', callBack);
// Update UI to show that file is ready to be uploaded
$('#dragDrop').text(files[index].name);
$('.file_upload')
.addClass('dropped')
.removeClass('drag')
.removeClass('documentDrag');
},
onError: function() {
showErrors({'': 'Something went wrong. Try refreshing the page.'});
$(formElem).find('input[type="submit"], button').removeAttr('disabled');
},
onDragOver: function() {
$('.file_upload').addClass('drag');
},
onDragLeave: function() {
$('.file_upload').removeClass('drag');
}
});
// Improve UI for clients without draganddrop support.
if(!Modernizr.draganddrop) {
$('#normalUpload span').contents().first().remove(); // Remove the "Or, " text
$('#normalUpload span').contents().last().remove(); // Remove the ending "."
// Turn upload link into button
$('#normalUpload span').contents().first()
.addClass('blue large awesome')
.css({'text-transform': 'capitalize'});
}
}
function setupNewPlaylist() {
$('a[href="#new"]').click(function(e) {
e.preventDefault();
$.get('/partial/colorbox_newPlaylist.html').success(function(markup) {
$.colorbox($.extend({
html: markup,
open: true,
onComplete: function() {
var form = $('#newPlaylistForm');
// Add _xsrf token to form
$('body > input[name="_xsrf"]').clone().appendTo(form);
$('input[name=title]', form).focus();
// Show playlist upload controls
$('#showPlaylistUpload').click(function() {
$('#playlistUpload').show();
$('#showPlaylistUpload').hide();
form.find('.colorboxSubmitButtons em').hide();
$.colorbox.resize();
});
// Auto-resizing textarea
$('textarea', form)
.autogrow($.extend({}, appSettings.autogrow,
{onResize: function(elem) {
// Ensure that elem had focus before re-setting the focus
var elemHadFocus = $(elem).is(':focus');
if (elemHadFocus) {
$.colorbox.resize();
$(elem).focus();
}
},
lineHeight: 18
})
);
// Setup uploader
setupUploader('#newPlaylistForm');
// Form submit event handler
form.submit(function(e) {
e.preventDefault();
$('#submitNewPlaylist').attr('disabled', 'disabled');
// Use the jQuery File Upload plugin to submit the new playlist.
// We tack on the form parameters to the request that the plugin sends.
if (form.data('callBack')) {
form.data('callBack')();
} else {
// No file selected, do normal xhr.
$.ajax('/upload', {
type: 'POST',
data: formToDictionary(form),
dataType: 'json'
})
.success(function(data, textStatus, jqXHR) {
onNewPlaylistResponse(data);
})
.error(function(data, textStatus, jqXHR) {
onNewPlaylistResponse(null);
});
}
});
}
}, appSettings.colorbox));
});
});
}
function onNewPlaylistResponse(data) {
if (data && data.success) {
var playlist = data.result;
player.loadPlaylist(playlist);
$.colorbox.close();
} else {
var errors = data && data.errors;
if (errors) {
showErrors(errors);
} else {
showErrors({'': 'Something went wrong. Try refreshing the page.'});
}
$('#submitNewPlaylist').removeAttr('disabled', 'disabled');
}
// TODO KLUDGE: Properly load the PlaylistView.
window.location = playlist.url;
}
function setupLogin() {
$('a[href="#login"]').click(function(e) {
e.preventDefault();
$.get('/partial/colorbox_login.html').success(function(markup) {
$.colorbox($.extend({
html: markup,
open: true,
onComplete: function() {
var form = $('#login');
$('input[name=email]', form).focus();
// Sign up link event handler
$('#loginSignup a').click(function() {
$('#navSignup').click();
});
form.submit(function(e) {
e.preventDefault();
$('#submitLogin').attr('disabled', 'disabled');
instantfm.login({
params: formToDictionary(form),
onSuccess: function(response) {
// everything is ok. (server returned true)
if (response && response.success) {
var session = response.result;
setSession(session);
tts('Hello, '+session.user.name.split(' ', 1));
$.colorbox.close();
log('Login succeeded.');
// If we session-own the current playlist, promote it
// client-side so we user-own it too.
if (model.playlist && model.session && model.playlist.session_id == model.session.id) {
model.playlist.user = model.session.user;
}
// server-side validation failed.
} else if (response && response.errors) {
showErrors(response.errors);
$.colorbox.resize();
$('input[name=password]', form).focus();
}
$('#submitLogin').removeAttr('disabled');
},
onException: function() {
showErrors({'': 'Something went wrong. Try refreshing the page.'});
$('#submitLogin').removeAttr('disabled');
},
});
});
}
}, appSettings.colorbox));
});
});
}
function setupLogout() {
$('a[href="#logout"]').click(function(event) {
event.preventDefault();
instantfm.logout({
onSuccess: function(newSession) { setSession(newSession); }
});
$('html').removeClass('loggedIn');
$('html').addClass('loggedOut');
});
}
function setupSignup() {
$('a[href="#signUp"]').click(function(e) {
e.preventDefault();
$.get('/partial/colorbox_signup.html').success(function(markup) {
$.colorbox($.extend({
html: markup,
open: true,
width: 450,
onComplete: function() {
var form = $('#fbSignupForm');
// Facepile
// BUGFIX: I think this causes "Uncaught TypeError: Cannot read property 'offsetWidth' of null"
// FB.XFBML.parse($('#fbFacepile').get(0), function(response) {
// // If none of the user's friends have connected to Instant.fm,
// // then lets fallback to showing the users who have liked our
// // page (including non-friends). We show the like box, but
// // use CSS trickery to just show the faces.
// window.setTimeout(function() {
// if ($('#fbFacepile').height() < 20) {
// $('#fbFacepile')
// .empty()
// .addClass('like')
// .append('<fb:like-box href="'+appSettings.fbPageURL+'" width="410" show_faces="true" stream="false" header="false"></fb:like-box>');
// FB.XFBML.parse($('#fbFacepile').get(0));
// }
// $.colorbox.resize();
// }, 1000);
// });
// Connect button
$('#fbConnectButton').click(onFBConnect);
}
}, appSettings.colorbox));
});
});
}
function onFBConnect(event) {
var form = $('#fbSignupForm');
FB.login(function(login_response) {
if (!login_response.authResponse) {
log('FB login failed.'); // user cancelled login
return;
}
// Check that they're not already registered
FB.api('/me', function (response) {
var fb_id = response.id,
auth_token = FB.getAuthResponse()['accessToken'];
instantfm.is_registered_fbid({
params: [fb_id],
onSuccess: function(is_registered) {
if (is_registered) {
form.hide();
showErrors({'': 'This Facebook user is already registered on Instant.fm. Try logging in instead.'});
return;
}
}
});
// Populate Signup Step 2 form
$('input[name=name]', form).val(response.name);
$('input[name=email]', form).val(response.email);
$('#fbProfileImage').css('background-image', 'url("http://graph.facebook.com/' + response.id + '/picture?type=square")');
$('#signupStep1').fadeOut(function() {
$('#signupBox > header > .subtitle').text('(2 of 2)');
$('#signupStep2').fadeIn(function() {
$.colorbox.resize();
$('input[name=password]', form).focus();
});
});
// Setup event handlers for Signup Step 2 form
form.submit(function(e) {
e.preventDefault();
$('#submitFbSignupForm').attr('disabled', 'disabled');
params = formToDictionary(form);
params["auth_token"] = auth_token;
params["fb_id"] = parseInt(fb_id);
instantfm.signup_with_fbid({
params: params,
onSuccess: function(response) {
if (response && response.success) {
session = response.result;
setSession(session);
$.colorbox.close();
log("Registration posted successfully.");
} else if (response && response.errors) {
// server-side validation failed.
showErrors(response.errors);
$.colorbox.resize();
}
$('#submitFbSignupForm').removeAttr('disabled');
},
onException: function() {
log('Error posting form ;_;');
$('#submitFbSignupForm').removeAttr('disabled');
},
});
});
});
}, {perms:'email'});
}
function setupRpc() {
var methods = ['update_songlist', 'update_title', 'update_description',
'is_registered_fbid', 'set_image_from_url', 'login', 'logout',
'new_playlist', 'signup_with_fbid', 'get_playlists_for_user',
'delete_playlist'];
instantfm = new rpc.ServiceProxy("/json-rpc?_xsrf=" + readCookie('_xsrf'), {
"sanitize": true,
"protocol": 'JSON-RPC',
"methods": methods,
});
}
function setupDeletePlaylist() {
$('a.delete').live('click', function(event) {
event.preventDefault();
id = $(this).data('id');
var confirmed = window.confirm("Really delete?")
if (confirmed) {
instantfm.delete_playlist({
params: [id],
onSuccess: function(response) {
log("Deleted playlist " + id);
$('div.playlist[data-id="' + id + '"]').remove();
}
});
}
})
}
function showErrors(errors) {
if (!errors) {
return;
}
var $errors = $('.colorbox .errors').empty();
$.each(errors, function(field, msg) {
var $p = $('<p></p>').text(field+' '+msg);
$errors.append($p);
});
$.colorbox.resize();
}