User:Alex brollo/vis.js

From Wikisource
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// mw.loader.load('//wikisource.org/w/index.php?title=User:Alex brollo/common.js&action=raw&ctype=text/javascript');
// mw.loader.load('//it.wikisource.org/w/index.php?title=MediaWiki:Gadget-visTest.js&action=raw&ctype=text/javascript');

var Vis={};
// tool shortcut 
/* conta il numero di occorrenze di stringa dentro testo; esce se testo === "" oppure stringa ==="" */
function count(testo, stringa) {
	var n = 0;
	if (testo !== "" && stringa !== "") {
		while (testo.indexOf(stringa) > -1) {
			n = n + 1;
			testo = testo.replace(stringa, "");
		}
	}
	return n;
}

/* 
Ricerca nella stringa testo la sottostringa che inizia con idi e termina con idf.  (idi e idf sono stringhe).
 
Se dc ("delimitatori compresi") è 1, restituisce la sottostringa completa di idi e idf; se dc è 0, restituisce la stringa
senza delimitatori; parametro opzionale con default 0.
Per risolvere correttamente il caso di ricerca di tag annidati, come i template, in cui l'identificatore iniziale ha una 
parte non aspecifica, e una parte specifica, può essere passato un quinto parametro, che definisce  la parte aspecifica dell'identificatore iniziale.
 
Esempio: volendo ottenere l'intero contenuto del template {{centrato|{{sc|Testo di prova}}|l=18em}}, il risultato corretto
NON proviene dalla ricerca find_stringa("{{centrato|","}}",1), perchè sarebbe {{centrato|{{sc|Testo di prova}}. 
Impostando invece find_stringa("{{centrato|","}}",1,"{{"), visto che "{{" è la parte aspecifica del primo delimitatore,
si ottiene il risultato corretto, a prescindere dal numero dei template annidati. 
 
Se la sottostringa non viene trovata, la funzione restituisce una stringa vuota "". 
 
*/
function find_stringa(testo, idi, idf, dc, x) {
	idip = testo.indexOf(idi);
	idfp = testo.indexOf(idf, idip + idi.length) + idf.length;
	if (idip > -1 && idfp > -1) {
		if (x !== "") {
			while (count(testo.slice(idip, idfp), x) > count(testo.slice(idip, idfp), idf)) {
				idfp = testo.indexOf(idf, idfp) + idf.length;
			}
		}
		if (dc === 0) {
			vvalore = testo.slice(idip + idi.length, idfp - idf.length);
		} else {
			vvalore = testo.slice(idip, idfp);
		}
	} else {
		vvalore = "";
	}
	return vvalore;
}


/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
var shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		};
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}
 
		var ele = opt.target;
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();
 
		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
 
			if(opt.disable_in_input) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;
 
				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
 
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code).toLowerCase();
 
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown
 
			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
 
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			};
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
 
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
 
				'pause':19,
				'break':19,
 
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
 
				'pageup':33,
				'page_up':33,
				'pu':33,
 
				'pagedown':34,
				'page_down':34,
				'pd':34,
 
				'left':37,
				'up':38,
				'right':39,
				'down':40,
 
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			};
 
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
 
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
 
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;
 
				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;
 
				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
 
				} else if(opt.keycode) {
					if(opt.keycode == code) kp++;
 
				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
 
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
 
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
 
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},
 
	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];
 
		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}



mw.loader.load('https://it.wikisource.org/wiki/MediaWiki:Gadget-vis.css','text/css');
//console.log("visTest versione 27.06.2017 "); // attivata funzione di ricerca
Vis.version="visTest versione 27.06.2017";
/*
Vis.cron : lista, cronologia navigazione
Vis.lp : lista (indice=numero pagina djvu, valore=pagina libro)
Vis.baseDjvu : stringa
Vis.numeroDjvu : numero
Vis.leggiOCR() : funzione
Vis.updateForm() : funzione
Vis.next() : funzione
Vis.previous(): funzione
Vis.build(): funzione
Vis.show() : funzione (!)
Vis.vaiPagDjvu(pagina) : funzione (salta a pag. djvu pagina)
Vis.link() : esamina un link ed esegue funzioni diverse a seconda della pagina bersaglio
*/
Vis.cron=[];
var messaggioNuovaPagina='<div class="center"><span>Pagina non ancora creata<br>'+
			'<b>Doppio click per creare </b></span></div>';
