var App; if (!App) App = {};
var Init; if (!Init) Init = {};
var Options; if (!Options) Options = {};


App = {
	
	'Stats' : null,
	'ie' : false,
	'ieVersion' : 0,
	'ie6' : false,
	'ie7' : false,
	'ie8' : false,

	'init' : function() {
		
		App.detectIE();
		
		$("input.hint, textarea.hint").hint();
		$('textarea.rich').ckeditor(Options.ckeditor);
		
		if(App.Init) {
			if(App.Init.Forms) {
				App.Init.Forms.Contact("form.contact");
			}
		}
		
		if(App.UI) {
			App.UI.Datepicker("input.datepicker");
		}

		var Carousel = new Init.Carousel(".carousel",{
			'slide' : 'img',
			'delay' : '5000',
			'random' : false,
			'onChange' : function(index) {

				$("#big-picture a.style-btn").removeClass("selected");
				$("#big-picture a.style-btn").eq(this.attr("rel")).addClass("selected");

                                $("p.label").css('display', 'none');
                                $("p.label").eq(this.attr("rel")).css('display', 'block');
			}
		});

		$("#big-picture a.style-btn").click(function(e) {
			e.preventDefault();
			$("#big-picture a.style-btn").removeClass("selected");
			var index = $("#big-picture a.style-btn").index($(this));
			$(this).addClass("selected");

                        $("p.label").css('display', 'none');
                        $("p.label").eq(index).css('display', 'block');

			if(Carousel.goTo) Carousel.goTo(index);
		});
		
		$("#big-picture img, #big-picture p").click(function(e) {
			e.preventDefault();
			if(Carousel.clearTimeout) Carousel.clearTimeout();
		});	

		$(".more").click(function(e) {
			e.preventDefault();
			var id = $(this).attr('rel');
			$('.excerpt[rel='+id+']').toggle();
			$('#'+id).toggle();
		});

		if(nid) {
			$('.excerpt[rel='+nid+']').toggle();
			$('#'+nid).toggle();			
		}
		
		$('.slogan-rotator h1');
		setInterval(function(){
			$('.slogan-rotator h1').filter(':visible').fadeOut(2000,function(){
				if($(this).next('h1').size()){
					$(this).next().fadeIn(1000);
				}
				else{
					$('.slogan-rotator h1').eq(0).fadeIn(1000);
				}
			});
		},8000);		
		
	},
	
	'detectIE' : function() {
		if ($.browser.msie) {
			App.ie = true;
			App.ieVersion = parseInt($.browser.version.substr(0,1));
			if(App.ieVersion == 6) { App.ie6 = true; }
			if(App.ieVersion == 7) { App.ie7 = true; }
			if(App.ieVersion == 8) { App.ie8 = true; }
		}
	}
	
};

$(App.init);

