User:Seb35/ScreenViewer/Code

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- License WTFPL Seb35 - version 5.0 (November 7, 2011)-->
<!-- To test, read (in French) http://fr.wikipedia.org/wiki/Utilisateur:Seb35/Diaporama -->
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
<!--<link rel="stylesheet" type="text/css" href="jquery-ui.css" />
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>-->
<style type="text/css">
body { background-color:black; padding:0; margin:0; overflow:hidden; overflow-y:hidden; overflow-x:hidden; }
.screen { position:absolute; }
.status-screen { position:absolute; top:0px; width:3px; height:3px; border: 1px solid; }
#fadeouttime-plus, #fadeouttime-minus, #fadeintime-plus, #fadeintime-minus, #displaytime-plus, #displaytime-minus { 
padding-bottom: 0.2em;
padding-left: 0.6em;
padding-right: 0.6em;
padding-top: 0.2em;
}
#nbajax {
  font-size:5px;
  color:white;
  position:absolute;
  top: -2px;
  left: 0px;
}
</style>
<script type="text/javascript">

//////////////////////////////////////////////////// DEFINITION OF CONSTANTS ///////////////////////////////////////////////////////////////////

const wikilink = '\\[\\[(.*)\\]\\]';
const regex_wikilink = new RegExp( '^' + wikilink + '$' );

const dbwikisites = { 'wikimediafoundation': { sites: {

// Per-language projects
'w':    { sublanguage:true, name: 'wikipedia'   },
'wikt': { sublanguage:true, name: 'wiktionary'  },
's':    { sublanguage:true, name: 'wikisource'  },
'q':    { sublanguage:true, name: 'wikiquote'   },
'n':    { sublanguage:true, name: 'wikinews'    },
'b':    { sublanguage:true, name: 'wikibooks'   },
'v':    { sublanguage:true, name: 'wikiversity' },

// Multilingual projects
'species':         { language: 'en', name: 'species.wikimedia',   https:'species'         },
'commons':         { language: 'en', name: 'commons.wikimedia',   https:'commons'         },
'oldwikisource':   { language: 'en', name: 'wikisource'                                   },
'betawikiversity': { language: 'en', name: 'beta.wikiversity',    https:'betawikiversity' },
'incubator':       { language: 'en', name: 'incubator.wikimedia', https:'incubator'       },

// Redirects of per-language projects
'wiktionary':  'wikt:en',
'wikinews':    'n:en',
'wikiquote':   'q:en',
'wikisource':  's:en',
'wikipedia':   'w:en',
'wikibooks':   'b:en',
'wikiversity': 'b:en',

// Unique sites
'meta':     { language: 'en', name: 'meta.wikimedia'          },
'outreach': { language: 'en', name: 'outreach.wikimedia'      },
'nost':     { language: 'en', name: 'nostalgia.wikimedia'     },
'tenwiki':  { language: 'en', name: 'ten.wikipedia'           },
'testwiki': { language: 'en', name: 'test.wikipedia'          },
'wn2005':   { language: 'en', name: 'wikimania2005.wikimedia' },
'wm2006':   { language: 'en', name: 'wikimania2006.wikimedia' },
'wm2007':   { language: 'en', name: 'wikimania2007.wikimedia' },
'wm2008':   { language: 'en', name: 'wikimania2008.wikimedia' },
'wm2009':   { language: 'en', name: 'wikimania2009.wikimedia' },
'wm2010':   { language: 'en', name: 'wikimania2010.wikimedia' },
'wm2011':   { language: 'en', name: 'wikimania2011.wikimedia' },
'wm2012':   { language: 'en', name: 'wikimania2012.wikimedia' },
'wmania':   'wm2011'

}, rules: { 'name': { unique: '${name}.org', family: '${sublanguage}.${name}.org' },
            'page_http':  { unique: 'http://${name}.org/wiki/$1', family: 'http://${sublanguage}.${name}.org/wiki/$1' },
            'page_https': { unique: 'https://secure.wikimedia.org/wikipedia/${https|name}/wiki/$1', family: 'https://secure.wikimedia.org/${name}/${sublanguage}/wiki/$1' },
            'action_http':  { unique: 'http://${name}.org/w/index.php?title=$1', family: 'http://${sublanguage}.${name}.org/w/index.php?title=$1' },
            'action_https': { unique: 'https://secure.wikimedia.org/wikipedia/${https|name}/w/index.php?title=$1', family: 'https://secure.wikimedia.org/${name}/${sublanguage}/w/index.php?title=$1' },
            'api_http':  { unique: 'http://${name}.org/w/api.php?callback=?', family: 'http://${sublanguage}.${name}.org/w/api.php?callback=?' },
            'api_https': { unique: 'https://secure.wikimedia.org/wikipedia/${https|name}/w/api.php?callback=?', family: 'https://secure.wikimedia.org/${name}/${sublanguage}/w/api.php?callback=?' },
            'content_language': { unique: '${language}', family: '${sublanguage}' } } }
};

const wikisyntax_params = {
'^\\[\\[(.*)\\]\\]$': { 'get': '$1', 'set': { 'wikilink': { 'type': 'string' } } },
'^image$': { 'set': { 'options.image': { 'type': 'number', 'value': true } } },
'^random$': { 'set': { 'optionslist.random': { 'type': 'number', 'value': 1000 } } },
'^random=(\d*)$': { 'get': '$1', 'set': { 'optionslist.random': { 'type': 'number' } } },
'^anon$': { 'set': { 'options.people': { 'type': 'number', 'value': 0 } } },
'^anon$': { 'set': { 'options.people': { 'type': 'number', 'value': 1 } } },
'^bot$': { 'set': { 'options.bot': { 'type': 'boolean', 'value': false } } },
'^!bot$': { 'set': { 'options.bot': { 'type': 'boolean', 'value': true } } },
'^(\d*) *pages?$': { 'get': '$1', 'set': { 'options.nbdisplay': { 'type': 'number' }, 'options.nbtitles': { 'type': 'number' } } },
'^(\d*) *pages? *in *(\d*)?$': { 'set': { 'options.nbdisplay': { 'type': 'number', 'get': '$1' }, 'options.nbtitles': { 'type': 'number', 'get': '$2' } } },
'^diff$': { 'set': { 'options.diff': { 'type': 'number', 'value': 1 } } },
'^since *(\d*) *(seconds?|minutes?|hours?|days?)$': { 'get': '$1 $2', 'set': { 'options.since': { 'type': 'number' } } },
'^from *\\[\\[(.*)\\]\\]$': { 'get': '$1', 'set': { 'options.firstpage': { 'type': 'string' } } },
'^static$': { 'set': { 'type': { 'type': 'number', 'value': 4 } } },
'^live$': { 'set': { 'type': { 'type': 'number', 'value': 5 } } }
};

const global_options = {
	'display_time': { 'type': 'number', 'range': { 'min': 1, 'max': 1000 }, 'default': 50 },
	'fadein_time': { 'type': 'number', 'range': { 'min': 1, 'max': 1000 }, 'default': 20 },
	'fadeout_time': { 'type': 'number', 'range': { 'min': 1, 'max': 1000 }, 'default': 20 },
	'random_display': { 'type': 'boolean', 'default': false },
	'fullscreen_images': { 'type': 'number', 'range': { 'min': 0, 'max': 2 }, 'default': 2 },
	'border_size': { 'type':  'number', 'range': { 'min': 0, 'max': 99 }, 'default': 5 },
	'internet_available': { 'type': 'number', 'range': { 'min': 0, 'max': 2 }, 'default': 2 },
	'background_color': { 'type': 'string', 'default': 'black' },
	'number_frames': { 'type': 'number', 'range': { 'min': 3, 'max': 20 }, 'default': 3 },
	'show_commands': { 'type': 'number', 'range': { 'min': 0, 'max': 2 }, 'default': 1 }, 
	'show_loading': { 'type': 'number', 'range': { 'min': 0, 'max': 3 }, 'default': 3 },
	'use_https': { 'type': 'boolean', 'default': false },
	'language': { 'type': 'string', 'default': 'fr' }
};

const environment_variables_def = {
	'ajax_available': { 'type': 'boolean', 'default': true },
	'repeattimebuttons': { 'type': 'number', 'default': 50 },
	'repeattimebuttons_initial': { 'type': 'number', 'default': 500 }
};

const l10n_all = {
'en': {
	'screenviewer': 'ScreenViewer',
	'addressdiapo': 'Address of diaporama:',
	'demo': '(demo)',
	'diaporama': 'Diaporama:',
	'scenario': 'Scenario',
	'technique': 'Technique',
	'theming': 'Theming',
	'randomdiapo': 'Randomized diaporama:',
	'fullscreenimages': 'Fullscreen images:',
	'always': 'Always',
	'depending': 'Depending',
	'never': 'Never',
	'fadeouttime': 'Fadeout time:',
	'fadeintime': 'Fadein time:',
	'displaytime': 'Display time:',
	'internetavail': 'Internet is available:',
	'onlybeginning': 'Only at the beginning',
	'duringalldiapo': 'During all the diaporama',
	'numberofframes': 'Number of frames:',
	'increaseslow': '(increase if slow connection)',
	'sizeborder': 'Size of the border',
	'background': 'Background',
	'black': 'Black',
	'white': 'White',
	'ok': 'Ok'
},
'fr': {
	'screenviewer': 'ScreenViewer',
	'addressdiapo': 'Adresse du diaporama :',
	'demo': '(démo)',
	'diaporama': 'Diaporama :',
	'scenario': 'Scénario',
	'technique': 'Technique',
	'theming': 'Thème',
	'randomdiapo': 'Diaporama aléatoire :',
	'fullscreenimages': 'Images plein écran :',
	'always': 'Toujours',
	'depending': 'Selon',
	'never': 'Jamais',
	'fadeouttime': 'Temps d\'effacement :',
	'fadeintime': 'Temps d\'apparition :',
	'displaytime': 'Temps d\'affichage :',
	'internetavail': 'Internet est disponible :',
	'onlybeginning': 'Seulement au début',
	'duringalldiapo': 'Pendant tout le diaporama',
	'numberofframes': 'Nombre de cadres :',
	'increaseslow': '(augmenter pour les connexions lentes)',
	'sizeborder': 'Taille de la bordure :',
	'background': 'Fond :',
	'black': 'Noir',
	'white': 'Blanc',
	'ok': 'Ok'
}};

var deci_var = ['fadeouttime','fadeintime','displaytime'];
var maxsize_var = {'fadeouttime':4,'fadeintime':4,'displaytime':4,'nbmainscreens':2,'bordersize':2};

/////////////////////////////////////////////////////////// GLOBAL VARIABLES //////////////////////////////////////////////////////////////

var environment = {};

var l10n = {};

var wikisites_diapo = [];






//alert('*');

var global_index = 0;
var pages_text = '';
var page = 0;
var page2 = 0;
var pages = Array();
var current_screen = 0;
var number_screens = 3;
var loaded_screens = Array();
var history_addresses = Array();
//var history = Array();
//var option = '(?: *, *([ 0-9a-z=-]*(?:\\[\\[[^\\]]*]\\]\\][ 0-9a-z=-]*)?))?'; // note: should add '[' ']' and escape ',' in '[[]]'
//var wikilink_with_options = wikilink + option;// + option + option + option + option;
//var regex_wikilink_with_options = new RegExp( '^' + wikilink_with_options + ' *$' );
var changing_screen = false;
var c = 0;
var getnumberpx = new RegExp( '^(\d*)px$' );
//var repeattimebuttons = 50;
//var repeattimebuttons_initial = 500;
var interv;
var interv2;
var noclick = false;
var ajax_current = false;
var ajax_next = Array();
var currenttext = '';
var reserved_slots = 0;
var reserved_slots_from = number_screens;
var preloadajaxqueue = [];

var ajax_requestid = 0;
var ajax_parameters = {};
var nb_current_active_ajax = 0;
//var diapo_text = '* [[w:fr:G]]\n* [[w:fr:Catégorie:Lumière sur/Îles]], content, live, random, 3 pages\n* [[w:fr:Catégorie:AJAX]], content, static, random, 2 pages, from [[B]]\n';
//var diapo_text = '* [[w:fr:Catégorie:AJAX]], from [[B, h, g]], from [[ug,go]]\n';
//var diapo_text = '* [[w:fr:Special:RecentChanges]],content,live,2 pages\n';


var diapo_text = '* [[w:fr:Catégorie:Rennes]], content, live, random, 3 pages\n';


//var diapo_text = '=== Rennes ===\n* [[w:fr:Rennes]]\n* [[w:fr:Hôtel de Blossac]]\n* [[w:fr:Patrimoine architectural de Rennes]]\n* [[commons:File:Celina-ohio-grand-lake.jpg]]\n* [[w:fr:Parcs et jardins de Rennes]]\n* [[w:fr:Rennes Métropole]]\n* [[commons:File:Georges de La Tour 020.jpg]]\n* [[commons:File:La Tour.jpg]]\n* [[w:fr:Monuments historiques à Rennes]]\n* [[w:fr:Fichier:Champs Libres entrée.jpg]]\n* [[w:fr:Rock\'n Solex]]\n* [[w:fr:Les Champs Libres]]\n* [[w:fr:Ouest-France]]\n* [[w:fr:Fichier:TGV train in Rennes station DSC08944.jpg]]\n* [[w:fr:Catégorie:Rennes]]\n* [[w:fr:Catégorie:Rennes]], content, random, 6 pages\n* [[w:en:Museum of Fine Arts of Rennes]]\n* [[commons:File:Rennes - rempart romain - rue de Juillet.jpg]]\n* [[commons:File:Rennes Hôtel de Blossac (Mascaron).jpg]]';
//var diapo_text = '=== Rennes ===\n* [[w:fr:Rennes]]\n* [[w:fr:Hôtel de Blossac]]\n* [[w:fr:Patrimoine architectural de Rennes]]\n* [[commons:File:Celina-ohio-grand-lake.jpg]]\n* [[w:fr:Parcs et jardins de Rennes]]\n* [[w:fr:Rennes Métropole]]\n* [[commons:File:Georges de La Tour 020.jpg]]\n* [[commons:File:La Tour.jpg]]\n* [[w:fr:Monuments historiques à Rennes]]\n* [[w:fr:Fichier:Champs Libres entrée.jpg]]\n* [[w:fr:Rock\'n Solex]]\n* [[w:fr:Les Champs Libres]]\n* [[w:fr:Ouest-France]]\n* [[w:fr:Fichier:TGV train in Rennes station DSC08944.jpg]]\n* [[w:fr:Catégorie:Rennes]]\n* [[w:en:Museum of Fine Arts of Rennes]]\n* [[commons:File:Rennes - rempart romain - rue de Juillet.jpg]]\n* [[commons:File:Rennes Hôtel de Blossac (Mascaron).jpg]]';

//////////////////////////////////////////////////////////////// DEFINITION OF OBJECTS //////////////////////////////////////////////////////////

function Diaporama() {
	
	//*
	
	this.diaporama = [];
	this.history = null;
	
	//*/
}

