// Scripts are copyrights Edouard Puginier & Frédéric Grasset
// Thanks you so much to people (including Vincent Bousquet) who helped me times ago
// Some amazing David Walsh ideas too, including Mootools IRC Chat guys

/* ======================================================================================================= */
/* =============================================== shared ============================================== */
/* ======================================================================================================= */

/* ============================== Manage display for the trail mask */
function footPrintsMask(){
	var windowTotalHeight = window.getScrollSize().y
	var windowHeight = window.getSize().y;
	var windowScrollHeight = window.getScroll().y;
	var allFootPrintMask = $$('.footPrintMask');
	var footPrintMaskTotal = allFootPrintMask.length;
	var footPrintsToFade = 2;

	allFootPrintMask.each(function(allFootPrintMaskElem, allFootPrintMaskIndex){
		var allFootPrintMaskElemPosition = allFootPrintMaskElem.getPosition().y;
		if ((allFootPrintMaskElemPosition + 100) < (windowHeight + windowScrollHeight)){
			allFootPrintMaskElem.addClass('_footOnScreen');
			var nLastFootPrint = $$('._footOnScreen').slice(-footPrintsToFade);
			nLastFootPrint.each(function(nLastFootPrintElem, nLastFootPrintIndex){
				nLastFootPrintElem.fade(nLastFootPrintIndex / footPrintsToFade)
			});
		}
		else {
			allFootPrintMaskElem.removeClass('_footOnScreen');
			allFootPrintMaskElem.fade('show');
		}
	});
}

/* ======================================================================================================= */
/* ================================================= load ================================================ */
/* ======================================================================================================= */

window.addEvent('load', function() {

});

/* ======================================================================================================= */
/* =============================================== domready ============================================== */
/* ======================================================================================================= */

