/** Libraries **/
/* jquery.backgroundPosition */
(function($){if(!document.defaultView||!document.defaultView.getComputedStyle){var oldCurCSS=$.curCSS;$.curCSS=function(elem,name,force){if(name==="background-position")name="backgroundPosition";if(name!=="backgroundPosition"||!elem.currentStyle||elem.currentStyle[name])return oldCurCSS.apply(this,arguments);var style=elem.style;if(!force&&style&&style[name])return style[name];return oldCurCSS(elem,"backgroundPositionX",force)+" "+oldCurCSS(elem,"backgroundPositionY",force)}}var oldAnim=$.fn.animate;
$.fn.animate=function(prop){if("background-position"in prop){prop.backgroundPosition=prop["background-position"];delete prop["background-position"]}if("backgroundPosition"in prop)prop.backgroundPosition="("+prop.backgroundPosition;return oldAnim.apply(this,arguments)};function toArray(strg){strg=strg.replace(/left|top/g,"0px");strg=strg.replace(/right|bottom/g,"100%");strg=strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");var res=strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);return[parseFloat(res[1],
10),res[2],parseFloat(res[3],10),res[4]]}$.fx.step.backgroundPosition=function(fx){if(!fx.bgPosReady){var start=$.curCSS(fx.elem,"backgroundPosition");if(!start)start="0px 0px";start=toArray(start);fx.start=[start[0],start[2]];var end=toArray(fx.end);fx.end=[end[0],end[2]];fx.unit=[end[1],end[3]];fx.bgPosReady=true}var nowPosX=[];nowPosX[0]=(fx.end[0]-fx.start[0])*fx.pos+fx.start[0]+fx.unit[0];nowPosX[1]=(fx.end[1]-fx.start[1])*fx.pos+fx.start[1]+fx.unit[1];fx.elem.style.backgroundPosition=nowPosX[0]+
" "+nowPosX[1]}})(jQuery);
/* jquery.cookie */
jQuery.cookie=function(key,value,options){if(arguments.length>1&&String(value)!=="[object Object]"){options=jQuery.extend({},options);if(value===null||value===undefined)options.expires=-1;if(typeof options.expires==="number"){var days=options.expires,t=options.expires=new Date;t.setDate(t.getDate()+days)}value=String(value);return document.cookie=[encodeURIComponent(key),"=",options.raw?value:encodeURIComponent(value),options.expires?"; expires="+options.expires.toUTCString():"",options.path?"; path="+
options.path:"",options.domain?"; domain="+options.domain:"",options.secure?"; secure":""].join("")}options=value||{};var result,decode=options.raw?function(s){return s}:decodeURIComponent;return(result=(new RegExp("(?:^|; )"+encodeURIComponent(key)+"=([^;]*)")).exec(document.cookie))?decode(result[1]):null};
/* jquery.JSON */
(function($){$.toJSON=function(o){if(typeof JSON=="object"&&JSON.stringify)return JSON.stringify(o);var type=typeof o;if(o===null)return"null";if(type=="undefined")return undefined;if(type=="number"||type=="boolean")return o+"";if(type=="string")return $.quoteString(o);if(type=="object"){if(typeof o.toJSON=="function")return $.toJSON(o.toJSON());if(o.constructor===Date){var month=o.getUTCMonth()+1;if(month<10)month="0"+month;var day=o.getUTCDate();if(day<10)day="0"+day;var year=o.getUTCFullYear();
var hours=o.getUTCHours();if(hours<10)hours="0"+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes="0"+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds="0"+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli="0"+milli;if(milli<10)milli="0"+milli;return'"'+year+"-"+month+"-"+day+"T"+hours+":"+minutes+":"+seconds+"."+milli+'Z"'}if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++)ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]"}var pairs=[];for(var k in o){var name;
var type=typeof k;if(type=="number")name='"'+k+'"';else if(type=="string")name=$.quoteString(k);else continue;if(typeof o[k]=="function")continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val)}return"{"+pairs.join(", ")+"}"}};$.evalJSON=function(src){if(typeof JSON=="object"&&JSON.parse)return JSON.parse(src);return eval("("+src+")")};$.secureEvalJSON=function(src){if(typeof JSON=="object"&&JSON.parse)return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,"@");filtered=
filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,"");if(/^[\],:{}\s]*$/.test(filtered))return eval("("+src+")");else throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string){if(string.match(_escapeable))return'"'+string.replace(_escapeable,function(a){var c=_meta[a];if(typeof c==="string")return c;c=a.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+
'"';return'"'+string+'"'};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}})(jQuery);

