$( function() {
	'use strict';
	var iwapi = new mw.ForeignApi( 'https://www.wikidata.org/w/api.php' );
	var v = mw.config.get();
	var blockmsg = 'The user or IP address is blocked.';
	var title = 'Description from Wikidata';
	var buttontextadd = 'Add Wikidata description';
	var buttonchangeImage = new Image(12, 12);
	buttonchangeImage.src = 'https://upload.wikimedia.org/wikipedia/commons/6/63/Arbcom_ru_editing.svg';
	var buttontitlechange = 'Change Wikidata description';
	var label = 'Wikidata description';
	var submitbuttontext = 'Save';
	var recentchangestext = 'The latest descriptions changed with this gadget can be viewed ';
	var recentchangeslinktext = 'here';
	var tagName = v.wgDBname + '-DescriptionGadget';
	if ( v.wgUserLanguage === 'sv' ) {
		blockmsg = 'Användaren eller IP-adressen är blockerad.';
		title = 'Beskrivning från Wikidata';
		buttontextadd = 'Lägg till Wikidata-beskrivning';
		buttontitlechange = 'Ändra Wikidata-beskrivning';
		label = 'Wikidata-beskrivning';
		submitbuttontext = 'Spara';
		recentchangestext = 'De senaste beskrivningarna ändrade med den här finessen kan visas ';
		recentchangeslinktext = 'här';
	}
	function getDescription() {
		function openDialog( prefill ) {
			var dialogstr = '<div>';
			dialogstr += '<p><label id="gadget-wikidatadescription-label" for="gadget-wikidatadescription-input">' + label + '</label></p>';
			dialogstr += '<input id="gadget-wikidatadescription-input">';
			dialogstr += '<button id="gadget-wikidatadescription-submit">' + submitbuttontext + '</button>';
			dialogstr += '<p>' + recentchangestext + '<a href="https://www.wikidata.orghttps://wiki95.com/sv/Special:RecentChanges?tagfilter=' + tagName + '">' + recentchangeslinktext + '</a>.</p>';
			dialogstr += '</div>';

			// Creating and opening a simple dialog window.

			// Subclass Dialog class. Note that the OOjs inheritClass() method extends the parent constructor's prototype and static methods and properties to the child constructor.

			function MyDialog( config ) {
				MyDialog.super.call( this, config );
			}
			var myDialog;
			var windowManager;
			if ( $( '.oo-ui-window-active' ).length === 0 ) {
				OO.inheritClass( MyDialog, OO.ui.Dialog );

				// Specify a title statically (or, alternatively, with data passed to the opening() method).
				MyDialog.static.name = 'gadgetwikidatadescriptiondialog';
				MyDialog.static.title = 'Simple dialog';

				// Customize the initialize() function: This is where to add content to the dialog body and set up event handlers.
				MyDialog.prototype.initialize = function () {
					// Call the parent method
					MyDialog.super.prototype.initialize.call( this );
					// Create and append a layout and some content.
					this.content = new OO.ui.PanelLayout( {
						padded: true,
						expanded: false
					} );
					this.content.$element.append( dialogstr );
					this.$body.append( this.content.$element );
					if ( prefill ) {
						$( '#gadget-wikidatadescription-input' ).val( prefill );
					}
					$( '#gadget-wikidatadescription-submit' ).click( function() {
						var editobj = {
							action: 'wbsetdescription',
							id: v.wgWikibaseItemId,
							language: v.wgContentLanguage,
							value: $( '#gadget-wikidatadescription-input' ).val(),
							formatversion: 2	
						};
						function edit() {
							( new mw.Api() ).get( {
								list: 'blocks',
								bkusers: mw.config.get( 'wgUserName' ),
								formatversion: 2
							} ).done( function( blockdata ) {
								if ( blockdata && blockdata.query && blockdata.query.blocks && blockdata.query.blocks.length ) {
									mw.notify( blockmsg, {
										type: 'error',
										tag: 'gadget-wikidatadescription-blocked'
									} );
								} else {
									iwapi.postWithToken( 'csrf', editobj ).done( function() {
										getDescription();
										myDialog.close();
									} ).fail( function( code, editres ) {
										mw.notify( code, {
											type: 'error',
											tag: 'gadget-wikidatadescription'
										} );
									} );
								}
							} );
						}
						iwapi.get( {
							action: 'query',
							list: 'tags',
							tglimit: 'max',
							tgprop: [
								'active',
								'defined',
								'source'
							],
							formatversion: 2
						} ).done( function( tagsres ) {
							var query = tagsres.query;
							var tags;
							function hasTag( tagobj ) {
								return tagobj.name === tagName && tagobj.defined && tagobj.active && tagobj.source.indexOf( 'manual' ) !== -1;
							}
							if ( query ) {
								tags = query.tags;
								if ( tags && Array.isArray( tags ) ) {
									if ( tags.some( hasTag ) ) {
										editobj.tags = tagName;
									}
								}
							}
							edit();
						} ).fail( function() {
							edit();
						} );
					} );
					$( '#gadget-wikidatadescription-input' ).keyup( function( e ) {
						if ( e.which === 13 ) {
							$( '#gadget-wikidatadescription-submit' ).trigger( 'click' );
						}
					} );
					$( '.oo-ui-windowManager' ).click( function( e ) {
						if ( !$( e.target ).parents().filter( '.oo-ui-window' ).length ) {
							myDialog.close();
						}
					} );
				};

				// Set up the ready mode of the window. 
				MyDialog.prototype.getReadyProcess = function ( data ) {
					return MyDialog.super.prototype.getReadyProcess.call( this, data )
					.next( function () {
						$( '#gadget-wikidatadescription-input' ).focus();
					}, this );
				};

				// 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.
				MyDialog.prototype.getTeardownProcess = function ( data ) {
					return MyDialog.super.prototype.getTeardownProcess.call( this, data )
					.first( function () {
						// Perform any cleanup as needed
						$( '.oo-ui-windowManager' ).remove();
					}, this );
				};

				// Make the window.
				myDialog = new MyDialog( {
					classes: [
						'gadget-wikidatadescription-dialog'
					]
				} );

				// Create and append a window manager, which will open and close the window.
				windowManager = new OO.ui.WindowManager();
				$( 'body' ).append( windowManager.$element );

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

				// Open the window!
				windowManager.openWindow( myDialog );
			}
		}
		iwapi.get( {
			action: 'wbgetentities',
			ids: v.wgWikibaseItemId,
			props: 'descriptions',
			languages: v.wgContentLanguage,
			formatversion: 2
		} ).done( function( data ) {
			var entitiesobj = data.entities;
			var entityobj;
            var descrContainer;
			var descriptionsobj;
			var descriptionobj;
			var text;
			$( '#gadget-wikidatadescription-container' ).remove();
			if ( entitiesobj ) {
				entityobj = entitiesobj;
				if ( entityobj ) {
					descriptionsobj = entityobj.descriptions;
					if ( descriptionsobj ) {
						descriptionobj = descriptionsobj;
                        descrContainer = document.createElement( 'div' );
                        descrContainer.setAttribute( 'id', 'gadget-wikidatadescription-container' );
	                    mw.util.addSubtitle( descrContainer );
						if ( descriptionobj ) {
							text = descriptionobj.value;
							if ( text ) {
								$( '#gadget-wikidatadescription-container' ).append(
									$( '<span>' ).attr( {
										id: 'gadget-wikidatadescription',
										title: title
									} ).text( text )
								);
								$( '#gadget-wikidatadescription-container' ).append(
									$( '<span>' ).attr( 'id', 'gadget-wikidatadescription-buttoncontainer' )
								);
								$( '#gadget-wikidatadescription-buttoncontainer' ).append(
									$( '<a>' ).attr( {
										href: 'https://www.wikidata.orghttps://wiki95.com/sv/' + v.wgWikibaseItemId,
										id: 'gadget-wikidatadescription-button',
										title: buttontitlechange
									} ).append( buttonchangeImage )
								);
								$( '#gadget-wikidatadescription-button' ).click( function( e ) {
									e.preventDefault();
									openDialog( text );
								} );
							}
						} else {
							$( '#gadget-wikidatadescription-container' ).append(
								$( '<a>' ).attr( {
									href: 'https://www.wikidata.orghttps://wiki95.com/sv/' + v.wgWikibaseItemId,
									id: 'gadget-wikidatadescription-button'
								} ).text( buttontextadd )
							);
							$( '#gadget-wikidatadescription-button' ).click( function( e ) {
								e.preventDefault();
								openDialog();
							} );
						}
					}
				}
			}
		} );
	}
	if ( v.wgWikibaseItemId ) {
		if (v.wgNamespaceNumber == 0) {
			getDescription();
		}
	}
} );