$(function() {

	//$.taconite.debug = true;
	
	$('div.blockUI.blockMsg.blockPage').livequery(function() {
		if ($(this).is(':visible')) {
			$('#page').addClass('hidden');
		}
		fixPngPopup();
	});
	
	$.ajaxSetup({
		type: "POST"/*,
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$.blockUI({
				message: '<div class="blockui_popup"><h1>Erreur Ajax !</h1><p class="fermer_fenetre"><a href="#" class="unblockui">Fermer la fenêtre</a></p><p>Type d\'erreur : '+textStatus+' ('+errorThrown+')</p></div>'
			});
		}*/
	});
	
	
	if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
		$('div.blockUI').livequery(function() {
			if($(this).is(':visible')) {
				$(this).bgiframe();
			}
		});
	}
	
	// galerie photo en lightbox
	$('p.galerie span a').colorbox({
		current: "{current}/{total}",
		previous: "Précédente",
		next: "Suivante",
		close: "Fermer",
		maxHeight: "90%",
		maxWidth: "90%",
		transition: "elastic"
	});
	
	$('p.galerie > a').livequery('click',function() {
		$(this).parent().find("span a:first").click();
		return false;
	});
	
	
	// XITI : mesure des clics
	$('a, input:button, input:submit').livequery('click',function() {
		var libelle = $(this).text();
		var type_clic;
		
		var url_base = /((http|https):\/\/[A-Za-z0-9._-]{0,})/.exec(top.location.href);
		var expr = new RegExp("^"+url_base[1]+"|^\/|^javascript|^#","g"); // pour tester si c'est un lien interne
		
		if ($('img',this).size() > 0) {
			libelle = $('img:first',this).attr('alt');
		}
		if ($(this).parents('div.docs_associes').size() > 0 || $(this).hasClass("statsT")) { // téléchargement
			type_clic = "T";
		} else if ($(this).is('input:button, input:submit')) { // action
			if ($(this).attr("value") != "") {
				libelle = $(this).attr("value");
			} else {
				if ($(this).attr('id') == "checklater") {
					libelle = "Validation email plus tard";
				} else if ($(this).attr('id') == "checknow") {
					libelle = "Confirmation email";
				} else if ($(this).attr('id') == "goagence") {
					libelle = "Connexion agence";
				}
			}
			type_clic = "A";
			//on ajoute le name du formulaire
			libelle += "_"+$(this).parents('form').get(0).name;
			
		} else if ($(this).is('a') && expr.test(this.href) == false) { // sortie
			type_clic = "S";
		} else { // navigation
			type_clic = "N";
		}
		
		//alert(type_clic+" :"+libelle+":");
		/*if (typeof xt_med == "function") {
			console.log("xt_med('C','','"+cleanString(libelle)+"','"+type_clic+"')");
			xt_med('C','',cleanString(libelle),type_clic);
		}*/
		
		if (typeof xt_click == "function") {
			//console.log("xt_click(this,'C','','"+cleanString(libelle)+"','"+type_clic+"')");
			xt_click(this,'C','',cleanString(libelle),type_clic);
		}
	});
	
	// on supprime les styles en dur des anciens gabarits SPIP
	$('#contenu div[style]').not('div[id*=partof]').each(function() {
		$(this).removeAttr('style');
	});
	
	// fix pour les png transparents. Merci IE6 !
	if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
		$.ifixpng('/imgs/pixel.gif');
		$('img, input[type=image], #masthead, #masthead div.mea, #main, #block_menu ul, #rech_top, #footer, #fsDepot, p.fermer_fenetre a').ifixpng();
		//$('#masthead').css({"position":"static", "z-index":"1000"});
		$('#onglets img').hover(function() {
			$(this).ifixpng();
		},function() {
			$(this).ifixpng();
		});
	}
	
	/*$('#bloc_menu ul').accordion({
		active: false,
		autoHeight: false,
		header: ".header"
	});*/
	

	/* utilisation dans le menu de gauche sur les entrées qui se déplient ! */
	$('a.has_menu').livequery('click',function() {
		$(this).parent().toggleClass('selected').find('> ul').toggle();
		return false;
	});
	
	// on enleve le focus sur les liens qui contiennent #
	$('a[@href*=#]').livequery('click',function() {
		$(this).blur();
	});
	
	
	$.blockUI.defaults = {
		message: '<h1>Veuillez patienter</h1>',
		css: {
			backgroundColor: '#fff',
			border: 'none',
			color: '#000',
			cursor: 'default',
			left: '50%',
			margin: '0 0 0 -15%',
			padding: 0,
			textAlign: 'center',
			top: '25%',
			width: '30%'
		},
		
		// styles for the overlay 
		overlayCSS:	{
			backgroundColor: '#000',	
			opacity: '0.6'
		},
		
		// z-index for the blocking overlay 
		baseZ: 1000,
		
		// set these to true to have the message automatically centered 
		centerX: true,// <-- only effects element blocking (page block controlled via css above) 
		centerY: true,
		
		// allow body element to be stetched in ie6; this makes blocking look better 
		// on "short" pages.	disable if you wish to prevent changes to the body height 
		allowBodyStretch: true,
		
		// be default blockUI will supress tab navigation from leaving blocking content; 
		constrainTabKey: true, 
		
		// fadeOut time in millis; set to 0 to disable fadeout on unblock 
		fadeOut:	400, 
		
		// suppresses the use of overlay styles on FF/Linux (due to significant performance issues with opacity) 
		applyPlatformOpacityRules: false 
	};
	
	// fermer une popup générée avec blockUI
	$('a.unblockui').livequery('click',function() {
		$.unblockUI({
            onUnblock: function() {
				$('#page').removeClass('hidden');
			}
        });
		return false;
	});
	
	// affichage d'une popup de teasing quand on clique sur un lien en tant que VA
	$('a.nocatal').livequery('click',function() {
		if ($('#bloc_menu div.teasing #request_uri').size() == 0) {
			$('#bloc_menu div.teasing form').prepend('<input type="hidden" name="request_uri" id="request_uri" value="" />');
		}
		$('#request_uri').val(this.href);
		$.blockUI({
			message: $('#bloc_menu div.teasing'),
			css: {
				cursor: 'default',
				marginLeft: "-269px",
				top: '10%',
				width: "538px"
			}
		});
		fixPngPopup();
		return false;
	});
	
	
	$('p.popup_imprimer a, p.imprimer a, a.imprimer, #lien_imprimer a').livequery('click',function() {
		window.print();
		return false;
	});
	
	// info bulle sur les pictos services dans le masthead
	$('#mast_pictos img, .pictos_services img').tooltip({
		delay: 0,
		extraClass: "pictos_services",
		left: -20,
		showURL: false,
		track: true,
		top: 20
	});
	
	// Zoom sur une photo au passage de la souris
	//$('.zoom a').tooltip({
	$('.zoom a').livequery(function() {
		if ($(this).parent().hasClass("lightbox") == false) {
			var lien = this;
			$(lien).tooltip({
				bodyHandler: function() {
					var url = lien.href.substring(lien.href.indexOf('#')+1);
					return $("<img/>").attr("src", url);
				},
				delay: 0,
				extraClass: "zoom",
				showURL: false,
				top: -173
			}).click(function() {
				lien.href = lien.href.substring(0,lien.href.indexOf('#'));
				//return false;
			});
		}
	});
	
	
	$('.lightbox a, .schemas li a')
		.each(function() { // petit hack pourri pour virer les images inexistantes sur Piwigo
			if ($(" > img",this).size() > 0 && $(" > img",this).height() <= "1" && $(" > img",this).width() <= "1") {
				$(this).parent().remove();
			}
		})
		.colorbox({
			current: "{current}/{total}",
			previous: "Précédente",
			next: "Suivante",
			close: "Fermer",
			maxHeight: "90%",
			maxWidth: "90%",
			resize: false,
			transition: "elastic"
		},function() {
			fixPngPopup();
		});
	
	// lien "changer d'agence" dans le masthead
	$('#changer_agence').bind('mouseenter', function() {
		$('#changer_agence > ul').show().bgiframe();
		$('#mast_infos_agence').css({zIndex: 1000});
		
	}).bind('mouseleave', function() {
		//console.log('leave');
		$('#changer_agence > ul').hide().bgiframe();
		$('#onglets li:last').show();
		$('#mast_infos_agence').removeAttr('style');
	});
	
	// lien vers l'aide dans le masthead
	$('#mast_help a').click(function() {
	
		ajax_blockui();
		$.ajax({
			url: this.href,
			success: function(response) {
			
				var html = $(response);
				var width = 0;
				var height = '620px';
				var margin = 0;
				$("img, object",html).each(function() {
					if ($.browser.msie) {
						$("body").append($(this).css({"position": "absolute", "top":"0", "left": "-9999px"}));
					}
					//width = ($(this).attr('width') > width) ? parseInt($(this).attr('width'))+30 : width;
					width = ($(this).attr('width') > width) ? parseInt($(this).attr('width')) : width;
					if ($.browser.msie) {
						$(this).remove();
					}
					margin = width / 2;
				});
				//console.log(width);
				
				$.blockUI({
					message: '<div class="blockui_popup">'+response+'</div>',
					css: {
						bottom: '10px',
						height: height,
						marginLeft: '-'+margin+'px',
						top: '10px',
						overflow: 'auto',
						width: width+'px'
					},
					centerY: true
				});
				fixPngPopup();
			}
		});
		return false;
	});
	
	//maj GM : 07/12/2009 - Suppression des mea contenant des formulaires DB2 en cas de DB2=NON !!
	$("td div.mea span.nodb2").parent().parent().hide();
	$("div.mea span.nodb2").parent().hide();
	$("a.nodb2").hide();
	
});