/**
 * DO NOT EDIT
 */
var SLIDESHOW_TIME_PER_TOTAL_TIME='shw_ptt',SLIDESHOW_TIME_PER_PICTURE='shw_pp';
var shw_d=0,shw_p=0,shw_c=0,shw_w=0,shw_l=0,shw_delay=0;
var dds_v=50;
var cshw_p=0;

/**
 * Customizable part
 */
 
/* Slideshow mode :
 * SLIDESHOW_TIME_PER_PICTURE : will use the shw_duration number
 *		as a display duration for each picture (the slideshow total
 *		duration will be (shw_duration * number of pictures) seconds).
 * SLIDESHOW_TIME_PER_TOTAL_TIME : will use the shw_duration number
 * 		as a display duration for the entire slideshow (each picture will 
 *		be display during (shw_duration / number of pictures) seconds).
 */
var slideshow_mode = SLIDESHOW_TIME_PER_PICTURE;
var shw_duration = 8; // in seconds;
var shw_loops = -1; // -1 for infinite loop
var content_slideshow_duration = 4;

/**
 * END OF customizable part
 */

function checkSecondaryNav() {
	if ($('#access-niv2').length) {
		$('#access-niv2 ul').css('left', Math.floor(($('#access-niv2').width() - $('#access-niv2 ul').width()) / 2))
	}
}
function initSlideshow() {
	if ($('#slideshow').length) {
		shw_c = $('#slidehow-pictures img').length;
		
		if (shw_c <= 1) return false;
		
		var shw_div = $('#slideshow').first();
		$('<div id="slideshow-nav">' + 
			'<div id="slideshow-nav-container"></div>' + 
			'<div id="slideshow-nav-progress">' + 
				'<div id="slideshow-nav-progress-bar"></div>' + 
			'</div>' + 
			'<div id="slideshow-nav-playpause" class="play"></div>' + 
			'<div id="slideshow-nav-bg"></div>' + 
		'</div>' + 
		'<div id="slideshow-cuts"></div>').appendTo($(shw_div));
		
		shw_w = $('#slideshow-nav').width();
		for (var i = shw_c - 1; i >= 0; i--) {
			$('#slideshow-nav-container').prepend('<span style="width:' + Math.floor(shw_w / shw_c) + 'px" id="slideshow-nav-' + i + '">' + ((String(i + 1).length == 1) ? ('0' + (i + 1)) : (i + 1) ) + '</span>');
			// -1 for the cuts (except the last one) cause we will add this 1px with the border-right style :)
			$('#slideshow-cuts').prepend('<span style="width:' + (Math.floor(shw_w / shw_c) - ((i - 1 == shw_c) ? 0 : 1)) + 'px" id="slideshow-cut-' + i + '"' + ((i == shw_c - 1) ? ' class="last"' : '') + '></span>')
		}
		
		if (SLIDESHOW_TIME_PER_TOTAL_TIME == slideshow_mode) {
			shw_d = Math.floor(shw_duration / shw_c);
		}
		else if (SLIDESHOW_TIME_PER_PICTURE == slideshow_mode) {
			shw_d = shw_duration;
		}
		
		$('#slideshow-title').click(function() { pauseSlideshow(); });
		if (0 != shw_delay) {
			bindSlideshowNavigation();
			setTimeout(resumeSlideshow, shw_delay);
		}
		else {
			resumeSlideshow();
		}
	}
}
function bindSlideshowNavigation() {
	unbindSlideshowNavigation();
	$('#slideshow-nav span').live('click', function() { navigateToSlideshowItem($(this).attr('id').substring(String('slideshow-nav-').length)); });
	$('#slideshow-cuts span').live('click', function() { navigateToSlideshowItem($(this).attr('id').substring(String('slideshow-cut-').length)); });
	$('#slideshow-nav-playpause').live('click', function() { if (1 == $('#slideshow-nav-progress-bar:animated').length) pauseSlideshow(); else resumeSlideshow(); });
}
function unbindSlideshowNavigation() {
	$('#slideshow-nav span').die('click');
	$('#slideshow-cuts span').die('click');
	$('#slideshow-nav-playpause').die('click');
}
function resumeSlideshow() {
	bindSlideshowNavigation();
	$('#slideshow-nav-playpause').removeClass('play').addClass('pause');
	$('#slideshow-nav-progress-bar').animate({ width: String('' + Math.floor(972 - (shw_p + 1) * (shw_w / shw_c)) + 'px') }, shw_d * 1000 * (Math.round((-1 * (Math.floor(972 - (shw_p + 1) * (shw_w / shw_c)) - $('#slideshow-nav-progress-bar').width())) / (shw_w / shw_c) * 100) / 100), 'linear', handleSlideshowComplete);
}
function pauseSlideshow() {
	$('#slideshow-nav-playpause').removeClass('pause').addClass('play');
	$('#slideshow-nav-progress-bar').stop(true);
}
function navigateToSlideshowItem(id) {
	if (id == shw_p) { return false; }
	unbindSlideshowNavigation();
	$('#slideshow-nav-progress-bar').stop(true);
	$('#slideshow-nav-progress-bar').animate({ width: String('' + Math.floor(972 - (id) * (shw_w / shw_c)) + 'px') }, 'slow', 'swing', function() { handleSlideshowComplete(id) });
}
function handleSlideshowComplete(id) {
	unbindSlideshowNavigation();
	var picts = $('#slidehow-pictures img');
	if (shw_p < shw_c - 1 || undefined != id) {
		$(picts[shw_p]).fadeOut();
		shw_p = (undefined == id) ? Number(shw_p + 1) : Number(id);
		$('#slideshow-nav-playpause').css('left', 30 + shw_p * (shw_w / shw_c));
		$(picts[shw_p]).fadeIn();
		var t = $(picts[shw_p]).attr('title');
		if ($('#slideshow-title p').text() != t) {
			var h = $('<p class="cache">' + t + '</p>').appendTo($('#slideshow-title')).height();
			$('#slideshow-title p.cache').remove();
			$('#slideshow-title p').animate({ opacity: 0 }, { duration: 'fast' }).animate({ height: h, duration: 'fast' }, { queue: true, complete: function() { $(this).text(t); } }).animate({ opacity: 1, duration: 'fast' }, { queue: true });
		}
		resumeSlideshow();
	}
	else { // back to first picture
		$(picts[shw_p]).fadeOut();
		shw_p = 0;
		$(picts[shw_p]).fadeIn();
		$('#slideshow-nav-playpause').css('left', 30);
		var t = $(picts[shw_p]).attr('title');
		var h = $('<p class="cache">' + t + '</p>').appendTo($('#slideshow-title')).height();
		$('#slideshow-title p.cache').remove();
		$('#slideshow-title p').animate({ opacity: 0 }, { duration: 'fast' }).animate({ height: h, duration: 'fast' }, { queue: true, complete: function() { $(this).text(t); } }).animate({ opacity: 1, duration: 'fast' }, { queue: true });
		$('#slideshow-nav-progress-bar').fadeOut(function() { 
			$(this).css('width', '100%').fadeIn();
			shw_l++;
			if (-1 == shw_loops || shw_l < shw_loops) {
				resumeSlideshow();
			}
		});
	}
}

