$(document).ready(function(){
	bindRollOverMainNav();
	bindAccessibilityBtns();
	bindAnimationScrollto();
});

function bindAccessibilityBtns()
{
	// Bind des boutons d'accessibilités
	$('#header #nav-accessibility a:not(.larger)').bind('click', function(e){
		e.preventDefault();
		
		var pourcentage = ((parseInt($('body').css('fontSize'))/16) * 100);
		if(pourcentage - 12 < 63) 
		{
			pourcentage = 63;
		} 
		else 
		{
			pourcentage = pourcentage - 12;
		}
		
		$('body').css('fontSize', (pourcentage + '%'));
	})
	
	$('#header #nav-accessibility a.larger').bind('click', function(e){
		e.preventDefault();
		
		var pourcentage = ((parseInt($('body').css('fontSize'))/16) * 100);
		if(pourcentage + 12 > 87) 
		{
			pourcentage = 87;
		} 
		else 
		{
			pourcentage = pourcentage + 12;
		}
		
		$('body').css('fontSize', (pourcentage + '%'));
	})
}

function bindIntroOngletExterieur()
{
	var futureHeight = $('#intro .expandable').innerHeight();
	$('#intro .expandable').css('height', '0px');
	$('#intro .three-column .apercu-application').wrap('<div class="apercu-application-wrapper"></div>');
	
	$('#intro-onglet .onglet-exterieur').bind('click', function(e){
		e.preventDefault();
		if(!$('#intro .expandable').is(':animated'))
		{
			if($('#intro .expandable').css('height') == '0px')
			{
				$('#intro .three-column .apercu-application-wrapper').each(function(){
					$(this).animate({
						height: $(this).find('.apercu-application').css('height')
					});
				});
					
				$('#intro .expandable').animate({
					height: futureHeight + 'px',
					marginTop: '8px'
				}, function(){
					$('#intro .expandable').css('height', 'auto');
					$('#intro-onglet .onglet-exterieur span').addClass('active');
				});
			}
			else
			{
				$('#intro .three-column .apercu-application-wrapper').each(function(){
					$(this).animate({
						height: '0px'
					});
				});

				$('#intro .expandable').animate({
					height: '0px',
					marginTop: '0px'
				}, function(){
					$('#intro-onglet .onglet-exterieur span').removeClass('active');
				});
			}
		}
		
	})
}

function bindRollOverMainNav()
{
	$('#nav-main .contain-dropdown').bind('mouseover', function(){
		$(this).addClass('hover');
		$(this).find('.container').show();
	})
	
	$('#nav-main .contain-dropdown').bind('mouseout', function(){
		$(this).removeClass('hover');
		$(this).find('.container').hide();
	})
}

function bindDemandeSlideToggle()
{
	var targetToOpen;
	var button;
	var parent;
	
	$('#demande-representant h3').bind('click', function(){
		button = $(this);
		parent = button.parents('.blue-box');
		targetToOpen = button.next('form');
		
		if(!targetToOpen.is(':animated'))
		{
			if(!targetToOpen.is(':visible'))
			{
				targetToOpen.slideDown(222, function(){
					parent.addClass('active');
				})
			}
			else
			{
				parent.removeClass('active');
				targetToOpen.slideUp(222)
			}
			
		}
	})
}

function bindFaqBtns()
{
	$('.question').each(function(){
		$(this).prepend($('<a href="#" class="btn">Ouvrir</a>'));
		$(this).find('.collapse').hide();
	});
	
	$('.btn').bind('click', function(e){
		e.preventDefault();
		e.stopPropagation();
		var parent = $(this).parents('.question');
		var divToCollapse = parent.find('.collapse');
		
		if(!divToCollapse.is(':animated'))
		{
			divToCollapse.slideToggle(222, function(){
				if(divToCollapse.is(':visible'))
				{
					parent.addClass('opened');
				}
				else
				{
					parent.removeClass('opened');
				}
			});
		}
	})
	
	$('.question h3').bind('click', function(){
		$(this).parents('.question').find('.btn').trigger('click');
	})
}

