/***************************************************************************************************************************************************
 * LAYER
 * @class : Layer
 * @depends: none
 */

if(typeof Layer !== 'undefined') {
	throw new Error("La variable Layer existe deja.");
}

var Layer = function(oObj) {
	oObj = oObj || {};
	this.layer = this.bkgLayer = this.bkgContentLayer = this.showCtrl = this.hideCtrl = null;
	this.display = false;
	this.contentLayer = oObj.content || '';
	this.top = this.left = 0;
	this.width = oObj.width || 'auto';
	this.height = oObj.height || 'auto';
	this.opacity = oObj.opacity || .8;
	this.isDisplayOnIE = (typeof window.attachEvent !== 'undefined');
	this.isDisplayOnIE6 = (typeof window.attachEvent !== 'undefined' && typeof XMLHttpRequest === 'undefined');
};

if(typeof Layer['extends'] === 'undefined') {
	Layer['extends'] = function(oExtend) {
		if(typeof oExtend !== 'object') {
			throw new Error("Le layer ne peut etre etendu qu'avec un objet.");
		}
		for(var sProp in oExtend) {
			if(oExtend.hasOwnProperty(sProp) && typeof Layer.prototype[sProp] === 'undefined') {
				Layer.prototype[sProp] = oExtend[sProp];
			}
		}
		return true;
	};
}

