Difference between revisions of "MediaWiki:Common.js"

From cm2.liecourt.com
(Fill database)
 
(11 intermediate revisions by 3 users not shown)
Line 5: Line 5:
 
$(document).ready(function () {
 
$(document).ready(function () {
  
  createPageTogglers = document.querySelectorAll('[data-creatpage]');
+
    createPageTogglers = document.querySelectorAll('[data-creatpage]');
  
  if(createPageTogglers && createPageTogglers.length > 0){
+
    if(createPageTogglers && createPageTogglers.length > 0){
  
    createPageTogglers.forEach(function(el){
+
        createPageTogglers.forEach(function(el){
  
      el.addEventListener(
+
            el.addEventListener(
        "click",
+
                "click",
        function () {
+
                function () {
          createPage( )
+
                    createPage( )
 +
                })
 
         })
 
         })
      })
 
  
  }
+
    }
  
 
})
 
})
  
console.log('uyfuyfuy' );
+
console.log('uyfuyfuy' );
 
var createPage = function (current_namespace, current_pagename) {
 
var createPage = function (current_namespace, current_pagename) {
  console.log("working");
+
    console.log("working");
 
+
 
  var hiddenInput = document.querySelector('#time-slot-field');
+
    var hiddenInput = document.querySelector('#time-slot-field');
 +
 
 +
    mw.loader.using(["oojs-ui-windows", 'mediawiki.widgets.DateInputWidget']).then(function () {
 +
        // Example: Using getSetupProcess() to configure a window with data passed
 +
        // at the time the window is opened.
 +
 
 +
        // Make a subclass of ProcessDialog
 +
        function PageCreateDialog(config) {
 +
            PageCreateDialog.super.call(this, config);
 +
        }
 +
        OO.inheritClass(PageCreateDialog, OO.ui.ProcessDialog);
 +
 
 +
        // Specify a name for .addWindows()
 +
        PageCreateDialog.static.name = "createPageDialog";
 +
        PageCreateDialog.static.title = "Select a Time Slot";
 +
        // Specify the static configurations: title and action set
 +
        PageCreateDialog.static.actions = [
 +
            {
 +
                flags: "primary",
 +
                label: "Continue",
 +
                action: "open",
 +
            },
 +
            {
 +
                flags: "safe",
 +
                label: "Cancel",
 +
            },
 +
        ];
 +
 
 +
        // Customize the initialize() function to add content and layouts:
 +
        PageCreateDialog.prototype.initialize = function () {
 +
            var dialol = this;
 +
            PageCreateDialog.super.prototype.initialize.call(this);
 +
            this.panel = new OO.ui.PanelLayout({
 +
                padded: true,
 +
                expanded: false,
 +
            });
 +
            this.content = new OO.ui.FieldsetLayout();
 +
 
 +
 
 +
            var date = new Date();
 +
 
 +
            // month = date.getMonth() + 1;
 +
 
 +
            this.urlInput = new mw.widgets.DateInputWidget({
 +
                value: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
 +
            });
  
  mw.loader.using(["oojs-ui-windows", 'mediawiki.widgets.DateInputWidget']).then(function () {
+
            this.field = new OO.ui.FieldLayout(this.urlInput, {
    // Example: Using getSetupProcess() to configure a window with data passed
+
                label: "Day",
    // at the time the window is opened.
+
                align: "top",
 +
            });
 +
 
 +
            var times = [];
 +
            for (var i = 10; i < 22; i++) {
 +
                var hour = i;
 +
                var pm = 'AM';
 +
                if (i > 12) {
 +
                    hour = i - 12;
 +
                    pm = 'PM';
 +
                }
 +
                times.push(
 +
                    new OO.ui.ButtonOptionWidget( {
 +
                        label:  hour + ':00' + ' - ' + hour + ':15 ' + pm
 +
                    })
 +
                );
 +
                times.push(
 +
                    new OO.ui.ButtonOptionWidget( {
 +
                        label:  hour + ':15' + ' - ' + hour + ':30 ' + pm
 +
                    })
 +
                );
 +
                times.push(
 +
                    new OO.ui.ButtonOptionWidget( {
 +
                        label:  hour + ':30' + ' - ' + hour + ':45 ' + pm
 +
                    })
 +
                );
 +
                times.push(
 +
                    new OO.ui.ButtonOptionWidget( {
 +
                        label:  hour + ':45' + ' - ' + (hour + 1) + ':00 ' + pm
 +
                    })
 +
                );
 +
            }
 +
 
 +
            this.slotSelect =  new OO.ui.ButtonSelectWidget( {
 +
                items:
 +
                times
 +
            } );
 +
 
 +
            this.slotsWrapper = new OO.ui.FieldLayout( new OO.ui.Widget( {
 +
                content: [
 +
                    new OO.ui.HorizontalLayout( {
 +
                        items: [
 +
                            this.slotSelect
 +
                        ]
 +
                    })
 +
                ]
 +
            }), {
 +
                label: "Time",
 +
                align: "top",
 +
            });
 +
 
 +
 
 +
 
 +
 
 +
            this.content.addItems([this.field, this.slotsWrapper]);
 +
            this.panel.$element.append(this.content.$element);
 +
            this.$body.append(this.panel.$element);
 +
            var that = this;
 +
            this.urlInput.on( 'change', function () {
 +
                // The value will always be a valid date or empty string, malformed input is ignored
 +
 
 +
                that.updateSlots();
 +
 
 +
            } );
 +
 
 +
        };
 +
 
 +
 
 +
        PageCreateDialog.prototype.updateSlots = function () {
 +
 
 +
            var that = this;
 +
            var date =  that.urlInput.getValue().split('-');
 +
 
 +
 
 +
            var month = date[1];
 +
            var year = date[0];
 +
            var day = date[2];
  
    // Make a subclass of ProcessDialog
 
    function PageCreateDialog(config) {
 
      PageCreateDialog.super.call(this, config);
 
    }
 
    OO.inheritClass(PageCreateDialog, OO.ui.ProcessDialog);
 
  
    // Specify a name for .addWindows()
 
    PageCreateDialog.static.name = "createPageDialog";
 
    PageCreateDialog.static.title = "Select a Time Slot";
 
    // Specify the static configurations: title and action set
 
    PageCreateDialog.static.actions = [
 
      {
 
        flags: "primary",
 
        label: "Continue",
 
        action: "open",
 
      },
 
      {
 
        flags: "safe",
 
        label: "Cancel",
 
      },
 
    ];
 
  
    // Customize the initialize() function to add content and layouts:
 
    PageCreateDialog.prototype.initialize = function () {
 
      var dialol = this;
 
      PageCreateDialog.super.prototype.initialize.call(this);
 
      this.panel = new OO.ui.PanelLayout({
 
        padded: true,
 
        expanded: false,
 
      });
 
      this.content = new OO.ui.FieldsetLayout();
 
  
     
+
            that.slotSelect.items.forEach(function(item){
      var date = new Date();
+
                item.setDisabled(false);
     
+
            })
    // month = date.getMonth() + 1;
 
     
 
      this.urlInput = new mw.widgets.DateInputWidget({
 
        value: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
 
      });
 
  
      this.field = new OO.ui.FieldLayout(this.urlInput, {
+
            var params = {
        label: "Day",
+
                action: 'ask',
        align: "top",
+
                query: '[[Slot month::' + month + ']][[Slot day::' + day + ']][[Slot year::' + year + ']]|?Slot|limit=500',
      });
+
                formatversion: 2,
     
+
                format: 'json'
      var times = [];
+
            }
      for (var i = 8; i < 20; i++) {
+
            var api = new mw.Api;
        var hour = i;
+
            api.post(params).done(function(data){
        var pm = 'AM';
+
                if (data.query.results) {
        if (i > 12) {
+
                    console.log(data.query.results)
          hour = i - 12;
+
                    Object.entries(data.query.results).forEach(function(slot){
          pm = 'PM';
+
                        var date = slot[1].printouts.Slot[0].fulltext || slot[1].printouts.Slot[0];
        }
+
                        var time = date.split('/')[1];
        times.push(
+
                        var item = that.slotSelect.getItemFromLabel(time);
        new OO.ui.ButtonOptionWidget( {
+
                        if(item){
label: hour + ':00' + ' - ' + hour + ':15 ' + pm
+
                            item.setDisabled(true);
          })
+
                        }
        );
+
                     })
      times.push(
+
                    // ["Workflow/90"].printouts.Slot[0]
        new OO.ui.ButtonOptionWidget( {
+
                }
label:  hour + ':15' + ' - ' + hour + ':30 ' + pm
+
            })
          })
+
             // ask query function here, and disbale results
        );
+
             // selectItemByLabel(label).setDisabled(true);
        times.push(
 
        new OO.ui.ButtonOptionWidget( {
 
label:  hour + ':30' + ' - ' + hour + ':45 ' + pm
 
          })
 
        );
 
        times.push(
 
        new OO.ui.ButtonOptionWidget( {
 
label:  hour + ':45' + ' - ' + (hour + 1) + ':00 ' + pm
 
          })
 
        );
 
      }
 
   
 
    this.slotSelect =  new OO.ui.ButtonSelectWidget( {
 
items:
 
  times
 
                     } );
 
     
 
    this.slotsWrapper = new OO.ui.FieldLayout( new OO.ui.Widget( {
 
content: [
 
new OO.ui.HorizontalLayout( {
 
items: [
 
              this.slotSelect
 
              ]
 
          })
 
        ]
 
        }), {
 
             label: "Time",
 
             align: "top",
 
          });
 
  
   
 
 
 
  
      this.content.addItems([this.field, this.slotsWrapper]);
 
      this.panel.$element.append(this.content.$element);
 
      this.$body.append(this.panel.$element);
 
      var that = this;
 
      this.urlInput.on( 'change', function () {
 
          // The value will always be a valid date or empty string, malformed input is ignored
 
 
 
        that.updateSlots();
 
       
 
      } );
 
     
 
    };
 
  
   
 
    PageCreateDialog.prototype.updateSlots = function () {
 
   
 
      var that = this;
 
          var date =  that.urlInput.getValue().split('-');
 
       
 
  
         var month = date[1];
+
         };
         var year = date[0];
+
         // Specify any additional functionality required by the window (disable opening an empty URL, in this case)
        var day = date[2];
 
  
       
+
        // Specify the dialog height (or don't to use the automatically generated height).
 +
        PageCreateDialog.prototype.getBodyHeight = function () {
 +
            // Note that "expanded: false" must be set in the panel's configuration for this to work.
 +
            // When working with a stack layout, you can use:
 +
            //  return this.panels.getCurrentItem().$element.outerHeight( true );
 +
            return this.panel.$element.outerHeight(true) + 200;
 +
        };
  
         
+
        // Use getSetupProcess() to set up the window with data passed to it at the time
          that.slotSelect.items.forEach(function(item){
+
        // of opening (e.g., url: 'http://www.mediawiki.org', in this example).
            item.setDisabled(false);
+
        PageCreateDialog.prototype.getSetupProcess = function (data) {
          })
+
            data = data || {};
         
+
            var nuthis = this;
          var params = {
+
            return PageCreateDialog.super.prototype.getSetupProcess
            action: 'ask',
+
                .call(this, data)
            query: '[[Slot month::' + month + ']][[Slot day::' + day + ']][[Slot year::' + year + ']]|?Slot|limit=500',
+
                .next(function () {
            formatversion: 2,
+
                    // Set up contents based on data
            format: 'json'
+
                     var val = hiddenInput.value;
          }
+
                     if (val) {
          var api = new mw.Api;
+
                        var split = val.split('/');
          api.post(params).done(function(data){
+
                        nuthis.urlInput.setValue(split[0]);
              if (data.query.results) {
+
                        nuthis.slotSelect.selectItemByLabel(split[1])
                console.log(data.query.results)
 
                Object.entries(data.query.results).forEach(function(slot){
 
                     var date = slot[1].printouts.Slot[0].fulltext || slot[1].printouts.Slot[0];
 
                     var time = date.split('/')[1];
 
                    var item = that.slotSelect.getItemFromLabel(time);
 
                    if(item){
 
                    item.setDisabled(true);
 
 
                     }
 
                     }
                })
+
                    nuthis.updateSlots();
                 // ["Workflow/90"].printouts.Slot[0]
+
 
              }
+
                 }, this);
          })
+
        };
          // ask query function here, and disbale results
+
        var boiler = "";
          // selectItemByLabel(label).setDisabled(true);
+
        // Specify processes to handle the actions.
         
+
        PageCreateDialog.prototype.getActionProcess = function (action) {
       
+
            var nuthis = this;
     
+
            if (action === "open") {
     
+
                // Create a new process to handle the action
    };
+
                return new OO.ui.Process(function () {
    // Specify any additional functionality required by the window (disable opening an empty URL, in this case)
 
  
    // Specify the dialog height (or don't to use the automatically generated height).
+
                    var day = nuthis.urlInput.getValue();
    PageCreateDialog.prototype.getBodyHeight = function () {
+
                    var time =  nuthis.slotSelect.findSelectedItem().label;
      // Note that "expanded: false" must be set in the panel's configuration for this to work.
 
      // When working with a stack layout, you can use:
 
      //  return this.panels.getCurrentItem().$element.outerHeight( true );
 
      return this.panel.$element.outerHeight(true) + 200;
 
    };
 
  
    // Use getSetupProcess() to set up the window with data passed to it at the time
+
                    console.log(day, time)
    // of opening (e.g., url: 'http://www.mediawiki.org', in this example).
+
                    hiddenInput.value = day + '/' + time;
    PageCreateDialog.prototype.getSetupProcess = function (data) {
+
                    var button = document.querySelector('#time-slot-button');
      data = data || {};
+
                    button.innerText = day + ' • ' + time;
      var nuthis = this;
+
                    return 800;
      return PageCreateDialog.super.prototype.getSetupProcess
+
                }).next(function(){
        .call(this, data)
+
                    nuthis.close({action: action});
        .next(function () {
+
                    return true;
          // Set up contents based on data
+
                })
          var val = hiddenInput.value;
+
            }
          if (val) {
+
            // Fallback to parent handler
            var split = val.split('/');
+
            return PageCreateDialog.super.prototype.getActionProcess.call(this, action);
            nuthis.urlInput.setValue(split[0]);
+
        };
            nuthis.slotSelect.selectItemByLabel(split[1])
 
          }
 
          nuthis.updateSlots();
 
       
 
          }, this);
 
    };
 
    var boiler = "";
 
    // Specify processes to handle the actions.
 
    PageCreateDialog.prototype.getActionProcess = function (action) {
 
      var nuthis = this;
 
      if (action === "open") {
 
        // Create a new process to handle the action
 
        return new OO.ui.Process(function () {
 
         
 
        var day = nuthis.urlInput.getValue();
 
        var time =  nuthis.slotSelect.findSelectedItem().label;
 
         
 
        console.log(day, time)
 
        hiddenInput.value = day + '/' + time;
 
        var button = document.querySelector('#time-slot-button');
 
        button.innerText = day + ' • ' + time;
 
        return 800;
 
        }).next(function(){
 
          nuthis.close({action: action});
 
          return true;
 
        })
 
      }
 
      // Fallback to parent handler
 
      return PageCreateDialog.super.prototype.getActionProcess.call(this, action);
 
    };
 
  
    // Use the getTeardownProcess() method to perform actions whenever the dialog is closed.
+
        // Use the getTeardownProcess() method to perform actions whenever the dialog is closed.
    // This method provides access to data passed into the window's close() method
+
        // This method provides access to data passed into the window's close() method
    // or the window manager's closeWindow() method.
+
        // or the window manager's closeWindow() method.
    PageCreateDialog.prototype.getTeardownProcess = function (data) {
+
        PageCreateDialog.prototype.getTeardownProcess = function (data) {
      return PageCreateDialog.super.prototype.getTeardownProcess
+
            return PageCreateDialog.super.prototype.getTeardownProcess
        .call(this, data)
+
                .call(this, data)
        .first(function () {
+
                .first(function () {
          // Perform any cleanup as needed
+
                    // Perform any cleanup as needed
        }, this);
+
                }, this);
    };
+
        };
  
    // Create and append a window manager.
+
        // Create and append a window manager.
    var windowManager = new OO.ui.WindowManager();
+
        var windowManager = new OO.ui.WindowManager();
    $(document.body).append(windowManager.$element);
+
        $(document.body).append(windowManager.$element);
  
    // Create a new process dialog window.
+
        // Create a new process dialog window.
    var createPageDialog = new PageCreateDialog();
+
        var createPageDialog = new PageCreateDialog();
  
    // Add the window to window manager using the addWindows() method.
+
        // Add the window to window manager using the addWindows() method.
    windowManager.addWindows([createPageDialog]);
+
        windowManager.addWindows([createPageDialog]);
  
    // Open the window!
+
        // Open the window!
    windowManager.openWindow(createPageDialog);
+
        windowManager.openWindow(createPageDialog);
  });
+
    });
 
};
 
};
  