function bindDropdownScrollto()
{
	$('#nav-main ul a').bind('click', function(e){
		e.preventDefault();
		
		var href = $(this).attr('href');
		var hash = href.substring(href.indexOf('#'));
		
		
		$('html, body').animate({
			scrollTop: $(hash).offset()['top']
		}, 300);
	})
}

function bindAnimationScrollto()
{
	$('.scrollto').bind('click', scrollToHash);
}

function scrollToHash(e)
{
	e.preventDefault();

	var href = $(this).attr('href');
	var hash = href.substring(href.indexOf('#'));
	
	$('html, body').animate({
		scrollTop: $(hash).offset()['top']
	}, 400);
}

function bindShowRepresentants()
{
	$('#choose-region').bind('change', showRepresentants);
}

function showRepresentants(){
	$('.pays_contacts').hide();
	
	var id_pays = $('#choose-region').val();
	
	if(id_pays != 0)
	{
		$('#pays' + id_pays).show();
		// fix ie6 overflow on title bug 
		$('#pays' + id_pays).find('h3').css('display', 'block');
	}
}

function setupFormContact() {
	var form = $('#demande-representant form');
	form.validate({
		submitHandler: function() {
			var to_hide = form.parent().parent();
			to_hide.curtains('open', "Veuillez patienter...");
			var submit = $('input[type=submit]', form).attr('disabled', 'disabled');
			$.ajax({
				type: 'POST',
				url: form.attr('action') + "?format=json", 
				data: form.serialize(), 
				success: function(data) {
					to_hide.curtains('updateMessage', data.message);
				},
				error: function() {
					submit.removeAttr('disabled');
					to_hide.curtains('close');
				}
			});
			return false;
		}
	});
};

function setupFormQuestion() {
	var form = $('#poser-question');
	form.validate({
		submitHandler: function() {
			var to_hide = form.parent();
			to_hide.curtains('open', "Veuillez patienter...");
			var submit = $('input[type=submit]', form).attr('disabled', 'disabled');
			$.ajax({
				type: 'POST',
				url: form.attr('action') + "?format=json", 
				data: form.serialize(), 
				success: function(data) {
					to_hide.curtains('updateMessage', data.message);
				},
				error: function() {
					submit.removeAttr('disabled');
					to_hide.curtains('close');
				}
			});
			return false;
		}
	});
};

function setupThematiques() {
	var current = findCurrentThematique();
	var found_thematique;
	$('#questions .thematique').each(function(idx, thematique) {
		var $thematique = $(thematique);
		$thematique.hide();
		if ($thematique.attr('id') == "theme_" + current) {
			$thematique.show();
		}
	});
	
	$('#liste-thematiques a').each(function (idx, anchor) {
		$(anchor).bind('click', function() {
			$('#questions .thematique').each(function(idx, thematique) {
				var a_theme = $(anchor).attr('href').substr(1);
				if ("theme_" + a_theme == $(thematique).attr('id')) {
					$(thematique).show();
					$('.question', thematique).show();
				} else {
					$(thematique).hide();
				}
				
				$('#criteres').val('');
			});
			
			return false;
		});
	});
};

function findCurrentThematique() {
	var thematiques = $.map($('#liste-thematiques a').toArray(), function(anchor) {
		return $(anchor).attr('href').substr(1);
	});
	
	var hash = window.location.hash;
	if (hash.length > 0) {
		var candidat = hash.substr(1);
		if (thematiques.indexOf(candidat) != -1) {
			return candidat;
		}
	}
	
	return thematiques[0];
};

function bindSearchForm() {
	$('#frm_recherche').bind('submit', function() {
		var criteres = $('#criteres').val().split(' ');
		var regex = new RegExp(criteres.join('|'), 'gi');
		
		$('.thematique').hide();
		
		$('.question').each(function (idx, question) {
			var $question = $(question);
			var text = $question.text();
			if (text.search(regex) != -1) {
				$question.show();
				$question.parent().show();
			} else {
				$question.hide();
			}
		});
		
		return false;
	});
};