Layer['extends']({

	set: function(oCont) {
		if(!oCont) {
			throw new Error("Le conteneur du layer est indefini.");
		}
		this.top = this.height == 'auto' ?
			'auto':
			(this.isDisplayOnIE6 ? document.documentElement.scrollTop : 0) + (
				window.innerHeight ?
					window.innerHeight:
					document.documentElement.clientHeight
			) / 2 - this.height / 2;
		this.left = this.width == 'auto' ?
			'auto':
			(document.body.offsetWidth / 2 - this.width / 2);
		this.layer = [
			'<div id="layer" style="width:', document.documentElement.scrollWidth + 'px',
			';height:', document.documentElement.scrollHeight + 'px',
			';"><div class="bkgLayer" style="width:', document.documentElement.scrollWidth + 'px',
			'; height:', document.documentElement.scrollHeight + 'px',
			'; opacity:', this.opacity,
			'; _filter:alpha(opacity=', this.opacity * 100,
			');"></div><div class="bkgContentLayer" style="width:', this.width == 'auto' ? 'auto': (this.width + 'px'),
			';height:', this.height == 'auto' ? 'auto': (this.height + 'px'),
			';top:', (this.top > 0 ? this.top : 0) + 'px',
			';left:', (this.left > 0 ? this.left : 0) + 'px',
			';"><span class="tlcLayer"></span><span class="trcLayer"></span><div class="contentLayer"><p class="hideCtrlLayer"><a href="#" id="hideCtrlLayer"><span>Fermer</span></a></p>', this.contentLayer,
			'</div><span class="blcLayer"></span><span class="brcLayer"></span></div></div>'
		].join('');
		oCont.innerHTML += this.layer;
		this.layer = document.getElementById('layer');
		var _oThat = this;
		this.isDisplayOnIE6 ? setTimeout(function() { _oThat.setSize(); }, 50): this.setSize();
		return true;
	},

	setSize: function() {
		if(this.layer) {
			this.bkgLayer = this.layer.getElementsByTagName('div')[0];
			this.bkgContentLayer = this.layer.getElementsByTagName('div')[1];
			this.contentLayer = this.bkgContentLayer.getElementsByTagName('div')[0];
			if(!(this.bkgLayer && this.bkgContentLayer && this.contentLayer)) {
				throw new Error("Un des elements du layer est indefini.");
			}
			this.bkgLayer.style.top = 0;
			this.bkgLayer.style.left = 0;
			this.bkgLayer.style.width = document.documentElement.offsetWidth + 'px';
			this.bkgLayer.style.height = document.documentElement.scrollHeight + 'px';
			if(this.bkgContentLayer.scrollWidth == 0) {
				this.bkgContentLayer.style.width = this.contentLayer.scrollWidth + 'px';
			}
			if(this.bkgContentLayer.scrollWidth < document.body.offsetWidth) {
				this.bkgContentLayer.style.left = document.body.offsetWidth / 2 - this.bkgContentLayer.scrollWidth / 2 + 'px';
			}
			var _iBodyHeight = (this.isDisplayOnIE6 ? document.documentElement.scrollTop : 0) + (
				window.innerHeight ?
					window.innerHeight:
					document.documentElement.clientHeight
			);
			if(parseInt(this.bkgContentLayer.style.top) != (_iBodyHeight / 2 - this.bkgContentLayer.offsetHeight / 2)) {
				this.top = _iBodyHeight / 2 - this.bkgContentLayer.offsetHeight / 2;
				this.bkgContentLayer.style.top = (this.top > 0  ? this.top : 0) + 'px';
			}
			if(!this.isDisplayOnIE6) {
				if(this.bkgContentLayer.scrollHeight < _iBodyHeight) {
					document.body.style.overflowX = 'hidden';
					this.bkgContentLayer.style.position = 'fixed';
				}
				else {
					document.body.style.overflow = 'auto';
					this.bkgContentLayer.style.position = 'absolute';
				}
			}
			this.addBehaviour();
		}
		return true;
	},

	addBehaviour: function() {
	
		var _oThat = this;
		var _aEls = document.getElementsByTagName('*');
		var _iEls = _aEls.length;
		while(--_iEls >= 0) {
			if(/\bshowCtrlLayer\b/.test(_aEls[_iEls].className)) {
				this.addEvent(_aEls[_iEls], 'click', function(e) {
					_oThat.stopEvent(e);
					_oThat.replaceImg(e);
					document.getElementById('layer').showCtrl = e.target || e.srcElement;
					setTimeout(function() { _oThat.show(e); }, 50);
				});
			}
			else if(/\bhideCtrlLayer\b/.test(_aEls[_iEls].className)) {
				this.addEvent(_aEls[_iEls], 'click', function(e) {
					_oThat.stopEvent(e);
					_oThat.hide(e);
				});
			}
			else if(_aEls[_iEls].id=='layer') {
				this.addEvent(_aEls[_iEls], 'click', function(e) {
					_oThat.stopEvent(e);
					_oThat.hide(e);
				});
			}
		}
		this.addEvent(window, 'resize', function() {
			if(_oThat.isDisplayOnIE) {
				var _iExClientHeight = document.documentElement.clientHeight;
				var _iExClientWidth = document.documentElement.clientWidth;
				var _interval = setInterval(function() {
					if(document.documentElement.clientHeight == _iExClientHeight && document.documentElement.clientWidth == _iExClientWidth) {
						clearInterval(_interval);
						_interval = null;
						_oThat.setSize();
					}
					_iExClientHeight = document.documentElement.clientHeight;
					_iExClientWidth = document.documentElement.clientWidth;
				}, 500);
			}
			else {
				_oThat.setSize();
			}
		});
		if(this.isDisplayOnIE6) {
			this.addEvent(window, 'scroll', function() { _oThat.adaptLayerOnScroll(); });
		}
	},

	adaptLayerOnScroll: function() {
		if(this.display) {
			this.bkgContentLayer.style.top = document.documentElement.scrollTop + document.documentElement.clientHeight / 2 - this.bkgContentLayer.offsetHeight / 2 + 'px';
		}
	},

	replaceImg: function(e) {
	
		var _oSrc = e.target || e.srcElement;
		var _oLayer = document.getElementById('layer');
		var _aDivs = _oLayer.getElementsByTagName('div');
		var _iDivs = _aDivs.length;
		while(--_iDivs >= 0) {
			if(/\bcontentLayer\b/.test(_aDivs[_iDivs].className)) {
				var _oContent = _aDivs[_iDivs];
				break;
			}
		}
		if(!_oContent) {
			return;
		}
		var _oLast = _oContent.childNodes[_oContent.childNodes.length - 1];
		while(_oLast && _oLast.nodeType != 1) {
			_oLast = _oLast.previousSibling;
		}
		if(/\bzoomed\b/.test(_oLast.className)) {
			_oLast.parentNode.removeChild(_oLast);
		}
		var _oSrcImg = _oSrc.parentNode.parentNode.previousSibling;
		while(_oSrcImg && _oSrcImg.nodeType != 1) {
			_oSrcImg = _oSrcImg.previousSibling;
		}
		if(_oSrcImg) {
			var _oImg = document.createElement('img');
			_oImg.className = 'zoomed';
			_oImg.src = '/img/' + _oSrc.rel;
			_oImg.alt = _oSrcImg.alt;
			_oContent.appendChild(_oImg);
		}
	
	},
	
	show: function(e) {
		if(this.layer) {
			var _aSelects = document.getElementsByTagName('select');
			var _iSelects = _aSelects.length;
			while(--_iSelects >= 0) {
				_aSelects[_iSelects].style.display = "none";
			}
			document.body.style.overflowX = 'hidden';
			if(!(/\bshowLayer\b/.test(this.layer.className))) {
				this.layer.className += ' showLayer';
				this.layer.style.display = 'block';
				setTimeout(function() { this.setSize(); }.bind(this), 200);
				this.display = true;
				var _oClose = document.getElementById('hideCtrlLayer');
				if(_oClose) {
					_oClose.focus();
				}
			}
			return true;
		}
		return false;
	},

	hide: function(e) {
		if(this.layer) {
			var _aSelects = document.getElementsByTagName('select');
			var _iSelects = _aSelects.length;
			while(--_iSelects >= 0) {
				_aSelects[_iSelects].style.display = "";
			}
			document.body.style.overflowX = 'auto';
			if(/\bshowLayer\b/.test(this.layer.className)) {
				this.layer.className = this.layer.className.replace(/\bshowLayer\b/, '');
				this.layer.style.display = 'none';
				this.display = false;
				if(document.getElementById('layer').showCtrl) {
					document.getElementById('layer').showCtrl.focus();
				}
			}
			return true;
		}
		return false;
	},

	addEvent: function(oEl, sEvType, fn, bCapture) {
		return document.addEventListener ?
			oEl.addEventListener(sEvType, fn, bCapture || false):
			oEl.attachEvent ?
				oEl.attachEvent('on' + sEvType, fn):
				false;
	},

	stopEvent: function(e) {
		if(e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}
		else if(e && window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		return false;
	}

});

var oMyLayer = new Layer({
	'width': 687,              // Largeur du layer
//	'height': 450,               // Hauteur du layer
//	'opacity': .8,                // Opacite du layer
	'content': ''                // Contenu du layer
});

oMyLayer.addEvent(
	window,
	'load',
	function() {
		oMyLayer.set(document.body);
	}
);


/***************************************************************************************************************************************************
 * SELECTS
 * @class : Selects
 * @depends: Mootools
 */

var Selects = new Class({

	modele: '',
	
	initialize: function() {
	
		$(window).addEvent('load', this.addBehaviours.bind(this));
	
	},
	
	addBehaviours: function() {
	
		$$('.modeles').each(this.addSelectBehaviour.bind(this));
	
	},
	
	addSelectBehaviour: function(oSelect) {
	
		if(!(window.attachEvent && typeof XmlHttpRequest === 'undefined')) {
			$(oSelect).addEvent('change', this.addTailleSelect.bindWithEvent(this));
		}
		
	},
	
	addTailleSelect: function(e) {
	
		if(e.nodeType == 1) {
			var _oSrc = $(e);
		}
		else {
			var _oEvent = new Event(e);
			var _oSrc = _oEvent.target;
			_oEvent.stop();
		}
		this.modele = _oSrc.getElements('option')[_oSrc.selectedIndex].value;
		new Request({
			url: '/ajax.php',
			method: 'get',
			onSuccess: this.onReceptTailleSelect.bindWithEvent(this, _oSrc)
		}).send('ajax=true&' + _oSrc.name + '=' + _oSrc.value);
	
	},
	
	onReceptTailleSelect: function(oResponse, oSrc) {

		var _oLast = $(oSrc).getParent().getLast();
		if($(_oLast).hasClass('contTailles')) {
			$(_oLast).destroy();
		}
		var _oFragment = new Element('div', {'class': 'contTailles'});
		$(oSrc).getParent().adopt(_oFragment);
		_oFragment.innerHTML = oResponse;

	}
	
});
var select = new Selects();


/***************************************************************************************************************************************************
 * DIRS
 * @class : Dirs
 * @depends: Mootools
 */

var Dirs = new Class({
	
	initialize: function() {
	
		$(window).addEvent('load', this.addBehaviours.bind(this));
	
	},
	
	addBehaviours: function() {
	
		$$('.goLeft').each(this.goLeftBehaviour.bind(this));
		$$('.goRight').each(this.goRightBehaviour.bind(this));
	
	},
	
	goLeftBehaviour: function(oLeft, iLeft) {
	
		oLeft.addEvent('click', this.goLeftHandler.bindWithEvent(this, [oLeft, iLeft]));
	
	},
	
	goLeftHandler: function(e, oLeft, iLeft) {
		
		var _oEvent = new Event(e);
		_oEvent.stop();
		var _oZoom = _oEvent.target.getParent('ul').getLast().getLast();
		var _oImg = $(oLeft).getParent('ul').getPrevious();
		new Request({
			url: '/ajax.php',
			method: 'get',
			onSuccess: this.goTo.bindWithEvent(this, [_oImg, _oZoom])
		}).send('ajax=true&pos=' + iLeft + '&dir=left&time=' + (new Date()).getTime());

	},
	
	goRightBehaviour: function(oRight, iRight) {

		$(oRight).addEvent('click', this.goRightHandler.bindWithEvent(this, [oRight, iRight]));
	
	},
	
	goRightHandler: function(e, oRight, iRight) {
			
		var _oEvent = new Event(e);
		_oEvent.stop();
		var _oZoom = _oEvent.target.getParent('ul').getLast().getLast();
		var _oImg = $(oRight).getParent('ul').getPrevious();
		new Request({
			url: '/ajax.php',
			method: 'get',
			onSuccess: this.goTo.bindWithEvent(this, [_oImg, _oZoom])
		}).send('ajax=true&pos=' + iRight + '&dir=right&time=' + (new Date()).getTime());
	
	},
	
	goTo: function(oResponse, oImg, oZoom) {
	
		var _aResponse = oResponse.split('|');
		oZoom.rel = _aResponse[0];
		oImg.src = _aResponse[1];
		oImg.alt = _aResponse[2];
	
	}

});
new Dirs();


/***************************************************************************************************************************************************
 * TESTFORM
 * @class : TestForm
 * @depends: Mootools
 */

var TestForm = new Class({
	
	initialize: function() {
	
		$(window).addEvent('load', this.addBehaviours.bind(this));
	
	},
	
	addBehaviours: function() {
	
		if($('livraison')) {
			$('livraison').addEvent('submit', this.checkInputs.bindWithEvent(this));
		}
	
	},
	
	checkInputs: function(e) {
	
		var _oEvent = new Event(e);
		var _oSrc = e.target;
		_oSrc.getElements('p').each(
			function(oP) {
			
				if($(oP).hasClass('error')) {
					$(oP).destroy();
				}
			
			}
		);
		var _bGood = true;
		_oSrc.getElements('.required').each(
			function(oInput) {
			
				if(oInput.value.trim() == '') {
					_bGood = false;
					new Element('p', {'class': 'error', 'text': 'Ce champ est obligatoire.'}).inject(oInput, 'after');
				}
			
			}
		);
		return _bGood ? true : _oEvent.stop();
	
	}

});
new TestForm();


/**
 * Cufonize
 */
function cufonize(){

	if(!window.attachEvent) {
		Cufon.now();
		Cufon.replace('.cufon');
	}
	
}
$(window).addEvent('load', function() {
	cufonize();
});