/**
 *	Onload function
 */
function openHash()
{
	hash = window.location.hash;

	if (hash != '') {
		hash.open(hash);
	} else {
		openUp('post', 'accueil');
	}
}

/**
 *	File to handle hashing of the url.
 */
String.prototype.toHash = function (what)
{
	// this.toString() MANDATORY... yay, on a String object...
	switch (this.toString()) {
		case 'post' :
			hash = what;
			break;
			
		case 'gold' :
			hash = this;
			break;
			
		case 'test' :
			hash = 'test';
			break;
		
		case 'infos' :
			if (what == '0') {
				hash = 'info';
			} else {
				hash = 'informations';
			}
			break;
		
		case 'camerindien' :
			switch (what) {
				case '1' :
					hash = this + ';actuel';
					break;
				case '0' : 
					hash = this + ';presentation';
					break;
				case '-1' :
					hash = this + ';old';
					break;
			}
			break;
			
		default : hash = this + ';' + what;
	}

	return hash;
}

String.prototype.fromHash = function (what)
{
	switch (what) {
		case 'camerindien' :
			switch(this) {
				case 'actuel' :
					which = '1';
					break;
				case 'presentation' : 
					which = '0';
					break;
				case 'old' :
					which = '-1';
					break;
			}
			break;
		case 'infos' :
			if (what == 'info') {
				hash = '1';
			} else {
				hash = '0';
			}
			break;
			
		default : which = this;
	}
	
	return which;
}

/**
 *	Opens a page from a hash
 */
String.prototype.open = function ()
{
	hash  = this.replace('#', '');
	whose = hash.split(';');
	
	switch (whose.length) {
		case 1 :
			switch (hash) {
				case 'gold' :
					openUp(hash, '');
					break;
					
				case 'info' :
					openUp('infos', 0);
					break;
					
				case 'informations' :
					openUp('infos', 1);
					break;
					
				default : 
					openUp('post', hash);
			}
			break;
			
		case 2 :
			openUp(whose[0], whose[1].fromHash(whose[0]));
			break;
				
		default : alert('Error in String.open(), wrong hash.');
	}
}
function Carrousel (pics,carrous) {
	//**Properties***********************
	this.top=pics.length-1;
	
	//~~Images props
	this.pImg=new Image();
	this.cImg=new Image();
	this.nImg=new Image();
	
	//**Methods**************************
	//~~pseudo constructor
	this.make=function () {
		this.pImg.src=pics[prev(this.pos)].href.replace('@','');
		this.cImg.src=pics[this.pos].href.replace('@','');
		this.nImg.src=pics[next(this.pos)].href.replace('@','');
		
		this.pImg.ready=false;
		this.nImg.ready=false;
		
		carrous.appendChild(this.pImg);
		carrous.appendChild(this.cImg);
		carrous.appendChild(this.nImg);
		
		this.pImg.onload=function () { car.pImg.ready=true; }
		this.nImg.onload=function () { car.nImg.ready=true; }
	};
	
	//~~Mvt and all
	var gauche=-908;
//	var automove=true;
	var finished=true;
	
	this.move=function (i) {
		if (this.nImg.ready && this.pImg.ready && finished) {
			this.slide(i);
		}
	};
	
	this.slide=function (i) {
		cpt=-30;
		finished=false;
		inter = setInterval(function () { glide(i); },30);
	};
	
	this.auto=function (l) {
		if (l==0) {
			clearInterval(auto);
		} else {
			this.move(1);
		}
	};
	
	//**Inner functions******************
	function prev (p) {
		if (p-1<0) {
			p=car.top;
		} else {
			p--;
		}
		
		return p;
	};
	
	function next (p) {
		if (p>=car.top) {
			p=0;
		} else {
			p++;
		}
		
		return p;
	};
	
	//--Gliding !
	function glide (sens) {
		var cur=gauche % 900;

		if (gauche<=-1815 || gauche>=-1) {
			clearInterval(inter);
			gauche=-908;

			if (sens==1) {
				car.pos=next(car.pos);
			} else {
				car.pos=prev(car.pos);
			}
			
			finished=true;
			car.make();
			carrous.style.left='-908px';
		} else {
			//~~~~Building a gaussian curve
			var t=Math.pow((cpt/10),4)/5.6;
			var m=(Math.exp(-t)/(Math.sqrt(2*Math.PI)));

			m=Math.round(m*80);
			
			//~~~~Minimum movement.
			if (m<1) {
				m=1;
			}
			/*
			//~~~~Setting a 5 step near the end while moving left
			if (m>5 && -cur>900) {
				m=908+cur;
			}
			//~~~~Setting a 5 step near the end while moving right
			if (m>5 && -cur<20) {
				m=20+cur;
			}
			*/
			if (sens==1) {
				gauche=gauche-m;
				carrous.style.left=gauche+'px';
			} 
		
			if (sens==-1) {
				gauche=gauche+m;
				carrous.style.left=gauche+'px';
			}
		
			cpt++;
		}
	};
}
//--Showing down functions
//-------------
//----Dropdown
function showDown(which,what) {
	var head = document.getElementById(which+'_head');
	var list = document.getElementById(which+'_list');

	clearInterval(list.timer);

	if (what==1) {
		clearTimeout(head.timer);
		
		if (list.maxh && list.maxh<=list.offsetHeight) { 
			return;
		} else if (!list.maxh) {
			list.style.display='block';
			list.style.height ='auto';
			list.maxh=list.offsetHeight;
			list.style.height ='0px';
		}
				
		list.style.display='block';
		list.timer = setInterval(function(){ slideDown(list,1); },20);
	} else {
		head.timer = setTimeout(function() { dCollapse(list); },50);
	}
}

