// JavaScript Document

/********************************************************************************************/
//popup slider
/********************************************************************************************/	
var currentPopup = 0;
var popupItems;
function initSlidePopup(){	
	currentPopup = 0;
	popupItems = [];
	if($('popupSlideContainerBox')!=null){
		if($('popupSlideContainerBox').firstDescendant()!=null){
			popupItems = $('popupSlideContainerBox').firstDescendant().childElements();
			if(popupItems.length>3){
				$('popupSlideLeft').style.display = "block";
				$('popupSlideRight').style.display = "block";
			}else{
				$('popupSlideLeft').style.display = "none";
				$('popupSlideRight').style.display = "none";
				$('popupSlideContainerBox').morph('margin-left:'+((4*90)-(popupItems.length*90))+'px', { duration: 0});
			}
		}
	}
	manageSlidePopupArrows();
	forcePopupFade.delay(1);
}
function slidePopupLeft(){	
	if(currentPopup>0){	
		currentPopup--;
		$('popupSlideContainerBox').morph('margin-left:-'+(currentPopup*90)+'px', { duration: 0.4});
	}
	manageSlidePopupArrows();
}
function slidePopupRight(){
	if(currentPopup<(popupItems.length-4)){		
		currentPopup++;
		$('popupSlideContainerBox').morph('margin-left:-'+(currentPopup*90)+'px', { duration: 0.4});
	}
	manageSlidePopupArrows();
}
function manageSlidePopupArrows(){
	if(currentPopup<(popupItems.length-4)){
		$('popupSlideRight').morph('opacity:1', { duration: 0.4});
	}else{
		$('popupSlideRight').morph('opacity:0', { duration: 0.4});
	}
	if(currentPopup>0){
		$('popupSlideLeft').morph('opacity:1', { duration: 0.4});
	}else{
		$('popupSlideLeft').morph('opacity:0', { duration: 0.4});
	}
}
function forcePopupFade(){
	
	// $('popup').morph('opacity:1', { duration: 0});	
}

/********************************************************************************************/
//HD movie
/********************************************************************************************/


function launchHDMovie(pMovie, pPoster){
	
	var str = '<video id="video_0" class="video-js" width="800" height="450" poster="'+pPoster+'" controls preload>';           
	str += '<source src="'+pMovie+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
	str += '<object class="vjs-flash-fallback" width="800" height="450"><param name="movie" value="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf"></param><param name="flashvars" value="src='+pMovie+'&controlBarMode=floating&poster='+pPoster+'&autoPlay=true&scaleMode=none"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="800" height="450" flashvars="src='+pMovie+'&controlBarMode=floating&poster='+pPoster+'&autoPlay=true&scaleMode=none"></embed></object>';
	str += '</video>';
	
	$('videoContainer').innerHTML = str;
	
	VideoJS.setupAllWhenReady();

	$('ld_movie').style.display = "block";
	$('hd_movie').style.display = "none";
}

function launchLDMovie(pMovie, pPoster){
	
	var str = '<video id="video_0" class="video-js" width="800" height="450" poster="'+pPoster+'" controls preload>';           
	str += '<source src="'+pMovie+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
	str += '<object class="vjs-flash-fallback" width="800" height="450"><param name="movie" value="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf"></param><param name="flashvars" value="src='+pMovie+'&controlBarMode=floating&poster='+pPoster+'&autoPlay=true&scaleMode=none"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="800" height="450" flashvars="src='+pMovie+'&controlBarMode=floating&poster='+pPoster+'&autoPlay=true&scaleMode=none"></embed></object>';
	str += '</video>';
	
	$('videoContainer').innerHTML = str;
	
	VideoJS.setupAllWhenReady();
	
	$('hd_movie').style.display = "block";
	$('ld_movie').style.display = "none";
}

/********************************************************************************************/
//touch events
/********************************************************************************************/

var initTouchX;
var initTouchY;
var _slideLock = false;

