Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/*
Written by [[User:Ravid ziv]] and [[User:ערן]]
*/
mw.hook( 've.activationComplete' ).add(function(){
	//importStylesheetURI('//tools.wmflabs.org/eranbot/clippy.css');
	//$.getScript('//tools.wmflabs.org/eranbot/clippy.min.js')

	var loadedAgent;
	var weasleWords = [];
	var warningsForWeasleWords = [];
	var WEASLE_WORD_PAGE = mw.config.get('WEASLE_WORD_PAGE') || "Wikipedia:Manual of Style/Words to watch/Config"

	function loadAgent(callback){
		callback(loadedAgent);
		/*
		if(loadedAgent) {
			callback(loadedAgent);
		}
		else
		{
			clippy.load('Clippy', function(agent) {
				loadedAgent = agent;
				agent._balloon.CLOSE_BALLOON_DELAY=8000;
				agent.show();
				if ( $('body').hasClass('ltr') ) {
					agent.moveTo(50,50);
				} else {
					agent.moveTo($('#mw-panel').position().left, 50);
				}
				agent._el.dblclick(function(){agent.hide()});
				callback(loadedAgent);
			});
		}
		*/
	}

	function showWarning(warn, x, y){
		loadAgent(function(agent) {
			mw.notify(warn);
			/*
			agent.speak(warn);
			if (x && y) {
				agent.moveTo(x,y);
			}
			*/
		});
	}

	function loadWeaselWords()
	{
		var api = new mw.Api();
		api.get({
			action:'parse',
			page: WEASLE_WORD_PAGE,
			prop: 'wikitext'
			}).done(function (data) {
				var text = data.parse.wikitext['*'].split('-----')[1]
				var genrealWeasleWords = text.split('\n*');

				for (var i=0;i<genrealWeasleWords.length;i++)
				{
					var splitedweasleWords = genrealWeasleWords[i].split("//");
					if ( splitedweasleWords.length !== 2 ) continue;
					weasleWords.push( new RegExp( splitedweasleWords[0], 'i' ) );
					warningsForWeasleWords.push(splitedweasleWords[1]);
				}
				searchWeasleWarnings( getText().join('\n') );
			});
	}

	function searchWeasleWarnings( text, ignoreWarning ){
		var warnings = [];
		for (var i=0; i<weasleWords.length;i++)
		{
			if ( weasleWords[i].test(text) )
			{
				warnings.push(weasleWords[i].exec(text) + ": " +warningsForWeasleWords[i]);
			}
		}

		console.log(warnings);
		if ( warnings.length>0 && !ignoreWarning ) {
			showWarning( warnings.join('\n') );
		}
		return warnings.length>0;
	}
	function extractText(){
		var nodes = [];
		function getTextNodes( obj ) {
			var i;

			for ( i = 0; i < obj.children.length; i++ ) {
				if ( obj.children[i].type == 'text'){
					nodes.push(obj.children[i]);
				}

				if ( obj.children[i].children ) {
					getTextNodes( obj.children[i] );
				}
			}
		}
		getTextNodes(model.documentModel.getDocumentNode());
		return nodes;
	}


	 function getText  (){
		var textNodes = extractText();
		var firstIndex = 0;
		var numReplacements = 0;
		var text = [];

		for (var nodeI = 0; nodeI < textNodes.length; nodeI++) {
			var node = textNodes[nodeI];
			var nodeRange = node.getRange();
			var nodeData = model.getLinearFragment( nodeRange ).getData();
			var nodeText = $.map(nodeData, function( e ){
					if ( e instanceof Array){ return e[0]; } else { return e; }
				}).join('');
			;

			text.push(nodeText);

		}

		return text;
	};

	var view = ve.init.target.getSurface().getView();
	var doc = view.getDocument();
	var model = ve.init.target.getSurface().getModel();
	var cachedNode = null;
	//while editing - only on current node
	model.on( 'documentUpdate', function () {
	try
	{

		var text,
		    selection = model.getSelection(),
		    node = doc.getBranchNodeFromOffset( selection.getRange().start ),
		    textMatches;
		if ( !( node instanceof ve.ce.ContentBranchNode ) ) {
		    return;
		}
		var hasWarnings = searchWeasleWarnings( $( node.$element[0] ).text(), $( node.$element[0] ).data( 'weaselWords' ) );
		if (hasWarnings){
			$( node.$element[0] ).data( 'weaselWords', true);
		} else {
			$( node.$element[0] ).data( 'weaselWords', null);
		}
	}
	catch(e){
		//the ve objects are not stable and it will 100% break some day so just ignore errors....
		console.log(e);
	}
	}
	);

	// loadAgent(function(){})
	loadWeaselWords();
});