ব্যবহারকারী:Sohom Datta/vus.js

টীকা: সংরক্ষণ করার পর, পরিবর্তনসমূহ তৎক্ষণাৎ নাও দেখাতে পারে। আপনার ব্রাউজারের ক্যাশ কিভাবে এড়াবেন তা জানতে এখানে ক্লিক করুন।
  • ফায়ারফক্স / সাফারি: Shift ধরে রাখা অবস্থায়পুনঃলোড করুন-এ ক্লিক করুন, অথবা Ctrl-F5 বা Ctrl-R (ম্যাক-এ ⌘-R) চাপুন
  • গুগল ক্রোম: Ctrl-Shift-R (ম্যাক-এ ⌘-Shift-R) চাপুন
  • ইন্টারনেট এক্সপ্লোরার: Ctrl ধরে রাখা অবস্থায় Refresh-এ ক্লিক করুন, অথবা Ctrl-F5 চাপুন
  • অপেরা: মেনু → ব্যবস্থাপনাসমূহ-এ যান (ম্যাকে অপেরা → পছন্দসমূহ) এবং এরপর গোপনীয়তা ও সুরক্ষা → ব্রাউজিং-এর তথ্য পরিষ্কার করুন → ক্যাশে করা ছবি ও ফাইলগুলি

অন্যান্য ব্রাউজার সম্পর্কে বিশদ নির্দেশাবলীর জন্য, উইকিপিডিয়া:আপনার ক্যাশে বাইপাস করুন দেখুন।

 /*
    This is gadget shows book in text mode.

    Original @Author : https://it.wikisource.org/wiki/Utente:Alex_brollo
    Link: https://it.wikisource.org/wiki/MediaWiki:Gadget-visTest.js
	
	Modified by @Author: Jayanta - https://meta.wikimedia.org/wiki/User:Jayantanth
	Modification purpose is to change the code to show book in Bengali wikisource
*/

