var browserwidth = 100;
var browserheight = 100;
var actualLeft;
var actualRight;
var v;
var offset;
var offsetValue = 0.5;
var actualImage = 1;
var myFx ;
var box = null;
var infoSlider;
var firstview = true;
var maxclick = 4;
var infoClick = 0;

var myKeyboardEvents = null;
var dragEvent = null;

var images;
var z = 0;

var homeDatas =[];

window.onload = function(){
  addEvent_trick(document.body, 'keydown', keyDown);
  addEvent_trick(window, 'keydown', keyDown);
}

window.addEvent('domready', function(){	
	$('infos').setStyle('height','auto');
	infoSlider = new Fx.Slide('infos').hide();
	$('infos').addEvent('click',function(e){
		infoSlider.hide();
	});
	
	setMenu();
	setInteraction();
	myFx = new Fx.Tween('slider');
	
	//charger la bonne page.
	
	//page par default
	
	var url = (window.location.hash.split('#')[1] == undefined)?'':window.location.hash.split('#')[1];
	var stp = (url!='')?parseInt(url.split('&step=')[1]):0;
	if(url.split('&step=')[0]!=undefined && stp!=0){
		loadAndGoFullsize('php/content.php?switch=fullsize&'+url.split('&step=')[0],'slider',stp);
	}else if(url.split('&step=')[0]!=undefined && url.split('&step=')[0]!=''){
		loadThumb('php/content.php?switch=thumb&'+url.split('&step=')[0],'slider');
	}else if(url.split('&step=')[0] =='' && url.split('&step=')[1] == 0){
		
		loadThumb('php/content.php?switch=thumb','slider');
	}else{
		//homepage
		//loadThumb('php/content.php','slider');
		//loadThumb('php/content.php?switch=thumb','slider');
		//alert("homepage");
		
		//loadSpecialHome('php/content.php','slider');
		//loadAndGoFullsize('php/content.php?switch=fullsize','slider',1);
		loadHomepage();
	}
	
	//resizeWrappers(0);
	//resizeImages();
	//setInteraction();
	
	window.addEvent('resize', function(){ 
		resizeWrappers(1);
		resizeImages();
	}); 
	
});

function setInteraction(){
	//keyboard EVENTS
	
	myKeyboardEvents = new Keyboard({
		defaultEventType: 'keydown',
		events: {
			'right': handle_right,
			'left' : handle_left
		}
	});
	//dragging Event
	dragEvent = new Drag.Move('slider', {
		limit:{'y':[0,0]},
		onCancel:function(e){
			//for the click only
			handle_right();
			infoClick++;
			if(infoClick >= maxclick){
				infoSlider.hide();
			}
			if(firstview){
				infoSlider.toggle();
				firstview = false;
			}
			},
		onComplete: function(e){
			if(actualLeft+$('slider').getPosition().x <=0){
					//alert("image de droite");	
					if((actualRight+$('slider').getPosition().x) >= ((actualRight-actualLeft)/2) +offset || actualRight==(browserwidth*v)){
						move(-actualLeft,0);
					}else{
						move(-actualRight,1);
						actualLeft = actualRight;
						actualRight = actualRight+browserwidth;
					}
				}else{
					//alert("image de gauche");
					if((actualLeft+$('slider').getPosition().x) >= ((actualRight-actualLeft)/2)-offset && actualLeft!=0){
						move(-actualLeft+browserwidth,-1);
						actualRight = actualLeft;
						actualLeft = actualLeft-browserwidth;
					}else{
						move(-actualLeft,0);
					}
				}
			
			
		}
	});

}


