/*!
 * Site Internet du CNFPT v2.5
 * http://www.cnfpt.fr/
 * Copyright 2011, CNFPT - Direction de la Communication - TIC
 * License: none (public domain)
 */
/*!
 * Reduced set from : jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
 * Copyright (c) 2007 George Smith
 */

// t: current time, b: begInnIng value, c: change In value, d: duration

	jQuery.extend( jQuery.easing,
	{
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) {
				s = 1.70158;
			}
			return (c*(t/=d)*t*((s+1)*t - s) + b);
		},
		easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) {
				s = 1.70158;
			}
			return (c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b);
		}
	/*
		easeInBounce: function (x, t, b, c, d) {
			return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
		},
		easeOutBounce: function (x, t, b, c, d) {
			if ((t/=d) < (1/2.75)) {
				return c*(7.5625*t*t) + b;
			} else if (t < (2/2.75)) {
				return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
			} else if (t < (2.5/2.75)) {
				return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
			} else {
				return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
			}
		},
		easein: function(x, t, b, c, d) {
			return c*(t/=d)*t + b; // in
	    },
		easeout: function(x, t, b, c, d) {
			return -c*t*t/(d*d) + 2*c*t/d + b;
	    }
	*/
	});

	String.prototype.trim = function() {
		var str = this.replace(/^\s/, ''),
			end = str.length -1,
			ws = /\s/;

		while(ws.test(str.charAt(end))) {
			end --;
		}
		return str.slice(0, end + 1);
	}

	function handleErrors(errors){
		if(typeof(errors) !== 'object' || errors.length === undefined) return false;
		
		var handlingErrors = document.getElementById('handlingErrors');
		
		if(document.createDocumentFragment) {
			fragment = document.createDocumentFragment();
		} else {
			fragment = document.createElement('div');
		}
		
		if(errors.length > 3) {
			v = document.createElement("var")
			v.setAttribute("class", "all");
		  	t = document.createTextNode("Les champs en caractères gras doivent être renseignés");
			v.appendChild(t);
			fragment.appendChild(v);			

		} else {
			
			for(var i=0, l=errors.length; i<l; i++) {
				v = document.createElement("var")
				v.setAttribute("class", errors[i].id);
			  	t = document.createTextNode(errors[i].message);
				v.appendChild(t);
				fragment.appendChild(v);
			}
		}
		
		while(handlingErrors.firstChild) {
			handlingErrors.removeChild(handlingErrors.firstChild);
		}
			
		handlingErrors.appendChild(fragment.cloneNode(true));
		while(fragment.firstChild) {
			fragment.removeChild(fragment.firstChild);
		}
		
		handleCorrections();
		
		$("html:not(:animated),body:not(:animated)").animate({
			scrollTop:$('.header').outerHeight()
		}, 700, 'easeOutBack');

	}
	
	function handleCorrections() {
		h = document.getElementById('handlingErrors') || null;
		if (h === null) return;
		
		$('.mandatory :input').change(function(event){
			id = this.id;
			css = this.parentNode.className;
			
			if(($('var[class="'+id+'"]').length > 0 || $('var[class="all"]').length > 0) && this.value.trim()!= '') {
				$('var[class="'+id+'"]').remove();
				this.parentNode.className = css.replace(/\s?error\s?/, '');
			}
		});
	}
	
	function phone_format(num) {
		// \D correspond a tout l'alphabet pour Firefox 2 et precedents
		// mais ... seulement 0,64 % environ de part de marche.
		// format = this.value.replace(/[^0-9]/g,'');
		format = num.replace(/\D/g,'');
		
		if(format.length==10) {
			return format.replace(/(\d\d)/g, "$1 ");
		} else if (format.length==9) {
			return format.replace(/(\d\d\d)(\d\d)(\d\d)(\d\d)/, "($1) $2 $3 $4");
		} else {
			return "";
		}
	}

	var ie = jQuery.support.cssFloat;
	if(document.getElementById('chunk') !== null) {
		
		var searchDefaultText = document.getElementById('chunk').value.toLowerCase();

		$('#chunk').focus(function(event){
			if(this.value.toLowerCase() == searchDefaultText){
				this.value = "";
			}
		}).blur(function(event){
			chunk = this.value.trim();
			if(chunk.length == '0') {
				this.value = searchDefaultText;			
			}
		});
		$('#searchThisText').click(function(event){
			var text = document.getElementById('chunk').value.toLowerCase();
			if(text.trim() === searchDefaultText){
				event.preventDefault();
				return false;
			}
		});
	};