Line 271: Line 271:
  
 
/***
 
/***
* REMOVE FILE
+
* REMOVE FILE
*
+
*
**/
+
**/
  
 
document.querySelectorAll('[data-removefile]').forEach(function(el){
 
document.querySelectorAll('[data-removefile]').forEach(function(el){
  el.addEventListener('click', function(){
+
    el.addEventListener('click', function(){
    console.log(el.dataset.removefile)
+
        console.log(el.dataset.removefile)
   
+
 
    var r = confirm("Are you sure?");
+
        var r = confirm("Are you sure?");
      if (r == true) {
+
        if (r == true) {
 
             var params = {
 
             var params = {
              action: 'delete',
+
                    action: 'delete',
              title: el.dataset.removefile,
+
                    title: el.dataset.removefile,
              format: 'json'
+
                    format: 'json'
          },
+
                },
          api = new mw.Api();
+
                api = new mw.Api();
  
          api.postWithToken( 'csrf', params ).done( function ( data ) {
+
            api.postWithToken( 'csrf', params ).done( function ( data ) {
              console.log( data );
+
                console.log( data );
              el.remove();
+
                el.remove();
          } );
+
            } );
      }  
+
        }
  })
+
    })
 
})
 
})
  
  
 
/**
 
/**
* POLLING FOR USER PAGES
+
* POLLING FOR USER PAGES
**/
+
**/
  
 
var pollWrapper = document.querySelector('[data-poll]');
 