function resizeWrappers(val){
	//val --->  pour la valeur du chargement qui ne tient pas compte du scroll invisible
	
	browserwidth = (val == 0)?$(document).getSize().x+15:$(document).getSize().x;
	//browserwidth = $(document).getSize().x;// 15 facteur non compris ?? scrollbar
	browserheight = $(document).getSize().y;
	
	
	
	offset = browserwidth*offsetValue;
	v=0;
	
	$$('.wrapp').each(function(item,index){
		item.setStyles({
			width:browserwidth,
			height:browserheight
			});
		v++;
		});
	
	actualLeft =(browserwidth*actualImage)-browserwidth;
	actualRight = browserwidth*actualImage;
	
	
	
	$('slider').setStyles({
			width:((browserwidth)*v)
	});	
	
	
	if(navigator.appName != 'Microsoft Internet Explorer'){
		
		//!!!!!!!!!    IE BUG !! pas de valeur negative
		$('slider').setPosition({
			x:(-(browserwidth*actualImage)+browserwidth)
		});
		
	}else{
		document.getElementById('slider').style.left = (-(browserwidth*actualImage)+browserwidth);
		}
}
	
function resizeImages(){
	marginTop = 0;
	nouvelle_hauteur = 0;
	nouvelle_largeur = 0;
	$$('.wrapp .elastic').each(function(item,index){
		_width = item.getStyle('width').toInt(); 
		_height = item.getStyle('height').toInt();
		if((browserwidth/browserheight) > (_width/_height)){
			//alert("on adapt la largeur");
			nouvelle_largeur = Math.round(( browserheight * _width )/_height);
			nouvelle_hauteur = browserheight;
			marginTop = 0;
			item.setStyles({
				'width':nouvelle_largeur,
				'height':browserheight,
				'margin-top':0
			});
		}
		
		if((browserheight/browserwidth)  > (_height/_width) ){
			//alert("on adapt la hauteur");
			nouvelle_hauteur = Math.round(( browserwidth * _height )/_width);
			nouvelle_largeur = browserwidth;
			marginTop = (browserheight-nouvelle_hauteur)/2;
			item.setStyles({
				'width':browserwidth,
				'height':nouvelle_hauteur,
				'margin-top':marginTop
			});
		}
		
		//alert(navigator.appName);
		
		if(navigator.appName != 'Microsoft Internet Explorer'){
			ns = item.nextElementSibling;
		}else{
			ns = item.nextSibling;
			}
		
		
		//alert("nextSib " +item.nextElementSibling.nextElementSibling);
		//legend
		if(ns!=null && ns.className !='loader' && ns!=undefined){
			if(navigator.appName != 'Microsoft Internet Explorer'){
				ns.setStyles({
						'right':(item.getPosition(item.parentNode).x),
						'top':marginTop+nouvelle_hauteur-ns.getStyle('height').toInt()-10
				});
			}else{
				ns.style.right = (item.getPosition(item.parentNode).x);
				ns.style.top = (marginTop+nouvelle_hauteur-ns.offsetHeight-10);
			}
		}
		
		// !!!!!!!!!!!  IE SECURE
		if(navigator.appName != 'Microsoft Internet Explorer'){
			nsNs = item.nextElementSibling.nextElementSibling;
		}else{
			nsNs = item.nextSibling.nextSibling;
			}
		
				
		if(ns != undefined){
		
			//loader
			if(nsNs!=null && nsNs!=undefined){
				if(navigator.appName != 'Microsoft Internet Explorer'){
					nsNs.setStyles({
							'right':(item.getPosition(item.parentNode).x+(nouvelle_largeur-128)/2),
							'top':(nouvelle_hauteur/2-(14/2))
					});
				}else{
					nsNs.style.right = (item.getPosition(item.parentNode).x+(nouvelle_largeur-128)/2);
					nsNs.style.top = (nouvelle_hauteur/2-(14/2));
				}
			}else if(ns.className =='loader'){
				if(navigator.appName != 'Microsoft Internet Explorer'){
					ns.setStyles({
						'right':(item.getPosition(item.parentNode).x+(nouvelle_largeur-128)/2),
						'top':((nouvelle_hauteur/2)-(14/2))
					});
				}else{
					ns.style.right = (item.getPosition(item.parentNode).x+(nouvelle_largeur-128)/2);
					ns.style.top = ((nouvelle_hauteur/2)-(14/2));
				}
			}
		
		}
		
		if(navigator.appName != 'Microsoft Internet Explorer'){
			ps = item.previousElementSibling;
		}else{
			ps = item.previousSibling;
			}
			
		//videoWrapper
		//alert(item.previousElementSibling);
		if(ps != null && ps.className !='loader' && ps!=undefined){
			if(navigator.appName != 'Microsoft Internet Explorer'){
				ps.setStyles({
						'top':marginTop,
						'height':nouvelle_hauteur-50
				});
			}else{
				ps.style.top = marginTop;
				ps.style.height = nouvelle_hauteur-50;
				}
		}
		
	});
}


