/* Fix IE lacks
-------------------------------------------- */
(function(){
	if( $.browser.msie && $.browser.version <= 6 ){
		$('.features li:first').css({ marginLeft: 0 });
		$('.pagination li.prec + li a').css({ borderLeft: 0 });
		$('.headlines.h4 .headline:first-child').css({ marginLeft: 0 });
		$('.wrap .c2:first-child').css({ marginLeft: 0 });
	}
})();

/* Navigation
-------------------------------------------- */
(function(){
	var nav = $('#navigation'),
		speed = 'normal',
		show = { opacity: 1 },
		hide = { opacity: 0 };
	$('dt',nav).mouseover(function(){	
		var DT = $(this),
			id = DT.get(0).id,
			cible = $('#s' + id);
		DT.siblings('dt').find('span').stop().animate(show, speed);
		$('span',DT).stop().animate(hide, speed);
		
		DT.siblings('dt').each(function(){
			var DTSib = $(this),
				cibleSib = $('#s' + DTSib.get(0).id);
			cibleSib.stop().animate(hide, speed);
		});
		cible.appendTo(nav).stop().animate(show, speed);
	}).filter('.on').removeClass('on').find('span').css(hide).end().next('dd:eq(0)').css(show).appendTo(nav);
})();

/* Tooltip
-------------------------------------------- */
(function(){
	var tpLayout ='<div id="tooltip"><p>{TITLE}</p></div>',
		follow = function(e){
			var w = $('#tooltip').width(),
				l = (($(window).width() - $('#content').width()) / 2) + $('#content').width();
			var p = ( (e.pageX + w) >= l ) ? e.pageX - w : e.pageX ;
			$('#tooltip').css({ left: p, top: e.pageY - 33 });
		};

	$('.tooltip').hover(
		function(event){
			if( !$('#tooltip').length ){
				var title = $(this).attr('rel'), layout = tpLayout.replace(/{TITLE}/,title);
				$('body').append(layout);
				follow(event);
				$(this).mousemove(function(e){ follow(e); });
			}
		},
		function(){ $('#tooltip').remove(); }
	);
})();

/* SLIDER
----------------------------------------------------------------- */
$('.slider').each(function(){
	var el = this;
	// Variables globales
	var _ = {
		nav : {
			arr : $('> span', el),
			slider : $('ul', el),
			thumbs : $('li', el),
			thumbsLength : $('li', el).length,
			thumbsVisible : 4,
			thumbsDatas : $.map($('img', el),function(o,i){
				return {
					index : i,
					titre : o.title,
					src : o.src,
					href : $(o).parents('a:eq(0)').attr('href')
				};
			})
		}
	};
	
	// Limit
	var limit = -Math.floor(_.nav.thumbsLength / _.nav.thumbsVisible) * _.nav.thumbs.outerWidth() * _.nav.thumbsVisible;
	
	// Add img if needed + set ul width
	var rest = _.nav.thumbsLength % _.nav.thumbsVisible;
	if( rest != 0 ){
		var nb = _.nav.thumbsVisible - rest, html = '';
		for(i=1 ; i<=nb ; i++) html += '<li></li>';
		_.nav.slider.append(html);
	}
	var newThumbsLength = _.nav.slider.find('li').length;
	_.nav.slider.width( _.nav.slider.find('li').length * _.nav.thumbs.outerWidth() );
	
	// Click on arrow
	var _clickArrow = function(){
		_.nav.arr.die('click').css({ visibility: 'visible' });;
		var dir = _.nav.arr.index(this);
		var delta = _.nav.thumbs.outerWidth() * _.nav.thumbsVisible;
		_move(dir,delta,1000);
	};
	_.nav.arr.click(_clickArrow).filter(':eq(0)').css({ visibility: 'hidden' });
	
	// Hover on thumbs
	var speed = 500;
	_.nav.thumbs.hover(
		function(){ $(this).stop().animate({ top: '-20px' }, speed); },
		function(){ $(this).stop().animate({ top: 0 }, speed); }
	);
	
	// Move function
	var _move = function(dir,delta,speed,cb){
		var pos = parseInt(_.nav.slider.css('margin-left'));
		if( dir == 1 ){ delta = pos - delta; }
		if( dir == 0 ){ delta = pos + delta; }
		_.nav.slider.animate({ marginLeft : delta },speed,function(){
			_.nav.arr.live('click',_clickArrow);
			if(parseInt(_.nav.slider.css('margin-left')) == 0){
				_.nav.arr.filter(':eq(0)').css({ visibility: 'hidden' });
			}
			if(parseInt(_.nav.slider.css('margin-left')) == limit){
				_.nav.arr.filter(':eq(1)').css({ visibility: 'hidden' });
			}
		});
	}

});