Diaporama.prototype.analysis_wikitext = function( wikitext, diaporama_id ) {
	
	//*
	
	if( typeof wikitext !== 'string' ) return;
	
	// Get the special diporama if a diaporama name is specified
	if( typeof diaporama_id === 'number' ) {
		
		var i_title = diaporama_id;
		var re_titles = wikitext.match(/^=== *(.*) *===$/gm);
		if( re_titles && re_titles.length > 1 ) {
			
			if( i_title == re_titles.length-1 ) {
				
				var re1_title = new RegExp( re_titles[i_title]+'(?:\n.*)*' );
				var re_text = re1_title.exec(wikitext);
				wikitext = re_text[0].split('\n').slice(1).join('\n');
			}
			else {
				
				var re1_title = new RegExp( re_titles[i_title]+'(?:\n.*)*\n'+re_titles[i_title+1], '' );
				var re_text = re1_title.exec(wikitext);
				var array_text = re_text[0].split('\n');
				wikitext = array_text.slice(1,array_text.length-1).join('\n');
			}
		}
	}
	
	// Split into single lines
	var pages = wikitext.match( /^\* *(?:\[\[(.*)\]\](, *[ 0-9a-z=-]* *)*|file:\/\/(.*))$/gm );
	//alert(wikitext);
	//alert(pages);
	
	// Analyse each line
	for( var index=0; index<pages.length; index++ ) {
		
		this.diaporama[index] = new Diapo();
		
		// Separate different options by taking care about commas in wikilinks
		pages[index] = pages[index].replace( /^\* *(.*)$/, '$1' );
		var options = pages[index].split(',');
		for( var i=0; i<options.length; i++ ) {
			
			if( /\[\[/.test( options[i] ) && !/\]\]/.test( options[i] ) ) {
				
				for( var j=i+1; j<options.length; j++ ) {
					
					if( /\]\]/.test( options[j] ) ) {
						
						options[i] = options.slice( i, j+1 ).join(',');
						options.splice( i+1, j-i );
						break;
					}
				}
			}
		}
		for( var i=0; i<options.length; i++ ) options[i] = options[i].trim();
		//alert(options);
		
		// Populate the object
		for( var i=0; i<options.length; i++ ) {
			
			//alert( 'in analysis_wikitext1' );
			
			var value = undefined;
			
			for( param in wikisyntax_params )
				
				if( RegExp(param).test( options[i] ) )
					
					break;
			
			settings = wikisyntax_params[param];
			
			if( settings['get'] != undefined ) value = options[i].replace( RegExp(param), settings['get'] );
			
			for( key in settings['set'] ) {
				
				var s = key.split( '.' );
				
				if( this.diaporama[index][s[0]] === undefined ) this.diaporama[index][s[0]] = {};
				
				if( settings['set'][key]['get'] != undefined ) value = options[i].replace( param, settings['set'][key]['get'] );
				
				if( settings['set'][key]['hook'] != undefined ) value = settings['set'][key]['hook']( value );
				
				if( settings['set'][key]['value'] != undefined ) value = settings['set'][key]['value'];
				
				if( settings['set'][key]['type'] == 'number' ) value = Number(value);
				
				if( s.length == 1 ) this.diaporama[index][s[0]] = value;
				else if( s.length == 2 ) this.diaporama[index][s[0]][s[1]] = value;
				else alert('error line 370' );
			}
		}
		
		// Verify the consistency -> don’t verify ;)
		
		//display_object(this.diaporama[index]);
		// Set the title
		this.diaporama[index].set_diapo( this.diaporama[index].wikilink );
		//delete this.diaporama[index].wikilink;
	}
	
	$.each( this.diaporama, function(k1,v1) {
		
		//display_object(v1.page);
	});
	
	alert( 'end analysis_wikitext' );
	
	//*/
}

function Diapo( wikilink, type ) {
	
	//*
	
	this.page = wikilink !== undefined ? new Page( wikilink ) : null;
	this.type = type !== undefined ? type : null;
	
	this.url = null;
	this.legend = null;
	this.parent = null;
	this.display = true;
	this.list = null;
	this.options = { 'people': 2, 'bots': true, 'since': '7 days', 'diff': true, 'namespaces': false, 'firstpage': '', 'image': true, 'width': 0, 'height': 0 };
	this.optionslist = { 'nbchilds': 0, 'indexes': [], 'random': 0, 'typelive': null, 'nbdisplay': 10, 'nbtitles': 10, 'indexe': 0 };
	
	//*/
}

Diapo.prototype.set_diapo = function( wikilink, type ) {
	
	//*
	
	if( typeof wikilink === 'string' ) this.page = new Page( wikilink );
	else if( typeof wikilink === 'number' ) this.type = type;
	
	if( type !== undefined && typeof type === 'number' ) this.type = type;
	
	//display_object(this.page);
	//display_object(this.optionslist);
	
	//this.determine_type();
	
	//*/
}

Diapo.prototype.determine_type = function() {
	
	//*
	
	// Check and modify type
	
	this.url = this.page.get_page_url();
	
	if( this.page.namespacenumber == 6 && this.options.image ) {
		
		if( global_options.fullscreen_images != 0 ) {
		
			this.type = 1;
			this.load_image_size();
		}
		else {
			
			this.type = 0;
			this.options.image = false;
		}
	}
	
	else if( this.type == 4 || this.type == 5 ) {
		
		if( environment_variables.internet_available == 0 ) this.type = 0;
		if( environment_variables.internet_available == 1 ) this.type = 4;
		
		if( this.page.namespacenumber != 14 && !( this.page.namespacenumber == -1 && ['Recentchanges','Newpages','Log'].indexOf(this.page.pagename) >= 0 ) ) this.type = 0;
	}
	
	else alert( 'error line 174' );
	
	
	// Download static lists
	
	if( this.type == 4 ) {
		
		this.load_static_list();
	}
	
	//*/
}

Diapo.prototype.load_image_size = function() {
	
	//*
	
	var self = this;
	
	if( self.type != 1 ) return;
	
	AjAX.niew();
	$.getJSON( self.page.project.api_url, {
		action: 'query',
		prop: 'imageinfo',
		iiprop: 'url|size|user',
		format: 'json'
	}, function(data) {
		
		$.each( data.query.pages, function( k1, v1 ) {
			
			if( !v1.imagerepository ) return;
			
			self.url    = v1.imageinfo[0].url;
			self.width  = Number(v1.imageinfo[0].width);
			self.height = Number(v1.imageinfo[0].height);
		});
		AjAX.done();
	});
	
	//*/
}

Diapo.prototype.load_category = function() {
	
	//*
	
	var api_parameters = {
		action: 'query',
		list: 'categorymembers',
		cmlimit: this.options.nbtitles,
		cmtitle: this.page.fullpagename
	};
	
	if( this.options.firstpage ) api_parameters.cmstartsortkey = this.options.firstpage;
	
	//AjAX.niew();
	$.getJSON( this.page.project.api_url, api_parameters, function(data) {
		/*
		var index = data.data.index;
		var project = diaporama[index].project;
		var isimage = diaporama[index].isimage;
		var pages_list = data.query.categorymembers;
		
		diaporama[index].nbtitles = pages_list.length;
		if( diaporama[index].nbdisplay > diaporama[index].nbtitles ) diaporama[index].nbdisplay = diaporama[index].nbtitles;
		diaporama[index].nbloaded = 0;
		
		$.each( data.query.categorymembers, function( k1, v1 ) {
			
			new Diapo
		for( var j=0; j<pages_list.length; j++ ) {
			
			var page = getNamespaceNumber( project, pages_list[j].title );
			var newpage = { type:-1, project:project, title:page[3], url:getURL(project,page[3],1) };
			
			if( page[0] == 6 && ( isimage || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) {
				
				newpage.type = 1;
				diaporama[index].list[diaporama[index].index] = newpage;
				getImageSize( true, index, diaporama[index].index );
			}
			else {
				
				newpage.type = 0;
				diaporama[index].list[diaporama[index].index] = newpage;
				diaporama[index].nbloaded++;
			}
			diaporama[index].index++;
		}
		
		//s='';for(var j=0;j<diaporama[index].nbtitles;j++)s+=diaporama[index].list[j].url+'\n';alert(s);
		
		diaporama[index].index = 0;
		if( diaporama[index].nbloaded == diaporama[index].nbtitles ) nbtreatedpages++;*/
	});
	
	//*/
}

function Page( wikilink ) {
	
	//*
	
	this.interwiki = null; // unique identifier
	
	this.project = null;    // of type Wikisite
	
	this.fullpagename = null; // namespace and pagename
	this.namespace = null;    // namespace name
	this.namespacenumber = null; // of type Number
	this.pagename = null;   // without namespace
	
	this.categories = null;
	this.interwikis = null;
	
	this.update_page( wikilink );
	
	//*/
}

Page.prototype.update_page = function( wikilink ) {
	
	//*
	
	this.project = Wikisite.get_from_wikilink( wikilink );
	this.interwiki = this.project.interwiki;
	
	if( this.project === null ) return;
	
	if( this.namespace+':'+this.pagename === this.fullpagename || (this.namespace == '' && this.pagename == this.fullpagename) || (this.project.namespaces === null && this.namespace !== null) ) return;
	
	this.fullpagename = this.project.get_page_from_wikilink( wikilink ).replace(/_/g,' ');
	
	if( this.project.namespaces !== null ) {
		
		re_wikititle = this.fullpagename.match(/^([^:]*):(.*)$/);
		
		if( re_wikititle !== null && re_wikititle.length == 3 ) {
			
			this.namespacenumber = this.project.namespaces[re_wikititle[1]];
			if( this.namespacenumber !== undefined ) {
				
				this.namespace = this.project.namespaces[this.namespacenumber];
				this.pagename = re_wikititle[2];
				this.namespacenumber = Number( this.namespacenumber );
				if( this.namespacenumber == -1 ) this.pagename = this.project.specialpages[this.pagename.replace(/ /g,'_')].replace(/_/g,' ');
				this.fullpagename = this.namespace + ':' + this.pagename;
			}
			else {
				this.namespace = '';
				this.namespacenumber = Number(this.project.namespaces['']);
				this.pagename = this.fullpagename;
			}
		}
		else {
			this.namespace = '';
			this.namespacenumber = Number(this.project.namespaces['']);
			this.pagename = this.fullpagename;
		}
	}
	else {
		
		var self = this;
		
		if( !/:/.test(self.fullpagename) ) {
			
			self.namespace = '';
			self.pagename = self.fullpagename;
		}
		
		AjAX.niew();
		$.getJSON( self.project.api_url, {
			action: 'query',
			prop: 'info',
			titles: self.fullpagename,
			format: 'json'
		}, function( data ) {
			$.each( data.query.pages, function( k1, v1 ) {
				self.fullpagename = v1.title;
				self.namespacenumber = v1.ns;
				if( self.namespace == '' ) self.pagename = self.fullpagename;
				//alert( 'after ' + self.namespacenumber + ' <' + self.namespace + '> ' + self.fullpagename + ' ' + self.pagename );
			});
			AjAX.done();
		});
	}
	
	//alert(this.namespacenumber);
	//alert(this.namespace);
	//alert(this.fullpagename);
	//alert(this.pagename);
	
	//if( this.categories === null ) this.load_categories();
	
	//alert( 'end update_page' );
	
	//*/
}

Page.prototype.load_categories = function() {
	
	//*
	
	// /!\ if problem with this, use:
	// var self = this; // and then self in the following in place of this
	
	AjAX.niew();
	$.getJSON( this.api_url, {
		action: 'parse',
		page: this.fullpagename,
		prop: 'categories|langlinks',
		format: 'json'
	}, function(data) {
		
		this.categories = [];
		this.interwikis = [];
		
		$.each( data.query.pages, function( k1, v1 ) {
			
			if( v1.langlinks !== undefined ) this.interwikis = v1.langlinks;
			
			$.each( v1.categories , function( k2, v2 ) {
				this.categories[this.categories.length] = v2.title;
			});
		});
		AjAX.done();
	});
	
	//*/
}

Page.prototype.get_page_url = function( action ) {
	
	//*
	
	return this.project.get_page_url( this.fullpagename, action );
	
	//*/
}

function Wikisite( wikilink ) {
	
	//*
	
	this.interwiki = null; // unique identifier
	
	this.name = null;
	this.use_https = false;
	this.page_url = null;
	this.action_url = null;
	this.api_url = null;
	this.page_http = null;
	this.page_https = null;
	this.action_http = null;
	this.action_https = null;
	this.api_http = null;
	this.api_https = null;
	this.content_language = null;
	this.namespaces = null;
	this.specialpages = null;
	this.difftime = 0;
	
	if( wikilink !== undefined ) { // From a full-qualified wikilink
		
		this.set_from_wikilink( wikilink );
	}
	
	//*/
}

Wikisite.get_from_wikilink = function( wikilink ) {
	
	//*
	
	// Get the supposed prefix et sublanguage
	var prefix = Wikisite.get_prefix_from_wikilink( wikilink );
	
	if( Wikisite.wikisites[prefix[2]] === undefined ) Wikisite.wikisites[prefix[2]] = new Wikisite( prefix );
	
	$.each(Wikisite.wikisites,function(k1,v1) {
		//display_object(v1);
	});
	return Wikisite.wikisites[prefix[2]];
	
	//*/
}

Wikisite.get_prefix_from_wikilink = Wikisite.prototype.get_prefix_from_wikilink = function( wikilink ) {
	
	//*
	
	// Variables used in this function
	var prefix, sublanguage, r;
	
	// Some constants
	const regex_wikilink = new RegExp( '^\\[\\[(.*)\\]\\]$' );
	const r_prefix = '[a-z0-9-]*';
	const r_sublanguage = '[a-z0-9-]{2,7}';
	
	// Sanitize for wikilinks in double bracket
	if( r = regex_wikilink.exec( wikilink ) ) wikilink = r[1];
	
	// Get the sublanguage if present
	if( r = new RegExp( '^(' + r_prefix + '):(' + r_sublanguage + '):(.*)$' ).exec( wikilink ) ) {
		
		prefix = r[1];
		sublanguage = r[2];
	}
	else if( r = new RegExp( '^(' + r_prefix + '):(.*)$' ).exec( wikilink ) ) {
		
		prefix = r[1];
		sublanguage = '';
	}
	else alert( 'error line 141' );
	
	return [ prefix, sublanguage, prefix+':'+sublanguage ];
	
	//*/
}

Wikisite.wikisites = {};

