var mouseMoved = false;

// cube infos variables
var currentFace;
var $cube = $('#cube');
var $container = $('#container');
// parallax variables
var desktopDevices = jQuery.browser.mobile ? false : true;
var mouseX = 0;
var mouseY = 0;
var rotateXpourcent = 0;
var rotateYpourcent = 0;
var rotation = {
	Y : 0,
	X : 0
};

Modernizr.load({
  test: jQuery.browser.mobile,
  yep: 'js/mylibs/jquery.animate-enhanced.min.js'
});

SWFAddress.addEventListener(SWFAddressEvent.EXTERNAL_CHANGE, handleChange);
SWFAddress.addEventListener(SWFAddressEvent.INIT, handleChange);
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);

$(document).ready(function () {
	$document = $(this);

	if(!Modernizr.csstransforms3d)
	{
		$('#supported').on('click', function(){ $(this).fadeOut(); });
	}
	else
	{
		if(desktopDevices)
		{
			$(document.documentElement).on('keydown', keyboard);
			$(this).on('mousemove', parallax);
			$(this).on('mousemove', mousePosition);
		}
		else
		{
			$('header').removeClass('notouch');
			$container.on('touchstart', mousedown);
			$container.on('touchmove', mousemove);
			$container.on('touchend', mouseend);
		}
	}
	
	updateCurrentFace();
	faceOffset();
	formInit();
	
	if($.cookie('dealer_de_talents') == null)
		$('#touchit img').doTimeout(500, interactiveMessage);

	$(window).on('resize', function(){
		var marginTop = ($(window).height()-$('#container').height())/2;
		if(marginTop < -90)
		marginTop = -90;
		$('#container').css('margin-top', marginTop);
	});

	$(window).resize();
});

/**
	SWFaddress change event handler
**/
var arPath;
var path;
var loaded = false;
var target;

function handleChange(event)
{
	if(event)
		path = event.path;

	if(path == "/")
		path = "/quisommesnous";
	
	arPath = path.split("!");
	
	if (path.substr(path.length - 1) != '/') {
		path += '/';
	}
	
	arPath = path.split("/");

	target = arPath[1];

	$('header a').removeClass('selected');
	$('header li.'+target+' a').addClass('selected');

	if(event.type == 'init' || event.type == 'externalChange')
		goTo(target);
}

function mousePosition(e){
	if(desktopDevices){
		mouseMoved = true;
		if(mouseX == e.pageX && mouseY == e.pageY)
			return;
		mouseX = e.pageX;
		mouseY = e.pageY;
		
		var mousePositionPourcentX  = (mouseX - $document.width()/2) / $document.width();
		var mousePositionPourcentY  = (mouseY - $document.height()/2) / $document.height();
		rotateXpourcent				= (mousePositionPourcentY*360) / 100;
		rotateYpourcent				= -(mousePositionPourcentX*360) / 100;
	}
};

function parallax(e){
	if(desktopDevices){
		faceOffset();
		
		$cube.css({'webkitTransitionDuration':'0s','-webkit-transform':'translateZ(-600px) ' + rotateAxis()});

		if(currentFace == 'quisommesnous')
			$('#raoul_shadow').css({'-webkit-transform': 'rotateZ('+(rotateYpourcent)+'deg) rotateX('+rotateXpourcent*10+'deg)', 'webkit-transform-origin':'50% 100%'});
	}
};

function faceOffset(){
	if(currentFace == 'quisommesnous'){
		rotation.Y = 0;
		rotation.X = 0;
	}else if(currentFace == 'notredemarche'){
		rotation.Y = 90;
		rotation.X = 0;
	}else if(currentFace == 'notrechampdaction'){
		rotation.Y = -90;
		rotation.X = 0;
	}else{
		rotation.Y = 0;
		rotation.X = -90;
	}
}

function updateCurrentFace(){
	currentFace = $cube.attr('class').substr(5);

	if(currentFace == "notredemarche")
		$('body').addClass('animLueur');
	else
		$('body').removeClass('animLueur');

	$('#cube > div').removeClass('active');
	$('#'+currentFace).addClass('active');
}

