/**
 * Gadget-CompletaTemplate.js
 * Funzione di autocompletamento dei template, basato sulla sottopagina /struct dei template.
 * Riscritto da zero a partire da:
 * http://it.wikipedia.org/w/index.php?title=MediaWiki:Gadget-CompletaTemplate.js&oldid=58406391
 * 
 * @author ]
 */
/*jshint unused: false */
/*global mediaWiki, jQuery */

( function ( mw, $ ) {
	'use strict';

	// previene con Firefox l'azione di default del tasto Tab 
	var tabDefault = true;

	function readTemplateStruct( template, readHandler ) {
		$.ajax( {
			url: mw.config.get( 'wgScript' ),
			data: {
				title: 'Template:' + template + '/struct',
				action: 'raw'
			},
			async: false,
			cache: false,
			dataType: 'text'
		} )
			.done( function ( data ) {
				readHandler( data.match( /(<pre>)(*?)(<\/pre>)/ ) );
			} )
			.fail( function ( jqXHR, textStatus, errorThrown ) {
				window.open( mw.config.get( 'wgArticlePath' )
					.replace( '$1', 'Speciale:Ricerca/Template:' + template ), '_blank' );
			} );
	}

	$( function () {
		$( '#wpTextbox1, #wpUploadDescription' ).keydown( function ( event ) {
			var text, cPos, tPos;
			if ( !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey && event.keyCode === 9 ) {
				tabDefault = true;
				cPos = $( event.target ).textSelection( 'getCaretPosition' );
				text = $( event.target ).val().substring( 0, cPos );
				tPos = text.lastIndexOf( '{{' );
				text = text.substring( tPos );
				if ( tPos >= 0 && !/\}\r\n\|]/.test( text ) ) {
					tabDefault = false;
					event.preventDefault();
					$( event.target ).textSelection( 'setSelection', { start: tPos, end: cPos } );
				} else {
					text = null;
				}
			} else if ( event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey && event.keyCode === 81 ) {
				event.preventDefault();
				text = $( event.target ).textSelection( 'getSelection' );
				text = text.length > 2 && text.indexOf( '{{' ) === 0 ? text : null;
			}
			if ( text ) {
				readTemplateStruct( text.substring( 2 ), function ( templateStruct ) {
					$( event.target ).textSelection( 'encapsulateSelection', { peri: templateStruct, replace: true } );
				} );
			}
		} );

		$( '#wpTextbox1, #wpUploadDescription' ).keypress( function ( event ) {
			if ( !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey && event.keyCode === 9 ) {
				return tabDefault;
			}
		} );
	} );
}( mediaWiki, jQuery ) );