Init.Carousel = function(selector,options) {

	var $el = jQuery(selector);
	if(!$el.length) { return; }

	//Paramètres par défauts
	var settings = jQuery.extend({
		slide: ".slide", //Défini une slide
		delay: 3000, //Délai entre chaque slide
		speed: 1000, //Vitesse du fade
		index: 0, //Début de l'animation
		random: true, //Débute l'animation sur une slide aléatoire
		onChange: function() {}
	}, options);


	//Variables privées
	var timeout = null;
	var slides = [];
	var stopCount = 0;
	var currentIndex = settings.index;
	var nextIndex = 0;
	var $slides = jQuery("<div class='slides' style='display:none;'></div>");


	function init() {

		//Construction du conteneur de slide
		if($el.find(".slides")) {
			$el.prepend($slides)
			$slides.css({"width":$el.width()+"px","height":$el.height()+"px","position":"relative","top":"0px","left":"0px"});
		}

		//Stockage des slides dans une array javascript
		slides = [];
		$el.find(settings.slide).each(function() {
			var slide = $(this).clone();
			slide.css({"position":"relative","margin":"0"});
			slides.push(slide);
			$(this).remove();
		});

		//Défini la première image aléatoirement et la suivante
		if(settings.random) { currentIndex = (Math.floor(Math.random()*slides.length)); }
		nextIndex = ((slides.length-1) == currentIndex) ? 0:currentIndex+1;

		//Ajoute la première slide et la suivante (en dessous)
		$slides.append(slides[currentIndex].clone().css({"zIndex":"21","position":"absolute","left":"0"}));
		$slides.append(slides[nextIndex].clone().css({"zIndex":"20","position":"absolute","left":"0"}));
		$slides.show();

		//Démarre la routine
		timeout = window.setTimeout(nextSlide,settings.delay);
	}

	function nextSlide() {

		settings.onChange.call($slides.find(settings.slide).eq(1),nextIndex);

		//Fade out la slide du dessus
		$slides.find(settings.slide).eq(0).fadeOut(settings.speed,function() {

			//Enlève la slide du dessus
			$(this).remove();

			//Défini la slide du dessous comme nouvelle slide du dessus
			$slides.find(settings.slide).eq(0).css({"zIndex":"21","position":"absolute","left":"0"});

			//Défini la slide en cours et la suivante(à ajouter)
			currentIndex = ((slides.length-1) == currentIndex) ? 0:currentIndex+1;
			nextIndex = ((slides.length-1) == currentIndex) ? 0:currentIndex+1;

			//Ajoute la slide suivante(en dessous)
			$slides.append(slides[nextIndex].clone().css({"zIndex":"20","position":"absolute","left":"0"}));

			//Continue la routine
			if ($slides.find(settings.slide).eq(0).attr('class') == 'system') {
				if (stopCount == 2) {
					window.clearTimeout(timeout);
					stopCount = 0;
				} else if (stopCount > 0) {
					timeout = window.setTimeout(nextSlide,2000);
					stopCount++;
				} else {
					timeout = window.setTimeout(nextSlide,2000);
				}
			} else {
				timeout = window.setTimeout(nextSlide,settings.delay);
			}
			
		});

	}

	this.goTo = function(index) {
		window.clearTimeout(timeout);

		$slides.find(settings.slide).eq(0).stop();

		var slideIndex = -1;
		jQuery.each(slides,function(i) {
			if(slideIndex == -1 && parseInt(this.attr("rel")) == index) { slideIndex = i; }
		});

		currentIndex = slideIndex;
		nextIndex = ((slides.length-1) == currentIndex) ? 0:currentIndex+1;

		$slides.html("");

		$slides.append(slides[currentIndex].clone().css({"zIndex":"21","position":"absolute","left":"0"}));
		$slides.append(slides[nextIndex].clone().css({"zIndex":"20","position":"absolute","left":"0"}));
		
		if ($slides.find(settings.slide).eq(0).attr('class') == 'system') {
			stopCount = 1;
			timeout = window.setTimeout(nextSlide,2000);
		}

		//timeout = window.setTimeout(nextSlide,settings.delay);
	}
	
	this.clearTimeout = function() {
		window.clearTimeout(timeout);
	}

	init();

};


/*********************************************
*
* Google Analytics Object
*
**********************************************/


Analytics = function(account) {

	var self = this;
	
	try {
		self.tracker = _gat._getTracker(account);
		self.tracker._setDomainName("none");
		self.tracker._setAllowLinker(true);
		self.account = account;
	} catch(err) {}
	
};

Analytics.prototype.tracker = null;
Analytics.prototype.account = null;

Analytics.prototype.setVar = function(visitor) {
	if(!this.tracker) { return; }
	try {
	
		this.tracker._setVar(visitor);
		
	} catch(err) {}
};

Analytics.prototype.track = function(page) {
	if(!this.tracker) { return; }
	try {
	
		if(!page) { this.tracker._trackPageview(); }
		else{ this.tracker._trackPageview(page); }
		
	} catch(err) {}
};

Analytics.prototype.event = function(cat,action,label) {
	if(!this.tracker) { return; }
	try {
	
		this.tracker._trackEvent(cat, action, label);
		
	} catch(err) {}
};

/*********************************************
*
* Common options
*
**********************************************/

Options = {

	'datepicker' : {
		buttonImageOnly: true,
		buttonImage: "/statics/icons/date.png",
		showOn: "both",
		dateFormat: 'yy-mm-dd',
		changeYear: true,
		changeMonth: true,
		showOtherMonths: true,
		constrainInput: true,
		yearRange: '-3:+50',
		dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
		dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Juin','Juil','Aoû','Sep','Oct','Nov','Déc'],
		appendText: "(AAAA-MM-JJ)"
	}

};

/*********************************************
*
* Templates
*
**********************************************/

Templates = {

	"render" : function(text,values) {
		var re_cache = {};
		var tmpl = text.replace(/%7B/ig,'{').replace(/%7D/ig,'}');
		$.each(values, function(k,v) {
			tmpl = tmpl.replace( new RegExp('{'+k+'}', 'gm'), v );	
		});
		
		return tmpl;

	}
};
