var myZoom;
var accordion;

var debug = function(msg) {

  if(typeof console !='undefined' ) { console.warn(msg); } else { alert(msg.message); }
 
}

function init(o) {
	
	// -------- ZOOM PHOTOS --------
	
	if(document.getElementById("zoom")) {
		$('zoom').style.display = 'block';
		myZoom = new Fx.Slide('zoom', {height: true, opacity: true, duration: 500});
		myZoom.hide();
	}
	
	if(document.getElementById("select")) {
		zoom = document.getElementsByClassName('zoom');
		for(i=0; i<zoom.length; i++) {
			zoom[i].onmouseover = function() { document.getElementById("galerie").style.backgroundImage = "url('"+this.href+"')"; }
			zoom[i].onclick = function() { return false; }
		}
	}
	
	accordion = new Accordion('h2.menutitre', 'ul.stretcher', { opacity:false, duration: 300,

            onActive:function(toggler, element){ 
				element.setStyle("display", "block");
				},

            onBackground:function(toggler, element){ 
				element.setStyle("display", "none");				}

    }, $('accordion'));
	accordion.display (-1);
	setTimeout(function(){
		( o==-1 ) ? accordion.display () : accordion.display (o);
	}, 10);

	
	// -------- FLASH INFOS --------
	
	try {
		
		$('flash_infos').innerHTML = '<marquee id="flash_infos" behavior="scroll" direction="up" scrollamount="1" scrolldelay="1" '
	                                 +'onMouseOver="this.stop()" onMouseOut="this.start()">'
								     +($('flash_infos').innerHTML)+'</marquee>';
									 
	} catch(e) { /* Pas de flash infos... */}
	
	// -------- PROMO --------
	
	/* try {
		
		$('promo').innerHTML = '<marquee id="promo" behavior="scroll" direction="up" scrollamount="1" scrolldelay="1" '
	                          +'onMouseOver="this.stop()" onMouseOut="this.start()">'
				               +($('promo').innerHTML)+'</marquee>';
							   
	} catch(e) { /* Pas de promos... * / }
	*/

	// -------- FIN INIT --------
	
}

function zoom() {
	myZoom.toggle();
}

function open_next(id) {
	document.getElementById(id).style.display = '';	
}

function addToFavorites() {
	if (document.all) { window.external.AddFavorite(location.href, document.title); }
	else { alert("Votre navigateur n'autorise pas l'ajout direct de signets.\n"
	            +"Pour ce faire, faites 'Control + D' pour l'ajouter ou utilisez le menu marque-pages.") }
}

function retour() {
	history.go(-1);	
}

function OpenWin(URL,width,height,nom) {
	window.open(URL,nom,"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizable=no");
}

function OpenWin2(URL,width,height,nom) {
	window.open(URL,nom,"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizable=yes");
}

function DisplayZoomPopUp(url) {
	window.open(url,'Zoom','height=500,width=500,left=0,top=0,scrollbars=yes');
}

function qte_moins(champ) {
	champ2 = champ + "_2";
	qte = document.getElementById(champ).value;
	document.getElementById(champ).value = Number(qte) - 1;
	document.getElementById(champ2).value = Number(qte) - 1;
	frmsubmit('recalc');
}

function qte_plus(champ) {
	champ2 = champ + "_2";
	qte = document.getElementById(champ).value;
	document.getElementById(champ).value = Number(qte) + 1;
	document.getElementById(champ2).value = Number(qte) + 1;
	frmsubmit('recalc');
}

function frmsubmit(func) {
	frm = document.entryform;
	frm.func.value = func;
	frm.submit();
}

var requete = null;