var pollWrapper = document.querySelector('[data-poll]');
Line 317: Line 317:
 
         then = now - (delta % interval);
 
         then = now - (delta % interval);
  
     
+
 
          if(pollWrapper.dataset.poll == 'Messages'){
+
        if(pollWrapper.dataset.poll == 'Messages'){
            goPolling()
+
            goPolling()
          }else{
+
        }else{
 
             workflowPolling()
 
             workflowPolling()
          }    
+
        }
 
     }
 
     }
 
}
 
}
Line 328: Line 328:
  
  
if(pollWrapper){
+
if(pollWrapper){
  poll();
+
    poll();
}
+
}
  
  
Line 339: Line 339:
  
 
function workflowPolling(){
 
function workflowPolling(){
  var params = {
+
    var params = {
action: 'ask',
+
        action: 'ask',
 
         query: '[[Workflow::' + pollWrapper.dataset.workflow + ']]|?Modification date',
 
         query: '[[Workflow::' + pollWrapper.dataset.workflow + ']]|?Modification date',
 
         formatversion: 2,
 
         formatversion: 2,
format: 'json'
+
        format: 'json'
};
+
    };
+
 
var api = new mw.Api();
+
    var api = new mw.Api();
  
 
     api.post( params ).done( function ( data ) {
 
     api.post( params ).done( function ( data ) {
      if(data.query.results) {
+
        if(data.query.results) {
        var flows = Object.entries(data.query.results).map(function(entrie){
+
            var flows = Object.entries(data.query.results).map(function(entrie){
            return entrie[1].printouts['Modification date'][0].timestamp
+
                return entrie[1].printouts['Modification date'][0].timestamp
        })
+
            })
        if(polledWorkflows && flows.sort().join() != polledWorkflows.sort().join()){
+
            if(polledWorkflows && flows.sort().join() != polledWorkflows.sort().join()){
          console.log('found something new', flows);
+
                console.log('found something new', flows);
              console.log('polled', polledWorkflows);
+
                console.log('polled', polledWorkflows);
 
                 reloadSection()
 
                 reloadSection()
        } else {
+
            } else {
 
                 console.log('polling, but found nothing new');
 
                 console.log('polling, but found nothing new');
          }
+
            }
        polledWorkflows = flows
+
            polledWorkflows = flows
      }
+
        }
 
     })
 
     })
  
Line 372: Line 372:
 
function goPolling(){
 
function goPolling(){
 
     var user = mw.config.values.wgRelevantUserName;
 
     var user = mw.config.values.wgRelevantUserName;
 
+
 
  var params = {
+
    var params = {
action: 'ask',
+
        action: 'ask',
 
         query: '[[Class::Workflow]][[Random juror::User:' + user + ']] OR [[Random judge::User:' + user + ']]',
 
         query: '[[Class::Workflow]][[Random juror::User:' + user + ']] OR [[Random judge::User:' + user + ']]',
 
         formatversion: 2,
 
         formatversion: 2,
format: 'json'
+
        format: 'json'
};
+
    };
+
 
var api = new mw.Api();
+
    var api = new mw.Api();
  
 
     api.post( params ).done( function ( data ) {
 
     api.post( params ).done( function ( data ) {
 
         if(data.query.results) {
 
         if(data.query.results) {
          var newKeys = Object.keys(data.query.results);
+
            var newKeys = Object.keys(data.query.results);
          if(polledJurors && newKeys.sort().join() != polledJurors.sort().join()){
+
            if(polledJurors && newKeys.sort().join() != polledJurors.sort().join()){
              console.log('found something new', newKeys);
+
                console.log('found something new', newKeys);
              console.log('polled', polledJurors);
+
                console.log('polled', polledJurors);
 
                 reloadSection()
 
                 reloadSection()
 
             } else {
 
             } else {
Line 399: Line 399:
 
function reloadSection(){
 
function reloadSection(){
  
  var template = pollWrapper.dataset.poll;
+
    var template = pollWrapper.dataset.poll;
  var paramters = pollWrapper.dataset.parameters.replaceAll('^', '|')
+
    var paramters = pollWrapper.dataset.parameters.replaceAll('^', '|')
  var params = {
+
    var params = {
action: 'parse',
+
            action: 'parse',
        text: '{{' + template + '|' + paramters + '|Fullpagename=' + mw.config.values.wgPageName.replaceAll('_', ' ') + '}}',
+
            text: '{{' + template + '|' + paramters + '|Fullpagename=' + mw.config.values.wgPageName.replaceAll('_', ' ') + '}}',
        contentmodel: 'wikitext',
+
            contentmodel: 'wikitext',
        wrapoutputclass: '',
+
            wrapoutputclass: '',
        disableeditsection: true,
+
            disableeditsection: true,
        disablelimitreport: true,
+
            disablelimitreport: true,
        disabletoc: true,
+
            disabletoc: true,
        formatversion: 2,
+
            formatversion: 2,
format: 'json'
+
            format: 'json'
},
+
        },
api = new mw.Api();
+
        api = new mw.Api();
  
 
     api.post( params ).done( function ( data ) {
 
     api.post( params ).done( function ( data ) {
      if(data.parse){
+
        if(data.parse){
        if(template == 'Messages'){
+
            if(template == 'Messages'){
          $(pollWrapper).html(data.parse.text)
+
                $(pollWrapper).html(data.parse.text)
        } else {
+
            } else {
          $('#mw-content-text').html(data.parse.text)
+
                $('#mw-content-text').html(data.parse.text)
 +
            }
 
         }
 
         }
      }
 
 
     })
 
     })
  
Line 431: Line 431:
  
 
function logmeout(){
 
function logmeout(){
+
 
var params = {
+
    var params = {
action: 'logout',
+
            action: 'logout',
format: 'json'
+
            format: 'json'
},
+
        },
api = new mw.Api();
+
        api = new mw.Api();
  
 
     api.postWithToken( 'csrf', params ).done( function ( data ) {
 
     api.postWithToken( 'csrf', params ).done( function ( data ) {
  console.log( data, 'we logged you out' );
+
        console.log( data, 'we logged you out' );
  window.location = mw.config.values.wgServer + '/index.php/Main_Page';
+
        window.location = mw.config.values.wgServer + '/index.php/Main_Page';
 
     } );
 
     } );
+
 
}  
+
}
  
  
Line 449: Line 449:
 
$( document ).ready(function() {
 
$( document ).ready(function() {
  
 
if ($('.WSShowOnSelect') ) {
 
WsShowOnSelect();
 
}
 
  
$('body.action-edit #wpTextbox1, body.action-submit #wpTextbox1').keydown(function(event)  {
+
    if ($('.WSShowOnSelect') ) {
    var x = event.keyCode;
+
        WsShowOnSelect();
    if (x == 13 ) {
+
    }
        if(!event.shiftKey){
+
 
          var insert =  document.execCommand('insertText', false, '<!-- \n -->');
+
    $('body.action-edit #wpTextbox1, body.action-submit #wpTextbox1').keydown(function(event)  {
          if(insert){
+
        var x = event.keyCode;
              event.preventDefault();
+
        if (x == 13 ) {
                $('#wpTextbox1').focus()
+
            if(!event.shiftKey){
                 insert
+
                var insert =  document.execCommand('insertText', false, '<!-- \n -->');
 +
                if(insert){
 +
                    event.preventDefault();
 +
                    $('#wpTextbox1').focus()
 +
                    insert
 +
                 }
 
             }
 
             }
 
         }
 
         }
     }
+
     })
})
 
  
  
Line 472: Line 472:
  
 
// Start of esc save
 
// Start of esc save
 
 
 
  $('body.action-edit, body.action-submit').keydown(function()  {
 
    var x = event.keyCode;
 
    if (x == 27) {
 
      $.ajax({
 
        url :'/api.php?action=query&meta=tokens&format=json',
 
        type: 'GET',
 
        dataType: 'json',
 
        success : function(result){
 
          var token = result.query.tokens.csrftoken;
 
  
          $("input[name='wpEditToken']").attr("value", token );
 
  
          saveEdit();
 
  
 +
    $('body.action-edit, body.action-submit').keydown(function()  {
 +
        var x = event.keyCode;
 +
        if (x == 27) {
 +
            $.ajax({
 +
                url :'/api.php?action=query&meta=tokens&format=json',
 +
                type: 'GET',
 +
                dataType: 'json',
 +
                success : function(result){
 +
                    var token = result.query.tokens.csrftoken;
 +
 +
                    $("input[name='wpEditToken']").attr("value", token );
 +
 +
                    saveEdit();
 +
 +
                }
 +
            });
 +
        }else{
 +
            mw.confirmCloseWindow();
 +
            $('#wpSave, #wpPreview, #wpDiff').on('click', function(){
 +
                $( window ).off( 'beforeunload' );
 +
            })
 
         }
 
         }
      });
 
    }else{
 
      mw.confirmCloseWindow();
 
      $('#wpSave, #wpPreview, #wpDiff').on('click', function(){
 
        $( window ).off( 'beforeunload' );
 
      })
 
    }
 
  
  })
+
    })
  
if($('body').hasClass('action-submit')){
+
    if($('body').hasClass('action-submit')){
  $('#top').prepend('<button class="btn btn-success enable-live-mode">Enable live mode</button>');
+
        $('#top').prepend('<button class="btn btn-success enable-live-mode">Enable live mode</button>');
  $(document).on('click','.enable-live-mode', function(){
+
        $(document).on('click','.enable-live-mode', function(){
    if($(this).hasClass('btn-success')){
+
            if($(this).hasClass('btn-success')){
    liveMode();
+
                liveMode();
    $(this).removeClass('btn-success');
+
                $(this).removeClass('btn-success');
    $(this).text('Live mode is on');
+
                $(this).text('Live mode is on');
  }else{
+
            }else{
      $(this).addClass('btn-success');
+
                $(this).addClass('btn-success');
      $('body.action-submit textarea').off("change keyup paste");
+
                $('body.action-submit textarea').off("change keyup paste");
      $(this).text('Enable live mode');
+
                $(this).text('Enable live mode');
  }
+
            }
  
  });
+
        });
}
+
    }
 
});
 
});
  
 
window.saveEdit = function() {
 
window.saveEdit = function() {
  $.ajax({
+
    $.ajax({
    url : $('form.mw-editform').attr('action'),
+
        url : $('form.mw-editform').attr('action'),
    type : 'POST',
+
        type : 'POST',
    data :$('form.mw-editform').serialize(),
+
        data :$('form.mw-editform').serialize(),
    success : function(html) {
+
        success : function(html) {
    $( window ).off( 'beforeunload' );
+
            $( window ).off( 'beforeunload' );
      mw.notify( 'Saved' );
+
            mw.notify( 'Saved' );
      if($('body').hasClass('action-submit')){
+
            if($('body').hasClass('action-submit')){
      var parser = new DOMParser();
+
                var parser = new DOMParser();
      var doc = parser.parseFromString(html, "text/html");
+
                var doc = parser.parseFromString(html, "text/html");
      var elem = doc.querySelectorAll('.mw-content-ltr')[0];
+
                var elem = doc.querySelectorAll('.mw-content-ltr')[0];
      $('.mw-content-ltr').html(elem);
+
                $('.mw-content-ltr').html(elem);
      }
+
            }
    }
+
        }
  })
+
    })
};  
+
};
  
 
window.liveMode = function() {
 
window.liveMode = function() {
  var oldVal = "";
+
    var oldVal = "";
  $('body.action-submit textarea').on("change keyup paste", function() {
+
    $('body.action-submit textarea').on("change keyup paste", function() {
    var currentVal = $(this).val();
+
        var currentVal = $(this).val();
    if(currentVal == oldVal) {
+
        if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
+
            return; //check to prevent multiple simultaneous triggers
    }
+
        }
 +
 
 +
        oldVal = currentVal;
 +
        var text = encodeURIComponent($('textarea').val());
  
    oldVal = currentVal;
+
        $.ajax({
    var text = encodeURIComponent($('textarea').val());
+
            url: '/api.php?action=parse&format=json&formatversion=2&title=New&text='+text+'&pst=&prop=text%7Cmodules%7Cjsconfigvars&preview=true&disableeditsection=true&uselang=en',
   
+
            dataType: 'json',
    $.ajax({
+
            success: function (x) {
      url: '/api.php?action=parse&format=json&formatversion=2&title=New&text='+text+'&pst=&prop=text%7Cmodules%7Cjsconfigvars&preview=true&disableeditsection=true&uselang=en',
+
                $('#wikiPreview').html(x.parse.text);
      dataType: 'json',
+
            }
      success: function (x) {
+
        });
        $('#wikiPreview').html(x.parse.text);
 
      }  
 
 
     });
 
     });
  });
 
 
};
 
};
 
/* End of Esc Save */
 
/* End of Esc Save */
Line 560: Line 560:
 
/***** WSForm: loading Select2 ****/
 
/***** WSForm: loading Select2 ****/
 
$( document ).ready(function() {
 
$( document ).ready(function() {
  if ($('select[data-inputtype="ws-select2"]')[0]) {
+
    if ($('select[data-inputtype="ws-select2"]')[0]) {
    mw.loader.load('/extensions/WSForm/select2.min.css', 'text/css');
+
        mw.loader.load('/extensions/WSForm/select2.min.css', 'text/css');
    $.getScript('/extensions/WSForm/select2.min.js').done(function() {
+
        $.getScript('/extensions/WSForm/select2.min.js').done(function() {
      $('select[data-inputtype="ws-select2"]').each(function() {
+
            $('select[data-inputtype="ws-select2"]').each(function() {
        var selectid = $(this).attr('id');
+
                var selectid = $(this).attr('id');
        var selectoptionsid = 'select2options-' + selectid;
+
                var selectoptionsid = 'select2options-' + selectid;
        var select2config = $("input#" + selectoptionsid).val();
+
                var select2config = $("input#" + selectoptionsid).val();
        var F = new Function(select2config);
+
                var F = new Function(select2config);
        return (F());
+
                return (F());
      });
+
            });
    });
+
        });
  }
+
    }
 
});
 
});
 
/* End of WSForm: Select2 */
 
/* End of WSForm: Select2 */
Line 594: Line 594:
 
         var columns = textarea.cols;
 
         var columns = textarea.cols;
 
         var lineCount = 0;
 
         var lineCount = 0;
 +
 +
        /**
 +
        * measures the text pixel width
 +
        * @param text
 +
        * @returns {*|jQuery}
 +
        */
 +
        function textMeasure(text) {
 +
            var div = document.createElement('div');
 +
            document.body.appendChild(div);
 +
            $(div).css({
 +
                position: 'absolute',
 +
                left: -1000,
 +
                top: -1000,
 +
                display: 'none'
 +
            });
 +
            $(div).html(text);
 +
            const width = $(div).outerWidth();
 +
            $(div).remove();
 +
            return width;
 +
        }
 +
 
         $.each(lines, function() {
 
         $.each(lines, function() {
             lineCount += Math.ceil(this.length / columns) || 1;
+
             lineCount += Math.ceil(textMeasure(this) / ($(textarea).innerWidth() - 125)) || 1;
 +
            // lineCount += Math.ceil(this.length / columns) || 1;
 
         });
 
         });
 
         var height = lineHeight * (lineCount + 1);
 
         var height = lineHeight * (lineCount + 1);
Line 653: Line 675:
 
     }
 
     }
 
     $(pre_parent_wssos).find('input[type=radio][name="'+ radioElm.name +'"]').on('change', function () {
 
     $(pre_parent_wssos).find('input[type=radio][name="'+ radioElm.name +'"]').on('change', function () {
      var wssos_value = $(this).data('wssos-show');
+
        var wssos_value = $(this).data('wssos-show');
      var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
+
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
 
         var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
 
         var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
 
         if ( $(this).parent().hasClass('WSShowOnSelect') ) {
 
         if ( $(this).parent().hasClass('WSShowOnSelect') ) {
Line 660: Line 682:
 
             wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
 
             wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
 
         }
 
         }
      $(parent_wssos).find('input[name="'+this.name+'"][type="radio"]').each(function(index, radiobtn) {
+
        $(parent_wssos).find('input[name="'+this.name+'"][type="radio"]').each(function(index, radiobtn) {
          var radio_hide_data_attr = $(radiobtn).data('wssos-show');
+
            var radio_hide_data_attr = $(radiobtn).data('wssos-show');
          $(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]').addClass('hidden');
+
            $(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]').addClass('hidden');
          putAllTypesNameInData($(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]'));
+
            putAllTypesNameInData($(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]'));
      });
+
        });
  
      if ( this.checked ) {
+
        if ( this.checked ) {
          wssos_elm.removeClass('hidden');
+
            wssos_elm.removeClass('hidden');
          putAllTypesDataInName(wssos_elm);
+
            putAllTypesDataInName(wssos_elm);
      } else {
+
        } else {
          wssos_elm.addClass('hidden');
+
            wssos_elm.addClass('hidden');
          putAllTypesNameInData(wssos_elm);
+
            putAllTypesNameInData(wssos_elm);
      }
+
        }
 
     });
 
     });
 
}
 
}
Line 713: Line 735:
 
     $(checkElm).on('change', function(e) {
 
     $(checkElm).on('change', function(e) {
 
         e.stopPropagation();
 
         e.stopPropagation();
      var wssos_value = $(this).data('wssos-show');
+
        var wssos_value = $(this).data('wssos-show');
      var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
+
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
      var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
+
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
 
         if ( $(this).parent().hasClass('WSShowOnSelect') ) {
 
         if ( $(this).parent().hasClass('WSShowOnSelect') ) {
 
             parent_wssos = $(this).parent()[0];
 
             parent_wssos = $(this).parent()[0];
Line 881: Line 903:
 
/* END OF WSSHOWONSELECT */
 
/* END OF WSSHOWONSELECT */
 
$( document ).ready(function() {
 
$( document ).ready(function() {
if( $('.redirect-link').length > 0 ) {
+
    if( $('.redirect-link').length > 0 ) {
$('.redirect-link a')[0].click();
+
        $('.redirect-link a')[0].click();
}
+
    }
 
})
 
})

Latest revision as of 10:08, 25 August 2022

/* Any JavaScript here will be loaded for all users on every page load. <script>*/



$(document).ready(function () {

    createPageTogglers = document.querySelectorAll('[data-creatpage]');

    if(createPageTogglers && createPageTogglers.length > 0){

        createPageTogglers.forEach(function(el){

            el.addEventListener(
                "click",
                function () {
                    createPage( )
                })
        })

    }

})

console.log('uyfuyfuy' );
var createPage = function (current_namespace, current_pagename) {
    console.log("working");

    var hiddenInput = document.querySelector('#time-slot-field');

    mw.loader.using(["oojs-ui-windows", 'mediawiki.widgets.DateInputWidget']).then(function () {
        // Example: Using getSetupProcess() to configure a window with data passed
        // at the time the window is opened.

        // Make a subclass of ProcessDialog
        function PageCreateDialog(config) {
            PageCreateDialog.super.call(this, config);
        }
        OO.inheritClass(PageCreateDialog, OO.ui.ProcessDialog);

        // Specify a name for .addWindows()
        PageCreateDialog.static.name = "createPageDialog";
        PageCreateDialog.static.title = "Select a Time Slot";
        // Specify the static configurations: title and action set
        PageCreateDialog.static.actions = [
            {
                flags: "primary",
                label: "Continue",
                action: "open",
            },
            {
                flags: "safe",
                label: "Cancel",
            },
        ];

        // Customize the initialize() function to add content and layouts:
        PageCreateDialog.prototype.initialize = function () {
            var dialol = this;
            PageCreateDialog.super.prototype.initialize.call(this);
            this.panel = new OO.ui.PanelLayout({
                padded: true,
                expanded: false,
            });
            this.content = new OO.ui.FieldsetLayout();


            var date = new Date();

            // month = date.getMonth() + 1;

            this.urlInput = new mw.widgets.DateInputWidget({
                value: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
            });

            this.field = new OO.ui.FieldLayout(this.urlInput, {
                label: "Day",
                align: "top",
            });

            var times = [];
            for (var i = 10; i < 22; i++) {
                var hour = i;
                var pm = 'AM';
                if (i > 12) {
                    hour = i - 12;
                    pm = 'PM';
                }
                times.push(
                    new OO.ui.ButtonOptionWidget( {
                        label:  hour + ':00' + ' - ' + hour + ':15 ' + pm
                    })
                );
                times.push(
                    new OO.ui.ButtonOptionWidget( {
                        label:  hour + ':15' + ' - ' + hour + ':30 ' + pm
                    })
                );
                times.push(
                    new OO.ui.ButtonOptionWidget( {
                        label:  hour + ':30' + ' - ' + hour + ':45 ' + pm
                    })
                );
                times.push(
                    new OO.ui.ButtonOptionWidget( {
                        label:  hour + ':45' + ' - ' + (hour + 1) + ':00 ' + pm
                    })
                );
            }

            this.slotSelect =  new OO.ui.ButtonSelectWidget( {
                items:
                times
            } );

            this.slotsWrapper = new OO.ui.FieldLayout( new OO.ui.Widget( {
                content: [
                    new OO.ui.HorizontalLayout( {
                        items: [
                            this.slotSelect
                        ]
                    })
                ]
            }), {
                label: "Time",
                align: "top",
            });




            this.content.addItems([this.field, this.slotsWrapper]);
            this.panel.$element.append(this.content.$element);
            this.$body.append(this.panel.$element);
            var that = this;
            this.urlInput.on( 'change', function () {
                // The value will always be a valid date or empty string, malformed input is ignored

                that.updateSlots();

            } );

        };


        PageCreateDialog.prototype.updateSlots = function () {

            var that = this;
            var date =  that.urlInput.getValue().split('-');


            var month = date[1];
            var year = date[0];
            var day = date[2];




            that.slotSelect.items.forEach(function(item){
                item.setDisabled(false);
            })

            var params = {
                action: 'ask',
                query: '[[Slot month::' + month + ']][[Slot day::' + day + ']][[Slot year::' + year + ']]|?Slot|limit=500',
                formatversion: 2,
                format: 'json'
            }
            var api = new mw.Api;
            api.post(params).done(function(data){
                if (data.query.results) {
                    console.log(data.query.results)
                    Object.entries(data.query.results).forEach(function(slot){
                        var date = slot[1].printouts.Slot[0].fulltext || slot[1].printouts.Slot[0];
                        var time = date.split('/')[1];
                        var item = that.slotSelect.getItemFromLabel(time);
                        if(item){
                            item.setDisabled(true);
                        }
                    })
                    // ["Workflow/90"].printouts.Slot[0]
                }
            })
            // ask query function here, and disbale results
            // selectItemByLabel(label).setDisabled(true);




        };
        // Specify any additional functionality required by the window (disable opening an empty URL, in this case)

        // Specify the dialog height (or don't to use the automatically generated height).
        PageCreateDialog.prototype.getBodyHeight = function () {
            // Note that "expanded: false" must be set in the panel's configuration for this to work.
            // When working with a stack layout, you can use:
            //   return this.panels.getCurrentItem().$element.outerHeight( true );
            return this.panel.$element.outerHeight(true) + 200;
        };

        // Use getSetupProcess() to set up the window with data passed to it at the time
        // of opening (e.g., url: 'http://www.mediawiki.org', in this example).
        PageCreateDialog.prototype.getSetupProcess = function (data) {
            data = data || {};
            var nuthis = this;
            return PageCreateDialog.super.prototype.getSetupProcess
                .call(this, data)
                .next(function () {
                    // Set up contents based on data
                    var val = hiddenInput.value;
                    if (val) {
                        var split = val.split('/');
                        nuthis.urlInput.setValue(split[0]);
                        nuthis.slotSelect.selectItemByLabel(split[1])
                    }
                    nuthis.updateSlots();

                }, this);
        };
        var boiler = "";
        // Specify processes to handle the actions.
        PageCreateDialog.prototype.getActionProcess = function (action) {
            var nuthis = this;
            if (action === "open") {
                // Create a new process to handle the action
                return new OO.ui.Process(function () {

                    var day = nuthis.urlInput.getValue();
                    var time =  nuthis.slotSelect.findSelectedItem().label;

                    console.log(day, time)
                    hiddenInput.value = day + '/' + time;
                    var button = document.querySelector('#time-slot-button');
                    button.innerText = day + ' • ' + time;
                    return 800;
                }).next(function(){
                    nuthis.close({action: action});
                    return true;
                })
            }
            // Fallback to parent handler
            return PageCreateDialog.super.prototype.getActionProcess.call(this, action);
        };

        // Use the getTeardownProcess() method to perform actions whenever the dialog is closed.
        // This method provides access to data passed into the window's close() method
        // or the window manager's closeWindow() method.
        PageCreateDialog.prototype.getTeardownProcess = function (data) {
            return PageCreateDialog.super.prototype.getTeardownProcess
                .call(this, data)
                .first(function () {
                    // Perform any cleanup as needed
                }, this);
        };

        // Create and append a window manager.
        var windowManager = new OO.ui.WindowManager();
        $(document.body).append(windowManager.$element);

        // Create a new process dialog window.
        var createPageDialog = new PageCreateDialog();

        // Add the window to window manager using the addWindows() method.
        windowManager.addWindows([createPageDialog]);

        // Open the window!
        windowManager.openWindow(createPageDialog);
    });
};



/***
 * REMOVE FILE
 *
 **/

document.querySelectorAll('[data-removefile]').forEach(function(el){
    el.addEventListener('click', function(){
        console.log(el.dataset.removefile)

        var r = confirm("Are you sure?");
        if (r == true) {
            var params = {
                    action: 'delete',
                    title: el.dataset.removefile,
                    format: 'json'
                },
                api = new mw.Api();

            api.postWithToken( 'csrf', params ).done( function ( data ) {
                console.log( data );
                el.remove();
            } );
        }
    })
})


/**
 * POLLING FOR USER PAGES
 **/

var pollWrapper = document.querySelector('[data-poll]');

var fps = 30;
var now;
var then;
var interval = 100000/fps;
var delta;

function poll(now) {
    if (!then) { then = now; }
    requestAnimationFrame(poll);
    delta = now - then;

    if (delta > interval) {
        then = now - (delta % interval);


        if(pollWrapper.dataset.poll == 'Messages'){
            goPolling()
        }else{
            workflowPolling()
        }
    }
}



if(pollWrapper){
    poll();
}





var polledWorkflows = false;

function workflowPolling(){
    var params = {
        action: 'ask',
        query: '[[Workflow::' + pollWrapper.dataset.workflow + ']]|?Modification date',
        formatversion: 2,
        format: 'json'
    };

    var api = new mw.Api();

    api.post( params ).done( function ( data ) {
        if(data.query.results) {
            var flows = Object.entries(data.query.results).map(function(entrie){
                return entrie[1].printouts['Modification date'][0].timestamp
            })
            if(polledWorkflows && flows.sort().join() != polledWorkflows.sort().join()){
                console.log('found something new', flows);
                console.log('polled', polledWorkflows);
                reloadSection()
            } else {
                console.log('polling, but found nothing new');
            }
            polledWorkflows = flows
        }
    })

}



var polledJurors = false;

function goPolling(){
    var user = mw.config.values.wgRelevantUserName;

    var params = {
        action: 'ask',
        query: '[[Class::Workflow]][[Random juror::User:' + user + ']] OR [[Random judge::User:' + user + ']]',
        formatversion: 2,
        format: 'json'
    };

    var api = new mw.Api();

    api.post( params ).done( function ( data ) {
        if(data.query.results) {
            var newKeys = Object.keys(data.query.results);
            if(polledJurors && newKeys.sort().join() != polledJurors.sort().join()){
                console.log('found something new', newKeys);
                console.log('polled', polledJurors);
                reloadSection()
            } else {
                console.log('polling, but found nothing new');
            }
            polledJurors = newKeys;
        }
    })
}

function reloadSection(){

    var template = pollWrapper.dataset.poll;
    var paramters = pollWrapper.dataset.parameters.replaceAll('^', '|')
    var params = {
            action: 'parse',
            text: '{{' + template + '|' + paramters + '|Fullpagename=' + mw.config.values.wgPageName.replaceAll('_', ' ') + '}}',
            contentmodel: 'wikitext',
            wrapoutputclass: '',
            disableeditsection: true,
            disablelimitreport: true,
            disabletoc: true,
            formatversion: 2,
            format: 'json'
        },
        api = new mw.Api();

    api.post( params ).done( function ( data ) {
        if(data.parse){
            if(template == 'Messages'){
                $(pollWrapper).html(data.parse.text)
            } else {
                $('#mw-content-text').html(data.parse.text)
            }
        }
    })

}





function logmeout(){

    var params = {
            action: 'logout',
            format: 'json'
        },
        api = new mw.Api();

    api.postWithToken( 'csrf', params ).done( function ( data ) {
        console.log( data, 'we logged you out' );
        window.location = mw.config.values.wgServer + '/index.php/Main_Page';
    } );

}



$( document ).ready(function() {


    if ($('.WSShowOnSelect') ) {
        WsShowOnSelect();
    }

    $('body.action-edit #wpTextbox1, body.action-submit #wpTextbox1').keydown(function(event)  {
        var x = event.keyCode;
        if (x == 13 ) {
            if(!event.shiftKey){
                var insert =  document.execCommand('insertText', false, '<!-- \n -->');
                if(insert){
                    event.preventDefault();
                    $('#wpTextbox1').focus()
                    insert
                }
            }
        }
    })




// Start of esc save



    $('body.action-edit, body.action-submit').keydown(function()  {
        var x = event.keyCode;
        if (x == 27) {
            $.ajax({
                url :'/api.php?action=query&meta=tokens&format=json',
                type: 'GET',
                dataType: 'json',
                success : function(result){
                    var token = result.query.tokens.csrftoken;

                    $("input[name='wpEditToken']").attr("value", token );

                    saveEdit();

                }
            });
        }else{
            mw.confirmCloseWindow();
            $('#wpSave, #wpPreview, #wpDiff').on('click', function(){
                $( window ).off( 'beforeunload' );
            })
        }

    })

    if($('body').hasClass('action-submit')){
        $('#top').prepend('<button class="btn btn-success enable-live-mode">Enable live mode</button>');
        $(document).on('click','.enable-live-mode', function(){
            if($(this).hasClass('btn-success')){
                liveMode();
                $(this).removeClass('btn-success');
                $(this).text('Live mode is on');
            }else{
                $(this).addClass('btn-success');
                $('body.action-submit textarea').off("change keyup paste");
                $(this).text('Enable live mode');
            }

        });
    }
});

window.saveEdit = function() {
    $.ajax({
        url : $('form.mw-editform').attr('action'),
        type : 'POST',
        data :$('form.mw-editform').serialize(),
        success : function(html) {
            $( window ).off( 'beforeunload' );
            mw.notify( 'Saved' );
            if($('body').hasClass('action-submit')){
                var parser = new DOMParser();
                var doc = parser.parseFromString(html, "text/html");
                var elem = doc.querySelectorAll('.mw-content-ltr')[0];
                $('.mw-content-ltr').html(elem);
            }
        }
    })
};

window.liveMode = function() {
    var oldVal = "";
    $('body.action-submit textarea').on("change keyup paste", function() {
        var currentVal = $(this).val();
        if(currentVal == oldVal) {
            return; //check to prevent multiple simultaneous triggers
        }

        oldVal = currentVal;
        var text = encodeURIComponent($('textarea').val());

        $.ajax({
            url: '/api.php?action=parse&format=json&formatversion=2&title=New&text='+text+'&pst=&prop=text%7Cmodules%7Cjsconfigvars&preview=true&disableeditsection=true&uselang=en',
            dataType: 'json',
            success: function (x) {
                $('#wikiPreview').html(x.parse.text);
            }
        });
    });
};
/* End of Esc Save */


/***** WSForm: loading Select2 ****/
$( document ).ready(function() {
    if ($('select[data-inputtype="ws-select2"]')[0]) {
        mw.loader.load('/extensions/WSForm/select2.min.css', 'text/css');
        $.getScript('/extensions/WSForm/select2.min.js').done(function() {
            $('select[data-inputtype="ws-select2"]').each(function() {
                var selectid = $(this).attr('id');
                var selectoptionsid = 'select2options-' + selectid;
                var select2config = $("input#" + selectoptionsid).val();
                var F = new Function(select2config);
                return (F());
            });
        });
    }
});
/* End of WSForm: Select2 */

(function($) {
    $.fn.autogrow = function() {
        return this.each(function() {
            var textarea = this;
            $.fn.autogrow.resize(textarea);
            $(textarea).focus(function() {
                textarea.interval = setInterval(function() {
                    $.fn.autogrow.resize(textarea);
                }, 500);
            }).blur(function() {
                clearInterval(textarea.interval);
            });
        });
    };
    $.fn.autogrow.resize = function(textarea) {
        var lineHeight = parseInt($(textarea).css('line-height'), 10);
        var lines = textarea.value.split('\n');
        var columns = textarea.cols;
        var lineCount = 0;

        /**
         * measures the text pixel width
         * @param text
         * @returns {*|jQuery}
         */
        function textMeasure(text) {
            var div = document.createElement('div');
            document.body.appendChild(div);
            $(div).css({
                position: 'absolute',
                left: -1000,
                top: -1000,
                display: 'none'
            });
            $(div).html(text);
            const width = $(div).outerWidth();
            $(div).remove();
            return width;
        }

        $.each(lines, function() {
            lineCount += Math.ceil(textMeasure(this) / ($(textarea).innerWidth() - 125)) || 1;
            // lineCount += Math.ceil(this.length / columns) || 1;
        });
        var height = lineHeight * (lineCount + 1);
        $(textarea).css('height', height);
    };
})(jQuery);

$('textarea.form-control').autogrow();


/* WSSHOWONSELECT */
/**
 * applying show on select on the page and make sure everyting will be handled as needed
 */
function WsShowOnSelect() {
    var selectArray = [];
    $('.WSShowOnSelect').find('[data-wssos-show]').each(function (index, elm) {
        if ( $(elm).is('option') ) {
            var isInArray = false;
            var selectParent = $(elm).parent()[0];
            for ( var i = 0; i < selectArray.length; i++ ) {
                if ( $(selectParent).is($(selectArray[i])) ) {
                    isInArray = true;
                }
            }
            if ( !isInArray ) {
                selectArray.push(selectParent);
                handleSelect(selectParent);
            }
        } else if ( $(elm).is('input[type=radio]') ) {
            handleRadio(elm);
        } else if ( $(elm).is('input[type=checkbox]') ) {
            handleCheckbox(elm);
        } else if ( $(elm).is('button') ) {
            handleButton(elm);
        }
    });
}

/**
 * handle the radio button changes, show what is needed
 * @param radioElm
 */
function handleRadio(radioElm) {
    var pre_wssos_value = $(radioElm).data('wssos-show');
    var pre_parent_wssos = $(radioElm).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    if ( $(radioElm).parent().hasClass('WSShowOnSelect') ) {
        pre_parent_wssos = $(radioElm).parent()[0];
        pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    }
    if ( radioElm.checked ) {
        $(pre_wssos_elm).removeClass('hidden');
        putAllTypesDataInName(pre_wssos_elm);
    } else {
        putAllTypesNameInData(pre_wssos_elm);
    }
    $(pre_parent_wssos).find('input[type=radio][name="'+ radioElm.name +'"]').on('change', function () {
        var wssos_value = $(this).data('wssos-show');
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( $(this).parent().hasClass('WSShowOnSelect') ) {
            parent_wssos = $(this).parent()[0];
            wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        }
        $(parent_wssos).find('input[name="'+this.name+'"][type="radio"]').each(function(index, radiobtn) {
            var radio_hide_data_attr = $(radiobtn).data('wssos-show');
            $(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]').addClass('hidden');
            putAllTypesNameInData($(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]'));
        });

        if ( this.checked ) {
            wssos_elm.removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        } else {
            wssos_elm.addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        }
    });
}

/**
 * handle the checkbox changes, show what is needed
 * @param checkElm
 */
function handleCheckbox(checkElm) {
    var pre_wssos_value = $(checkElm).data('wssos-show');
    var pre_parent_wssos = $(checkElm).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    if ( $(checkElm).parent().hasClass('WSShowOnSelect') ) {
        pre_parent_wssos = $(checkElm).parent()[0];
        pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    }
    if ( checkElm.checked ) {
        pre_wssos_elm.removeClass('hidden');
        // set the dataset value of data-name-attribute back in the name attribute
        putAllTypesDataInName(pre_wssos_elm);

        // set the name value of the unchecked element in the value of data-name-attribute and remove the name attribute
        if ( $(checkElm).has('data-wssos-show-unchecked') ) {
            var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked');
            var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]');
            putAllTypesNameInData(pre_unchecked_elm);
        }
    } else {
        // set data-name-attribute to the value of name attribute and remove the name attribute
        putAllTypesNameInData(pre_wssos_elm);

        if ( $(checkElm).has('data-wssos-show-unchecked') ) {
            var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked');
            var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]');
            $(pre_unchecked_elm).removeClass('hidden');
            // set the name attribute to the value of data-name-attribute
            putAllTypesDataInName(pre_unchecked_elm);
        }
    }
    $(checkElm).on('change', function(e) {
        e.stopPropagation();
        var wssos_value = $(this).data('wssos-show');
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( $(this).parent().hasClass('WSShowOnSelect') ) {
            parent_wssos = $(this).parent()[0];
            wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        }
        if ( this.checked ) {
            wssos_elm.removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        } else {
            wssos_elm.addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        }

        if ( $(this).has('data-wssos-show-unchecked') ) {
            var wssos_unchecked_value = $(this).data('wssos-show-unchecked');
            var wssos_unchecked_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_unchecked_value+'"]');
            if ( this.checked ) {
                wssos_unchecked_elm.addClass('hidden');
                putAllTypesNameInData(wssos_unchecked_elm);
            } else {
                wssos_unchecked_elm.removeClass('hidden');
                putAllTypesDataInName(wssos_unchecked_elm);
            }
        }
    });
}


/**
 * handle the select box changes to show what is needed on select
 * @param selectElm
 */
function handleSelect(selectElm) {
    var selectVal = $(selectElm).val();
    $(selectElm).children().each(function (index, option) {
        var wssos_value = $(option).data('wssos-show');
        var parent_wssos = $(option).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( option.selected || $(option).val() === selectVal) {
            wssos_elm.removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        } else {
            wssos_elm.addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        }
    });

    $(selectElm).on('change', function () {
        $(this).children().each(function (index, option) {
            var wssos_value = $(option).data('wssos-show');
            var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
            var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
            if ( option.selected ) {
                wssos_elm.removeClass('hidden');
                putAllTypesDataInName(wssos_elm);
            } else {
                wssos_elm.addClass('hidden');
                putAllTypesNameInData(wssos_elm);
            }
        });
    });
}

function handleButton(btnElm) {
    var pre_wssos_value = $(this).data('wssos-show');
    var pre_parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');

    // set up the start and make sure the element is hidden
    $(pre_wssos_elm).addClass('hidden');
    putAllTypesNameInData(pre_wssos_elm);
    // add on click listener to the button
    $(btnElm).on('click', function(e) {
        var wssos_value = $(this).data('wssos-show');
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');

        // possibility to hide the wanted element back if an option
        if ( !$(wssos_elm).hasClass('hidden') ) {
            $(wssos_elm).addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        } else {
            $(wssos_elm).removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        }
    });
}

/**
 * find all different types which name attribute should go to the dataset
 * @param elm
 */
function putAllTypesNameInData(elm) {
    putNameAttrValueInDataset($(elm).find('input,select,textarea'));
    putRequiredInDataset($(elm).find('input,select,textarea'));
}


/**
 * find all different types which data-attribute should go to the name-attribute
 * @param elm
 */
function putAllTypesDataInName(elm) {
    putDatasetValueBackInName($(elm).find('input,select,textarea'));
    putDatasetInRequired($(elm).find('input,select,textarea'));
}

/**
 * set the name attribute value to the dataset data-name-attribute, remove the name attribute
 * @param elm
 */
function putNameAttrValueInDataset($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).attr('name') !== '' ) {
            var name = $(elm).attr('name');
            if (name) {
                $(elm).attr('data-name-attribute', name);
                $(elm).removeAttr('name');
            }
        }
    });
}


/**
 * set the name attribute to the value of the data-name-attribute
 * @param elm
 */
function putDatasetValueBackInName($elm) {
    $.each($elm, function(index, elm) {
        if ( $(elm).attr('data-name-attribute') !== '' ) {
            var datasetName = $(elm).data('name-attribute');
            if (datasetName) {
                $(elm).attr('name', datasetName);
            }
        }
    });
}

/**
 * set the required attr in the dataset data-ws-required
 * @param $elm
 */
function putRequiredInDataset($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).is(':required') ) {
            $(elm).attr('data-ws-required', true);
            $(elm).prop('required', false);
        }
    });
}

/**
 * if the element has data-ws-required the make the element required
 * @param $elm
 */
function putDatasetInRequired($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).data('ws-required') ) {
            $(elm).prop('required', true);
        }
    })
}

/* END OF WSSHOWONSELECT */
$( document ).ready(function() {
    if( $('.redirect-link').length > 0 ) {
        $('.redirect-link a')[0].click();
    }
})