MediaWiki:Common.js

Uit Dorpsbelang Den Hout
Ga naar:navigatie, zoeken

Opmerking: nadat u de wijzigingen hebt opgeslagen is het wellicht nodig uw browsercache te legen.

  • Firefox / Safari: houd Shift ingedrukt terwijl u op Vernieuwen klikt of druk op Ctrl-F5 of Ctrl-R (⌘-Shift-R op een Mac)
  • Google Chrome: druk op Ctrl-Shift-R (⌘-Shift-R op een Mac)
  • Internet Explorer: houd Ctrl ingedrukt terwijl u op Vernieuwen klikt of druk op Ctrl-F5
  • Opera: ga naar Menu → Instellingen (Opera → Voorkeuren op een Mac) en daarna naar Privacy & beveiliging → Browsegegevens wissen... → Tijdelijk opgeslagen afbeeldingen en bestanden.
// JavaScript die hier wordt geplaatst heeft invloed op alle pagina's voor alle gebruikers <script> 

// edit page thing

var windowManager = null;
var hubSettingsDialog = null;
var dialolg = "";



$(document).ready(function () {

  openHubToggler = document.querySelector('.open-page-settings');

  if(openHubToggler){

    openHubToggler.addEventListener(
      "click",
      function () {
        openHubSetting()
    })

  }

})

