User:Sross (Public Policy)/ambassadorwikilove.js

Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
// code prevented from executing due to [[phab:T72470]]
if (false) {
  // Script depends on jQuery dialog widget
  mw.loader.using( 'jquery.ui', function() {
    // Construct object (to prevent namespace conflicts)
    wikiLove = {

      displayProgress: function( form, message ) {
        $('#'+form+' div').hide(); // remove everything else from the dialog box
        $('#'+form).append ( $('<div style="text-align:center;margin:3em 0;"></div>').html( message+'<br/><img src="http://upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />' ) );
      },
      
      displayError: function( form, error ) {
        $('#'+form+' div').hide(); // remove everything else from the dialog box
        $('#'+form).append ( $('<div style="color:#990000;margin-top:0.4em;"></div>').html( 'Error: '+error ) );
      },
      
      getEditToken: function() {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=query&prop=info&intoken=edit&titles=Main%20Page&indexpageids&format=json',
          dataType: 'json',
          success: function( data ) {
            if ( data.query.pages && data.query.pageids ) {
              var pageid = data.query.pageids[0];
              wikiLove.editToken = data.query.pages[pageid].edittoken;
            }
          }
        });
      },
      
      getEmailable: function() {
        // Test to see if the 'E-mail this user' link exists
        wikiLove.emailable = $('#t-emailuser').length ? true : false;
      },
      
      editPage: function( form, summary, template ) {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=edit&title='+encodeURIComponent(mw.config.get('wgPageName'))+'&section=new&summary='+encodeURIComponent(summary)+'&text='+encodeURIComponent(template)+'&format=json&token='+encodeURIComponent(wikiLove.editToken),
          dataType: 'json',
          type: 'POST',
          success: function( data ) {
            if ( data.edit.result == "Success" ) {
              window.location.reload();
            } else {
              wikiLove.displayError( form, 'Unknown result from API.' );
            }
          },
          error: function( xhr ) {
            wikiLove.displayError( form, 'Edit failed.' );
            //console.debug( xhr.responseText );
          }
        });
      },
      
      sendEmail: function( form, subject, text ) {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=emailuser&target='+encodeURIComponent(wgTitle)+'&subject='+encodeURIComponent(subject)+'&text='+encodeURIComponent(text)+'&format=json&token='+encodeURIComponent(wikiLove.editToken),
          dataType: 'json',
          type: 'POST'
        });
      },

      launchDialog: function( interface, emailOption ) {
        // If user is emailable, add email checkbox to forms that request it
        if ( emailOption && typeof wikiLove.emailable !== 'undefined' && wikiLove.emailable ) {
          if ( typeof interface.data('emailCheckboxAppended') == 'undefined' ) {
            interface.append( $('<div style="margin-top:0.4em;"></div>').html('<input type="checkbox" name="notify"/> Notify user by email') );
            interface.data('emailCheckboxAppended', true);
          }
        }
        // Open the dialog box
        interface.dialog('open');
        // Retrieve the edit token so it will be available when the form is submitted
        wikiLove.getEditToken();
      },
      
      initialize: function() {

        // Function to make a list of images selectable
        $.fn.selectItem = function() {
          return this.each(function() {
            var containerId = this.id;
            var customId = 0;
            $('#'+containerId+' img').css('border', '8px solid transparent');
            $('#'+containerId+' img').each(function() {
              if (this.id == '') {
                this.id = 'select_img_' + customId;
                customId++;
              }
              $('#'+this.id).click(function() {
                  $('#'+containerId+'Selected').val(this.title);
                  $('#'+containerId+' img').css('border', '8px solid transparent');
                  $('#'+this.id).css('border', '8px solid #AED0EA');
              })
            });
          });
        };
      
        // List of all available awards
        var $awardList = [
          'The Original Barnstar',
          'Wikipedia Ambassador Barnstar',
          'The WikiPen'
        ];
        
        // Define award interface
        $wlAwards = $('<div id="awardForm" style="position:relative;"></div>')
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Select award: ' ).append( $('<select id="awardSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a message (without a signature):<br/>' ).append( $('<textarea name="message" id="awardMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
          .dialog({
            width: 500,
            autoOpen: false,
            title: 'Give an award',
            modal: true,
            buttons: { "Give award": function() { 
              $(this).dialog({buttons:{}});
              if ( typeof wikiLove.editToken !== 'undefined' ) {
                if ( $('#awardForm input[name="notify"]').attr('checked') ) {
                  // Send email
                  wikiLove.sendEmail( 'awardForm', 'You\'ve been given an award on Wikipedia!', 'Hello '+wgTitle+'!\n\nI just gave you an award on your English Wikipedia talk page.' );
                }
                // Perform edit to page
                wikiLove.displayProgress( 'awardForm', 'Adding award to page...' );
                var template = '{{subst:'+$('#awardSelect').val()+'|'+$('#awardMessage').val() +' ~~~~}}';
                wikiLove.editPage( 'awardForm', 'Award', template );
              } else {
                wikiLove.displayError( 'awardForm', 'Could not retrieve edit token.' );
              }
            }}
          });
    
        // Populate award selection list
        $.each( $awardList, function(index, value) { $('#awardSelect').append( $('<option></option>').val(value).html(value) ); });

        // List of message types
        var $messageList = [
          'Just a message',
          'Ambassador welcome',
        ];

        // Define message interface
        $wlMessage = $('<div id="messageForm" style="position:relative;"></div>')
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Select message or template: ' ).append( $('<select id="messageSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a message (without a signature), or leave blank for welcome template:<br/>' ).append( $('<textarea name="message" id="messageMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
          .dialog({
            width: 500,
            autoOpen: false,
            title: 'Leave a message',
            modal: true,
            buttons: { "Leave message": function() { 
              $(this).dialog({buttons:{}});
              if ( typeof wikiLove.editToken !== 'undefined' ) {
                if ( $('#messageForm input[name="notify"]').attr('checked') ) {
                  // Send email
                  wikiLove.sendEmail( 'messageForm', 'You\'ve got a message from your Wikipedia mentor!', 'Hello '+wgTitle+'!\n\nI just left you a message on your English Wikipedia talk page.' );
                }
                // Perform edit to page
                wikiLove.displayProgress( 'messageForm', 'Leaving your message...' );
                var template = '{{subst:'+$('#messageSelect').val()+'|'+$('#messageMessage').val() +' ~~~~}}';
                wikiLove.editPage( 'messageForm', 'Message', template );
              } else {
                wikiLove.displayError( 'messageForm', 'Could not retrieve edit token.' );
              }
            }}
          });
    
        // Populate award selection list
        $.each( $messageList, function(index, value) { $('#messageSelect').append( $('<option></option>').val(value).html(value) ); });
    
        // Insert new tab into page
        var menuMessage = '<li id="wl-message"><span><a onclick="wikiLove.launchDialog( $wlMessage, true ); return false;" href="#">Message</a></span></li>';
        var menuAward = '<li id="wl-award"><span><a onclick="wikiLove.launchDialog( $wlAwards, true ); return false;" href="#">Award</a></span></li>';
        var wikiLoveMenu = '<div class="vectorMenu" id="p-wikilove"><h5><span>WikiLove</span><a href="#" style="padding:0 0.4em;width:auto;"><span style="display:inline-block;height:2.5em;width:16px;margin-right:14px;background-position:0 60%;background-image:url(http://upload.wikimedia.org/wikipedia/commons/thumb/4/42/Wikipedia-Ambassador-Program-Logo.png/16px-Wikipedia-Ambassador-Program-Logo.png);background-repeat:no-repeat;">&nbsp;</span></a></h5><div class="menu"><ul>'+menuMessage+menuAward+'</ul></div></div>';
        $('#p-cactions').after(wikiLoveMenu);

      } // close initialize function

    } // close wikiLove object
    wikiLove.initialize();
    wikiLove.getEmailable();
  }) // close mw.loader
} // close if
//</nowiki>