// Expositions


// On tranforme les rel='expo' pour gérer la popup
$(document).ready(function(){
		$('a[rel=expo]')	
			.attr('target','MFPExpoWindow')
			.click( openExpo );
	});

// Liens "quitter"
var _quitLink = '';
function quitlink(){
	switch( _quitLink ){
	case 'expo':
		goHome();
		break;
		
	case 'expo2':
		quitExpo2();
		break;
		
	case 'galerie':
		quitGalerie();
		break;
		
	case 'zoom':
		finZoomVisionneuse();
		break;
	}
}


// Fonction pour positionner le titre dans le header
function setHeaderTitle( str ){
	document.getElementById( "headerTitle" ).innerHTML = str;
}

// Fonction pour placer le cadre rose dans les chapitres de l'expo
function setPinkBorder( idx ){
	$('#chapters .selectionframe').remove();
	$('#chapters .thumb a')
		.eq( idx - 1 )
		.append( '<img class="selectionframe" src="../res/skinDefault/themeDefault/frame_rose.gif" alt="" />' );
}

// Fonction dans les écrans de niveau pour ajuster le cartouche
function adjustCartouche(){
	//return;
	var cartouche = $('#cartouche');
	var cartoucheHeight = cartouche.height(); //alert('cartoucheHeight = ' + cartoucheHeight);
	var expoimage = $('#expoimage');
	var offsetExpoimage = expoimage.offset(); //alert('offsetExpoimage.top = ' + offsetExpoimage.top);
	var expoimageHeight = expoimage.height(); //alert('expoimageHeight = ' + expoimageHeight);
	var windowHeight = 	$(window).height();   //alert('windowHeight = ' + windowHeight);
	var t = offsetExpoimage.top + expoimageHeight + cartoucheHeight - windowHeight;
	
	// ajout GeC: prise en compte de la scrollPosition
	var scrollTop = $(window).scrollTop();   //alert('scrollTop = ' + scrollTop);	
	t -= scrollTop;
	
	if( t >  0 ){
		cartouche.css( "top", -t + "px" );    //alert('cartouche.css top set to ' + (-t) + 'px');
	}

}

var _Niveau1Index = 1;

// Fonction pour faire tout ce qu'il faut dans les écrans de niveau 1
function initNiveau1( str, idx ){
	_Niveau1Index = idx;
	setHeaderTitle( str );
	setPinkBorder( idx );
	$(window).resize( adjustCartouche );
	
	// ajout GeC: prise en compte de la scrollPosition
	$(window).scroll( adjustCartouche );
	
	$(window).load( adjustCartouche );
	//adjustCartouche();
	
	openIntroExpo();
}

function goToChapter( idx ){
	idx = ((idx - 1) % 13);
	if( idx < 0 ) idx += 13;
	document.location.href = 
		$('#chapters .thumb a').eq( idx ).attr( "href" );
}

function prevChapter(){
	goToChapter( _Niveau1Index - 1 );
}

function nextChapter(){
	goToChapter( _Niveau1Index + 1 );
}

// Fonction dans les écrans de niveau 1, pour sélectionner une image
function showCartelImage( idx ){
	//pink border
	$('#cartouche .rthumbsblock .selectionborder').remove();
	$('#cartouche .rthumbsblock .rthumb a')
		.eq( idx - 1 )
		.append( '<div class="selectionborder"></div>' );

	//images
	$('#expoimage img').hide();
	$('#expoimage img')
		.eq( idx - 1 )
		.show();

	//cartels
	$('#cartouche .rightblock .textline').hide();
	$('#cartouche .rightblock .textline')
		.eq( idx - 1 )
		.show();
}

// Ouverture Expo permanente (popup )
function openExpo(){
	var win;
	var W = Math.min( 1024, screen.availWidth );
	var H = Math.min( 750, screen.availHeight );
	var X = ((screen.availWidth-W)/2);
	var Y = 0;
	window.mfpOpenIntroExpo = undefined;
	win = window.open( 
		'about:blank', 
		'MFPExpoWindow', // Utilisé dans la fermeture dans _template.xsl
		'width=' + W + ',height=' + H + ',scrollbars=yes,status=yes,resizable=yes,location=no' );
	try{
		win.moveTo(X,Y);
		win.focus();
	}catch( e ){};
}