function loadThumb(address,div){
	var options = {
			url: address, 	
			method : 'get', 
			update: $(div),
			evalScripts: true,					
			onRequest: function() {	
				$(div).innerHTML='<img src="gfx/loadinfo.gif" width="16px" height="16px" border="0" alt="loading" style="width:16px;height:16px;margin:5px;">';
			},									
			onSuccess: function() {	
				$('slider').setStyles({
					width:browserwidth
				});	
				var url = (address.split('&')[1] == undefined)?'':address.split('&')[1];
				window.location.hash = url+'&step=0';
				myKeyboardEvents.deactivate();	
				dragEvent.detach();
				/*
				$$('#thumbnail img').each(function(item,index){
					item.addEvent('mouseover',function(e){
						this.setTransform('rotate(0deg)');
					});	
					item.addEvent('mouseout',function(e){
						this.setTransform('rotate('+Number.random(-8,8)+'deg)');
					});
				})
				*/
			}
		};									
	var monObjetAjax= new Request.HTML(options);
	monObjetAjax.send();
}

function loadSpecialHome(address,div){
	var options = {
			url: address, 	
			method : 'get', 
			update: $(div),
			evalScripts: true,					
			onRequest: function() {	
				$(div).innerHTML='<img src="gfx/loadinfo.gif" width="16px" height="16px" border="0" alt="loading" style="width:16px;height:16px;margin:5px;">';
			},									
			onSuccess: function() {	
				
				$('slider').setStyles({
					width:browserwidth
				});
				
				myKeyboardEvents.deactivate();	
				dragEvent.detach();
				//resizeWrappers(0);
			}
		};									
	var monObjetAjax= new Request.HTML(options);
	monObjetAjax.send();
}



function loadAndGoFullsize(address,div,step){
	var options = {
			url: address, 	
			method : 'get', 
			update: $(div),
			evalScripts: true,					
			onRequest: function() {	
				resetPosition(div,1);
				$(div).innerHTML='<img src="gfx/loadinfo.gif" width="16px" height="16px" border="0" alt="loading" style="width:16px;height:16px;margin:5px;">';
			},									
			onSuccess: function() {	
				resizeWrappers(0);
				resizeImages();	
				resetPosition(div,step);
				var url = (address.split('&')[1] == undefined)?'':address.split('&')[1];
				window.location.hash = url+'&step='+step;	
				myKeyboardEvents.activate();
				dragEvent.attach();
				loadImage((step-1));
				loadImage((step));
			}
		};									
	var monObjetAjax= new Request.HTML(options);
	monObjetAjax.send();
}

function setMenu(){
	new Fx.Accordion($('accordeon'), '#accordeon h2', '#accordeon .content',{
		display:-1,
		alwaysHide: true,
		opacity:true
		});
	$$('#accordeon .menuClick').each(function(item,index){
		item.addEvent('click',function(e){
			e.stop();
			loadAndGoFullsize(this.href,'slider',1);
		});
	});	
	
	$$('#accordeon .content').each(function(item,index){
		/*
		if(item.firstChild.type == undefined){
			el = item.firstChild;
			for(var i in el){
				alert(i+" / "+el[i]);
			}
		}
		*/
		//alert(item.firstChild.tagName);
		if(item.firstChild.tagName == 'DIV'){
			item.setStyles({
				width:'300px'	
				});
			}
	});	
	
	$$('#icons img').each(function(item,index){
		item.addEvent('click', function(e){
			e.stop();
			switch(this.alt){
				case "fullsize":
					//resetPosition('slider');
					var url = (window.location.hash.split('#')[1] == undefined)?'':window.location.hash.split('#')[1];
					loadAndGoFullsize('php/content.php?switch=fullsize&'+url,'slider',1);
				break;
				case "thumb":
					resetPosition('slider',1);
					var url = (window.location.hash.split('#')[1] == undefined)?'':window.location.hash.split('#')[1];
					loadThumb('php/content.php?switch=thumb&'+url,'slider');
				break;
				case "info":
					//openFacebox('php/info.php');
					infoSlider.toggle();
					firstview = false;
				break	
			}	
		});	
	});
}