/* Listing
----------------------------------------------------------------- */
(function(){

	// Scope
	var list = $('#list'),
		nav = $('#cat'),
		actu = $('#idListing #actu'),
		speed = 'normal',
		switchClass = 'isOpen';
	
	if( nav.height() > actu.height() || nav.height() == actu.height() ){
		if( $.browser.msie && $.browser.version <= 6 ){ list.css({ height: nav.height() }); }
		else{ list.css({ minHeight: nav.height() }); }
	}
	if( nav.height() < actu.height() ){ list.css({ minHeight: actu.height() }); }
	
	// Selectors	
	$.expr[':'].hasNotCat = function(a,b,c,d){
		var obj = $(a), cat = c[3];
		if( obj.next('dd:eq(0)').find('li[rel=cat' + cat + ']').length ){ return false; }
		else{ return true; }
	};
	$.expr[':'].hasCat = function(a,b,c,d){
		var obj = $(a), cat = c[3];
		if( obj.next('dd:eq(0)').find('li[rel=cat' + cat + ']').length ){ return true; }
		else{ return false; }
	};
	
	// DT Event
	$('dt:not(:first-child)',list).click(function(){
		if( !$(this).next('dd:eq(0)').find('ul:visible').length ){
			$('dt',list).removeClass(switchClass)
			$('dd:visible',list).slideUp(speed);
			$(this).addClass(switchClass).next('dd:eq(0)').slideDown(speed);
		}
		if( $('dt:first-child',list).hasClass('open') ){
			$('dt:first-child',list).removeClass('open');
			$('dt',list).removeClass(switchClass)
			$('dd:visible',list).slideUp(speed);
			$(this).addClass(switchClass).next('dd:eq(0)').slideDown(speed);
		}
	});
	$('dt:first-child',list).click(function(){
		if( $(this).hasClass('open') ){
			$(this).removeClass(switchClass).removeClass('open');
			$('dt:visible:gt(1)',list).removeClass(switchClass).next('dd').css({ display: 'none' });
		}
		else{
			$(this).addClass(switchClass).addClass('open');
			$('dt:not(:first-child)',list).addClass(switchClass).next('dd').css({ display: 'block' });
		}
	});
	
	// Default count
	list.find('small').find('span').html($('li:eq(0)',nav).attr('count'));
	
	
	// LI Event
	//$('dt:eq(0), dd:last', list).addClass('ext');
	$('dt:eq(1)', list).addClass(switchClass);
	$('dt, li, dt:eq(1) + dd',list).css({ display: 'block' });
	
	$('li',nav).click(function(){
		
		// Current tab
		var li = $(this), count = li.attr('count'), name = li.attr('name');
		$('.on',nav).removeClass('on');
		li.addClass('on');
		
		// Update count
		list.find('small').find('span').html(count);
		
		// Switcher
		list.find('dl').fadeOut(speed,function(){
			$('dt:first',list)[0].firstChild.nodeValue = name;
			if( li.get(0).id == 'cat0' ){
				$('dd',list).css({ display: 'none' });
				$('dt, li, dt:eq(1) + dd',list).css({ display: 'block' });
				//$('dt:eq(0), dd:last', list).addClass('ext');
				$('dt', list).removeClass(switchClass);
				$('dt:eq(1)', list).addClass(switchClass);
			}
			else{
				var cat = li.get(0).id.substring(3);
				$('dd, li',list).css({ display: 'none' });
				$('dt:hasNotCat("' + cat + '"), dt:hasNotCat("' + cat + '") + dd',list).css({ display: 'none' });
				$('li[rel=cat' + cat + ']',list).css({ display: 'block' });
				$('dt:hasCat("' + cat + '"), dt:first-child',list).css({ display: 'block' });
				//$('dt:hasCat("' + cat + '"):eq(0), dt:hasCat("' + cat + '"):last + dd',list).addClass('ext');
				$('dt:hasCat("' + cat + '"):eq(0) + dd',list).css({ display: 'block' });
				$('dt', list).removeClass(switchClass);
				$('dt:hasCat("' + cat + '"):eq(0)').addClass(switchClass);
			}
			list.find('dl').fadeIn(speed);
		});
	});
	
	if(location.hash != ''){
		var urlHash = location.hash,
			catId = '#cat' + urlHash.substring(1,urlHash.length);
		$(catId).trigger('click');
	}

})();

