/* Définition des comportements javascript du site */
/* Activer les effets sur les formulaires  */
function setCSSBehaviours() {
	$$('.themes select').addEvent('change', function() { console.log(this); });
	
	$$('a.back, a.retour').addEvent('click', function(e) {
		if (document.referrer.indexOf(location.protocol+'//'+location.hostname) == 0) {
			history.back(); new Event(e).stop();
		}
	});
	$$('#nav-contenu .print').addEvent('click', function(e) { window.print(); new Event(e).stop(); });
	// Séparateurs dans le texte
	var separateur = new Element('div', {'class': 'separateur'});
	$$('hr').each( function(hr) { separateur.clone().replaces(hr); } );
/*	$$('#nav form#recherche').addEvent('submit', function(e) {
		var myHTMLRequest = new Request.HTML({
				'url': addtpl(this.action,'recherche'),
				'onSuccess' : function(responseTree, responseElements, responseHTML, responseJavaScript) { minipopup('<h2>Recherche</h2>'+responseHTML,'width:600px;height:600px;'); }
		}).get(this);
		new Event(e).stop();
	});
	*/
}

function start_ajax_request(elem) {
	if (elem == null) elem = $('preview');
	elem.set('opacity', 0.6).setStyle('cursor', 'wait');
}
function end_ajax_request(elem) {
	if (elem == null) elem = $('preview');
	elem.set('opacity', 1).setStyle('cursor', 'default');
}
window.addEvent('domready', setCSSBehaviours);
window.addEvent('load', function() {
	$$('#contenu img').each (function (img) {
		if (img.hasClass('noauto')) return;
		if (img.src.indexOf('INTERVAL') != -1) return;
		legende = '';
		// Vérifier si on n'est pas dans un <div> gauche droite ou centre
		var parent = img.getParent('div');
		if (parent.hasClass('gauche') || parent.hasClass('droite') || parent.hasClass('centre')) {
			return;
		}
		// Mettre le TITLE de l'image en légende dessous
		if (!img.hasClass('nolegend'))
		{
			if (img.get('title')) {
				legende = new Element('span').set('text', img.get('title'));
			}
			/*
			else if (img.get('alt')) {
				legende = new Element('span').set('text', img.get('alt'));
			}
			*/
		}
		// Détecter les zooms
		a = img.getParent();
		if (a.get('tag') == 'a') {
			if (!a.getProperty('rel') && a.href.match(/(jpg|png|gif)$/i)) {
				a.setProperties({ 'rel': 'lightbox[]', 'title': (legende!=''?legende.get('text'):'')});
			}
		} else { a = false; }

		// Mettre un conteneur div autour des images alignées
		var iclass, align;
		if (!img.getProperty('align') && img.getProperty('class')) {
			iclass = img.getProperty('class');
			img.removeProperty('class');
			img.removeProperty('align');
		} else if (img.getProperty('align')) {
			align = img.getProperty('align');
			if (align == 'left') { iclass = 'gauche'; }
			else if (align == 'right') { iclass = 'droite'; }
			else { iclass = 'centre'; }
			img.removeProperty('align');
		} else iclass = 'centre';
		div = new Element('div', { 'class': iclass });
		if (legende) {
			legende.injectInside(div);
			if (iclass == 'gauche' || iclass == 'droite') {
				div.setStyle('position', 'relative');
				legende.setStyles({
					'padding': '5px',
					'position': 'absolute',
					'bottom': 0,
					'right': 0,
					'left': 0,
					'color': '#FFF',
					'background': 'transparent url(images/opacity.png)'
				});
			}
		}
		if (a != false) {
			// On injecte le lien
			a.clone().injectTop(div);
			div.replaces(a);
		} else {
			// Pas de lien, on injecte l'image
			img.clone().injectTop(div);
			div.replaces(img);
		}
	});
	if (typeof Slimbox != 'undefined') {
		Slimbox.scanPage();
	}

	// Mettre la taille des div droite & gauche à celle de l'image...
	$$('div.gauche, div.droite, div.centre').each( function(div) {
		// Trouver l'image
		var img = div.getElement('img');
		if (img) {
			img.addEvent('load', function(e) { if (this.width > 0) { div.setStyle('width', this.width+'px'); } });
		}
	} );
});

window.addEvent('domready', function() {
	// Vérification des liens
	var uri = location.protocol+'//'+location.host;
	$$('#preview a[href]').each( function(a) {
		var ext, infos, flength;
		if (a.hasClass('noauto')) return;
		if (a.getElement('img')) return;
		if (a.href.search(/(pdf|doc|rtf|xls|xla|ppt|pps|zip|rar|jpg|png|gif)$/i) != -1) {
			ext = RegExp.$1;
			infos = ext.toUpperCase();
			a.addClass('icone fichier '+ext);
			flength = '';
			new Request({
				method: 'HEAD',
				url: a.href,
				emulation: false,
				async: true,
				onSuccess: function() {
					if (flength = this.getHeader('Content-Length')) {
						infos += ', '+(flength/1024).round()+' Ko';
					}
					new Element('span').set('text', ' ('+infos+')').injectInside(a);
					a.setProperty('title', a.title+' ('+infos+')');
				},
				onFailure: function() {
					a.addClass('broken');
					new Element('span').set('text', ' ('+infos+')').injectInside(a);
					a.setProperty('title', a.title+' ('+infos+')');
				}
			}).send();
		} else if (a.href.indexOf(uri) != 0 && a.href.indexOf('http') == 0) {
			a.addClass('icone url');
			if (!a.getProperty('target')) a.setProperty('target', '_blank');
		} else if (a.href.indexOf('mailto:') == 0) {
			a.addClass('icone email');
		}
	});
});

function minipopup(html, style) {
	if ($('minipopup')) {
		$('minipopup').dispose();
	}
	var div = new Element('div', { 'id': 'minipopup', 'style': "position:absolute;visibility:hidden;width:450px;height:400px;overflow:auto;border:1px solid #000;padding:5px;padding-right:10px;background:#FFF;"+style });
	if (typeof html == 'string') {
		div.set('html', html);
	} else {
		div.adopt(html);
	}
	var a = new Element('a').set({
		'class': 'close',
		'style': 'clear: both; float: none; display: block; text-align: right',
		'href': '#',
		'text': 'Fermer'
	});
	a.clone().injectTop(div);
	a.clone().injectBottom(div);
	div.injectInside($('contenu') || document.getElement('body'));
	var d = div.getSize();
	var w = window.getSize();
	function repos() {
		var s = window.getScroll();
		var left = (w.x/2-d.x/2+s.x)+'px';
		var top = (w.y/2-d.y/2+s.y)+'px';
		div.setStyles({
			'visibility': 'visible',
			'left': left,
			'top': top
		});
	}
	window.addEvent('scroll', repos);
	repos();
	div.getElements('.close').addEvent('click', function(event) { div.dispose(); window.removeEvent('scroll', repos); event.stop(); });
	div.getElements('label').addEvent('click', function() { div.dispose(); window.removeEvent('scroll', repos); });
	document.getElement('body').addEvent('click', function() { div.dispose(); window.removeEvent('scroll', repos); });
	div.addEvent('click', function(event) { event.stopPropagation(); } );
}

function addtpl(url, tpl) {
	if (url.indexOf('tpl=') != -1) return url.replace(/tpl=[^&]+/, 'tpl='+tpl);
	if (url.indexOf('?') == -1) return url+'?tpl='+tpl;
	else return url+'&tpl='+tpl;
}

if (typeof console != "object") {
	var console = {
		'log':function(){}
	};
}
