/**
 *	ImageFlow 0.9
 *
 *	This code is based on Michael L. Perrys Cover flow in Javascript.
 *	For he wrote that "You can take this code and use it as your own" [1]
 *	this is my attempt to improve some things. Feel free to use it! If
 *	you have any questions on it leave me a message in my shoutbox [2].
 *
 *	The reflection is generated server-sided by a slightly hacked  
 *	version of Richard Daveys easyreflections [3] written in PHP.
 *	
 *	The mouse wheel support is an implementation of Adomas Paltanavicius
 *	JavaScript mouse wheel code [4].
 *
 *	Thanks to Stephan Droste ImageFlow is now compatible with Safari 1.x.
 *
 *
 *	[1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
 *	[2] http://shoutbox.finnrudolph.de/
 *	[3] http://reflection.corephp.co.uk/v2.php
 *	[4] http://adomas.org/javascript-mouse-wheel/
 */


/* Configuration variables */
var conf_reflection_p = 0.5;         // Sets the height of the reflection in % of the source image 
var conf_focus = 4;                  // Sets the numbers of images on each side of the focussed one
var conf_slider_width =60;          // Sets the px width of the slider div
var conf_images_cursor = 'pointer';  // Sets the cursor type for all images default is 'default'
var conf_slider_cursor = 'default';  // Sets the slider cursor type: try "e-resize" default is 'default'

/* Id names used in the HTML */
var conf_imageflow = 'imageflow';    // Default is 'imageflow'
var conf_loading = 'loading';        // Default is 'loading'
var conf_images = 'images';          // Default is 'images'
var conf_captions = 'captions';      // Default is 'captions'
var conf_scrollbar = 'scrollbar';    // Default is 'scrollbar'
var conf_slider = 'slider';          // Default is 'slider'
/* Ajout emilie */
var conf_fleche_g ='fleche-g';
var conf_fleche_d ='fleche-d';
/*fin  Ajout emilie */
	/* Ajout emilie*/
	var cranOpacite = 20;
	var opacite =100;
	var sensOpacite = "d";
	var indexEnCours = 0;
	var onLoadOpacite = false;
	var onAScroller = false;
	var clic=false;
	/* Ajout emilie*/
	
/* Define global variables */
var caption_id = 0;
var new_caption_id = 0;
var current = 0;
var target = 0;
var mem_target = 0;
var timer = 0;
var array_images = new Array();
var new_slider_pos = 0;
var dragging = false;
var dragobject = null;
var dragx = 0;
var posx = 0;
var new_posx = 0;
var xstep = 150;


function step()
{
	switch (target < current-1 || target > current+1) 
	{
		case true:
			moveTo(current + (target-current)/3);
			window.setTimeout(step, 50);
			timer = 1;
			break;

		default:
			timer = 0;
			break;
	}
}