window.openHubSetting = function () {
  mw.loader
    .using([
      "oojs-ui-core",
      "oojs-ui-windows",
      "oojs-ui-widgets",
      "mediawiki.widgets.UsersMultiselectWidget",
       "mediawiki.widgets.DateInputWidget",
    ])
    .then(function () {
      return new mw.Api().loadMessagesIfMissing([
        "mustbeloggedin",
        "permissiondenied",
        "fileexists-shared-forbidden",
        "chunk-too-small",
        "windows-nonascii-filename",
        "stashfailed",
        "http",
        "verification-error",
      ]);
    })
    .then(function () {



      function PageOneLayout(name, config) {
        var that = this;
        var loadedName = "";
        PageOneLayout.super.call(this, name, config);

        this.nameInput = new OO.ui.TextInputWidget({
          placeholder: "Bericht titel",
          validate: function (val) {
            if (loadedName == val) {
              that.nameField.setErrors([]);
              return true;
            }
            if (!val) {
              dialolg.hasChanged = false;
              if (dialolg.panel.currentPageName !== "full") {
                dialolg.actions.categorized.actions.open[0].setDisabled(true);
              }
              that.nameField.setErrors(["Titel mag niet leeg zijn"]);
              return false;
            }
    
                dialolg.actions.categorized.actions.open[0].setDisabled(false);
                that.nameField.setErrors([]);
                //console.log(dialol.titlefield.getFlags( ))
                that.nameInput.setValidityFlag(true);
                return true;
             
          },
        });

        this.nameField = new OO.ui.FieldLayout(this.nameInput, {
          label: "Titel",
          align: "top",
        });

        this.descriptionInput = new OO.ui.MultilineTextInputWidget( {
            autosize: true,
            placeholder: "Bericht samenvatting",
            value: ''
        } )
        

        this.descriptionField = new OO.ui.FieldLayout(this.descriptionInput, {
          label: "Samenvatting",
          align: "top",
        });
        
         this.adminscomboBox = new mw.widgets.UsersMultiselectWidget({
          // selected: admins
        });
        var that = this;
        //set selected admins
  
       //   that.adminscomboBox.addOptions(admins);
        //  that.adminscomboBox.setValue(admins);

        this.adminsField = new OO.ui.FieldLayout(this.adminscomboBox, {
          label: "Auteurs",
          align: "top",
        });


        this.tagscomboBox =  new OO.ui.MenuTagMultiselectWidget( {
           // inputPosition: 'outline',
           // allowArbitrary: false,
            verticalPosition: 'below',
             placeholder: "Selteer tags",
            menu: {
              filterFromInput: true,
              filterMode: "substring",
            },
            options: []
         } )
        
        function onlyUnique(value, index, self) {
          return self.indexOf(value) === index;
        }
        
        var params = {
          action: "ask",
          query:
            "[[Class::Bericht]][[Domein::" + mw.config.values.wgServerName + "]][[Tags::+]]|?Tags|limit=500",
          format: "json",
        };
        var api = new mw.Api();

        api.get(params).done(function (data) {
          var tags = Object.entries(data.query.results).map( function(el){
            return el[1].printouts.Tags.join()
          }).filter(onlyUnique);
          
          var tags = tags.map(function(tag){
              return {
                    data: tag                   
                }
          
          })
          that.tagscomboBox.addOptions(tags)
    
        })
        
       
        


        this.tagsField = new OO.ui.FieldLayout(this.tagscomboBox, {
          label: "Tags",
          align: "top",
        });
        
        this.layoutDrop = new OO.ui.DropdownInputWidget( {
            options: [
                {
                    data: 'layout1',
                    label: 'Layout 1'
                },
                {
                    data: 'layout2',
                    label: 'Layout 2'
                },
            ],
            value: 'layout1'
        } )
        
        this.layoutField = new OO.ui.FieldLayout(this.layoutDrop, {
          label: "Layout",
          align: "top",
        });
        
              this.dateInput = new mw.widgets.DateInputWidget();
        
        this.dateField = new OO.ui.FieldLayout(this.dateInput, {
          label: "Datum",
          align: "top",
        });


        var loadedDisc = "";

        var loadedTags = [];
        //get values for inputs

        var params = {
          action: "ask",
          query:
            "[[" +
             mw.config.values.wgPageName +
            "]]|?Titel|?Tags|?Datum|?Samenvatting|?Layout|?Persoon|?Show date",
          format: "json",
        };
        var api = new mw.Api();

        api.get(params).done(function (data) {
          console.log(data);
          if (data.query.results) {
            var index = Object.keys(data.query.results)[0];
            var description = data.query.results[index].printouts.Samenvatting;
            var name = data.query.results[index].printouts.Titel;
            var tagids = data.query.results[index].printouts.Tags;
            var datum = data.query.results[index].printouts.Datum;
            var layout = data.query.results[index].printouts.Layout;
            var persoon = data.query.results[index].printouts.Persoon;

            if (description && description[0]) {
              loadedDisc = description[0];
              that.descriptionInput.setValue(description[0]);
            }
            
            if (layout && layout[0]) {
              that.layoutDrop.setValue(layout[0].fulltext);
            }
            
            if (persoon && persoon[0]) {
             that.adminscomboBox.addOptions([{data:persoon[0].fulltext, label:persoon[0].fulltext}]);
              that.adminscomboBox.setValue([{data:persoon[0].fulltext, label:persoon[0].fulltext}]);
            }

            if (name && name[0]) {
              loadedName = name[0];
              that.nameInput.setValue(name[0]);
            }
            
            if(datum && datum[0]) {
              var date = datum[0].raw.split('/')
              that.dateInput.setValue(date[1] + "-" + date[2] + "-" + date[3])
            }

            if (tagids) {
              var selected = [];
              tagids.forEach(function (tag) {
                if (tag) {
                  loadedTags.push(tag);
                  selected.push({
                    data: tag,
                    label: tag,
                  });
                }
              });
              that.tagscomboBox.addOptions(selected);
              that.tagscomboBox.setValue(selected);
            }
          }
        });

    
        
  
        this.$element.append(
          this.nameField.$element,
          this.adminsField.$element,
          this.tagsField.$element,
          this.layoutField.$element,
          this.dateField.$element,
          this.descriptionField.$element
        );

        this.tagscomboBox.input.$input.attr( 'autocomplete', 'off' );


    
      }

      OO.inheritClass(PageOneLayout, OO.ui.PageLayout);
      PageOneLayout.prototype.setupOutlineItem = function () {
        this.outlineItem.setLabel("Bericht details");
      };
    
    
    



      function PageFourLayout(name, config) {
        PageFourLayout.super.call(this, name, config);

        this.uploadButton = new OO.ui.SelectFileWidget({
          accept: [ 
            'image/png',
  		    'image/jpeg',
            'application/pdf'
          ],
          $tabIndexed: $(
            '<a class="oo-ui-buttonElement-button" role="button" tabindex="0" aria-disabled="false" rel="nofollow"><span class="oo-ui-iconElement-icon oo-ui-icon-upload"></span><span class="oo-ui-labelElement-label">Select a file</span><span class="oo-ui-indicatorElement-indicator oo-ui-indicatorElement-noIndicator"></span><input title="" class="oo-ui-inputWidget-input" type="file" tabindex="-1" accept="image/png, image/jpeg, application/pdf"></a>'
          ),
          showDropTarget: true,
        });

        this.uploadLayout = new OO.ui.FieldLayout(this.uploadButton, {
          align: "top",
        });

        this.progressBar = new OO.ui.ProgressBarWidget({
          progress: false,
        });

        this.progressBar.toggle();

        var img = document.querySelector(".image-wrapper img");
        if (img) {
          this.image = $(img.cloneNode());
          this.image[0].classList.add("img-thumbnail", "mb-4");

          this.$element.append(this.image);
        }
        var that = this;
        this.uploadButton.on("change", function (data) {
          that.uploadLayout.setErrors([]);
          if (data.length) {
            dialolg.hasImage = true;
            dialolg.actions.categorized.actions.open[0].setDisabled(false);
          } else {
            dialolg.hasImage = false;
            dialolg.actions.categorized.actions.open[0].setDisabled(true);
          }
        });

        this.$element.append(
          this.progressBar.$element,
          this.uploadLayout.$element
        );
      }
      OO.inheritClass(PageFourLayout, OO.ui.PageLayout);
      PageFourLayout.prototype.setupOutlineItem = function () {
        this.outlineItem.setLabel("Bericht afbeelding");
      };

      var page1 = new PageOneLayout("larger"),
        page2 = new PageFourLayout("large");
  

      function HubSettingsDialog(config) {
        HubSettingsDialog.super.call(this, config);
      }
      OO.inheritClass(HubSettingsDialog, OO.ui.ProcessDialog);

 

      // Specify a name for .addWindows()
      HubSettingsDialog.static.name = "hubSettingsDialog";
      HubSettingsDialog.static.title = "Bericht instellingen";
      // Specify the static configurations: title and action set
      HubSettingsDialog.static.actions = [
        {
          flags: ["primary", "progressive"],
          label: "Opslaan",
          action: "open",
        },
        {
          flags: "safe",
          label: "Sluiten",
        },
      ];

      HubSettingsDialog.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.panel.pages.larger.$element.outerHeight( true );
        //return this.panel.$element.outerHeight(true);
        return this.panel.getCurrentPage().$element[0].scrollHeight;
      };

      HubSettingsDialog.prototype.initialize = function () {
        dialolg = this;
        HubSettingsDialog.super.prototype.initialize.call(this);
        this.panel = new OO.ui.BookletLayout({
          outlined: true
        });

        this.panel.connect(this, {
          set: "onBookletLayoutSet",
        });

   
        this.panel.addPages([page1, page2]);

        //this.panel.$element.append( this.content.$element );
        this.$body.append(this.panel.$element);
      };
    
         HubSettingsDialog.prototype.getSetupProcess = function (data) {
        data = data || {};
        return HubSettingsDialog.super.prototype.getSetupProcess
          .call(this, data)
          .next(function () {

            // Set up contents based on data
           // if (dialolg.panel.currentPageName == "full") {
           //   dialolg.actions.categorized.actions.open[0].setDisabled(false);
          //  }

          }, this);
      };

      HubSettingsDialog.prototype.onBookletLayoutSet = function (page) {
       this.setSize(page.getName());

      };

      HubSettingsDialog.prototype.getActionProcess = function (action) {
        var nuthis = this;
        if (action === "open") {
          // Create a new process to handle the action
          return new OO.ui.Process(function () {
   

            if (nuthis.panel.currentPageName == "large") {
              nuthis.actions.categorized.actions.open[0].setDisabled(true);
              nuthis.panel.pages.large.progressBar.toggle();
                var param = {
                filename:
                  Date.now() +
                  "hubimg" +
                  nuthis.panel.pages.large.uploadButton.currentFiles[0].name.match(/\.[0-9a-z]+$/i)[0],
                format: "json",
                ignorewarnings: 1,
                text:
                  "{{Bericht file|Class=Bericht file|Domein=" +
                  mw.config.values.wgServerName + "|Bericht=" + mw.config.values.wgPageName +
                  "}}",
              };
              var api = new mw.Api();
              api
                .upload(
                  nuthis.panel.pages.large.uploadButton.currentFiles[0],
                  param
                )
                .progress(function (data) {
                  nuthis.panel.pages.large.progressBar.setProgress(data * 100);
                })
                .done(function (data) {
                  if (data.upload) {
                    var newimg = data.upload.imageinfo.url;
                    console.log(data);
                    nuthis.panel.pages.large.progressBar.setProgress(0);
                    nuthis.panel.pages.large.progressBar.toggle();
                    nuthis.panel.pages.large.uploadButton.setValue();
                    var img = document.querySelector(".space-home-div img");
                    if (img) {
                      img.srcset = newimg;
                      img.src = newimg;
                    }
                    nuthis.panel.pages.large.image[0].srcset = newimg;
                    nuthis.panel.pages.large.image[0].src = newimg;

                    nuthis.panel.pages.large.uploadLayout.setSuccess([
                      "Saved successfully",
                    ]);
                    setTimeout(function () {
                      nuthis.panel.pages.large.uploadLayout.setSuccess([]);
                    }, 6000);
/***
                    var params = {
                        action: "edit",
                        title: mw.config.values.wgCanonicalNamespace + ":Home",
                        format: "json",
                        section: "new",
                        text: "",
                      },
                      api = new mw.Api(); 

                    api.postWithToken("csrf", params).done(function (data) {});
          **/
                  }
                })
                .fail(function (data) {
                  if (data == "duplicate") {

                    var newimg = document.querySelector('.oo-ui-selectFileWidget-thumbnail').style.backgroundImage
                   
                    newimg = newimg.substr(5, newimg.length - 7)

                    nuthis.panel.pages.large.uploadLayout.setSuccess([
                      "Saved successfully",
                    ]);

                    var img = document.querySelector(".image-wrapper img");
                    if (img) {
                      img.srcset = newimg;
                      img.src = newimg;
                    }
                    nuthis.panel.pages.large.image[0].srcset = newimg;
                    nuthis.panel.pages.large.image[0].src = newimg;

                    setTimeout(function () {
                      nuthis.panel.pages.large.uploadLayout.setSuccess([]);
                    }, 6000);
/***
                    var params = {
                      action: "edit",
                      title: mw.config.values.wgCanonicalNamespace + ":Home",
                      format: "json",
                      section: "new",
                      text: "&nbsp;",
                    },
                    api = new mw.Api(); 

                    api.postWithToken("csrf", params).done(function (data) {

 

                    });
                    
                    **/

                  }else{
                      nuthis.panel.pages.large.progressBar.setProgress(0);
                      nuthis.panel.pages.large.progressBar.toggle();
                      nuthis.panel.pages.large.uploadLayout.setErrors([
                        mw.message(data).text(),
                      ]);
                      console.log(mw.message(data).text());
                  }
                });
            }

               if (nuthis.panel.currentPageName == "larger") {
              nuthis.actions.categorized.actions.open[0].setDisabled(true);
                 console.log(nuthis.panel.pages.larger.tagscomboBox
                    .getValue().join(","));
                 console.log("{{Bericht" +
                  "|Datum=" + 
                 nuthis.panel.pages.larger.dateInput.getValue() +
                  "|Layout=" +
                  nuthis.panel.pages.larger.layoutDrop.getValue() +
                  "|tags=" +
                  nuthis.panel.pages.larger.tagscomboBox
                    .getValue().join(",") +
                  "|Domein=" +
                  mw.config.values.wgServerName +
                  "|Titel=" +
                  nuthis.panel.pages.larger.nameInput.getValue() +
                     "|Auteur=" +  nuthis.panel.pages.larger.adminscomboBox.getSelectedUsernames().join(",") +
                  "|Samenvatting=" +
                  nuthis.panel.pages.larger.descriptionInput.getValue() +
                  "}}");
                 
              var params = {
                action: "editslot",
                title: mw.config.values.wgPageName,
                text:
                  "{{Bericht" +
                  "|Datum=" + 
                 nuthis.panel.pages.larger.dateInput.getValue() +
                  "|Layout=" +
                  nuthis.panel.pages.larger.layoutDrop.getValue() +
                  "|tags=" +
                  nuthis.panel.pages.larger.tagscomboBox
                    .getValue().join(",") +
                  "|Domein=" +
                  mw.config.values.wgServerName +
                  "|Auteur=" +  nuthis.panel.pages.larger.adminscomboBox.getSelectedUsernames().join(",") +
                  "|Titel=" +
                  nuthis.panel.pages.larger.nameInput.getValue() +
                  "|Samenvatting=" +
                  nuthis.panel.pages.larger.descriptionInput.getValue() +
                  "}}",
                slot: "ws-slot",
                format: "json",
              };
              var api = new mw.Api();

              api.postWithToken("csrf", params).done(function (data) {

                  var pageTitle = document.querySelector('.title-wrapper h2') ;
                  if (pageTitle) {
                    pageTitle.innerText =  nuthis.panel.pages.larger.nameInput.getValue();
                  }
                

       
                nuthis.panel.pages.larger.nameField.setSuccess([
                  "Saved successfully",
                ]);
                setTimeout(function () {
                  nuthis.panel.pages.larger.nameField.setSuccess([]);
                }, 6000);
              });
            }
          }, this);
        }
        // Fallback to parent handler
        return HubSettingsDialog.super.prototype.getActionProcess.call(this, action);
      };

      if (!windowManager) {
        windowManager = new OO.ui.WindowManager();

        hubSettingsDialog = new HubSettingsDialog();

        // Create and append a window manager.

        $(document.body).append(windowManager.$element);

        // Create a new process dialog window.

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

        // Open the window!
        windowManager.openWindow(hubSettingsDialog);

        //$( document.body ).append( booklet.$element );
      } else {
        hubSettingsDialog.open();
        //windowManager.openWindow( myDialog );
      }
    });
};



