/* ------------------------------------------------------------------------
	General init
------------------------------------------------------------------------- */

	$(function(){
		backgrounds.init($('.background'));
		footer.init();
	});


/* ------------------------------------------------------------------------
	Class: Homepage
	Description: Handles the homepage gallery
------------------------------------------------------------------------- */

	homepage = {
		init : function(json){
			currentArticle = 0,
			content = json,
			galleryNav = '';
			
			// Build the project navigation
			$('#page > .content article').after('<div class="nav"><ul></ul></div>');
			
			// Preload all images and build the thumbnail navigation
			$(content).each(function(i){
				preload = new Image();
				preload.src = content[i].image;
				
				// Build the gallery
				var thumbnailLink = $('<a />')
									.attr('src','#')
									.click(function(){
										currentArticle = i;
										homepage.changeArticle(currentArticle);
									});
				
				thumbnail = $('<img>').attr({src:content[i].thumbnail,width:74,height:74})
				
				$(thumbnailLink).append(thumbnail);
									
				$('#page > .content .nav ul').append($('<li />').append(thumbnailLink));
			});
			
			// Select the first item
			$('#page > .content .nav li:first').addClass('selected');
			$('#page > .content .nav li:last').addClass('last');
			
			// Bind the click to open the gallery
			$('#page > .content > p a').click(function(){
				homepage.showArticles();
			});
			
			// var randomnumber=Math.floor(Math.random()*(content.length - 1));
			// homepage.changeArticle(randomnumber);
		},
		changeArticle : function(which){
			$('#page > .content .nav li.selected').removeClass('selected');
			$('#page > .content .nav li:eq('+which+')').addClass('selected');
			
			$('#page > .content article h1').text(content[which].title);
			$('#page > .content article p span').text(content[which].description);
			$('#page > .content article p a').attr('href',content[which].url);
			
			// Create new image for cross-fase
			$('.background:first')
				.clone()
				.appendTo('body')
				.hide()
				.css('z-index',1)
				.fadeIn(function(){
					// Remove all the other backgrounds
					$('.background:first').remove();
				});
			$('.background:last img').attr('src',content[which].image);
			$('.background:last a').attr('href',content[which].url);

			Cufon.refresh('h1');

			backgrounds.init($('.background:last'));
		},
		showArticles : function(){
			$('#page > .content .nav').slideToggle('fast');
		}
	}



/* ------------------------------------------------------------------------
	Class: Footer
	Description: Footer actions
------------------------------------------------------------------------- */

	footer = {
		init : function(){
			var maxHeight = 0;
			$('#page > footer section').each(function(){
				maxHeight = ($(this).height() > maxHeight) ? $(this).height() : maxHeight;
			});
			maxHeight += 10;
			
			$('#page > footer')
				.click(function(){
					if($('footer .content').height() <= 0){
						$('footer .content').animate({'height':maxHeight},'fast');
						
						$('html,body').animate({scrollTop: 100000}, 1000);
					}else{
						$('footer .content').animate({'height':0},'fast');
					};
				
					$('footer').toggleClass('open');
				})
				.hover(function(){ clearTimeout(footer_timeout); });
			
			// Prevent the animation for links that goes to other pages
			$('#page > footer a[rel=internal],#page > footer a[target=_blank]').click(function(e){
				e.stopPropagation();
			});
			
			$('#page > footer > nav a').click(function(e){
				e.preventDefault();
			});
			
			// Fix the montreal.ad logo sizer
			$('#montreal_ad img').width(52);
			$('#montreal_ad').show();
		}
	}


/* ---------------------------------------------------------------------------
	Class: Backgrounds
	Description: insert background image and streching within browser viewport
------------------------------------------------------------------------------ */

	backgrounds = {
		init : function(which){
			$(window)
				.unbind('resize')
				.resize(function(){
					backgrounds.resize(which);
				});
			
			backgrounds.resize(which);
			

		},
		resize : function(which) {
			img = $(which).find('img:first');
			
			//Define image ratio
			var ratio = $(img).height()/$(img).width();

			//Gather browser and current image size
			var imagewidth = $(img).width();
			var imageheight = $(img).height();
			var browserwidth = $(document).width();
			var browserheight = $(window).height();

			//Resize image to proper ratio
			if ((browserheight/browserwidth) > ratio){
			    $(which).height(browserheight);
			    $(which).width(browserwidth);
			    $(img).height(browserheight);
			    $(img).width(browserheight / ratio);
			} else {
			    $(which).width(browserwidth);
			    $(which).height(browserheight);
			    $(img).width(browserwidth);
			    $(img).height(browserwidth * ratio);
			}
		}
	};


/* ------------------------------------------------------------------------
	Function: _getScroll
	Description: Returns a json with the scroll values
------------------------------------------------------------------------- */

	function _getScroll(){
		if (self.pageYOffset) {
			return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
		} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
			return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
		} else if (document.body) {// all other Explorers
			return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
		};
	};
	