var tabDescription = new Array();
tabDescription[0]="1957 c'&eacute;tait...";
tabDescription[1]="Mais 1957 c'est aussi la naissance de SES &agrave; Drancy";
tabDescription[2]="SES d&eacute;marre son activit&eacute; par la fabrication de plaques min&eacute;ralogiques";
tabDescription[3]="Diversification vers le march&eacute; de la signalisation en plein essor";
tabDescription[4]="D&eacute;localisation en Touraine et ouverture de l'usine de Chambourg sur Indre";
tabDescription[5]="1&eacute;res gammes de portiques et potences en aluminium et de caissons lumineux";
tabDescription[6]="L'usine de Tours ouvre ses portes";
tabDescription[7]="1ers panneaux &agrave; messages variables";
tabDescription[8]="SES est le premier fabricant &agrave; mettre sur le march&eacute; mondial un panneau &agrave; messages variables alphanum&eacute;riques le &quot;SYLVIA&quot; qu'il prot&egrave;ge par un brevet";
tabDescription[9]="Ouverture de FDS pr&egrave;s de Boston aux U.S.A.";
tabDescription[10]="SES devient filiale de Colas, le leader mondial de la construction routi&egrave;re";
tabDescription[11]="SES est une des premi&egrave;res entreprises de signalisation &agrave; recevoir la certification  ISO 9001 version 1994";
tabDescription[12]="Acquisition de  la soci&eacute;t&eacute; ADEM dans l'Aisne (fabricant de signalisation fixe et de plaques &eacute;maill&eacute;es";
tabDescription[13]="SES est certifi&eacute;e ISO 9001 version 2000 ";
tabDescription[14]="2000 m&sup2; d'ateliers suppl&eacute;mentaires sont construits sur le site de production de Chambourg et de nouveaux locaux sur le site de Tours pour accueillir les Bureaux d'Etudes.";
tabDescription[15]="SES quitte le groupe Colas et redevient une soci&eacute;t&eacute; ind&eacute;pendante";
tabDescription[16]="SES f&ecirc;te son cinquanti&egrave;me anniversaire";
tabDescription[17]="La filiale am&eacute;ricaine FDS change d'identit&eacute; et devient SES America";
tabDescription[18]="Cr&eacute;ation de ACCES SIGNES sp&eacute;cialis&eacute;e dans les services li&eacute;s &agrave; la signalisation verticale et horizontale";
tabDescription[19]="SES lance Express Signal, la vente au comptoir de produits de signalisation et de s&eacute;curit&eacute; au sein de ses agences";
tabDescription[20]="2 000 m&sup2; d'ateliers suppl&eacute;mentaires sont en cours de construction sur le site de production de Chambourg sur Indre, dans le cadre de la  r&eacute;industrialisation compl&egrave;te du site";


var onGlide = false;

function glideTo(x, new_caption_id)
{
	
	/* Animate gliding to new x position */
	target = x;
	mem_target = x;
	onGlide =true;
	if (timer == 0)
	{
		if(clic==true)
		{
			
			clic=false;
		/*Ajout emilie */
		indexEnCours=caption_id*2;
		changeOpacite(indexEnCours);
		/*Ajout emilie */
		}
		else
		{
		/*Ajout emilie */
		indexEnCours=new_caption_id*2;
		changeOpacite2(indexEnCours);
		/*Ajout emilie */
		}
		window.setTimeout(step, 50);
		timer = 1;
		
	}
	
	/* Display new caption */
	caption_id = new_caption_id;
	//alert (new_caption_id);
	caption = img_div.childNodes.item(array_images[caption_id]).getAttribute('alt');
	if (caption == '') caption = '&nbsp;';
	//caption_div.innerHTML = caption  ;
	caption_div.innerHTML ="<span class='annee' >"+caption+"</span><br/>"+tabDescription[new_caption_id] ;//Changement emilie
	//alert(caption);
	/* Set scrollbar slider to new position */
	if (dragging == false)
	{
		new_slider_pos = (scrollbar_width * (-(x*100/((max-1)*xstep))) / 100) - new_posx;
		slider_div.style.marginLeft = (new_slider_pos - conf_slider_width) + 'px';
	}

}