/// new page 

var noPage = document.querySelector('.no-page-new-page');

if (noPage) {
  mw.loader
    .using([
        "oojs-ui-widgets"
    ]).then( function (){
          var fieldset = new OO.ui.FieldsetLayout( { 
                  label: 'Deze pagina bevat geen tekst.'
              } );
    
    
         var tagscomboBox =  new OO.ui.DropdownInputWidget( {
             placeholder: "Selteer tags",
            menu: {
              filterFromInput: true,
              filterMode: "substring",
            },
            options: []
         } )
        
        function onlyUnique(value, index, self) {
          return self.indexOf(value) === index;
        }
        
        var params = {
          action: "ask",
          query:
            "[[Class::Bericht]][[Domein::" + mw.config.values.wgServerName + "]][[Tags::+]]|?Tags|limit=500",
          format: "json",
        };
        var api = new mw.Api();

        api.get(params).done(function (data) {
          var tags = Object.entries(data.query.results).map( function(el){
            return el[1].printouts.Tags.join()
          }).filter(onlyUnique);
          
          var tags = tags.map(function(tag){
              return {
                    data: tag                   
                }
          
          })
         tagscomboBox.setOptions(tags)
    
        })
    
       var overzichtButton =   new OO.ui.ButtonWidget( {
                          label: 'Overzicht maken',
                          flags: [
                                  'primary',
                                  'progressive'
                          ]
                  } )
       
       
  
       
             var berichtButton =   new OO.ui.ButtonWidget( {
                          label: 'Bericht maken',
                          flags: [
                                  'primary',
                                  'progressive'
                          ]
                  } )

          // Add an action field layout: 
          fieldset.addItems( [ 
              new OO.ui.ActionFieldLayout(
                  tagscomboBox,
                  overzichtButton,
                  {
                          label: 'Een overzicht maken:',
                          align: 'top'
                  }
              ),
              new OO.ui.ActionFieldLayout(
                 new OO.ui.LabelWidget( 
                    {
                      label: 'Een bericht maken:',
                      align: 'top'
                    }
                  ),
                   berichtButton
              )
          ] );

          $( noPage ).append( fieldset.$element );
    
    
           overzichtButton.on('click', function(){
      
              createBerichtOfOverzicht('Overzicht')

            })
    
    
    
            berichtButton.on('click', function(){
      
                     createBerichtOfOverzicht('Bericht')

            })
    
    function createBerichtOfOverzicht(type){
       var tags = ''
       if(type == 'Overzicht') { tags = '|tags=' + tagscomboBox.getValue()  }
              var params = {
                  action: 'editslot',
                  title: mw.config.values.wgPageName ,
                  text: '{{' + type
                          +'|Domein=' + mw.config.values.wgServerName
                         + tags 
                          +'}}',
                  slot: 'ws-slot',
                   format: 'json'
                    },
                    api = new mw.Api();

                api.postWithToken( 'csrf', params ).done( function ( data ) {
                    window.location.replace("https://" + mw.config.values.wgServerName + "/index.php/" + mw.config.values.wgPageName + '?veaction=edit')
                } );
    
    }
    
    

  })
  
}


   

