// JavaScript Document
var pathWay = 'fileadmin/templates/';
window.addEvent('domready', function()
{
	var header = null;
	if(header = $('anim-header'))
	{
		var params = { 
			id: 'animHeader',
			width:630, 
			height: 180, 
			params: { wmode:'transparent'}, 
			vars: { width:630, height:180 }
		};
		var headerMovie = new Swiff(pathWay+'flash/a-chacun-son-velo.swf', params);
		headerMovie.inject(header);
	}
	/*
		<img src="images/meteo/cloudy.png" alt="CLoudy" />
		<strong>Lundi</strong>
		<br />Min : 20 ° C
		<br />Max : 28 ° C
		<br />Couverture nuageuse partielle
	*/
	var weather = {
		url: pathWay+'getWeather.php', 
		active:0, 
		init:function()
		{
			this.container = $('meteo'); 
			if(!this.container) return; 
			this.container.addClass('loading-blue'); 
			var $this = this; 
			
			// ARROWS EVENTS
			this.prev = $('meteo-prev').addEvent('click', this.change); 
			this.next = $('meteo-suiv').addEvent('click', this.change); 
			this.prev.goto = -1; 
			this.next.goto = 1; 
			
			// REQUEST 
			this.req = new Request.JSON(
			{
				url: $this.url,
				onComplete:function(res)
				{
					$this.container.removeClass('loading-blue');
				},
				onSuccess: function(res)
				{
					$this.result = res.weather; 
					if($this.result)
					{
						$this.now = res.weather.current_conditions; 
						$this.days = res.weather.forecast_conditions; 
						
						$this.nb = $this.days.length;
						if($this.nb>0){ 
							$this.makeItem($this.days[$this.active]);
						}
					}
					//$this.start(); 
				},
				onFailure: function(res)
				{
					$this.container.set('text', "Aucune donnée météo n'est disponible.");
				}
			});
			this.req.send();
		},
		makeItem:function(data)
		{
			var img = new Image();
			img.src = pathWay+'images/meteo/'+this.getIcon(data.icon['@attributes'].data);
			img.alt = data.condition['@attributes'].data;
			var text = '<strong>'+this.getDayName(data.day_of_week['@attributes'].data)+'</strong>';
			text += '<br /> Min : '+data.low['@attributes'].data;
			text += '<br /> Max : '+data.high['@attributes'].data;
			text += '<br /> '+data.condition['@attributes'].data;
			this.container.set('html',text);
			img.inject(this.container,'top');
		},
		getIcon: function(name)
		{
			var newName = '';
			
			weatherIcons.each(function(el)
			{
				if(el.name == name)
				{
					newName=el.newName;
				}
			});
			return(newName);
		},
		getDayName: function(name)
		{
			var newName = '';
			
			daysOfWeek.each(function(el)
			{
				if(el.short == name)
				{
					newName=el.long;
				}
			});
			return(newName);
		},
		change:function(e)
		{
			if(e) e.stop();
			dir = e.target.goto;
			next = weather.active + dir;
			if(next<0) {
				next = weather.nb-1;
			}else if(next==weather.nb){
				next = 0;
			}
			weather.active = next;
			weather.makeItem(weather.days[next]);
		}
	}
	
	
	var slider = {
		populated:false,
		init: function()
		{
			var $this = this;
			this.isPaused = 0;
			this.container = $('slider-content');
			this.overAllContainer = $('slider-container');
			if(!this.container) return;
			this.listContainer = $('slider-menu');
			this.slides = this.container.getElements('.slide');
			this.ul = new Element('ul').inject(this.listContainer);
			this.active = null;
			this.timer = null,
			this.transitionTime = 6000,
			this.aList = [];
			this.prev = $('slider-top').getElement('a');
			this.next = $('slider-bottom').getElement('a');
			if(this.slides.length>1) this.populateList();
			
			if(this.prev && this.next && this.populated) {
				this.prev.addEvent('click', function(e)
				{
					if(e) e.stop();
					$this.scrollList(-1);
				});
				this.next.addEvent('click', function(e)
				{
					if(e) e.stop();
					$this.scrollList(1);
				});
			}
			
			// Pause on mouse over
			this.overAllContainer.addEvents(
				{
					'mouseenter':function(e)
					{
						$this.pauseIt();
					},
					'mouseleave':function(e)
					{
						$this.pauseIt();
					}
				});
			
			this.timer = this.autoChange.periodical(this.transitionTime, this);
		},
		populateList: function()
		{
			var $this = this;
			this.populated = true;
			this.slides.each(function(el, index)
			{
				el.titre = el.getElement('h2').get('text');
				var listeEl = new Element('a', {'href':'#'}).inject(new Element('li').inject(this.ul)).set('html', '<span>'+el.titre+'</span>');
				listeEl.store('infos',{'el':el,'numero':index});
				listeEl.addEvent('click', function(e)
				{
					if(e) e.stop();
					$clear($this.timer);
					$this.change(this);
					$this.timer = $this.autoChange.periodical($this.transitionTime, $this);
				});
				el.hide();
				this.aList.push(listeEl);
			}, this);
			this.change(this.aList[0]);
		},
		pauseIt: function () {
		
			var self = this;
			
			//only move if not currently moving
			if (self.isPaused == 0) {
				self.isPaused = 1;
				$clear(self.timer);
			} else {
				self.isPaused = 0;
				$clear(self.timer);
				self.timer = this.autoChange.periodical(this.transitionTime, this);
			}
			
		},
		change: function(el){
			var infos = el.retrieve('infos');
			if($chk(this.active))
			{
				if(this.active != infos.numero)
				{
					this.aList[this.active].removeClass('active');
					this.slides[this.active].hide();
					//var outRevealFx = new Fx.Reveal(this.slides[this.active], {duration: 500, mode: 'horizontal'});
					//outRevealFx.dissolve();
					//this.slides[this.active].fx = this.slides[this.active].effect('opacity', {duration: 1000}).start(0);
					this.aList[infos.numero].addClass('active');
					//var inRevealFx = new Fx.Reveal(this.slides[infos.numero], {duration: 500, mode: 'horizontal'});
					//inRevealFx.reveal();
					this.slides[infos.numero].show();
					//this.slides[infos.numero].fx = this.slides[infos.numero].effect('opacity', {duration: 1000}).start(0);
				}
			}else{
				this.aList[infos.numero].addClass('active');
				this.slides[infos.numero].show();
			}
			this.active = infos.numero;
		},
		scrollList: function(dir)
		{
			//var lis = this.ul.getElements('li');
			
			if(dir == -1) {
				//lis[lis.length - 1].inject(this.ul, 'top');
				$clear(this.timer);
				if (this.active == 0)
				{
					//this.active = 0;
					this.change(this.aList[this.slides.length -1]);
				} else {
					this.change(this.aList[this.active - 1]);
					
				}
				this.timer = this.autoChange.periodical(this.transitionTime, this);
			}else{
				//lis[0].inject(this.ul);
				$clear(this.timer);
				if (this.active == (this.slides.length -1))
				{
					//this.active = 0;
					this.change(this.aList[0]);
				} else {
					this.change(this.aList[this.active + 1]);
					
				}
				this.timer = this.autoChange.periodical(this.transitionTime, this);
			}
		},
		autoChange:function()
		{
			if (this.isPaused == 0) {
				if (this.active == (this.slides.length -1))
				{
					//this.active = 0;
					this.change(this.aList[0]);
				} else {
					this.change(this.aList[this.active + 1]);
				}
			}
		},
	};
	
	var actus = {
		init: function()
		{
			var actusC = $$('.actus-wrapper');
			var $this = this;
			actusC.each(function(el,ind)
			{
				var actus = el.getElement('.actus-container');
				var lien = el.getElement('.actus-loader a');
				var infos = {}; 
				if(lien) {
					lien = lien.get('href');
					$this.getList(lien, actus, infos, ind);
				}
			}, this);
		}
		,getList : function(link, target, infos, ind)
		{
			var that = this;
			var req = new Request({
				method: 'get',
				url: link, 
				onSuccess: function(response){
					target.removeClass('loading');
					target.set('html', response);
					
					var scr = new MakeScrollbar({content:target, ignoreMouse:false, id:'scrollbar'+ind, top:0, offsetX:0, pos:'css'}); 
					scr.changeSteps();
				} 
			});
			req.send();
			target.empty().addClass('loading');
		}

	};
	
	var logos = {
		init: function()
		{
			this.container = $('logos-container');
			this.prev = $('logos-prev');
			this.next = $('logos-suiv');
			this.nav();
			//fmcScrollTo
		},
		nav:function()
		{
			var that = this;
			//
			var el = this.container;
			if(!el) return;
			var els = el.getElements('.logo');
			var len = els.length;
			if(len>0)
			{
				var elWidth = els[0].getSize().x;
				var stepLength = Math.ceil(el.getSize().x / elWidth);
				$('logos-wrapper').setStyle('width', (elWidth * (len+1)));
				var steps = Math.ceil(len/stepLength); 
				if(steps>1) {
						
					var scroller = new fmcScrollTo({ 
						slides: els,
						container: el,
						duration:700
					});
					var theStep = 0;
					var scrollable = false;
					var stepsArray = new Array();
					scrollable = true;
					this.checkBTNS(scroller.startIndex, steps, stepLength);
					
					this.prev.addEvent('click',function(e)
					{
						if(e) e.stop();
						if(scroller.startIndex != 0 && (scroller.startIndex-stepLength)>=0)
						{
							scroller.scrollToEl(scroller.startIndex-stepLength);
						}else{
							scroller.scrollToEl(0);
						}
						that.checkBTNS(scroller.startIndex, steps, stepLength);
					});
					
					this.next.addEvent('click',function(e)
					{
						if(e) e.stop();
						if(scroller.startIndex < len-1 && Math.ceil(scroller.startIndex + stepLength / stepLength) - 1 <= steps)
						{
							scroller.scrollToEl(scroller.startIndex+stepLength);
						}else{
							//alert('Last : '+ scroller.startIndex +' - '+ (stepLength*steps-stepLength));
							scroller.scrollToEl(stepLength*steps-stepLength);
						}
						that.checkBTNS(scroller.startIndex, steps, stepLength);
					});
				}else{
					this.prev.hide();
					this.next.hide();
				}
				
			}else{
				this.prev.hide();
				this.next.hide();
			}
		},
		checkBTNS:function (startIndex, steps, stepsLength, el)
		{
			var minus = false;
			var plus = false;
			//alert(Math.ceil((startIndex+stepsLength) / stepsLength));
			if(Math.ceil((startIndex+stepsLength) / stepsLength) == steps)
			{
				plus = false;
				this.next.addClass('disabled');
			}else{
				plus = true;
				this.next.removeClass('disabled');
			}
			if(startIndex == 0)
			{
				this.prev.addClass('disabled');
			}else{
				this.prev.removeClass('disabled');
			}
		}
	};
	
	var cal = {
		init: function(options)
		{
			var that = this;
			if(options) this.c = $(options.container);
			if(!this.c) return;
			this.els = this.c.getElements('.eventsCal');
			this.shown = null;
			this.nextMonth = this.c.getElement('a.suiv');
			this.prevMonth = this.c.getElement('a.prec');
			$$(this.nextMonth, this.prevMonth).addEvent('click', function(e){
				if(e) e.stop();
				that.changeCal(this.href);
			});
			this.els.each(function(el, ind)
			{
				var tip = el.getElement('.eventsCalTip');
	
				//alert(tip);
				if(tip){
					tip.addEvents(
					{
						'mouseleave': function(e)
						{
							this.timer = this.hide.delay(2000, this);
						},
						'mouseenter': function(e)
						{
							if(this.timer) $clear(this.timer);
						}
					});
					var trigger = el.getElement('.day').addEvents(
					{
						'click': function(e)
						{
							if(e) e.stop();
							this.tip.toggle();
							if(that.shown && that.shown != this.tip) that.shown.hide();
							that.shown = this.tip;
						}
					});
					trigger.tip = tip;
				}
			});
		},
		changeCal : function(link)
		{
			var href = link+'&type=100';
			var that = this;
			var req = new Request({
				method: 'get', 
				url: href, 
				onSuccess: function(response){
					that.c.removeClass('loading');
					that.c.set('html', response);
					that.init();
				} 
			});
			req.send();
			this.c.empty().addClass('loading');
		}
	}
	
	var newsletterInput = {
		
		init: function()
		{
			var c;
			var defaultText = 'Votre email';
			if(c = $('tx-srfeuserregister-pi1-email')){
				this.c = c;
			}else{
				return;
			}
			
			this.c.addEvents(
			{
				'focus': function(e)
				{
					if(this.value == defaultText) {
						this.value = '';
						this.removeClass('labeled');
					}
				},
				'blur': function(e)
				{
					if(this.value == '') {
						this.value = defaultText;
						this.addClass('labeled');
					}
				}
			});
			if(this.c.get('value') == '') this.c.set('value', defaultText);
			if(this.c.get('value') == defaultText) {
				this.c.addClass('labeled');
			}
			$('tx-srfeuserregister-pi1-fe_users_form').addEvent('submit', function(e)
			{
				if(c.get('value') == defaultText) e.stop();
			});
		}
	};
	
	$$('input[type=text].f3-form-error','input[type=password].f3-form-error', 'textarea.f3-form-error').each(function(input)
	{
		input.addEvent('focus', function(e)
		{
			this.removeClass('f3-form-error');
		});
	});
	
	weather.init();
	slider.init();
	actus.init();
	//logos.init();
	cal.init({'container':'agenda'});
	newsletterInput.init();
	
	/* LOGOS */
	if ($('marques')) {
		
		new SlideItMoo({
			overallContainer: 'marques',
			elementScrolled: 'logos-container',
			thumbsContainer: 'logos-wrapper',
			itemsSelector: '.blockLogos',
			itemsVisible:1,
			elemsSlide:1,
			itemWidth: 946,
			itemHeight:89,
			showControls:0,
			autoSlide: 4000,
			transition: Fx.Transitions.quad,
			duration: 1200,
			direction:1,
			showControls:1,
		});
		
		$('marques').setStyle('width', 960);
		
	}
	
	/*if ($('slider-container')) {
	
		//slider variables for making things easier below
		var itemsHolder = $('slider-container');
		var myItems = $$(itemsHolder.getElements('.slide'));
		
		//controls for slider
		var theControls = $('slider-left');
		var numNavHolder = $(theControls.getElement('ul'));
		var thePlayBtn = $(theControls.getElement('.play_btn'));
		var thePrevBtn = $(theControls.getElement('.prev_btn'));
		var theNextBtn = $(theControls.getElement('.next_btn'));
		
		
		//create instance of the slider, and start it up		
		var mySlider = new SL_Slider({
			slideTimer: 8000,
			transitionTime: 1500, 		    //Transition time (1 second = 1000)
			transitionType: 'cubic:out',	//Transition type
			orientation: 'horizontal',      //vertical, horizontal, or none: None will create a fading in/out transition.
			fade: true,                    //if true will fade the outgoing slide - only used if orientation is != None
			isPaused: false,
			container: itemsHolder,
			items: myItems,
			numNavActive: true,
			numNavHolder: numNavHolder,
			prevBtn: thePrevBtn,
			nextBtn: theNextBtn,
			pauseOnHover: true
		});
		
		mySlider.start();
		
	}*/
	
	/*
	Lien Magasin
	*/
	
	if ($('liensmag') && $$('.mag')) {
		
		$$('.mag').each(function(el, ind) {
			
			if (el.get('text') == 'Mauguio') {
				if ($('mag1')) {
					lien = $('mag1').clone();
					lien.replaces(el);
				}
			}
			if (el.get('text') == 'Lunel') {
				if ($('mag2')) {
					lien = $('mag2').clone();
					lien.replaces(el);
				}
			}
			if (el.get('text') == 'Castelnau') {
				if ($('mag3')) {
					lien = $('mag3').clone();
					lien.replaces(el);
				}
			}
			
		});
		
	}
	
});