/* ------------------------------------------------------------------------
	Cookie functions
------------------------------------------------------------------------- */

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}


/* ------------------------------------------------------------------------
	Class: video_player
	Uses: Controls the HTML5 video player.....OH YES!
------------------------------------------------------------------------- */

	var video_player = function(){
		var 
			video_container,
			video_element,
			video_controls,
			video_scrobble_bar,
			video_bar_width,
			video_settings,
			is_ipad = navigator.userAgent.match(/iPad/i) != null,
			is_iphone = navigator.userAgent.match(/iPhone/i) != null;
			playing = false,
			scrobbling = false;
		
		function init(settings){
			video_settings = settings;
			if($.browser.webkit && !is_iphone && !is_ipad) {
				$('<div></div>')
					.addClass('video')
					.appendTo('body')
					.html($(video_settings.element).html())
					.css({
						position: 'absolute',
						top: $(video_settings.element).offset().top,
						left: $(video_settings.element).offset().left,
						'z-index': 10000
					});
				
				video_container = $('.video:last');
				
				$(video_container).append('<a href="#" class="full-button play">Play</a>');
				
				$(video_container)
					.find('.play')
					.click(function(){
						$(this).addClass('loading')
						$(this).removeClass('play');
						_insert_player();
						return false;
					});
				
			}else if(is_iphone || is_ipad){
				video_container = $('.video:last');
				_insert_controlless_player();
			}else{
				$('.video').html('<object width="'+settings.width+'" height="'+settings.height+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+settings.clip_id+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+settings.clip_id+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+settings.width+'" height="'+settings.height+'"></embed></object>');
			}
		}
		
		function _insert_player(){
			$(video_container).find('img:first').remove();
			
			$(video_container).append(' \
				<div class="controls"> \
					<button class="play">Play</button> \
					<div class="bars"> \
						<div class="played"></div> \
						<div class="play-line"></div> \
					</div> \
					<div class="timebox"> \
					00:00 \
					</div> \
					<a href="#" id="fullscreen">Full</a> \
				</div> \
			');
	
			video_controls = $(video_container).find('.controls');
			video_bar_width = $(video_controls).find('.bars').width();
			
			$('<video></video>')
				.attr({
					src: 'http://www.vimeo.com/play_redirect?clip_id='+video_settings.clip_id+'&amp;quality=sd',
					width: video_settings.width,
					height: video_settings.height
				})
				.appendTo($(video_container));
				
			video_element = $(video_container).find('video')[0];
			video_scrobble_bar = $(video_controls).find('.bars');
			
			// Loader display
			readyinterval = setInterval(function(){
				if(video_element.readyState >= 3) {
					clearInterval(readyinterval);
					$(video_container).find('.full-button').fadeOut();
				}
			},1000);
			
			// Bind the events
			$(video_controls).find('.play').unbind('click').click(function(){
				_play(this);
			});
			
			// Fullscreen madness!
			$('#fullscreen').click(function(){ _fullscreen('open'); });
			
			// The seek to time click!
			$(video_controls).find('.bars').click(function(event){
				cur_x = event.clientX-$(this).offset().left;
				
				seek_time = cur_x / $(this).width() * video_element.duration;
				
				video_element.currentTime = seek_time;
			});
			
			// Show/Hide the controls
			$(video_container).hover(function(){
				$(video_controls).fadeIn();
			},
			function(){
				if(playing) {
					$(video_controls).fadeOut();
				}
			});
			
			// The time scrobbling
			// $(video_controls).find('.bars')
			// 	.mousemove(function(event){
			// 		_scrobble(event);
			// 	})
			// 	.mouseout(function(){
			// 		scrobbling = false;
			// 	});
			
			// Play it!
			$(video_controls).find('.play').trigger('click');
		}
		
		function _insert_controlless_player(){
			poster_src = $(video_container).find('img:first').attr('src');
			$(video_container).find('img:first').remove();

			$('<video></video>')
				.attr({
					src: 'http://www.vimeo.com/play_redirect?clip_id='+video_settings.clip_id+'&amp;quality=sd',
					width: video_settings.width,
					height: video_settings.height,
					controls: true,
					poster: poster_src
				})
				.appendTo($(video_container));
		}
		
		function _play(caller){
			playing = true;
			
			$(caller)
				.unbind('click')
				.bind('click',function(){
					_pause(this);
				})
				.text('Pause')
				.removeClass('play')
				.addClass('pause');
				
			video_element.play();
			
			_progress(video_element.currentTime);
		};
		
		function _pause(caller){
			playing = false;
			
			$(caller)
				.unbind('click')
				.bind('click',function(){
					_play(this);
				})
				.text('Play')
				.removeClass('pause')
				.addClass('play');
				
			video_element.pause();
		};
		
		function _progress(time){
			
			if(typeof progress == 'undefined'){
				progress = setInterval(function(){
					_progress(video_element.currentTime);
				},200)
			}
			
			// Update the progress bar
			$(video_controls).find('.played').width(time/video_element.duration*video_bar_width);
			
			// Update the time box
			var minutes = '0' + Math.floor(Math.ceil(video_element.currentTime) / 60);
			var seconds = Math.ceil(video_element.currentTime)%60;
			var seconds = (seconds < 10) ? seconds = '0' + seconds : seconds;
			
			$(video_controls).find('.timebox').text(minutes + ":" + seconds);
			
			// if(!scrobbling) {
			// 	$(video_controls).find('.timebox').css('left',0);
			// 	$(video_controls).find('.timebox div').text(minutes + ":" + seconds);
			// }else{
			// 	$(video_controls).find('.timebox').css('left',cur_x-$(video_scrobble_bar).find('.played').width());
			// }
			
			if (time == video_element.duration) { // Video is done
				clearInterval(_progress);
				$('.pause').trigger('click');
				video_element.currentTime = 0;
			}
		};
		
		function _scrobble(event){
			if(!video_element.duration) return;
			scrobbling = true;

			cur_x = event.clientX-$(video_scrobble_bar).offset().left;
			
			seek_time = Math.ceil(cur_x / $(video_scrobble_bar).width() * video_element.duration);
			
			// Update the time box
			var minutes = Math.floor(Math.ceil(seek_time) / 60);
			var seconds = Math.ceil(seek_time)%60;
			var seconds = (seconds < 10) ? seconds = '0' + seconds : seconds;
			
			$(video_controls).find('.timebox div').text(minutes + ":" + seconds);
			
			$(video_controls).find('.timebox').css('left',cur_x-$(video_scrobble_bar).find('.played').width());

		};
		
		function _fullscreen(state){
			if(state == 'open') {
				video_initial_width = $(video_container).width();
				video_initial_height = $(video_container).height();
				video_initial_top = $(video_container).css('top');
				video_initial_left = $(video_container).css('left');
				
				$(video_container)
					.addClass('fullscreen')
					.animate({
						width: $(window).width(),
						height: $(window).height(),
						top: 0,
						left: 0
					})
					.find('video,img')
					.animate({
						width: $(window).width(),
						height: $(window).height()
					});
				
				$('#fullscreen')
					.unbind('click')
					.click(function(){ _fullscreen('close'); })
					.text('Close');
				
				$('body').css('overflow','hidden');
			}else{
				$(video_container)
					.animate({
						width: video_initial_width,
						height: video_initial_height,
						top: video_initial_top,
						left: video_initial_left
					},function(){ $(this).removeClass('fullscreen') })
					.find('video,img')
					.animate({
						width: video_initial_width,
						height: video_initial_height
					});
				
					$('#fullscreen')
						.unbind('click')
						.click(function(){ _fullscreen('open'); })
						.text('Full');
				
				$('body').css('overflow','visible');
			}
		}
		
		// Expose only the init function
		return {
			init: init
		};
	}();