//
var nwBericht = document.querySelector('.new-bericht-veld');

if (nwBericht) {
  mw.loader
    .using([
        "oojs-ui-widgets"
    ]).then( function (){

      var fieldset = new OO.ui.FieldsetLayout( { 
              label: 'Nieuw bericht'
          } );
    
      var input = new OO.ui.TextInputWidget( {
                      placeholder: 'Bericht titel',
                      inputFilter: function (val) {
                          var regx = /[^\?\!%$#@&,\'\":<>\/\]/gi;
                          return val
                            .replace(regx, "")
                        }
              } );
    
    var button =   new OO.ui.ButtonWidget( {
                      label: 'Maken',
                      flags: [
                              'primary',
                              'progressive'
                      ]
              } )

      // Add an action field layout: 
      fieldset.addItems( [ 
          new OO.ui.ActionFieldLayout(
              input,
              button,
              {
                      label: 'Titel',
                      align: 'top'
              }
          )
      ] );    
      console.log(fieldset)

      $( nwBericht ).append( fieldset.$element );
    
    

  })
  
}




//js voor menu
 

 document.addEventListener('click', function(e){
 

        document.querySelectorAll('.main-menu .hover').forEach(function(e){e.classList.remove('hover')})
 	
      if(e.target.closest('.main-menu li')){
 
  addthehover(e.target.closest('li'))
 
      }
 

    })
//upload hub image

var uploadWrappers = document.querySelectorAll('.ws-image-upload');
if(uploadWrappers.length > 0){
  mw.loader.using( ['oojs-ui-core', 'oojs-ui-widgets'] ).done( function () {
    
    uploadWrappers.forEach(function(uploadWrapper){
	
    var uploadButton = new OO.ui.SelectFileWidget( {
  	accept: [
  		'image/png',
  		'image/jpeg',
        'application/pdf'
  	],
  	$tabIndexed: $( '<a class="oo-ui-buttonElement-button" role="button" tabindex="0" aria-disabled="false" rel="nofollow"><span class="oo-ui-iconElement-icon oo-ui-icon-upload"></span><span class="oo-ui-labelElement-label">Select a file</span><span class="oo-ui-indicatorElement-indicator oo-ui-indicatorElement-noIndicator"></span><input title="" class="oo-ui-inputWidget-input" type="file" tabindex="-1" accept="image/png, image/jpeg"></a>' ),
  	showDropTarget: true
  } );

	var submitBtn = new OO.ui.ButtonInputWidget( {
	type: 'submit',
	useInputTag: true,
	label: 'Upload',
	flags: [
		'primary',
		'progressive'
	]
} )
    
submitBtn.$element.hide();
	$(uploadWrapper).append([ uploadButton.$element, submitBtn.$element ]);

var param = "";
var filetext = uploadWrapper.dataset.filetext;

uploadButton.on('change', function(data){
  
   submitBtn.$element.hide();
  if(data[0]){
     submitBtn.$element.show();

    param = {
			filename: Date.now() + data[0].name,
			format: 'json',
			ignorewarnings: 1,
	        text: filetext 
		}  
  }
})
  
	var api = new mw.Api();


	submitBtn.on( 'click', function () {
		submitBtn.$element.hide();
		var progressBar = new OO.ui.ProgressBarWidget( {
				progress: false
			} );
		$(uploadWrapper).append( progressBar.$element );
		api.upload( uploadButton.currentFiles[0], param ).progress(function(data){
			progressBar.setProgress(data * 100);
		}).done( function ( data ) {
          if(data.upload){
            $('.upload-group').html('<img src="'+data.upload.imageinfo.url+'">');
              uploadButton.info.$element.find('.oo-ui-indicator-clear')[0].click();

             progressBar.$element.remove();
           
          }
			console.log( data );
		} ).fail( function ( data ) {
			console.log( data );
            progressBar.$element.remove();
            uploadButton.info.$element.find('.oo-ui-indicator-clear')[0].click();
          
           
           showWarningMsg('Upload failed',  mw.msg(data) );
		} );
	} );
   } );
  } );
}

function showWarningMsg(title, message){
       var messageDialog = new OO.ui.MessageDialog();

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

        // Add the dialog to the window manager.
        windowManager.addWindows( [ messageDialog ] );

        // Configure the message dialog when it is opened with the window manager's openWindow() method.
        windowManager.openWindow( messageDialog, {
          title: title,
          message: message
        } );
}







function removeImg(el){

}


function toggleDateField(el){
  var datefield =  el.closest('.grid-datum').querySelector('[type="date"]');
  var hiddenfiel =  el.closest('.grid-datum').querySelector('[type="hidden"]');
  datefield.classList.toggle('disabled');
  if(datefield.classList.contains('disabled')){
    hiddenfiel.value = "false";
  }else{
    hiddenfiel.value = "";
  }
}


//js for file uplaod

var counter = 0;
var dropped;

var fileInput = document.getElementById('widget-file-upload-files');   

var settingsPreview, settingsCaption, settingsDrop, settingsFilepagetemplate, settingsFilepageparameters, settingsFilename, settingsType;

if(fileInput){
 settingsPreview = fileInput.getAttribute('data-preview');
 settingsCaption = fileInput.getAttribute('data-caption');
 settingsDrop = fileInput.getAttribute('data-drop');
 settingsFilepagetemplate = fileInput.getAttribute('data-filepagetemplate');
 settingsFilepageparameters = fileInput.getAttribute('data-filepageparameters');
 settingsFilename = fileInput.getAttribute('data-filename');
 settingsType = fileInput.getAttribute('data-type');

 fileInput.addEventListener('change', handleFileSelect, false); //is a <input type="file" id="files" name="files[]" multiple />
}
                                                                                       
                                                                                               
function createFilename(filename){
  var output = settingsFilename;                                                                                          
  var regex = /<(\w+)>/gm;
  var m;
  var name = filename.split('.')[0];
  
  if(settingsType && filename.split('.')[1]  != 'pdf'){
    var type = settingsType;
  }else{
    var type = filename.split('.')[1];   
  }
  
  while ((m = regex.exec(settingsFilename)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    }    
    // The result can be accessed through the `m`-variable.
    m.forEach(function(match, groupIndex){
      
      if(match == "FILENAME"){
        output = output.replace('<'+match+'>', name);
      }else{
        var input = fileInput.closest('form').querySelector('[name="'+match+'"]');
        if(input){
          val = input.value;
          output = output.replace('<'+match+'>', val);
        }        
      }
      // console.log(`Found match, group ${groupIndex}: ${match}`);
    });
  }
  return output+'.'+type;
}                                                                                              

function createWikitext(filename, caption){
  var output = settingsFilepageparameters;                                                                                          
  var regex = /<(\w+)>/gm;
  var m;
  var name = filename.split('.')[0];
  var type = filename.split('.')[1]; 
  
  while ((m = regex.exec(settingsFilepageparameters)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    } 
    // The result can be accessed through the `m`-variable.
    m.forEach(function(match, groupIndex){
      
      if(match == "FILENAME"){
        output = output.replace('<'+match+'>', name);
      }else{
        var input = fileInput.closest('form').querySelector('[name="'+match+'"]');
        if(input){
          val = input.value;
          output = output.replace('<'+match+'>', val);
        }
        
      }
      // console.log(`Found match, group ${groupIndex}: ${match}`);
    });
  }
  output = output.replace(/:/g,'=');
  output = output.replace(/;/g,'|');
  if(caption){
    output = '{{'+settingsFilepagetemplate+'|'+output+'|caption='+caption+'|type='+type+'}}';
  }else{
    output = '{{'+settingsFilepagetemplate+'|'+output+'|type='+type+'}}';
  }
  return output;
}                                                                                                    

function handleFileSelect() {  
  if(settingsPreview != "false"){
    
   $('.grid-img img').remove()
                     

    
    createPreviews(fileInput.files);
  }  
 // fileInput.closest('label').style.display = "none"
 // fileInput.closest('form').querySelector('[type="submit"]').style.display = "inline-block"
 // fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)  
  
}

function uploadFiles(evt){
  if(evt){
     evt.preventDefault();
  }
  if(dropped){
    var files = dropped;
  }else{
    var files = fileInput.files;
  }
  var proms = []; 
  for(i = 0; i < files.length; ++i){
    file = files[i];
    var fileName = files[i].name;
    
    if(settingsType && settingsType == 'png' && fileName.split('.')[1] != 'png' && fileName.split('.')[1] != 'pdf'){
   
    //convert jpg to png !!! yeah so cool
       var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64


        var image = new Image();
        image.onload = function() { 

          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          canvas.getContext("2d").drawImage(image, 0, 0);

          //   var png = new Image();
          //    png.src = canvas.toDataURL("image/png");

           canvas.toBlob(function(blob) {

            var prom =  doApiCall(blob, fileName);
            proms.push(prom)
            //  return blob;

          },'image/png', 1)
          //   return dt;
          //  document.getElementById("widget-file-upload-preview").appendChild(png)
          }
        image.src = srcData;
      }
      fileReader.readAsDataURL(file);

    }else{
     var prom =  doApiCall(file, fileName);
     proms.push(prom)
    }
    
   
  }
  Promise.all(proms).then(function(values) {
 // fileInput.closest('form').submit();
    $('#real-submit').click();
  });
}