function touchStart( e ) {
	//e.preventDefault();	
	
	var targetEvent =  e.touches.item(0);
	initTouchX = targetEvent.clientX;
	initTouchY = targetEvent.clientY;	
	
	return false;
}
  
function touchMove( e ) {
	//e.preventDefault();
	
	var targetEvent =  e.touches.item(0);
	var diffX = initTouchX-targetEvent.clientX;
	var diffY = initTouchX-targetEvent.clientY;
	
	if(_slideLock == false){
		_slideLock = true;
		unLockSlide.delay(0.5);
		if(diffX>10){		
			slideRight();
		}
		if(diffX<-10){	
			slideLeft();
		}
	}
	
	return false;
}

function unLockSlide(){
	_slideLock = false;
}

function inspect( obj ) {  
	if (typeof obj === "undefined") {  
		return "undefined";  
	}  
	var _props = [];  
	for ( var i in obj ) {  
		_props.push( i + " : " + obj[i] );   
	}  
	return " {" + _props.join( ",<br>" ) + "} ";  
}  
/********************************************************************************************/
//popup section blog
/********************************************************************************************/	
function custompopup(pPage){
	_log('custompopup');
	_log(pPage);
}
/********************************************************************************************/
//field focus
/********************************************************************************************/	
function manageFocus(pEl, pValue){
	$(pEl).title = pValue;
	$(pEl).observe('focus', function(event){	
		if(event.target.value == event.target.title){
			
			event.target.value = '';
		}
	});
}
/********************************************************************************************/
//menus & submenus
/********************************************************************************************/	
function refreshFilters(){
	
	orderBlocs();
	
	window.setTimeout(orderBlocs, 500, true);
	
	var el;
	if($('catalogue')!=null){ el = $('catalogue'); }
	if($('blog')!=null){ el = $('blog'); }
	
	if($(el)!=null){
		if($(el).firstDescendant()!=null){
			if($(el).firstDescendant().childElements()!=null){
				var items = $(el).firstDescendant().childElements();	
				var isset = false;
				for(var i=0; i<items.length; i++){

					if($(items[i]).hasClassName('on')){
						isset = true;
					}else{
						$(items[i]).toggleClassName('off');
					}
				}	
				if(isset == false){
					
					$(el).firstDescendant().firstDescendant().toggleClassName('on');
				}
				Cufon.refresh();
				Cufon.now();
			}
		}
	}
}
/********************************************************************************************/
//filter management
/********************************************************************************************/	
function refreshSubFilters(pId){	
	
	_log("refreshSubFilters = "+pId);
	var el;
	if($('catalogueajx')!=null){ el = $('catalogueajx'); }
	if($('blogajx')!=null){ el = $('blogajx'); }
	
	if($(el)!=null){
	
		var items = $(el).firstDescendant().firstDescendant().childElements();
		if(items[0].className == 'menuItemList'){
			var cpt = 0;
			for(var i=0; i<items.length; i++){
				var sub = items[i].childElements();
				_log(sub);
				for(var j=0; j<sub.length; j++){
					if(cpt==pId){
						$(sub[j]).firstDescendant().className='on';
					}else{
						$(sub[j]).firstDescendant().className='off';
					}
					cpt++;					
				}
			}
			
		}else{

			for(var i=0; i<items.length; i++){
				if(i==pId){
					$(items[i]).firstDescendant().firstDescendant().className='on';
				}else{
					$(items[i]).firstDescendant().firstDescendant().className='off';
				}		
			}
		}
	}
}
/********************************************************************************************/
//position blocs blog
/********************************************************************************************/	
function orderBlocs(){
	
	if($('articlesBlogBloc')!=null){
	
		var items = $('articlesBlogBloc').childElements();	
		
		var basx = 14;
		var basey = Position.cumulativeOffset($('cataloguetab'))[1]-108;
	
		var pos = [];
		var line = 0;
		var column = 0;
		for(var i=0; i<items.length; i++){
			
			xb.addEvent($(items[i]), 'mouseenter', Relegate.create(this, doBlogEnter, i), false);
			xb.addEvent($(items[i]), 'mouseleave', Relegate.create(this, doBlogLeave, i), false);				
				
			if(column == 0){
				pos[line] = [];
			}
			if(line>0){
				
				_y = pos[line-1][column];			
			}else{
				_y = basey;			
			}
			var pSup = $(items[i]).offsetHeight;
			if($(items[i]).offsetHeight<10){
				pSup = 100;
			}
			pos[line].push(_y+pSup+30);
			
			$(items[i]).style.left = ((column*240)+basx) + 'px';

			$(items[i]).style.top = _y+'px';
			$(items[i]).style.position = 'absolute';
			
			if(column < 3){
				column++;
			}else{
				column = 0;
				line++;
			}
		}
		
		var arr;
		if(pos[line]){
			if(pos[line].length>0){
				arr = pos[line];
			}else{
				arr = pos[line-1];
			}
		}else{
			
			arr = pos[0];
		}
		var _h=0;
		for(var j = 0; j<arr.length; j++){
			if(arr[j]>_h){
				_h = arr[j];
			}
		}
		
		
		_log(_h);
		
		$('articlesBlogBloc').style.height = (_h-300)+"px";	
		$('cnt').style.height = (_h+500)+"px";	
		
	}
}