//Fonction de retour à l'accueil
function goHome(){
	if( window.opener && window.name == "MFPExpoWindow" ){
		window.close();
	}else{
		document.location.href = "content.php?CID=LQ_SYS_CONTENT_HOME_fr-FR_C";
	}
}

// Impression
function printContent(){
	window.print();
}

/**********************************
	Fonctions pour le plan de l'expo 
***********************************/
var _planExpo = {};

function initPlan( contentId ){
	$('<div id="planexpo"></div>')
		.appendTo('#page')
		.hide()
		.click( closePlanExpo );
	_planExpo.contentId = contentId;
	_planExpo.loaded = false;
	if( _planExpo.timeoutId ) window.clearTimeout( _planExpo.timeoutId );
}

function togglePlan(){
	var jqPlan = $('#planexpo')
	if( jqPlan.css( "display" ) == 'none' ){
		if( !_planExpo.loaded ){
			_planExpo.loaded = true;
			jqPlan
				.html('<div class="ajaxloading"/>')
				.load( '../planExpo.php', {}, planExpoLoaded );
		}
		openPlanExpo();
	}else{
		closePlanExpo();
	}
}

function openPlanExpo(){
	$('#planexpolink a').html( planExpoOff );
	$('#planexpo').show();
	$('#quitlink a').hide();
}

function closePlanExpo(){
	$('#planexpolink a').html( planExpoOn );
	$('#planexpo').hide();
	$('#quitlink a').show();
}

function planExpoLoaded(){
	var jqPlan = $('#planexpo');
	_planExpo.jsBlink = 
		jqPlan.find( "a[href*='content.php?CID=" + _planExpo.contentId + "']" )
			.parent()
			.andSelf()
			.filter( '.blink' );
	blinkPlanActive();
}

function blinkPlanActive(){
	try{
		if( _planExpo.jsBlink.css( "visibility" ) == 'hidden' ){
			_planExpo.jsBlink.css( "visibility", "visible" );
		}else{
			_planExpo.jsBlink.css( "visibility", "hidden" );
		}
		_planExpo.timeoutId = window.setTimeout( "blinkPlanActive()", 1000 );
	}catch( e ){}
}

/**********************************
	Fonctions pour l'introduction de l'expo 
***********************************/
function closeIntroExpo(){
	$('#introexpobackground').hide();
	$('#introexpo').hide();
}
function openIntroExpo(){
	if( window.opener && !window.opener.mfpOpenIntroExpo ){
		window.opener.mfpOpenIntroExpo = 'Open';
		$('#introexpobackground')
			.show()
			.click( closeIntroExpo );
		$('#introexpo')
			.show()
			.click( closeIntroExpo );

	}
}
/**********************************
	Fonctions pour la visionneuse 
***********************************/

// Lancement de la visionneuse
function visionneuse( contentId ){
	document.location.href = 'content.php?CID=' + contentId;
}