/**
 * Shorcut code credit
 * 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;
	}
};





// console.log("visTest versione maggio 2019 "); // attivata evidenziazione parole dopo ricerca
// var Vis={};
Vis={}; //espongo Vis in globale per debug
Vis.version="visTest versione 02.08.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>পাতাটি এখনও তৈরি হয়নি<br>'+
			'<b>Doppio click per creare </b></span></div>';
var ocr="";
var level="";
var user=""; 
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.sal3_r='<img src="https://upload.wikimedia.org/wikisource/it/0/0e/Ipotesi_varianti_SAL_75%25_1.png" style="position:absolute; top:2px;left:2px; display:none;">';
Vis.sal3_f='<img src="https://upload.wikimedia.org/wikisource/it/0/0e/Ipotesi_varianti_SAL_75%25_1.png" style="position:absolute; top:2px;right:2px; display:none;">';
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) {
	//return;
	var number = titolo.substring(titolo.lastIndexOf('/') + 1);
	titolo = titolo.replace('/' + number, '/'+ convertOdiaNumber(number));

	// convertEnglishNumber()
	$.get(mw.config.get("wgServer")+"/w/index.php?title="+titolo+"&action=edit", 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;">লেখা নেই</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="https://bn.wikisource.org/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 = convertEnglishNumber($(this).find(".mw-search-result-heading a").attr("title").substring($(this).find(".mw-search-result-heading a").attr("title").lastIndexOf("/")+1));

				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 {
		// se il link punta a nsPagina apri in vis
		if (called.indexOf("bn.wikisource.org/wiki/পাতা:") !==-1 || called.indexOf("bn.wikisource.org/wiki/নির্ঘণ্ট:") !==-1 ) {
			if (called.indexOf("?")!== -1) called+="#vis=true";

		}
		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', 'Previous Page')
	.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', 'Next Page')
	.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', 'Close')
		.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="Enlarge Font" alt="Ingrandisci carattere" />' +
			' <img id="bottoneRiduciCarattere" style="cursor: pointer" src="//upload.wikimedia.org/wikipedia/commons/e/ea/Farm-Fresh_magnifier_zoom_out.png" title="Reduce Font" 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="Search" 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="https://bn.wikisource.org/w/index.php?title=$pagina$&action=edit";
		url=url.replace("$pagina$",Vis.baseDjvu+convertOdiaNumber(Vis.numeroDjvu));
		window.open(url,"linkEsterno");
		});

	$("#body_f").dblclick(function() {
		var url="https://bn.wikisource.org/w/index.php?title=$pagina$&action=edit";
		url=url.replace("$pagina$",Vis.baseDjvu+convertOdiaNumber(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);
    $(".visForm").draggable(); 
    $("#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" >'+
	'	  <div class="popHeader" style="background-color:lightgray; width:inherit; height:20px;">'+
	'		  <input id="searchInput" type="text" placeholder="Enter search"><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="Go to page" />'));
	$('#pageInput').keypress(function (e) {
		//var key = e.which;
		// var paginaLibro="";
		if(e.which == 13)  { 
			// the enter key code
			var paginaLibro= isNaN($('#pageInput').val()) ? $('#pageInput').val() : convertOdiaNumber($('#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>';

	var number = titolo.substring(titolo.lastIndexOf('/') + 1);
	titolo = titolo.replace('/' + number, '/'+ convertOdiaNumber(number));


	$.ajax({
  		url: 'https://bn.wikisource.org/w/api.php',
  		data: {
    		format: 'json',
    		action: 'parse', 
			prop:"text|wikitext", 
			page: titolo,
			contentmodel: "proofread-page"
   		},
   		dataType: 'jsonp' // this is the important one!
	}).done(function(data) {
  	
  	try {
  		wikitext=data.parse.wikitext["*"];
  		html=$(data.parse.text["*"])[0].outerHTML;
  		// console.log(html);

  	// eliminazione commenti
  	while (find_stringa(html,"<!--","-->",1)!=="") {
		html=html.replace(find_stringa(html,"<!--","-->",1),"");
  		} 
  	} catch (err) {
  		wikitext="Pagina inesistente";
  		console.log("errore nel try riga 337");
  		// console.log(html)
  	}
  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%");
  	// oscuramento barra qualità
  	$(".prp-page-qualityheader",html).css("display","none");
  	$(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));
  	// qui inserito parsing del wikitext per ricavare user e level!!!
  	level=find_stringa(wikitext,'level="','"',0);
	user=find_stringa(wikitext,'user="','"',0);
  	console.log (user+" "+level);
  	if (fr=="r") $("#header_"+fr).append($(Vis.sal3_r)); else $("#header_"+fr).append($(Vis.sal3_f));
	if (level==="3" && user!=mw.config.get("wgUserName") ) $("#header_"+fr+" img").toggle();
  	} 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")!==undefined && $("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);
			// prova eliminazione unescape
			// $(this).data("called",unescape($(this).attr("href")));
			$(this).data("called",$(this).attr("href"));
			$(this).attr("href","#");
			// proviamo.... 
			$(this).click(function() {Vis.link(this);});
			
			/*
			var href=$(this).attr("href");
			var r=/\/wiki\/(.+\/)(\d+)/;
			var dati=r.exec(href);
			if (dati !== null && dati[2]!==undefined && dati[1]==Vis.baseDjvu ) {
				
				 $(this).click(function(){
					// event.preventDefault(); // disabilito link;
					
					// modifico gli attributi
					$(this).data("caller",Vis.numeroDjvu+"").data("called",$(this).attr("href")).attr("onclick","test(this)");
					
					
					
					Vis.cron.push(Vis.numeroDjvu);
					console.log("link interno alla pagina:" + $(this).html(), "numero pagina djvu chiamante: "+ Vis.numeroDjvu,($(this).html()==Vis.numeroDjvu));
					$("#pageInput").val(Vis.lp[Vis.numeroDjvu]);
					$(".visForm input[value='djvu']").click();
					$(".visForm input[name='vai_a_pagina']").val(dati[2]);
					$("#esegui_vai").click();
				
					});	
		
				// link a pagina dello stesso libro
			} else { 
				$(this).attr("target","linkEsterno");
			} */
		});
	});
};
function start() {
	
	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("নির্ঘণ্ট:","পাতা:")+"/"+
		// 	/\/page(\d+)-/.exec($(".thumbinner img").attr("src"))[1];break;
		case "Index": pagina = decodeURIComponent($('.prp-index-pagelist').find('a:first').attr('href').replace("/wiki/",""));break;
		case "":pagina = decodeURIComponent( $(".ws-pagenum").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=convertEnglishNumber(pagina.substring(pagina.lastIndexOf("/")+1))*1;
	Vis.lp=[];

	$.ajax({
  		url: 'https://bn.wikisource.org/w/api.php',
  		data: {
    		format: 'json',
    		action: 'parse', 
			prop:"text", 
			page: Vis.baseDjvu.substring(0,Vis.baseDjvu.length-1).replace("পাতা:","নির্ঘণ্ট:")
   		},
   		dataType: 'jsonp' // this is the important one!
	}).done(function(data) {
  		var $html=$(".index-pagelist p",$((data.parse.text["*"]))); // modificata 28/12/2018
		$("a[title^='পাতা:']",$html).each(function() {              // idem
		$(this).children().filter("span").remove();

		// console.log($html);
		
		var href= decodeURIComponent($(this).attr("href"));
		if ($(this).attr("class")==="new")
			// Vis.lp[alert(href)/\/(\d+)&action/.exec($(this).attr("href"))[1]*1]=$.trim($(this).text());
			Vis.lp[convertEnglishNumber(href.substring(href.lastIndexOf('/') + 1))*1]=$.trim($(this).text());
		else
			Vis.lp[convertEnglishNumber(href.substring(href.lastIndexOf('/') + 1))*1]=$.trim($(this).text());
			// 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",start);
		mw.util.addPortletLink(
			'p-tb',
			"javascript:void(0)",
			'Visualizzatore',
			'Visualizzatore',
			'Visualizzatore'
		);
		$("#Visualizzatore").click(function() {start();});
		if (window.location.href.indexOf("vis=true")!==-1) start();
		if (mw.config.get("wgCanonicalNamespace")==="Index") $('<div class="mw-indicator" style="cursor: pointer" title="Read the book in text mode">'+
		'<img alt="Read the book in text mode" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/64/Android_Emoji_1f4d6.svg/40px-Android_Emoji_1f4d6.svg.png">'+
		'</div>').click(function() {start();}).prependTo(".mw-indicators");
}

/* conta il numero di occorrenze di stringa dentro testo*/
function count(testo, stringa) {
		n = 0;
		while (testo.indexOf(stringa) > -1) {
			n = n + 1;
			testo = testo.replace(stringa, "");
		}
		return n;
	}
	
 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;
	}
	
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;
	}
function convertOdiaNumber(number) {
	var input = String(number).split('');
	var mapData = {
		"0": "০",
		"1": "১",
		"2": "২",
		"3": "৩",
		"4": "৪",
		"5": "৫",
		"6": "৬",
		"7": "৭",
		"8": "৮",
		"9": "৯"
	};
	var output = '';
	var tempArray = [];
	for (var i = 0; i < input.length; i++) {
		tempArray.push(mapData[input[i]]);
	}
	output = tempArray.join('');
	return output;
}

function convertEnglishNumber(number) {
	var input = String(number).split('');
	var mapData = {
		"০": "0",
		"১": "1",
		"২": "2",
		"৩": "3",
		"৪": "4",
		"৫": "5",
		"৬": "6",
		"৭": "7",
		"৮": "8",
		"৯": "9"
	};
	var output = '';
	var tempArray = [];
	for (var i = 0; i < input.length; i++) {
		tempArray.push(mapData[input[i]]);
	}
	output = tempArray.join('');
	return output;
}