function initContentSlideshow() {
	if ($('.content-pictures') && 1 < $('.content-pictures img').length) {
		window.setTimeout(handleContentSlideshowComplete, content_slideshow_duration * 1000);
	}
}
function handleContentSlideshowComplete() {
	var picts = $('.content-pictures img');
	$($('.content-pictures img')[cshw_p]).fadeOut();
	cshw_p = (cshw_p + 1 < picts.length) ? cshw_p + 1 : 0;
	$($('.content-pictures img')[cshw_p]).fadeIn();
	window.setTimeout(handleContentSlideshowComplete, content_slideshow_duration * 1000);
}

function initD2SWorldSlideshow() {
	if ($('#d2sworld-slideshow').length) {
		$('#d2sworld-slideshow-nav a').click(function() {
			var id = $(this).attr('id').substring($(this).attr('id').lastIndexOf('-') + 1);
			$('#d2sworld-slideshow-nav a').removeClass('current-item');
			$(this).addClass('current-item');
			$('#d2sworld-slideshow img').hide();
			$($('#d2sworld-slideshow img')[id]).show();
			$('#d2sworld-slideshow-description div').hide();
			$('#d2sworld-slideshow-description-'+id).show();
			return false;
		});
	}
	return false;
}
function animateD2SWorldMapLinksMarkers(link, out) {
	$(link).animate({ backgroundPosition: '15px 10px' }, 300 );
	$(link).animate({ backgroundPosition: '15px 0px' }, 300, function() { animateD2SWorldMapLinksMarkers(link); });
}
function handleD2SWorldMapLinksMarkersAnimateComplete(link) {
	animateD2SWorldMapLinksMarkers(link);
}

