$(function()
{	
	
	SlideShow.init();
	
	$('body').addClass('default');
	
	var $body_start = $('body#start');
		
	if ($body_start.size())
	{
		// Make intro img on start close on click
		$body_start.one('click',function()
		{
			$('body').removeAttr('style').removeClass('show-intro');
			
			SlideShow.init_switch_image(null,false);
			return false;
		});	
		
		$('header a').click(function()
		{
			if ($('body').hasClass('show-intro'))
			{
				$('body').removeAttr('style').removeClass('show-intro');
				SlideShow.init_switch_image(null,false);
			}
			else
			{
				$('ul.categories a.all').trigger('click');
				$('#info p.back a').trigger('click');
				$('#content').removeClass('flipped');
			}		

			return false;
		});
		
		// setTimeout(function()
		// {
		// 	$body_start.trigger('click');
		// },300)
		
	}
	
	var fancybox_settings_video =
	{
		'opacity':true,
		'width':'100%',
		'height':'100%',
		'overlayOpacity':0.90,
		'overlayColor':'#000',
		'titlePosition':'outside',
		// 'titleFormat':format_title,
		'titleShow':false,
		'transitionIn':'fade',
		'cyclic':false,
		'margin':0,
		'showCloseButton':true,
		'showNavArrows':false,
		'padding':0,
		'scrolling':'no',
		'onClosed':function()
		{
			window.clearTimeout(window.stuff_hide);
			
			$('#fancybox-info').remove();
			
			$('#set-thumbs').fadeOut();
			
			SlideShow.play();
			
			h2_placed = false;
		},
		'onComplete':function()
		{			
			if (! h2_placed)
			{				
				var $header = $('#vid h2').clone();
				
				var $fb_close = $('#fancybox-close');
				
				var $close = $fb_close.clone();
				
				$fb_close.remove();
				
				$('#fancybox-overlay').append($close).after('<div id="fancybox-info">' + $header.html() + '</div>');
												
				Cufon.replace('#fancybox-info em',{ fontFamily: 'metro' });
				
				h2_placed = true;
			}
			
			$('#fancybox-close').show();
			
			window.clearTimeout(window.stuff_hide);
			
			var $stuff = $('#fancybox-info, #fancybox-close');
			
			$('#fancybox-inner,#fancybox-overlay').bind('mousestop',function()
			{				
				window.stuff_hide = setTimeout(function()
				{
					console.log('fadeout');
					$stuff.fadeOut();
					
				},4000);
			});
			
			$('#fancybox-inner,#fancybox-overlay').bind('mousemove',function()
			{
				window.clearTimeout(window.stuff_hide);
				if (! $stuff.is(':visible'))
				{
					$stuff.fadeIn();
				}
			});
			
			$('#fancybox-inner').trigger('mousestop');
			
		}
	};
	
	var $set_thumbs = $('#set-thumbs');	
	
	var set_thumbs_opened = false;
	
	var timer = 0;
	
	var fancybox_settings_photo =
	{
		'opacity':true,
		'width':'100%',
		'height':'100%',
		'overlayOpacity':0.90,
		'overlayColor':'#000',
		'titlePosition':'outside',
		// 'titleFormat':format_title,
		'titleShow':false,
		'transitionIn':'fade',
		'cyclic':false,
		'margin':30,
		'showCloseButton':true,
		'showNavArrows':true,
		'padding':0,
		'scrolling':'no',
		'onStart':function()
		{
			$('#fancybox-wrap').css('margin-top','-10px');
			$('body').removeClass('default').css({'overflow':'hidden'});
		},
		'onClosed':function()
		{
			$('body').addClass('default').removeAttr('style');
			$('#set-thumbs').fadeOut();
			SlideShow.play();
			
			$('#fancybox-info').remove();
			
			window.clearTimeout(window.stuff_hide);
			
			$('#fancybox-inner,#fancybox-overlay').unbind('mousestop');
			$('#fancybox-inner,#fancybox-overlay').unbind('mousemove');
			
			h2_placed = false;
		},
		'onComplete':function(e)
		{
			if (! h2_placed)
			{
				var $header = $('#set-thumbs h2').clone();
				
				var $fb_close = $('#fancybox-close');
				
				var $close = $fb_close.clone();
				
				$fb_close.remove();
				
				$('#fancybox-overlay').append($close).after('<div id="fancybox-info">' + $header.html() + '</div>');
								
				Cufon.replace('#fancybox-info em',{ fontFamily: 'metro' });
				
				h2_placed = true;
			}
			
			$('#fancybox-close').show();
			
			var $stuff = $('#set-thumbs, #fancybox-info, #fancybox-close');
			
			window.clearTimeout(window.stuff_hide);
			
			$('#fancybox-inner,#fancybox-overlay').bind('mousestop',function()
			{	
				window.clearTimeout(window.stuff_hide);	
				window.stuff_hide = setTimeout(function()
				{
					console.log('fadeout');
					$stuff.fadeOut();
					
				},4000);
			});
			
			$('#fancybox-inner,#fancybox-overlay').bind('mousemove',function()
			{
				window.clearTimeout(window.stuff_hide);
				if (! $stuff.is(':visible'))
				{
					$stuff.fadeIn();
				}
			});
			
			$('#fancybox-inner').trigger('mousestop');
						
		}		
	};
	
	var h2_placed = false;
			
	
	// apply fancybox to all photos in grid
	$('#photos ul.pics li a[href*="video"]').fancybox(fancybox_settings_video);
	
	// Make clients list visible
	$('ul.site li').not('.blog').find('a').click(function()
	{
		SlideShow.pause();
		
		var target_name = $(this).parent('li').attr('class');
		
		var $content = $('#content');
		
		$content.addClass('flipped ' + target_name);
		
		var content_height = $('#info div.' + target_name).height();
		
		$content.height(content_height +80);
		
		return false;
	});
	
	// Close clients
	$('#info p.back a').click(function()
	{
		SlideShow.play();
		$('#content').removeAttr('class').removeAttr('style');
		return false;
	});
	
	
	// Get images of photo set when clicking a thumb
	$('#photos ul.pics li a[href*="photo-set"]').click(function()
	{
		SlideShow.pause();
		
		$(this).append('<span class="loading">Loading</span>');
		
		var url = $(this).attr('href');
		
		var url_split = url.split('/');
		
		var type = url_split[1]; // photo-set or video
				
		var pic_id = url_split[url_split.length -1]; // get pic id, last segment of url
		
		$.get(url,function(data) // Get list of pics
		{			
			var $set_thumbs = $('#set-thumbs');

			if ($set_thumbs.size()) // if $set_thumbs exists (if user has previously viewed a set)
			{
				$set_thumbs.empty(); // Empty it 
				
				$set_thumbs.append($(data).children()); // append ul to $set_thumbs

				if ($set_thumbs.is(':hidden')) // Check if hidden - then fade in
				{
					$set_thumbs.fadeIn();
				}
			}
			else // if $set_thumbs doesn't exist, just append it to body
			{
				$('body').append(data);
			}

			var $set_thumb_links = $('#set-thumbs li a');

			$set_thumb_links.fancybox(fancybox_settings_photo); // apply fancybox to thumbs

			$set_thumb_links.click(function() // apply sel class to clicked thumb
			{
				$(this).parents('ul').eq(0).find('li').removeClass('sel');
				$(this).parent('li').addClass('sel');
				return false;
			});
			
			// Trigger click on the same img in $set_thumbs that was clicked in big grid
			// This is done by fetching the id from the url (we did that above)
			// and then find the right one in $set_thumbs by looking for that same id in the rel attr
			
			$set_thumb_links.parents('ul').eq(0).find('li[rel="' + pic_id + '"] a').trigger('click');
										
			$('span.loading').remove();
			
		});
		
		return false;
	});
	
	// Category filtering
	
	var $target = $('ul.photos');
	
	var $category_links = $('ul.categories li a');
	
	$category_links.click(function()
	{
		var $this = $(this);
		
		$(this).parents('ul').eq(0).find('li').removeClass('sel');
		$(this).parent('li').addClass('sel');
		
		var type = $(this).attr('class');		
		
		if (type != 'all')
		{
			SlideShow.pause();
			$('#featured').fadeOut();
		}
		else
		{
			SlideShow.play();
			$('#featured').fadeIn();
		}
			
		$target.fadeOut(function()
		{			
			$target.find('li').show();

			if (type != 'all')
			{
				$target.find('li').not('.' + type).hide();
			}
			
			$target.fadeIn();
		});
		
		return false;
	});
	
	NewWindow.init();

});