function doBlogEnter(e, pId){
	
	if($('articlesBlogBloc')!=null){
		
		var items = $('articlesBlogBloc').childElements();
		for(var i=0; i<items.length; i++){
			
			if(i==pId){
				$(items[i]).setStyle({
					  backgroundColor: '#e7e7e7'
				});	
			}else{
				
				$(items[i]).setStyle({
					  backgroundColor: '#FFFFFF'
				});				
			}
		}		
	}
}

function doBlogLeave(e, pId){
	
	if($('articlesBlogBloc')!=null){
		
		var items = $('articlesBlogBloc').childElements();
		$(items[pId]).setStyle({
			  backgroundColor: '#FFFFFF'
		});		
	}
}

/********************************************************************************************/
//gestion div durée
/********************************************************************************************/	
function revealDuration(pEl){
	if($(pEl).firstDescendant().childElements()[2]!=null){
		var el = $(pEl).firstDescendant().childElements()[2];
		$(el).morph('opacity:0', { duration: 0});
		$(el).style.display = "block";
		$(el).morph('opacity:1', { duration: 0.4 });
	}
}
function hideDuration(pEl){
	if($(pEl).firstDescendant().childElements()[2]!=null){
		var el = $(pEl).firstDescendant().childElements()[2];
		$(el).morph('opacity:0', { duration: 0.4 });
	}
}
/********************************************************************************************/
//cufon refresh
/********************************************************************************************/	
function refreshFonts(){	
	try{
		Cufon.refresh();
		Cufon.now();
	}catch (e){}
}
/********************************************************************************************/
//popup (layer readmore & purge fermeture)
/********************************************************************************************/	

function override(f, g) { return function() { return g(f); }}

function closeAndEmptyPopup(pEl){	
	
	closepopup();	
}

/*
function closepopup(){
	alert('closepopup');
	try{
		VideoJS.pause();
	}catch (e){}
	if($('popupContainer')!=null){
		$('popupContainer').innerHTML = "";
	}
	Effect.Shrink('popupbox', {duration:0.2, direction:'bottom-left'});
	Effect.Fade('popup');
	if (window.pumpitdown) {pumpitdown();}
}
*/
function expendPopupText(){	
	$('popupTxt').morph('margin-top:-558px', { duration: 0.8 });
	$('popupMainContainer').style.display = "block";
	$('popupTxtCredit').style.display = "none";
	$('popupReadmore').morph('opacity:0', { duration: 0.4 });
	$('popupRetour').morph('display:block', { duration: 0.4 });
	$('popupRetour').morph('opacity:100', { duration: 0.4 });
}