function resetPosition(div,position){
	actualImage =position;
	actualLeft = browserwidth*(actualImage-1);
	actualRight = browserwidth*actualImage;
	
	//alert(navigator.appName);
	
	if(navigator.appName != 'Microsoft Internet Explorer'){
	//!!!!!!!!!! BUG EXPLORER !!
	
		$(div).setPosition({
			x:-actualLeft
		});
	
	}else{
		document.getElementById('slider').style.left = -actualLeft;
		}
}

function move(left,position){
	myFx.start('left',left);
	actualImage+=position;
	//alert(actualImage);
	window.location.hash = window.location.hash.split('#')[1].split('&')[0]+'&step='+actualImage;
	loadImage((actualImage-1));
	loadImage((actualImage));
}
	
function handle_right(e){
	//alert("touched right");
	if(actualRight!=(browserwidth*v)){
		move(-actualRight,1);
		actualLeft = actualRight;
		actualRight = actualRight+browserwidth;
	}else{
		myFx.start('left', -(actualLeft+50), -actualLeft);
	}	
}
function handle_left(e){
	//alert("touched left");
	if(actualLeft!=0){
		move(-actualLeft+browserwidth,-1);
		actualRight = actualLeft;
		actualLeft = actualLeft-browserwidth;
	}else{
		myFx.start('left', 50, 0);
	}
}
function openFacebox(address)
{
	if(box!=null){box.fastclose();}
	box = new Facebox({
		title:'Navigation help',
		url: address,
		ajaxDelay: 400,
		cancelValue: 'Ok',
		cancelFunction: function(){
			box.close();
			box = null;
		},
		height:120
	});
	box.show();
}

function setPos(posx,posy,width,height,depth,img){
	if(width!=0 && height!=0){
		img.setStyles({'width':width,'height':height});
	}
	img.parentNode.setStyles({'z-index':depth});
	img.parentNode.setPosition({x:posx, y:posy});
	if(depth>z){
		z=depth;
	}
}

function setPos2(img,index){
	if(parseInt(homeDatas[index][0])!=0 && parseInt(homeDatas[index][1])!=0){
		img.setStyles({'width':parseInt(homeDatas[index][0]),'height':parseInt(homeDatas[index][1])});
	}
	img.setStyles({'z-index':homeDatas[index][4]});
	img.setPosition({x:homeDatas[index][2],y:homeDatas[index][3]});
}

function loadImage(i){
	if($('wrapper_'+i)!=null){
		if("undefined" !== typeof(images[i]) && $('wrapper_'+i).getElements('img').getProperty('alt') == 'img_thumb'){
			new Asset.image(images[i], {
				onload: function(){
					if($('wrapper_'+i) != undefined){
							$('wrapper_'+i).getElements('img').setProperty('src',images[i]);
							$('wrapper_'+i).getElements('img').setProperty('alt','img_full');
							$('loader_'+i).setStyles({'backgroundImage':'none'});
					}
				},
				onComplete: function(){
						
				},
				onerror: function(){
				}
			});
		} 
	}
}

//trick to prevent the default arrow usage

function addEvent_trick(obj, evType, fn){
  if(obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
  }else if(obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  }
}

function keyDown(e){
  var ev = e||event;
  var key = ev.which||ev.keyCode;
  var esc = 0;

  switch(key){
  case 37: // left
  case 38: // up
  case 39: // right
  case 40: // down
     esc = 1;
  break;
  }
  if(esc && ev.preventDefault){
    ev.preventDefault();
  }
  return esc;
}
