// namespaces
var dom = new Object();
var box = new Object();

// outils
dom = {
	addLoadEvent : function(func) {
		var oldonload = window.onload;
		if(typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if(oldonload) {oldonload();}
				func();
			}
		}
	},
	
	support : {
		'id' : typeof document.getElementById,
		'tag' : typeof document.getElementsByTagName,
		'el' : typeof document.createElement,
		'txt' : typeof document.createTextNode
	}
};

// Gestion des liens à l'impression
box.printURL = {
	datas : {
		'bodyClass' : 'liens',
		'coreID' : 'core',
		'urlClass' : 'printURL',
		'h3Text' : 'Adresses des liens externes au site',
		'lnkTests' : ['http', 'floatthatbox']
	},
	
	init : function() {
		if(dom.support.id == 'undefined' || dom.support.tag == 'undefined' || dom.support.el == 'undefined') {return;}
		var core = document.getElementById(box.printURL.datas.coreID);
		if(!core) {return;}
		var lks = core.getElementsByTagName('a');
		var div = document.createElement('div');
		div.className = box.printURL.datas.urlClass;
		var h3 = document.createElement('h3');
		h3.innerHTML = box.printURL.datas.h3Text;
		var ol = document.createElement('ol');
		var str = ''; 
		var href = '';
		var c = 0;
		
		for(var i = 0; i < lks.length; i++) {
			var href = lks[i].href;
			if(document.body.className == box.printURL.datas.bodyClass) {
				box.printURL.createInlineURL(lks[i]);
				continue;
			}
			if(href.indexOf(box.printURL.datas.lnkTests[0]) == -1 || href.indexOf(box.printURL.datas.lnkTests[1]) != -1) {continue;}
			if(i == 0) {
				c++;
				box.printURL.createListing(href, ol);
				box.printURL.createRef(lks[i], c);
			} else {
				c++;
				if(str.indexOf('['+href+']') != -1) {continue;}
				box.printURL.createListing(href, ol);
				box.printURL.createRef(lks[i], c);
			}
			str = str+'['+href+']';
		}
		
		if(c > 0) {
			div.appendChild(h3);
			div.appendChild(ol);
			core.appendChild(div);
		}
	},
	
	createInlineURL : function(lk) {
		var span = document.createElement('span');
		span.className = box.printURL.datas.urlClass;
		span.innerHTML = ' ('+lk.href+')';
		lk.parentNode.insertBefore(span, lk.nextSibling);
	},
	
	createListing : function(href, ol) {
		var li = document.createElement('li');
		li.innerHTML = href;
		ol.appendChild(li);
	},
	
	createRef : function(lk, c) {
		var ref = document.createElement('sup');
		ref.className = box.printURL.datas.urlClass;
		ref.innerHTML = '['+c+']';
		lk.parentNode.insertBefore(ref, lk.nextSibling);
	}
}

// Slider images sur fiches projet web
box.slider = {
	datas : {
		'sliderID' : 'slider',
		'controlID' : 'control',
		'itemID' : 'slide',
		'linkHref' : '#',
		'linkText' : 'Image ',
		'linkTitle' : 'Visuel n°',
		'imgInitialPos' : '0px',
		'activeClass' : 'actif',
		'activeItem' : 0,
		'animHeight' : 332,
		'animDecrease' : 10,
		'animDelay' : 25
	},
	
	init : function() {
		if(dom.support.id == 'undefined' || dom.support.tag == 'undefined' || dom.support.el == 'undefined') {return;}
		var slider = document.getElementById(box.slider.datas.sliderID);
		if(!slider) {return;}
		var img = slider.firstChild;
		var slides = Number(slider.className.match(/\d/));
		if(isNaN(slides) || slides < 2) {return;}
		box.slider.createControl(slider, img, slides);
	},
	
	createControl : function(slider, img, slides) {
		img.style.top = box.slider.datas.imgInitialPos;
		var ul = document.createElement('ul');
		ul.setAttribute('id', box.slider.datas.controlID);
		var lk = new Array();
		var li = new Array();
		for(var i = 0; i < slides; i++) {
			lk[i] = document.createElement('a');
			lk[i].setAttribute('href', box.slider.datas.linkHref);
			lk[i].setAttribute('title', box.slider.datas.linkTitle+(i+1));
			lk[i].innerHTML = box.slider.datas.linkText+(i+1);
			lk[i].nb = i;
			li[i] = document.createElement('li');
			li[i].setAttribute('id', box.slider.datas.itemID+(i+1));
			li[i].className = i == 0 ? box.slider.datas.activeClass : '';
			li[i].appendChild(lk[i]);
			ul.appendChild(li[i]);
			lk[i].onclick = function() {
				li[box.slider.datas.activeItem].className = '';
				li[this.nb].className = box.slider.datas.activeClass;
				box.slider.datas.activeItem = this.nb;
				img.finalY = - this.nb * box.slider.datas.animHeight;
				img.current = parseInt(img.style.top);
				box.slider.animate(img, box.slider.datas.animDecrease, box.slider.datas.animDelay);
				return false;
			};
		}
		slider.appendChild(ul);
	},
	
	animate : function(img, decrease, delay) {
		if(img.current < img.finalY) {
			var dist = Math.ceil(Math.abs((img.finalY - img.current) / decrease));
			img.current += dist;
		} else if(img.current > img.finalY) {
			var dist = Math.ceil(Math.abs((img.finalY - img.current) / decrease));
			img.current -= dist;
		} else {
			clearTimeout(img.timer);
		}
		
		img.style.top = img.current+'px';
		img.timer = setTimeout(function() {box.slider.animate(img, decrease, delay)}, delay);
	}
};

