var resizeMapCol = function resizeMapCol( oEventsManager )
{
	if ($$('.pagination') && $$('.pagination').length > 0)
	{
		if ( $$('.results') && $$('.results').length > 0 && $$('.col_map') && $$('.col_map').length > 0 )
		{
			// Set height for bottom gmap
			var iPaginationHeight = $$('.pagination td')[0].getSize().y.toInt();
			$$('.results .bottom_gmap')[0].setStyle('height', iPaginationHeight );

			var iSize = $$('.results')[0].getSize().y.toInt();
			var iMapHeight = $$('.col_map')[0].getSize().y.toInt();

			if ( iMapHeight >= iSize)
			{
				var iResultTableHeight = $$('.results table')[0].getSize().y.toInt();
				var oTR = new Element('tr');
				oTR.setStyles({'height': iSize - iResultTableHeight, 'visible' : 'hidden'});
				oTR.inject($$('.results .pagination')[0], 'before');
			}
			else
			{
				iSize -= $$('.results .dd_header')[0].getSize().y.toInt();
				iSize -= $$('.results .pagination')[0].getSize().y.toInt();

				$$('.col_map')[0].setStyle('height', iSize - 14 );
			}
		}
	}

	oEventsManager.fireEvent('nextStep');
}

var oMapManager;