function creerRequete() {
    try {
        requete = new XMLHttpRequest();
    } catch (microsoft) {
        try {
            requete = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(autremicrosoft) {
            try {
                requete = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(echec) {
                requete = null;
            }
        }
    }
    if(requete == null) {
        alert('Impossible de créer l\'objet requête,\nVotre navigateur ne semble pas supporter les object XMLHttpRequest.');
    }
}

function page(catid) {
	creerRequete();
	var url = 'scripts/page.php?id='+catid;
	requete.open('GET', url, true);
	
	requete.onreadystatechange = function() {
		if(requete.readyState == 4) {
			if(requete.status == 200) {
				document.getElementById('page').innerHTML = requete.responseText;
			}
		}
	};
	
	requete.send(null);
}

function vide(vdefault, champ){
	if(champ.value==vdefault){
		champ.value='';
	}
}

function zoomGalerie(src, width, height, texte){
    var div = $('div_zoom_galerie');
    var div2 = $('div_zoom_galerie_contenu');
    var img = div2.getElementsByTagName('canvas')[0];
    
    if(div!=null){
        
        div.style.width=document.width+'px'; 
        div.style.height=document.height+'px';
        div.style.visibility='visible';
        div.style.backgroundColor='#000';
        div.style.zIndex = '999';
        change_opacity('div_zoom_galerie', 0.1, 0.6, '+');
        
        div2.style.visibility='visible';
        div2.style.zIndex = '1000';
        change_opacity('div_zoom_galerie_contenu', 0.1, 1, '+');
        div2.style.top = Math.ceil(parseInt(window.innerHeight)/2) + 'px';
        div2.style.left= Math.ceil(parseInt(window.innerWidth)/2)-Math.ceil(width/2) + 'px';
        
        if(texte!=''){
            div2.innerHTML = '<p style="width:'+width+'px">'+texte+'</p>' + div2.innerHTML;
        }
        div2.innerHTML = '<img src="' + src + '" />' + div2.innerHTML;
    }
    return true;
}

function change_opacity(id, depart, arriver, sens){
    if(sens == '-' || sens == '-1')
        var arriver_test = depart>parseFloat(arriver)-0.1
    else
        var arriver_test = depart<parseFloat(arriver)+0.1
        
    if(arriver_test){
        $(id).style.opacity = depart;
        if(sens == '-' || sens == '-1')
            suivant = parseFloat(depart-0.1);
        else
            suivant = parseFloat(depart+0.1);
            
        setTimeout('change_opacity("'+id+'", '+suivant+', '+arriver+', "'+sens+'")', 10)
    }
    else{
        if(arriver==0){
            
            $(id).style.visibility='hidden';
        }
    }
}

function fermer_zoom_galerie(){
    var div = $('div_zoom_galerie_contenu');
    var img = div.getElementsByTagName('img')[0];
    var p = div.getElementsByTagName('p')[0];
    div.style.visibility='hidden';
    
    change_opacity('div_zoom_galerie_contenu', 1, 0, '-');
    
    var anciennoeud = div.removeChild(img);
    
    if(p!=null){
        var anciennoeud = div.removeChild(p);
    }
    
    change_opacity('div_zoom_galerie', 0.6, 0, '-');   
    
    return true;
}

// ------------------------------------------------------------------------------------------------

/* Element.implement({

	isVisible: function(){
		return (this.getStyle('display') || 'none') != 'none' && this.getStyle('visibility') != 'hidden';
	},

	show: function(){
		return this.setStyle('display', this.retrieve('display', '')).set('opacity', 1);
	},

	hide: function(visibility){
		if (!this.retrieve('display')){
			var display = this.getStyle('display');
			this.store('display', (display == 'none') ? 'block' : display);
		}
		return (visibility) ? this.set('opacity', 0) : this.setStyle('display', 'none');
	},

	toggle: function(visibility){
		return this[this.isVisible() ? 'hide' : 'show'](visibility);
	}

}); */

/**
 * ReMooz - Zoomer
 *
 *
 * Inspired by so many boxes and zooms
 *
 * @version		1.0
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var ReMooz = new Class({

	Implements: [Events, Options, Chain],

	options: {
		link: null,
		type: 'image',
		container: null,
		className: null,
		centered: false,
		dragging: true,
		closeOnClick: true,
		shadow: 'onOpen',
		resize: true,
		margin: 20,
		resizeFactor: 0.95,
		resizeLimit: false, // {x: 640, y: 640}
		fixedSize: false,
		cutOut: true,
		addClick: true,
		opacityLoad: 0.75,
		opacityResize: 1,
		opacityTitle: 0.75,
		resizeOptions: {},
		fxOptions: {},
		closer: true,
		temporary: false,
		onBuild: $empty,
		onLoad: $empty,
		onOpen: $empty,
		onOpenEnd: $empty,
		onClose: $empty,
		onCloseEnd: $empty,
		generateTitle: function(el) {
			var text = el.getProperty('title');
			if (!text) return false;
			var title = text.split(' :: ');
			var head = new Element('h6', {'html': title[0]});
			return (title[1]) ? [head, new Element('p', {'html': title[1]})] : head;
		}
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		var origin = this.options.origin;
		this.origin = ((origin) ? $(origin) || this.element.getElement(origin) : null) || this.element;
		this.link = this.options.link || this.element.getProperty('href') || this.element.getProperty('src');
		this.container = $(this.options.container) || this.element.getDocument();
		this.bound = {
			'click': function(e) {
				this.open.delay(1, this);
				return false;
			}.bind(this),
			'close': this.close.bind(this),
			'dragClose': function(e) {
				if (e.rightClick) return;
				this.close();
			}.bind(this)
		};
		if (this.options.addClick) this.bindToElement();
	},

	destroy: function(unload) {
		if (this.box && !unload) this.box.destroy();
		this.box = this.tweens = this.body = this.content = null;
		return null;
	},

	bindToElement: function(element) {
		($(element) || this.element).addClass('remooz-element').addEvent('click', this.bound.click);
		return this;
	},

	getOriginCoordinates: function() {
		var coords = this.origin.getCoordinates();
		delete coords.right;
		delete coords.bottom;
		return coords;
	},

	open: function(e) {
		if (this.opened) return (e) ? this.close() : this;
		this.opened = this.loading = true;
		if (!this.box) this.build();
		this.coords = this.getOriginCoordinates();
		this.coords.opacity = this.options.opacityLoad;
		this.coords.display = '';
		this.tweens.box.set(this.coords);
		this.box.addClass('remooz-loading');
		ReMooz.open(this.fireEvent('onLoad'));
		this['open' + this.options.type.capitalize()]();
		return this;
	},

	finishOpen: function() {
		this.tweens.fade.start(0, 1);
		this.drag.attach();
		this.fireEvent('onOpenEnd').callChain();
	},

	close: function() {
		if (!this.opened) return this;
		this.opened = false;
		ReMooz.close(this.fireEvent('onClose'));
		if (this.loading) {
			this.box.hide();
			return this;
		}
		this.drag.detach();
		this.tweens.fade.cancel().set(0).fireEvent('onComplete');
		if (this.tweens.box.timer) this.tweens.box.clearChain();
		var vars = this.getOriginCoordinates();
		if (this.options.opacityResize != 1) vars.opacity = this.options.opacityResize;
		this.tweens.box.start(vars).chain(this.closeEnd.bind(this));
		return this;
	},

	closeEnd: function() {
		if (this.options.cutOut) this.element.setStyle('visibility', 'visible');
		this.box.hide();
		this.fireEvent('onCloseEnd').callChain();
		if (this.options.temporary) this.destroy();
	},

	openImage: function() {
		var tmp = new Image();
		tmp.onload = tmp.onabort = tmp.onerror = function(fast) {
			this.loading = tmp.onload = tmp.onabort = tmp.onerror = null;
			if (!tmp.width || !this.opened) {
				this.fireEvent('onError').close();
				return;
			}
			var to = {x: tmp.width, y: tmp.height};
			if (!this.content) this.content = $(tmp).inject(this.body);
			else tmp = null;
			this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'].create({
				'delay': (tmp && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		tmp.src = this.link;
		if (tmp && tmp.complete && tmp.onload) tmp.onload(true);
	},

	/**
	 * @todo Test implementation
	 */
	openElement: function() {
		this.content = this.content || $(this.link) || $E(this.link);
		if (!this.content) {
			this.fireEvent('onError').close();
			return;
		}
		this.content.inject(this.body);
		this.zoomTo({x: this.content.scrollWidth, y: this.content.scrollHeight});
	},

	zoomRelativeTo: function(to) {
		var scale = this.options.resizeLimit;
		if (!scale) {
			scale = this.container.getSize();
			scale.x *= this.options.resizeFactor;
			scale.y *= this.options.resizeFactor;
		}
		for (var i = 2; i--;) {
			if (to.x > scale.x) {
				to.y *= scale.x / to.x;
				to.x = scale.x;
			} else if (to.y > scale.y) {
				to.x *= scale.y / to.y;
				to.y = scale.y;
			}
		}
		return this.zoomTo({x: to.x.toInt(), y: to.y.toInt()});
	},

	zoomTo: function(to) {
		to = this.options.fixedSize || to;
		var box = this.container.getSize(), scroll = this.container.getScroll();
		var pos = (!this.options.centered) ? {
			x: (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(scroll.x + this.options.margin, scroll.x + box.x - this.options.margin - to.x),
			y: (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(scroll.y + this.options.margin, scroll.y + box.y - this.options.margin - to.y)
		} :  {
			x: scroll.x + ((box.x - to.x) / 2).toInt(),
			y: scroll.y + ((box.y - to.y) / 2).toInt()
		};
		if (this.options.cutOut) this.element.setStyle('visibility', 'hidden');
		this.box.removeClass('remooz-loading');
		var vars = {left: pos.x, top: pos.y, width: to.x, height: to.y};
		if (this.options.opacityResize != 1) vars.opacity = [this.options.opacityResize, 1];
		else this.box.set('opacity', 1);
		this.tweens.box.start(vars).chain(this.finishOpen.bind(this));
		this.fireEvent('onOpen');
	},

	build: function() {
		this.addEvent('onBlur', function() {
			this.focused = false;
			this.box.removeClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndex);
		}, true);
		this.addEvent('onFocus', function() {
			this.focused = true;
			this.box.addClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndexFocus);
		}, true);
		this.element.addEvent('trash', this.destroy.bind(this));

		var classes = ['remooz-box', 'remooz-type-' + this.options.type, 'remooz-engine-' + Browser.Engine.name + Browser.Engine.version];
		if (this.options.className) classes.push(this.options.className);
		this.box = new Element('div', {
			'class': classes.join(' '),
			'styles': {'display': 'none', 'zIndex': ReMooz.options.zIndex}
		});

		this.tweens = {
			'box': new Fx.Morph(this.box, $merge({
					'duration': 400,
					'unit': 'px',
					'transition': Fx.Transitions.Quart.easeOut,
					'chain': 'cancel'
				}, this.options.resizeOptions)
			),
			'fade': new Fx.Tween(null, 'opacity', $merge({
					'duration': 300,
					'chain': 'cancel'
				}, this.options.fxOptions)).addEvents({
					'onComplete': function() {
						if (!this.element.get('opacity')) this.element.setStyle('display', 'none');
					},
					'onStart': function() {
						if (!this.element.get('opacity')) this.element.setStyle('display', '');
					}
				}
			)
		};
		this.tweens.fade.element = $$();

		if (this.options.shadow && !Browser.Engine.trident4) {
			var shadow = new Element('div', {'class': 'remooz-bg-wrap'}).inject(this.box);
			['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
				new Element('div', {'class': 'remooz-bg remooz-bg-' + dir}).inject(shadow);
			});
			this.tweens.bg = new Fx.Tween(shadow, 'opacity', {'chain': 'cancel'}).set(0);
			this.addEvent(this.options.shadow, this.tweens.bg.set.bind(this.tweens.bg, 1), true);
			this.addEvent('onClose', this.tweens.bg.set.bind(this.tweens.bg, 0), true);
		}

		if (this.options.closer) {
			var closer = new Element('a', {
				'class': 'remooz-btn-close',
				'events': {'click': this.bound.close}
			}).inject(this.box);
			this.tweens.fade.element.push(closer);
		}
		this.body = new Element('div', {'class': 'remooz-body'}).inject(this.box);

		var title = this.options.title || this.options.generateTitle.call(this, this.element);
		if (title) {
			this.tweens.fade.element.push(new Element('div', {'class': 'remooz-title'}).adopt(
				new Element('div', {'class': 'remooz-title-bg', 'opacity': this.options.opacityTitle}),
				new Element('div', {'class': 'remooz-title-content'}).adopt(title)
			).inject(this.box));
		}
		this.tweens.fade.set(0).fireEvent('onComplete');
		
		this.fireEvent('onBuild', this.box, this.element);
		
		this.drag = new Drag.Move(this.box, {
			'snap': 15,
			'onBeforeStart': function() {
				if (!this.focused && !this.loading) ReMooz.focus(this);
				else if (this.loading || this.options.closeOnClick) this.box.addEvent('mouseup', this.bound.dragClose);
			}.bind(this),
			'onSnap': function() {
				this.box.removeEvent('mouseup', this.bound.dragClose);
				if (!this.options.dragging) this.drag.stop();
				else this.box.addClass('remooz-box-dragging');
			}.bind(this),
			'onComplete': function() {
				this.box.removeClass('remooz-box-dragging');
			}.bind(this)
		});
		this.drag.detach();
		
		this.box.inject(this.element.getDocument().body);
	}

});