function jpgtopng(file){
var fs = "";
     
    

}


function doApiCall(fileToUpload,fileName){
  return new Promise(function(resolve, reject){
    
    
       
    
    
    formdata = new FormData(); 
    formdata.append("action", "upload");
    formdata.append("filename", createFilename(fileName));
    //formdata.append("filename", fileName);
    formdata.append("token", mw.user.tokens.get( 'csrfToken' ) );
    formdata.append("file", fileToUpload);
    formdata.append("ignorewarnings", "true");
    formdata.append("format", "json");
    
    
    //as we now have created the data to send, we send it...
    $.ajax( { //http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery
      url: mw.util.wikiScript( 'api' ), //url to api.php 
      contentType:false,
      processData:false,
      type:'POST',
      data: formdata,//the formdata object we created above
      success:function(data){
        resolve(data)
        //  setTimeout(function(){
        editFilePage(fileName);
        //  },100)
      },
      error:function(xhr,status, error){
        console.log(error)
        reject(error)
      }
    });
  });
}


function createPreviews(filesSelected){
  if (filesSelected.length > 0) {
    
    for(i = 0; i < filesSelected.length; ++i){
      
      var fileToLoad = filesSelected[i];
      var fname = fileToLoad.name;
        var name = fname.split('.')[0];
        var type = fname.split('.')[1];  
      
      if(type == "pdf" || type == "doc" || type == "docx"){
      	
      	var newImage = document.createElement('img');
          newImage.src = "https://handhavingsupport.wiki/images/d/da/File.svg";
          var dt = filesSelected[counter]
          counter = counter + 1;
        
          if(settingsCaption){
            
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<p>'+fname+'</p><input data="'+dt.name+'" type="text" placeholder="caption" class="form-control"  /></div>';
            
          }else{
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<p>'+fname+'</p></div>';
          }
        
      }else {
        
        var fileReader = new FileReader();
        
        fileReader.onload = function(fileLoadedEvent) {
          var srcData = fileLoadedEvent.target.result; // <--- data: base64
          
          var newImage = document.createElement('img');
          newImage.src = srcData;
          var dt = filesSelected[counter]
          counter = counter + 1;
          
          if(settingsCaption){
            
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<input data="'+dt.name+'" type="text" placeholder="caption" class="form-control"  /></div>';
            
          }else{
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'</div>';
          }
        }
        
        fileReader.readAsDataURL(fileToLoad);
      }
    }
  }
}

