window.addEvent('domready', function() {	

	// Execution automatique
	(function () {
		new SlideShow('banner', [urlWeb+'templates/01/images/leftbar-banner1.jpg', 
								 urlWeb+'templates/01/images/leftbar-banner2.jpg',
								 urlWeb+'templates/01/images/leftbar-banner3.jpg',
								 urlWeb+'templates/01/images/leftbar-banner4.jpg',
								 urlWeb+'templates/01/images/leftbar-banner5.jpg',
								 urlWeb+'templates/01/images/leftbar-banner6.jpg'
									]);

		var menu = new DhtmlMenu('menu','submenu');
		menu.fixmenu('menu');
		menu.fixsubmenu('submenu');
		httpRequest ($('legal-mention'), $('content'));
		httpRequest ($('sitemap'), $('content'));
		
	})();
	
	
	
	String.prototype.getRoot = function () {
		return this.replace(/^.*\/([^\/]+)$/g,"$1");
	}
	
	

	
});


var SlideShow = new Class ({
	Implements: Options,

	options : {
		imageTime	:	2000,
		fadeTime	:	1500
	},
	
	initialize : function (container, images, options) {
		this.setOptions(options);
		this.container = $(container);
		
		this.images = images.map(function(url) {
			return new Element('img', 
							   {'src' : url,
							    'width' : '100%', 'height': '100%',
								'tween' : {duration : this.options.fadeTime}
							   });
		}, this);
		

		this.index = 0;
		this.currentImage = this.images[this.index].inject(container);
		this.fade.periodical(this.options.imageTime + this.options.fadeTime, this);
	},
	
	fade : function () {
		this.index = (this.index + 1) % this.images.length;
		this.lastImage = this.currentImage;
		
		this.currentImage = this.images[this.index].fade('hide').inject(this.container).fade('in');
	}
	
});

	var DhtmlMenu = new Class ({
		Implements: Options,
		
		options : {
			menuList : [],
			submenuList : [],
			submenuOpenDelay : 1200,
			submenuCloseDelay : 500,
			minRight : 0,
			maxRight : 0
		},
		
		initialize : function (menuContainer, submenuContainer, options) {
			this.setOptions(options);
			this.menuList = this.options.menuList;
			this.submenuList = this.options.submenuList;
			this.current = null;
			this.currentFlag = 0;
			this.currentMenu = -1;

			this.menu = $(menuContainer);
			
			// Récupérer la liste des menus
			this.menuItems();
			
			// Récupérer la liste des sous-menus
			this.submenuItems();
			
			//this.animateMenuItems();
			this.openSubmenu(this.currentMenu);
		},
		
		menuItems: function () {
			var lst = this.menu.getElements('div[id^='+this.menu.id+']');
			lst.each(function(item,index) {
				this.menuList[index] = item;
				this.currentMenu = index;
			}, this);
		},
		
		submenuItems: function () {
			this.menuList.each(function(item,index) {
				var id = item.id.match(/menu(\d+)/);
				this.submenuList[index] = $('sub'+this.menu.id);
				
				// Si le sous-menu existe >> ajouter un évènement
				if (this.submenuList[index] != null) {
					
					var openDelay = this.options.submenuOpenDelay;
					var closeDelay = this.options.submenuCloseDelay;
					var minRight = this.options.minRight;
					var maxRight = this.options.maxRight;
					
					this.submenuList[index].addEvents({
						'open' : function() {
							this.set('tween', {duration: openDelay});
							if (this.style.right == "" || this.style.right.toInt() != maxRight)
								this.tween('right', [minRight, maxRight]);
							else this.tween('right', [maxRight, minRight]);
						},
						
						'close' : function() {
							this.set('tween', {duration: closeDelay});
							if (this.style.right.toInt() == maxRight) this.tween('right', [maxRight, minRight]);
						}
					});
					
				//	this.fixsubmenu(this.submenuList[index]);
				}

			}, this);
		},
		
		animateMenuItems: function () {
			this.menuList.each(function(item,index) {
				var submenu = this.submenuList[index];

				item.addEvents({
					'mouseover' : function(event) {
						if (this.current == null) {
							this.openSubmenu(index);
						}
						else if (this.current != index && this.currentMenu) {
								this.closeSubmenu(this.current);
							this.openSubmenu(index);
						}
						else if (this.current == index && this.currentFlag == 0) {
							this.openSubmenu(index);
						}
						this.current = index;
						
					}.bindWithEvent(this)
				});
				
			}, this);
		},
		
		testSubmenu: function (index) {
			return	(this.submenuList[index] != null);
		},
		
		openSubmenu: function (index) {
			if (this.testSubmenu(index) == true) {
				this.submenuList[index].fireEvent('open');
				this.currentFlag = 1;
			}
			return this.submenuList[index];
		},
		
		closeSubmenu: function (index) {
			if (this.testSubmenu(index) == true) {
				this.submenuList[index].fireEvent('close');
				this.currentFlag = 0;
			}
			return this.submenuList[index];
		},
		
		fixmenu: function(container) {
			var temp = $(container).getElements('div');
			var length = temp.length;
			temp.each(function(item, index) {
				if (index == 0)
					item.set('class', 'first');
				if (index == length - 1)
					item.set('class', 'last');
			});
		},
		
		fixsubmenu: function(container) {
			var temp = $(container).getElements('div');
			var length = temp.length;
			temp.each(function(item, index) {
				if (index == 0)
					item.set('class', 'first');
				if (index == length - 1)
					item.set('class', 'last');
			});
		}
	});


	function httpRequest (srcElt, dstElt) {
	srcElt.addEvent('click', function(event) { 
		event.stop();
        var req = new Request({  
					method: 'get',  
             		url: srcElt.get('href'), 
	             	onComplete: function(response) { dstElt.set('html',response) ; }  
		         	}).send();  
    	});  
	}

	function httpRequestPost (srcElt, dstElt) {
				var data = "";
							var elt = $$("#searchForm input").each(function (item, index) {
							data += item.getProperty("name") + "=" +item.getProperty("value")+"&";
							});

         		var req = new Request({  
					method: 'post',  
					data: data,
        	     	url: srcElt.getProperty('action'), 
            	 	onComplete: function(response) { $('content').set('html',response) ; }  
	         	}).send();  
				
		}