function manageMention(){
	$('popupMainContainer').style.display = "block";
	$('popupTxtCredit').style.display = "none";
}

function collapsePopupText(){	
	$('popupTxt').morph('margin-top:-120px', { duration: 0.8 });
	manageMention.delay(0.8);
	$('popupRetour').morph('opacity:0', { duration: 0.4 });
	$('popupReadmore').morph('opacity:100', { duration: 0.4 });
}

function expendPopupMention(){	
	$('popupTxt').morph('margin-top:-558px', { duration: 0.8 });
	$('popupMainContainer').style.display = "none";
	$('popupTxtCredit').style.display = "block";
	$('popupReadmore').morph('opacity:0', { duration: 0.4 });
	$('popupRetour').morph('display:block', { duration: 0.4 });
	$('popupRetour').morph('opacity:100', { duration: 0.4 });
}

/********************************************************************************************/
//slideshow
/********************************************************************************************/	
var current = 0;
var _duration = 4;
var _manual  = false;

function slideRight(){	
	
	_manual = true;
	var items = $('slidecontainer').select('li');
	if(current+1<items.length){
		current++;
	}else{
		current = 0;
	}
	$('slidecontainer').morph('margin-left:-'+(current*940)+'px', { duration: 0.6});
	manageSlideArrows();
}

function slideLeft(){	
	
	_manual = true;
	var items = $('slidecontainer').select('li');
	if(current>0){	
		current--;	
	}else{
		current=items.length-1;	
	}
	$('slidecontainer').morph('margin-left:-'+(current*940)+'px', { duration: 0.6});
	manageSlideArrows();
}

function forceSlide(pId){

	current = pId;
	$('slidecontainer').morph('margin-left:-'+(current*940)+'px', { duration: 0});
	manageSlideArrows();
}

function autoSlideRight(){	
	
	if(_manual == true){
		
		_manual = false;
	}else{
		var items = $('slidecontainer').select('li');
	
		if(current+1<items.length){
			current++;
		}else{
			current = 0;
		}
		$('slidecontainer').morph('margin-left:-'+(current*940)+'px', { duration: 0.6});
		manageSlideArrows();
	}
}

function autoSlide(){
	
	new PeriodicalExecuter(function(pe) {
		_log('autoSlide');
		window.autoSlideRight();
	}, _duration);
}

function manageSlideArrows(){
	
	var items = $('slidecontainer').select('li');
	
	if(current+1<(items.length)){
		$('arrowRight').morph('opacity:1', { duration: 0.4});
	}else{
		$('arrowRight').morph('opacity:0.4', { duration: 0.4});
	}
	if(current>0){
		$('arrowLeft').morph('opacity:1', { duration: 0.4});
	}else{
		$('arrowLeft').morph('opacity:0.4', { duration: 0.4});
	}
	hackFontSafari.delay(0.4);
}

function hackFontSafari(){
	refreshFonts();
}

