/**
 * Open the image pages on the new tab
 * 
 * Author: Serhio Magpie
 * Licenses: MIT, CC BY-SA
 */

// <nowiki>

$( function () {
	var _config = {
		localLinks: mw.loader.getState('ext.gadget.directLinkToCommons') !== 'ready',
	};
	var _strings = {
		title_hint: '(открыть изображение на новой вкладке: ALT + клик)',
	};
	var _processedNodes = [];

	function Item( $image ) {
		if ( !$image || $image.length === 0 || _processedNodes.includes( $image ) ) {
			return;
		}

		this.$image = $image;
		this.$link = $image.closest( 'a' );
		
		if ( this.$link &&  this.$link.length > 0) {
			// this.linkPagename = this.getLinkPagename();
			// this.setTitle( this.$link );
			this.$link.on( 'pointerdown', this.onClick.bind( this ) );
		} else {
			// this.setTitle( this.$image );
			this.$image.on( 'pointerdown', this.onClick.bind( this ) );
		}
		
		_processedNodes.push( this.$image );
	}
	
	Item.prototype.getImageSrc = function () {
		return this.$image.attr( 'src' );
	};

	Item.prototype.getImagePagename = function ( isLocalLink ) {
		var name;
		
		try {
			var url = mw.util.parseImageUrl( this.getImageSrc() );
			var title = mw.Title.newFromText( url.name, 6 );
			name = isLocalLink ? title.getPrefixedDb() : [ 'File', title.getMain() ].join( ':' ); 
		} catch(e) {}
		
		return name;
	};
	
	Item.prototype.getLinkPagename = function () {
		var name;
		
		try {
			var url = new URL( this.$link.prop( 'href' ) );
			var urlPathname =  decodeURIComponent( url.pathname );
			if ( /^\/wiki\//.test( urlPathname ) ) {
				name = mw.Title.newFromUserInput( urlPathname.replace( /^\/wiki\//, '' ) ).getPrefixedDb(); 
			}
		} catch(e) {}
		
		return name;
	};
	
	Item.prototype.checkIsCommons =  function () {
		return this.getImageSrc().indexOf( '//upload.wikimedia.org/wikipedia/commons/' ) > -1;
	};
	
	Item.prototype.setTitle = function ( $node ) {
		var titles = [ _strings.title_hint ];
		
		var currentTitle = $node.attr( 'title' );
		if ( currentTitle && currentTitle.length > 0 ) {
			titles.unshift( currentTitle );
		}
		
		$node.attr( 'title', titles.join( ' ' ) );
	};

	Item.prototype.onClick = function ( event ) {
		if ( !event.altKey ) {
			return;
		}
		
		event.preventDefault();
		
		var isLocalLink = !this.checkIsCommons() || _config.localLinks;
		var pageName = this.getImagePagename( isLocalLink );
		if ( !pageName ) {
			return;
		}
		
		var url = isLocalLink ? mw.util.getUrl( pageName ) : [ '//commons.wikimedia.org/wiki', pageName ].join( '/' );
		window.open( url, '_blank' ).focus();
	};
		
	function process( $context ) {
		if ( !$context || $context.length === 0 ) {
			return;
		}
			
		$context.find( 'img' ).each( function () {
			new Item( $( this ) );
		} );
	}
	
	mw.hook( 'wikipage.content' ).add( process );
} );

// </nowiki>