/* Flash HOME
----------------------------------------------------------------- */
if( $('#idHome').length ){
	var win = $(window),
		reposition = function(){
			var w = win.width();
			if( w < 1160 ){
				var delta = -(1160 - w) / 2;
				$('#cover3dWrapper').css({ left: delta });
			}
			else{
				$('#cover3dWrapper').css({ left: 0 });
			}
		};
	reposition();
	win.resize(reposition);
}

/* Newsletter form validation
----------------------------------------------------------------- */
(function(){
	var data = {};
	// Verif mail function
	var verification = function(email,errorHandler,ismodal,cb){
		
		// if empty
		if(email == ''){
			errorHandler.html(msg.empty[_.lang]);
			return false;
		}
		
		// if invalid
		else if(!reg.test(email)){
			errorHandler.html(msg.invalid[_.lang]);
			return false;
		}
		
		// Term of use
		else if ( ismodal && !$('#cgu:checked').length ) {
			errorHandler.html(msg.cgu[_.lang]);
			return false;
		}
		
		// else submit
		else{
			$.ajax({
				type: 'POST',
				data: {
					action: 'verifMail',
					mail: email
				},
				url: '/index/ajaxmail',
				dataType: 'json',
				success: function(data){
					if(data.success) cb();
					else{
						errorHandler.html(msg.exist[_.lang]);
					}
				}
			});
		}
	};
	
	// Variables
	var form = $('#newsletterForm'),
		msg = {
			empty: {
				'fr' : 'Le champ email est vide.',
				'en' : 'Email field is empty.'
			},
			invalid: {
				'fr' : 'L\'email n\'est pas valide.',
				'en' : 'Invalid email.'
			},
			exist: {
				'fr' : 'Cette adresse mail existe déjà.',
				'en' : 'This email already exist.'
			},
			valid: {
				'fr' : 'Félicitation, votre inscription à la newsletter a bien été prise en compte.<br />Un mail vient de vous être envoyé avec un lien de confirmation.',
				'en' : 'Thank you for your registration, an email just sent you with confirmation link.'
			},
			noconfirm: {
				'fr' : 'Votre confirmation de mail n\'est pas correcte, merci de renouveler votre demande.',
				'en' : 'Your confirmation mail is not correct, thank you to renew your request.'
			},
			cgu: {
				'fr' : 'Vous devez acceptez les conditions générales d\'utilisation pour vous inscrire à la newsletter.',
				'en' : 'To subscribe to this Newsletter, you must understand and agree to the terms and conditions.'
			}
		},
		reg = new RegExp('^[a-z0-9\.\_\-]+@[a-z0-9\.\-]{2,}[\.][a-z]{2,3}$', 'i');

	form.find('input[type=submit]').click(function(){
		var errorHandler = $('.features .error:eq(0)');
		data.email1 = $('#email',form).val();
		verification(data.email1,errorHandler,false,function(){
			errorHandler.html('')
			$('#mask, #modal').css({ visibility: 'visible' });
			$('object,embed').css({ visibility: 'hidden' });
		});	
		return false;
	});
	
	$('#valid-email-btn').click(function(){
		var errorHandler = $('#modal .error:eq(0)');
		data.email2 = $('#email-verif').val();
		verification(data.email2,errorHandler,true,function(){
			errorHandler.html('');
			// MAIL OK
			if( data.email1 === data.email2 ){
				$.ajax({
					type: 'POST',
					data: {
						action: 'validMail',
						mail: data.email2
					},
					url: '/index/ajaxmail',
					dataType: 'json',
					success: function(data){
						if(data.success){
							$('#modal').fadeOut('normal',function(){
								$('#modal *:gt(0)').remove();
								$('#modal').html('<p class="close">x</p><p style="padding-right:20px;">' + msg.valid[_.lang] + '</p>').fadeIn('normal');
							});
						}
					}
				});
			}
			// MAIL KO
			else{
				$('#modal p:gt(1)').fadeOut('slow',function(){
					$('#modal p:eq(2)').html(msg.noconfirm[_.lang]);
					$('#modal p:eq(2)').fadeIn('slow');
					setTimeout('location.reload(true);', 3000);
				});
			}
		});
	});
	
	$(document.getElementById('toggleHook')).click(function(){
		$('+ div',this).toggle();
	}).css({ cursor: 'pointer', textDecoration: 'underline' }).next('div:eq(0)').css({ display: 'none' });
	
})();

