/* Définition des comportements javascript du site */
/* Activer les effets sur les formulaires  */
function setCSSBehaviours() {
	
	$$('select#departement, .themes select').addEvent('change', function() { this.form.submit(); });
	$$('a.back, a.retour').addEvent('click', function(e) {
		if (document.referrer.indexOf(location.protocol+'//'+location.hostname) == 0) {
			history.back(); new Event(e).stop();
		}
	});
	$$('a.print').addEvent('click', function(e) {
		var p = new Element('div');
		p.set('load', {
			'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {
				var w = window.open('');
				w.document.write(responseHTML.replace('<div id="preview"></div>', '<div id="preview">'+$('preview').get('html')));
				w.document.close();
				w.print();
			}
		});
		p.load('fr/?tpl=print&tplonly=1');
		return false;
	});
	$$('#coldroite input').addEvent('focus', function(e) { this.select(); });
	// Séparateurs dans le texte
	var separateur = new Element('div', {'class': 'separateur'});
	$$('hr').each( function(hr) { separateur.clone().replaces(hr); } );
	$$('#catalogue li[class^=f1-OCC]').setStyle('display', 'none');
	$$('#catalogue ul').each(function(ul) {
		var c = 0;
		ul.getChildren('li[class^=f2]').each(function(li) {
			c++;
			if ((c % 6) == 0) {
				new Element('li').addClass('separator').injectBefore(li);
			}
			var child = li.getChildren();
			if (child && child.length == 1) {
				// Si on n'a pas de sousmenu, ajouter un div qui ferme le menu
				new Element('div').set({'class': 'single'}).injectInside(li);
			}
		});
	})
	
	if ($('accordion')) {
		window.accordeon = new Accordion(
			$$('.drag'), // Balises poignée (nom du div ou on clique pour ouvrir la fiche)
			$$('.content'),	// Contenu à cacher
			{ show: 0, opacity: false, alwaysHide: true },
			$('accordion')
		);
		var n = 0;
		var x = 0;
		// Repérer l'élément selectionné
		$$('.drag').each(function(node) {
			n = n+1;
			if (node.hasClass('select')) { x = n; }
		});
		if (x > 0) { window.accordeon.display(x-1); }
	}	
	var myAccordion = new Accordion($('accordion'), 'div.drag', '.content', {
		opacity: false,
		display: -1,
		alwaysHide: true,
		onActive: function(toggler, element){
			toggler.setStyle('background', 'url(images/bg_fleche-bas.gif) no-repeat scroll left top');
		},
		onBackground: function(toggler, element){
			toggler.setStyle('background', 'url(images/bg_fleche-droite.gif) no-repeat scroll left top');
		}
	});	
	
}

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
		done = false;
		$$('div.gauche, div.droite, div.centre').each( function(div) {
			if (!done) if (div.hasChild(img)) { done = true; }
		});
		if (done) return;
		// Mettre le TITLE de l'image en légende dessous
		if (img.get('title') && !img.hasClass('nolegend')) {
			legende = new Element('span').set('text', img.get('title'));
		}
		// 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': img.getProperty('alt') });
			}
		} 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 (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'); } });
			div.setStyle('text-align', 'center');
		}
	} );
});

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',
				emulation: false,
				url: a.href,
				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;z-index:9999;visibility:hidden;width:450px;height:400px;overflow:auto;border:1px solid #000;padding:5px;padding-right:10px;cursor:move;background:#FFF;"+style });
	html = '<div style="text-align:right"><a href="#" class="close">X</a></div><br style="clear: both">'+html+'<div style="text-align:right; clear: both"><a href="#" class="close">X</a></div>';
	div.set('html', html);
	if (div.makeDraggable) { div.makeDraggable(); }
	div.injectInside(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(){}
	};
}
var addScroller = function(container_name) { 
	var i = 0;
	var elems = $$('#' + container_name + ' .element');
	var totalheight = 0;
	elems.each(function(el) { totalheight += el.getStyle('height').toInt(); });
	var container = $(container_name);
	if(!container)
		return;
	var myScroll = new Fx.Scroll(container);
	function scrollDown() {
		i--;
		if (elems[i]) {
			myScroll.toElement(elems[i]);
		} else {
			i++;
		}
	}
	function scrollUp() {
		i++;
		if (elems[i]) {
			myScroll.toElement(elems[i]);
			if (container.getScroll().y > totalheight) {
				// Bloquer au dernier
				i--;
			}
		} else {
			i--;
		}
	}		

	var s = new Element('div').setProperty('id', 'scroll-'+container_name).set('html', '<img src="images/suivant.png" class="noauto d"> <img src="images/precedent.png" class="noauto u">');
	s.addClass('scroll');
	s.getElements('img.d').addEvent('click', scrollUp);
	s.getElements('img.u').addEvent('click', scrollDown);
	s.injectBefore($(container_name));
}