// Preview des paysages 2d/3d
box.thumbs = {
	datas : {
		'bodyClass' : 'paysages',
		'coreID' : 'core',
		'linkClass' : 'thumb',
		'linkClassActive' : 'thumb actif',
		'linkTextShow' : '[+]',
		'linkTextHide' : '[fermer]',
		'linkTitle' : 'Afficher la miniature',
		'loadPath' : '../load/css/bg/load.gif',
		'folderName' : 'thumbs/',
		'pattern' : /([a-z0-9-]+\.jpg)$/i,
		'activeThumb' : ''
	},
	
	init : function() {
		if(dom.support.id == 'undefined' || dom.support.tag == 'undefined' || dom.support.el == 'undefined') {return;}
		if(document.body.className != box.thumbs.datas.bodyClass) {return;}
		var core = document.getElementById(box.thumbs.datas.coreID);
		if(!core) {return;}
		box.thumbs.items = core.getElementsByTagName('li');
		if(box.thumbs.items.length < 1) {return;}
		box.thumbs.img = document.createElement('img');
		box.thumbs.img.setAttribute('src', box.thumbs.datas.loadPath);
		box.thumbs.createThumbs();
	},
	
	createThumbs : function() {
		for(var i = 0; i < box.thumbs.items.length; i++) {
			var o = box.thumbs.items[i];
			o.lk = document.createElement('a');
			o.lk.nb = i;
			o.lk.link = o.getElementsByTagName('a')[0];
			o.lk.setAttribute('href', o.lk.link.href.replace(box.thumbs.datas.pattern, box.thumbs.datas.folderName+'$1'));
			o.lk.setAttribute('title', box.thumbs.datas.linkTitle);
			o.lk.innerHTML = box.thumbs.datas.linkTextShow;
			o.lk.className = box.thumbs.datas.linkClass;
			o.appendChild(o.lk);
			
			o.lk.onclick = function() {
				if(typeof box.thumbs.active == 'object' && box.thumbs.active != this) {
					box.thumbs.active.innerHTML = box.thumbs.datas.linkTextShow;
					box.thumbs.active.className = box.thumbs.datas.linkClass;
					box.thumbs.active.setAttribute('title', box.thumbs.datas.linkTitle);
				}
				this.className = this.className == box.thumbs.datas.linkClass ? box.thumbs.datas.linkClassActive : box.thumbs.datas.linkClass;
				this.setAttribute('title', this.title == box.thumbs.datas.linkTitle ? '' : box.thumbs.datas.linkTitle);
				this.innerHTML = this.innerHTML == box.thumbs.datas.linkTextShow ? box.thumbs.datas.linkTextHide : box.thumbs.datas.linkTextShow;
				var id = this.href.substring(this.href.lastIndexOf('/')+1, this.href.lastIndexOf('.'));
				var img = document.getElementById(id);
				if(!img) {
					var dim = box.thumbs.items[this.nb].className.match(/\d{1,3}/g);
					var alt = this.link.innerHTML;
					box.thumbs.img.setAttribute('src', box.thumbs.datas.loadPath); // transitions
					box.thumbs.img.setAttribute('alt', alt);
					box.thumbs.img.setAttribute('src', this.href);
					box.thumbs.img.setAttribute('width', dim[0]);
					box.thumbs.img.setAttribute('height', dim[1]);
					box.thumbs.img.setAttribute('id', id);
					this.parentNode.appendChild(box.thumbs.img);
				} else {
					this.parentNode.removeChild(img);
				}
				box.thumbs.active = this;
				return false;
			};
		}
	}
};