//----Down collapsing
function dCollapse (list) {
	list.timer = setInterval(function () { slideDown(list,-1); },20);
}

//----Down Hiding
function keep(id) {
	var head = document.getElementById(id+'_head');
	var list = document.getElementById(id+'_list');
	
	clearTimeout(head.timer);
	clearInterval(list.timer);
	
	if (list.offsetHeight < list.maxh) {
		list.timer = setInterval(function () { slideDown(list,1);},20);
	}
}

//----Down sliding
function slideDown (list,x) {
	var curH = list.offsetHeight;
	var dist;
	
	if (x==1) {
		dist=Math.round((list.maxh - curH) / 10);
	} else {
		dist=Math.round(curH / 10);
	}
	
	if (dist<=1 && x==1) {
		dist=1;
	}
	
	list.style.height =curH + (dist*x) + 'px';
	list.style.opacity=(curH/list.maxh);
	
	if ((curH < 5 && x!=1 ) || (curH > (list.maxh -2) && x==1)) {
	
		if (x!=1) {
			list.style.display='none';
		}
	
		clearInterval(list.timer);
	}
}
function count () {
	var cpt =document.getElementById('rest');
	var form=document.getElementById('form');
	var text=form.com.value;
	var lgth=text.length;
	var lim =1000;
	
	if (lgth > lim) {
		form.com.value=text.substring(0,lim);
		cpt.innerHTML=0;
		return;
	} else {
		cpt.innerHTML=(1000-lgth);
	}
}
String.prototype.lien=function () {
	return this.replace('/thbs/','/');  //removes /thbs/
}