/*
	if(!ie) {
		$(".wrapper").fadeIn(1200);
		$("a[rel~=external]").live('click', function(event) {
			event.preventDefault();
			var link = this;
			$(".wrapper").fadeOut(700, function() { document.location = link.href;	});
		});
	}
*/
	if(document.getElementById('links') !== null) {
		var anchor = $('<a href="#">Imprimer la page</a>').click(function(event){
			event.preventDefault();
			window.frameElement ? window.top.print() : window.print();
		});
		$('.print').append(anchor);
	}
	
	if(document.getElementById('gotop') !== null) {
		$('#gotop').click(function(event){
			event.preventDefault();
			$('html,body').animate({scrollTop:$('#top').offset().top},{duration:500,easing:'easeOutBack'});
		});
	}
	if(document.getElementById('sitemap') !== null) {
		$('#sitemap').find('h3').click(function(event){
			$('h3').removeClass('current');
			$(this).addClass('current').next().slideDown();
		});
	}
	
	
/*
 * fifth file, 'carousel' plugin.
 */
	try {
		if(!$('.clipper ul li').length) {
			$('div.services').fadeOut();
		}
		
		if($('.clipper ul li').length > 1) {
			$('<a class="prev" href="#"></a>').prependTo('#carousel');
			$('<a class="next" href="#"></a>').appendTo('#carousel');			

			var ul = $('.clipper ul');
			var next = $('.next');
			var prev = $('.prev');
			var liwidth = parseInt($('#carousel li').css('width'));
			var ulwidth = parseInt($('#carousel ul').css('width'));
			var offset = 0;
			var max = (ulwidth - liwidth);

			$('.next, .prev').bind('click keypress', function(event){
				event.preventDefault();
				event.stopPropagation();
						
				if(event.type === 'click') {
					if(/disabled/.test(this.className)) return;

					if(this.className == 'next') {
						if(offset == max) {
							ul.animate({'left': 0});
							offset = 0;
						} else {
							offset += liwidth;
							ul.animate({'left': -offset});
						}
					
						/*
						offset += liwidth;
						ul.animate({'left': -offset});
						prev.removeClass('disabled');
						prev.attr('href','#');
						if(offset == max) {
							next.addClass('disabled');
							prev.removeAttr('href');
						}
						*/
					
					} else {
						if(offset == 0) {
							ul.animate({'left': -max});
							offset = max;
						} else {
							offset -= liwidth;
							ul.animate({'left': -offset});
						}
						/*
						offset -= liwidth;
						ul.animate({'left': -offset});
						next.removeClass('disabled');
						next.attr('href','#');
						if(offset == 0) {
							prev.addClass('disabled');
							prev.removeAttr('href');
						}
						*/
					}
				}

			});

			var intervalId = null;
			var stopScrolling = false;
			
			function autoScroll(){	
				intervalId = window.setInterval(function(){
					$('.next').click();	
				}, 2500);
			};

			jQuery('#carousel').hover(
				function(){window.clearInterval(intervalId);},
				function(){
					if(!stopScrolling) {
						autoScroll();
					}
				}
			);

			autoScroll();
			
			if(intervalId !== null) {
				$('#stopCarousel').text('Arrêter le défilement');
				
				$('#stopCarousel').bind('click keypress', function(event){
					event.preventDefault();
					event.stopPropagation();
						
					if(event.type === 'click') {
						window.clearInterval(intervalId);
						stopScrolling = true;
					}
				});
			}
		}

	} catch(e) { }

/**
 * mosaic animation
 * Rely onrely Isotope jQuery plugin.
 * http://isotope.metafizzy.co/
 */
	
	var  timestamp	= +new Date()
		,imgs		= []
		,ids		= []
		,blank		= '/site/assets/images/interface/blank.png'
		,upload		= '/site/fr/uploads/'
		,params		= {
			'X-Requested-With':'XMLHttpRequest',
			'X-Requested-By': (document.body.addEventListener ? null : 'Trident'),
			'bunch':''
			};
			
	var setSrc = document.body.addEventListener ?
		function(arr, index){
			scheme = (arr[index].length > 200 ? 'jpeg' : 'png');
			return 'data:image/'+scheme+';base64,'+arr[index];
		}:
		function(arr, index){
			return '/site/fr/uploads/'+arr[index];
		};
		
	$('#container img').each(function(){
		imgs.push(this);
		ids.push(this.id);
	});
	
	if(ids.length) {
		params.bunch = ids.join(';');
	
		$.post('/site/api/accompagne/_rollon-accompagne.php?t='+timestamp, params, function(xhr){
			data = xhr.split("\u0001");

			for(var i=0, len=imgs.length; i<len; i++) {
				imgs[i].src = setSrc(data,i);
			}
		});	
		$('#container').isotope({itemSelector:'.item', layoutMode:'fitRows'});
		
		$('#container').find('.item').click(
			function(event){
				if (!/large/.test(this.className)) {					
					$('.item').removeClass('large');
					$('.item span').hide();
					$(this).toggleClass('large');
					$('#container').isotope('reLayout', function(){
						$('.large span').fadeIn();
					});
					return false;
				}
			}
		);
		
	}
	

