var windowWidth = $(window).width();

// If they resize the window, we update the width
$(window).resize(function()
{
	var windowWidth = $(window).width();
});

function set_title(page)
{
	var frag = window.location.hash.substr(2);

	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-25607152-1']);
	_gaq.push(['_trackPageview', frag]);
	(function()
	{
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();

	var delim = 'Lubie - ';
	var title = explode(delim, $('title').html());
	
	if ($.browser.msie)
	{ 
		if( $.browser.version == 9.0)
		{
			$('title').html(page + delim + title[1]);
		}
		else
		{
			document.title = page + delim + title[1];
		}
	}
	else
	{
		$('title').html(page + delim + title[1]);
	}
}

// Sammy -------------------------------------------------------------------- */

var app = $.sammy(function()
{
	// Load template engine (www.handlebarsjs.com)
	this.use(Sammy.Handlebars, 'hb');
	
	// So we can keep a reference to 'app' all the time
	var that = this;
	that.controller = null;

/* Transition --------------------------------------------------------------- */
	
	this.bind('EaseOut', function()
	{
		$('html, body').animate({ scrollTop: 0 }, 150);

		// Controller must be the same name as the id of the section (<section id="foo">) in the template
		var controller = that.controller;
		var $controller = $('#'+controller);

		$controller.addClass('old');
		$controller.css('position', 'absolute');

		$controller.find('#banner').stop().animate({top: '0px', left: '-='+windowWidth}, 450);
		$controller.find('#content_wrapper').stop().animate({top: '0px', left: '-='+windowWidth}, 650, function()
		{
			$controller.remove();
		});
	});

	this.bind('EaseIn', function()
	{
		// Add current class to the active link
		$('#top nav ul li').removeClass('current');
		$('#top nav ul li .'+that.controller).parent().addClass('current');

		// If the user spam-click different pages, we fadeout if there is more than 1 transition
		var total_old = $('.old').length
		if(total_old > 1)
		{
			$('.old').fadeOut('normal');
		}
					
		// Controller must be the same name as the id of the section (<section id="foo">) in the template
		var controller = that.controller;
		var $controller = $('#'+controller);

		$('#sections').animate({minHeight: $controller.height()}, 1000);

		$controller.css('position', 'absolute');

		$controller.find('#banner').stop().animate({left: '0px'}, 450);
		$controller.find('#content_wrapper').stop().animate({left: '0px'}, 900, function()
		{
			// Put it back to relative so it has a height
			$('#'+controller).css('position', 'relative');
		});
	});
	
	this.bind('ShowLoading', function(){
		$("#content-loading").fadeIn('fast');
	});
	
	this.bind('HideLoading', function(){
		$("#content-loading").fadeOut('fast');
	});

/* Home --------------------------------------------------------------------- */

	this.get('#!/accueil', function() 
	{
		this.trigger('EaseOut');

		that.controller = 'accueil';
		set_title('');

		// render the template and pass it through handlebars
		this.render('templates/accueil.php').then(function()
		{
			// Put the new section in a var and then position it outside of the screen 
			//before showing it, otherwise it was flicking for 1/2 sec.
			var html = $(innerShiv(this.content, false));

			// Position it
			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			// Add it
			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			// Re-call its javascript
			this.trigger('accueilAfter');
		});
	});

	// All the javascript of the page need to be called each time the home is called
	// since there is new html nodes each time
	this.bind('accueilAfter', function()
	{
		/* Latest news ------------------------------------------------------ */
		
		//get latest news async
		$.ajax({
			url:"ajax/news.php",
			type:'POST',
			data: 'ppp=10',
			global: true,
			async: true,
			cache: false,
			dataType: 'text',
			success: function(data)
			{
				data = $.trim(data);
				
				$("#latest > .roll > .articles").html(data);
				
				//hide loading
				$("#loading-latest").fadeOut('fast');
				
				//animate carousel
				$('#latest .roll').slides(
				{
					container: 'articles',
				    play: 4000,
				    pause: 3500,
				    slideSpeed: 500,
				    hoverPause: true,
				    generateNextPrev: false,
				    generatePagination: false
				});
			},
			error: function()
			{
				$("#latest > .roll > .articles").html('<article class="post"><h2><a>Aucun billet de blogue</a></h2></article>');
				$("#latest > .roll > .pagination").animate({'opacity': 0}, 'fast'); //to keep the object
				$("#loading-latest").fadeOut('fast');
			}
		});
		
		/* Showreel --------------------------------------------------------- */
		
		$('.showreel .view').css('opacity', 0);

		$('.showreel').hover(function()
		{
			$('.showreel .title, .showreel .dash, .showreel .desc, .showreel .lubie, .showreel .def').stop().animate({ opacity: 0.55 }, 150);
			$('.showreel .view').stop().animate({width: '251', opacity: 1}, 150);
			
		}, function()
		{
			$('.showreel .title, .showreel .dash, .showreel .desc, .showreel .lubie, .showreel .def').stop().animate({ opacity: 1.0 }, 150);
			$('.showreel .view').stop().animate({width: '0', opacity: 0}, 150);
		});

		$('.showreel a').colorbox(
		{
			iframe:true, 
			innerWidth:660, 
			initialWidth:660, 
			innerHeight:368, 
			initialHeight: 368, 
			opacity:0.90, 
			top:118, 
			transition:'fade',
			fixed: true
		});

		$(document).bind('cbox_complete', function()
		{
			$('#logo a').hide();
			$('#container').prepend('<img src="assets/images/logo.png" alt="Lubie" id="logo_overlay" />');
		});

		$('#container').click(function()
		{
			$('.showreel a').colorbox.close();
		});

		$(document).bind('cbox_cleanup', function()
		{
			$('#logo a').show();
			$('#logo_overlay').remove();
		});

		$(document).bind('cbox_closed', function()
		{
			$('#colorbox').css({marginLeft: '0'});
		});

		$('.showreel a').click(function()
		{
			$('#colorbox').css({marginLeft: '139px'});
			$('html, body').scrollTop(0);
		});

		/* Featured projects fade ------------------------------------------- */

		$('#featured article a').hover(function()
		{
			var $more = $(this).parents('article').find('.read_more span');

			if ($more.is(':animated'))
			{
				$more.stop().fadeTo(250, 1);
			} 
			else 
			{
				$more.fadeTo(250, 1);
			}

			var $monochrome = $(this).parents('article').find('.monochrome');

			if ($monochrome.is(':animated'))
			{
				$monochrome.stop().fadeTo(250, 0);
			} 
			else 
			{
				$monochrome.fadeTo(250, 0);
			}
		},
		function()
		{
			var $more = $(this).parents('article').find('.read_more span');

			if ($more.is(':animated'))
			{
				$more.stop().fadeTo(250, 0);
			} 
			else 
			{
				$more.fadeTo(250, 0);
			}

			var $monochrome = $(this).parents('article').find('.monochrome');

			if ($monochrome.is(':animated'))
			{
				$monochrome.stop().fadeTo(250, 1);
			} 
			else
			{
				$monochrome.fadeTo(250, 1);
			}
		});

		/* Latest news pagination effect ------------------------------------ */

		$('#latest .pagination .prev').hover(function()
		{
			$(this).parent().find('.hover').css('right', '-21px');
			$(this).parent().find('.hover').stop().animate({ right: '+=21' }, 150);
		},
		function()
		{
			$(this).parent().find('.hover').stop().animate({ right: '-=21' }, 150);
		});	

		$('#latest .pagination .next').hover(function()
		{
			$(this).parent().find('.hover').css('left', '-21px');
			$(this).parent().find('.hover').stop().animate({ left: '+=21' }, 150);
		},
		function()
		{
			$(this).parent().find('.hover').stop().animate({ left: '-=21' }, 150);
		});
	});

/* Portfolio ---------------------------------------------------------------- */
	
	this.get('#!/portfolio', function()
	{
		this.trigger('EaseOut');

		that.controller = 'portfolio';
		set_title('Portfolio | ');

		// render the template and pass it through handlebars
		this.render('templates/portfolio.php').then(function()
		{
			var html = $(innerShiv(this.content, false));

			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			this.trigger('portfolioAfter');
		});
	});

	this.bind('portfolioAfter', function()
	{
		$('#banner ul li a').hover(function()
		{
			var $that = $(this);

			$that.find('.box').stop().animate(
			{
				bottom: '-755px',
				right: '-680px'
			}, 350, function()
			{
				$that.find('.box span').fadeIn('fast');
			});
		},function()
		{
			var $that = $(this);

			$that.find('.box span').fadeOut(80);

			$that.find('.box').stop().animate(
			{
				bottom: '-950px',
				right: '-960px'
			}, 350);
		});

		$('#pucks li').hover(function()
		{
			$(this).find('div').stop().fadeTo(250, 1);
		},function()
		{
			$(this).find('div').stop().fadeTo(250, 0);
		});

		var delay = 0;
		$('#pucks .more a').click(function()
		{
			$('#pucks .more').fadeOut(250, function()
			{
				$('#pucks li.hide').each(function()
				{
					$(this).delay(delay).fadeIn(100);
					delay += 200;
				});
			});

			return false;
		});
	});

/* Single client ------------------------------------------------------------ */

	this.get('#!/portfolio/:name', function()
	{
		this.trigger('EaseOut');

		that.controller = 'client';

		if(this.params['name']  == 'ericsalvail')
		{
			set_title('Éric Salvail | Portfolio | ');
		}
		else if(this.params['name']  == 'jeuxducanada')
		{
			set_title('Jeux du Canada 2013 | Portfolio | ');
		}
		else if(this.params['name']  == 'mesbobettes')
		{
			set_title('Mesbobettes.ca | Portfolio | ');
		}
		else if(this.params['name']  == 'portetoncasque')
		{
			set_title('Porte ton casque - Ville de Sherbrooke | Portfolio | ');
		}
		else if(this.params['name']  == 'phoenix')
		{
			set_title('Le phœnix de Sherbrooke | Portfolio | ');
		}
		else
		{
			set_title('Client | ');
		}

		// render the template and pass it through handlebars
		this.render('templates/clients/' + this.params['name'] + '.php').then(function()
		{
			var html = $(innerShiv(this.content, false));

			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			this.trigger('clientAfter');
		});
	});

	this.bind('clientAfter', function()
	{
		$('#gallery a').colorbox({rel:'client'});
		$('#features ul:first').find('li:first').css('background-position', 'bottom left');

		$('#client #banner').slides(
		{
			container: 'roll',
		    play: 4000,
		    pause: 3500,
		    slideSpeed: 500,
		    hoverPause: true,
		    generateNextPrev: false,
		    pagination: true,
		    generatePagination: false
		});

		// smooth scroll to making of
		$('.view_making_of span').click(function()
		{
			$('html,body').animate({scrollTop:$('#making_of').offset().top - 180}, 250);
		});
	});

/* Services ----------------------------------------------------------------- */
	
	this.get('#!/services', function()
	{
		this.trigger('EaseOut');

		that.controller = 'services';
		set_title('Services | ');

		// render the template and pass it through handlebars
		this.render('templates/services.php').then(function()
		{
			var html = $(innerShiv(this.content, false));

			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			this.trigger('servicesAfter');
		});
	});

	this.bind('servicesAfter', function()
	{
		$('#steps_titles span').hover(function()
		{
			step = $(this);
			$('#steps .' + $(this).attr('class')).addClass('hover');
			$('#steps .'  + $(this).attr('class')).animate({backgroundPosition: '0 0', paddingLeft: '5px'}, {duration: 150});
		}, function()
		{
			$('#steps .'  + $(this).attr('class')).animate({backgroundPosition: '-300 0', paddingLeft: '0'}, {duration: 150}, function()
			{ 
				$('#steps .' + $(this).attr('class')).removeClass('hover');
			});
		});

		$('.tags span').hover(function()
		{
			$("#"+$(this).attr('class')).stop().fadeTo(250, 1);
		}, function()
		{
			$("#"+$(this).attr('class')).stop().fadeOut(250);
		});
	});

/* Team --------------------------------------------------------------------- */
	
	this.get('#!/equipe', function()
	{
		this.trigger('EaseOut');

		that.controller = 'equipe';
		set_title('Équipe | ');

		// render the template and pass it through handlebars
		this.render('templates/equipe.php').then(function()
		{
			var html = $(innerShiv(this.content, false));

			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			this.trigger('equipeAfter');
		});
	});

	this.bind('equipeAfter', function()
	{
		var current = '';
		$('#faces li a').click(function()
		{
			$('html,body').animate({scrollTop:$('#content').offset().top - 180}, 250);

			var person = $(this).attr('id');

			$('#faces li a').removeClass('selected');
			$('#faces li a span').hide();
			$(this).addClass('selected');

			if(current != person)
			{
				current = person;

				$('#person *').fadeOut('normal', function()
				{
					$('#person').hide();

					$.get('templates/employes/'+person+'.php',
					function(data)
					{
						$('#person').html(data);
						$('#person').fadeIn();
					});
				});	
			}

			return false;
		});

		$('#faces li').addClass('current');

		$('#faces li a').hover(function()
		{
			$(this).parent().stop().fadeTo(350, 1);
			$(this).find('span').stop().fadeTo(350, 1);
		}, function()
		{
			var $li = $(this).parent();

			if($li.hasClass('current'))
			{
				$li.stop().fadeTo(350, 1);	
			}
			else
			{
				$li.stop().fadeTo(350, 0.5);	
			}

			if(!$(this).hasClass('selected'))
			{
				$(this).find('span').stop().fadeTo(350, 0);	
			}
		});

		$('#select_dept ul li span').hover(function()
		{
			var $li = $(this).parent();
			$('#select_dept ul li span').css('color', '#3d0f65');

			if($li.hasClass('tous'))
			{
				$(this).parents('ul').css('background-position', '0 0');

				$('#faces li').stop().fadeTo(200, 1);
				$('#faces li').addClass('current');
			}
			else if($li.hasClass('service_conseil'))
			{
				$(this).parents('ul').css('background-position', '0 -33px');
				$(this).css('color', '#fff');

				$('#faces li').not('.service_conseil').removeClass('current').stop().fadeTo(200, 0.5);
				$('#faces li.service_conseil').addClass('current').stop().fadeTo(200, 1);
			}
			else if($li.hasClass('developpement'))
			{
				$(this).parents('ul').css('background-position', '0 -66px');
				$(this).css('color', '#fff');

				$('#faces li').not('.developpement').removeClass('current').stop().fadeTo(200, 0.5);
				$('#faces li.developpement').addClass('current').stop().fadeTo(200, 1);
			}
			else if($li.hasClass('creation'))
			{
				$(this).parents('ul').css('background-position', '0 -99px');
				$(this).css('color', '#fff');

				$('#faces li').not('.creation').removeClass('current').stop().fadeTo(200, 0.5);
				$('#faces li.creation').addClass('current').stop().fadeTo(200, 1);
			}
		});
	});

/* Contact ------------------------------------------------------------------ */
	
	this.get('#!/contact', function()
	{
		this.trigger('EaseOut');

		that.controller = 'contact';
		set_title('Contactez-nous | ');

		// render the template and pass it through handlebars
		this.render('templates/contact.php').then(function()
		{
			var html = $(innerShiv(this.content, false));

			html.find('#banner, #content_wrapper').css(
			{
				left: windowWidth
			});

			html.prependTo('#sections');
			
			// Add effects from right to left
			this.trigger('EaseIn');

			this.trigger('contactAfter');
		});
	});

	this.bind('contactAfter', function()
	{
		// Insert email by JS to try prevent spam
		$('.email_js').attr('href','mailto:info@lubie.co');
		$('.email_js').html('info@lubie.co');

		$('#contact form').validate(
		{
			rules:
			{
				fullname: "required", 
				organisation: "required",
				telephone: "required",
				email:
				{ 
					required: true, 
					email: true
				},
				message: "required"
			}, 
			messages:
			{ 
				fullname: "Ce champs est obligatoire", 
				organisation: "Ce champs est obligatoire",
				telephone: "Ce champs est obligatoire",
				email:
				{ 
					required: "Ce champs est obligatoire", 
					email: "Le courriel doit être valide"
				},
				message: "Ce champs est obligatoire"				
			},
			invalidHandler: function(form, validator) {
			  var errors = validator.numberOfInvalids();
				  if (errors) {
						$('#contact #form #message-container').html('');
						$('#contact #form #message-container').append('<div class="errormessage">Vérifier vos champs de saisie</div>');
					
					//$('<div class="success">Merci, vous recevrez de nos nouvelles très bientôt!</div>').insertBefore('#contact #form form');
						$('#contact #form .errormessage').slideDown(200);
				  } else {
					    $('#contact #form  #message-container').html('');
						$("#contact #form .errormessage").hide();
				  }
			},			
			submitHandler: function(form)
			{
				$fullname = $('#fullname');
				$organisation = $('#organisation');
				$email = $('#email');
				$telephone = $('#telephone');
				$message = $('#message');

				$.post('ajax/contact.php',
				{
					fullname: $fullname.val(), 
					organisation: $organisation.val(),
					email: $email.val(), 
					telephone: $telephone.val(),
					message: $message.val()
				},
				function(data)
				{
					$fullname.val('');
					$organisation.val('');
					$email.val('');
					$telephone.val('');
					$message.val('');
					
					$('#contact #form #message-container').html('');
					$('#contact #form #message-container').append('<div class="success">Merci, vous recevrez de nos nouvelles très bientôt!</div>');
					
					//$('<div class="success">Merci, vous recevrez de nos nouvelles très bientôt!</div>').insertBefore('#contact #form form');
					$('#contact #form .success').slideDown(200);
				});
			}
		});
	});

/* 404 ---------------------------------------------------------------------- */

	this.notFound = function()
	{
		window.location.href = '404.html';
	}
});