function Diapo() {
	var self=this;
	/************************************
	DOM oriented creation of the diaporama
	************************************/
	//--Nodes
	//---------
	this.bg=document.createElement('div');
	this.bg.id='bgd';
	
	this.div=document.createElement('div');
	this.div.id='dimg';
	this.div.style.height=((window.innerHeight) ? window.innerHeight : document.body.clientHeight)-40+'px';
	this.div.style.width=((window.innerWidth) ? window.innerWidth : document.body.clientWidth)-40+'px';
	
	this.p=document.createElement('p');
	this.p.id='diapop';
	
	this.cmt=document.createElement('p');
	this.cmt.id='cmt';
	
	//---------
	//--Arrows
	//---------
	//----Left
	this.left=new Image();
	
	this.left.src ='img/arr_left.png';
	this.left.id  ='diapo_left';
	this.left.setAttribute('onclick','diapo.prev()'); //TODO
	//----Right
	this.right=new Image();
	
	this.right.src ='img/arr_right.png';
	this.right.id  ='diapo_right';
	this.right.setAttribute('onclick','diapo.next()'); //TODO
	
	//**Other properties of object:Diapo*
	this.diapo=document.getElementById('diapos').getElementsByTagName('img');
	this.top=this.diapo.length-1;

	/************************************
	************** Methods **************
	************************************/
	//---------
	//--Pseudo constructor
	//---------
	this.full=function (img,i) {
		car.auto(0);
		this.pos=i;
		
		document.body.appendChild(this.bg);
		this.bg.appendChild(this.div);
		this.build();

		//**Adding <p> containg arrows and comments
		this.div.appendChild(this.p);
		
		this.div.appendChild(this.left);
		this.div.appendChild(this.right);
	};
	//---------
	//--Pseudo destructor
	//---------
	this.close=function () {
		document.body.removeChild(this.bg);
	};
	//---------
	//--Creates images
	//---------
	this.build=function () {
		var img=this.diapo[this.pos];
		
		//**Trick to create a new div when diaporama is not active
		try {
			this.div.removeChild(this.current);
			this.current=new Image();
			this.div.insertBefore(this.current,this.p);
		} catch (e) {
			this.current=new Image();
			this.div.appendChild(this.current);
		}

		//**Comments are stored in a hidden div using the same organisation as images
		this.p.innerHTML='<span onclick="diapo.close();" id="close">Close</span><br/>'; //TODO
		this.p.innerHTML+=document.getElementById('cmt').children[this.pos].innerHTML;
		
		this.current.id ='current';
		this.current.alt=img.alt;
		this.current.src=img.src.lien();

		this.ready();
	};
	//---------
	//--Avoiding unloaded bad fetching of properties
	//---------
	this.ready=function () {
		this.current.onload=function () {
			if (self.current.height<20) {
				var tag = new Date().getTime();
			
				self.current.src=self.current.src+'?'+tag;
				self.ready();
				return;
			}
		
			self.cpt=1;
			self.inter=setInterval(function () { self.spawn(); },1);
		}
		//this.fetch();
	};
	//---------
	//--Fetches comments associated in DB /sigh
	//---------
	this.fetch=function () {
		var xhttp = new XMLHttpRequest;
		
		var img		= this.current;
		
		var folder	= img.src.slice(img.src.indexOf('diapos/')+7,img.src.lastIndexOf('/'));
		var nom		= img.src.slice(img.src.lastIndexOf('/')+1);
		var req		= 'folder='+encodeURIComponent(folder)+'&img='+encodeURIComponent(nom);
		
		xhttp.onreadystatechange=function () {
			if (xhttp.readyState==4 && xhttp.status==200) {
				self.p.innerHTML=xhttp.responseText;
			}
		}
	
		xhttp.open('POST','page/diapo_comment.php',true);
		xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		xhttp.send(req);
	};
	//---------
	//--Previous
	//---------
	this.prev=function () {
		if (this.pos-1<0) {
			this.pos=this.top;
		} else {
			this.pos--;
		}
		
		this.build();		

	};
	//---------
	//--Next
	//---------
	this.next=function () {
		if (this.pos+1>this.top) {
			this.pos=0;
		} else {
			this.pos++;
		}
		
		this.build();
	};
	//---------
	//--Fading
	//---------
	this.spawn=function () {
		if (this.current.style.opacity>=1) {
			clearInterval(this.inter);
			this.current.style.opacity=1;
		} else {
			this.current.style.opacity=Math.sqrt(this.cpt/20);
			this.cpt++;
		}
	};
}
function openUp(which, what) {
	var xhttp= new XMLHttpRequest;
	var show = document.getElementById('show');
	var css	 = document.getElementById('style');
	var top  = document.getElementById('top');

	show.innerHTML='<img src="img/ROND.gif" alt="Loading..." id="loading" />';
	
	xhttp.onreadystatechange = function () {
		if (xhttp.readyState==4 && xhttp.status==200) {
			show.innerHTML=xhttp.responseText;
			
			//**Loading custom style*****
			css.href='styles/'+which+'.css';
			
			//**Hiding/showing top link**
			if (show.offsetHeight>1000) {
				top.style.display='inline';
			} else {
				top.style.display='none';
			}
			
			window.location.hash = which.toHash(what);
			
			//**Various pending functions
			w8();
			testMel();
		} else if (xhttp.status==404) {
			show404();
		}
	}
	
	if (which=='') {
		which='test';
	}
	
	xhttp.open('GET','page/'+which+'.php?q='+what,true);
	xhttp.send();
}
//-------------
//--404 not found
//-------------
function show404() {
	var xhttp= new XMLHttpRequest;
	var show = document.getElementById('show');

	xhttp.onreadystatechange = function () {
		if (xhttp.readyState==4 && xhttp.status==200) {
			show.innerHTML=xhttp.responseText;
		}
	}
	
	xhttp.open('GET','page/e404.php',true);
	xhttp.send();
}
//-------------
//--Diaporama creating
//-------------
function opDiapo(which) {
	var xhttp= new XMLHttpRequest;
	var show = document.getElementById('show');
	var css	 = document.getElementById('style');
	
	show.innerHTML='<img src="img/ROND.gif" alt="Loading..." id="loading" />';

	xhttp.onreadystatechange = function () {
		if (xhttp.readyState==4 && xhttp.status==200) {
			show.innerHTML=xhttp.responseText;
			css.href='styles/diapo.css';
			diapo=new Diapo();
			
			//var thbs=document.getElementById('diapos').getElementsByTagName('img');
			
		}
	}
	
	xhttp.open('GET','page/diapo.php?p='+which,true);
	xhttp.send();
}
//-------------
//--Images resizing
//-------------
//----Have to wait for images to be loaded
function w8 () {
	var img=document.getElementById('show').getElementsByTagName('img');
	
	if (img.length>0) {
		img[img.length-1].onload=testImg; //reference to function :/
	}
}