function rotateAxis(){
	var rotateAxis = rotation.X == 0 ? 'rotateX('+(rotateXpourcent+rotation.X)+'deg) rotateY('+(rotateYpourcent+rotation.Y)+'deg)' : 'rotateX('+(rotateXpourcent+rotation.X)+'deg) rotateZ('+(rotateYpourcent+rotation.Y)+'deg)';
	return rotateAxis;
};

function goTo(face){
	if(currentFace == face)
		return;
	
	$document.off('mousemove', parallax);

	$cube.attr('style','').css('webkitTransitionDuration','1s').removeClass().addClass('goto_'+face);

	$('#cube > div').css('webkitTransitionDuration','0s');
	$('#'+currentFace).stop(false, true).animate({opacity:0}, 700);
	$('#'+face).stop(false, true).animate({opacity:1}, 1000);
	// $('#'+currentFace).stop(false, true).fadeOut(700);
	// $('#'+face).stop(false, true).fadeIn(1400);
	updateCurrentFace();
	faceOffset();

	$cube.one('webkitTransitionEnd', function(){
		if(desktopDevices){
			$(this).css({'webkitTransitionDuration':'0.4s','-webkit-transform':'translateZ(-600px) ' + rotateAxis()});
			$document.on('mousemove', parallax);
		}
		SWFAddress.setValue(face);
	});
	return face;
}

function backTo(from, to){
	$document.off('mousemove', parallax);
	$cube.attr('style','-webkit-transition-property: -webkit-transform; -webkit-animation: from_'+from+'_to_'+to+' 1.5s;').css('webkitTransitionDuration','1s').removeClass().addClass('goto_'+to);
	// $('#'+from).doTimeout(500, function(){$('#'+from).fadeOut(700)});
	// $('#'+to).doTimeout(500, function(){$('#'+to).fadeIn(1400)});
	$('#cube > div').css('webkitTransitionDuration','0s');
	$('#'+from).doTimeout(500, function(){$('#'+from).animate({opacity:0}, 700)});
	$('#'+to).doTimeout(500, function(){$('#'+to).animate({opacity:1}, 1400)});
	updateCurrentFace();
	faceOffset();

	$cube.one('webkitAnimationEnd', function(){
		$(this).css({'webkitTransitionDuration':'0s','-webkit-transform':'translateZ(-600px) ' + rotateAxis()});

		// $(this).css({'webkitTransitionDuration':'0.4s','-webkit-transform':'translateZ(-600px) ' + rotateAxis()});
		$document.on('mousemove', parallax);
		SWFAddress.setValue(to);
	});
	return to;
}

//Menu navigation
$('header ul a, header #logo').on('click', function(e){
	e.preventDefault();
	goTo($(this).attr('href').split('#/')[1]);
});
/*$('header ul a').click(function(e){
	var href = this.href.split('#')[1];
	if (href == $('#cube').attr('class').substr(5))
		return;
	
	//matrix = new WebKitCSSMatrix($('#'+$(this).text()).css('-webkit-transform'));
	//$('#cube').css('-webkit-transform', matrix.rotate('270deg'));
	$document.unbind('mousemove', parallax);

	$('#cube').attr('style','').removeClass().addClass('goto_'+target);
	$('#'+currentFace).fadeOut(700);
	$('#'+target).fadeIn(1000);
	updateCurrentFace();
	faceOffset();

	//setTimeout(function(){$document.bind('mousemove', parallax);},1000);
	if(useParallax){
		$('#cube').one('webkitTransitionEnd', function(){
			$(this).attr('style','-webkit-transition-duration:0.5s;')
				   .css({'-webkit-transform':'translateZ(-600px) ' + rotateAxis()});
			$document.bind('mousemove', parallax);
		});
	}
});*/

