(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 deferredFbInvite = null;
        var facebookHelper = null;
        var sendingEmails = false

        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 createFbInvite() {

            if(deferredFbInvite == null || (typeof(deferredFbInvite.isRejected)!=='undefined' && deferredFbInvite.isRejected())) {
                deferredFbInvite = rest.createFbInviteUrl();
            }

            return deferredFbInvite;
        }

        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', sendEmails);
                $('#btn-next-invitation').on('click', clickNext);
                $('#invitation-dialog input[name=email-filter]').on('input', onFilterChange);
            }
            else {
                $('#btn-send-invitation').off('click', sendEmails);
                $('#btn-next-invitation').off('click', clickNext);
                $('#invitation-dialog input[name=email-filter]').off('input', onFilterChange);
            }
        }

        function invalidEmails(emails) {
            var badEmails = [];
            emails.map(function(email) {
                if (!( /(.+)@(.+){2,}\.(.+){2,}/.test(email) )){
                    var ee = email.replace(/ /g,'');
                    if (0 < ee.length) badEmails.push(ee);
                }
            });
            return badEmails;
        }

        // send invitations one after another, so as not to 'spam' the server very heavily.
        // this should be a bulk call, clearly
        function sendEmails(e) {
            if(sendingEmails) {
                return;
            }
            var $button = $(e.target)
            var emails = $('#txt-emails').val().split(',');
            if(emails.length > 0) {
                var max_email = <%= Rails.application.config.max_email_invites_per_request %>;
                if (max_email < emails.length) {
                  app.notifyAlert('Too many emails', 'You can send up to '+max_email.toString()+' email invites.  You have '+emails.length.toString());
                  return;
                }
                var invalids = invalidEmails(emails);
                if (0 < invalids.length) {
                  app.notifyAlert('Invalid emails', 'Please confirm email addresses');
                } else {
                  sendingEmails = true
                  $button.addClass("disabled")
                  rest.createEmailInvitations(emails, $('#txt-message').val())
                  .fail(function(jqXHR) {
                    app.notifyServerError(jqXHR, 'Unable to Invite Users');
                    app.layout.closeDialog('inviteUsers');
                    sendingEmails = false
                    $button.removeClass("disabled")
                  })
                  .done(function() {
                    app.notifyAlert('Invites sent', 'You sent '+emails.length.toString()+' email invites');
                    app.layout.closeDialog('inviteUsers');
                    sendingEmails = false
                    $button.removeClass("disabled")
                  });
                  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

        function handleFbStateChange(response) {
            // if the UI needs to be updated based on the status of facebook, here's the place to do it
        }

        function showFeedDialog() {

            createFbInvite()
                .done(function(fbInviteResponse) {
                    var signupUrl = fbInviteResponse["signup_url"];

                    var obj = {
                        method: 'feed',
                        link: signupUrl,
                        picture: 'https://www.jamkazam.com/assets/web/logo-256.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: signupUrl }]
                    };
                    logger.debug("facebook feed options:", obj);
                    function fbFeedDialogCallback(response) {
                        //logger.debug("feedback dialog closed: " + response['post_id'])
                        if (response && response['post_id']) {
                            context.JK.GA.trackServiceInvitations(context.JK.GA.InvitationTypes.facebook, 1);
                        }
                    }
                    FB.ui(obj, fbFeedDialogCallback);
                })
                .fail(app.ajaxError)

        }

        function showFacebookDialog(evt) {
            if (!(evt === undefined)) evt.stopPropagation();
            showFeedDialog();
        }

        // END FB handlers
        //////////////


        function clearTextFields() {
          $('#txt-emails').val('').removeData('google_invite_count');
          $('#txt-message').val('');
        }

        function beforeShow() {
            sendingEmails = false
            registerEvents(true);

            $('#invitation-dialog input[name=email-filter]').val('');
        }

        function afterHide() {
            registerEvents(false);
        }

        function initialize(_facebookHelper){
            facebookHelper = _facebookHelper;

            var dialogBindings = {
                'beforeShow' : beforeShow,
                'afterHide': afterHide
            };

            app.bindDialog('inviteUsers', dialogBindings);

            facebookHelper.deferredLoginStatus().done(function(response) { handleFbStateChange(response); });
        };

        this.initialize = initialize;
        this.showEmailDialog = showEmailDialog;
        this.showGoogleDialog = showGoogleDialog;
        this.showFacebookDialog = showFacebookDialog;
    }

  return this;
})(window,jQuery);