// Positionne l'écran sur un index
function setIndexVisionneuse( idx ){
	$('#zoomed').hide();
	$('a.zoom').css( "visibility", "hidden" );
	if( idx == null ) return;
	if( idx[0] == _visio.index[0] && idx[1] == _visio.index[1] ) return; // Même vue;
	if( _visioVues.length <= idx[0] ) return // Pas de chapitre

	// Sélection visionneuse (liens)
	for( var i = 0; i < _visioVues.length; i++ ){
		if( i == idx[0] ){
			$('#chapitre' + i).addClass( "active" );
		}else{
			$('#chapitre' + i).removeClass( "active" );
		}
	}
	// Affichage des vignettes
	var s0 = Math.floor( _visio.index[1] / VISIO_PAGE_SIZE ) * VISIO_PAGE_SIZE;
	var s1 = Math.floor( idx[1] / VISIO_PAGE_SIZE ) * VISIO_PAGE_SIZE;
	if( idx[0] != _visio.index[0] || s1 != s0 ){
		var i, k = Math.min( VISIO_PAGE_SIZE, _visioVues[idx[0]].length - s1 );
		for( i = 0; i < k; i++ ){
			$('#gradient #thumbImage' + i )
				.load( "fragment.php img",
					{CID: _visioVues[idx[0]][i + s1], NUM: 2});
			$('#gradient #thumb' + i ).css( "display", "block" );
		}
		for(; i < VISIO_PAGE_SIZE; i++ ){
			$('#gradient #thumb' + i ).css( "display", "none" );
		}
	}
	// Affichage vue;
	_visio.index = idx;
	$('#gradient .selectionVue').remove();
	if( _visioVues[idx[0]].length > idx[1] ){
		$height = $('#gradient #leftpart').height();
		$('#gradient #leftpart')
			.html('<div class="ajaxloading" style="height: ' + $height + 'px"/>')
			.load( "fragment.php img",
				{CID:  _visioVues[idx[0]][idx[1]], NUM: 1});
		$('#gradient #rightpart')
			.html('<div class="ajaxloading"/>')
			.load( "fragment.php",
				{CID:  _visioVues[idx[0]][idx[1]], NUM: 3});
		// Rose...
		var thumb = $('#gradient #thumb' + (idx[1] % VISIO_PAGE_SIZE) + ' a' );
		thumb.append( '<img class="selectionVue"'
				+ 'src="../res/skinDefault/themeDefault/' 
				+ thumb.children('div').attr( "class" ) + '.jpg" alt="" />' );
	}
	// Gestion de la visibilité des boutons
	//... Des séries
	$('#gradient .arrowback').css( "visibility",
		(getPrevSerieVue() == null ? "hidden" : "visible") );
	$('#gradient .arrownext').css( "visibility",
		(getNextSerieVue() == null ? "hidden" : "visible") );
	//... Suivant/Précédent
	$('#gradient .prevVue').css( "visibility",
		(getPrevVue() == null ? "hidden" : "visible") );
	$('#gradient .nextVue').css( "visibility",
		(getNextVue() == null ? "hidden" : "visible") );	
	// ...Zoom
	// Chargement du zoom 
	$.ajax( {
		url: "fragment.php",
		data: {CID:  _visioVues[_visio.index[0]][_visio.index[1]], NUM: 4},
		success: zoomCallback
		} );
	
	// Pour test	
	//zoomVisionneuse();
}

// Chargement d'une vue de la visionneuse
function vueVisionneuse( contentId ){
	// On donne à l'image d'attente (ajaxloading) une taille identique à l'image qu'on vient de quitter...
	$height = $('#gradient #leftpart').height();
	$('#gradient #leftpart')
		.html('<div class="ajaxloading" style="height: ' + $height + 'px"/>')
		.load( "fragment.php",
			{CID: contentId, NUM: 1});
	$('#gradient #rightpart')
		.html('<div class="ajaxloading"/>')
		.load( "fragment.php",
			{CID: contentId, NUM: 3});
}

// Chargement du chapitre d'une visionneuse
function chapitreVisionneuse( num ){
	setIndexVisionneuse( new Array( num, 0 ) );
}

// Chargement des vignettes d'un chapitre
// Click sur une vignette
function clickVignetteVisionneuse( num ){
	var idx = num + (Math.floor( _visio.index[1] / VISIO_PAGE_SIZE ) * VISIO_PAGE_SIZE);
	setIndexVisionneuse( new Array( _visio.index[0], idx ) );
}

// Série suivante dans un chapitre
function nextSerieVisionneuse(){
	idx = getNextSerieVue();
	if( idx != null ){
		setIndexVisionneuse( idx );
	}
}

// Série précédente dans un chapitre
function prevSerieVisionneuse(){
	idx = getPrevSerieVue();
	if( idx != null ){
		setIndexVisionneuse( idx );
	}
}

// Vignette suivante
function nextVueVisionneuse(){
	idx = getNextVue();
	if( idx != null ){
		setIndexVisionneuse( idx );
	}
}