var addFieldEvent = function addFieldEvent( oEventsManager )
{
	var aToggler = $$('.menu a.all');
	var offset_y = 40;
	if (aToggler.length > 0)
	{
		aToggler.each(function(elem)
		{
			var parent = elem.getParent();
			var aContent = parent.getChildren('div.all');

			if (aContent.length > 0)
			{
				elem.addEvent('click', function(){
					$$('div.all').setStyle('display', 'none');
					var menu = $$('.content .menu');
					var position = this.getPosition(menu[0]);

					var aElement = aContent[0].getElements('.arrow,.close,.flash');

					aContent[0].setStyles({'display': 'block', 'top': (position.y - offset_y)+'px'});
					if ( elem.hasClass('scrollTo') )
					{
						var oScroll = window.getScroll();
						var oObjectPos = aContent[0].getPosition();
						window.scrollTo(oScroll.x, oObjectPos.y - 10 );
					}
					aElement.setStyle('display', 'none');
					aElement.setStyle('display', 'block');
				});
			}
		});
	}

	var aContent = $$('.menu div.all a.close');
	if (aContent.length > 0)
	{
		aContent.each(function(elem)
		{
			elem.addEvent('click', function()
			{
				var div = this.getParent();
				div.setStyle('display', 'none');
			});
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var nbItemList = function(oEventsManager)
{
	var displayPage = function()
	{
		if($("display_choice").getStyle("display") == "none") {
			$("display_choice").setStyles({
				"display":"block"
			});
			$("display_choice").addEvent("mouseleave",displayPage);
		}
		else {
			$("display_choice").setStyles({
				"display":"none"
			});
			$("display_choice").removeEvent("mouseleave",displayPage);
		}
	}

	if($("display_page")) $("display_page").addEvent("mouseenter",displayPage);

	$$('#display_choice ul li a').addEvent('click', function(e)
	{
		e.stopPropagation();
		var iVal = this.get('rel');
		var oUrl = new URI(window.location);
		oUrl.setData('nb_res', iVal);
		oUrl.set('fragment', 'selection');
		oUrl.go();
	});

	oEventsManager.fireEvent('nextStep');
}

var addMapEvent = function( oEventsManager )
{
	var sIdContainer = 'gmap';

	// init GPS center of map
	var oGPSCenter = new Hash ({
		iLatitude: 45.677401,
		iLongitude: 6.394043
	});

	var iZoom = 9;

	if( $(sIdContainer) )
	{
		oMapManager = new MapManager( sIdContainer, {
			oGPSCenter: oGPSCenter,
			iZoomValue: iZoom,
			iMapTypeID: google.maps.MapTypeId.TERRAIN
		});
		oMapManager.initMap();

		oMapManager.addEvent( 'mapLoaded', function mapLoaded()
		{
			this.removeEvent( 'mapLoaded', mapLoaded );
			oEventsManager.fireEvent('nextStep');
		});

	} else
		oEventsManager.fireEvent('nextStep');
}

var addMarkersEvent = function( oEventsManager )
{
	if( $$('.object') && $$('.object').length > 0 )
	{
		/*######## BUILD PICTO DEFAULT URI ########*/
		var oURI = new URI();
		oURI.set('directory', oURI.get('directory') + '../content/scripts/displayPicto.php');
		/*######## END BUILD PICTO DEFAULT URI ########*/

		/*######## BUILD MARKER COLLECTION ########*/
		//Initialize MarkerCollection object
		var oMarkerCollection = new MapMarkerCollection({
			behaviour:{
				multipoints:{
					container: "<table cellspacing='0' cellpadding='0' border='0'>\n\
									<tr>\n\
										<td><img src='img/global/map/picto_blue_left.gif' class='fl' alt='' /></td>\n\
										<td>\n\
											<div class='conteneur' id='conteneur'>\n\
												##CONTENT##\n\
											</div>\n\
										</td>\n\
										<td><img src='img/global/map/picto_blue_right.gif' class='fl' alt='' /></td>\n\
									</tr>\n\
								</table>",
					element: "<a href='javascript:void(0);' title='##CONTENT##' rel='MultiMarker'>##CONTENT##</a>",
					icon: 'img/global/map/picto_multi.gif',
					event: function( oMultiPointMarker )
					{
						oMultiPointMarker.addEvent( 'MarkerAppended', function()
						{
							oMultiPointMarker.oMarkerEvents.customover = google.maps.event.addListener(
								oMultiPointMarker.getGMarker(),
								'mouseover',
								function()
								{
									oMultiPointMarker.CollectionData.multiPointOverlay.setPositionFromMarker(this.getGMarker());
									oMultiPointMarker.CollectionData.multiPointOverlay.setMap(this.getGMarker().getMap());
								}.bind(oMultiPointMarker)
							);

							oMultiPointMarker.oMarkerEvents.overlayout = google.maps.event.addListener(
								oMultiPointMarker.CollectionData.multiPointOverlay,
								'overlayLoaded',
								function()
								{
									oMultiPointMarker.CollectionData.multiPointOverlay.element.addEvents({
										'mouseleave': function()
										{
											oMultiPointMarker.CollectionData.multiPointOverlay.setMap(null);
										}.bind(oMultiPointMarker)
									});

									var aChildren = this.getChildrenCollection(oMultiPointMarker.CollectionData.childrenIndex);
									if( aChildren instanceof Array && aChildren.length > 0 )
									{
										aChildren.each( function( oCurrentChild )
										{
											var oLink = oMultiPointMarker.CollectionData.multiPointOverlay.element.getElement('a[title='+oCurrentChild.CollectionData.index+']');
											if( oLink )
											{
												oLink.addEvents({
													'mouseenter': function()
													{
														oCurrentChild.fireEvent('mouseenter');
													},

													'mouseleave': function()
													{
														oCurrentChild.fireEvent('mouseleave');
													}
												});

												if( $chk(oCurrentChild.obtLink) && oCurrentChild.obtLink != "" )
													oLink.set('href', oCurrentChild.obtLink);
											}
										});
									}
								}.bind(this)
							);
						}.bind(this));
					}
				}
			}
		});
		/*######## END BUILD MARKER COLLECTION ########*/

		/*######## BUILD ALL MARKERS AND PUSH INSIDE COLLECTION ########*/
		$$('.object').each
		(
			//For each point given
			function( oItem, sIndex )
			{
				var oInput = oItem.getElement("input[name='geoloc']");
				if( oInput )
				{
					var aCoords = oInput.get('value').split(';');

					if( aCoords.length == 2 )
					{
						oURI.clearData();
						oURI.setData('font_size', 2);
						oURI.setData('string', sIndex.toInt() + 1);
						oURI.setData('picto', 'picto_red.gif');
						oURI.setData('font_color', '255|255|255');

						//Build a valid marker object
						var oCurrentMarker = new MapMarker(
							{
								oGPSCoord : {
									iLatitude: aCoords[0].replace(',', '.').toFloat(),
									iLongitude: aCoords[1].replace(',', '.').toFloat()
								},
								oIcon :
								{
									sIconPath : oURI.toString()
								}
							}
						);

						var oLink = oItem.getElement('a');
						if( oLink )
							oCurrentMarker.obtLink = oLink.get('href');

						oMarkerCollection.pushMarkerWithExactPositionFilter(oCurrentMarker, sIndex.toInt() + 1);
					}
				}
			}
		);
		/*######## END BUILD ALL MARKERS AND PUSH INSIDE COLLECTION ########*/

		/*######## SHOW MARKERS AND INITIALIZE ENVENT ON EACH ########*/
		oMarkerCollection.addEvent(
			'AllMarkerAppended',
			function()
			{
				oMapManager.setCenterWidthBounds();

				/**############ INIT ALL EVENTS ON APPENDED MARKERS ############*/
				var oSynchronousEventsFunction = function( aSelector )
				{
					if( aSelector && aSelector.length > 0 )
					{
						var oCurrentHighlight;
						var aTotalMarkers = this.getAllValidMarkers();

						aTotalMarkers.each(
							//For each filtered markers array
							function( oItem )
							{
								oCurrentHighlight = null;
								var iIndex = oItem.CollectionData.index - 1;

								/**############ IF GOOGLE MARKER HAVE BEEN INITIALIZED ############*/
								if( oItem.getGMarker() )
								{
									/**############ INIT GMAP MARKER EVENTS ############*/
									oItem.oMarkerEvents.click = google.maps.event.addListener(
										oItem.getGMarker(),
										'click',
										function()
										{
											if( $defined(this.obtLink) && this.obtLink != "" )
											{
												var oOBTURI = new URI(this.obtLink);
												oOBTURI.go();
											}
										}.bind(oItem)
									);

									oItem.oMarkerEvents.customover = google.maps.event.addListener(
										oItem.getGMarker(),
										'customover',
										function()
										{
											if( this.oIcon.sIconPath  != null && this.CollectionData.childrenIndex == null )
											{
												this.oIcon.sIconPath = this.oIcon.sIconPath.replace('picto_red', 'picto_blue');
												this.getGMarker().setIcon( this.getCustomMarkerImage() );
											}
										}.bind(oItem)
									);

									oItem.oMarkerEvents.customout = google.maps.event.addListener(
										oItem.getGMarker(),
										'customout',
										function()
										{
											/*if( this.oIcon.sIconPath  != null && this.CollectionData.childrenIndex == null )
											{
												this.oIcon.sIconPath = this.oIcon.sIconPath.replace('picto_blue', 'picto_red');
												this.getGMarker().setIcon( this.getCustomMarkerImage() );
											}*/

											var a = function()
											{
												if( this.oIcon.sIconPath  != null && this.CollectionData.childrenIndex == null && oCurrentHighlight.CollectionData.index != this.CollectionData.index)
												{
													this.oIcon.sIconPath = this.oIcon.sIconPath.replace('picto_blue', 'picto_red');
													this.getGMarker().setIcon( this.getCustomMarkerImage() );
												}
											}.bind(this)

											a.delay(50);
										}.bind(oItem)
									);

									oItem.oMarkerEvents.mouseover = google.maps.event.addListener(
										oItem.getGMarker(),
										'mouseover',
										function()
										{
											if( oCurrentHighlight instanceof MapMarker )
											{
												if( oCurrentHighlight.CollectionData.parentIndex == null )
													google.maps.event.trigger(oCurrentHighlight.getGMarker(), 'customout');
												else if( oCurrentHighlight.CollectionData.parentIndex != null )
													this.getParent( oCurrentHighlight.CollectionData.parentIndex ).CollectionData.multiPointOverlay.setMap(null);
											}

											if( oItem.oIcon.sIconPath  != null && oItem.CollectionData.childrenIndex == null )
											{
												oItem.oIcon.sIconPath = oItem.oIcon.sIconPath.replace('picto_red', 'picto_blue');
												oItem.getGMarker().setIcon( oItem.getCustomMarkerImage() );
											}

											oItem.fireEvent('mouseenter');

											oCurrentHighlight = oItem;
										}.bind(this)
									);

									oItem.oMarkerEvents.mouseout = google.maps.event.addListener(
										oItem.getGMarker(),
										'mouseout',
										function()
										{
											if ($$('a.landing_mode')[0].rel == '1')
											{
											oItem.oIcon.sIconPath = oItem.oIcon.sIconPath.replace('picto_blue', 'picto_red');
											oItem.getGMarker().setIcon( oItem.getCustomMarkerImage() );
											}

										});
									/**############ END INIT GMAP MARKER EVENTS ############*/
								}
								/**############ END IF GOOGLE MARKER HAVE BEEN INITIALIZED ############*/

								/**############ INTERACTION BETWEEN LIST AND MARKER ############*/
								if( aSelector[iIndex] )
								{
									aSelector[iIndex].addEvents({
										'mouseenter': function()
										{
											if( oCurrentHighlight instanceof MapMarker )
											{
												if( oCurrentHighlight.CollectionData.parentIndex == null )
													google.maps.event.trigger(oCurrentHighlight.getGMarker(), 'customout');
												else if( oCurrentHighlight.CollectionData.parentIndex != null )
												{
													var oParent = this.getParent( oCurrentHighlight.CollectionData.parentIndex );
													oParent.CollectionData.multiPointOverlay.setMap(null);
												}
											}

											if( oItem.CollectionData.parentIndex == null )
												google.maps.event.trigger(oItem.getGMarker(), 'customover');
											else if( oItem.CollectionData.parentIndex != null )
											{
												var oMarker = this.getParent( oItem.CollectionData.parentIndex );
												oMarker.CollectionData.multiPointOverlay.setPositionFromMarker(oMarker.getGMarker());
												oMarker.CollectionData.multiPointOverlay.setMap(null);
												oMarker.CollectionData.multiPointOverlay.setMap(oMarker.getGMarker().getMap());

												oMarker.oMarkerEvents.boldlayout = google.maps.event.addListener(
													oMarker.CollectionData.multiPointOverlay,
													'overlayLoaded',
													function()
													{
														this.element.getElements('table tr td a').set('style', '');
														var oHighLightedElement = this.element.getElement('a[title="'+(iIndex+1)+'"]');
														oHighLightedElement.setStyle('font-weight', 'bold');
													}
												);
											}

											oCurrentHighlight = oItem;
										}.bind(this),

										'mouseleave': function()
										{
											if( oCurrentHighlight instanceof MapMarker )
											{
												if( oCurrentHighlight.CollectionData.parentIndex == null )
												{
													google.maps.event.trigger(oCurrentHighlight.getGMarker(), 'customout');
													google.maps.event.trigger(oCurrentHighlight.getGMarker(), 'mouseout');
												}
												else if( oCurrentHighlight.CollectionData.parentIndex != null )
												{
													var oParent = this.getParent( oCurrentHighlight.CollectionData.parentIndex );
													oParent.CollectionData.multiPointOverlay.setMap(null);
												}
											}
										}
									});
								}
								/**############ END INTERACTION BETWEEN LIST AND MARKER ############*/

								/**############ INTERACTION BETWEEN MARKER AND LIST ############*/
								oItem.addEvents({
									'mouseenter': function()
									{
										if( aSelector[iIndex] )
										{
											if( $chk(aSelector[iIndex].onmouseover))
												aSelector[iIndex].onmouseover();
											else
												aSelector[iIndex].fireEvent('mouseenter');

											if( $('objects_list') )
											{
												var oElement = aSelector[iIndex];
												var oElementPosition = oElement.getPosition($('objects_list'));
												var oParentPosition = oElement.getParent().getPosition($('objects_list'));

												if( oElementPosition.y + 150 > $('objects_list').getStyle('height').toInt() )
												{
													oElement.getParent().setStyle(
														'top',
														-1 * ( oElementPosition.y + 150 + Math.abs(oParentPosition.y) - $('objects_list').getStyle('height').toInt() )
													);
												}
												else if( oElementPosition.y < 0 )
												{
													oElement.getParent().setStyle(
														'top',
														oParentPosition.y + Math.abs(oElementPosition.y)
													);
												}
											}
										}
									}
								});
								/**############ END INTERACTION BETWEEN MARKER AND LIST ############*/
							}.bind(this)
						);
					}
				}
				oSynchronousEventsFunction.bind( this ).run( [ $$('.object') ] );
				/**############ END INIT ALL EVENTS ON APPENDED MARKERS ############*/

				oEventsManager.fireEvent('nextStep');
			}
		);

		oMarkerCollection.showMarkers( oMapManager );
		/*######## END SHOW MARKERS AND INITIALIZE ENVENT ON EACH ########*/
	}
	else
		oEventsManager.fireEvent('nextStep');
}

var addSliderItemBtnEvent = function( oEventsManager )
{
	// get container for list
	var oContainerItemList = $$('.carto table .objects_list .objects_viewport');

	// set height for one item
	var iHeightItem = 57;

	// get top button for slide
	var oClickTop = $$('.carto table td#clickable_top');
	if( oClickTop )
	{
		// call moveTo on click
		oClickTop.addEvent( 'click', function(){
			moveTo.run( [oContainerItemList, iHeightItem] );
		});

		// roll over
		oClickTop.addEvent( 'mouseenter', function(){
			this.getElements('img').set('src', './img/global/landing/arrow_up_roll.gif');
		});

		oClickTop.addEvent( 'mouseleave', function(){
			this.getElements('img').set('src', './img/global/landing/arrow_up.gif');
		});
	}

	// get bottom button for slide
	var oClickBottom = $$('.carto table td#clickable_bottom');
	if( oClickBottom )
	{
		// call moveTo on click
		oClickBottom.addEvent( 'click', function(){
			moveTo.run( [oContainerItemList, -iHeightItem] );
		});

		// roll over
		oClickBottom.addEvent( 'mouseenter', function(){
			this.getElements('img').set('src', './img/global/landing/arrow_down_roll.gif');
		});

		oClickBottom.addEvent( 'mouseleave', function(){
			this.getElements('img').set('src', './img/global/landing/arrow_down.gif');
		});
	}

	// moveTo function for slide item container
	var moveTo = function ( oElement, iValue ){
		var iTopElement 	= oElement.getStyle('top')[0].toInt();
		var iHeightParent 	= oElement.getParent()[0].getHeight();
		var iHeightElement 	= oElement.getHeight();
		var iMaxValue		= iHeightParent - iHeightElement;

		if( iTopElement + iValue >= 0 )
			oElement.setStyle( 'top', 0 );
		else if( iTopElement + iValue < iMaxValue )
			oElement.setStyle( 'top', iMaxValue );
		else
			oElement.setStyle( 'top', iTopElement + iValue );
	}

	oEventsManager.fireEvent('nextStep');
}

var addItemCartoListEvent = function( oEventsManager )
{
	// get items
	var aItem = $$('.carto table .objects_list .objects_viewport .object');
	var aItemClassImg = $$('.carto table .objects_list .objects_viewport .object div.image');

	// add mouse over event on each item
	aItem.each( function( elem ){
		elem.addEvent( 'mouseenter', function(e){
			if( e )
				e.stopPropagation();

			// reinit all item with old class value or empty value
			reInitClassItem.run();

			// remove img class if exist
			if( this.hasClass('img') )
				this.removeClass('img');

			// add open class
			this.addClass('open');
		});
	});

	// reinit class on item
	var reInitClassItem = function()
	{
		// remove open class on each item
		aItem.each( function( elem ){
			elem.removeClass('open');
		});

		// add img class on item which was img before had opened
		aItemClassImg.each( function( elem ){

		});
	}

	oEventsManager.fireEvent('nextStep');
}

var changeLandingMode = function( oEventsManager )
{
	var aBtnMode = $$('.landing_mode');
	aBtnMode.each(function(oBtnMode)
	{
		oBtnMode.addEvent('click', function(e)
		{
			e.stopPropagation();

			var iMode = this.get('rel'); // 0 = To Default Mode - 1 = To Carto Mode
			var oUrl = new URI(window.location);
			oUrl.setData('carto_mode', iMode);
			oUrl.set('fragment', 'selection');
			oUrl.go();
		});
	});

	oEventsManager.fireEvent('nextStep');
}

var cartoFollowScroll = function( oEventsManager )
{
	if ( $$('.gmap_container #gmap') && $$('.gmap_container #gmap').length > 0 )
	{
		var iMapPosition = $('gmap').getPosition();
		var oMapSize = $('gmap').getSize();
		var iMapContainer = $$('.results .col_map')[0].getStyle('height');

		$$('.gmap_container').setStyle('position', 'relative');

		window.addEvent('scroll', function()
		{
			if ( window.getScroll() )
			{
				var iScrollY = window.getScroll().y;
				if ( iScrollY > iMapPosition.y )
				{
					var iNewPos =  (iScrollY.toInt() - iMapPosition.y.toInt());
					if ( iNewPos + oMapSize.y < iMapContainer.toInt() - 15 )
						$('gmap').setStyles({ 'top' : iNewPos + 'px', 'margin-top' : '15px'});
				}
				else
					$('gmap').setStyles({'top' : 0, 'margin-top' : 0});
			}
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var addCufonInfos = function( oEventsManager )
{
	Cufon.replace('.list .top_list .informations span');
	Cufon.replace('.list_filters .head .title');

	oEventsManager.fireEvent('nextStep');
}

var addScrollAll = function( oEventsManager )
{
	if( $$('div.all') )
	{
		if( $("other_criteria") )
			$('other_criteria').setStyle('display', 'block');

		$$('div.all').each(function(el, index){
			el.setStyle('display', 'block');
			el.id = 'allBlock'+index;
			oAllContent = el.getChildren('.all_content')[0];
			if (!oAllContent.hasClass('territory'))
			{
				oAllContent.id = 'allContent' + index;
				//IE6 simulate max-height and min height
				if ( el.getSize().y > 520 )
					oAllContent.setStyle('height', '520px');
				if ( el.getSize().y < 85 )
					oAllContent.setStyle('height', '85px');

				//custom scroll
				new ScrollBar(el.id, oAllContent.id , {hScroll: false});
			}
			el.setStyle('display', 'none');
		});

		if( $("other_criteria") )
			$('other_criteria').setStyle('display', 'none');
	}

	oEventsManager.fireEvent('nextStep');
}

var addDirectListEvents = function( oEventsManager )
{
	if ( $('directAccess') )
	{
		$('directAccess').addEvent('change', function(e){
			e.stop();
			window.location = $('directAccess').value;
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var displayFilters = function( oEventsManager )
{
	if ( $$('.list_filters .list_content') && $$('.list_filters .list_content').length > 0 )
	{
		// Sauvegarde du lien affiché
		var oActualLink;
		if( $$('.list_filters .head li.selected')[0] )
		{
			oActualLink = $$('.list_filters .head li.selected')[0];
			if( oActualLink.getPrevious() )
				oActualLink.getPrevious().getElement('a').removeClass('off');
		}

		$$('.list_filters .head li a').addEvent('mouseenter',
			function()
			{
				// Gestion des petits traits en fond
				if( $defined(oActualLink) )
					oActualLink.removeClass('selected');

				// Masquage du bloc correspondant
				$$('.list_filters .head li a').addClass('off');
				$$('.list_filters .list_content').removeClass('on');

				oActualLink = this.getParent();
				if( oActualLink.getPrevious() )
					oActualLink.getPrevious().getElement('a').removeClass('off');
				oActualLink.addClass('selected');

				$('bloc_' + this.get('id') ).addClass('on');
			}
		);
	}

	oEventsManager.fireEvent('nextStep');
}

var manageCalendar = function( oEventsManager )
{
	/** instance of Calendar eighty six **/
	if( $('first_date') )
	{
		var calendar1 = new CalendarEightysix('first_date', {
			'startMonday': true,
			'format': '%d/%m/%Y',
			'minDate': 'today',
			'defaultDate': sStartDate,
			'toggler': 'cal_begin',
			'offsetX': -82,
			'offsetY': 19
		});
	}

	if( $('last_date') )
	{
		var sMinDate = 'today';
		if( sStartDate != '' )
			sMinDate = sStartDate;

		var calendar2 = new CalendarEightysix('last_date', {
			'startMonday': true,
			'format': '%d/%m/%Y',
			'minDate': sMinDate,
			'defaultDate': sEndDate,
			'toggler': 'cal_end',
			'offsetX': -82,
			'offsetY': 19
		});
	}

	if(
		$chk(calendar1) && calendar1 instanceof CalendarEightysix
		&& $chk(calendar2)  && calendar2 instanceof CalendarEightysix
	){
		calendar1.addEvent('change', function(date) {
			date = date.clone(); //At least one day higher; so increment with one day
			calendar2.options.minDate = date; //Set the minimal date
			if( calendar2.getDate().diff(date) >= 1 )
				calendar2.setDate(date); //If the current date is lower change it
			else
				calendar2.render(); //Always re-render
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var displayMap = function( oEventsManager )
{
	var currentTerritory = null;

	if( $$('.territoire') )
	{
		$$('.territoire .list_data li a').addEvents({
			mouseover : function( el ) {
				// Calcul des positions
				var iWidth = $('display_map').getStyle('width').toInt();
				var iHeight = $('display_map').getStyle('height').toInt();

				// Position du li
				var sLeft = this.getPosition().x;
				var sTop = this.getPosition().y; // position of the right arrow

				// position carto
				var iPositionX = sLeft - iWidth;
				var iPositionY = sTop - iHeight + 245;

				$('display_map').setStyles({
					'visibility' : 'visible',
					'left' : iPositionX+'px',
					'top' : iPositionY+'px'
				});

				// display territory
				if(
					$type( $('carto-dd').handleShowTerritory ) == 'function'
					&& currentTerritory != this.id
				){
					currentTerritory = this.id;

					$('carto-dd').handleShowTerritory( this.id );
				}
			},
			mouseleave : function( el ) {

				if( $type( $('carto-dd').handleHideTerritories ) == 'function' )
				{
					currentTerritory = null;

					$('carto-dd').handleHideTerritories();
				}

				$('display_map').setStyles({
					'visibility':'hidden',
					'top':'-1000px'
				});
			}
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var cityAutocompletion = function( oEventsManager )
{
	if( $$('.autocompletion')[0] )
	{
		var aAutocompletion = $$('.autocompletion');

		aAutocompletion.each(function (el){

			var autoComplInput = el.getElements('input');

			//var links = el.getChildren('div.tooltip_content').getChildren('div.scroll').getChildren('ul.colonne').getChildren('li').getChildren('a');
			var aLinks = $$('#page .commune #all-cities')[0].getElements('ul.list_data li a');

			var aAutoWord = new Array();

			aLinks.each(function (elem){
				aAutoWord.push(elem.get('text')+'@'+elem.get('href'));
			});

			// Custom choices creation
			if( autoComplInput[0] )
			{
				new Autocompleter.Local(autoComplInput[0], aAutoWord, {
					'minLength': 1,
					'selectMode': 'pick',
					'appendDiv': $(document.body),
					'injectChoice': function(token){

						// setValue in Observer Class modified to suppress the span
						aIdLink = token.split('@');
						sLabel = aIdLink[1];
						sValue = aIdLink[0];
						var aValue = sValue.split(' (');
						sValue = aValue[0] + ' <span>(' + aValue[1] + '</span>';

						var choice = new Element('li');
						//new Element('span', {'html': this.markQueryValue(sValue)}).inject(choice);
						new Element('a', {
							'class': 'demo-info',
							'href': sLabel,
							'target': '_self',
							'title': aValue[0],
							'html': this.markQueryValue(sValue)
						}).inject(choice);

						choice.inputValue = sValue;
						this.addChoiceEvents(choice).inject(this.choices);
					}
				});
			}

		});
	}

	oEventsManager.fireEvent('nextStep');
}

var cityFirstLetter = function( oEventsManager )
{
	if( $$('.filter_letter .letters')[0] )
	{
		$$('.filter_letter .letters li a').addEvent('click',
			function()
			{
				$$('.filter_letter .letters li a').setStyle('font-weight','normal');
				$('filtered-cities').set('html', '');
				if( this.getParent().hasClass('first') )
				{
					$('filtered-cities').setStyle('display', 'none');
					$('all-cities').setStyle('display', 'block');
				}
				else
				{
					this.setStyle('font-weight','bold');

					var aSearch  = new Array('À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý');
					var aReplace  = new Array('A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y');

					var sFirstLetter = this.get('html');
					var aElements = new Array();
					$$('.list_content.commune .list_data a').each(
						function( element )
						{
							var sCommune = element.get('html');
							aSearch.each( function( sItem, iIndex ) { sCommune = sCommune.replace(sItem, aReplace[iIndex]); });
							if( sCommune.indexOf(sFirstLetter) == 0 )
								aElements.push(element.getParent().clone());
						}
					);


					var iLimit = ((Math.floor(aElements.length / 3) == 0) ? 1 : Math.floor(aElements.length / 3));
					var iValidLimit = iLimit;
					var iPassed = 0;
					var oUL;
					var iModulo = ( aElements.length < 3 ) ? 0 : aElements.length % 3;
					aElements.each(
						function( oElement, iIndex )
						{
							if( ( iIndex - iPassed ) % iValidLimit == 0 )
							{
								if( iModulo > 0 )
								{
									iValidLimit = iLimit + 1;
									iModulo--;
								}
								else
									iValidLimit = iLimit;

								iPassed = $('filtered-cities').getElements('li').length;

								oUL = new Element('ul', {'class':'list_data fl'});
								oUL.inject($('filtered-cities'));
							}

							oElement.inject(oUL);
						}
					);

					$('all-cities').setStyle('display', 'none');
					$('filtered-cities').setStyle('display', 'block');
				}
			}
		);
	}

	oEventsManager.fireEvent('nextStep');
}

if ( oEventsManager != null && oEventsManager != undefined )
{
	oEventsManager.registerEvent('resizeMapCol', resizeMapCol);
	oEventsManager.registerEvent('addFieldEvent', addFieldEvent);
	oEventsManager.registerEvent('nbItemList', nbItemList);
	oEventsManager.registerEvent('addMapEvent', addMapEvent);
	oEventsManager.registerEvent('addSliderItemBtnEvent', addSliderItemBtnEvent);
	oEventsManager.registerEvent('addItemCartoListEvent', addItemCartoListEvent);
	oEventsManager.registerEvent('changeLandingMode', changeLandingMode);
	oEventsManager.registerEvent('cartoFollowScroll', cartoFollowScroll);
	oEventsManager.registerEvent('addCufonInfos', addCufonInfos);
	oEventsManager.registerEvent('addMarkersEvent', addMarkersEvent);
	oEventsManager.registerEvent('addDirectListEvents', addDirectListEvents);
	oEventsManager.registerEvent('displayFilters', displayFilters);
	oEventsManager.registerEvent('displayMap', displayMap);
	oEventsManager.registerEvent('manageCalendar', manageCalendar);
	oEventsManager.registerEvent('cityAutocompletion', cityAutocompletion);
	oEventsManager.registerEvent('cityFirstLetter', cityFirstLetter);
}