/*
 * fourth file, 'home' plugin.
 */

/**
 *	video loading
 */
	var  timestamp = +new Date()
		,params = {'type':'metier','topic':'promotion'}
		;


	$('#clip').bind('click', function(event){
		event.preventDefault();
		
		$(this).parent().addClass('loading');
		$(this).children().fadeOut();
		$('#video').empty().load('/site/medias/video-loader.php?t='+timestamp, params,
		function(response,status,xhr){
			$('#video').removeClass('loading');
			$(this).unbind(event);
			if (status == 'error') {
				$('#video').html(xhr.status + " " + xhr.statusText);
			}
		});
	});


/**
 * catalog
 */
	if(document.getElementById('detaillee') !== null) {
		var  keywords			= document.getElementById('MotsCles')
			,defaultKeyWords 	= keywords.value
			,selects 			= ['nil','nil']
			,messages			= [
									 "Indiquez le département d'activité professionnelle.<br>Indiquez le domaine recherché et/ou une recherche libre."
									,''
									,'']
			,help				= []
			,form 				= document.getElementById('detaillee')
			;

		$('#MotsCles').focus(function(event){
			if(this.value == defaultKeyWords){
				this.value = "";
			}
		}).blur(function(event){
			chunk = this.value.trim();
			if(chunk.length == '0') {
				this.value = defaultKeyWords;			
			}
		});

		$('#detaillee .help').each(function(index){
			help[index] = $(this).attr('title') || '';
			$(this).removeAttr('title');
			$(this).click(function(event){
				event.stopPropagation();
				if(help[index]!== '') {
					form.getElementsByTagName('div')[index].innerHTML = help[index];
				}
			});
		});

		$('#detaillee select').each(function(index) {
			selects[index] = this.options[this.selectedIndex].value;
	
			$(this).change(function(){
				if(index === 0) {
					if(this.options[this.selectedIndex].value !== 'nil'){
						selects[index] = this.options[this.selectedIndex].value;
						form.getElementsByTagName('div')[0].innerHTML = '';
					} else {
						selects[index] = 'nil';
						form.getElementsByTagName('div')[0].innerHTML = help[0];
					}
				} else {
					selects[index] = this.options[this.selectedIndex].value;
				}
			});
		});
	

		$('#detaillee').click(function(event) {
			if(event.target.name.indexOf('soumettre') != -1) {
				event.preventDefault();
			
				if(selects[0] === 'nil') {
					form.getElementsByTagName('div')[0].innerHTML = messages[0];
					return false;
				}
				if(selects[0] !== 'nil'){
					if (selects[1] === 'nil' && keywords.value === defaultKeyWords) {
						return false;
					}
				}/*
				if(selects[1] !== 0 && keywords.value !== defaultKeyWords) {
					return false;
				}*/
				$('#detaillee').append('<input type="hidden" name="'+event.target.name+'" value="'+event.target.value+'"/>');
				this.submit();
			}
		});
	}

/**
 * ticker
 */
/*! liScroll 1.0. © 2007-2010 Gian Carlo Mingati */

jQuery.fn.liScroll = function(settings) {
	settings = jQuery.extend({travelocity: 0.01}, settings);
	
	return this.each(function(){
		var $strip = jQuery(this);
		$strip.addClass("newsticker");
		var stripWidth = 0;
		var $mask = $strip.wrap("<div class='mask' style=''></div>");
		var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
		var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width 	
		var currentState = true;
		
		$strip.find("li").each(function(i){
			$(this).attr("style","height:18px");
			stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar
		});
		$strip.width(stripWidth);			
		var totalTravel = stripWidth+containerWidth;
		var defTiming = totalTravel/settings.travelocity; // thanks to Scott Waye		
		function scrollnews(spazio, tempo){
			$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
		}
		scrollnews(totalTravel, defTiming);
				
		$strip.hover(function(){
			jQuery(this).stop();
			currentState = false;
			
		}, function(){
			var offset = jQuery(this).offset();
			var residualSpace = offset.left + stripWidth;
			var residualTime = residualSpace/settings.travelocity;
			scrollnews(residualSpace, residualTime);
			currentState = true;
		});
		
		$('#stop').click(function(){
			if(currentState === true){
				$strip.trigger('mouseenter');
				currentState = false;
				$(this).html('Reprendre le défilement');
			} else {
				$strip.trigger('mouseleave');
				currentState = true;
				$(this).html('Arrêter le défilement');
			}
		});	
	});	
};


	try {
		$("#ticker").liScroll({travelocity: 0.06});
		setTimeout(function(){
			$('#stabilisator').css('visibility','visible');
			}, 500);
	} catch(e) { }