//----Resizing to desired size
function resize(obj,size) {
	if (obj.width==690) {
		obj.style.width=size+'px';
	} else {
		obj.style.width='690px';
	}
}

//----Setting onclick event.
function testImg () {
	var img=document.getElementById('show').getElementsByTagName('img');
	
	for (i in img) {
		if (img[i] && img[i].width>690) {
			img[i].className+=' big';
			img[i].setAttribute('onclick','resize(this,'+img[i].width+')');
			img[i].style.width='690px';
		}
	}
}

//-------------	
//--Function to hide mails from bots
//-------------
function testMel() {
	var mel =/mel/gi; //regexp

	for (x=0;x<document.getElementsByTagName('span').length;x++) {

		if (mel.test(document.getElementsByTagName('span')[x].className)) {
			var a  =document.getElementsByTagName('span')[x];
			var enc=a.className.split(' ');
			var to ='';
			var who='';
			
			for (i=0;i<enc[1].length;i+=3) {
				var ch=enc[1].substr(i,3);
				ch=ch.replace('!','');
				
				to+='&#'+(ch-i)+';';
			}
			
			for (j=0;j<enc[2].length;j+=3) {
				var ca=enc[2].substr(j,3);
				ca=ca.replace('!','');
				
				who+='&#'+(ca-j)+';';
			}

			a.innerHTML='<a href="mailto:'+to+'">'+who+'</a>';
		}
	}
}

//-------------
//--Function showing images in big
//-------------
//----Display
function grande(nom) {
	var div=document.createElement('div');
	var blk=document.createElement('div');
	var img=new Image();
	
	img.src='pics/'+nom;
	div.appendChild(blk);
	blk.appendChild(img);
	div.id='bgd';
	
	document.body.appendChild(div);
	
	div.onclick=function () {
		document.body.removeChild(div);
	}
}
function vignette(node, way)
{
	if (way == 1) {
		onode = node.nextSibling;
	} else {
		onode = node.previousSibling;
	}
	
	while (onode) {
		if (onode.nodeType == 1) {
			otarget=onode;
			break;
		}
		
		if (way == 1) {
			onode = node.nextSibling;
		} else {
			onode = node.previousSibling;
		}
	}
	
	node.style.display  = 'none';
	onode.style.display = 'block';
}