// Vignette précédente
function prevVueVisionneuse(){
	idx = getPrevVue();
	if( idx != null ){
		setIndexVisionneuse( idx );
	}
}
// Zoom
var _visio = {index: [-1, -1]};
var _zoom = {
	leftmargin: [9, 38, 67, 96, 125],
	scales: [0.2, 0.4, 0.6, 0.8, 1],
	currentScale: 0,
	initialSize: {},
	containerSize: {} };

// Callback de chargement du zoom dans l'initialisation de la visionneuse
function zoomCallback( dataLoaded, textStatus ){
	if( textStatus == "success" && dataLoaded.match( /<img/i ) ){
		$('a.zoom').css( "visibility", "visible" );
		_zoom.data = dataLoaded;
	}
}

// Ouverture du zoom; le code du zoom a été chargé 
function zoomVisionneuse(){
	$('#zoomed').show();
	var div = $('#bigpicture');
	div.css( "visibility", "hidden" );
	_zoom.initialSize = {width: 0, height: 0};
	_zoom.containerSize.width = div.width();
	_zoom.containerSize.height = div.height();
	$('.zoomscale').click( zoomScaleClick );
	div.html( _zoom.data );
	div.find( ":not(img)" ).remove(); // Pour nettoyer les br
	$('#zoomed').addClass( 'ajaxloading' );
	$('#bigpicture img')
		.load( zoomImageLoaded );
	// Un poil compliqué à gérer...
	//$('.zoomscale .cursor')
	//	.draggable( {axis: 'x', containment: 'parent'} );
	
	// Gestion du label du bouton quitter...
	$jqQuitLink = $('#quitlink a');
	_zoom.savedQuitLink = _quitLink;
	_zoom.savedQuitLabel = $jqQuitLink.html();
	$jqQuitLink.html( zoomQuitLabel );
	_quitLink = "zoom";
}

function zoomImageLoaded( e ){
	$('#zoomed').removeClass( 'ajaxloading' );
	var img = $('#bigpicture img');
	_zoom.initialSize.width = img.width();
	_zoom.initialSize.height = img.height();
	zoomScale( 0, true );
	img.draggable( {stop: zoomStopDrag} );
	$('#bigpicture').css( "visibility", "visible" );
}
function zoomScale( scale ){
	// L'image est agrandie ou reduite en prenant pour point fixe le centre de bigpicture,
	// le div englobant...
	var initialScaling = (arguments.length >= 2 ? arguments[1] : false );
	
	// Si la taille n'est pas définie, on bouge pas d'une oreille
	if( _zoom.initialSize.width == 0 ) return;
	
	var img = $('#bigpicture img');
	
	var newWidth = Math.round( _zoom.initialSize.width * _zoom.scales[scale] );
	var newHeight = Math.round( _zoom.initialSize.height * _zoom.scales[scale] );
	
	if( initialScaling ){
		// L'image est restituee a sa plus petite resolution et centree en haut...
		var newLeft = Math.round( (_zoom.containerSize.width - newWidth) / 2 )
		img.width( newWidth )
			.height( newHeight )
			.css( "top", "0px" )
			.css( "left", newLeft + "px" );
	}else{
		// Gestion du top et left pour garder le centre du container fixe
		var oldTop = parseInt( img.css( "top" ) );
		var oldLeft = parseInt( img.css( "left" ) );
		var K = _zoom.scales[scale] / _zoom.scales[_zoom.currentScale];
		var Cw = (_zoom.containerSize.width / 2) * (1 - K);
		var Ch = (_zoom.containerSize.height / 2) * (1 - K);

		var newLeft = Math.round( oldLeft * K + Cw );
		var newTop = Math.round( oldTop * K + Ch );
		img.width( newWidth )
			.height( newHeight )
			.css( "top", newTop + "px" )
			.css( "left", newLeft + "px" );
		zoomCrop();
	}
	$('.cursor').css("left", _zoom.leftmargin[scale] + "px");
	_zoom.currentScale = scale;
}
function incZoomScale(){
	if( _zoom.currentScale < 4 ) zoomScale( _zoom.currentScale + 1 );
}
function decZoomScale(){
	if( _zoom.currentScale > 0 ) zoomScale( _zoom.currentScale - 1 );
}
function zoomScaleClick(  eventObject ){
	var off = $('.zoomscale').offset();
	var x = eventObject.pageX - off.left;
	for( var i = 0; i < _zoom.leftmargin.length - 1; i++ ){
		if( x < (_zoom.leftmargin[i] + _zoom.leftmargin[i+1]) / 2 ){
			return zoomScale( i );
		}
	}
	return zoomScale( _zoom.leftmargin.length - 1 );
}
function finZoomVisionneuse(){
	// Gestion du label du bouton quitter...
	$jqQuitLink = $('#quitlink a');
	$jqQuitLink.html( _zoom.savedQuitLabel );
	_quitLink = _zoom.savedQuitLink;
	
	$('#zoomed').hide();
}
// On empêche que l'image parte trop loin...
function zoomStopDrag( e, ui ){
	zoomCrop();
}