/* Search Options
----------------------------------------------------------------- */
(function(){
	var form = $('#searchOptions');
	$('span',form).click(function(){
		var value = $(this).attr('rel');
		$(':hidden[name=type]',form).val(value);
		form.submit();
	});
})();
(function(){
	var form = $('#paginationForm');
	$('a',form).click(function(){
		var value = $(this).attr('rel');
		$(':hidden[name=page]',form).val(value);
		form.submit();
		return false;
	});
})();

/* Modal 
----------------------------------------------------------------- */
(function(){
	var modal = $('#modal');
	$('.close',modal).live('click',function(){
		modal.css({ visibility: 'hidden' });
		$('#mask').css({ visibility: 'hidden' });
		//$(document.getElementById('cover3dWrapper')).css({ visibility: 'visible' });
		$('object,embed').css({ visibility: 'visible' });
	});
})();

/* Drop down menu / search options
----------------------------------------------------------------- */
(function(){
	var menu = $('#searchForm .sweet-select');
	$(menu).click(function(){ $(this).find('dd').toggle(); });
	$('li',menu).click(function(){
		menu.find('dt').html( $(this).text() ).end().next('input:hidden').val( $(this).attr('rel') );
		$('li.on',menu).removeClass('on');
		$(this).addClass('on');
	});
	
	$(document).click(function(e){
		if( !$(e.target).parents('.sweet-select').length && !$(e.target).hasClass('sweet-select')  ){
			$('.sweet-select dd').css({ display: 'none' });
		}
	});
	
})();

/* Z-Index generator
----------------------------------------------------------------- */
$(function() {
	var zIndexNumber = 9000;
	$('#navigation, #header, #header *').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
	$('#footer').css('zIndex', '9999');
});

/* Ajax process -> Pagination dans les résultats
----------------------------------------------------------------- */
(function(){
	if( $('#idResultats').length ){
		$.ajax({
			type: 'POST',
			data: { page: parseInt($('.headlines:eq(0)').attr('rel')),id_news: parseInt($('.headlines:eq(0)').attr('id')) },
			url: '/news/ajax',
			dataType: 'html',
			success: function(data){ $('.headlines:eq(0)').prepend(data); }
		});
		$('.pagination:eq(0) li').live('click',function(){
			var numPage = $('.pagination:eq(0) li').index(this) + 1;
			$('.headlines:eq(0) ul').remove();
			$.ajax({
				type: 'POST',
				data: { page: numPage,id_news: parseInt($('.headlines:eq(0)').attr('id')) },
				url: '/news/ajax',
				dataType: 'html',
				success: function(data){ $('.headlines:eq(0)').prepend(data); }
			});
			$(this).addClass('on');
			return false;
		});
	}
})();