var ocr="";

function produciLista(testo, s1, s2, delim, x) {
	lista = [];
	while (find_stringa(testo, s1, s2, true, x) > "") {
		elemento = find_stringa(testo, s1, s2, true, x);
		testo = testo.replace(elemento, "");
		if (delim) {
			lista.push(elemento);
		} else {
			lista.push(elemento.slice(s1.length, - s2.length));
		}
	}
	return lista;
}

Vis.hl=function(elemento,parola) {
	// eliminazione acapo che i tags html
	var i=0;
	var lista=[];
	var testo=elemento.html();
	// fase 1: codifica
	var tags = produciLista(testo, "<", ">", 1);
	for (i = 0; i < tags.length; i += 1) {
		testo = testo.replace(tags[i], "[#" + i + "#]");
	}
	// evidenziazione parola
	testo=testo.split(parola).join("<span style='background-color:yellow'>"+parola+"</span>");
	// fase 3: decodifica
	for (i = 0; i < tags.length; i += 1) {
		testo = testo.replace("[#" + i + "#]", tags[i]);
	}
	elemento.html(testo);
};


Vis.vaiPagDjvu=function(pagina) {
	
	$(".visForm input[value='djvu']").click();
	$(".visForm input[name='vai_a_pagina']").val(pagina);
	$("#esegui_vai").click();
}
Vis.leggiOCR=function(titolo,fr) {
	$.get(mw.config.get("wgServer")+"/w/index.php?title="+titolo+"&action=edit&redlink=1", function( data ) {
		ocr=$("#wpTextbox1",$(data)).val();
		ocr=ocr.split("\n");
		for (i=0;i<ocr.length;i+=1) {
			ocr[i]=$.trim(ocr[i])+"<br/>";
			// altre funzioni postOCR
		}
		ocr='<span style="color:red;">Visualizzazione OCR</span><br/></br>'+ocr.join("\n");
		$("#body_"+fr).html(ocr);
                if ($("body").data("matches").length>0) for (i=0;i<$("body").data("matches").length;i+=1) {
  		     Vis.hl($("#body_"+fr).eq(0),$("body").data("matches")[i]);
  	        }
	});
};
// riceve una normale stringa di ricerca e carica in Vis.searchResult una lista in cui il title è il testo contenente la parola 
// e il text è il numero pagina djvu
Vis.search=function(dati) {
	$(".popBody").html("");
	var lista=[];
	var url=mw.config.get("wgserver")+"/w/index.php?search="+encodeURIComponent(dati+" prefix:"+Vis.baseDjvu)+"&limit=500";
	var html=$.get(url, function(data) {
		// se la ricerca ha successo esiste un ul classe mw-search-results
		Vis.searchResult=$(".mw-search-results",$(data));
		var matches=[];
		
		
		Vis.searchResult.find(".searchmatch").each(function(){
			if (matches.indexOf($(this).text())===-1) matches.push($(this).text());
		} );
		$("body").data("matches",matches);
		
		
		
		// se Vis.searchResult.length è 0 nessun risultato, altrimenti la ul dei risultati
		if (Vis.searchResult.length>0) {
			Vis.searchResult.addClass("hlist");
			console.log("trovate "+Vis.searchResult.children("li").length);
			// elaborazione elementi li
			$("li",Vis.searchResult).each(function(index,value) {
				var nDjvu=/\d+$/.exec($(this).children(".mw-search-result-heading").children("a").attr("title"))[0];
				if (Vis.lp[nDjvu]===undefined) $(this).remove();
				else {
					$(this).data("nDjvu",nDjvu*1);
					$(this).attr("title",$(this).children(".searchresult").text());
					$(this).html(Vis.lp[nDjvu]);
					$(this).click(function() {Vis.vaiPagDjvu($(this).data("nDjvu"))});
				}
			});
			Vis.searchResult.find("li").sort(function(a,b) {return $(a).data("nDjvu")-$(b).data("nDjvu")}).appendTo(Vis.searchResult);
			$(".popBody").append(Vis.searchResult);
			
		}
	});
}