function zoomCrop(){
	var img = $('#bigpicture img');
	var w = img.width();
	var h = img.height();
	var l = parseInt( img.css( "left" ) );
	var t = parseInt( img.css( "top" ) );
	if( w > _zoom.containerSize.width ){
		if( l > 0 ){
			img.css( "left", "0px" );
		}else if( l < (_zoom.containerSize.width - w) ){
			img.css( "left", (_zoom.containerSize.width - w) + "px" );
		}
	}else{
		if( l < 0 ){
			img.css( "left", "0px" );
		}else if( l > (_zoom.containerSize.width - w) ){
			img.css( "left", (_zoom.containerSize.width - w) + "px" );
		}
	}
	if( h > _zoom.containerSize.height ){
		if( t > 0 ){
			img.css( "top", "0px" );
		}else if( t < (_zoom.containerSize.height - h) ){
			img.css( "top", (_zoom.containerSize.height - h) + "px" );
		}
	}else{
		if( t < 0 ){
			img.css( "top", "0px" );
		}else if( t > (_zoom.containerSize.width - h) ){
			img.css( "top", (_zoom.containerSize.height - h) + "px" );
		}
	}
}
// UTILS pour la visionneuse
// Donne l'index de la vue suivante; null si elle n'existe pas
function getNextVue(){
	newVueIdx = _visio.index[1] + 1;
	for( var i = _visio.index[0]; i < _visioVues.length; i++ ){
		if( _visioVues[i].length > newVueIdx ) return new Array( i, newVueIdx );
		newVueIdx = 0;
	}
	return null;
}
// Donne l'index de la vue précédente; null si elle n'existe pas
function getPrevVue(){
	if( _visio.index[1] > 0 ) return new Array( _visio.index[0], _visio.index[1] - 1 );
	for( var i = _visio.index[0] - 1; i >= 0; i-- ){
		if( _visioVues[i].length > 0 ) return new Array( i, _visioVues[i].length - 1 );
	}
	return null;
}
// Donne l'index de la vue dans la série suivante du même chapitre; null si pas possible
function getNextSerieVue(){
	var i = (Math.floor( _visio.index[1] / VISIO_PAGE_SIZE ) + 1) * VISIO_PAGE_SIZE;
	if( _visioVues[_visio.index[0]].length > i ){
		return new Array( _visio.index[0], i );
	}else{
		return null;
	}
}
// Donne l'index de la vue dans la série précédente du même chapitre; null si pas possible
function getPrevSerieVue(){
	var i = (Math.floor( _visio.index[1] / VISIO_PAGE_SIZE ) * VISIO_PAGE_SIZE) - 1;
	if( i >= 0 ){
		return new Array( _visio.index[0], i );
	}else{
		return null;
	}
}

/******************************************
    Fonctions pour la recherche avancée 
*******************************************/

var ADVANCEDSEARCH_CONTENTID = 'LQ_SYS_CONTENT_Recherche_avancee_fr-FR_C';

