(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;

        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('keyup', onFilterChange);
            }
        }

        function sendEmail() {
          var emails = [];
          emails = $('#txt-emails').val().split(',');

          for (var i=0; i < emails.length; i++) {
            rest.createInvitation($.trim(emails[i]), $('#txt-message').val())
              .done(function() {

              });
          }

          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");
        }

        function showFacebookDialog() {
            /*
             $('#invitation-textarea-container').hide();
             $('#invitation-checkbox-container').show();
             $('#btn-send-invitation').hide();
             $('#btn-next-invitation').show();
             invitationDialog.showDialog();
             $('#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(/, $/, '');
                 $('#txt-emails').val(emails);
                 });
                 },
                 error: function() {
                 $('#invitation-checkboxes').html("Load failed");
                 }
                 });
                 */
            };
            window._oauth_win = window.open("/auth/facebook_login", "_blank", "height=500,width=500,menubar=no,resizable=no,status=no");
        }

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

        function beforeShow() {
            registerEvents(true);

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

        function afterHide() {
            registerEvents(false);
        }

        function initialize(){
            var dialogBindings = {
                'beforeShow' : beforeShow,
                'afterHide': afterHide
            };

            app.bindDialog('inviteUsers', dialogBindings);
        };


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

  return this;
})(window,jQuery);