// Gestion des préférences
box.preferences = {
	datas : {
		'menuID' : 'menu',
		'formID' : 'F_prefs',
		'lnkID' : 'F_liens',
		'imgID' : 'F_images',
		'propName' : 'gestionFenetres',
		'cookieName' : 'floatthatbox',
		'cookieDuration' : 365,
		'lnkTests' : ['http','floatthatbox'],
		'imgTests' : ['load/paysages/','thumbs'],
		'dynClass' : 'js',
		'itemClass' : 'preferences',
		'linkHref' : '/preferences/',
		'linlTitle' : 'Gérez votre navigation sur Float that Box!',
		'linkText' : 'Préférences',
		'informClass' : 'informing',
		'informText' : 'Vos préférences ont été enregistrées...'
	},
	
	init : function() {
		if(dom.support.id == 'undefined' || dom.support.tag == 'undefined' || dom.support.el == 'undefined') {return;}
		box.preferences.createLink();
		box.preferences.record();
		box.preferences.set();
	},
	
	createLink : function() {
		var menu = document.getElementById(box.preferences.datas.menuID);
		if(!menu) {return;}
		var items = menu.getElementsByTagName('li');
		var cible = items[items.length - 1];
		
		var lk = document.createElement('a');
		lk.setAttribute('href', box.preferences.datas.linkHref);
		lk.setAttribute('title', box.preferences.datas.linkTitle);
		lk.innerHTML = box.preferences.datas.linkText;
		
		var li = document.createElement('li');
		li.className = box.preferences.datas.itemClass;
		li.appendChild(lk);
		
		menu.className = box.preferences.datas.dynClass;
		cible.parentNode.insertBefore(li, cible);
	},
	
	record : function() {
		var form = document.getElementById(box.preferences.datas.formID);
		if(!form) {return;}
		box.preferences.items = form.elements[box.preferences.datas.propName];
		var s = document.createElement('strong');
		s.innerHTML = box.preferences.datas.informText;
		var p = document.createElement('p');
		p.setAttribute('tabIndex', -1);
		p.className = box.preferences.datas.informClass;
		p.appendChild(s);
		
		form.onsubmit = function() {
			var str = '';
			for(var i = 0; i < box.preferences.items.length; i++) {
				str += (box.preferences.items[i].checked == false) ? box.preferences.items[i].value+'0' : box.preferences.items[i].value+'1'; 
				if(i < box.preferences.items.length - 1) {str += ':';}
			}
			box.cookie.record(box.preferences.datas.cookieName, str, box.preferences.datas.cookieDuration);
			this.parentNode.insertBefore(p, this);
			p.focus();
			return false;
		};
	},
	
	set : function() {
		var values = box.cookie.read(box.preferences.datas.cookieName);
		if(values.length < 1) {return;}
		var lnk = document.getElementById(box.preferences.datas.lnkID);
		var img = document.getElementById(box.preferences.datas.imgID);
		var lks = document.getElementsByTagName('a');
		
		for(var i = 0; i < lks.length; i++) {
			var href = lks[i].getAttribute('href');
			if(values[0] == 'lnk1') {
				if(lnk) {lnk.setAttribute('checked', 'checked');}
				if(href.indexOf(box.preferences.datas.lnkTests[0]) != -1 && href.indexOf(box.preferences.datas.lnkTests[1]) == -1) {
					lks[i].onclick = function() {
						window.open(this.href);
						return false;
					}
				}
			}
			if(values[1] == 'img1') {
				if(img) {img.setAttribute('checked', 'checked');}
				if(href.indexOf(box.preferences.datas.imgTests[0]) != -1 && href.indexOf(box.preferences.datas.imgTests[1]) == -1) {
					lks[i].onclick = function() {
						window.open(this.href);
						return false;
					}
				}
			}
		}
	}
};

// Enregistrement/lecture cookie
box.cookie = {
	record : function(name, value, days) {
	  if (days) {
	    var date = new Date();
    	date.setTime(date.getTime()+(days*24*60*60*1000));
  	  var expires = '; expires='+date.toGMTString();
	  } else  {
			expires = '';
		}
	  document.cookie = name+'='+value+expires+'; path=/';
	},
	
	read : function(name) {
	  var cookie = document.cookie.split(';');
		for(var i = 0; i < cookie.length; i++) {
			if(cookie[i].indexOf(name) != -1) var str = cookie[i];
		}
		if(!str) {str = ''; return str;}
		var cut = str.indexOf('=')+1;
		str = str.substring(cut);
		var values = str.split(':');
	  return values;
	}
};