function ajax_blockui() {
	$.blockUI({
		message: '<p style="padding: 50px;"><img src="/imgs/_v2/ajax-loader-big.gif" /></p>',
		css: {
			marginLeft: '-221px',
			width: '442px'
		}
	});
}
function ajax_wait(show) {
	if (show) {
		var position = ($.browser.msie && navigator.appVersion.indexOf('MSIE 6') > -1) ? "absolute" : "fixed";
		$('body').prepend('<p id="wait" style="background: red; color: #FFF; font-weight: bold; padding: 5px; position: '+position+'; right: 0; top: 0; z-index: 1000;">Veuillez patienter</p>');
	} else {
		$('#wait').remove();
	}
}

function fixPngPopup() {
	if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
		$('div.blockUI *, #colorbox *').ifixpng();
	}
}

function cleanString(txt) {
	var caractere1 = "éêèëîïíàâáùüûçñôöó";
	var caractere2 = "eeeeiiiaaauuucnooo";
	var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-_:~\\/";
	txt = txt.toLowerCase();
	for (i = 0; i < txt.length; i++) {
		var pos = caractere1.indexOf(txt.charAt(i));
		if (pos != -1) {
			txt = txt.substring(0, i) + caractere2.charAt(pos) + txt.substring(i+1, txt.length);
		} else {
			pos = alphabet.indexOf(txt.charAt(i));
			if (pos == -1) {
				txt = txt.substring(0, i) + '_' + txt.substring(i+1, txt.length);
			}	
		}
	}
	return txt;
}

function getDt() {
	var tmp = new Date();
	return tmp.getHours()+""+tmp.getMinutes()+""+tmp.getSeconds()+""+tmp.getMilliseconds();
}