ReMooz.factory = function(extended) {
	return $extend(this, extended);
};

ReMooz.factory(new Options).factory({

	options: {
		zIndex: 41,
		zIndexFocus: 42,
		query: 'a.remooz',
		parse: 'rel',
		modal: false,
		parseSecure: false
	},

	initialize: function(container, options) {
		this.setOptions(options);
		return $(container || document).getElements(this.options.query).map(function(el) {
			var obj = el.getProperty(this.options.parse);
			if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) obj = $merge(obj, this.options.classOptions);
			return new ReMooz(el, $merge(obj));
		}, this);
	},

	stack: [],

	open: function(obj) {
		var last = this.stack.getLast();
		this.focus(obj);
		if (last && this.options.modal) last.close();
	},

	close: function(obj) {
		var length = this.stack.length - 1;
		if (length > 1 && this.stack[length] == obj) this.focus(this.stack[length - 1]);
		this.stack.remove(obj);
	},

	focus: function(obj) {
		var last = this.stack.getLast();
		obj.fireEvent('onFocus', [obj]);
		if (last == obj) return;
		if (last) last.fireEvent('onBlur', [last]);
		this.stack.remove(obj).push(obj);
	}

});

Element.implement({

 fadeTo : function( amount, whenFinished, duration ) {
   if(typeof whenFinished != 'function') {
	 whenFinished = function() {}   
   }
   this.setStyle('visibility','visible');
   this.effect('opacity', {
      transition : new Fx.Transition(Fx.Transitions.Quad.easeOut, 6).easeOut 
    , duration : ( (duration!=null && duration>0) ? duration : 500 )
    , onComplete : function() { 
	    if(amount==0) this.element.setStyle('visibility','hidden');
	    this.whenFinished.bind(this.element)();
	  }.bind({whenFinished:whenFinished,element:this})
   }).start(this.getOpacity(),amount);
   return this;
 }
		
});

var currentPhoto = 0;
var photos = [];
var gid;

window.addEvent('load', function() {
  photos = $$('#diaporama img');
  var i = 0;
  photos.each(function(myEl){
	  if(i!=currentPhoto) { 
		myEl.setOpacity(0); 
	  } else {
		myEl.setOpacity(1);  
	  }
	  i++; 
  });
  gid = setInterval(function(){
	if(currentPhoto>=photos.length-1) {	
	  myImg = photos[0];
	  currentPhoto = 0;
	} else {
	  myImg = photos[currentPhoto];
	  currentPhoto++; 
	}
	
	i = 0;
	photos[currentPhoto];
	photos.each(function(myEl){
	  if(i!=currentPhoto) { 
		myEl.fadeTo(0); 
	  } else {
		myEl.fadeTo(1);  
	  }
	  i++; 
	});
  },2000);
});