function changeOpacite(indexEnCours)
{
	//alert(indexEnCours);
		var coteOpacite=1;
		max = img_div.childNodes.length;
		if(onLoadOpacite==true)
		{
			for (var index = 0; index < max; index++)
			{ 
				var image = img_div.childNodes.item(index);
			//alert(index);
					if (image.nodeType == 1)
					{
						
						//vers la droite
						if(sensOpacite=="d")
						{
								var indexDebut=indexEnCours-10;
								if(indexDebut<0){indexDebut=0;}
								var indexFin=indexEnCours+8;
								if(indexFin>max){indexFin=max};
								//On commence que 5 image avant le index à 100 et 4 apres
								if(index>=indexDebut && index<=indexFin)
								{
										if(document.all && !window.opera)
										{ 
											//Determine l'opacite (augmenter ou diminuer)
											opacite=image.style.filter.replace("alpha(opacity=","");
											opacite=parseInt(opacite.replace(");",""));
											//alert(opacite);
											if(opacite<=100 && coteOpacite==1)
											{
												if(opacite==100){coteOpacite=2;}
												
													opacite=opacite-cranOpacite;
											}
											else
											{
												opacite=opacite+cranOpacite;
											}
											//Change l'opacite
											//alert("opacite apres"+opacite);
											image.style.filter = 'alpha(opacity='+opacite+');' ;
										} 
										//FIREFOX
										else
										{ 
											//Determine l'opacite (augmenter ou diminuer)
											opacite=(image.style.opacity*100);
											if(opacite<=100 && coteOpacite==1)
											{
												if(opacite==100){coteOpacite=2;}
												
													opacite=opacite-cranOpacite;
											}
											else
											{
												opacite=opacite+cranOpacite;
											}
											//Change l'opacite
											image.style.opacity = opacite/100;
											//alert("opacite apres"+opacite);
										}
								}
						}
						//vers la gauche
						else
						{
							var indexDebut=indexEnCours-8;
							if(indexDebut<0){indexDebut=0;}
							var indexFin=indexEnCours+10;
							if(indexFin>max){indexFin=max};
							
							//On commence que 5 image avant le index à 100 et 4 apres
							if(index>=indexDebut && index<=indexFin)
							{
									if(document.all && !window.opera)
									{ 
										//Determine l'opacite (augmenter ou diminuer)
										opacite=image.style.filter.replace("alpha(opacity=","");
										opacite=parseInt(opacite.replace(");",""));
										//alert(opacite);
										if(opacite<=100 && coteOpacite==1)
										{
											opacite=opacite+cranOpacite;
											if(opacite==100){coteOpacite=2;}
										}
										else
										{
											opacite=opacite-cranOpacite;
										}
										//Change l'opacite
										//alert("opacite apres"+opacite);
										image.style.filter = 'alpha(opacity='+opacite+');' ;
									} 
									//FIREFOX
									else
									{ 
										//Determine l'opacite (augmenter ou diminuer)
										opacite=(image.style.opacity*100);
										if(opacite<=100 && coteOpacite==1)
										{
											opacite=opacite+cranOpacite;
											if(opacite==100){coteOpacite=2;}
										}
										else
										{
											opacite=opacite-cranOpacite;
										}
										//Change l'opacite
										image.style.opacity = opacite/100;
										//alert("opacite apres"+opacite);
									}
							}
						}
					}
			}
		}
		max = array_images.length;	
}

function changeOpacite2(indexEnCours)
{
	//alert("Image en 100 :"+indexEnCours); 
	var tabNbImgOpacite = new Array();
	tabNbImgOpacite[0]=80;
	tabNbImgOpacite[1]=60;
	tabNbImgOpacite[2]=40;
	tabNbImgOpacite[3]=20;
	tabNbImgOpacite[4]=0;
	
	//alert(indexEnCours);
		var coteOpacite=1;
		max = img_div.childNodes.length;
		
		if(onLoadOpacite==true)
		{
			//Détermination des nombres d'images d'avant et après
			var indexDebut=indexEnCours-8;
				if(indexDebut<=0)
				{
					var nbImgAvant=indexEnCours/2;
					indexDebut=0;
					opacite=tabNbImgOpacite[nbImgAvant];
				}
				else{opacite=0;}
				
			var indexFin=indexEnCours+8;
			
	
			
			if(indexFin>max){indexFin=max};
			
			//alert("indexEnCours"+indexEnCours+"-indexDebut"+indexDebut+"-indexFin"+indexFin);
			
			for (var index = 0; index < max; index++)
			{ 
				var image = img_div.childNodes.item(index);
			//alert(index);
					if (image.nodeType == 1)
					{			
							if(onGlide)
							{
								
								if(document.all && !window.opera)
										{ 
											image.style.filter = 'alpha(opacity=100);' ;
											
										} 
										//FIREFOX
										else
										{ 
											image.style.opacity = 1;
											
										}
							}
							else
							{
								//On commence que 5 image avant le index à 100 et 4 apres
								if(index>=indexDebut && index<=indexFin)
								{
										if(document.all && !window.opera)
										{ 
											//Determine l'opacite (augmenter ou diminuer)
											if(coteOpacite==1)
											{
												
												opacite=opacite+cranOpacite;
												if(opacite==100){coteOpacite=2;}
											}
											else
											{
												opacite=opacite-cranOpacite;
											}
											//Change l'opacite
											//alert("opacite apres"+opacite);
											//alert("img"+index+"-opacite"+opacite);
											image.style.filter = 'alpha(opacity='+opacite+');' ;
										} 
										//FIREFOX
										else
										{ 
											//Determine l'opacite (augmenter ou diminuer)
											if( coteOpacite==1)
											{
												opacite=opacite+cranOpacite;
												if(opacite==100){coteOpacite=2;}
											}
											else
											{
												opacite=opacite-cranOpacite;
											}
											//Change l'opacite
											image.style.opacity = opacite/100;
											//alert("opacite apres"+opacite);
										}
								}
								//sinon opacite à zero
								else
								{
									if(document.all && !window.opera)
										{ 
											image.style.filter = 'alpha(opacity=0);' ;
										} 
										//FIREFOX
										else
										{ 
											image.style.opacity = 0;
										}
								}
							}
					}
			}
		}
		max = array_images.length;	
}

