﻿
var IE7	= !(navigator.appVersion.indexOf("MSIE 7.") == -1);
var IE	= (navigator.appName == "Microsoft Internet Explorer");

/**
 * Ajout de code special IE7
 *
 * @author	bgcboyus : http://prototype.lighthouseapp.com/users/20379
 **/

Effect.BlindUp = function(element) {
	element = $(element);
	element.makeClipping();
	return new Effect.Scale(element, 0,
		Object.extend({ scaleContent: false,
			scaleX: false,
			restoreAfterFinish: (IE && !IE7) ? false : true,
			afterFinishInternal: function(effect) {
				effect.element.hide().undoClipping();
			}
		}, arguments[1] || { })
	);
};

Effect.BlindDown = function(element) {
	element = $(element);
	var elementDimensions = element.getDimensions();
	return new Effect.Scale(element, 100, Object.extend( {
		scaleContent: false,
		scaleX: false,
		scaleFrom: 0,
		scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
		restoreAfterFinish: (IE && !IE7) ? false : true,
		afterSetup: function(effect) {
			effect.element.makeClipping().setStyle({height: '0px'}).show();
		},
		afterFinishInternal: function(effect) {
			effect.element.undoClipping();
			Effect.Appear(element, {delay: 1, duration: .1});
		}
	}, arguments[1] || { }));
};

// INITIALISATIONS

var boxesByCat = {
	'home' : ['tournee', 'zoom', 'news', 'cie-lhoche'],
	'repertoire' : ['distribution', 'presse', 'presentation', 'extraits'],
	'compagnie' : ['cie-presentation', 'img-container', 'dates', 'soutien'],
	'lionelhoche' : ['choregraphie', 'img-container', 'cvitae', 'presse'],
	'contact' : ['contactus', 'img-container'],
	'bonus' : ['liens', 'img-container', 'bonusvideo', 'bonusphoto']
};

/**
 * Supprime le "px" d'une hauteur de style CSS (180.5px -> 180.5)
 *
 * @param	string
 * @return	float
 **/
function px2Int(h){
	return parseFloat(h.replace('px', ''));
}

/**
 * Degug sur Firebug et console IE DebugBar / Companion.JS
 *
 * @param	mixed
 * @return	void
 **/
function cl (c) {
	if ( "undefined" != typeof console )
		console.log(c) ;
}

/**
 * Remet la largeur des blocs mainright et mainleft d'appoint si la largeur du
 * viewport est impaire
 * Event.observe(window, 'resize', restoreBadSizes);
 * @return	void
 **/
function restoreBadSizes () {
	if( document.viewport.getDimensions().width % 2 > 0 ) {
		if (Prototype.Browser.WebKit) {
			(function(){
				$('mainright').setStyle({width : $('mainleft').getWidth() + 1 + 'px' });
			}).delay(0.3);
		}
		$('left-shadow').setStyle({backgroundPosition : '1px 0'});
	} else {
		// A VOIR SUR SAFARI
		if (Prototype.Browser.WebKit) {
			(function(){
				$('mainright').setStyle({width : $('mainleft').getWidth() });
			}).delay(0.3);
		}
		$('left-shadow').setStyle({backgroundPosition : '0 0' });
	}
}

/**
 *
 * Event.observe(window, 'resize', testBoxesHeight);
 * @return	void
 **/
function testBoxesHeight () {
	$$('.plusbar').each(function (ele) {
		var plusmoinsBloc = $$('#' + ele.parentNode.id + ' .plus').first();
		var txtBloc = $$('#' + ele.parentNode.id + ' .txt').first();
		var txtHeight = px2Int(txtBloc.getStyle('padding-top')) +
			 txtBloc.getHeight() + px2Int(txtBloc.getStyle('padding-bottom')) ;

		if (txtHeight < ele.parentNode.getHeight()) {
			if (!plusmoinsBloc.hasClassName('blank-background'))
				$$('#' + ele.parentNode.id + ' .plus').first().addClassName('blank-background');
		} else {
			if (plusmoinsBloc.hasClassName('blank-background'))
				$$('#' + ele.parentNode.id + ' .plus').first().removeClassName('blank-background');
		}
	}) ;
}

/**
 * Observer sur les évenements onresize de la fenetre
 *
 * @return	void
 **/
function onResizeObserver () {
	testBoxesHeight();
	restoreBadSizes();
	setContainerHeight()
}
Event.observe(window, 'resize', onResizeObserver);