window.addEvent('domready', function() {

/* ============================================================ */
/* ============================== Init var */
/* ============================================================ */

	var _animationSettings0 = $$('._animationSettings0');
	var _animationSettings1 = $$('._animationSettings1');
	var _animationSettings2 = $$('._animationSettings2');
	var _animationSettings3 = $$('._animationSettings3');
	var _animationSettings4 = $$('._animationSettings4');
	var allUserInputs = $$('.userInput');
	var allGenericInputs = $$('.genericInput');
	var allGenericTextareas = $$('.genericTextarea');
	var allGenericTextInputs = allGenericInputs.combine(allGenericTextareas);
	var requiredData = $$('.requiredData');
	var indexCheckProgress = $('indexCheckProgress');
	var indexWorkInProgress2 = $('indexWorkInProgress2');
	var indexHeaderHoverBackground = $$('.indexHeaderHoverBackground');
	var indexHeaderArea = $('indexHeaderArea');
	var indexHeaderBackgroundHole = $('indexHeaderBackgroundHole');
	var indexHeaderSection1 = $('indexHeaderSection1');
	var indexHeaderSection2 = $('indexHeaderSection2');
//	var indexHeaderMenuPrevNext = [$$('.indexHeaderPrev'), $$('.indexHeaderNext')];

/* ============================================================ */
/* ============================== Init effect */
/* ============================================================ */

	/* ============================== Default animation settings */
	_animationSettings0.set('tween', {duration: 100, transition: Fx.Transitions.Linear, link: 'cancel'});
	_animationSettings1.set('tween', {duration: 200, transition: Fx.Transitions.Quad.easeInOut, link: 'cancel'});
	_animationSettings2.set('tween', {duration: 1000, transition: Fx.Transitions.Bounce.easeOut, link: 'cancel'});
	_animationSettings3.set('tween', {duration: 3000, transition: Fx.Transitions.Quad.easeInOut, link: 'cancel'});
	_animationSettings4.set('tween', {duration: 500, transition: Fx.Transitions.Elastic.easeOut, link: 'cancel'});

	/* ============================== Displaying footPrints */
	footPrintsMask();

/* ============================================================ */
/* ============================== Positionning inputs backgrounds */
/* ============================================================ */

	var userInputBackgroundPosition = [ // userInputStyle, userInputHeightGap, userInputStyleGap, leftPartPosX, rightPartPosX, rightPartPictoPosX
		['.normalSize.neutral', -26, 0, 0, -285, -270],
		['.normalSize.important', -26, -130, 0, -285, -270],
		['.normalSize.critical', -26, -260, 0, -285, -270],
		['.normalSize.variant1', -24, -390, 0, -285, -270],
		['.bigSize.variant1', -40, -390, -300, -580, -570]
	]

var setInputBackground = function(){
	userInputBackgroundPosition.each(function(userInputBackgroundPositionElem){
		var userInputStyle = userInputBackgroundPositionElem[0];
		var userInputHeightGap = userInputBackgroundPositionElem[1];
		var userInputStyleGap = userInputBackgroundPositionElem[2];
		var leftPartPosX = userInputBackgroundPositionElem[3];
		var rightPartPosX = userInputBackgroundPositionElem[4];
		var rightPartPictoPosX = userInputBackgroundPositionElem[5];
		$$(userInputStyle).each(function(userInputStyleElem){
			var defaultBackgroundPostion = function(){
				userInputStyleElem.getChildren('.leftPart').setStyle('background-position', leftPartPosX + 'px ' + (0 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart').setStyle('background-position', rightPartPosX + 'px ' + (0 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart.picto').setStyle('background-position', rightPartPictoPosX + 'px ' + (0 + userInputStyleGap) + 'px');
			};
			var overBackgroundPosition = function(){
				userInputStyleElem.getChildren('.leftPart').setStyle('background-position', leftPartPosX + 'px ' + (userInputHeightGap + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart').setStyle('background-position', rightPartPosX + 'px ' + (userInputHeightGap + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart.picto').setStyle('background-position', rightPartPictoPosX + 'px ' + (userInputHeightGap + userInputStyleGap) + 'px');
			};
			var activeBackgroundPosition = function(){
				userInputStyleElem.getChildren('.leftPart').setStyle('background-position', leftPartPosX + 'px ' + (userInputHeightGap*2 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart').setStyle('background-position', rightPartPosX + 'px ' + (userInputHeightGap*2 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart.picto').setStyle('background-position', rightPartPictoPosX + 'px ' + (userInputHeightGap*2 + userInputStyleGap) + 'px');
			};
			var desactivatedBackgroundPosition = function(){
				userInputStyleElem.getChildren('.leftPart').setStyle('background-position', leftPartPosX + 'px ' + (userInputHeightGap*3 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart').setStyle('background-position', rightPartPosX + 'px ' + (userInputHeightGap*3 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart.picto').setStyle('background-position', rightPartPictoPosX + 'px ' + (userInputHeightGap*3 + userInputStyleGap) + 'px');
			};
			var activatedBackgroundPosition = function(){
				userInputStyleElem.getChildren('.leftPart').setStyle('background-position', leftPartPosX + 'px ' + (userInputHeightGap*4 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart').setStyle('background-position', rightPartPosX + 'px ' + (userInputHeightGap*4 + userInputStyleGap) + 'px');
				userInputStyleElem.getChildren('.rightPart.picto').setStyle('background-position', rightPartPictoPosX + 'px ' + (userInputHeightGap*4 + userInputStyleGap) + 'px');
			};

			if(userInputStyleElem.get('class').contains('desactivatedInput')){
				desactivatedBackgroundPosition();
			} else if(userInputStyleElem.get('class').contains('activatedInput')){
				activatedBackgroundPosition();
			} else {
				defaultBackgroundPostion();
				userInputStyleElem.addEvents({
					'mouseout': function() {
						defaultBackgroundPostion();
					},
					'mouseover': function() {
						overBackgroundPosition();
					},
					'mouseup': function() {
						overBackgroundPosition();
					},
					'mousedown': function() {
						activeBackgroundPosition();
					}
				});
			}
		});
	});
};
setInputBackground();

/* ============================================================ */
/* ============================== Size-up elements taking in account borders and paddings */
/* ============================================================ */

	var genericHiddenInputAreas = $$('._genericHiddenInputArea');
	var genericHiddenLabels = $$('._genericHiddenLabel');
	var genericHiddenInputs = $$('._genericHiddenInput');
	var genericHiddenTextareas = $$('._genericHiddenTextarea');
	var genericHiddenTextareasMaxW = $$('._genericHiddenTextareaMaxW');
	var genericHiddenTextareasMaxH = $$('._genericHiddenTextareaMaxH');
	var genericHiddenSelect = $$('._genericHiddenSelect');
	var genericInputAreaWidth = genericHiddenInputAreas.getProperty('value'); // 50%,, 500, etc.
	var genericLabelWidth = genericHiddenLabels.getProperty('value'); // 20%,,60,120,90
	var genericInputWidth = genericHiddenInputs.getProperty('value');
	var genericTextareaWidth = genericHiddenTextareas.getProperty('value');
	var genericTextareaMaxWidth = genericHiddenTextareasMaxW.getProperty('value');
	var genericTextareaMaxHeight = genericHiddenTextareasMaxH.getProperty('value');
	var genericSelectWidth = genericHiddenSelect.getProperty('value');

	var sizeUpStuffs = function(propertyValueArray, targetCase, targetAction, currentElem, currentIndex){
		var sizeElement = function(){
			if(!propertyValueArray[currentIndex].test(/^[0-9]+$/)){
				currentTarget.setStyle('width', propertyValueArray[currentIndex]);
			} else {
				var currentTargetDecoWidth = currentTarget.getComputedSize().computedLeft + currentTarget.getComputedSize().computedRight;
				currentTarget.setStyle('width', propertyValueArray[currentIndex] - currentTargetDecoWidth) + 'px';
			}
		};
		switch(targetCase){
			case 1:
				var currentTarget = currentElem.getParent(targetAction);
				sizeElement();
				break;
			case 2:
				var currentTarget = currentElem.getNext(targetAction);
				sizeElement();
				break;
		}
	};

	genericHiddenInputAreas.each(function(currentElem, currentIndex){
		sizeUpStuffs(genericInputAreaWidth, 1, "", currentElem, currentIndex);
	});
	genericHiddenLabels.each(function(currentElem, currentIndex){
		sizeUpStuffs(genericLabelWidth, 2, ".genericLabel", currentElem, currentIndex);
	});
	genericHiddenInputs.each(function(currentElem, currentIndex){
		sizeUpStuffs(genericInputWidth, 2, ".genericInput", currentElem, currentIndex);
	});
	genericHiddenTextareas.each(function(currentElem, currentIndex){
		sizeUpStuffs(genericTextareaWidth, 2, ".genericTextarea", currentElem, currentIndex);
	});
	genericHiddenSelect.each(function(currentElem, currentIndex){
		sizeUpStuffs(genericSelectWidth, 2, ".genericSelect", currentElem, currentIndex);
	});

	genericHiddenLabels.each(function(genericHiddenLabelsElem, genericHiddenLabelsIndex){
		var targetedGenericLabel = genericHiddenLabelsElem.getNext('.genericLabel');
	//	targetedGenericLabel.getNext('.genericInfoMini').setStyle('margin-left', genericLabelWidth[genericHiddenLabelsIndex] + 'px');
	});

	genericHiddenTextareas.each(function(genericHiddenTextareasElem, genericHiddenTextareasIndex){
		var targetedGenericTextarea = genericHiddenTextareasElem.getNext('.genericTextarea');
	//	targetedGenericTextarea.setStyles({
	//		'max-width': genericTextareaMaxWidth[genericHiddenTextareasIndex] + 'px',
	//		'max-height': genericTextareaMaxHeight[genericHiddenTextareasIndex] + 'px'
	//	});
	});

/* ============================================================ */
/* ============================== generic effects */
/* ============================================================ */

/* ============================== OverText */

//$('alertMsg1').set('html', indexHeaderSection1.getStyle('-webkit-transform'));

	/* ============================== Animate progress status */
	indexCheckProgress.addEvent('click', function(){
		indexWorkInProgress2.tween('height', [indexWorkInProgress2.getStyle('height'), 200]);
		indexCheckProgress.addClass('activatedInput');
		indexCheckProgress.tween('bottom', [indexCheckProgress.getStyle('bottom'), 290]);
	});

	/* ============================== Fade effect over _indexHeaderHoverBackground elements */
	if(!Browser.ie){
		$$('._indexHeaderHoverBackground').addEvents({
			'mouseover': function(event) {
				(event).stop();
				indexHeaderHoverBackground.fade('in');
			},
			'mouseout': function(event) {
				(event).stop();
				indexHeaderHoverBackground.fade('out');
			}
		});
	} else {
		$$('._indexHeaderHoverBackground').addEvents({
			'mouseover': function(event) {
				(event).stop();
				indexHeaderHoverBackground.fade('show');
			},
			'mouseout': function(event) {
				(event).stop();
				indexHeaderHoverBackground.fade('hide');
			}
		});
	}

	/* ============================== Flip animations */
	if(Browser.safari || Browser.chrome){
		$('indexAboutUsMenuLink2').addEvent('click', function(event){ //Displaying Contact area --> So masking Intro area
			event.stop();
			new Fx.Tween(indexHeaderSection2, {
				onStart: function(){
					indexHeaderSection2.addClass('indexHeaderBackground');
					indexHeaderSection2.removeClass('displayNone');
					indexHeaderBackgroundHole.fade('show'); // Mask Æpyornis's Eggs
					indexHeaderSection1.addClass('indexHeaderBackground');
					indexHeaderSection1.setStyle('-webkit-transform', 'rotateY(-180deg)'); //Mask Intro area by rotationY
				},
				onComplete: function(){
					indexHeaderSection2.removeClass('indexHeaderBackground');
					indexHeaderBackgroundHole.fade('hide'); // Mask Æpyornis's Eggs
					indexHeaderSection1.addClass('displayNone');
					indexHeaderSection1.removeClass('indexHeaderBackground');
//					indexHeaderMenuPrevNext.each(function(elem){ // Display Prev and Next links
//						elem.fade('in');
//					});
					allGenericTextInputs.each(function(genericInputElem){ // Display OverText only onComplete (because of display bug)
						new OverText($(genericInputElem));
					});
					$$('label.overTxtLabel').each(function(elem){ // Display OverTextLabel
						elem.fade('in');
					});
				},
				duration: 1000
			}).start('-webkit-transform', 'rotateY(0deg)'); //Display Contact area by rotationY
			// added by Fred in order to show the "cansel" and "send" buttons next time the panel is shown
			$('closeContact').addClass('displayNone');
			$('closeContact').fade('out');
			$('cancelContact').fade('show');
			$('sendContact').fade('show');
		});

		[$('cancelContact'), $('closeContact')].each(function(elem){
			elem.addEvent('click', function(event){ //Displaying Intro area --> So masking Contact area
				event.stop();
				new Fx.Tween(indexHeaderSection1, {
					onStart: function(){
						indexHeaderSection1.addClass('indexHeaderBackground');
						indexHeaderSection1.removeClass('displayNone');
						indexHeaderBackgroundHole.fade('show'); // Display Æpyornis's Eggs
						indexHeaderSection2.addClass('indexHeaderBackground');
						indexHeaderSection2.setStyle('-webkit-transform', 'rotateY(180deg)'); //Mask Intro area by rotationY
//						indexHeaderMenuPrevNext.each(function(elem){ // Mask Prev and Next links
//							elem.fade('out');
//						});
					},
					onComplete: function(){
						indexHeaderSection1.removeClass('indexHeaderBackground');
						indexHeaderBackgroundHole.fade('hide'); // Mask Æpyornis's Eggs
						indexHeaderSection2.addClass('displayNone');
						indexHeaderSection2.removeClass('indexHeaderBackground');
					},
					duration: 1000
				}).start('-webkit-transform', 'rotateY(0deg)'); //Display Contact area by rotationY
			});
		});

	} else {
		$('indexAboutUsMenuLink2').addEvent('click', function(event){ //Displaying Contact area --> So masking Intro area
			event.stop();
			indexHeaderSection1.addClass('displayNone');
			indexHeaderSection2.removeClass('displayNone');
		});
	
		[$('cancelContact'), $('closeContact')].each(function(elem){
			elem.addEvent('click', function(event){ //Displaying Intro area --> So masking Contact area
				event.stop();
				indexHeaderSection1.removeClass('displayNone');
				indexHeaderSection2.addClass('displayNone');
			});
		});
	}

/* ============================================================ */
/* ============================== Form validator & various */
/* ============================================================ */

	/* ============================== Add Mootools class 'required' to childrens requiredData Inputs */
	requiredData.each(function(requiredDataElem){
		var requiredDataTarget = requiredDataElem.getChildren(['.genericInput', '.genericTextarea']);
		requiredDataTarget.each(function(requiredDataTargetElem){
			requiredDataTargetElem.addClass('required');
		});
	});

	/* ============================== Animate required input background */
	var requiredPictoWidth = 33;
	var requiredInputFocusPaddingRight = 10; // D
	requiredData.each(function(requiredDataElem){
		var requiredDataTarget = requiredDataElem.getChildren(['.genericInput', '.genericTextarea']);
		requiredDataTarget.each(function(requiredDataTargetElem){
			var requiredDataTargetElemTotalWidth = requiredDataTargetElem.getComputedSize().totalWidth; // A
			var requiredDataTargetElemWidth = requiredDataTargetElem.getComputedSize().width; // B
			var requiredDataTargetElemPaddingRight = requiredDataTargetElem.getStyle('padding-right').toInt(); // C
			requiredDataTargetElem.addEvents({
				'focus': function(event) {
					(event).stop();
					requiredDataTargetElem.setStyle('padding-right', requiredInputFocusPaddingRight);
					requiredDataTargetElem.setStyle('width', requiredDataTargetElemWidth + requiredDataTargetElemPaddingRight - requiredInputFocusPaddingRight); // B + C - D
					requiredDataTargetElem.tween('background-position', (requiredDataTargetElemTotalWidth - requiredPictoWidth) + ' 2', (requiredDataTargetElemTotalWidth - requiredInputFocusPaddingRight) + ' 2');
				},
				'blur': function(event) {
					(event).stop();
					requiredDataTargetElem.setStyle('padding-right', requiredDataTargetElemPaddingRight);
					requiredDataTargetElem.setStyle('width', requiredDataTargetElemWidth);
					requiredDataTargetElem.tween('background-position', (requiredDataTargetElemTotalWidth - requiredInputFocusPaddingRight) + ' 2', (requiredDataTargetElemTotalWidth - requiredPictoWidth) + ' 2');
				}
			});
		});
	});

	/* ============================== contact Aim */
//	if($('#contactAim option[selected]').get('html') == 'toto'){
//		$('conctactAim').getNext('.genericInfoMini').fade('out');
//	}

	/* ============================== Styling form validation */
	var indexHeaderSection2Form = new Form.Validator($('indexHeaderSection2Form'), {
		serial: false,
		onElementFail: function(currentInput) {
			currentInput.getParent('.genericInputArea').addClass('genericInputAreaAlert');
			currentInput.tween('left', [10, 0]);
		},
		onElementPass: function(currentInput) {
			currentInput.getParent('.genericInputArea').removeClass('genericInputAreaAlert');
		}
	});

	$('sendContact').addEvent('click', function(event){
		//event.stop();
		var prenom = encodeURIComponent(document.contactForm.prenom.value);
		var nom = encodeURIComponent(document.contactForm.nom.value);
		var email = encodeURIComponent(document.contactForm.email.value);
		var sujet = encodeURIComponent(document.contactForm.sujet.value);
		var texte = encodeURIComponent(document.contactForm.texte.value);
		var Cc = document.contactForm.Cc.checked?'1':'';
		var MailingListSignUp = document.contactForm.MailingListSignUp.checked?'1':'';
		var mailRequest = new Request({
			url: '/sendmail.php',
			method: 'post',
			onSuccess: function(respText, respXML) {
				put_stamp(respText == '1');
			},
			onFailure: function(xhr) {
				put_stamp(false);
			}
		});
		var data = 'nom='+nom+'&prenom='+prenom+'&email='+email+'&sujet='+sujet+'&texte='+texte+'&Cc='+Cc+'&MailingListSignUp='+MailingListSignUp;
		mailRequest.send(data);
	});

	/* ============================== simulate validation */
//	$('sendContact2').addEvent('click', function(event){
//		put_stamp(true);
//	});
});

/* ============================================================ */
/* ============================== put stamp if mailSent OK */
/* ============================================================ */
function put_stamp(ok) {
	var indexStamp = $('indexStamp');
	var indexStamper = $('indexStamper');
	if (ok) {
		new Fx.Tween(indexStamp, {
			onStart: function(){
				indexStamp.removeClass('displayNone');
			},
			onComplete: function(){
				var postedDateDM = new Date().format('%d %b');
				var postedDateY = new Date().format('%Y');
				indexStamper.set('html', postedDateDM + '<br />' + postedDateY);
				indexStamper.removeClass('displayNone');
				indexStamper.fade('show');
			},
			duration: 1000
		}).start('opacity', 1);
	}
	$('closeContact').removeClass('displayNone');
	$('closeContact').fade('in');
	$('cancelContact').fade('hide');
	$('sendContact').fade('hide');
}


/* ======================================================================================================= */
/* =============================================== scroll ============================================== */
/* ======================================================================================================= */

window.addEvent('scroll', function() {

	/* ============================== Manage display for the trail mask */
	footPrintsMask();

//	var indexTrailMask = $('indexTrailMask');
//	var windowTotalHeight = window.getScrollSize().y
//	var windowHeight = window.getSize().y;
//	var windowScrollHeight = window.getScroll().y;
//	if ((windowTotalHeight - 100) < windowHeight + windowScrollHeight){
//		indexTrailMask.fade('out');
//	}
//	else {
//		indexTrailMask.fade('show');
//	}

});

/* ======================================================================================================= */
/* =============================================== resize ============================================== */
/* ======================================================================================================= */

window.addEvent('resize', function() {

	//$('alertMsg1').set('html', window.getCoordinates().right);

});