// Validation formulaire contact
box.form = {
	datas : {
		'formID' : 'F_contact',
		'fields' : {
			'F_nom' : {'test1' : 'vide', 'msg1' : '(requis)'},
			'F_email' : {'test1' : 'vide', 'msg1' : '(requis)', 'test2' : 'email', 'msg2' : '(format non valide)'},
			'F_sujet' : {'test1' : 'vide', 'msg1' : '(requis)'},
			'F_message' : {'test1' : 'vide', 'msg1' : '(requis)'}
		},
		'vide' : /^\s*$/,
		'email' : /^\s*[\w-]+(\.[\w-]+)*@([\w-]+\.)+[A-Z]{2,7}\s*$/i,
		'errorClass' : 'erreur',
		'informClass' : 'informing',
		'informText' : 'Le fomulaire contient au moins une erreur (champ omis ou non valide). Toute erreur est indiquée en italique et en blanc à côté du champ concerné. Merci de corriger.'
	},

	init : function() {
		if(dom.support.id == 'undefined' || dom.support.el == 'undefined') {return;}
		var f = document.getElementById(box.form.datas.formID);
		if(!f) {return;}
		box.form.checks(f.elements, 'direct');
		f.onsubmit = function() {
			box.form.valid = true;
			box.form.checks(this.elements, 'submit');
			if(!box.form.valid) {box.form.inform(this);}
			return box.form.valid;
		}
	},

	checks : function(o, m) {
		for(var t in box.form.datas.fields) {
			if(!o[t]) {continue;}
			m == 'submit' ? box.form.text(o[t]) : o[t].onchange = function() {box.form.text(this);};
		}
	},

	text : function(o) {
		var n = o.name;
		var v = o.value;
		if(box.form.datas.fields[n].test1 == 'vide') {
			var e1 = box.form.datas.vide.test(v);
			if(!e1) {
				if(box.form.datas.fields[n].test2) {
					var e2 = box.form.datas[box.form.datas.fields[n].test2].test(v);
					!e2 ? box.form.error(o, box.form.datas.fields[n].msg2, n) : box.form.flush(n);
				} else {
					box.form.flush(n);
				}
			} else {
				box.form.error(o, box.form.datas.fields[n].msg1, n);
			}
		} else {
			if(v.length != 0) {
				var e1 = box.form.datas[box.form.datas.fields[n].test1].test(v);
				!e1 ? box.form.error(o, box.form.datas.fields[n].msg1, n) : box.form.flush(n);
			} else {
				box.form.flush(n);
			}
		}
	},

	error : function(o, m, n) {
		box.form.valid = false;
		var id = 'msg'+n;
		var el = document.getElementById(id);
		if(el) {
			el.firstChild.nodeValue = ' '+m;
			el.className = box.form.datas.errorClass;
		} else {
			el = document.createElement('em');
			el.innerHTML = ' '+m;
			el.setAttribute('id', id);
			el.className = box.form.datas.errorClass;
			var p = box.form.get(o);
			p.appendChild(el);
		}
	},

	flush : function(n) {
		var id = 'msg'+n;
		var el = document.getElementById(id);
		if(el) {
			el.innerHTML = ' ';
			el.className = '';
		}
	},

	get : function(o) {
		while(o.previousSibling) {
			o = o.previousSibling;
			if(o.nodeType == 1 && o.nodeName.toLowerCase() == 'label') {break;}
		}
		return o;
	},

	inform : function(o) {
		var verif = document.getElementById('inform'+o.name);
		if(verif) {
			verif.focus();
			return;
		}
		var elt = document.createElement('p');
		var str = document.createElement('strong');
		str.innerHTML = box.form.datas.informText;
		elt.appendChild(str);
		elt.className = box.form.datas.informClass;
		elt.setAttribute('id','inform'+o.name);
		elt.setAttribute('tabIndex',-1);
		o.parentNode.insertBefore(elt,o);
		elt.focus();
	}
};

// Chargement des fonctions
dom.addLoadEvent(box.preferences.init);
dom.addLoadEvent(box.slider.init);
dom.addLoadEvent(box.thumbs.init);
dom.addLoadEvent(box.form.init);
dom.addLoadEvent(box.printURL.init);