// nuova funzione, riceve l'elemento a href modificato dalla funzione show
Vis.link=function(elemento){
	var caller=$(elemento).data("caller");
	var called=$(elemento).data("called");
	var callerPaginaLibro=Vis.lp[caller*1];
	// Vis.cron.push($(elemento).data("caller"));
	// regex che restituisce base e numero pagina se il link punta allo stesso libro
	var r=/\/wiki\/(.+\/)(\d+)/;
	var dati=r.exec(called);
	// caso link che punta a pagina del libro
	if (dati !== null && dati[2]!==undefined && dati[1]==Vis.baseDjvu ) {
		Vis.cron.push(caller);
		Vis.vaiPagDjvu(dati[2]);
		$("#pageInput").val(callerPaginaLibro);
	} 
	// caso link che punta altrove
	else {
		window.open(called,"linkEsterno");
	}
};


Vis.updateForm=function() {
	
	$(".vis input[name='numeroDjvu-retro']").val(Vis.numeroDjvu*1);
	$(".vis input[name='numeroLibro-retro']").val(Vis.lp[Vis.numeroDjvu*1]);
	$(".vis input[name='numeroDjvu-fronte']").val(Vis.numeroDjvu*1+1);
	$(".vis input[name='numeroLibro-fronte']").val(Vis.lp[Vis.numeroDjvu*1+1]);
}


Vis.next=function() {
	if (Vis.numeroDjvu<(Vis.lp.length-1)) {
		Vis.numeroDjvu=Vis.numeroDjvu*1+2;
		Vis.show(Vis.baseDjvu+Vis.numeroDjvu,"retro");
		Vis.show(Vis.baseDjvu+(Vis.numeroDjvu*1+1),"fronte");
		Vis.updateForm();
	}
};

Vis.previous=function() {
	if(Vis.numeroDjvu>0) { 
		Vis.numeroDjvu=Vis.numeroDjvu*1-2;
		Vis.show(Vis.baseDjvu+Vis.numeroDjvu,"retro");
		Vis.show(Vis.baseDjvu+(Vis.numeroDjvu*1+1),"fronte");
		Vis.updateForm();
	}
};