//Keyboard navigation
function keyboard(e) {
	if(!mouseMoved)
		return;

	$(document.documentElement).off('keydown', keyboard);
	$(document.documentElement).one('keyup', function(){
		$(document.documentElement).on('keydown', keyboard);
	});
	
	var charCode = event.which || event.keyCode || event.charCode;
	var up = 38;
	var down = 40;
	var right = 39;
	var left = 37;

	switch(charCode){
		case up:
			e.preventDefault();
			currentFace == "contacteznous" ? backTo("contacteznous","quisommesnous") : goTo("contacteznous");
		break;
		case down:
			e.preventDefault();
			if(currentFace == "contacteznous"){
				goTo("quisommesnous");
			}else if(currentFace == "notrechampdaction"){
				backTo("notrechampdaction","contacteznous");	
			}else if (currentFace == "quisommesnous"){
				backTo("quisommesnous","contacteznous");
			}else if (currentFace == "notredemarche"){
				backTo("notredemarche","contacteznous");
			}
		break;
		case left:
			e.preventDefault();
			if(currentFace == "notredemarche"){
				backTo("notredemarche","notrechampdaction");
			}else if(currentFace == "quisommesnous"){
				goTo("notredemarche");
			}else if(currentFace == "contacteznous"){
				goTo("notredemarche");
			}else if(currentFace == "notrechampdaction"){
				goTo("quisommesnous");
			}
		break;
		case right:
			e.preventDefault();
			if(currentFace == "notrechampdaction"){
				backTo("notrechampdaction","notredemarche");
			}else if(currentFace == "quisommesnous"){
				goTo("notrechampdaction");
			}else if(currentFace == "contacteznous"){
				goTo("notrechampdaction");
			}else{
				goTo("quisommesnous");
			}
		break;
	};

	faceOffset();
};

function formInit(){
	$('form span').click(function(){
		$(this).hide();
		$(this).siblings('input').focus();
	});

	$('form input, form textarea').focus(function(){
		$(document.documentElement).off('keydown', keyboard);

		$(this).siblings('span').hide();
	});

	$('form input, form textarea').blur(function(){
		$(document.documentElement).on('keydown', keyboard);

		if($(this).val() == "")
			$(this).siblings('span').show();
	});

	$('#form').validate();
	$('#form').ajaxForm({success: showResponse}); 
	
	function showResponse(data)  {
		if(!data.error){
			$('label.error').fadeOut();
			$('#form').animate({'top':'-800px'}, function(){
				$(this).hide();
				$('#sent').fadeIn();
			});
		}
	}
}


/* Touch gestures */
var inGesture = false;
var matrix;

var originalX = 0;
var originalY = 0;

var deltaY = 0;
var deltaX = 0;

var totalDeltaY = 0;
var totalDeltaX = 0;

var DELTA_X_OFFSET = 40;
var DELTA_Y_OFFSET = 30;

var alphaY = 0;
var alphaX = 0;

var oldDeltaY = 0;
var oldDeltaX = 0;

// $container.on('touchcancel', function() {
// 	inGesture = false;
// });


function mousedown(event) {
	//console.log('mouse down');
	var e = event.originalEvent;

	if(e.touches.length > 1)
		return;

	inGesture  = true;
	originalX = (e.touches) ? e.touches[0].pageX : e.pageX;
	originalY = (e.touches) ? e.touches[0].pageY : e.pageY;
	
	if(e.touches && e.touches.length!=1) {
		inGesture = false;
	}
	
	$cube[0].style.webkitTransitionDuration = '0s';
	$('#cube > div').css('webkitTransitionDuration','0s');
	matrix = getMatrix();
	$cube.css({'-webkit-transform' : matrix});
	$('#cube > div:not(.active)').stop();
};