function moveTo(x)
{
	current = x;
	var zIndex = max;
	
	/* Main loop */
	for (var index = 0; index < max; index++)
	{
		var image = img_div.childNodes.item(array_images[index]);
		var current_image = index * -xstep;

		/* Don't display images that are not conf_focussed */
		if ((current_image+max_conf_focus) < mem_target || (current_image-max_conf_focus) > mem_target)
		{
			image.style.visibility = 'hidden';
			image.style.display = 'none';
		}
		else 
		{
			var z = Math.sqrt(10000 + x * x) + 100;
			var xs = x / z * size + size;

			/* Still hide images until they are processed, but set display style to block */
			image.style.display = 'block';
			/* Process new image height and image width */
			var new_img_h = (image.h / image.w * image.pc) / z * size;
            
			switch ( new_img_h > max_height )
			{
				case false:
					var new_img_w = image.pc / z * size;
					break;

				default:
					new_img_h = max_height;
					var new_img_w = image.w * new_img_h / image.h;
					break;
			}
			/*var new_img_top = (images_width * 0.34 - new_img_h) + images_top + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p);*/
			var new_img_top = (images_width * 0.34 - new_img_h) + images_top + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p) - 170;

			/* Set new image properties */
			image.style.left = xs - (image.pc / 2) / z * size + images_left + 'px';
			if(new_img_w && new_img_h)
			{ 
				image.style.height = new_img_h + 'px'; 
				image.style.width = new_img_w + 'px'; 
				image.style.top = new_img_top + 'px';
			}
			image.style.visibility = 'visible';

			/* Set image layer through zIndex */
			switch ( x < 0 )
			{
				case true:
					zIndex++;
					break;

				default:
					zIndex = zIndex - 1;
					break;
			}
			
			/* Change zIndex and onclick function of the focussed image */
			switch ( image.i == caption_id )
			{
				case false:
					image.onclick = function() {glideTo(this.x_pos, this.i); }
					
					/*Ajout Emilie*/
					//alert(target+", "+new_caption_id);
					window.document.getElementById('fleche-d').onclick = function() { /*alert(new_caption_id);*/handle(-1); }
					window.document.getElementById('fleche-g').onclick = function() { /*alert(new_caption_id);*/handle(1); }
					/*Ajout Emilie*/
					
					
					break;

				default:
					zIndex = zIndex + 1;
					//image.onclick = function() { document.location = this.url; }
					image.onclick = function() { window.open(this.url); }
					
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += xstep;
	
	}
	
}

/* Main function */
function refresh(onload)
{
	/* Cache document objects in global variables */
	imageflow_div = document.getElementById(conf_imageflow);
	img_div = document.getElementById(conf_images);
	scrollbar_div = document.getElementById(conf_scrollbar);
	slider_div = document.getElementById(conf_slider);
	caption_div = document.getElementById(conf_captions);
	
	/*Ajout emilie*/
	fleche_g_div = document.getElementById(conf_fleche_g);
	fleche_d_div = document.getElementById(conf_fleche_d);
	/*Ajout Emilie*/

	/* Cache global variables, that only change on refresh */
	images_width = img_div.offsetWidth;
	/*images_top = imageflow_div.offsetTop;*/
	images_top = imageflow_div.offsetTop - 170;
	images_left = imageflow_div.offsetLeft;
	max_conf_focus = conf_focus * xstep;
	//size = images_width * 0.5;
size = images_width * 0.7;
	scrollbar_width = images_width * 0.61;
	conf_slider_width = conf_slider_width * 0.1;
	max_height = images_width * 0.51;

	/* Change imageflow div properties */
	imageflow_div.style.height = max_height + 'px';

	/* Change images div properties */
	img_div.style.height = images_width * 0.338 + 'px';

	/* Change captions div properties */
	caption_div.style.width = images_width + 'px';
	caption_div.style.marginTop = images_width * 0.15 + 'px';

	/* Change scrollbar div properties */
	scrollbar_div.style.marginTop = images_width * 0.02 + 'px';
	scrollbar_div.style.marginLeft = images_width * 0.15 + 'px';
	scrollbar_div.style.width = scrollbar_width  + 'px';
	
	/* Set slider attributes */
	slider_div.onmousedown = function () { dragstart(this); };
	
	
	slider_div.style.cursor = conf_slider_cursor;

	/* Cache EVERYTHING! */
	max = img_div.childNodes.length;
	var i = 0;

	for (var index = 0; index < max; index++)
	{ 
		var image = img_div.childNodes.item(index);
		//alert(image.nodeType);
		
		if (image.nodeType == 1)
		{
			array_images[i] = index;
			
			/* Set image onclick by adding i and x_pos as attributes! */
			image.onclick = function() { glideTo(this.x_pos, this.i); }
			
			image.x_pos = (-i * xstep);
			image.i = i;
			
			/* Add width and height as attributes ONLY once onload */
			if(onload == true)
			{
				image.w = image.width;
				image.h = image.height;
				/*Ajout emilie */
				
				if(document.all && !window.opera)
				{ 
					image.style.filter = 'alpha(opacity='+opacite+');' ;
				} 
				else
				{ 
					image.style.opacity = opacite/100;
				}
				if(opacite<=20)
					{
						opacite=0;
					}
				else
					{
					opacite=opacite-cranOpacite;
					}
				/*Ajout emilie */
			}
            
			/* Check source image format. Get image height minus reflection height! */
			switch ((image.w + 1) > (image.h / (conf_reflection_p + 1))) 
			{
				/* Landscape format */
				case true:
					image.pc = 118;
					break;

				/* Portrait and square format */
				default:
					image.pc = 100;
					break;
			}

			/* Set ondblclick event */
			image.url = image.getAttribute('longdesc');
			//image.ondblclick = function() { document.location = this.url; }
			image.ondblclick = function() { window.open(this.url); }

			/* Set image cursor type */
			image.style.cursor = conf_images_cursor;

			i++;
		}
	}
	max = array_images.length;

	/* Display images in current order */
	moveTo(current);
	glideTo(current, caption_id);
	scrollbar_div.style.width="418px";
	onLoadOpacite=true;
}

/* Show/hide element functions */
function show(id)
{
	var element = document.getElementById(id);
	element.style.visibility = 'visible';
}
function hide(id)
{
	var element = document.getElementById(id);
	element.style.visibility = 'hidden';
	element.style.display = 'none';
}

/* Hide loading bar, show content and initialize mouse event listening after loading */
window.onload = function()
{
	if(document.getElementById(conf_imageflow))
	{
		hide(conf_loading);
		refresh(true);
		show(conf_images);
		show(conf_scrollbar);
		initMouseWheel();
		initMouseDrag();
		//setTimeout("dragTest()", 5000);
	}
		function up(e)
		{
			if (!e) e = window.event;

			  if (navigator.userAgent.indexOf("Firefox") != -1) {
		            if (e.button == 0) {
                		onFaitquelqueChose()
		            } 
		        }
		        else {
		            if (e.button == 1) {
		               onFaitquelqueChose()
		            }
		        }
			dragstop();
		}


	
	document.onmouseup= up;

}


function onFaitquelqueChose()
{
	if (onGlide)
	{
		onGlide=false;
		//alert(caption_id);
		indexEnCours=caption_id*2;
		changeOpacite2(indexEnCours);
	}


}

/* Refresh ImageFlow on window resize */
window.onresize = function()
{
	if(document.getElementById(conf_imageflow)) refresh();
}

/* Fixes the back button issue */
window.onunload = function()
{
  document = null;
}


/* Handle the wheel angle change (delta) of the mouse wheel */
function handle(delta) {

	clic=true;
	var change = false;
	switch (delta > 0)
	{
		case true:
			if(caption_id >= 1)
			{
				sensOpacite = "g";
				target = target + xstep;
				new_caption_id = caption_id - 1;
				change = true;
				indexEnCours=indexEnCours-2;
			}
			break;

		default:
			if(caption_id < (max-1))
			{
				sensOpacite = "d";
				target = target - xstep;
				new_caption_id = caption_id + 1;
				change = true;
				indexEnCours=indexEnCours+2;
			}
			break;
	}
	
	/* Glide to next (mouse wheel down) / previous (mouse wheel up) image */
	if (change == true)
	{
		glideTo(target, new_caption_id);
		
		/*Ajout emilie */
		//indexEnCours=caption_id*2;
		//alert(indexEnCours);
		//changeOpacite(indexEnCours);
		/*Ajout emilie */
	}
	
	
}

/* Event handler for mouse wheel event */
function wheel(event)
{
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta)
	{
		delta = event.wheelDelta / 120;
	}
	else if (event.detail)
	{
		delta = -event.detail / 3;
	}
	if (delta) handle(delta);
	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

/* Initialize mouse wheel event listener */
function initMouseWheel()
{
	if(window.addEventListener) imageflow_div.addEventListener('DOMMouseScroll', wheel, false);
	imageflow_div.onmousewheel = wheel;
}

/* This function is called to drag an object (= slider div) */
function dragstart(element)
{
	dragobject = element;
	dragx = posx - dragobject.offsetLeft + new_slider_pos;
}

/* This function is called to stop dragging an object */
function dragstop()
{
	dragobject = null;
	dragging = false;
	
}

/* This function is called on mouse movement and moves an object (= slider div) on user action */
function drag(e)
{
	posx = document.all ? window.event.clientX : e.pageX;
	if(dragobject != null)
	{
		dragging = true;
		new_posx = (posx - dragx) + conf_slider_width;

		/* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */
		if(new_posx < ( - new_slider_pos)) new_posx = - new_slider_pos;
		if(new_posx > (scrollbar_width - new_slider_pos)) new_posx = scrollbar_width - new_slider_pos;
		
		var slider_pos = (new_posx + new_slider_pos);
		var step_width = slider_pos / ((scrollbar_width) / (max-1));
		var image_number = Math.round(step_width);
		var new_target = (image_number) * -xstep;
		var new_caption_id = image_number;

		dragobject.style.left = new_posx + 'px';
		
		glideTo(new_target, new_caption_id);
		onAScroller = true;
		
	}
}

/* Initialize mouse event listener */
function initMouseDrag()
{
	document.onmousemove = drag;
	document.onmouseup = dragstop;

	/* Avoid text and image selection while dragging  */
	document.onselectstart = function () 
	{
		if (dragging == true)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
}

function getKeyCode(event)
{
	event = event || window.event;
	return event.keyCode;
}

document.onkeydown = function(event)
{
	var charCode  = getKeyCode(event);
	switch (charCode)
	{
		/* Right arrow key */
		case 39:
			handle(-1);
			break;
		
		/* Left arrow key */
		case 37:
			handle(1);
			break;
	}
}

isAutoScroll = true;
function dragTest() {

    setTimeout("recurDrag('-1','1')", 0);
}

function recurDrag(position, direction) {

    if (isAutoScroll) {
        idContenuSlideEnCours = "";
        handle(position);

        if ((caption_id < (array_images.length - 1)) && (direction == '1')) {
            setTimeout("recurDrag('-1','1')", 2000);
        }
        else if ((caption_id >= (array_images.length - 1)) && (direction == '1')) {
            setTimeout("recurDrag('1','-1')", 2000);
        }
        else if ((direction == '-1') && (caption_id > 0)) {
            setTimeout("recurDrag('1','-1')", 2000);
        }
        else if ((direction == '-1') && (caption_id <= 0)) {
            setTimeout("recurDrag('-1','1')", 2000);
        } else {
            setTimeout("recurDrag('1','-1')", 2000);
        }
    }

}