/**
 * Change la couleur des barres <hr/> selon le background
 * Event.observe(window, 'load', setHRBarColor);
 *
 *(A REECRIRE)
 */
function setHRBarColor () {
	$$('.barre-hori').each(function (el) {
		var parentCol = el.ancestors().first().getStyle('color') ;
		if(!IE7)
			parentCol = parentCol.rgbToHex()

		if(parentCol == '#000000'  ) {
			el.addClassName('noir');
		}
	});
}

/**
 * Applique un makeClipping Prototype sur les boites de la page
 *
 */

function makeBoxesClipping () {
	boxesByCat[categorie].each(function (id) {
		if (Object.isElement($(id))){
			$(id).makeClipping() ;
			if(IE7 && Object.isElement($(id + '-container')))
				$(id + '-container').makeClipping() ;
		}
	});
}

/**
 * Initialise des variables selon la page sur laquelle on est
 *
 * Event.observe(window, 'load', initVars);
 **/
function initVars () {

	switch (categorie) {
		case 'home' :
			correspondingBoxes = {'news' : 'cie-lhoche', 'tournee' : 'zoom'};
			pageBoxes = {left : ['news', 'cie-lhoche'] , right : ['tournee','zoom']};
			break;

		case 'repertoire' :
			correspondingBoxes = {'presentation' : 'presse', 'extraits' : 'distribution'};
			pageBoxes = {left : ['presentation', 'presse'] , right : ['extraits','distribution']};
			break;

		case 'compagnie' :
			correspondingBoxes = {'cie-presentation' : 'img-container', 'dates' : 'soutien'};
			pageBoxes = {left : ['cie-presentation', 'img-container'] , right : ['dates','soutien']};
			break;

		case 'lionelhoche' :
			correspondingBoxes = {'choregraphie': 'img-container', 'cvitae' : 'presse'};
			pageBoxes = {left : ['choregraphie', 'img-container'] , right : ['cvitae','presse']};
			break;

		case 'bonus' :
			correspondingBoxes = {'liens' : 'bonusvideo'};
			pageBoxes = {left : [], right : []};
			break;

		case 'contact' :
			correspondingBoxes = {'contactus' : 'img-container'};
			pageBoxes = {left : [], right : []};
			break;

		default : throw $break;

	}
}
//var ieExceptions;
var correspondingBoxes, pageBoxes;

var innerH, innerW;

/**
 * Redimensionne le container principal (descendant direct de BODY) en calculant
 * les hauteurs gauches et droties actuelles selon la page dans laquelle on est
 *
 *
 * @param	e			Event
 * @return	void
 */
function setContainerHeight(e) {

	var leftHeight, rightHeight;

	if (self.innerHeight) {
		innerW = self.innerWidth;
		innerH = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		innerW = document.documentElement.clientWidth;
		innerH = document.documentElement.clientHeight;
	} else if (document.body) {
		innerW = document.body.clientWidth;
		innerH = document.body.clientHeight;
	}

	switch (categorie) {

		case 'home' :
			leftHeight = px2Int($('left-container').getStyle('top')) + $('left-container').getHeight() + $('footer').getHeight();
			rightHeight = px2Int($('right-container').getStyle('top')) + $('right-container').getHeight() + $('footer').getHeight();
			break ;

		case 'repertoire' :
			leftHeight = px2Int($('left-container').getStyle('top')) +
				$('presentation').getHeight() +
				$('footer').getHeight() +
				(Object.isElement($('presse')? $('presse').getHeight() : 0 ));
			rightHeight = $('right-container').getHeight() + $('footer').getHeight();
			break ;

		case 'compagnie' :
			leftHeight = px2Int($('left-container').getStyle('top')) + $('cie-presentation').getHeight() + $('img-container').getHeight() + $('footer').getHeight();
			rightHeight = px2Int($('dates').getStyle('top')) + $('dates').getHeight() + $('soutien').getHeight() + $('footer').getHeight();
			break ;

		case 'lionelhoche' :
			px2Int($('choregraphie').getStyle('height')) ;
			leftHeight = px2Int($('left-container').getStyle('top')) + $('left-container').getHeight() + $('footer').getHeight();
			rightHeight = px2Int($('right-container').getStyle('top')) + $('right-container').getHeight() + $('footer').getHeight();
			break ;

		case 'bonus' :
			leftHeight = px2Int($('left-container').getStyle('top')) + $('left-container').getHeight() + $('footer').getHeight();
			rightHeight = px2Int($('right-container').getStyle('top')) + $('right-container').getHeight() + $('footer').getHeight();
			break ;

		case 'contact' :
			leftHeight = px2Int($('left-container').getStyle('top')) + $('left-container').getHeight() + $('footer').getHeight();
			rightHeight = px2Int($('right-container').getStyle('top')) + $('right-container').getHeight() + $('footer').getHeight();
			break ;

		default :
			return;
	}
	//if ($('container').getHeight() < innerH)
	//	calcHeight = innerH;

	calcHeight = Math.max(Math.max(leftHeight, rightHeight), innerH);
	if (Math.abs(calcHeight-innerH) < 2)
		calcHeight	= innerH;


	$('container').setStyle({height: calcHeight +'px'});
}