function editFilePage(file){
  
  if(settingsCaption){
    var caption = document.querySelector('[data="'+file+'"]').value;
    var newWikitextEdit = createWikitext(file, caption);
  }else{
    var newWikitextEdit = createWikitext(file);
  }
  
  var params = {
    action: 'edit',
    title: 'File:'+createFilename(file),
    text: newWikitextEdit,
    format: 'json'
  },
  api = new mw.Api();
  
  api.postWithToken( 'csrf', params ).done( function ( data ) {
    console.log( data );
  } );
  
}



var dropArea = document.getElementById('drop-area');

if(dropArea){
  
  
  ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(function(eventName){
    dropArea.addEventListener(eventName, preventDefaults, false)
  })
  
  function preventDefaults (e) {
    e.preventDefault()
    e.stopPropagation()
  } 
  
  ;['dragenter', 'dragover'].forEach(function(eventName){
    dropArea.addEventListener(eventName, highlight, false)
  })
  
  ;['dragleave', 'drop'].forEach(function(eventName){
    dropArea.addEventListener(eventName, unhighlight, false)
  })
  
  function highlight(e) {
    dropArea.classList.add('highlight')
  }
  
  function unhighlight(e) {
    dropArea.classList.remove('highlight')
  }
  
  dropArea.addEventListener('drop', handleDrop, false)
  
  function handleDrop(e) {
    var dt = e.dataTransfer
    var files = dt.files
    dropped = files;
    
    if(settingsPreview != "false"){
      createPreviews(files);
    }   
    
    fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)
  }  
  
}