function clone_line (container, indexTable) {

	var elt = container+'_'+$(indexTable).get('value');
	var lastElt = $(elt).clone().injectAfter(elt);

	var lst = $(container).getElements('div');
	lst.each(function(item,index) {
		if (item.get('id') == null) {
			lastElt.set('id',container+'_'+index);
			lastElt.set('style','background:'+((index%2 == 0)?'#b8af7c':'#c9c298')+'; width:100%; padding:5px;')
			$(indexTable).set('value',index);
			update_clone_line (lastElt, index);
		}
		
	}, this);
	
}


function update_clone_line (element, indexElt) {
	var lst = $(element).getElements('input');
	lst.each(function(item,index) {
		item.set('name',item.get('name').replace(/^(.*)_([0-9]+)$/,"$1_"+indexElt));
	});
}

var Forms = new Class ({
		Implements: Options,
		
		options : {
			formValidInput : 'valid-form',
			errorClass : 'error'
		},

		initialize : function (container, options) {
			this.setOptions(options);
			this.validForm = $(this.options.formValidInput);
			
			
			this.container = $(container);

			this.obl = [];
			this.initUrl();
			this.initPopup();

			$('valid-form').addEvent('click', function(event) {
				event.stop();
				this.obl.empty();
				this.parseInput(this.container); 
				if (this.obl.length > 0) {
					event.preventDefault(); 
					this.displayObl();
				}else $('content-form').submit();
			}.bind(this));
		},
		
		initUrl : function () {
			this.action = this.container.get('action');
		},
		
		initPopup : function () {
			this.popup = new Element ('div', {'id' : 'popup'});
			this.popup.inject(document.body, 'top');
			
			this.popup.addEvents({
				'show' : function () { this.toggleClass('show'); },
				'hide' : function () { this.toggleClass('show'); }
			});
		},
		
		parseInput : function (container) {
			var bool = true;
			(container.getElements('input, textarea, select')).each(function (elt, i) {
				if (elt.hasClass('obligatoire') && this.testInput(elt) == false) {
					elt.addClass(this.options.errorClass);
					this.obl.push(elt);
				}else if (elt.hasClass('error')) elt.removeClass('error');
			}, this);
		},
		
		testInput : function (tag) {
			var result =  true;

			switch (tag.get('tag')) {
				case 'input'	:	if (tag.get('type') == 'text') {
										if (tag.get('value').trim() == '')
											result = false;
										tag.addEvent('click', function() { this.select(); });
									}
									else if (tag.get('type') == 'checkbox' && tag.checked == false) result = false;
									else if (tag.get('type') == 'radio' && tag.checked == false) result = false
									break;

				case "textarea"	:	if (tag.get('value').trim() == '') result = false;
									break;

				case "select"	:	if (tag.get('value') == 0) result = false;
									break
			}
			
			return result;
		},

		displayObl : function () {
			this.popup.empty();
			
			var background = new Element('div', {'class': 'background'});
			background.inject(this.popup);
			
			var message = new Element('div', {'class': 'message'});
			message.addEvent('click', function () { this.popup.fireEvent('hide'); }.bind(this));

			if (this.obl.length > 0) {
				(new Element('p', {'html' : 'Les champs du formulaire <span class="rouge">en rose</span> contiennent des erreurs ou ne sont pas remplis correctement'})).inject(message);
				(new Element('p', {'html' : '&gt;&gt; Revenir sur le formulaire', 'class' : 'link'})).inject(message);
				(new Element('p', {'class' : 'footer'})).inject(message);
	
				message.inject(this.popup);
				
				this.popup.fireEvent('show');
			}
		}
	});