var SlideShow =
{
	current_img : 0,
	
	num_images : 0,
	
	$container :'',
	
	$nav_container : '',
	
	interval : 4000,
	
	paused: false,
	
	timer:'',
	
	pause:function()
	{
		SlideShow.paused = true;
	},
	
	play:function()
	{
		SlideShow.paused = false;
		SlideShow.init_switch_image(null,false);
	},
	
	init:function()
	{
		$base = $('#start #featured');
		
		if (! $base.size())
		{
			return false;
		}
		
		SlideShow.$container = $base.find('ul');
				
		var $containers = SlideShow.$container.find('li');
		
		$containers.filter(':gt(0)').hide();
		//SlideShow.$container.height($containers.filter(':first').css('height'));
		
		SlideShow.num_images = SlideShow.$container.find('li').size();
		
		if (SlideShow.num_images < 2)
		{
			return false;
		}
		
		var nav = '<nav>';
		
		var sel;
		
		for(var i = 0;i < SlideShow.num_images;i++)
		{
			sel = (i == 0) ? ' class="sel"' : '';
			
			nav+= '<a href="#"' + sel + '></a>';
		}
		
		nav+= '</nav>';
		
		SlideShow.$container.parent().append($(nav));
		
		SlideShow.$nav_container = $base.find('nav');
		
		SlideShow.$nav_container.delegate('a','click',function()
		{
			var index = $(this).index();
			
			var is_animating = SlideShow.$container.find('li:eq(' + (SlideShow.current_img) + ')').filter(':animated').size();
			
			if (index == SlideShow.current_img || is_animating)
			{
				return false;
			}
			
			window.clearTimeout(SlideShow.timer);
			
			SlideShow.init_switch_image(index,false);
			return false;
		});
		
		SlideShow.init_switch_image(null,true);
	},
	
	init_switch_image:function(i,init)
	{	
		
		var $img_to_show;
		
		if (i !== null)
		{
			$img_to_show = SlideShow.$container.find('li:eq(' + (i) + ')');
		}
		else
		{
			if (init || SlideShow.current_img == (SlideShow.num_images-1))
			{
				$img_to_show = SlideShow.$container.find('li:first');
			}
			else
			{
				$img_to_show = SlideShow.$container.find('li:eq(' + (SlideShow.current_img + 1) + ')');
			}
		}
		
		var interval = (init || i !== null) ? 0 : 4000;
		
		if (! $img_to_show.find('a img').size()) // img is loaded
		{
			var src = $img_to_show.attr('data-src');
			
			$('<img />').attr('src',src).load(function()
			{
				var $a = $img_to_show.find('a');
				
				$img_to_show.append('<span class="title">' + $a.attr('title') + '</span>').removeAttr('data-src')
					.find('a').append($(this));				
				
				SlideShow.switch_image($img_to_show,init,interval);					
				
			});
		}
		else
		{
			SlideShow.switch_image($img_to_show,init,interval);
		}		
	},
	
	switch_image:function($img_to_show,init,interval)
	{			
		var $to_hide;
		
		$to_hide = SlideShow.$container.find('li:eq(' + (SlideShow.current_img) + ')');
		
		// if ($img_to_show.index() == (SlideShow.num_images-1))
		// {
		// 	$to_hide = SlideShow.$container.find('li:first');
		// }
		// else
		// {
		// 	$to_hide = $img_to_show.next();
		// }
						
		SlideShow.timer = window.setTimeout(function()
		{		
			if (SlideShow.paused)
			{
				return false;
			}
				
			SlideShow.$nav_container.find('a.sel').removeClass('sel').end()
				.find('a:eq(' + ($img_to_show.index()) + ')').addClass('sel');
			
			$img_to_show.fadeIn('slow');
			
			if ($to_hide.size())
			{
				$to_hide.fadeOut('slow');				
			}
			
			SlideShow.current_img = $img_to_show.index();
			
			if (! init)
			{
				SlideShow.init_switch_image(null,false);
			}
						
		},interval);
	}
};

