$(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 && /6.0/.test($.browser.version)) {
		$('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').live('click',function() {
		$(this).parent().find("span a:first").click();
		return false;
	});
	
	
	// XITI : mesure des clics
	$('a, input:button, input:submit').live('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).hasClass("statsT") || $(this).parents('div.docs_associes').size() > 0) { // téléchargement
		if ($(this).hasClass("statsT") || /\/spip\/IMG/.test($(this).attr("href"))) { // 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 && /6.0/.test($.browser.version)) {
		$.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').live('click',function() {
		$(this).parent().toggleClass('selected').find('> ul').toggle();
		return false;
	});
	
	// on enleve le focus sur les liens qui contiennent #
	$('a[href*=#]').live('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%'
		},
		
	    // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w 
	    // (hat tip to Jorge H. N. de Vasconcelos) 
	    iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
	    // force usage of iframe in non-IE browsers (handy for blocking applets) 
	    forceIframe: false,
		
		// 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,

		showOverlay: true
	};
	
	// fermer une popup générée avec blockUI
	$('a.unblockui').live('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').live('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').live('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"
		},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;
	});
	
	
	/** ouverture d'un div en lightbox
	 * 
	 * <a href="#[id du div a afficher]_[largeur]_[hauteur]" class="lightbox">lien</a>
	 */
	$('a.lightbox').live('click',function() {
		var tmpId = this.href.substring(this.href.indexOf('#'));
		
		var tab = tmpId.split("_");
		var tabId = new Array();
		var tabDim = new Array();
		var id = "";
		for (var i = 0; i < tab.length; i++) {
			if (isNaN(tab[i])) {
				tabId.push(tab[i]);
			} else {
				tabDim.push(tab[i]);
			}
		}
		
		$.blockUI({
			message: $(tabId.join("_")),
			css: {
				bottom: '10px',
				height: (tabDim[1] != null)? tabDim[1]+'px' : '50%',
				marginLeft: '-'+((tabDim[0] != null)? (tabDim[0] / 2)+'px' : '25%'),
				top: '10%',
				overflow: 'auto',
				width: (tabDim[0] != null)? tabDim[0]+'px' : '50%'
			},
			centerY: true
		});
		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();
	
	
	// recuperation des infos du navigateur dans le formulaire de contact
	if ($(':input[name=form_browser_infos]').size() > 0) {
		var browser_infos = navigator.userAgent;
		var flash = false;
		var flashVersion;
		// on teste la présence du plugin Flash
		if(navigator.plugins.length > 0) {
			for (i in navigator.plugins) {
			    for (j in navigator.plugins[i]) {
			        if (/Shockwave Flash/.test(navigator.plugins[i][j])) {
			            flash = true;
			            flashVersion = navigator.plugins[i].version;
			        }
			    }
			}
		} else {
			// pour IE : solution pas très jolie
			for(var i=20; i>0; i--) {
				flashVersion = 0;
				flash = false;
				try{
					var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
					flashVersion = i;
					flash = true;
					break;
				}
				catch(e){
				}
			}
		}
		
		browser_infos += (flash == true) ? " | Flash activé (version "+flashVersion+")" : " | Pas de plugin Flash";
		$(':input[name=form_browser_infos]').val(browser_infos);
	}
	
});

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 && $.browser.version.indexOf('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 && /6.0/.test($.browser.version)) {
		$('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();
}