/* ------------------------------------------------------------------------
	Class: slideshow
	Uses: Controls the slideshows in the project pages
------------------------------------------------------------------------- */

	var slideshow = function(){
		var 
			slideshow_container,
			image_count,
			image_width = 595,
			image_height = 333,
			current_image = 0;

		function init(json,container){
			slideshow_container = container;
			image_count = json.length;

			// Append the nav
			$(slideshow_container).append('<a href="#" class="previous">Previous</a><a href="#" class="next">Next</a>');


			// Append the images
			for (var i=1; i < json.length; i++) {
				$('<img />')
					.attr('src',json[i])
					.css({
						left: image_width
					})
					.appendTo(slideshow_container);
			};
			
			// Bind the events
			$(slideshow_container).find('.next').click(function(){ _next(); return false; })
			$(slideshow_container).find('.previous').click(function(){ _previous(); return false; })
		}
		
		function _next(){
			$(slideshow_container)
				.find('img:eq('+current_image+')')
				.animate({left: -image_width});
				
			if (current_image >= (image_count-1)){
				current_image = 0;
			}else{
				current_image++;
			}
			
			$(slideshow_container)
				.find('img:eq('+(current_image)+')')
				.css('left',image_width)
				.animate({left: 0});
		}
		
		function _previous(){
			$(slideshow_container)
				.find('img:eq('+current_image+')')
				.animate({left: image_width});
			
			current_image--;
			if (current_image < 0){
				current_image = image_count-1;
			}
			
			$(slideshow_container)
				.find('img:eq('+(current_image)+')')
				.css('left',-image_width)
				.animate({left: 0});
		}

		// Expose only the init function
		return {
			init: init
		};
	}();