var NewWindow =
{
	init:function()
	{
		var $links = $('a[href^="http://"], a[href^="https://"], a[href$=".pdf"]');

		$links.click(function()
		{	
			var $this = $(this);
			var href = $this.attr('href');

			if (href.indexOf('johannespescatore.com') == -1 && href.indexOf('johannespescatore.dev') == -1)
			{
				window.open(href);
				return false;
			}
		});
	}
};


function format_title(title)
{
    return '<p class="caption"><span>' + (title && title.length ?  title : '' ) + '</span></p>';
}


/*
 * jQuery Mousestop Event v1.0
 * http://richardscarrott.co.uk/posts/view/jquery-mousestop-event
 *
 * Copyright (c) 2010 Richard Scarrott
 * W/ thanks to Ben Alman for his decent jQuery special event API write up:
 * http://benalman.com/news/2010/03/jquery-special-events/
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Requires jQuery v1.3+
 *
 */

(function($) {
	// public vars
	$.mousestopDelay = 50;

	// special event
	$.event.special.mousestop = {
		setup: function(data) {
			$(this).data('mousestop', {delay: data})
				   .bind('mouseenter.mousestop', mouseenterHandler)
				   .bind('mouseleave.mousestop', mouseleaveHandler);
		},
		teardown: function() {
			$(this).removeData('mousestop')
			       .unbind('.mousestop');
		}
	};

	// private methods
	function mouseenterHandler() {
		if (typeof this.timeout === 'undefined') {
			this.timeout = null;
		}
		
		var elem = $(this),
			data = elem.data('mousestop'),
			delay = data.delay || $.mousestopDelay;

		elem.bind('mousemove.mousestop', function() {
			clearTimeout(this.timeout);
			this.timeout = setTimeout(function() {
				elem.trigger('mousestop');
			}, delay);
		});
	};
	
	function mouseleaveHandler() {
		var elem = $(this);
		elem.unbind('mousemove.mousestop');
		clearTimeout(this.timeout);
	};

	// shorthand alias
	$.fn.mousestop = function(data, fn) {
		if (fn == null) {
			fn = data;
			data = null;
		}

		return arguments.length > 0 ? this.bind('mousestop', data, fn) : this.trigger('mousestop');
	};
})(jQuery);