// Charge la recherche avancée dans une collection données
function advancedSearch_chooseCollection( strCollectionId ){
	
	//Charge l'aide contextuelle
	switch( strCollectionId ){
		case '':
			//Retour au choix de la sélection
			var fnum = 2;
			break;
		case 'MATERIAL':
			//Retour au choix de la sélection
			var fnum = 3;
			break;
		case 'IMAGE':
			//Retour au choix de la sélection
			var fnum = 4;
			break;
		case 'DOCUMENT':
			//Retour au choix de la sélection
			var fnum = 5;
			break;
	}
	
	$('#searchText')
		.html('<div class="ajaxloadingblack"/>')
		.load( 'fragment.php',
			{ CID: ADVANCEDSEARCH_CONTENTID, NUM: fnum} );
	
	//Charge le formulaire
	$('#searchForm')
		.html('<div class="ajaxloadingblack"/>')
		.load( '../advancedSearch.php', { TYPE: strCollectionId}, function(data, textStatus){
			$(".selectHierarchy").each(function(i){
				 
				$(this).treeview({
				collapsed: true,
					animated: "fast", // Nécessaire pour active l'option toggle
					toggle: function() {
						// todo: pour gérer convenablement les [+] dans l'arbre
					}
				}); 
			 });
		});
	
	
}

function advancedSearch_selectHierarchyWindowWithRoot( listId ){
	$('#' + listId).show('fast');	
}

function advancedSearch_resetSelectField( fieldId, listId ){
	$('#' + fieldId).attr('value', '' );
	$('#selectLabel_' + fieldId).html('');
	$('#' + listId).hide('fast');
}

function advancedSearch_closeHierarchy( listId ){
	$('#' + listId).hide('fast');
}

function advancedSearch_selectItem( fieldId, listId, valueId ){
	$('#' + fieldId).attr('value', $('#value-' + valueId).attr('value') );
	$('#selectLabel_' + fieldId).html($('#label-' + valueId).html());
	$('#' + listId).hide('fast');
}

function advancedSearch_validateSearch(){
	var params = $("#advancedSearchForm .advancedSearchForm").serializeArray();
	
	$('#searchText')
		.html('<div class="ajaxloadingblack"/>');
	
	//Charge le formulaire
	$('#searchForm')
		.html('<div class="ajaxloadingblack"/>');
	
	$.ajax({
		type: "POST",
		url: "../advancedSearch.php?OP=search",
		data: params,
		dataType: "json",
		success: advancedSearch_searchCallback
	});
}

function advancedSearch_gopage( page ){
	var params = $("#advancedSearchForm :input").serializeArray();
	
	//Charge le formulaire
	$('#searchForm')
		.html('<div class="ajaxloadingblack"/>');
	
	$.ajax({
		type: "POST",
		url: "../advancedSearch.php?OP=search&PAGE=" + page,
		data: params,
		dataType: "json",
		success: advancedSearch_searchCallback
	});
}

function advancedSearch_searchCallback(data, textStatus){
	//Le résultat du post est un JSON

	if( data.nbResult == 0 ){
		//Recherche infructueuse
		$('#searchText')
			.html('<div class="ajaxloadingblack"/>')
			.load( 'fragment.php',
				{ CID: ADVANCEDSEARCH_CONTENTID, NUM: 7} );
	} else {
		//On a des résultat
		$('#searchText')
			.html('<div class="ajaxloadingblack"/>')
			.load( 'fragment.php',
				{ CID: ADVANCEDSEARCH_CONTENTID, NUM: 6} );
	}

	$('#searchForm')
		.html(data.html);
	/*
	$(data.html).load(function(){
		alert('toto');
		$('#searchForm')
			.html(this);
	});
	*/
}
function closeObject(){
	$('#objectDetail').hide();
}
function showObject( id, img ){
	$('#objectDetail')
		.html('<div class="ajaxloading"/>')
		.show()
		.load( 
			"../object.php?ID=" + id + "&IMG=" + img,
			{FILTER: 'detail'} );
}