/**************** Import from function-home.js ********************************/


/**
 * Pour la page 'home', gestion des clic sur les + et -
 *
 **/
var HomeBoxManage = Class.create();

HomeBoxManage.prototype = {

	boxes			: [],
	boxesContent	: [],
	contents		: null,
	titles			: null,
	activeBox		: null,
	state			: false,
	defaultHeight	: 'auto !important',

	options			: {},
	ieExceptions	: null,

	initialize		: function (options, ieExceptions) {

		this.canToggle	= true ;
		this.options = Object.extend(this.options, options || {} );
		this.ieExceptions	= ieExceptions;
		this.boxesContent	= new Array ;

		this.searchBoxes() ;
		this.observeBoxes() ;

	},
	observeBoxes		: function () {
		$$('.boxes').each ((function (boxe) {
			var txtContSize = px2Int($$('#' + boxe.id + ' .txt').first().getStyle('padding-top')) + $$('#' + boxe.id + ' .txt').first().getHeight() + px2Int($$('#' + boxe.id + ' .txt').first().getStyle('padding-bottom')) ;
			if(boxe.parentNode.getHeight() <= txtContSize )
				if(boxe.next())
					Event.observe (boxe.next(), 'click' , this.toggleAll.bindAsEventListener(this, boxe) ) ;
		} ).bind(this)) ;
	},
	stopObservingBoxes	: function () {
		$$('.boxes').each ((function(boxe) {
			Event.stopObserving(boxe.next(), 'click' , this.toggleAll.bindAsEventListener(this, boxe) ) ;
		} ).bind(this));

	},
	searchBoxes		: function () {
		// Avant d'ajouter la boite, on regarde si cela sert a quelquechose
		// d'activer les + sinon on les enlève et on raccourci la boite
		$$('.boxes').each ((function (boxe){
			if(boxe.parentNode.getHeight() <= $$('#' + boxe.id + ' .txt').first().getHeight() ) {
				this.boxesContent.push ({
					id : boxe.id,
					originalHeight : $(boxe.id + '-container').getStyle('height'),
					winHeight	: document.documentElement.scrollHeight		// a deplacer
				});
			} else {
				boxe.parentNode.setStyle({'height': parseInt(px2Int($(boxe.id).getStyle('height')) + px2Int($(boxe.id + '-plus').getStyle('height'))) + 'px'});
				boxe.parentNode.style.minHeight = '0%';
			}

			// On set les hauteurs
			boxe.parentNode.setStyle({'height': boxe.parentNode.getHeight() + 'px'});
			boxe.parentNode.style.minHeight = '0%';

			if (IE7 && boxe.parentNode.next()){
				boxe.parentNode.next().style.top = boxe.parentNode.getHeight() + 'px';
			}
		}).bind(this) ) ;
	},

   /**
	* Met la height pour que l'on voit tout son contenu
	**/
	toggleAll		: function (event, boxe) {
		var idBoxe	= boxe.readAttribute('id')
		var parent	= $(idBoxe + '-container');
		var child	= boxe.select('.txt').first();
		var plus	= parent.select('#'+idBoxe+'-plus').first();
		var grow	= false;

		// SI ON VEUT OUVRIR UNE BOITE : ON REGARDE LES ETAT DE CHACUNE DES BOITES,
		// SI UNE BOITE EST OUVERTE ON LA FERME
		if (boxe.parentNode.select('.plus').first().hasClassName('moins')) {
			this.goEffect(event, boxe, this.getOriginalHeight(boxe), false);
		} else {
			var wait = false;
			// Si une boite est ouverte on la ferme d'abord
			$$('.boxes').each((function (b) {
				var aPlus = b.parentNode.select('.plus');
				if (aPlus.length > 0 && aPlus.first().hasClassName('moins')) {
					wait = true;
					this.goEffect(event, b, this.getOriginalHeight(b), false);
				}
			}).bind(this));

			delay = wait ? 0.8 : 0.01;

			newHeight = px2Int(child.getStyle('padding-top')) + px2Int(child.getStyle('height')) + px2Int(child.getStyle('padding-bottom')) + plus.getHeight() + 'px';

			this.goEffect.bind(this).delay(delay, event, boxe, newHeight, true);
		}
	},

	getOriginalHeight : function (box) {
		var originalH = '' ;
		this.boxesContent.each(function(b){
			if(b.id == box.id)
				originalH = b.originalHeight;
		});
		return originalH ;
	},

   /**
	* Lance l'effet avec un evenement en particulier sur une boite
	* @param	event	L'évenement
	* @param	box		La boite
	* @param	newh	La nouvelle hauteur
	* @param	grow	Mode grossissement ou non
	* @return	void
	**/
	goEffect : function (event, box, newH, grow) {
		// On recalcule les options en mode grow
		if(grow)
			this.options = initHeights();

		if (IE7) {
			box.parentNode.setStyle({height : box.parentNode.getHeight() + 'px'});
		}
		var morph = new Effect.Morph(box.parentNode, {
			style: {
				height: newH
			},

			duration: 0.8,

			// On desactive les click temporairement
			beforeStart : (function (e) {
				// Attention trick --> peut poser des pbs
				if(grow)
					box.parentNode.setStyle({minHeight : parseFloat(box.parentNode.getStyle('height'))+'px'});
				var windowHeight	= (typeof(window.innerWidth) == 'number') ? window.innerHeight : document.documentElement.clientHeight;

				// Clic sur une colonne de gauche
				if ($(box.id).descendantOf('left-container')) {
				//	newContainerHeight = grow ? Math.max(this.options.left.max, this.options.left.min) : this.options.left.min;
					var numBox = (pageBoxes.left[0] == box.id) ? 1 : (pageBoxes.left[1] == box.id) ? 0 : null ;

					if (numBox == null)
						return;

					if (grow) {
						newContainerHeight = px2Int($('left-container').getStyle('top')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('padding-top')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('height')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('padding-bottom'))+
							$('footer').getHeight();
						newContainerHeight += (pageBoxes.left[numBox] == 'img-container') ? $('img-container').getHeight() : ((Object.isElement($(pageBoxes.left[numBox] + '-container'))) ? $(pageBoxes.left[numBox] + '-container').getHeight() : 0);

						if (Object.isElement($(box.id).next()))
							newContainerHeight += $(box.id).next().getHeight() ;	// #plus
					} else
						newContainerHeight = this.options.left.min;
				} else {
					// Clic sur une colonne de droite
					//newContainerHeight = grow ? Math.max(this.options.right.max, this.options.right.min) : this.options.right.min;
					var numBox = (pageBoxes.right[0] == box.id) ? 1 : (pageBoxes.right[1] == box.id) ? 0 : null ;

					if (numBox == null)
						return;

					if (grow) {
						newContainerHeight = px2Int($('right-container').getStyle('top')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('padding-top')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('height')) +
							px2Int($$('#' + box.id + ' .txt').first().getStyle('padding-bottom')) +
							$('footer').getHeight();

						newContainerHeight += (pageBoxes.right[numBox] != 'img-container') ? $(pageBoxes.right[numBox] + '-container').getHeight() : $('img-container').getHeight();

						if (Object.isElement($(box.id).next()))
							newContainerHeight += $(box.id).next().getHeight() ;	// #plus
					} else
						newContainerHeight = this.options.right.min;
				}

				if (windowHeight > newContainerHeight)
					newContainerHeight = windowHeight

				if (IE7) {
					$('container').setStyle({height : windowHeight + 'px'});
				}

				var morph = new Effect.Morph($('container'), {
					style: {
						height: newContainerHeight + 'px'
					},
					duration: 0.8,
					transition : Effect.Transitions.sinoidal
				});

				if(IE7 && this.ieExceptions[box.id] != undefined) {
					var idMorphBox = Object.isElement($(this.ieExceptions[box.id] + '-container')) ? this.ieExceptions[box.id] + '-container' : this.ieExceptions[box.id];
					//alert( idMorphBox + ' ' + newH) ;
					$(idMorphBox).setStyle({top : box.getHeight() + 'px'});
					var morph = new Effect.Morph($(idMorphBox), {
						style: {
							top: newH
						},
						duration: 0.8,
						transition : Effect.Transitions.sinoidal
					});
				}
			}).bind(this),

			afterFinish : (function (e) {
				if(IE7 && Object.isElement($('cie-lhoche'))) {
				/*	$('cie-lhoche').setStyle({
						top : newH
					});*/
				}
				type = box.id == 'news' ? 'left' : 'right' ;
				plusMoins = box.parentNode.select('.plus').first().toggleClassName('moins');
			}).bind(this),

			transition : Effect.Transitions.sinoidal
		}) ;

		// !!!
		if(!IE7)
			Event.stop(event);
		return ;
	}
} ;