function removeFile(el, file){
  
  var message = confirm("Weet je zeker dat je dit bestand wilt verwijderen?")
  if(message == true){
    var params = {
    action: 'delete',
    title: file,
    format: 'json'
  },
  api = new mw.Api();

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


function postBericht(el, template, mode){
  var titel = "";
  var domein = "";
  var parameters = "";
  var prefix = "";
  var page = "";
  var multiparameters = {};
  var inputs = el.closest('form').querySelectorAll('select, textarea, input:not([name="mwreturn"] ):not([name="mwdb"] ):not([name="mwtoken"] ):not([type="file"]):not([name="mwaction"]):not([name="exclude"])'), i;
  for(i = 0; i < inputs.length; ++i){
   if(inputs[i].name == "Titel"){titel = inputs[i].value};
   if(inputs[i].name == "Pagename"){page = inputs[i].value};
   if(inputs[i].name == "Prefix"){prefix = inputs[i].value};
   if(inputs[i].name == "Domein"){domein = inputs[i].value};
   if(inputs[i].type == "radio"){ 
       if(inputs[i].checked){ 
          parameters += '|'+inputs[i].name+'='+inputs[i].value;
       }
   }else{
    if(inputs[i].name.includes("[]")){
      if(!multiparameters[inputs[i].name.replace('[]', '')]){
         multiparameters[inputs[i].name.replace('[]', '')] = [];
      }
      multiparameters[inputs[i].name.replace('[]', '')].push(inputs[i].value);
    }else{
    parameters += '|'+inputs[i].name+'='+inputs[i].value;
  }
  }
  }
  if(mode == "domein"){
     var url = domein.replace('.','-');
  }else{
    if(page){
      var url = page;
    }else{
      var regex = /[\s'"?’!@\n\|_&,.\/\{\}\[\]]/gm;
      var url = prefix.replace('.','-')+'/'+titel.replace(regex, '-');
    }
    
  }
  
    var multi = "";
    for(i = 0; i < Object.keys(multiparameters).length; ++i){
      multi += '|'+Object.keys(multiparameters)[i]+'='+multiparameters[Object.keys(multiparameters)[i]].toString(); 

    }
    
  var wikitext = '{{'+template+parameters+multi+'}}'
 console.log(wikitext) 
var params = {
					action: 'edit',
					title: url,
					text: wikitext,
					format: 'json'
				},
				api = new mw.Api();

			api.postWithToken( 'csrf', params ).done( function ( html ) {
                        window.location.href = window.location.origin+'/index.php/'+url;
           })
}

var multiselect = document.querySelector('#multi-select2');

if(multiselect){
   multiselect.addEventListener('change', function(){
 

var sp = document.createElement('div')

sp.innerHTML = this.value+'<input type="hidden" name="tags[]" value="'+this.value+'">';
sp.classList.add('botn');
sp.addEventListener('click', function(){
   this.remove();
}, false)
document.querySelector('.out').appendChild(sp)

this.value = ""}, false);
}

var drops = document.querySelectorAll('.menu-drop');

drops.forEach(function(drop){

 
  
  
   drop.addEventListener('click', function(e){
      document.querySelectorAll('.main-menu .hover').forEach(function(el){el.classList.remove('hover')})
           e.preventDefault()
         e.stopPropagation()
     console.log(e.target.closest('li'))
   
          addthehover(e.target.closest('li'))
    
   

  })
   
})



function addthehover(el){
  el.classList.add('hover')
  var ml = el.closest('li');
  
  if(ml == typeof Object){
    console.log('?',ml)
   addthehover(ml)
  }
}


var _onPaste_StripFormatting_IEPaste = false;

    function OnPaste_StripFormatting(elem, e) {

        if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
            e.preventDefault();
            var text = e.originalEvent.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (e.clipboardData && e.clipboardData.getData) {
            e.preventDefault();
            var text = e.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (window.clipboardData && window.clipboardData.getData) {
            // Stop stack overflow
            if (!_onPaste_StripFormatting_IEPaste) {
                _onPaste_StripFormatting_IEPaste = true;
                e.preventDefault();
                window.document.execCommand('ms-pasteTextOnly', false);
            }
            _onPaste_StripFormatting_IEPaste = false;
        }

    }





/*veforall */


//check for visualeditor textareas
    var vetextarea = document.querySelectorAll('.ve-area-wrapper textarea');

    if(vetextarea){
         //load veforall
         mw.loader.using('ext.veforall.main').then(function(data){

         vetextarea.forEach(function(el){
            //un-escape pipes
            var text = $(el).val();
            var esc = text.replace(/{{!}}/gmi, "|");
            $(el).val(esc);
            //apply visualeditor(s)
            $(el).applyVisualEditor();
         })

        })
     }

    //save visualeditor form

    function veToText(){
             //find active visualeditors
            var visualEditors = $.fn.getVEInstances();
            if( visualEditors.length > 0 ) {
                var savingQueue = [];
                $(visualEditors).each( function( i, ve ) {
                    //update textareas
                    savingQueue.push( ve.target.updateContent() );
                  });
                $.when.apply( $, savingQueue ).then( function () {
                    $(visualEditors).each( function( i, ve ) {
                      //escape pipes
                      var text = ve.$node.val();
                      var esc = text.replace(/(?<!{{[^}]+)\|(?!=[^]+}})/gmi, "{{!}}");
                      ve.$node.val(esc);

                     });
                   //submit form
                   $('#real-submit').click();
                //uploadFiles();
                });
            }

    }