dojo.provide('xn.widget.video.privacy.InviteCustomizer');

xn.widget.video.privacy.InviteCustomizer = {

    execute: function() {
        dojo.require("ning._.social");
        dojo.event.connect('around', ning._.social, 'sendMessage', dojo.lang.nameAnonFunc(function(invocation) {
            if (! xn.widget.video.privacy.InviteCustomizer.isInvite(invocation)) { return invocation.proceed(); }
            if (invocation.args[0].fromInviteCustomizer) { return invocation.proceed(); }
            var errorHandler = invocation.args[0].error ? invocation.args[0].error : function(errors) { alert(errors.errors[0].error); };
            // Check number of recipients, even if such a check is done elsewhere, as InviteController.php places a limit on the number
            // of recipients (50); moreover, the check in sendMessage() will not work as we will call it once per recipient  [Jon Aquino 2006-06-07]
            if (invocation.args[0].recipient.length > 50) {
                errorHandler({errors: [{error: 'The maximum number of recipients is 50.'}]});
                return;
            }

            var recipientScreenNamesAndEmails = dojo.lang.map(invocation.args[0].recipient, function(recipient) {
                return recipient.to || recipient.name || recipient;
            });
            dojo.lang.forEach(dojo.widget.manager.byType('VideoPrivacyPanel'), function(privacyPanel) {
                privacyPanel.addInvitees(recipientScreenNamesAndEmails);
            });

            dojo.io.bind({
                url: '/index.php/main/privacy/generateInviteKeys',
                method: 'post',
                preventCache: true,
                content: { recipients: recipientScreenNamesAndEmails.join(';') },
                mimetype: 'text/javascript',
                load: function(type, data, event){
                    if ('errorMessage' in data && data.errorMessage.indexOf('Not allowed to send invites') > -1) {
                        errorHandler({errors: [{error: 'The site owner has restricted who can send invites to this site - sorry about that!'}]});
                        return;
                    }
                    // slice() makes a copy of the array  [Jon Aquino 2006-09-20]
                    var recipients = invocation.args[0].recipient.slice();
                    var processNextRecipient = function() {
                        if (recipients.length == 0) {
                            if (invocation.args[0].success) { invocation.args[0].success(); }
                            return;
                        }
                        var newUrl = invocation.args[0].url + '?from_invite=yes&key=' + data.inviteKeys.pop();
                        ning._.social.sendMessage({
                            recipient: recipients.pop(),
                            subject: invocation.args[0].subject,
                            body: xn.widget.video.privacy.InviteCustomizer.replaceLast(invocation.args[0].url, newUrl, invocation.args[0].body.replace()),
                            url: newUrl,
                            // Don't save a copy 50 times  [Jon Aquino 2006-06-06]
                            saveACopy: invocation.args[0].saveACopy && invocation.args[0].recipient.length == 1,
                            success: arguments.callee,
                            error: invocation.args[0].error,
                            fromInviteCustomizer: true
                        });
                    }
                    processNextRecipient();
                }
            });
        }, dj_global));
    },

   isInvite: function(invocation) {
       return invocation.args[0].url == ning.CurrentApp.url;
   },

   replaceLast: function(search, replace, subject) {
       return xn.widget.video.privacy.InviteCustomizer.reverse(xn.widget.video.privacy.InviteCustomizer.reverse(subject).replace(xn.widget.video.privacy.InviteCustomizer.reverse(search), xn.widget.video.privacy.InviteCustomizer.reverse(replace)));
   },

   /**
    * From "Q1325 Is there any way to reverse a string?", http://www.irt.org/script/1325.htm
    */
    reverse: function(str) {
      if (!str) return '';
      var revstr='';
      for (i = str.length-1; i>=0; i--)
          revstr+=str.charAt(i)
      return revstr;
   }

}
ning.Bar.whenLoaded(function() {
    xn.widget.video.privacy.InviteCustomizer.execute();
});