/**
 * Initialisation des min et max height gauche et droite pour chaque moitié et
 * recuperation des ids boites
 *
 * @return object
 **/
function initHeights() {

	var pagesIDs = {
		left : {
			min : px2Int($('left-container').getStyle('top')) + $('left-container').getHeight() + $('footer').getHeight(),
			max : px2Int($('left-container').getStyle('top'))+ $('footer').getHeight(),
			ids:[]
		},
		right : {
			min : px2Int($('right-container').getStyle('top')) + $('right-container').getHeight()  + $('footer').getHeight(),
			max : px2Int($('right-container').getStyle('top'))+ $('footer').getHeight(),
			ids:[]
		}
	};

	// Gauche 1 ou 2 enfants de type [...]-container avec [...] --> id
	$('left-container').childElements().each(function(ele) {
		pagesIDs.left.ids.push(ele.childElements().length > 0 ? ele.childElements().first().id : ele.id);
	});

	// Droite 1 ou 2 enfants de type id-container
	$('right-container').childElements().each(function(ele) {
		pagesIDs.right.ids.push(ele.childElements().length > 0 ? ele.childElements().first().id : ele.id);
	});

	pagesIDs.left.ids.each(function (ele) {
		if ($$('#' + ele + ' .txt').length > 0) {
			pagesIDs.left.max += px2Int($$('#' + ele + ' .txt').first().getStyle('padding-top')) +
							px2Int($$('#' + ele + ' .txt').first().getStyle('height')) +
							px2Int($$('#' + ele + ' .txt').first().getStyle('padding-bottom'));
			// Barre +/-
			if (Object.isElement($(ele).next()))
				pagesIDs.left.max += $(ele).next().getHeight() ;	// #plus
		} else {
			pagesIDs.left.max += $(ele).getHeight();
		}
	});

	pagesIDs.right.ids.each(function (ele) {
		if ($$('#' + ele + ' .txt').length > 0) {
			pagesIDs.right.max += px2Int($$('#' + ele + ' .txt').first().getStyle('padding-top')) +
							px2Int($$('#' + ele + ' .txt').first().getStyle('height')) +
							px2Int($$('#' + ele + ' .txt').first().getStyle('padding-bottom'));
			// Barre +/-
			if (Object.isElement($(ele).next()))
				pagesIDs.right.max += $(ele).next().getHeight();
		} else {
			pagesIDs.right.max += $(ele).getHeight();
		}
	});
	return pagesIDs ;
}

var homeBoxManage ;

var startBoxManagement = function () {

	restoreBadSizes();
	setHRBarColor();
	makeBoxesClipping();
	initVars();
	testBoxesHeight();
	setContainerHeight.delay(0.2);

	var pageOptions = initHeights();

	homeBoxManage = new HomeBoxManage(pageOptions, correspondingBoxes) ;

	function init() {
        if(!_os) {
			setTimeout(init, 50);
			return;
		}
        _os.appVersion = "0.2.1";
        _os.requireAll('UI', ['behaviors/model.js'], {});
    }

	if (categorie == 'contact') {
		$('contactus-container').setStyle({ height : $$('#contactus .txt').first().getHeight() + 'px'});
		$('contactus').setStyle({ height : $$('#contactus .txt').first().getHeight() + 'px'});
		$('contactus-container').setStyle({ minHeight : '5%'});
	}

	if (categorie == 'repertoire' || categorie == 'bonus')
		init();
} ;

Event.observe(window, 'load', startBoxManagement);

Event.observe(window, 'load', function () {

	if( (true || IE7) && categorie == 'home') {
		var cieHeight = $('cie-lhoche').getHeight();
		$('cie-lhoche').setStyle({
			height : cieHeight + 'px'
		}) ;
	}
});