/********************************************************************************************/
//menu
/********************************************************************************************/
document.observe("dom:loaded", function() {
	
	closepopup = override(closepopup, function() {

		try{
			VideoJS.pause();
		}catch (e){}
		if($('popupContainer')!=null){
			$('popupContainer').innerHTML = "";
		}
		// Effect.Shrink('popupbox', {duration:0.2, direction:'bottom-left', afterFinish:function() {
		// 	$('popupbox').style.display = 'block';
		//   }
		// });
		Effect.Shrink('popupbox', {duration:0.2, direction:'bottom-left'});
		Effect.Fade('popup', {afterFinish:function() {
			$('popupbox').style.display = 'block';
		  }
		});
		if (window.pumpitdown) {pumpitdown();}
	});

	if (Prototype.Browser.IE) {
		try{ 
			$('m_1').observe('mouseenter', Relegate.create(this, doenterIE, 'm_1'));
		} catch (e) {}
		try{ 
			$('m_1').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_1'));
		} catch (e) {}
		try{ 
			$('m_2').observe('mouseenter', Relegate.create(this, doenterIE, 'm_1'));
		} catch (e) {}
		try{ 
			$('m_2').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_1'));
		} catch (e) {}
		try{ 
			$('m_3').observe('mouseenter', Relegate.create(this, doenterIE, 'm_1'));
		} catch (e) {}
		try{ 
			$('m_3').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_1'));
		} catch (e) {}
		//$('m_1').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_1'));
		//$('m_2').observe('mouseenter', Relegate.create(this, doenterIE, 'm_2'));
		//$('m_2').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_2'));
		//$('m_3').observe('mouseenter', Relegate.create(this, doenterIE, 'm_3'));
		//$('m_3').observe('mouseleave', Relegate.create(this, doleaveIE, 'm_3'));
	}else{
		xb.addEvent($('m_1'), 'mouseenter', doenter, false);
		xb.addEvent($('m_1'), 'mouseleave', doleave, false);
		xb.addEvent($('m_2'), 'mouseenter', doenter, false);
		xb.addEvent($('m_2'), 'mouseleave', doleave, false);
		xb.addEvent($('m_3'), 'mouseenter', doenter, false);
		xb.addEvent($('m_3'), 'mouseleave', doleave, false);
	}
	/*

	if (Prototype.Browser.IE) {
		xb.addEvent($('m_1'), 'mouseenter', Relegate.create(this, doenterIE, 'm_1'), false);
		xb.addEvent($('m_1'), 'mouseleave', Relegate.create(this, doleaveIE, 'm_1'), false);
		xb.addEvent($('m_2'), 'mouseenter', Relegate.create(this, doenterIE, 'm_2'), false);
		xb.addEvent($('m_2'), 'mouseleave', Relegate.create(this, doleaveIE, 'm_2'), false);
		xb.addEvent($('m_3'), 'mouseenter', Relegate.create(this, doenterIE, 'm_3'), false);
		xb.addEvent($('m_3'), 'mouseleave', Relegate.create(this, doleaveIE, 'm_3'), false);
	}else{
		xb.addEvent($('m_1'), 'mouseenter', doenter, false);
		xb.addEvent($('m_1'), 'mouseleave', doleave, false);
		xb.addEvent($('m_2'), 'mouseenter', doenter, false);
		xb.addEvent($('m_2'), 'mouseleave', doleave, false);
		xb.addEvent($('m_3'), 'mouseenter', doenter, false);
		xb.addEvent($('m_3'), 'mouseleave', doleave, false);
	}
	*/
	

	if($('arrowRight')!=null){
		$("arrowRight").observe('mouseover', function(event){
			$('arrowRight').morph('opacity:0.6', { duration: 0.2 });
		});
		$("arrowRight").observe('mouseout', function(event){
			$('arrowRight').morph('opacity:1', { duration: 0.2 });
		});
	}
	if($('arrowLeft')!=null){
		$("arrowLeft").observe('mouseover', function(event){
			$('arrowLeft').morph('opacity:0.6', { duration: 0.2 });
		});
		$("arrowLeft").observe('mouseout', function(event){
			$('arrowLeft').morph('opacity:1', { duration: 0.2 });
		});
	}
	
	orderBlocs();
	orderBlocs.delay(1);
});

function doenterIE(e, pStr){
		
	var el = $(pStr);
	if(el.hasClassName('off')){
		el.toggleClassName('roll');
		el.removeClassName('off');
		refreshFonts();
	}
}

function doleaveIE(e, pStr){
	
	var el = $(pStr);
	if($(pStr).hasClassName('roll')){
		el.toggleClassName('off');
		el.removeClassName('roll');
		refreshFonts();
	}
}

function doenter(e){
	
	var el = e.target;
	if($(el).hasClassName('off')){
		$(el).toggleClassName('roll');
		$(el).removeClassName('off');
		refreshFonts();
	}
}