Vis.build=function () {
	var logo=$('<img  src="//upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Wikisource-logo.png/80px-Wikisource-logo.png" class="logo" >');
	
	$("body").append($("<div>")
		.attr("class","vis")
	);
	
	$(".vis").append(logo);
	// $(".vis").append($("<table class='libro' align='center'>"));
	var frecce=$("<div class='freccia'>");
	frecce.clone().css( {"left": "50px", "cursor": "pointer"} ).attr("id","frecciaIndietro").attr('title', 'Pagina precedente')
	.append('<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Arrleft.svg/36px-Arrleft.svg.png">')
	.click(function() {Vis.previous();}).appendTo($(".vis"));
	
	frecce.clone().css( {"right": "50px", "cursor": "pointer"} ).attr("id","frecciaAvanti").attr('title', 'Pagina successiva')
	.append('<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/Arrright.svg/36px-Arrright.svg.png">')
	.click(function() {Vis.next();}).appendTo($(".vis"));
	
	frecce.clone()
		.attr("id","iconaChiudi").attr('title', 'Esci')
		.append('<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Dialog-error-round.svg/36px-Dialog-error-round.svg.png"/>')
		.css({"right": "30px", "top": "0px", "color": "red", "cursor": "pointer"})
		.click(function() { 
			$(".vis").remove();
			$("body").css("overflow","scroll");
			})
		.appendTo($(".vis"));
	
	var dimensioneCarattere = 100;
		
	var d = '<div class="noprint" style="position:fixed; right:30px; top:70px;">' +
			'<img id="bottoneIngrandisciCarattere" style="cursor: pointer" src="//upload.wikimedia.org/wikipedia/commons/3/30/Farm-Fresh_magnifier_zoom_in.png" title="Ingrandisci carattere" alt="Ingrandisci carattere" />' +
			' <img id="bottoneRiduciCarattere" style="cursor: pointer" src="//upload.wikimedia.org/wikipedia/commons/e/ea/Farm-Fresh_magnifier_zoom_out.png" title="Riduci carattere" alt="Riduci carattere" />' +
			' <img id="attivaRicerca" style="cursor: pointer" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Crystal_Clear_action_filefind.png/30px-Crystal_Clear_action_filefind.png" title="Attiva ricerca" alt="Attiva ricerca" />' +
			'</div>';
	var tabella='<table class="libro" align="center">'+
		'<tr><td id="header_r">header retro</td><td id="header_f">header fronte</td></tr>' +
		'<tr><td id="body_r"></td><td id="body_f"></td></tr>' +
		'<tr><td id="footer_r">footer retro</td><td id="footer_f">footer fronte</td></tr>' +
		'</table>';
	$(".vis").append($(d));
	$(".vis").append($(tabella));
	$("#header_r,#header_f,footer_r,footer_f").addClass("pagetext");
	// $(".libro").draggable();
	
	$('#bottoneIngrandisciCarattere').click(function() {
		if (dimensioneCarattere < 200) {
			dimensioneCarattere += 5;
		}
		$(".libro").css("font-size", dimensioneCarattere + "%");
	});

	
	$('#bottoneRiduciCarattere').click(function() {
		if (dimensioneCarattere > 50) {
			dimensioneCarattere -= 5;
		}
		$(".libro").css("font-size", dimensioneCarattere + "%");
	});
	
	$("#attivaRicerca").click(function() {
		$("#pop1").toggle();
		if ($("#pop1").css("display")==="block") $("#pop1 input").focus();
	});
	
	$("#body_r").dblclick(function() {
		var url=mw.config.get("wgServer")+"/w/index.php?title=$pagina$&action=edit";
		url=url.replace("$pagina$",Vis.baseDjvu+Vis.numeroDjvu);
		window.open(url,"linkEsterno");
		});

	$("#body_f").dblclick(function() {
		var url=mw.config.get("wgServer")+"/w/index.php?title=$pagina$&action=edit";
		url=url.replace("$pagina$",Vis.baseDjvu+(Vis.numeroDjvu+1));
		window.open(url,"linkEsterno");
	});
	var form=$('<div class="visForm">'+
		'<span class="label">Nome pagina: </span><input type="text" name="baseDjvu" size="50" readonly><br>'+
		'<span class="label">Numero pagina file: </span><input type="text" name="numeroDjvu-retro" size="10" readonly>'+
			' <input type="text" name="numeroDjvu-fronte" size="10" readonly><br>'+
		'<span class="label">Numero pagina libro: </span><input type="text" name="numeroLibro-retro" size="10" readonly>'+
			' <input type="text" name="numeroLibro-fronte"  size="10" readonly><br>'+
		'<span class="label">Numero pagine totali: </span><input type="text" name="numeroPagine" size="10" readonly><br>'+
		'<span class="label">Vai a pagina: </span><input type="text" name="vai_a_pagina" size="10">'+
		'djvu <input type="radio" name="tipo_pagina" value="djvu" checked>libro <input type="radio" name="tipo_pagina" value="libro">'+
		' <input type="submit" id="esegui_vai" value="Vai!" >'+
		'</div>');
    $(".vis").append(form);
    
    $("#esegui_vai").click(function() {
    	// calcolo pagina djvu corrispondente a pagina libro dispari (fronte) corrispondente o immediatamente successiva
    	var tipo_pag_go=$("input[name='tipo_pagina']:checked").val();
    	var pag_go=$("input[name='vai_a_pagina']").val();
    	if (tipo_pag_go==="djvu") {
    		pag_go=pag_go*1;
    		if ((Vis.lp[pag_go]*1)%2!==0) pag_go-=1;
    	} else {
    		pag_go=Vis.lp.indexOf(pag_go+"");
    		try {
    			if ((Vis.lp[pag_go]*1)%2!==0) pag_go-=1;
    		}

    		catch(err) {
    			console.log("errore in input pagina")
    		}
    		
    		
    	}
    	Vis.numeroDjvu=pag_go;
    	Vis.show(Vis.baseDjvu+Vis.numeroDjvu,"retro");
		Vis.show(Vis.baseDjvu+(Vis.numeroDjvu*1+1),"fronte");
		Vis.updateForm();
    });
    // creazione di un popup per la ricerca parole
    var box=$('<div id="pop1" style="font-family:Georgia;font-size:90%;position: fixed; top: 100px; left: 100px; border: 2px solid gray;'+
    '        max-width:400px; min-width: 200px; z-index: 10; background-color: white; display:none; ">'+
	'	  <div class="popHeader" style="background-color:lightgray; width:inherit; height:20px;">'+
	'		  <input id="searchInput" type="text" placeholder="Immetti ricerca"><img id="close" src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Dialog-error-round.svg/20px-Dialog-error-round.svg.png" style="float:right; cursor: pointer">'+
	'	  </div>'+
	'	  <div class="popBody">'+
	'	  </div>'+
	'</div>');
	$("#close",box).click(function(){$(this).parent().parent().toggle();} );
	$("#searchInput",box).keypress(function (e) {
			//var key = e.which;
			// var paginaLibro="";
			if(e.which == 13)  { 
				// the enter key code
				var ricerca=$(this).val();
				Vis.search($(this).val());
				// console.log("Trovate "+Vis.searchResult.children("li").length+" pagine.");
			}
		}); 
	$(".vis").append(box);
    //$(box).draggable();
    
    // creazione di un campo per saltare a una pagina del libro, sente Enter (agisce settando visForm nascosto)
	$(".vis").append($('<input style="position:fixed; right:30px; top:110px;" size="8" id="pageInput" placeholder="Vai a pag." />'));
	$('#pageInput').keypress(function (e) {
		//var key = e.which;
		// var paginaLibro="";
		if(e.which == 13)  { 
			// the enter key code
			var paginaLibro=$('#pageInput').val();
			console.log(paginaLibro);
			if (Vis.lp.indexOf(paginaLibro)===-1) {
				$('#pageInput').val("???");
			} else {

			    $(".visForm input[value='libro']").click();
				$(".visForm input[name='vai_a_pagina']").val(paginaLibro);
				$("#esegui_vai").click();
			}
		}
	}); 
	function visFormToggle() {$(".visForm").toggle();}
	shortcut.add("Ctrl+Alt+m",visFormToggle);
};

	

