jam-cloud/web/app/assets/javascripts/invitationDialog.js

301 lines
11 KiB
JavaScript

(function(context,$) {
"use strict";
context.JK = context.JK || {};
context.JK.InvitationDialog = function(app) {
var logger = context.JK.logger;
var rest = context.JK.Rest();
var waitForUserToStopTypingTimer;
var sendingEmail = false;
var fbInviteURL_ = null;
function trackMetrics(emails, googleInviteCount) {
var allInvitations = emails.length; // all email invites, regardless of how they got in the form
var emailInvitations = allInvitations - (googleInviteCount ? googleInviteCount : 0); // take out google invites
context.JK.GA.trackServiceInvitations(context.JK.GA.InvitationTypes.email, emailInvitations);
if (googleInviteCount) {
context.JK.GA.trackServiceInvitations(context.JK.GA.InvitationTypes.google, googleInviteCount);
}
}
function filterInvitations() {
waitForUserToStopTypingTimer = null;
var filter = $('#invitation-dialog input[name=email-filter]').val();
var showAll = true;
if(filter.length > 1) {
showAll = false;
}
$('#invitation-checkboxes').children().each(function (index, node) {
var input = $(node).find('input');
if(showAll) {
$(node).show()
}
else {
var email = input.attr('data-email');
if(email.toLowerCase().indexOf(filter.toLowerCase()) > -1) {
$(node).show()
}
else {
if(!input.is(':checked')) {
$(node).hide()
}
}
}
});
}
function onFilterChange() {
if(waitForUserToStopTypingTimer) {
clearTimeout(waitForUserToStopTypingTimer);
}
waitForUserToStopTypingTimer = setTimeout(filterInvitations, 300);
}
function registerEvents(onOff) {
if(onOff) {
$('#btn-send-invitation').on('click', sendEmail);
$('#btn-next-invitation').on('click', clickNext);
$('#invitation-dialog input[name=email-filter]').on('input', onFilterChange);
}
else {
$('#btn-send-invitation').off('click', sendEmail);
$('#btn-next-invitation').off('click', clickNext);
$('#invitation-dialog input[name=email-filter]').off('input', onFilterChange);
}
}
function sendInvitation(i, emails) {
rest.createInvitation($.trim(emails[i]), $('#txt-message').val())
.always(function() {
if(i < emails.length - 1) {
sendInvitation(i + 1, emails);
}
});
}
// send invitations one after another, so as not to 'spam' the server very heavily.
// this should be a bulk call, clearly
function sendEmail(e) {
if(!sendingEmail) {
sendingEmail = true;
var emails = $('#txt-emails').val().split(',');
if(emails.length > 0) {
sendInvitation(0, emails);
}
trackMetrics(emails, $('#txt-emails').data('google_invite_count'));
}
}
function clickNext() {
$('#invitation-textarea-container').show();
$('#invitation-checkbox-container').hide();
$('#btn-send-invitation').show();
$('#btn-next-invitation').hide();
}
function showEmailDialog() {
$('#invitation-dialog').show();
$('#invitation-textarea-container').show();
$('#invitation-checkbox-container').hide();
$('#btn-send-invitation').show();
$('#btn-next-invitation').hide();
clearTextFields();
app.layout.showDialog('inviteUsers')
}
function showGoogleDialog() {
$('#invitation-dialog').show();
$('#invitation-textarea-container').hide();
$('#invitation-checkbox-container').show();
$('#btn-send-invitation').hide();
$('#btn-next-invitation').show();
clearTextFields();
app.layout.showDialog('inviteUsers')
$('#invitation-checkboxes').html('<div style="text-align: center; margin-top: 100px;">Loading your contacts...</div>');
window._oauth_callback = function() {
window._oauth_win.close();
window._oauth_win = null;
window._oauth_callback = null;
$.ajax({
type: "GET",
url: "/gmail_contacts",
success: function(response) {
$('#invitation-checkboxes').html('');
for (var i in response) {
$('#invitation-checkboxes').append("<label><input type='checkbox' class='invitation-checkbox' data-email='" + response[i] + "' /> " + response[i] + "</label>");
}
$('.invitation-checkbox').change(function() {
var checkedBoxes = $('.invitation-checkbox:checkbox:checked');
var emails = '';
for (var i = 0; i < checkedBoxes.length; i++) {
emails += $(checkedBoxes[i]).data('email') + ', ';
}
emails = emails.replace(/, $/, '');
// track how many of these came from google
$('#txt-emails').val(emails).data('google_invite_count', checkedBoxes.length);
});
},
error: function() {
$('#invitation-checkboxes').html("Load failed!");
}
});
};
window._oauth_win = window.open("/auth/google_login", "_blank", "height=500,width=500,menubar=no,resizable=no,status=no");
}
//////////////
// FB handlers
// Additional initialization code such as adding Event Listeners goes here
function handle_fblogin_response(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
window.fb_logged_in_state = "connected";
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
// TODO: popup authorization dialog
window.fb_logged_in_state = "not_authorized";
}
else {
// the user isn't logged in to Facebook.
window.fb_logged_in_state = "not_logged_in";
}
}
this.fb_login = function() {
FB.login(function(response) {
handle_fblogin_response(response);
}, {scope:'publish_stream'});
}
function fbInviteURL() {
if (fbInviteURL_ === null) {
$.ajax({
type: "GET",
async: false,
url: '/api/invited_users/facebook',
success: function(response) {
fbInviteURL_ = response['signup_url'];
},
error: app.ajaxError
});
}
return fbInviteURL_;
}
function show_feed_dialog() {
var obj = {
method: 'feed',
link: fbInviteURL(),
picture: 'http://jamkazam.com/assets/logo.png',
name: 'Join me on JamKazam',
caption: 'Play live music in real-time sessions with others over the Internet, as if in the same room.',
description: '',
actions: [{ name: 'Signup', link: fbInviteURL() }]
};
function fbFeedDialogCallback(response) {
//console.log("feedback dialog closed: " + response['post_id'])
if (response['post_id']) {
context.JK.GA.trackServiceInvitations(context.JK.GA.InvitationTypes.facebook, 1);
}
}
FB.ui(obj, fbFeedDialogCallback);
}
function showFacebookDialog(evt) {
if (!(evt === undefined)) evt.stopPropagation();
var fb_state = window.fb_logged_in_state;
if (fb_state == "connected") {
show_feed_dialog();
} else if (fb_state == "not_authorized") {
this.fb_login();
} else {
this.fb_login();
}
}
function callFB(fbAppID){
var fbAppID_ = fbAppID;
window.fbAsyncInit = function() {
FB.init({
appId : fbAppID_,
// channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html',
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow server to access the session?
xfbml : true, // parse XFBML tags on this page?
oauth : true, // enable OAuth 2.0
});
// listen to see if the user is known/logged in
FB.getLoginStatus(function(response) {
handle_fblogin_response(response);
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
}
// END FB handlers
//////////////
function clearTextFields() {
$('#txt-emails').val('').removeData('google_invite_count');
$('#txt-message').val('');
}
function beforeShow() {
sendingEmail = false;
registerEvents(true);
$('#invitation-dialog input[name=email-filter]').val('');
}
function afterHide() {
registerEvents(false);
}
function initialize(fbAppID){
var dialogBindings = {
'beforeShow' : beforeShow,
'afterHide': afterHide
};
app.bindDialog('inviteUsers', dialogBindings);
callFB(fbAppID);
};
this.initialize = initialize;
this.showEmailDialog = showEmailDialog;
this.showGoogleDialog = showGoogleDialog;
this.showFacebookDialog = showFacebookDialog;
}
return this;
})(window,jQuery);