function doleave(e){
	
	var el = e.target;
	if($(el).hasClassName('roll')){
		$(el).toggleClassName('off');
		$(el).removeClassName('roll');
		refreshFonts();
	}
}
/********************************************************************************************/
//utils
/********************************************************************************************/	
var xb =
{
	evtHash: [],

	ieGetUniqueID: function(_elem)
	{
		if (_elem === window) { return 'theWindow'; }
		else if (_elem === document) { return 'theDocument'; }
		else { return _elem.uniqueID; }
	},

	addEvent: function(_elem, _evtName, _fn, _useCapture)
	{
		if (typeof _elem.addEventListener != undefined)
		{
			if (_evtName == 'mouseenter')
				{ _elem.addEventListener('mouseover', xb.mouseEnter(_fn), _useCapture); }
			else if (_evtName == 'mouseleave')
				{ _elem.addEventListener('mouseout', xb.mouseEnter(_fn), _useCapture); } 
			else
				{ _elem.addEventListener(_evtName, _fn, _useCapture); }
		}
		else if (typeof _elem.attachEvent != undefined)
		{
			var key = '{FNKEY::obj_' + xb.ieGetUniqueID(_elem) + '::evt_' + _evtName + '::fn_' + _fn + '}';
			var f = xb.evtHash[key];
			if (typeof f != undefined)
				{ return; }
			
			f = function()
			{
				_fn.call(_elem);
			};
		
			xb.evtHash[key] = f;
			_elem.attachEvent('on' + _evtName, f);
	
			// attach unload event to the window to clean up possibly IE memory leaks
			window.attachEvent('onunload', function()
			{
				_elem.detachEvent('on' + _evtName, f);
			});
		
			key = null;
			//f = null;   /* DON'T null this out, or we won't be able to detach it */
		}
		else
			{ _elem['on' + _evtName] = _fn; }
	},	

	removeEvent: function(_elem, _evtName, _fn, _useCapture)
	{
		if (typeof _elem.removeEventListener != undefined)
			{ _elem.removeEventListener(_evtName, _fn, _useCapture); }
		else if (typeof _elem.detachEvent != undefined)
		{
			var key = '{FNKEY::obj_' + xb.ieGetUniqueID(_elem) + '::evt' + _evtName + '::fn_' + _fn + '}';
			var f = xb.evtHash[key];
			if (typeof f != undefined)
			{
				_elem.detachEvent('on' + _evtName, f);
				delete xb.evtHash[key];
			}
		
			key = null;
			//f = null;   /* DON'T null this out, or we won't be able to detach it */
		}
	},
	
	mouseEnter: function(_pFn)
	{
		return function(_evt)
		{
			var relTarget = _evt.relatedTarget;				
			if (this == relTarget || xb.isAChildOf(this, relTarget))
				{ return; }
			_pFn.call(this, _evt);
		};
	},
	
	isAChildOf: function(_parent, _child)
	{
		if (_parent == _child) { return false; };
		
		while (_child && _child != _parent)
			{ _child = _child.parentNode; }
		
		return _child == _parent;
	}	
};

function Relegate(){};
Relegate.create = function(t,f){
	var a = new Array();
	for(var i=2; i<arguments.length; i++){
		a.push(arguments[i]);
	}
	return function(){
		var b = new Array();
		for(var i=0; i<arguments.length; i++){
			b.push(arguments[i]);
		}
		return f.apply(t, b.concat(a));
	};
};

function _log(el){
	
	try{ 
		console.log(el);
	} catch (e) {}
}
/********************************************************************************************/
//	alternclass
/********************************************************************************************/	
function alternclass(cssid, id) {
	
	_log("alternclass = "+cssid+" # "+id);
	var cpt = 0;
	while (document.getElementById(cssid+cpt)) {
		document.getElementById(cssid+cpt).className='off';
		cpt++;
	}
	document.getElementById(cssid+id).className='on';
}