Wikisite.prototype.set_from_wikilink = function( wikilink ) {
	
	//*
	
	// Variables used in this function
	var prefix, organization, sublanguage, key, value, data, r, sites, s, var_def;
	
	// Get the prefix et sublanguage
	if( typeof wikilink === 'string' ) {
		
		r = this.get_prefix_from_wikilink( wikilink );
		prefix = r[0];
		sublanguage = r[1];
	}
	else if( typeof wikilink == 'object' && wikilink.length >= 2 ) {
		
		prefix = wikilink[0];
		sublanguage = wikilink[1];
	}
	
	// Get the informations related to the prefix
	for( organization in dbwikisites ) {
		
		sites = dbwikisites[organization].sites || organization;
		
		if( sites[prefix] === undefined ) continue;
		
		// Set the interwiki after some checks
		if( this.interwiki == null ) {
			
			this.interwiki = prefix;
			if( sites[prefix].sublanguage == true ) {
				
				this.interwiki += ':' + sublanguage;
				if( sublanguage == '' ) alert( 'error line 153' );
			}
		}
		
		// If this prefix is an alias
		if( typeof sites[prefix] == 'string' ) {
			
			alert( 'is_redirect' );
			this.get_from_wikilink( sites[prefix]+':' );
			break;
		}
		
		else {
			
			rules = dbwikisites[organization].rules || sites[prefix];
			
			for( key in rules ) {
				
				value = ( sublanguage ? rules[key].family : rules[key].unique ) || rules[key];
				
				// Replace the placeholders
				while( r = value.match( RegExp( '\\$\\{([a-z\|]*)\\}' ) ) ) {
					
					s = r[1].split( '|' );
					
					for( var i=0; i<s.length; i++ ) {
						
						var_def = s[i] == 'sublanguage' ? sublanguage : sites[prefix][s[i]];
						
						if( var_def !== undefined ) {
							
							value = value.replace( new RegExp( '\\$\\{'+r[1]+'\\}', 'g' ), var_def );
							break;
						}
					}
				}
				
				this[key] = value;
			}
			
			break;
		}
	}	
	
	if( !this.name || !this.page_http || !this.action_http || !this.api_http ) alert( 'error line 184' );
	
	this.set_https_status( false );
	
	this.download_siteinfo();
	
	//*/
}

Wikisite.prototype.set_https_status = function( toggle ) {
	
	//*
	
	if( environment.use_https.value && this.page_https && this.action_https && this.api_https ) this.use_https = !!toggle;
	else this.use_https = false;
	
	if( this.use_https ) {
		
		this.page_url = this.page_https;
		this.action_url = this.action_https;
		this.api_url = this.api_https;
	}
	else {
		
		this.page_url = this.page_http;
		this.action_url = this.action_http;
		this.api_url = this.api_http;
	}
	
	//*/
}

Wikisite.prototype.get_page_from_wikilink = function( wikilink ) {
	
	//*
	
	return new RegExp( '^' + this.interwiki + ':(.*)$' ).exec( wikilink )[1];
	
	//*/
}

Wikisite.prototype.get_page_url = function( title, action ) {
	
	//*
	
	title = title.replace( / /g, '_' );
	
	if( action === undefined ) return this.page_url.replace( /$1/, title );
	else return this.action_url.replace( /$1/, title ) + action;
	
	//*/
}

Wikisite.prototype.download_siteinfo = function() {
	
	//*
	
	var self = this;
	
	this.info_retrieved = false;
	
	AjAX.niew();
	$.getJSON( this.api_url, {
		action: 'query',
		meta: 'siteinfo',
		siprop: 'general|namespaces|namespacealiases|specialpagealiases',
		format: 'json'
	}, function(data) {
		
		self.siteinfo = {};
		self.namespaces = {};
		self.specialpages = {};
		
		var re_date = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.exec(data.query.general.time);
		var their_date = Date.UTC(Number(re_date[1]),Number(re_date[2])-1,Number(re_date[3]),Number(re_date[4]),Number(re_date[5]),Number(re_date[6]),0);
		var diff_date = Date.now()-their_date;
		
		self.siteinfo.difftime = diff_date;
		
		for( var nsnb in data.query.namespaces ) {
			
			star = data.query.namespaces[nsnb]['*'];
			canonical = data.query.namespaces[nsnb]['canonical'];
			
			self.namespaces[nsnb] = star;
			self.namespaces[star] = nsnb;
			self.namespaces[canonical] = nsnb;
		}
		
		for( var nsnb=0; nsnb<data.query.namespacealiases.length; nsnb++ )
			
			self.namespaces[data.query.namespacealiases[nsnb]['*']] = String(data.query.namespacealiases[nsnb].id);
		
		for( var nsnb=0; nsnb<data.query.specialpagealiases.length; nsnb++ ) {
			
			self.specialpages[data.query.specialpagealiases[nsnb].realname] = data.query.specialpagealiases[nsnb].realname;
			
			for( var alias=0; alias<data.query.specialpagealiases[nsnb].aliases.length; alias++ )
				
				self.specialpages[data.query.specialpagealiases[nsnb].aliases[alias]] = data.query.specialpagealiases[nsnb].realname;
		}
		
		AjAX.done();
	});
	
	//*/
}

function AjaX() {
	
	var self = this;
	
	this.current_ajax = 0;
	this.nextstep = null;
	
	this.niew = function() { self.current_ajax++; }
	this.done = function() {
		
		self.current_ajax--;
		if( self.current_ajax == 0 ) {
			
			//alert('launch event end ajax');
			this.nextstep();
		}
	}
}

var AjAX = new AjaX();

















/*
var check_parameters = {
  'title':       { 'type': 'string',          'mandatory': true                                                       }, // standalone
  'project':     { 'type': 'string',          'mandatory': true                                                       }, // standalone
  'type':        { 'type': 'number',          'mandatory': true, 'range': [0,1,2,3,4,5]                               }, // standalone
  'legend':      { 'type': 'string',          'mandatory': false                                                      }, // standalone
  'categories':  { 'type': 'array string',    'mandatory': false                                                      }, // standalone
  'parent':      { 'type': 'array string',    'mandatory': false                                                      }, // if is in a list, so not checkable in wikisyntax
  'url':         { 'type': 'string',          'mandatory': true,  'range': /^https?:\/\/.*$/                          }, // LAST parameter, depends from all others
  'display':     { 'type': 'boolean',         'mandatory': false                                                      }, // standalone
  'options':     { 'type': 'object',          'mandatory': false                                                      }, // 
  'list':        { 'type': 'array recursive', 'mandatory': false                                                      }, // if type ∈ {4,5}
  'optionslist': { 'type': 'object',          'mandatory': false                                                      }, // 
  'options.firstpage': { 'type': 'string',    'mandatory': false                                                      }, // 
  'options.people':    { 'type': 'number',    'mandatory': false, 'range': [0,1,2]                                    }, // 
  'options.bots':      { 'type': 'boolean',   'mandatory': false                                                      }, // 
  'options.since':     { 'type': 'string',    'mandatory': false, 'range': /^(\d*) (seconds?|minutes?|hours?|days?)$/ }, // standa
  'options.diff':      { 'type': 'boolean',   'mandatory': false                                                      }, // standalone, used if type==5 & typelivelist==1
  'options.namespace': { 'type': 'array string', 'mandatory': false                                                   }, // 
  'optionslist.typelivelist': { 'type': 'string',       'mandatory': false                                            }, // 
  'optionslist.random':       { 'type': 'number',       'mandatory': false, 'range': { 'min': 0, 'max': 1000 }        }, // 
  'optionslist.nbchilds':     { 'type': 'string',       'mandatory': false, 'range': { 'min': 0 }                     }, // 
  'optionslist.indexes':      { 'type': 'array number', 'mandatory': false,                                           }, // 
  'optionslist.size':         { 'type': 'number',       'mandatory': false, 'range': { 'min': 0 }                     }, // 
  'optionslist.index':        { 'type': 'number',       'mandatory': false, 'range': { 'min': 0 }                     }  // 
};

var deci_var = ['fadeouttime','fadeintime','displaytime'];
var maxsize_var = {'fadeouttime':4,'fadeintime':4,'displaytime':4,'nbmainscreens':2,'bordersize':2};
*/
/*

Loadflow:
* initScreenViewer
* displayDialog
* selectList
* downloadNamespaces
* readList
* initScreens

*/

//
// Initialize once
//
function initScreenViewer() {
	
	//*
	
	//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
	
	// Add environment variables
	for( var va in global_options ) {
		
		environment[va] = global_options[va]['default'];
	}
	for( var va in environment_variables_def ) {
		
		environment[va] = environment_variables_def[va]['default'];
	}
	
	AjAX.nextstep = disp;
	
	// Check the support of Ajax and availability of Internet
	if( !environment.internet_available ) environment_variables.ajax_available = false;
	if( !environment.ajax_available || !$.support.ajax ) {
		
		environment.ajax_available = false;
	}
	//alert('ajax='+environment.ajax_available+' '+$.support.ajax);
	
	$('body').append('<div id="nbajax">0</div>');
	//$('body').append('<div id="stopdiv" style="position:absolute; top:0px; left:0px; width:5px; height:100%;"></div>');
	//$('#stopdiv').mouseleave(function(){ var s='History:\n'; for( i=0; i<history_addresses.length; i++ ) s += history_addresses[i]+'\n'; alert(s); });
	
	// Launch the dialog
	//displayDialog();
	
	diap = new standalone_diaporama( window );
	
	diap.expert_dialog();
	
	//*/
}