Vis.show=function (titolo,classe) {
	console.log("passo da show per titolo:",titolo)
	var fr="";
	if (classe.indexOf("fronte")!==-1) fr="f";
	if (classe.indexOf("retro")!==-1) fr="r";
	if (fr==="") {
		alert("Errore! chiamata show con parametro classe errato/assente");
		return false;
	}
	var np=/(\d+)$/.exec(titolo)[1]*1;
	var wikitext="";
	var html="";
	var riGrigia='<table width="100%"><td align="center" style="color:#dddddd">#pag#</td></table>';
	$.ajax({
  		url: mw.config.get("wgServer")+'/w/api.php',
  		data: {
    		format: 'json',
    		action: 'parse', 
			prop:"text|wikitext", 
			page: titolo
   		},
   		dataType: 'jsonp' // this is the important one!
	}).done(function(data) {
  	
  	try {
  		wikitext=data.parse.wikitext["*"];
  		html=$(data.parse.text["*"])[1].outerHTML;
  	// eliminazione commenti
  	while (find_stringa(html,"<!--","-->",1)!=="") {
		html=html.replace(find_stringa(html,"<!--","-->",1),"");
  		} 
  	} catch (err) {
  		wikitext="Pagina inesistente";
  	}
		
  if (wikitext!=="Pagina inesistente") {
  	html=html.replace(/(cite_note-\d+)/g,"$1"+fr).replace(/(cite_ref-\d+)/g,"$1"+fr);
  	html=$(html).css("font-size","100%");
  	$(document.body).data("wikitext_"+classe,wikitext);
  	$("#body_"+fr+",#header_"+fr+",#footer_"+fr+"").html("").css("visibility","initial");
  	html.addClass(classe).appendTo($("#body_"+fr+"")); 
  	$("#header_"+fr).append($("#body_"+fr+" table[title='RigaIntestazione']").eq(0));
  	$("#footer_"+fr).append($("#body_"+fr+" table[title='PieDiPagina']").eq(0));
	riGrigia=riGrigia.replace("#pag#",Vis.lp[np]);
	$("#header_"+fr).append($(riGrigia));
  	} else {
  		if (np<1 || np> (Vis.lp.length-2))    
  			$("#body_"+fr+",#header_"+fr+",#footer_"+fr+"").html("").css("visibility","hidden");           //caso oltre i limiti 
  		else 	{
  			riGrigia=riGrigia.replace("#pag#",Vis.lp[np]);
  			
  			$("#body_"+fr+",#header_"+fr+",#footer_"+fr+"").html("").css("visibility","initial");
  			$("#header_"+fr).append($(riGrigia));
  			// $(messaggioNuovaPagina).appendTo($("#body_"+fr));
  			Vis.leggiOCR(titolo,fr);
  			
  		}
  	} 
  	if ($("body").data("matches").length>0) for (i=0;i<$("body").data("matches").length;i+=1) {
  		Vis.hl($("#body_"+fr).eq(0),$("body").data("matches")[i]);
  	}
  	
  
    
  	// qui aggiungere routine per link interni (if ....)

 	$(".vis a:not([href^='#'])").each(function() {
			// $(this).attr("onclick","Vis.link(this)");
			$(this).data("caller",Vis.numeroDjvu);
			$(this).data("called",$(this).attr("href"));
			$(this).attr("href","#");
			// proviamo.... 
			$(this).click(function() {Vis.link(this);})
			
			
		});
	});
};
Vis.start=function() {
	
	Vis.cron=[];
	Vis.build();
	var pagina="";
	
	
	switch(mw.config.get("wgCanonicalNamespace")) {
		case "Page": pagina = mw.config.get("wgPageName"); break;
		case "Index": pagina = mw.config.get("wgPageName").replace("Indice:","Pagina:").replace("Index:","Page:")+"/"+
			/\/page(\d+)-/.exec($(".mw-parser-output img").attr("src"))[1];break;
		/* disattivazione partenza da ns0 (provvisoria)
                case "":pagina = $(".numeropagina a").eq(0).attr("title");
		if (pagina === undefined) {
			//testo non proofread
			return;
			}
			else {
				pagina = pagina.replace(/ /g,"_");
			}
		*/
	}
	
	/*
	if (mw.config.get("wgCanonicalNamespace") === "Page") {
		pagina = mw.config.get("wgPageName");
	} else {
		pagina = $(".numeropagina a").eq(0).attr("title");
		if (pagina === undefined) {
			//testo non proofread
			return;
		}
		else {
			pagina = pagina.replace(/ /g,"_");
		}
	} */
	
	Vis.baseDjvu=pagina.substring(0,pagina.lastIndexOf("/")+1);
	Vis.numeroDjvu=pagina.substring(pagina.lastIndexOf("/")+1)*1;
	Vis.lp=[];
	$.ajax({
  		url: mw.config.get("wgServer")+'/w/api.php',
  		data: {
    		format: 'json',
    		action: 'parse', 
			prop:"text", 
			page: Vis.baseDjvu.substring(0,Vis.baseDjvu.length-1).replace("Pagina:","Indice:")
   		},
   		dataType: 'jsonp' // this is the important one!
	}).done(function(data) {
  		html=$(find_stringa(data.parse.text["*"],'<div id="pagine',"</div>",1))
		$("a[title^='Pagina:']",html).each(function() {
		$(this).children().filter("span").remove();
		
		if ($(this).attr("class")==="new")
			Vis.lp[/\/(\d+)&action/.exec($(this).attr("href"))[1]*1]=$.trim($(this).text());
		else
			Vis.lp[/\d+$/.exec($(this).attr("href"))[0]*1]=$.trim($(this).text());
		
		});
		if (isFront()) 	Vis.numeroDjvu-=1;

		Vis.show(Vis.baseDjvu+Vis.numeroDjvu,"retro current");
		Vis.show(Vis.baseDjvu+(Vis.numeroDjvu+1),"fronte current");
		$(".vis input[name='numeroPagine']").val(Vis.lp.length-1);
		$(".vis input[name='numeroDjvu-retro']").val(Vis.numeroDjvu*1);
		$(".vis input[name='numeroLibro-retro']").val(Vis.lp[Vis.numeroDjvu*1]);
		$(".vis input[name='numeroDjvu-fronte']").val(Vis.numeroDjvu*1+1);
		$(".vis input[name='numeroLibro-fronte']").val(Vis.lp[Vis.numeroDjvu*1+1]);
		$(".vis input[name='baseDjvu']").val(Vis.baseDjvu);
		localStorage.lp=JSON.stringify(Vis.lp);
		$("body").css("overflow","hidden");
		$(".vis").toggle();
		
		shortcut.add("Ctrl+left",function() {$("#frecciaIndietro").click();});
		shortcut.add("Ctrl+right",function() {$("#frecciaAvanti").click();});
		shortcut.add("Ctrl+x",function() {$("#iconaChiudi").click();});
	
		$(document).keydown(function (e) {
			if (e.which == 27) {
				//ESC
				$("#iconaChiudi").click();
				$(document).off('keydown');
			}
			else if (e.which == 39) {
				//freccia DX
				$("#frecciaAvanti").click();
			}
			else if (e.which == 37) {
				//freccia SX
				$("#frecciaIndietro").click();
			}
		});
	});
	
	
	
	/*if (! isFront()) 	Vis.numeroDjvu-=1;
	Vis.show(Vis.baseDjvu+Vis.numeroDjvu,"retro current");
	Vis.show(Vis.baseDjvu+(Vis.numeroDjvu+1),"fronte current");
	$("body").css("overflow","hidden");
	$(".vis").toggle(); */
	return false;

}
function isFront() {
	var isOdd=true;

	try {
		if ((Vis.lp[Vis.numeroDjvu]*1)%2===0) isOdd=false;
	} catch(err) {
		isOdd=true;
	} 
	return isOdd;
}
if ((mw.config.get("wgCanonicalNamespace")==="Index" ||mw.config.get("wgCanonicalNamespace")==="Page" || mw.config.get("wgCanonicalNamespace")==="") 
	// && mw.config.get("wgAction")==="view") {
	) {
		shortcut.add("Ctrl+Alt+v",Vis.start);
		mw.util.addPortletLink(
			'p-tb',
			"javascript:void(0)",
			'Visualizzatore',
			'Visualizzatore',
			'Visualizzatore'
		);
		$("#Visualizzatore").click(function() {Vis.start();});
		if (window.location.href.indexOf("vis=true")!==-1) Vis.start();
		if (mw.config.get("wgCanonicalNamespace")==="Index") $('<div class="Top_icon_raw" style="cursor: pointer" title="Visualizzatore">'+
		'<img alt="Link a visualizzatore" src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/7a/Book_blue.png/30px-Book_blue.png">'+
		'</div>').click(function() {Vis.start();}).appendTo(".top_icon_cont");
}