function bindSelectionDemo() {
	$('.demo').bind('click', function() {
		afficherDemo(this);
		$('#intro').scrollTo();
	});
	
	$('#demos #intro .play').bind('click', function() {
		var $this = $(this);
		var titre = $("#intro h2").text();
		var video = $this.attr('rel');
		
		$.colorbox({
			open: true,
			title: titre,
			html: '<embed width="677" height="550" menu="false" wmode="window" quality="high" bgcolor="#f5f4f1" src="' + video + '" type="application/x-shockwave-flash">'
		});
	});
	
	afficherDemo($('.demo.defaut'));
};

function afficherDemo(demo) {
	$demo = $(demo);
	
	var info = getInfoDemo($demo);
	var connexes = videosConnexes($demo);
	
	updateIntro(info.titre, info.description, info.duree, info.thumbnail, info.video, connexes);
};

function getInfoDemo(demo) {
	$demo = $(demo);
	return {
		id: $demo.attr('id'),
		titre: $("h4", $demo).html(),
		description: $("p.description", $demo).html(),
		duree: $(".duree span", $demo).html(),
		thumbnail: $demo.data('thumbnail'),
		video: $demo.data('video')
	};
};

function videosConnexes(demo) {
	var connexes = [];
	
	var el_connexes = $(demo).siblings(".demo");
	var nb = Math.min(2, el_connexes.length);
	
	for (var i = 0; i < nb; i++) {
		connexes.push(getInfoDemo(el_connexes[i]));
	}
	
	return connexes;
};

function updateIntro(titre, description, duree, thumbnail, video, connexes) {
	connexes = connexes || [];
	
	$("#intro h2").html(titre);
	$("#intro p.description").html(description);
	$("#intro .duree span").html(duree);
	
	$("#intro .thumbnail").attr('src', '/media/demos/' + thumbnail);
	$("#intro .play").attr('rel', '/media/demos/' + video);
	
	$('#intro .connexes').html('');
	
	var nb = connexes.length;	
	for (var i = 0; i < nb; i++) {
		var li_class = (i + 1 == nb ? ' class="last"' : '');
		var video = connexes[i];
		$('#intro .connexes').append("<li" + li_class + '><a href="#' + video.id + '">' + video.titre + ' <span class="duree">' + video.duree + '</span></a></li>');
	}
	
	$('#intro .connexes a').bind('click', function() {
		$this = $(this);
		
		var target = $this.attr('href');
		$(target).trigger('click');
		
		return false;
	});
};

/******************************************************************************
	CURTAINS
******************************************************************************/
(function($){
	var methods = {
		open: function(message) {
			message = message || "";
			
			var curtain = $('<div class="curtain"></div>');
			curtain.css({'z-index': 999, opacity: 0});

			curtain.width(this.outerWidth());
			curtain.height(this.outerHeight());
			curtain.offset(this.offset());
			
			if (message != "") {
				curtain.html("<p>" + message + "</p>");
			}
			
			this.prepend(curtain);
			
			curtain.fadeTo("slow", 0.8);
		},
		close: function() {
			$('.curtain', this).remove();
		},
		updateMessage: function(message) {
			message = message || "";
			
			if (message != "") {
				message = "<p>" + message + "</p>";
			}
			
			$('.curtain', this).html(message);
		}
	};
	
	$.fn.curtains = function(method) {
		method = method || 'open';
		
		if (method == "open") {
			methods.open.apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (method == "close") {
			methods.close.apply(this);
		} else if (method == "updateMessage") {
			methods.updateMessage.apply(this, Array.prototype.slice.call(arguments, 1));
		}
		
		return this;
	};
})(jQuery);

/******************************************************************************
	Scroll To
******************************************************************************/
(function($){
	$.fn.scrollTo = function(duration) {
		duration = duration || 400;
		$('html, body').animate({
			scrollTop: $(this).offset()['top']
		}, duration);
	}
})(jQuery);