function initD2SWorldMap() {
	if ($('#d2sworld-map-links')) {
		$('#d2sworld-map-links a').mouseover(function() {
			$(this).queue();
			animateD2SWorldMapLinksMarkers($(this), false);
		});
		$('#d2sworld-map-links a').mouseout(function() {
			$(this).clearQueue();
			$(this).stop().animate({ backgroundPosition: '15px 5px' }, 300);
		});
	}
	return false;
}

function getD2SWorldDynamicCustoms() {
	var a = $.evalJSON($.cookie('d2sworld_dynamic_custom'));
	var b = [
		{ n: a[0], l: 'Amphithéâtre', t: '08h00 - 12h00', c: 'amphi' },
		{ n: a[1], l: 'Salle de formation', t: '08h00 - 12h00', c: 'form' },
		{ n: a[2], l: 'Amphithéâtre', t: '14h00 - 18h00', c: 'amphi' },
		{ n: a[3], l: 'Salle de formation', t: '14h00 - 18h00', c: 'form' }
	];
	return b;
}

function updateDynamicPictures() {
	var a = getD2SWorldDynamicCustoms();
	var c = $('#d2sworld-slideshow-dynamic-item > div').first();
	$(c).empty();
	
	switch ($('#d2sworld-slideshow-dynamic-item').attr('role')) {
		case "dyn1":
			if (dds_v <= 100) { // Morning
				$(a).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="location">'+ item['l'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			else {
				$(a.slice(-2)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="location">'+ item['l'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			break;
		case "dyn2":
			if (dds_v <= 100) { // Morning
				$(a.slice(0,2)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="location">'+ item['l'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			else {
				$(a.slice(-2)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="location">'+ item['l'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			break;
		case "dyn3":
			if (dds_v <= 100) { // Morning
				$(a.slice(0,1)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			else {
				$(a.slice(2,3)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			break;
		case "dyn4":
			if (dds_v <= 100) { // Morning
				$(a.slice(1,2)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			else {
				$(a.slice(3,4)).each(function(i, item) {
					$('<div class="p'+ i +' '+ item['c'] +'"><span class="name">'+ item['n'] +'</span><span class="time">'+ item['t'] +'</span></div>').appendTo($(c));
				});
			}
			break;
	}
}

function D2SWorldDynamicStartMarquee() {
	var f = -1 * $('.d2sworld-dynamic-marquee span').width() - 10;
	var d = 1 * String($('.d2sworld-dynamic-marquee span').css('left')).substring(0,String($('.d2sworld-dynamic-marquee span').css('left')).length - 2) - f;
	$('.d2sworld-dynamic-marquee span').animate({ left: f }, 1000 * (d / 24), 'linear', function() { $(this).css('left',   $('.d2sworld-dynamic-marquee').width()); D2SWorldDynamicStartMarquee() });
}

function initD2SWorldDynamic() {
	if ($('#d2sworld-dynamic-form')) {
		// Setting cookie if not present
		if (! $.cookie('d2sworld_dynamic_custom')) {
			$.cookie('d2sworld_dynamic_custom', $.toJSON(["Congrès Modulex","Formation Ariadne","Comité financier D2S","R&D LEGO"]), { expires: 7, path: '/' });
		}
		
		// Default form inputs values
		a = $.evalJSON($.cookie('d2sworld_dynamic_custom'));
		$(a).each(function(i, item) {
			$('#d2sworld-dynamic-form_'+i).val(item);
		});
		
		// submitting form
		$('#d2sworld-dynamic-form').submit(function() {
			var f = [];
			$($(this).serializeArray()).each(function(i, item) {
				f.push(item['value']);
			});
			$.cookie('d2sworld_dynamic_custom', $.toJSON(f), { expires: 7, path: '/' });
			
			if ($('#d2sworld-dynamic-presentation-link').attr('href') == window.location) {
				window.location = ($('#d2sworld-dynamic-form-link').attr('href'));
			}
			else {
				$('#d2sworld-dynamic-form-link').click();
				updateDynamicPictures();
			}
			return false;
		});
	}
	
	$('#d2sworld-dynamic-form-link').click(function() {
		if (! $(this).hasClass('current-item')) {
			$(this).addClass('current-item');
			$('#d2sworld-map').fadeOut(function() { $('.d2sworld-dynamic-form').fadeIn(); });
			$('.d2sworld-dynamic-form :input').first().focus();
		}
		else {
			$(this).removeClass('current-item');
			$('.d2sworld-dynamic-form').fadeOut(function() { $('#d2sworld-map').fadeIn(); });
		}
		return false;
	});
	
	$('#d2sworld-dynamic-slider').slider({
		value: dds_v,
		min:0,
		max:200,
		slide: function(event, ui) {
			if (ui.value > 100 && dds_v <= 100) {
				dds_v = 150;
				updateDynamicPictures();
			}
			else if (ui.value <= 100 && dds_v > 100) {
				dds_v = 50;
				updateDynamicPictures();
			}
		},
		stop: function(event, ui) {
			if (ui.value > 100) {
				$(this).slider('value', 150);
				
			}
			else {
				$(this).slider('value', 50);
			}
		}
	});
	
	updateDynamicPictures();
	
	if ($('.d2sworld-dynamic-marquee:visible').length) {
		D2SWorldDynamicStartMarquee();
	}
	
	return false;
}

function initAccordions() {
	if ($('.j-acc').length) {
		$('.j-acc').accordion({
			autoHeight: false,
			icons: { 'header': false, 'headerSelected': false }
		});
	}
}

function initHomepageAds() {
	if ($('.homepage-content').length) { // home
		if (! $('.homepage-content .first-visit').length) {
			if ($('.home-ad-2').length) {
				$('.home-ad-0').hide();
				$('.home-ad-2').show();
				$('.home-ad-2 img').load(function() {
					window.setTimeout(function() { $('.home-ad-2').fadeOut($('.home-ad-0').delay(600).fadeIn()); }, 14000);
				});
				window.setTimeout(function() { $('.home-ad-2').fadeOut($('.home-ad-0').delay(600).fadeIn()); }, 20000);
			}
		}
	}
}

$(document).ready(function() {
	checkSecondaryNav();
	initHomepageAds();
	initContentSlideshow();
	initSlideshow();
	initD2SWorldSlideshow();
	initD2SWorldMap();
	initD2SWorldDynamic();
	initAccordions();
});