/* Ticker
----------------------------------------------------------------- */
/*
(function(){
	var ticker = $(document.getElementById('ticker')), tpl = '<a href="{LINK}"><strong>{TITLE} : </strong>{TEXT}</a>', language = _.lang;
	
	var animation = function(item){
		var templ = tpl.replace(/{TITLE}/, item.title).replace(/{TEXT}/, item.text).replace(/{LINK}/, item.link),
			newEl = $(templ).css({ left: '820px' }),
			oldEl = ticker.find('a');
		oldEl.fadeOut(1000, function(){
			oldEl.remove();
			ticker.find('dd').append(newEl);
			newEl.animate({ left: 0 }, 1000);
		});		
	};
	
	$.ajax({
		url: '/site/medias/news/ticker-' + language + '.txt',
		success: function(data){
			var json = eval(data), tab = json.items, len = tab.length - 1, i = 0;

			// First time
			animation(tab[i]); i++;
			
			// Next times
			setInterval(function(){
				if( i == len ) i = 0;
				animation(tab[i]);
				i++;
			}, 10000);
			
		},
		error: function(){
			console.log('error');
		}
	});
})();
*/

(function(){
	var ticker = $(document.getElementById('ticker')),
		tpl = '<li><a href="{LINK}"><strong>{TITLE} : </strong>{TEXT}</a></li>';
	
	$.ajax({
		url: '/site/medias/news/ticker-' + _.lang + '.txt',
		success: function(data){
			var json = eval(data),
				news = json.items,
				len = news.length,
				frag = '<ul id="scroller">',
				i = 0;
			
			// Fill
			for (i = 0; i < len; i++) { frag += tpl.replace(/{TITLE}/, news[i].title).replace(/{TEXT}/, news[i].text).replace(/{LINK}/, news[i].link); }
			frag += '</ul>';
			ticker.find('dd').append(frag);
			var t = window.setTimeout(function(){
				$(document.getElementById('scroller')).liScroll();
				window.clearTimeout(t);
			},1000);
		}
	});
})();

(function(){
	jQuery.fn.liScroll = function (settings) {
	    settings = jQuery.extend({
	        travelocity: 0.07
	    }, settings);
	    return this.each(function () {
	        var $strip = jQuery(this);
	        var stripWidth = 0;
	        var $mask = $strip.parents('dd:eq(0)');
	        var containerWidth = $mask.width();
	        $strip.find('li').each(function (i) {
	            stripWidth += jQuery(this, i).outerWidth(true);
	        });
	        $strip.width(stripWidth);
	        var totalTravel = stripWidth + containerWidth;
	        var defTiming = totalTravel / settings.travelocity;
	
	        function scrollnews(spazio, tempo) {
	            $strip.animate({
	                marginLeft: '-=' + spazio
	            }, tempo, "linear", function () {
	                $strip.css("margin-left", containerWidth);
	                scrollnews(totalTravel, defTiming);
	            });
	        }
	        scrollnews(totalTravel, defTiming);
	        $strip.hover(function () {
	            jQuery(this).stop();
	        }, function () {
	            var offset = jQuery(this).offset();
	            var residualSpace = offset.left + stripWidth;
	            var residualTime = residualSpace / settings.travelocity;
	            scrollnews(residualSpace, residualTime);
	        });
	    });
	};
})();



/* Ticker
----------------------------------------------------------------- */
$('#idAcademy .map').click(function(){
	$('#mask, #modal').css({ visibility: 'visible' });
});


/* Social
----------------------------------------------------------------- */
$(document.getElementById('socialToggle')).click(function(){
	var el = $(this);
	el.toggleClass('open');
	$('+ div', el).slideToggle();
});