function mousemove(event) {
	var e = event.originalEvent;
	e.preventDefault();

	$cube[0].style.webkitTransitionDuration = '0s';
	
	var currentX = (e.touches) ? e.touches[0].pageX : e.pageX;
	var currentY = (e.touches) ? e.touches[0].pageY : e.pageY;

	deltaY = -(currentY-originalY) / 13;
	deltaX = (currentX-originalX) / 15;

	$cube.css({'-webkit-transform':matrix.rotate(deltaY, deltaX)});

	alphaY = deltaY/100*2;
	alphaX =  deltaX/100*2;
	
	$('#'+currentFace).css('opacity' , 1-Math.abs(alphaX));

	switch(currentFace){
		case 'quisommesnous':
				$('#notredemarche').css({'opacity' : alphaX});
				$('#notrechampdaction').css({'opacity' : -alphaX});
				//$('#contacteznous').css({'opacity' : -alphaY});
		break;
		case 'notrechampdaction':
				$('#quisommesnous').css({'opacity' : alphaX});
				// $('#contacteznous').css({'opacity' : -alphaY});
		break;
		case 'notredemarche':
				$('#quisommesnous').css({'opacity' : -alphaX});
				// $('#contacteznous').css({'opacity' : -alphaY});
		break;
		case 'contacteznous':
				$('#notredemarche').css({'opacity' : alphaX});
				$('#notrechampdaction').css({'opacity' : -alphaX});
				$('#quisommesnous').css({'opacity' : alphaY});
		break;
	}
}

function mouseend(event) {
	var e = event.originalEvent;
	if(e.touches.length > 0)
		return;
	$cube[0].style.webkitTransitionDuration = '0.5s';

	var originY = rotation.Y;
	var originX = rotation.X;

	$cube.css({'-webkit-transform':'translate3d(0,0,-600px) rotateX(' + originX + 'deg) rotateY(' + originY + 'deg)' });
	
	$('#cube > div').css({'webkitTransitionProperty':'opacity','webkitTransitionDuration':'0.5s'});
	$('#cube > div:not(.active)').css('opacity','0');
	$('#'+currentFace).css({'opacity' : 1});

	inGesture = false;
	
	if(deltaX >= DELTA_X_OFFSET)
		swipe('left');
	else if(deltaX <= -DELTA_X_OFFSET)
		swipe('right');

	if(deltaY >= DELTA_Y_OFFSET)
		swipe('down');
	else if(deltaY <= -DELTA_Y_OFFSET)
		swipe('up');
}

function getMatrix() {
	var transform = window.getComputedStyle($cube[0]).webkitTransform;
	return matrix = new WebKitCSSMatrix(transform);
}

function swipe(direction) {
	deltaY = 0;
	deltaX = 0;
	inGesture  	= true;

	switch(direction){
		case 'up':
			currentFace == "contacteznous" ? null : touchTo("contacteznous");
		break;
		case 'down':
			if(currentFace == "contacteznous"){
				touchTo("quisommesnous");
			}else if(currentFace == "notrechampdaction"){
				return;	
			}else if (currentFace == "quisommesnous"){
				return;
			}else if (currentFace == "notredemarche"){
				return;
			}
		break;
		case 'left':
			if(currentFace == "notredemarche"){
				return;
			}else if(currentFace == "quisommesnous"){
				touchTo("notredemarche");
			}else if(currentFace == "contacteznous"){
				touchTo("notredemarche");
			}else if(currentFace == "notrechampdaction"){
				touchTo("quisommesnous");
			}
		break;
		case 'right':
			if(currentFace == "notrechampdaction"){
				return;
			}else if(currentFace == "quisommesnous"){
				touchTo("notrechampdaction");
			}else if(currentFace == "contacteznous"){
				touchTo("notrechampdaction");
			}else{
				touchTo("quisommesnous");
			}
		break;
	};

	faceOffset();
};

function touchTo(face){
	if(currentFace == face)
		return;

	$cube.attr('style','').removeClass().addClass('goto_'+face);
	
	$cube.css('webkitTransitionDuration','0.5s');
	
	$('#'+currentFace).css('opacity','0');
	$('#'+face).css('opacity','1');
	
	updateCurrentFace();
	faceOffset();

	$cube.one('webkitTransitionEnd', function(){
		SWFAddress.setValue(face);
	});

	return face;
}

function interactiveMessage(){
	$.cookie('dealer_de_talents', 'visited');
	
	if(desktopDevices)
	{
		$('#keyboard').show().doTimeout(2500, function(){
			$(this).fadeOut();
		});
	}else{
		$('#touchit img').show().animate({left:165}, 400).animate({left:-35}, 400).animate({left:65}, 400, function(){
			$(this).hide();
		});
	}
}