function disp() {
	
	/*
	
	if( diap !== undefined && diap !== null && diap.diaporama !== undefined && diap.diaporama !== null && diap.diaporama.diaporama !== undefined && diap.diaporama.diaporama !== null ) {
		
		display_object( Wikisite.get_from_wikilink( 'w:fr:' ).namespaces );
		
		$.each( diap.diaporama.diaporama, function(k1,v1) {
			
			display_object(v1.page);
		});
	}
	
	alert('end disp');
	
	//*/
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////       DIALOG BOX      //////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



function standalone_diaporama( window ) {
	
	//this.self = this;
	this.window = window;
	this.wikitext = '';
	this.diaporama = null;
	
	//this.$ = $
	l10n = l10n_all[environment.language];
}

standalone_diaporama.prototype = {
	
	// Display the expert dialog box
	expert_dialog: function() {
		
		//*
		
		var self = this;
		
		// If dialog is already open
		if( $('#parametersdialog' ).length ) return;
		
		// Open the dialog
		$('body').append( '<div id="parametersdialog" /'+'>' );
		
		// If Ajax, ajax-load a distant page
		if( environment.ajax_available ) {
			
			$('#parametersdialog').append( l10n.addressdiapo+' <input type="text" id="addressdiapo" value="" /'+'> <a id="demo-ajax" style="cursor:pointer;color:#0645ad;">'+l10n.demo+'</a><br /'+'><br /'+'>');
			
			$('#addressdiapo').change(function() {
				
				var project = Wikisite.get_from_wikilink( $(this).val() );
				if( !project ) return;
				var page = project.get_page_from_wikilink( $(this).val() );
				
				$('#textdiapo').attr( 'disabled', 'disabled' );
				AjAX.niew();
				$.getJSON( project.api_url, {
					action: 'query',
					prop: 'revisions',
					titles: page,
					rvprop: 'content',
					format: 'json'
				}, function(data) {
					
					$.each( data.query.pages, function( k1, v1 ) {
						
						if( k1 == '-1' ) return;
						$('#textdiapo').val( v1.revisions[0]['*'] );
						self.setDialogText( v1.revisions[0]['*'] );
					});
					$('#textdiapo').removeAttr( 'disabled' );
					AjAX.done();
				});
			});
			
			$('#demo-ajax').click(function() {
				
				$('#addressdiapo').val('w:fr:Utilisateur:Seb35/Diaporama').trigger('change');
				//$('#choicesinput-UmVubmVz').delay(1000).val(['v3']);
				//$('#choices').trigger('change').trigger('click');
				//$('#choices label').delay(1010).attr('aria-pressed','false').removeClass('ui-state-active');
				//$('#choices label[for="choicesinput-UmVubmVz"]').delay(1020).attr('aria-pressed','true').addClass('ui-state-active');
			});
		}
		
		// Main textarea
		$('#parametersdialog').append(l10n.diaporama+' <textarea id="textdiapo" rows="5" style="width:100%;">'+diapo_text+'</textarea><br /'+'>');
		$('#textdiapo').keyup(function() {
			
			setDialogText( $(this).val() );
		});
		
		// When there is many diaporamas in one page
		$('#parametersdialog').append('<div id="choices" /'+'><br /'+'>');
		
		// Options
		var tabscenario = '';
		var tabtechnical = '';
		var tabtheming = '';
		var summary = '<ul><li><a href="#tabscenario">'+l10n.scenario+'</a></li><li><a href="#tabtechnical">'+l10n.technique+'</a></li><li><a href="#tabtheming">'+l10n.theming+'</a></li></ul>';
		
		// Checkbox israndom
		tabscenario += '<label>'+l10n.randomdiapo+' <input type="checkbox" id="israndom" /'+'></label><br /'+'>';
		
		// fullscreen
		tabscenario += l10n.fullscreenimages+' <input type="radio" id="fullscreenimages-2" name="fullscreenimages" value="2" /'+'><label for="fullscreenimages-always">'+l10n.always+' </label><input type="radio" id="fullscreenimages-1" name="fullscreenimages" value="1" /'+'><label for="fullscreenimages-depending">'+l10n.depending+' </label><input type="radio" id="fullscreenimages-0" name="fullscreenimages" value="0" /'+'><label for="fullscreenimages-never">'+l10n.never+'</label><br /'+'>';
		
		// Text fadeouttime
		tabscenario += l10n.fadeouttime+' <span id="fadeouttime" style="font-family:monospace;">'+(environment.fadeout_time<100?' ':'')+(environment.fadeout_time%10==0?(environment.fadeout_time/10)+'.0':(environment.fadeout_time/10))+'</span><span style="font-family:monospace;">s</span> <input type="button" id="fadeouttime-minus" style="font-size:50%; vertical-align:middle;" value="−" /'+'><input type="button" id="fadeouttime-plus" style="font-size:50%; vertical-align:middle;" value="+" /'+'><br /'+'>';
		
		// Text fadeintime
		tabscenario += l10n.fadeintime+' <span id="fadeintime" style="font-family:monospace;">'+(environment.fadein_time<100?' ':'')+(environment.fadein_time%10==0?(environment.fadein_time/10)+'.0':(environment.fadein_time/10))+'</span><span style="font-family:monospace;">s</span> <input type="button" id="fadeintime-minus" style="font-size:50%; vertical-align:middle;" value="−" /'+'><input type="button" id="fadeintime-plus" style="font-size:50%; vertical-align:middle;" value="+" /'+'><br /'+'>';
		
		// Text displaytime
		tabscenario += l10n.displaytime+' <span id="displaytime" style="font-family:monospace;">'+(environment.display_time<100?' ':'')+(environment.display_time%10==0?(environment.display_time/10)+'.0':(environment.display_time/10))+'</span><span style="font-family:monospace;">s</span> <input type="button" id="displaytime-minus" style="font-size:50%; vertical-align:middle;" value="−" /'+'><input type="button" id="displaytime-plus" style="font-size:50%; vertical-align:middle;" value="+" /'+'><br /'+'>';
		
		// Checkbox isinternet
		tabtechnical += '<label><input type="checkbox" id="isinternet" checked="checked" /'+'> '+l10n.internetavail+'</label><br /'+'>';
		$('#isinternet').change(function() {
			
			if( !$('#isinternet:checkbox:checked').val() ) { $('#lisinternetlive1,#lisinternetlive2').css( 'color', 'gray' ); $('#isinternetlive1,#isinternetlive2').attr('disabled','disabled'); }
			else { $('#lisinternetlive1,#lisinternetlive2').css( 'color', 'black' ); $('#isinternetlive1,#isinternetlive2').removeAttr('disabled'); }
		});
		
		// Checkbox isajax
		tabtechnical += '    <label id="lisinternetlive1"><input type="radio" id="isinternetlive1" name="isinternetlive" value="false" /'+'> '+l10n.onlybeginning+'</label><br /'+'>';
		tabtechnical += '    <label id="lisinternetlive2"><input type="radio" id="isinternetlive2" name="isinternetlive" value="true" checked="checked" /'+'> '+l10n.duringalldiapo+'</label><br /'+'>';
		
		
		// Text nbmainscreens
		tabtechnical += l10n.numberofframes+' <span id="nbmainscreens" style="font-family:monospace;">'+(environment.number_frames<10?' ':'')+environment.number_frames+'</span> <input type="button" id="nbmainscreens-minus" style="font-size:50%; vertical-align:middle;" value="−" /'+'><input type="button" id="nbmainscreens-plus" style="font-size:50%; vertical-align:middle;" value="+" /'+'> <small>'+l10n.increaseslow+'</small><br /'+'>';
		
		// Text bordersize
		tabtheming += l10n.sizeborder+' <span id="bordersize" style="font-family:monospace;">'+(environment.border_size<10?' ':'')+environment.border_size+'</span> px <input type="button" id="bordersize-minus" style="font-size:50%; vertical-align:middle;" value="−" /'+'><input type="button" id="bordersize-plus" style="font-size:50%; vertical-align:middle;" value="+" /'+'><br /'+'>';
		//tabtheming += l10n.sizeborder+' <input type="text" id="bordersize" value="5" maxlength="2" size="2" /'+'> px<br /'+'>';
		
		// Text backgroundtype
		tabtheming += l10n.background+'<br /'+'>';
		tabtheming += '    <input type="radio" name="backgroundtype" id="backgroundtype-black" value="black" checked="checked" /'+'><label for="backgroundtype-black"> '+l10n.black+'</label><br /'+'>';
		tabtheming += '    <input type="radio" name="backgroundtype" id="backgroundtype-white" value="white" /'+'><label for="backgroundtype-white"> '+l10n.white+'</label><br /'+'>';
		//tabtheming += '    <input type="radio" name="backgroundtype" id="backgroundtype-color" value="color" /'+'><label for="backgroundtype-color"> Color: </label><input type="text" name="backgroundcolor" id="backgroundcolor" value="" disabled="disabled" /'+'><br /'+'>';
		
		$('#parametersdialog').append('<div id="tabs">'+summary+'<div id="tabscenario">'+tabscenario+'</div><div id="tabtechnical">'+tabtechnical+'</div><div id="tabtheming">'+tabtheming+'</div></div>');//alert('*');
		$('#tabs').tabs();
		$('input:radio[name=fullscreenimages]').val( [ environment.fullscreen_images ] );
		
		//alert((0.2+0.1));
		//alert((2.0-0.1));
		//alert((2.0-0.1-0.1));
		//alert((2.0-0.1-0.1-0.1));
		//note this isn't 1.7 so I cannot use directly floating numbers even for a simple operation like that.
		
		//$('#fadeouttime-minus,#fadeouttime-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { display_object(this); display_object(e);} );
		$('#fadeouttime-minus,#fadeouttime-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { self.setter_timing(e); } );
		$('#fadeintime-minus,#fadeintime-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { self.setter_timing(e); } );
		$('#displaytime-minus,#displaytime-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { self.setter_timing(e); } );
		$('#nbmainscreens-minus,#nbmainscreens-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { self.setter_timing(e); } );
		$('#bordersize-minus,#bordersize-plus').button().bind( 'mousedown mouseup mouseleave click', function(e) { self.setter_timing(e); } );
		
		$('#fadeouttime').click( function(e) { self.direct_setter_timing(e); } );
		$('#fadeintime').click( function(e) { self.direct_setter_timing(e); } );
		$('#displaytime').click( function(e) { self.direct_setter_timing(e); } );
		$('#nbmainscreens').click( function(e) { self.direct_setter_timing(e); } );
		$('#bordersize').click( function(e) { self.direct_setter_timing(e); } );
		
		$('#isinternet').change(function() {
			
			if( !$('#isinternet:checkbox:checked').val() ) { $('#lisinternetlive1,#lisinternetlive2').css( 'color', 'gray' ); $('#isinternetlive1,#isinternetlive2').attr('disabled','disabled'); }
			else { $('#lisinternetlive1,#lisinternetlive2').css( 'color', 'black' ); $('#isinternetlive1,#isinternetlive2').removeAttr('disabled'); }
		});
		//$('input[name=backgroundtype]').change(function() {
		//	
		//	if( $('input:radio[name=backgroundtype]:checked').val() != 'color' ) $('#backgroundcolor').attr('disabled','disabled');
		//	else $('#backgroundcolor').removeAttr('disabled').focus();
		//});
		
		$('#parametersdialog').dialog( { buttons: [ { text: l10n.ok, click: function() { self.create_diaporama_from_expert_dialog(); } } ], title: l10n.screenviewer, minWidth: 600, closeOnEscape: false } );
		
		//*/
	},
	
	//
	// Timers for parameters, mouse-related
	//
	setter_timing: function( event, down ) {
		
		//*
		
		var self = this;
		
		var variab;
		var id = event.target.id.replace( /^(.*)-.*$/, '$1' );
		var plus = true;
		if( event.target.id.indexOf('minus') >= 0 ) plus = false;
		
		if( down == undefined ) {
			
			if( event.type == 'mousedown' ) down = environment.repeattimebuttons_initial;
			else if( event.type == 'mouseup' ) { down = 0; noclick = true; }
			else if( event.type == 'mouseleave' ) down = 0;
			else if( event.type == 'click' ) {
				
				if( noclick ) { noclick = false; return; }
				noclick = false;
				down = -1;
			}
		}
		else if( down != 0 ) down = environment.repeattimebuttons;
		
		if( down == 0 ) {
			
			clearTimeout( interv );
			return;
		}
		
		if( id == 'fadeouttime' ) {
			
			if( !plus && environment.fadeout_time <= 1 ) { self.setter_timing(event,0); return; }
			if( plus ) environment.fadeout_time += 1;
			else environment.fadeout_time -= 1;
			variab = environment.fadeout_time;
		}
		else if( id == 'fadeintime' ) {
			
			if( !plus && environment.fadein_time <= 1 ) { self.setter_timing(event,0); return; }
			if( plus ) environment.fadein_time += 1;
			else environment.fadein_time -= 1;
			variab = environment.fadein_time;
		}
		else if( id == 'displaytime' ) {
			
			if( !plus && environment.display_time <= 1 ) { self.setter_timing(event,0); return; }
			if( plus ) environment.display_time += 1;
			else environment.display_time -= 1;
			variab = environment.display_time;
		}
		else if( id == 'nbmainscreens' ) {
			
			if( !plus && environment.number_frames <= 3  ) { self.setter_timing(event,0); return; }
			if(  plus && environment.number_frames >= 20 ) { self.setter_timing(event,0); return; }
			if( plus ) environment.number_frames += 1;
			else environment.number_frames -= 1;
			variab = environment.number_frames;
		}
		else if( id == 'bordersize' ) {
			
			if( !plus && environment.border_size <= 0  ) { self.setter_timing(event,0); return; }
			if(  plus && environment.border_size >= 99 ) { self.setter_timing(event,0); return; }
			if( plus ) environment.border_size += 1;
			else environment.border_size -= 1;
			variab = environment.border_size;
		}
		
		if( deci_var.indexOf(id) >= 0 ) $('#'+id).empty().text((variab<100?' ':'')+(variab%10==0?(variab/10)+'.0':(variab/10)));
		else $('#'+id).empty().text((variab<10?' ':'')+variab);
		
		if( down > 0 ) interv = setTimeout( self.setter_timing, down, event, down );
		
		//*/
	},
	
	// Timers for parameters, direct-editing-related
	direct_setter_timing: function( event ) {
		
		//*
		
		var self = this;
		
		var caller = event.target;
		var caller_id = caller.id;
		
		var var_var = {'fadeouttime':environment.fadeout_time,'fadeintime':environment.fadein_time,'displaytime':environment.display_time,'nbmainscreens':environment.number_frames,'bordersize':environment.border_size};
		var old_text = $(caller).text();
		
		$(caller).empty().append('<input type="text" id="'+caller_id+'-text" size="'+maxsize_var[caller_id]+'" maxlength="'+maxsize_var[caller_id]+'" style="font-size:70%; vertical-align:middle;" value="'+var_var[caller_id]+'" /'+'>').unbind();
		if( deci_var.indexOf(caller_id) >= 0 ) $(caller).append(' d');
		$('#'+caller_id+'-minus,#'+caller_id+'-plus').css('visibility','hidden');
		$('#'+caller_id+'-text').focus().keydown(function(e) {
			
			if( e.which == 27 ) {
				
				$(caller).empty().text(old_text);
				$('#'+caller_id+'-minus,#'+caller_id+'-plus').css('visibility','visible');
				$(caller).click(self.direct_setter_timing);
			}
			
			if( e.which != 13 ) return;
			$(this).trigger('change');
		
		}).focusout(function(){
			
			$(this).trigger('change');
		
		}).change(function() {
			
			var variab;
			var newval = Number($(this).val());
			
			if( $(this).val() && ( (newval>=3&&caller_id=='nbmainscreens') || (newval>=1&&(caller_id=='fadeouttime'||caller_id=='fadeinttime'||caller_id=='displaytime')) || (newval>=0&&caller_id=='bordersize') ) && ( (newval<=20&&caller_id=='nbmainscreens') || (newval<=99&&caller_id=='bordersize') || (caller_id=='fadeouttime'||caller_id=='fadeintime'||caller_id=='displaytime') ) && Math.floor(newval) == newval ) {
				
				if( caller_id == 'fadeouttime' ) variab = environment.fadeout_time = newval;
				else if( caller_id == 'fadeintime' ) variab = environment.fadein_time = newval;
				else if( caller_id == 'displaytime' ) variab = environment.display_time = newval;
				else if( caller_id == 'nbmainscreens' ) variab = environment.number_frames = newval;
				else if( caller_id == 'bordersize' ) variab = environment.border_size = newval;
				
				if( deci_var.indexOf(caller_id) >= 0 ) $(caller).empty().text((variab<100?' ':'')+(variab%10==0?(variab/10)+'.0':(variab/10)));
				else $(caller).empty().text((variab<10?' ':'')+variab);
			}
			else $(caller).empty().text(old_text);
			
			$('#'+caller_id+'-minus,#'+caller_id+'-plus').css('visibility','visible');
			$(caller).click(self.direct_setter_timing);
		});
		
		//*/
	},
	
	//
	// Set the text in the dialog box
	//
	setDialogText: function( text ) {
		
		//*
		
		var self = this;
		
		//alert('beg setdialogtex');
		if( text == self.wikitext ) return;
		else self.wikitext = text;
		
		re_titles = text.match(/^===(.*)===$/gm);
		
		for( var i=0; re_titles && i<re_titles.length; i++ ) {
			
			re_titles[i] = re_titles[i].replace( /^===(.*)===$/, '$1' ).trim();
			if( /=/.exec( re_titles[i] ) || !re_titles[i] ) re_titles.splice( i, 1 );
		}
		
		if( re_titles && re_titles.length > 1 ) {
			
			// Get old value to replace this value after treatment
			var oldvalue = $('input:radio[name=choicesinput]:checked').attr('id');
			if( oldvalue != undefined ) oldvalue = oldvalue.replace( /^choicesinput-(.*)-\d*$/, '$1' );
			
			// First: with radio buttons
			$('#choices').empty();
			var choices = '<br /'+'>';
			var nbchecked = 0;
			var doubles = Array();
			
			for( var i=0; i<re_titles.length; i++ ) {
				
				choices += '<input type="radio" name="choicesinput" id="choicesinput-'+btoa(re_titles[i])+'-'+i+'" value="'+i+'"';
				if( btoa(re_titles[i]) == oldvalue ) { choices += ' checked="checked"'; nbchecked++; }
				choices +=  '/'+'><label for="choicesinput-'+btoa(re_titles[i])+'-'+i+'"> '+re_titles[i]+'</label>';
				
				if( re_titles.indexOf( re_titles[i] ) < i && doubles.indexOf( re_titles[i] ) == -1 ) doubles.push( re_titles[i] );
			}
			
			if( nbchecked >= 2 ) choices = choices.replace( / checked="checked"/g, '' );
			
			$('#choices').append(choices);
			$('#choices').buttonset();
			
			$( "#parametersdialog" ).dialog( 'option', 'position', 'center' );
			
			if( doubles.length > 0 ) {
				
				var labs = $('#choices label');
				for( var i=0; i<doubles.length; i++ ) {
					
					for( var j=0; j<labs.length; j++ ) {
						
						if( labs.eq(j).text() == ' '+doubles[i] ) labs.eq(j).css( 'color', 'red' );
					}
				}
			}
			
			// Second: with menu (jQueryUI 1.9)
			//   var choices = '<ul id="choicesinput">';
			//   for( i=0; i<re_titles.length; i++ ) {
			//   	
			//   	re2_title = re_titles[i].match(/^===(.*)===$/);
			//   	choices += '<li id="choicesinput'+i+'"><a href="#">'+re2_title[1].trim()+'</a></li>';
			//   }
			//   choices += '</ul>';
			//   $('#choices').append(choices);
			//   $('#choicesinput').menu({
			//   	select: function(event, ui) { alert('o'); }
			//   });
			//   $('#displayChoices').dialog();
		}
		else {
			
			$('#choices').empty();
			$('#parametersdialog' ).dialog( 'option', 'position', 'center' );
		}
		//alert('end setdialogtex');
		//*/
	},
	
	create_diaporama_from_expert_dialog: function() {
		
		//*
		
		var self = this;
		
		self.wikitext = $('#textdiapo').val();
		
		self.diaporama_id = Number($('input:radio[name=choicesinput]:checked').val());
		
		// Scenario
		environment.fullscreen_images = Number($('input:radio[name=fullscreenimages]:checked').val());
		
		//environment.fadeout_time = Number($('#fadeouttime').val());
		//environment.fadein_time = Number($('#fadeintime').val());
		//environment.display_time = Number($('#displaytime').val());
		
		// Technique
		if( !$('#isinternet:checkbox:checked').val() ) environment.internet_available = false;
		if( !environment.internet_available ) environment.ajax_available = false;
		else environment.ajax_available = true;
		//setFrames(number_screens);
		
		// Theming
		//bordersize = Number( $('#bordersize').val() );
		
		environment.background_color = $('input:radio[name=backgroundtype]:checked').val();
		
		//if( environment.color == 'black' ) environment.background_color = 'black';
		//else if( color == 'white' ) environment.background_color = 'white';
		//else if( color == 'color' ) background_color= $('#backgroundcolor').val();
		
		$('body').css( 'background-color', environment.background_color );
		
		self.diaporama = new Diaporama();
		
		self.diaporama.analysis_wikitext( self.wikitext, self.diaporama_id );
		
		//display_object(self.diaporama);
		
		//alert( 'end create_diaporama_from_expert_dialog' );
	}
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////       READ DIAPORAMA      ////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Read the list to download appropriate namespaces
 */
function analyze_syntax( pages ) {
	
	//*
	
	for( var index=0; index<pages.length; index++ ) {
		
		diaporama[index] = clone( default_page );
		
		// Separate different options by taking care about commas in wikilinks
		pages[index] = pages[index].replace( /^\* *(.*)$/, '$1' );
		var options = pages[index].split(',');
		for( var i=0; i<options.length; i++ ) {
			
			if( /\[\[/.test( options[i] ) && !/\]\]/.test( options[i] ) ) {
				
				for( var j=i+1; j<options.length; j++ ) {
					
					if( /\]\]/.test( options[j] ) ) {
						
						options[i] = options.slice( i, j+1 ).join(',');
						options.splice( i+1, j-i );
						break;
					}
				}
			}
		}
		for( var i=0; i<options.length; i++ ) options[i] = options[i].trim();
		

		// Populate the object
		for( var i=0; i<options.length; i++ ) {
			
			var value = undefined;
			
			for( param in wikisyntax_params )
				
				if( param.test( options[i] ) )
					
					break;
			
			setting = wikisyntax_params[param];
			
			if( settings['get'] != undefined ) value = options[i].replace( param, settings['get'] );
			
			for( key in settings['set'] ) {
				
				var s = key.split( '.' );
				var k = diaporama[s[0]];
				
				for( var j=0; j<s.length-1; j++ ) {
					
					if( k == undefined ) k = {};
					k = k[s[0]];
				}
				
				if( settings['set'][key]['get'] != undefined ) value = options[i].replace( param, settings['set'][key]['get'] );
				
				if( settings['set'][key]['hook'] != undefined ) value = settings['set'][key]['hook']( value );
				
				if( settings['set'][key]['value'] != undefined ) value = settings['set'][key]['value'];
				
				if( settings['set'][key]['type'] == 'number' ) value = Number(value);
			}
		}
		
		// Verify the consistency -> don’t verify ;)
		
		
		
		
		
		var wikisyntax = clone( wikisyntax_parameters );
		var check_params = [];
		var my_params = {};
		
		for( param in wikisyntax_parameters ) {
			
			my_params[param] = { treated:false, chainload:[] };
		}
		
		// Construct the resulting array
		for( var i=0; i<options.length; i++ ) {
			
			for( var param in my_params ) {
				
				alert( options[i] + ' ' + param );
				
				// Only treat untreated parameters
				if( my_params[param].treated ) continue;
				
				// Load the chain
				parameter = wikisyntax_parameters;
				for( var i=0; i<my_params[param].chainload.length; i++ ) {
					
					parameter = parameter[my_params[param].chainload[i].p]['result'][my_params[param].chainload[i].v];
				}
				
				// Only treat wikitext parameters
				if( parameter[param].load != 'wikitext' ) continue;
				
				// Check mandatory syntax parameters
				if( parameter[param].type == undefined ) alert( 'error line 83' );
				
				//alert( (parameter[param].type) + ' && ' + (parameter[param].regex instanceof Array) + ' && ' + (parameter[param].regex.length) + ' && ' + (parameter[param].regex[0] instanceof String) + ' && ' + (parameter[param].regex[0] instanceof RegExp) + ' && ' + (parameter[param].regex[1] instanceof String) + ' && ' + (parameter[param].regex) );
				alert('type='+parameter[param].type);
				//console.log( "param = %s, parameter = %o", param, parameter );
				
				alert(parameter.toString());
				
				// First case: boolean
				if( parameter[param].type == 'boolean' ) {
					alert('here');
					var r;
					
					//console.log(parameter[param].regex);
					alert(parameter[param].regex);
					
					if( parameter[param].regex != undefined ) {
						
						if( parameter[param].regex instanceof RegExp ) r = parameter[param].regex;
						else r = new RegExp( parameter[param].regex );
					}
					alert(r);
					if( r != undefined && r.test( options[i] ) ) diaporama[index][param] = true;
					else diaporama[index][param] = false;
				}
				
				// Second case: string
				else if( (parameter[param].type == 'string' || parameter[param].type == 'number') && (parameter[param].regex instanceof Array) && (parameter[param].regex.length == 2) ) {
					
					var r;
					
					alert(typeof(parameter[param].regex[0]));
					if( typeof(parameter[param].regex[0]) == "string" ) r = new RegExp( parameter[param].regex[0] );
					else r = parameter[param].regex[0];
					
					if( r.test( options[i] ) ) diaporama[index][param] = options[i].replace( r, parameter[param].regex[1] );
					else if( parameter[param]['default'] != undefined ) diaporama[index][param] = parameter[param]['default'];
					
					if( parameter[param].type == 'number' ) diaporama[index][param] = new Number(diaporama[index][param]);
				}
				
				// Third case: perhaps there is a hook
				else if( parameter[param].hook != undefined );
				
				// Fourth case: error
				else alert( 'error line 108' );
				
				// If there is a hook
				if( parameter[param].hook != undefined ) diaporama[index][param] = parameter[param].hook( index, param, options, diaporama[index][param] );
				
				// Check limits
				if( parameter[param].type == 'number' ) check_params[check_params.length] = param;
				
				// If there is result and this result add new syntax parameters
				if( parameter[param].result != undefined ) {
					
					if( parameter[param].result[diaporama[index][param]] != undefined ) {
						
						var new_chainload = [];
						for( var i=0; i<my_params[param].chainload.length; i++ ) new_chainload[i] = clone(my_params[param].chainload[i]);
						my_params[param].chainload[my_params[param].chainload.length] = { p:param, v:diaporama[index][param] };
						
						for( var new_param in parameter[param].result[diaporama[index][param]] ) my_params[new_param] = { treated:false, chainload:new_chainload };
					}
				}
				
				my_params[param].treated = true;
			}
		}
		
		alert( '6 instanceof Number' );
		alert( new Number(5) instanceof Number );
		
		
		// Check limits
		for( i=0; i<check_params.length; i++ ) {
		
			if( parameter[check_params[i]].type == 'number' ) {
				
				var mini = parameter[check_params[i]].min;
				var maxi = parameter[check_params[i]].max;
				
				if( /*typeof(mini) == 'String' &&*/ diaporama[index][check_params[i]][mini] != undefined && (diaporama[index][check_params[i]][mini] instanceof Number) ) mini = diaporama[index][check_params[i]][mini];
				else /*if( typeof(mini) == 'String' )*/ alert( 'error line 137' );
				
				if( /*typeof(maxi) == 'String' &&*/ diaporama[index][check_params[i]][maxi] != undefined && (diaporama[index][check_params[i]][maxi] instanceof Number) ) maxi = diaporama[index][check_params[i]][maxi];
				else /*if( typeof(maxi) == 'String' )*/ alert( 'error line 140' );
				
				if( mini != undefined && diaporama[index][check_params[i]] < mini ) alert( 'error line 142' );
				if( maxi != undefined && diaporama[index][check_params[i]] > maxi ) alert( 'error line 143' );
			}
		}
		
		// Add default and check missing parameters
		for( param in wikisyntax ) {
			
			if( parameter[param].load != 'wikitext' ) continue;
			
			if( parameter[param].treated == false ) {
				
				if( parameter[param]['default'] != undefined ) {
					
					diaporama[index][param] = parameter[param]['default'];
					parameter[param].treated = true;
				}
				else alert( 'error line 155' );
			}
		}
		
		switch( diaporama[index].type ) {
			
			case 0: get_wikisyntax_main( index, param, options ); break;
			case 1: get_wikisyntax_image( index, param, options ); break;
			case 2: get_wikisyntax_category( index, param, options ); break;
			case 3: get_wikisyntax_rc( index, param, options ); break;
		}
		
	}
	
	//*/
}

function post_analysis_syntax() {
	
	//*
	
	
	
	//*/
}

function get_wikisyntax_title( value ) {
	
	//*
	
	var link = getProject( value, 0 );
	value = getNamespaceNumber( link[0], link[1] )[3];
	
	return value;
	
	//*/
}

function get_wikisyntax_project( value ) {
	
	//*
	
	var link = getProject( value, 0 );
	value = link[0];
	
	return value;
	
	//*/
}

function get_wikisyntax_type( index, param, options, value ) {
	
	//*
	
	var namespace = getNamespaceNumber( diaporama[index].project, diaporama[index].title )[0];
	var partialtitle = getNamespaceNumber( diaporama[index].project, diaporama[index].title )[3];
	
	if( namespace == 6 && ( options.indexOf('image') >= 0 || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) value = 1;
	
	else if( namespace == 14 && options.indexOf('content') >= 0 && ( ajax_initial || (ajax_live && options.indexOf('live') >= 0) ) ) value = 2;
	
	else if( namespace == -1 && (['Recentchanges','Newpages','Log'].indexOf(partialtitle) >= 0) && options.indexOf('content') >= 0 && ( ajax_initial || (ajax_live && options.indexOf('live') >= 0) ) ) value = 3;
	
	else alert( 'error line 174' );
	
	return value;
	
	//*/
}

function get_wikisyntax_image( index, options ) {
	
	//*
	if( !ajax ) return;
	
	diaporama[index].api = '&action=query&prop=imageinfo&iiprop=url|size|user';
	
	initial_ajax_queries++;
	
	load_ajax_image( index, diaporama[index] );
	
	//*/
}

function load_ajax_image( index, page ) {
	
	//*
	var api_url = getURL( diaporama[index].project, getNamespaceNumber( diaporama[index].project, page.title )[3], 2, {index:index,page:page} ) + page.api;
	
	$.getJSON( api_url, function(data) {
		
		getAfterAjax(data);
		
		var index = data.data.index;
		var page = data.data.page;
		var pages_list = data.query.pages;
		
		for( var t in pages_list ) {
			
			if( !pages_list[t].imagerepository ) break;
			
			page.url    = pages_list[t].imageinfo[0].url;
			page.url2   = pages_list[t].imageinfo[0].url.replace( /^.*\/[0-9a-f]\/[0-9a-f]{2}\/(.*)$/, '$1' );
			page.width  = Number(pages_list[t].imageinfo[0].width);
			page.height = Number(pages_list[t].imageinfo[0].height);
			
			break;
		}
		
		if( initial_ajax_queries > 0 ) initial_ajax_queries--;
		if( initial_ajax_queries == 0 ) post_analysis_syntax();
	});
	
	//*/
}

function get_wikisyntax_category( index, param, options ) {
	
	//*
	if( !ajax ) return;
	
	diaporama[index].api =
	      '&action=query'
	    + '&list=categorymembers'
	    + '&cmlimit='+diaporama[index].nbtitles
	    + '&cmtitle='+encodeURIComponent(diaporama[index].title.replace(/ /g,'_'))
	    + (diaporama[index].from?'&cmstartsortkey='+encodeURIComponent(diaporama[index].from.replace(/ /g,'_')):'');
	
	if( diaporama[index].live == true ) return;
	
	initial_ajax_queries++;
	
	load_ajax_category( index, diaporama[index] );
	
	//*/
}

function load_ajax_category( index, page ) {
	
	//*
	$.getJSON( getURL(diaporama[index].project,'',4,{index:index,page:page}) + page.api, function(data) {
		
		getAfterAjax(data);
		
		var index = data.data.index;
		var project = diaporama[index].project;
		var isimage = diaporama[index].isimage;
		var pages_list = data.query.categorymembers;
		
		diaporama[index].nbtitles = pages_list.length;
		if( diaporama[index].nbdisplay > diaporama[index].nbtitles ) diaporama[index].nbdisplay = diaporama[index].nbtitles;
		diaporama[index].nbloaded = 0;
		
		for( var j=0; j<pages_list.length; j++ ) {
			
			var page = getNamespaceNumber( project, pages_list[j].title );
			var newpage = { type:-1, project:project, title:page[3], url:getURL(project,page[3],1) };
			
			if( page[0] == 6 && ( isimage || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) {
				
				newpage.type = 1;
				diaporama[index].list[diaporama[index].index] = newpage;
				getImageSize( true, index, diaporama[index].index );
			}
			else {
				
				newpage.type = 0;
				diaporama[index].list[diaporama[index].index] = newpage;
				diaporama[index].nbloaded++;
			}
			diaporama[index].index++;
		}
		
		//s='';for(var j=0;j<diaporama[index].nbtitles;j++)s+=diaporama[index].list[j].url+'\n';alert(s);
		
		diaporama[index].index = 0;
		if( diaporama[index].nbloaded == diaporama[index].nbtitles ) nbtreatedpages++;
		
		initial_ajax_queries--;
		if( initial_ajax_queries == 0 ) post_analysis_syntax();
	});
	
	//*/
}
/**
 * Pre-read the list to download appropriate namespaces
 */
function pre_analyze_syntax( wikitext ) {
	
	//*
	
	var pages = wikitext.match(/^\* *(?:\[\[(.*)\]\](, *[ 0-9a-z=-]* *)*|file:\/\/(.*))$/gm);
	
	//alert( 'display_time = '+display_time+'\n'+
	//       'fadeout_time = '+fadeout_time+'\n'+
	//       'fadein_time = '+fadein_time+'\n'+
	//       'random_display = '+random_display+'\n'+
	//       'number_of_pages = '+(pages?pages.length:0)+'\n'+'\n'+
	//       'pages = '+'\n'+pages.join('\n')
	//     );
	
	if( pages && pages.length > 0 ) {
		
		for( var i=0; i<pages.length; i++ )
			
			if( /^\* *\[\[.*\]\].*$/.test( pages[i] ) ) getProject( pages[i].replace(/^\* *\[\[(.*)\]\].*$/,'$1') );
		
		downloadNamespaces();
	}
	
	//*/
}

/**
 * Select the list of slides between all lists of the page
 */
function selectList() {
	
	//*
	var text = $('#textdiapo').val();
	
	var i_title = 0;
	var re_titles = text.match(/^=== *(.*) *===$/gm);
	if( re_titles && re_titles.length > 1 ) {
		
		i_title = Number($('input:radio[name=choicesinput]:checked').val());
		if( i_title == NaN ) return;
		
		if( i_title == re_titles.length-1 ) {
			var re1_title = new RegExp( re_titles[i_title]+'(?:\n.*)*' );
			var re_text = re1_title.exec(text);
			text = re_text[0].split('\n').slice(1).join('\n');
		}
		else {
			
			var re1_title = new RegExp( re_titles[i_title]+'(?:\n.*)*\n'+re_titles[i_title+1], '' );
			var re_text = re1_title.exec(text);
			var array_text = re_text[0].split('\n');
			text = array_text.slice(1,array_text.length-1).join('\n');
		}
	}
	
	re_display_time = /^display_time *= *(\d*)$/m.exec(text);
	if( re_display_time ) display_time = re_display_time[1];
	
	re_fadeout_time = /^fadeout_time *= *(\d*)$/m.exec(text);
	if( re_fadeout_time ) fadeout_time = re_fadeout_time[1];
	
	re_fadein_time = /^fadein_time *= *(\d*)$/m.exec(text);
	if( re_fadein_time ) fadein_time = re_fadein_time[1];
	
	re_random_display = /^random_display *= *(\d*)$/m.exec(text);
	if( re_random_display ) {
		if( re_random_display[1] == 'true' ) random_display = true;
		if( re_random_display[1] == 'false' ) random_display = false;
	}
	
	// Scenario
	fullscreenimages = $('input:radio[name=fullscreenimages]:checked').val();
	/*
	fadeout_time = Number($('#fadeouttime').val());
	fadein_time = Number($('#fadeintime').val());
	display_time = Number($('#displaytime').val());*/
	
	// Technique
	if( !$('#isinternet:checkbox:checked').val() ) internet = false;
	if( !internet ) ajax_initial = ajax_live = false;
	else {
		
		ajax_initial = true;
		if( $('input:radio[name=isinternetlive]:checked').val() == 'false' ) ajax_live = false;
		else ajax_live = true;
	}
	setFrames(number_screens);
	
	
	// Theming
	//bordersize = Number( $('#bordersize').val() );
	
	var color = $('input:radio[name=backgroundtype]:checked').val();
	if( color == 'black' ) background_color = 'black';
	else if( color == 'white' ) background_color = 'white';
	//else if( color == 'color' ) background_color= $('#backgroundcolor').val();
	
	$('body').css( 'background-color', background_color );
	
	
	pages = text.match(/^\* *(?:\[\[(.*)\]\](, *[ 0-9a-z=-]* *)*|file:\/\/(.*))$/gm);
	
	//alert( 'display_time = '+display_time+'\n'+
	//       'fadeout_time = '+fadeout_time+'\n'+
	//       'fadein_time = '+fadein_time+'\n'+
	//       'random_display = '+random_display+'\n'+
	//       'number_of_pages = '+(pages?pages.length:0)+'\n'+'\n'+
	//       'pages = '+'\n'+pages.join('\n')
	//     );
	
	if( pages && pages.length > 0 ) {
		
		for( var i=0; i<pages.length; i++ )
			
			if( /^\* *\[\[.*\]\].*$/.test( pages[i] ) ) getProject( pages[i].replace(/^\* *\[\[(.*)\]\].*$/,'$1') );
		
		downloadNamespaces();
	}
	//*/
}

/*

Format:

Array( type, options... )

- type = 0 : normal static page
             ex: * [[w:fr:A (lettre)]]
             - page: page name with namespace
             
- type = 1 : image
             ex: * [[w:fr:Fichier:Latin A.svg]], image
                 * [[w:fr:Fichier:EgyptianA-01.svg]], image, max
             - page: name of the image, with the local namespace
             - size: if = false original size, with the maximum of the display resolution
                     if = true force to the display resolution
             
- type = 2 : content of a category
             ex: * [[w:fr:Catégorie:A]], content, static, random, 5 pages in 15
                 * [[w:fr:Category:A]], content, live, random, 10 pages, from [[Ā]]
                 * [[w:fr:Catégorie:A]], content, static, 5 pages
                 * [[w:fr:Catégorie:A]], content, live, 5 pages, from [[Æ]]
             - page: category name with the local namespace
             - project: url-identifier of the project
             - isstatic: true if static, false if live (default: true)
             - nbpages: number of pages to download (<= 500) (default: 0)
             - israndom: true if random, false if linear (default)
             - nbdisplay: number of pages to display
             - from: first page in the list
             - list: array of the downloaded pages
             - index: index used in the live diaporama
             
- type = 3 : recentchanges
             ex: * [[w:fr:Special:Recentchanges]]
             - page: 'Special:Recentchanges' in the local name
             - project: url-identifier of the project
             - isstatic: true if static, false if live (default: true)
             - nbpages: number of pages to download (<= 500) (default: 0)
             - israndom: true if random, false if linear (default)
             - nbdisplay: number of pages to display
             - 
             - list: array of the downloaded pages
             - index: index used in the live diaporama
             
*/

function readList() {
	
	//*
	
	nbtreatedpages = 0;
	
	for( var index=0; index<pages.length; index++ ) {
		
		// Separate different options
		pages[index] = pages[index].replace( /^\* *(.*)$/, '$1' );
		var options = pages[index].split(',');
		for( var i=0; i<options.length; i++ ) {
			
			if( /\[\[/.test( options[i] ) && !/\]\]/.test( options[i] ) ) {
				
				for( var j=i+1; j<options.length; j++ ) {
					
					if( /\]\]/.test( options[j] ) ) {
						
						options[i] = options.slice( i, j+1 ).join(',');
						options.splice( i+1, j-i );
						break;
					}
				}
			}
		}
		for( var i=0; i<options.length; i++ ) options[i] = options[i].trim();
		options[0] = options[0].replace(regex_wikilink,'$1');
		
		// Get link
		var link = getProject( options.shift(), 0 );
		var project = link[0];
		var page = getNamespaceNumber( project, link[1] );
		
		//alert(''+index+': '+pages[index]+'\n'+link+'\n'+page+'\n'+options);
		
		///////////
		// Image //
		///////////
		
		if( page[0] == 6 && ( options.indexOf('image') >= 0 || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) {
			
			pages[index] = {};
			pages[index].type    = 1;
			pages[index].project = project;
			pages[index].page    = page[3];
			
			var api_url =
			    getURL( project, page[3], 2, {index:index} )
			    + '&action=query'
			    + '&prop=imageinfo'
			    + '&iiprop=url|size|user';
			
			if( ajax_initial )
				
				$.getJSON( api_url, function(data) {
					
					getAfterAjax(data);
					
					var index = data.data.index;
					var pages_list = data.query.pages;
					
					for( var t in pages_list ) {
						
						if( !pages_list[t].imagerepository ) break;
						pages[index].url    = pages_list[t].imageinfo[0].url;
						pages[index].url2   = pages_list[t].imageinfo[0].url.replace( /^.*\/[0-9a-f]\/[0-9a-f]{2}\/(.*)$/, '$1' );
						pages[index].width  = Number(pages_list[t].imageinfo[0].width);
						pages[index].height = Number(pages_list[t].imageinfo[0].height);
						
						break;
					}
					
					nbtreatedpages++;
					
					if( nbtreatedpages == pages.length ) initScreens();
				});
			
			else nbtreatedpages++;
		}
		
		///////////////////////////
		// Content of a category //
		///////////////////////////
		
		else if( page[0] == 14 && options.indexOf('content') >= 0 && ( ajax_initial || (ajax_live && options.indexOf('live') >= 0) ) ) {
			
			pages[index] = {};
			pages[index].type    = 2;
			pages[index].project = project;
			pages[index].page    = page[3];
			pages[index].url     = getURL( project, page[3], 1 );
			pages[index].list    = Array();
			pages[index].index   = 0;
			pages[index].wait    = {};
			
			var nbpage1 = -1;
			var nbpage2 = -1;
			var nbpages = 500;
			var nbdisplay = 500;
			var from = '';
			var isstatic = true;
			var israndom = false;
			var isimage = false;
			
			if( options.indexOf('image') >= 0 ) isimage = true;
			if( options.indexOf('live') >= 0 ) isstatic = false;
			if( options.indexOf('random') >= 0 ) israndom = true;
			
			for( var i=0; i<options.length; i++ ) {
				
				if( /^(\d*) *pages? *(?:in *(\d*))?$/.test(options[i]) ) {
					
					var res_nbpage = options[i].match(/^(\d*) *pages? *(?:in *(\d*))?$/);
					
					nbpage1 = Number(res_nbpage[1]);
					if( res_nbpage[2] ) nbpage2 = Number(res_nbpage[2]);
				}
				
				else if( /^from *\[\[(.*)\]\]$/.test(options[i]) ) {
					
					var res_from = options[i].match( /^from *\[\[(.*)\]\]$/ );
					from = res_from[1];
				}
			}
			
			if( !israndom ) {
				
				if( nbpage1 != -1 ) nbpages = nbpage1;
				else nbpages = 10;
				nbdisplay = nbpages;
			}
			else {
				
				if( nbpage2 != -1 ) nbpages = nbpage2;
				if( nbpage1 != -1 ) nbdisplay = nbpage1;
				else nbdisplay = 6;
			}
			
			if( nbpages > 500 ) nbpages = 500;
			if( nbdisplay > nbpages ) nbdisplay = nbpages;
			
			pages[index].isstatic  = isstatic;
			pages[index].isimage   = isimage;
			pages[index].nbpages   = nbpages;
			pages[index].israndom  = israndom;
			pages[index].nbdisplay = nbdisplay;
			pages[index].from      = from;
			pages[index].api       =
			      '&action=query'
			    + '&list=categorymembers'
			    + '&cmlimit='+pages[index].nbpages
			    + '&cmtitle='+encodeURIComponent(pages[index].page.replace(/ /g,'_'))
			    + (pages[index].from?'&cmstartsortkey='+encodeURIComponent(pages[index].from.replace(/ /g,'_')):'');
			
			if( isstatic )
				
				$.getJSON( getURL(project,'',4,{index:index})+pages[index].api, function(data) {
					
					getAfterAjax(data);
					
					var index = data.data.index;
					var project = pages[index].project;
					var isimage = pages[index].isimage;
					var pages_list = data.query.categorymembers;
					
					pages[index].nbpages = pages_list.length;
					if( pages[index].nbdisplay > pages[index].nbpages ) pages[index].nbdisplay = pages[index].nbpages;
					pages[index].nbloaded = 0;
					
					for( var j=0; j<pages_list.length; j++ ) {
						
						var page = getNamespaceNumber( project, pages_list[j].title );
						var newpage = { type:-1, project:project, page:page[3], url:getURL(project,page[3],1) };
						
						if( page[0] == 6 && ( isimage || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) {
							
							newpage.type = 1;
							pages[index].list[pages[index].index] = newpage;
							getImageSize( true, index, pages[index].index );
						}
						else {
							
							newpage.type = 0;
							pages[index].list[pages[index].index] = newpage;
							pages[index].nbloaded++;
						}
						pages[index].index++;
					}
					
					//s='';for(var j=0;j<pages[index].nbpages;j++)s+=pages[index].list[j].url+'\n';alert(s);
					
					pages[index].index = 0;
					if( pages[index].nbloaded == pages[index].nbpages ) nbtreatedpages++;
					
					if( nbtreatedpages == pages.length ) {
						
						pages[index].nbloaded = undefined;
						initScreens();
					}
				});
			
			else nbtreatedpages++;
		}
		
		///////////////////////////
		// Display RecentChanges //
		///////////////////////////
		
		else if( page[0] == -1 && (['Recentchanges','Newpages','Log'].indexOf(page[2]) >= 0) && options.indexOf('content') >= 0 && ( ajax_initial || (ajax_live && options.indexOf('live') >= 0) ) ) {
			
			pages[index] = {};
			pages[index].type    = 3;
			pages[index].project = project;
			pages[index].page    = page[3];
			pages[index].url     = getURL( project, page[3], 1 );
			pages[index].list    = Array();
			pages[index].index   = 0;
			pages[index].wait    = {};
			
			var nbpage1 = -1;
			var nbpage2 = -1;
			var nbpages = 500;
			var nbdisplay = 500;
			var israndom = false;
			var since = false;
			var isstatic = true;
			var anon = '';
			var bot = '';
			var user = '';
			var rctype = '';
			
			if( options.indexOf('nobot') >= 0 ) bot = '!bot';
			if( options.indexOf('live') >= 0 ) isstatic = false;
			if( options.indexOf('random') >= 0 ) israndom = true;
			
			for( var i=0; i<options.length; i++ ) {
				
				if( /^bots? *(?:= *\[\[(.*)\]\])?$/.test(options[i]) ) {
					
					var re_res = options[i].match(/^bots? *(?: *=\[\[(.*)\]\])?$/);
					if( re_res[1] ) user = re_res[1];
					else bot = 'bot';
				}
				
				else if( /^anons? *(?:= *\[\[(.*)\]\])?$/.test(options[i]) ) {
					
					var re_res = options[i].match(/^anons? *(?:= *\[\[(.*)\]\])?$/);
					if( re_res[1] ) user = re_res[1];
					else anon = 'anon';
				}
				
				else if( /^users? *(= *\[\[.*\]\])?$/.test(options[i]) ) {
					
					var re_res = options[i].match(/^users? *(?: *=\[\[(.*)\]\])?$/);
					if( re_res[1] ) user = re_res[1];
					else anon = '!anon';
				}
				
				else if( /^(\d*) *pages? *(?:in *(\d*))?$/.test(options[i]) ) {
					
					var res_nbpage = options[i].match(/^(\d*) *pages? *(?:in *(\d*))?$/);
					
					nbpage1 = Number(res_nbpage[1]);
					if( res_nbpage[2] ) nbpage2 = Number(res_nbpage[2]);
				}
				
				else if( /^since (\d*)/.test(options[i]) ) {
					
					var re_res;
					since = Date.now()-siteinfo[project].difftime
					if( (re_res = /(\d*) *seconds?/.exec(options[i])) != null ) since -= Number(re_res[1])*    1000;
					if( (re_res = /(\d*) *minutes?/.exec(options[i])) != null ) since -= Number(re_res[1])*   60000;
					if( (re_res = /(\d*) *hours?/.exec(options[i]))   != null ) since -= Number(re_res[1])* 3600000;
					if( (re_res = /(\d*) *days?/.exec(options[i]))    != null ) since -= Number(re_res[1])*86400000;
				}
			}
			
			if( !israndom ) {
				
				if( nbpage1 != -1 ) nbpages = nbpage1;
				else nbpages = 10;
				nbdisplay = nbpages;
			}
			else {
				
				if( nbpage2 != -1 ) nbpages = nbpage2;
				if( nbpage1 != -1 ) nbdisplay = nbpage1;
				else nbdisplay = 6;
			}
			
			if( user ) bot = anon = '';
			
			if( page[2] == 'Recentchanges' ) rctype = '';
			else if( page[2] == 'Newpages' ) rctype = 'new';
			if( page[2] == 'Log' ) rctype = 'log';
			
			if( nbpages > 500 ) nbpages = 500;
			if( nbdisplay > nbpages ) nbdisplay = nbpages;
			
			pages[index].isstatic  = isstatic;
			pages[index].nbpages   = nbpages;
			pages[index].israndom  = israndom;
			pages[index].nbdisplay = nbdisplay;
			pages[index].anon      = anon;
			pages[index].bot       = bot;
			pages[index].user      = user;
			pages[index].rctype    = rctype;
			pages[index].since     = (since!==false?ISODateString(new Date(since)):'');
			pages[index].api       =
			      '&action=query'
			    + '&list=recentchanges'
			    + ( pages[index].type ? '&rctype='+pages[index].rctype : '' )
			    + '&rclimit='+pages[index].nbpages
			    + ( pages[index].since ? '&rcend='+pages[index].since : '' )
			    + ( anon || bot ? '&rcshow=' + anon + (anon&&bot?'|':'') + bot : '' )
			    + ( pages[index].user ? '&rcuser='+encodeURIComponent(pages[index].user.replace(/ /g,'_')) : '' );
			
			if( isstatic )
				
				$.getJSON( getURL(project,'',4,{index:index})+pages[index].api, function(data) {
					
					getAfterAjax(data);
					
					var index = data.data.index;
					var project = pages[index].project;
					var pages_list = data.query.recentchanges;
					
					pages[index].nbpages = pages_list.length;
					if( pages[index].nbdisplay > pages[index].nbpages ) pages[index].nbdisplay = pages[index].nbpages;
					
					for( var j=0; j<pages_list.length; j++ ) {
						
						var page = getNamespaceNumber( project, pages_list[j].title );
						var newpage = { type:0, project:project, page:page[3], url:getURL(project,page[3],1) };
						
						pages[index].list[pages[index].index] = newpage;
						
						pages[index].index++;
					}
					
					//s='';for(var j=0;j<pages[index].nbpages;j++)s+=pages[index].list[j].url+'\n';alert(s);
					
					pages[index].index = 0;
					nbtreatepages++;
					
					if( nbtreatedpages == pages.length ) initScreens();
				});
			
			else nbtreatedpages++;
		}
		
		//else if( /^http:\/\/(.*)\/wiki\/(.*)\*(?:\[(\d*)\])?$/.test(pages[index]) ) {
		//	
		//	if( ajax_allpages ) {
		//		
		//		var api = pages[index].match(/^http:\/\/(.*)\/wiki\/(.*)\*(?:\[(\d*)\])?$/);
		//		var url_project = api[1];
		//		wikititle = getNamespaceNumber(url_project,api[2]);
		//		if( wikititle.length > 0 ) {
		//			
		//			alert(wikititle);
		//			var limit = 10;
		//			if( api[3] ) limit = api[3];
		//			var api_url = getURL( url_project, 4 )+'&action=query&list=allpages&aplimit='+limit+'&apnamespace='+wikititle[0]+'&apprefix='+wikititle[1];
		//			$.getJSON( api_url, function(data) { pages_list = data.query.allpages; endarray = pages.slice(index+1); pages = pages.slice(0,index); for( j=0; j<pages_list.length; j++ ) pages.push(getURL(url_project,pages_list[j].title,1)); pages = pages.concat( endarray ); index+= pages_list.length; readList(); } );
		//			break;
		//		}
		//	}
		//	else pages = pages.slice(0,index).concat(pages.slice(index+1));
		//}
		else {
			
			pages[index] = {};
			pages[index].type    = 0;
			pages[index].project = project;
			pages[index].page    = page[3];
			pages[index].url     = getURL( project, page[3], 1 );
			
			nbtreatedpages++;
		}
	}
	
	if( nbtreatedpages == pages.length ) {
		
		//s = ''; for( var i=0; i<pages.length; i++ ) s += pages[i]['type']+':'+pages[i]['url']+'\n';
		//alert('Result:\n'+s);
		
		//setFrames(number_screens);
		
		
		initScreens();
	}
	
	//*/
}

function getImageSize( initial, index, index2, nr ) {
	
	//*
	
	var page = pages[index];
	if(  initial && ( page.type == 2 || page.type == 3 ) ) page = pages[index].list[index2];
	if( !initial && ( page.type == 2 || page.type == 3 ) ) page = pages[index].wait[String(nr)][index2];
	
	var api_url =
	    getURL( page.project, page.page, 2, {initial:initial,index:index,index2:index2} )
	    + '&action=query'
	    + '&prop=imageinfo'
	    + '&iiprop=url|size|user';
	
	$.getJSON( api_url, function(data) {
		
		getAfterAjax(data);
		
		var initial = data.data.initial;
		var index = data.data.index;
		var index2 = data.data.index2;
		var pages_list = data.query.pages;
		var page = pages[index];
		if(  initial && ( page.type == 2 || page.type == 3 ) ) page = pages[index].list[index2];
		if( !initial && ( page.type == 2 || page.type == 3 ) ) page = pages[index].wait[String(nr)][index2];
		
		for( var t in pages_list ) {
			
			if( !pages_list[t].imagerepository ) break;
			page.type    = 1;
			page.project = page.project;
			page.page    = page.page;
			page.url     = pages_list[t].imageinfo[0].url;
			page.url2    = pages_list[t].imageinfo[0].url.replace( /^.*\/[0-9a-f]\/[0-9a-f]{2}\/(.*)$/, '$1' );
			page.width   = Number(pages_list[t].imageinfo[0].width);
			page.height  = Number(pages_list[t].imageinfo[0].height);
			
			break;
		}
		
		if( initial ) {
			
			if( pages[index].type == 2 || pages[index].type == 3 ) {
				
				pages[index].nbloaded++;
				
				if( pages[index].nbloaded == pages[index].nbpages ) nbtreatedpages++;
			}
			else nbtreatedpages++;
			
			if( nbtreatedpages == pages.length ) {
				
				pages[index].nbloaded = undefined;
				initScreens();
			}
		}
		else {
			
			pages[index].nbloaded++;
			
			if( pages[index].nbloaded == pages[index].nbpages ) {
				
				pages[index].nbloaded = undefined;
				
				for( var j=0; j<pages[index].nbdisplay && j<number_screens && !loaded_screens[(j+nr)%number_screens] && ((j+nr)%number_screens != current_screen || init); j++ )
					
					preloadScreen( (nr+j)%number_screens, index );
				
				if( preloadajaxqueue.length > 0 ) {
					
					var newelem = preloadajaxqueue.shift();
					preloadAjax( newelem.nr, newelem.index );
				}
			}
		}
	});
	
	//*/
}

//
// Set the frames
// 
// @param[in] nb_new_frames Number of frames to set
//
function setFrames( nb_new_frames ) {
	
	//*
	
	$('#parametersdialog').dialog('destroy').remove();
	
	// Verify parameters
	var nb_frames = $('iframe').length;
	if( nb_new_frames < 2 ) nb_new_frames = 2;
	if( nb_new_frames <= nb_frames ) return;
	
	// Add frames
	for( ; nb_frames<nb_new_frames; nb_frames++ ) {
		
		$('body').append( '<iframe name="screen'+nb_frames+'" id="screen'+nb_frames+'" class="screen screen'+nb_frames+'" frameborder="0" scrolling="no" src="" /'+'>' );
		if( nb_frames != 0 ) $('#screen'+nb_frames).css( 'display', 'none'  );
		else                 $('#screen'+nb_frames).css( 'display', 'block' );
		
		$('body').append( '<div id="status-screen'+nb_frames+'" class="status-screen" style="left:'+(5+10*nb_frames)+'px; background-color:red; border-color:red;" /'+'>' );
	}
	
	// Set width and height
	$('iframe').width(window.innerWidth-2*bordersize).height(window.innerHeight-2*bordersize).css( { 'top':bordersize+'px', 'left':bordersize+'px' } );
	
	// Reset all frames
	number_screens = nb_new_frames;
	for( var i=0; i<number_screens; i++ ) {
		
		loaded_screens[i] = false;
		$('#screen'+i).attr( 'src', '' );
		$('#status-screen'+i).css( { 'background-color':'red', 'border-color':'red' } );
	}
	
	//*/
}

function initScreens() {
	
	//*
	current_screen = 0;
	page = 0;
	page2 = 0;
	history_addresses = Array();
	//history = Array();
	history_index = 0;
	
	s = '';
	
	for( var i=0; i<pages.length; i++ ) {
		
		s += 'type:' + pages[i].type + '\n';
		s += 'project:' + pages[i].project + '\n';
		s += 'page:' + pages[i].page + '\n';
		s += 'url:' + pages[i].url + '\n';
		
		if( pages[i].type == 1 ) {
			
			s += 'url2:' + pages[i].url2 + '\n';
			s += 'width:' + pages[i].width + '\n';
			s += 'height:' + pages[i].height + '\n';
		}
		
		else if( pages[i].type == 2 || pages[i].type == 3 ) {
			
			s += 'list:\n';
			for( var l in pages[i].list ) {
				
				s += '  ( ';
				s += 'type:' + pages[i].list[l].type + ', ';
				s += 'project:' + pages[i].list[l].project + ', ';
				s += 'page:' + pages[i].list[l].page;
				
				if( pages[i].list[l].type == 1 ) {
					
					s += ', ';
					s += 'url:' + pages[i].list[l].url + ', ';
					s += 'url2:' + pages[i].list[l].url2 + ', ';
					s += 'width:' + pages[i].list[l].width + ', ';
					s += 'height:' + pages[i].list[l].height;
				}
				s += ' )\n';
			}
			s += 'index:' + pages[i].index + '\n';
			//s += 'wait:' + pages[i].wait + '\n';
			s += 'isstatic:' + pages[i].isstatic + '\n';
			s += 'nbpages:' + pages[i].nbpages + '\n';
			s += 'israndom:' + pages[i].israndom + '\n';
			s += 'nbdisplay:' + pages[i].nbdisplay + '\n';
			
			if( pages[i].type == 2 ) {
				
				s += 'isimage:' + pages[i].isimage + '\n';
				s += 'from:' + pages[i].from + '\n';
				s += 'api:' + pages[i].api + '\n';
			}
			else {
				
				s += 'anon:' + pages[i].anon + '\n';
				s += 'bot:' + pages[i].bot + '\n';
				s += 'user:' + pages[i].user + '\n';
				s += 'rctype:' + pages[i].rctype + '\n';
				s += 'since:' + pages[i].since + '\n';
				s += 'api:' + pages[i].api + '\n';
			}
		}
		
		if( i < pages.length-1 ) s += '\n';
	}
	
	//alert( s );
	
	
	for( var i=0; i<number_screens; i++ ) loaded_screens[i] = false;
	//reserved_slots_from = number_screens;
	
	for( var i=0; i<number_screens; i++ ) {
		//alert('*0');
		preloadScreen(i);//alert('*1');
		changePage();//alert('*2');
		
		// Very very very important: wait before add this hook to the screens, do not add immediatly after appending of the iframe, else the first trivial (empty) load breaks everything after in the synchronisation
		$('#screen'+i).load(onloadscreen);
	}
	
	// Set the event attached to resize of the screen
	$(window).resize(function() {
		
		$('iframe').width(window.innerWidth-2*bordersize).height(window.innerHeight-2*bordersize).css( { 'top':bordersize+'px', 'left':bordersize+'px' } );
	});
	
	//alert('fin init');
	//*/
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////       DIAPORAMA      ///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//* *     *
//    +
//
//* *
//    +
//
//  * *
//+
//
//si reserved_slots >= number_screens
// false
//sinon
// reserved_slots_from > nr >= (reserved_slots+reserved_slots_from)%number_screens
//
//

function preloadScreen( nr, index ) {
	
	//*
	
	//alert('nr='+nr+' '+index);
	
	// Invalid loading state
	loaded_screens[nr] = false;
	$('#status-screen'+nr).css( { 'background-color':'red', 'border-color':'red' } );
	
	var differed = true;
	
	// Get parameters
	if( index == undefined ) {
		
		if( true ) index = page;
		differed = false;
		//if( page2 == 0 || pages[page].list.length > 0 ) index = page;
		//if( page2 == 0 || pages[page].index < pages[page].nbpages ) index = page;
		//if( reserved_slots < number_screens && nr < reserved_slots_from && nr >= (reserved_slots+reserved_slots_from)%number_screens ) index = page;
		//else {
			
			//alert('exit');
		//	return;
		//}
	}
	
	// Get current page
	var cur_page = pages[index];
	
	//alert(cur_page.index+' '+cur_page.type+' '+cur_page.isstatic);
	if( ( cur_page.type == 2 || cur_page.type == 3 ) && cur_page.index == 0 && !cur_page.isstatic ) {
		
		//alert(cur_page.index);
		//else if( page2 != 0 ) {alert('exit');return;}
		if( cur_page.wait[String(nr)] != undefined ) {/*alert('load wait');*/cur_page.list = clone(cur_page.wait[String(nr)]); cur_page.wait[String(nr)] = undefined; }
		else if( page2 != 0 ) {/*alert('exit');*/return;}
		else {/*alert('loadajax');*/preloadAjax( nr, index ); return; }
	}
	//alert('index='+cur_page.index+' nr='+nr+' page='+page+' page2='+page2);
	if( ( cur_page.type == 2 || cur_page.type == 3 ) && cur_page.index >= 0 && cur_page.index < cur_page.nbdisplay ) {
		
		
		
		//reserved_slots = cur_page.nbpages-cur_page.index-1;
		//if( reserved_slots > number_screens ) reserved_slots = number_screens;
		//reserved_slots_from = nr;
		//s='';
		//for( var j=0; j<pages[index].list.length; j++ ) s+=pages[index].list[j].page+'\n';
		var r = Math.floor((pages[index].nbpages+1)*Math.random());
		//alert('random '+cur_page.israndom+' '+r+' '+s);
		if( cur_page.israndom ) cur_page = pages[index].list[r];
		else cur_page = pages[index].list[pages[index].index];
	}
	//alert('index(2)='+pages[index].index);
	//var src_page = '';
	
	// Restore big dimensions
	$('#screen'+nr).width( window.innerWidth-2*bordersize ).height( window.innerHeight-2*bordersize ).css( {'top':bordersize+'px', 'left':bordersize+'px'} );
	//alert('*');
	//alert('index(2)='+cur_page.index);
	// Normal page
	if( cur_page.type == 0 ) {
		
		//alert(nr,index);
		preloadPage( nr, cur_page );
		//save_history( pages[index], nr );
	
	// Image
	} else if( cur_page.type == 1 ) {
		
		preloadImage( nr, cur_page );
		//save_history( pages[index], nr );
	}
	
	//alert( 'next');
	
	// Category or Recentchanges/Newpages/Log
	if( pages[index].type == 2 || pages[index].type == 3 ) {
		
		//alert(pages[index].index);
		pages[index].index = ( pages[index].index + 1 ) % pages[index].nbdisplay;
		//alert('next 2-3 page '+pages[index].list+' '+pages[index].nbpages);
		//alert(pages[index].index);
		
		//if( !pages[index].isstatic ) {
			
			//if( pages[index].index == 0 ) {
				
				//pages[index].list = [];
				
				//reserved_slots += pages[index].nbdisplay;
				//preloadAjax( nr, index );
			//}
			//else if( pages[index].list.length > 0 ) preloadScreen( (nr+1)%number_screens, index );
		//}
	}
	//alert('*+'+nr);
	
	// Category or Recentchanges/Newpages/Log (further loading)
	//else if( ( cur_page.type == 2 || cur_page.type == 3 ) && ( cur_page.isstatic || ( page2 != 0 && ( cur_page.list.length > 0 ) ) ) ) {
	//	
	//	var src_page = '';
	//	
	//	if( cur_page.index == 0 ) {
	//		
	//		var inr = (nr+1)%number_screens;
	//		while( cur_page.wait[String(inr)] != undefined ) {
	//			
	//			if( cur_page.wait[inr].index != 0 ) {
	//				
	//				cur_page.index = cur_page.wait[inr].index
	//				cur_page.list = cur_page.wait[inr].list;
	//				break;
	//			}
	//			cur_page.wait[inr] = undefined;
	//		}
	//	}
	//	
	//	if( cur_page.israndom ) src_page = cur_page.list[Math.floor((cur_page.nbpages+1)*Math.random())].url;
	//	else src_page = cur_page.list[cur_page.index].url;
	//	cur_page.index = (cur_page.index+1) % cur_page.nbdisplay;
	//	
	//	$('#screen'+nr).attr( 'src', src_page );
	//}
	//
	//
	//// Category or Recentchanges/Newpages/Log (medium loading)
	//else if( cur_page.type == 2 || cur_page.type == 3 )
	//	
	//	return;
	
	//*/
}

function preloadPage( nr, cur_page ) {
	
	//*
	
	// Invalid loading state
	loaded_screens[nr] = false;
	$('#status-screen'+nr).css( { 'background-color':'red', 'border-color':'red' } );
	
	$('#screen'+nr).attr( 'src', cur_page.url );
	
	//*/
}

//
// Preload an image
//
// @param[in] nr     ID of the frame
// @param[in] index  Number of the page
// @param[in] index2 Second index, in case of sub-list
//
function preloadImage( nr, cur_page ) {
	
	//*
	
	// Invalid loading state
	loaded_screens[nr] = false;
	$('#status-screen'+nr).css( { 'background-color':'red', 'border-color':'red' } );
	
	// Get properties
	var src_page = cur_page.url;
	var width = cur_page.width;
	var height = cur_page.height;
	
	// Get screen dimensions
	var screen_width = window.innerWidth-2*bordersize;
	var screen_height = window.innerHeight-2*bordersize;
	var ratio_width = width/screen_width;
	var ratio_height = height/screen_height;
	
	// Adapt the image to the screen dimensions:
	
	// 1) image smaller than the screen;
	if( width <= screen_width && height <= screen_height )
	
		$('#screen'+nr).width( width ).height( height ).css( { 'top':Math.floor((screen_height-height)/2+bordersize)+'px', 'left':Math.floor((screen_width-width)/2+bordersize)+'px' } );
	
	// 2) landscape format (relatively to the screen);
	else if( ratio_width < ratio_height ) {
		
		src_page = src_page.replace( /^(.*)\/([0-9a-f])\/([0-9a-f]{2})\/(.*)$/, '$1/thumb/$2/$3/$4/' )+Math.ceil(width/ratio_height)+'px-'+cur_page['url2'];
		$('#screen'+nr).width( Math.ceil(width/ratio_height) ).height( screen_height ).css( 'left', Math.floor((screen_width-width/ratio_height)/2+bordersize)+'px' );
	
	// 3) portrait format (relatively to the screen)
	} else {
		
		src_page = src_page.replace( /^(.*)\/([0-9a-f])\/([0-9a-f]{2})\/(.*)$/, '$1/thumb/$2/$3/$4/' )+screen_width+'px-'+cur_page['url2'];
		$('#screen'+nr).width( screen_width ).height( Math.ceil(height/ratio_width) ).css( 'top', Math.floor((screen_height-height/ratio_width)/2+bordersize)+'px' );
	}
	
	// Load the page
	$('#screen'+nr).attr( 'src', src_page );
	
	//*/
}

//
// Preload a category/Recentchanges/Newpages/Log using Ajax
//
// @param[in] nr    ID of the frame
// @param[in] index Number of the page
//
function preloadAjax( nr, index ) {
	
	//*
	
	if( pages[index].nbloaded != undefined ) {
		
		preloadajaxqueue.push( {nr:nr,index:index} );
		return;
	}
	
	//pages[index].list = [];
	pages[index].nbloaded = 0;
	
	AjAX.niew();
	$.getJSON( getURL(pages[index].project,'', 4,{nr:nr,index:index})+pages[index].api, function(data) {
		//alert('preloadajax');
		getAfterAjax(data);
		
		var nr = data.data.nr;
		var index = data.data.index;
		var cur_page = pages[index];
		var project = cur_page.project;
		var isimage = cur_page.isimage;
		
		if( cur_page.type == 2 ) pages_list = data.query.categorymembers;
		else if( cur_page.type == 3 ) pages_list = data.query.recentchanges;
		
		if( cur_page.israndom ) cur_page.nbpages = pages_list.length;
		
		cur_page.wait[String(nr)] = [];
		var list = cur_page.wait[String(nr)];
		
		for( var j=0; j<cur_page.nbpages; j++ ) {
			
			var page = getNamespaceNumber( project, pages_list[j%pages_list.length].title );
			var newpage = { type:-1, project:project, page:page[3], url:getURL(project,page[3],1) };
			
			if( cur_page.type == 2 && ( page[0] == 6 && ( isimage || fullscreenimages == 'always' ) && fullscreenimages != 'never' ) ) {
				
				newpage.type = 1;
				list[j] = newpage;
				getImageSize( false, index, j, nr );
			}
			else {
				
				newpage.type = 0;
				list[j] = newpage;
				cur_page.nbloaded++;
			}
		}
		
		//alert('*');
		//alert(cur_page.nbloaded+ ' '+cur_page.nbpages);
		if( cur_page.nbloaded == cur_page.nbpages ) {
			//alert('fin load ajax list='+cur_page.wait[String(nr)]);
			cur_page.nbloaded = undefined;
			///alert(loaded_screens);
			//j=0;
			//alert( ''+nr+' '+cur_page.nbdisplay +' '+ number_screens + !loaded_screens[(j+nr)%number_screens] + ((j+nr)%number_screens != current_screen) + init );
			for( var j=0; j<cur_page.nbdisplay && j<number_screens && !loaded_screens[(j+nr)%number_screens] && ((j+nr)%number_screens != current_screen || init); j++ ){
				//alert('j='+j);
				preloadScreen( (nr+j)%number_screens, index );}
			
			if( preloadajaxqueue.length > 0 ) {
				
				var newelem = preloadajaxqueue.shift();
				preloadAjax( newelem.nr, newelem.index );
			}
		}
		
		//s='';for(var j=0;j<pages[index].nbpages;j++)s+=pages[index].list[j].url+'\n';alert(s);
		
		//pages[index].index = 0;
		//if( pages[index].nbloaded == pages[index].nbpages ) nbtreatedpages++;
		//
		//if( nbtreatedpages == pages.length ) {
		//	
		//	pages[index].nbloaded = undefined;
		//	initScreens();
		//}
		
		//var newlist = Array();
		//for( var j=0; j < cur_page.nbdisplay || (cur_page.nbrandom && j < cur_page.nbpages); j++ )
		//	
		//	newlist.push( { type:0, project:cur_page.project, page:pages_list[j%pages_list.length].title, url:getURL(cur_page.project,pages_list[j%pages_list.length].title,1) } );
		//
		//cur_page.wait[snr] = {}
		//cur_page.wait[snr].index = 0;
		//cur_page.wait[snr].list = newlist;
		
		//for( var j=0; j<cur_page.nbdisplay && j<number_screens && !loaded_screens[(j+nr)%number_screens] && ((j+nr)%number_screens != current_screen || init); j++ ) {
		//	
		//	if( cur_page.nbrandom ) src_page = cur_page.wait[snr].list[Math.floor((cur_page.nbpages+1)*Math.random())].url;
		//	else src_page = cur_page.wait[snr].list[cur_page.wait[snr].index].url;
		//	cur_page.wait[snr].index = (cur_page.wait[snr].index+1) % cur_page.nbdisplay;
		//	
		//	$('#screen'+((j+nr)%number_screens)).attr( 'src', src_page );
		//}
		//s='';for(var j=0;j<cur_page.nbpages;j++)s+=cur_page.wait[snr].list[j].url+'\n';alert(s);
		//
		//if( cur_page.wait[snr].index == 0 ) {
		//	
		//	//cur_page.index = cur_page.wait[snr].index
		//	//cur_page.list = cur_page.wait[snr].list;
		//	cur_page.wait[snr] = undefined;
		//}
	});
	
	//*/
}

//
//
//
function save_history( cur_page, nr, index, index2 ) {
	
	//*
	
	history_addresses[history_index] = {};
	
	if( cur_page.type == 0 || cur_page.type == 1 ) history_addresses[history_index].node = clone( cur_page );
	else if( cur_page.type == 2 || cur_page.type == 3 ) history_addresses[history_index].node = clone( cur_page.list[index2] );
	
	history_addresses[history_index].nr = nr;
	history_addresses[history_index].index = index;
	history_addresses[history_index].index2 = index2;
	
	if( cur_page.type == 2 || cur_page.type == 3 ) {
		
		history_addresses[history_index].parent = {};
		history_addresses[history_index].parent.type = cur_page.type;
		history_addresses[history_index].parent.project = cur_page.project;
		history_addresses[history_index].parent.page = cur_page.page;
		history_addresses[history_index].parent.url = cur_page.url;
		
		history_addresses[history_index].parent.isstatic = cur_page.isstatic;
		history_addresses[history_index].parent.nbpages = cur_page.nbpages;
		history_addresses[history_index].parent.nbrandom = cur_page.nbrandom;
		history_addresses[history_index].parent.nbdisplay = cur_page.nbdisplay;
		history_addresses[history_index].parent.type = cur_page.type;
		history_addresses[history_index].parent.api = cur_page.api;
		
		if( cur_page.type == 2 ) {
			
			history_addresses[history_index].parent.isimage = cur_page.isimage;
			history_addresses[history_index].parent.from = cur_page.from;
		}
		else if( cur_page.type == 3 ) {
			
			history_addresses[history_index].parent.anon = cur_page.anon;
			history_addresses[history_index].parent.bot = cur_page.bot;
			history_addresses[history_index].parent.user = cur_page.user;
			history_addresses[history_index].parent.rctype = cur_page.rctype;
			history_addresses[history_index].parent.since = cur_page.since;
		}
	}
	
	history_index++;
	
	//*/
}

//
// Advance the indexes of the current (loading) page
//
function changePage() {
	
	//*
	
	var cur_page = pages[page];
	
	if( ( cur_page.type == 2 || cur_page.type == 3 ) && page2 < cur_page.nbdisplay-1 )
		
		page2++;
	
	else {
		
		if( !random_display ) page = (page+1)%(pages.length);
		else page = Math.floor(Math.random()*(pages.length));
		page2 = 0;
	}
	
	//*/
}

//
// Main event when a frame is loaded
//
function onloadscreen() {
	
	//*
	
	var next_screen = (current_screen+1) % number_screens;
	var nr = Number(/^screen(\d*)$/.exec($(this).attr('id'))[1]);
	
	//alert('loaded'+nr);
	loaded_screens[nr] = true;
	$('#status-screen'+nr).css( { 'background-color':'green', 'border-color':'green' } );
	if( nr == 0 && init ) $('#status-screen'+nr).css( 'border-color', background_color );
	
	if( false && changing_screen ); // very useful protection, which was (is) really useful to avoid synchro problems during the initialization - this is really a test to know if there is no synchro problem, particularly with special scenarios (content of category (particularly live), RC...)
	else if( nr == current_screen && loaded_screens[next_screen]    ) changescreen();
	//else if( init && nr == next_screen    && loaded_screens[current_screen] ) changescreen();
	else if( nr == next_screen    && loaded_screens[current_screen] ) changescreen();
	
	//*/
}

//
// Go to the next screen
//
function changescreen() {
	
	//*
	
	//changing_screen = true;
	var next_screen = (current_screen+1) % number_screens;
	
	//history_addresses.push( $('#screen'+current_screen).attr( 'src' ) );
	if( current_screen == 0 && init ) {
		
		setTimeout( changescreen, display_time*100 );
		init = false;
		return;
	}
	
	$('#screen'+current_screen).fadeOut( fadeout_time*100, function() {
		
		$('#status-screen'+current_screen).css( 'border-color', 'green' );
		$('#status-screen'+((current_screen+1)%number_screens)).css( 'border-color', background_color );
		//loaded_screens[current_screen] = false;
		
		$('#screen'+next_screen).fadeIn( fadein_time*100, function() {
			
			current_screen = (current_screen+1)%number_screens;
			next_screen = (current_screen+1)%number_screens;
			
			//changing_screen = false;
			//alert('*1');
			//alert((-1+3)%3);
			preloadScreen((current_screen-1+number_screens)%number_screens);//alert('*2');
			changePage();//alert('*3'+next_screen+loaded_screens[next_screen]);
			
			if( loaded_screens[next_screen] ) { /*alert('loadnext');*/setTimeout( changescreen, display_time*100 );}
		});
	});
	
	//*/
}






////////////////////////////////////////////////////////////////////////////////
//                              AUXILIARY SCRIPTS                             //
////////////////////////////////////////////////////////////////////////////////


function getAfterAjax( data ) {
	
	//*
	
	
	
	//*/
}

//
// Get a date with the ISO 8601 format
// 
// MIT license
// © 2011 Inimino
// from Mozilla Developer Center, page en/JavaScript/Reference/Global_Objects/Date
//
function ISODateString(d) {
	
	//*
	
	function pad(n) { return n<10 ? '0'+n : n }
	return d.getUTCFullYear()+'-'
	+ pad(d.getUTCMonth()+1)+'-'
	+ pad(d.getUTCDate())+'T'
	+ pad(d.getUTCHours())+':'
	+ pad(d.getUTCMinutes())+':'
	+ pad(d.getUTCSeconds())+'Z'
	
	//*/
}

//
// Fonction de clonage
//
// CC-BY-SA license
// @author Keith Devens
// @see http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
//
function clone(srcInstance) {
	
	//*
	
	// Si l'instance source n'est pas un objet ou qu'elle ne vaut rien c'est une feuille donc on la retourne
	if( typeof(srcInstance) != 'object' || srcInstance == null )
		
		return srcInstance;
	
	// On appel le constructeur de l'instance source pour crée une nouvelle instance de la même classe
	var newInstance = srcInstance.constructor();
	
	// On parcourt les propriétés de l'objet et on les recopies dans la nouvelle instance
	for( var i in srcInstance )
		
		newInstance[i] = clone(srcInstance[i]);
	
	// On retourne la nouvelle instance
	return newInstance;
	
	//*/
}

function display_object( o ) {
	
	//*
	
	var s = '';
	
	for( var t in o ) s += t + ':' + o[t] + '\n';
	
	alert( s );
	
	//*/
}

$(initScreenViewer);


</script>
</head>
</html>