
var pannel,
	pannelUI = {
		dimensions: {
			min: {
				height: 0,
				//height: 293,
				//width: 178,
				width: 0,
				top: 165,
				//top: 185,
				left: 0
				},
			max: {
				height: 560,
				width: 958,
				top: 165,
				left: 0
				}
		},
		styles: {
			min: {
				//borderColor: '#D0D0D0',
				borderColor: '#FFFFFF',
				borderWidth: '2px',
				borderHoverColor: '#3D3D3D'
			},
			max: {
				borderColor: '#000000',
				borderWidth: '4px'
			}
		},
		toggleView: function(options){
			if (pannel.data('isExpanded')){
				this.close(options);
			}else{
				this.open(options);
			}
		},
		open: function(options) {
			//console.log('[pannelUI] open begins');
			if (pannel.data('isExpanded')){
				//console.log('[pannelUI] pannel already opened. Aborting...');
				return
			}
			var dimensions = this.dimensions,
				styles = this.styles;
	
			// Maximize pannel
			pannel.data('isExpanded', true).css('outline', '0').addClass('pannel-opened');
			timbres.fadeOut();
			pannel
			.empty()
			.append('<div style="width: 100%; height: 100%; background-color: #ffffff; display: none;"></div>')
			.animate(
				{
					width: dimensions.max.width ,
					height: dimensions.max.height,
					borderWidth: styles.max.borderWidth,
					left: dimensions.max.left,
					top: dimensions.max.top
				},300,'easeInQuint',
				function() {
					pannel
						.css('border-color', styles.max.borderColor)
						.append(mapIframe.show())
						.show();
					jQuery('.carte-print').show();
				}
			)
			.find('div')
			.animate({opacity: 'show'}, 1500, function(){
				pannel.children('div').remove();
			});
			// Modification du stylage en vue de l'impression
			jQuery('#contenu-accueil-centre, #um-contenu-droite').addClass('no-print');
	
			// stockage dans l'historique de navigation du browser
			jQuery.history.load(location.hash.replace(/^#/,''));
			
			//console.log('[pannelUI] open ends...');
		},
		close: function() {
			//console.log('[pannelUI] close begins');
			if (!pannel.data('isExpanded')){
				//console.log('[pannelUI] pannel already closed. Aborting...');
				return
			}
			var dimensions = this.dimensions,
				styles = this.styles;
	
			// Minimize pannel
			jQuery('.carte-print').hide();
			jQuery('#carte-print').empty();
			timbres.fadeIn();
			mapIframe.fadeOut(600, function() {
				jQuery(this).remove();
			});
			// IE6 plante au moment d'animer la fermeture du panneau, allez savoir pourquoi...
			var duration = (jQuery.browser.msie && jQuery.browser.version == 6) ? 0 : 300;
			pannel
			.animate(
				{
					width: dimensions.min.width ,
					height: dimensions.min.height,
					borderWidth: styles.min.borderWidth,
					left: dimensions.min.left,
					top: dimensions.min.top
				}, duration, 'easeInQuint',
				function(){
					pannel
						.css({
							borderColor: styles.min.borderColor,
							top: dimensions.min.top
							})
						.empty()
						.append('<img src="bibECLAIR/images/pixel.gif" border="0" style="width: 100%; height: 100%" />') /* IE fix */
					.data('isExpanded', false)
					.removeClass('pannel-opened');
				}
			);
			// Restauration du stylage en vue de l'impression
			jQuery('#contenu-accueil-centre, #um-contenu-droite').removeClass('no-print');
			// stockage dans l'historique de navigation du browser
			jQuery.history.load('');
			//console.log('[pannelUI] close ends...');
		}
	},
	// newHash: lorsque non nulle, contient l'id de la bulle à ouvrir. 
	newHash = null;

function handleHistoryEvents(){
	// On branche le plugin history sur les gestionnaires d'événements de l'objet infoHelper qui contrôlent l'ouverture et la fermeture des bulles (dans le iframe). On peut ainsi sauvegarder dans l'historique du navigateur l'état de l'interface à chaque changement.
	//console.log('[handleHistoryEvents]');
	mapIframe[0].contentWindow.jQuery(mapIframe[0].contentWindow.infoHelper).bind('openInfowindow', function(event, hash){
		//parent.console.log('[handleHistoryEvents] openning %s',hash);
		jQuery.history.load('bibECLAIR/' + hash);
	});
	mapIframe[0].contentWindow.jQuery(mapIframe[0].contentWindow.infoHelper).bind('closeInfowindow', function(){
		//parent.console.log('[handleHistoryEvents] closing infowindow');
		jQuery.history.load('bibECLAIR');
	});
}

function historyChanged(hash) {
	// Fonction callback pour le plugin history.
	// S'exécute lorsque l'usager se déplace dans l'historique du navigateur.
	// On peut aussi l'exécuter sur demande pour mettre à jour l'interface.
	var isExpanded = pannel.data('isExpanded');//,
	var launchPannel = false;
	//console.log('[historyChanged]');
	hash = hash.toLowerCase().replace(/\/$/,'').split('/');
	if (hash[0] == '') {
		//console.log('[historyChanged] Empty string \'\' hash found');
		pannelUI.close();
	}
	else if (hash[0] == 'bibeclair' || hash[0] == 'babillard'){
		pannelUI.open();
		hash[1] = hash[1] || '';
		//console.log('[historyChanged] New hash found \'%s\'',hash[1]);
		newHash = hash[1];
	}
}

jQuery(window).load(function(){
	var d = pannelUI.dimensions;
	window.timbres = jQuery('#timbres');
	window.mapIframe = jQuery('<iframe id="mapIframe" width="100%" height="100%" scrolling="no" frameborder="0" />');
	mapIframe.attr('src', 'bibECLAIR/default.htm');
	mapIframe.load(function(){
		//console.log('mapIframe loaded');
		mapIframe.data('loaded',true);
	});
	// L'image transparente est nécessaire dans IE pour que la boîte ait une largeur et une longueur != 0
	pannel = jQuery('<div id="pannel" class="pannel no-print"><img src="bibECLAIR/images/pixel.gif" border="0" style="width: 100%; height: 100%" /></div>')
		.data('isExpanded', false)
		.css({
			height: d.min.height,
			width : d.min.width,
			top: d.min.top,
			left: d.min.left
	  	})
		.appendTo('#um-enveloppe')
		/* à désactiver au besoin
	  	.hover(
			function(){
				if (!jQuery(this).data('isExpanded')) {
					console.log('hover in');
					var hoverColor = pannelUI.styles.min.borderHoverColor;
					jQuery(this).stop().animate({borderTopColor: hoverColor, borderRightColor: hoverColor, borderBottomColor: hoverColor, borderLeftColor: hoverColor}, 'fast');
				}
			},
			function(){
				if (!jQuery(this).data('isExpanded')) {
					console.log('hover out');
					var color = pannelUI.styles.min.borderColor;
					jQuery(this).stop().animate({borderTopColor: color, borderRightColor: color, borderBottomColor: color, borderLeftColor: color}, 'fast');
				}
			}
		)
	  	.click(function() {
			// On affiche le message de bienvenue par défaut
			var hash = location.hash.replace(/^#/,'').replace(/\/$/,'');
			if (hash.split('/').length == 1 && !pannel.data('isExpanded')){
				newHash = 'bienvenue';
				jQuery.history.load('babillard/bienvenue');
			}
			pannelUI.toggleView();
		});
		 fin de la désactivation */
	// initialisation du plugin jquery.history
	jQuery.history.init(historyChanged);
	
	jQuery('a[href^=#babillard], a[href^=#bibECLAIR]').click(function(e){
		e.preventDefault();
		// On affiche le message de bienvenue par défaut
		var hash = location.hash.replace(/^#/,'').replace(/\/$/,'');
		if (hash.split('/').length == 1 && !pannel.data('isExpanded')){
			newHash = 'bienvenue';
			jQuery.history.load('bibECLAIR/bienvenue');
		}
		pannelUI.toggleView();
	});
	
	// On met à jour l'interface en fonction de l'ancre présente dans l'URL de la page
	jQuery.fx.off = true;
	historyChanged(location.hash.replace(/^#/,''));
	jQuery.fx.off = false;
});
