/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"/>

$(document).ready(function ()
{
	// slider beneath nav
	$('#header .nav, #footer .nav')
	.each(function (i)
	{
		var b = $('<b />').appendTo(this);

		$('li', this)
		.mouseenter(function (e)
		{
			var w = $('a', this).width();
			var l = ($(this).position().left || -20) + (($(this).outerWidth() - w) / 2);

			b.stop(true).stop(true).animate({
				width: w,
				left: l
			}, 150);

			w = undefined;
			l = undefined;
		})
		.mouseleave(function (e)
		{
			$(this).siblings('.current').mouseenter();
		});
	});

	// animated scrolling triggers
	$('#header .nav li a, #footer .nav li a, .back-to-top a, .sausages a')
	.each(function (i)
	{
		var target = (this.hash || '#/home/').substr(1);

		$('*[id="' + target + '"]').attr('id', '/js' + target);
	})
	.click(function (e)
	{
		e.preventDefault();

		var target = (this.hash || '#/home/').substr(1);

		if ($.address.value() == target)
		{
			var target = $('*[id="/js' + target + '"]');

			animatedScrollTo(target.offset().top, Math.round(Math.abs($(window).scrollTop() - target.offset().top) * .5));
		}
		else
		{
			$.address.value(target);
		}

		return false;
	});

	// animated scroll function
	function animatedScrollTo(scroll, speed)
	{
		return $.Deferred(function (defer)
		{
			$($.browser.webkit ? 'body' : 'html').animate({
				scrollTop: scroll
			}, speed, function ()
			{
				$('.nav a').blur();

				defer.resolve();
			});
		})
		.promise();
	}

	// waypoints
	$('*[id="/js/home/"]').waypoint(function ()
	{
		$('.nav a[rel="home"]').closest('li').addClass('current').siblings('li.current').removeClass('current').mouseleave();
		$('.sausage-1').addClass('current').siblings('li').removeClass('current');

		clearInterval(intv);
	}, { offset: function () { return -($('.section[id="/js/work/"]').offset().top / 2) } });

	$('*[id="/js/work/"]').waypoint(function (e, dir)
	{
		if (dir == 'down')
		{
			$('.nav a[href$="#/work/"]').closest('li').addClass('current').siblings('li.current').removeClass('current').mouseleave();
			$('.sausage-2').addClass('current').siblings('li').removeClass('current');
		}
		else
		{
			$('.nav a[rel="home"]').closest('li').addClass('current').siblings('li.current').removeClass('current').mouseleave();
			$('.sausage-1').addClass('current').siblings('li').removeClass('current');
		}

		clearInterval(intv);
	}, { offset: 100 });

	$('*[id="/js/what/"]').waypoint(function (e, dir)
	{
		if (dir == 'down')
		{
			$('.sausage-3').addClass('current').siblings('li').removeClass('current');
		}
		else
		{
			$('.sausage-2').addClass('current').siblings('li').removeClass('current');
		}

		clearInterval(intv);
	}, { offset: 100 });

	$('*[id="/js/clients/"]').waypoint(function (e, dir)
	{
		if (dir == 'down')
		{
			$('.sausage-4').addClass('current').siblings('li').removeClass('current');
		}
		else
		{
			$('.sausage-3').addClass('current').siblings('li').removeClass('current');
		}

		clearInterval(intv);
	}, { offset: 100 });

	$('*[id="/js/contact/"]').waypoint(function (e, dir)
	{
		if (dir == 'down')
		{
			// do this on the way down
			$('.nav a[href$="#/contact/"]').closest('li').addClass('current').siblings('li.current').removeClass('current').mouseleave();

			$('.sausage-5').addClass('current').siblings('li').removeClass('current');

			intv = setInterval(spaceships, 10);
		}
		else
		{
			// do this on the way back up through the waypoint
			$('.nav a[href$="#/work/"]').closest('li').addClass('current').siblings('li.current').removeClass('current').mouseleave();

			$('.sausage-4').addClass('current').siblings('li').removeClass('current');

			clearInterval(intv);
		}

	}, { offset: '50%' });


	// deeplinking and change handlers
	var title = document.title;
	var work = $('.dynamic-content').html();
	var scroll;
	var page;

	$.address.init(function (e)
	{
		if (!e.path || e.path == '/')
		{
			$.address.value('/home/');
		}
	})
	.change(function (e)
	{
		var target, ajax, targetOffsetTop, path;

		path = e.path.match(/(work|home|what|clients|contact)(?:\/([^\/]+))?\//);

		page = path[1];

		if (path[1] && path[1] == 'work' && path[2])
		{
			target = $('*[id="/js/work/"]');

			if (path[2] == 'all')
			{
				ajax = $.get('/?_escaped_fragment_=/work/all/');
			}
			else if (path[2] == 'showcase')
			{
				ajax = $.get('/?_escaped_fragment_=/work/showcase/');
			}
			else
			{
				ajax = $.get('/?_escaped_fragment_=/work/' + path[2] + '/');

				scroll = $(window).scrollTop();
			}

			page = path[2];
		}
		else
		{
			target = $('*[id="/js/' + (path[1] || 'home') + '/"]');
			ajax = $.Deferred();

			// reset work
			if (/home|work/.test(page))
			{
				page = 'work';

				ajax.resolve(/*[*/work/*, 'internal']*/);
			}
			else
			{
				ajax.reject();
			}
		}

		/*targetOffsetTop = target && target.offset() ? target.offset().top : 0;

		if (scroll && path[2] == 'all')
		{
		targetOffsetTop = scroll;

		scroll = null;
		}*/

		$.when(ajax/*, animatedScrollTo(targetOffsetTop, Math.max(500, Math.min(1000, Math.round(Math.abs($(window).scrollTop() - targetOffsetTop) * .5))))*/)
		.then(function (data)
		{
			var dynContent = $('.dynamic-content');
			var newItems = $(data/*[0]*/).find('img, iframe')
			.each(function (i)
			{
				$(this).data('mediaSrc', this.src);

				this.src = '/_assets/images/img_placeholder.png';
			}).end();

			// fix height work region
			dynContent.height(dynContent.height());

			// fade out current list
			dynContent.fadeTo(500, 0, function ()
			{
				// detach the old items (could remove them if we are not going to put them back ever)
				dynContent.empty();

				// insert new content
				dynContent.append(newItems);

				// attach waypoints for lazy loading
				dynContent.find('img, iframe').each(function (i)
				{
					if ($(this).data('mediaSrc'))
					{
						$(this).fadeTo(0, 0).waypoint(function ()
						{
							$(this).waypoint('destroy');

							// attach the onload handler
							$(this).load(function (e)
							{
								// fade in	
								$(this).fadeTo(500, 1);
							});

							// set the src
							this.src = $(this).data('mediaSrc');

							// if image loaded in cache already
							if (this.complete || this.readyState === 4)
							{
								// fade in
								$(this).fadeTo(500, 1);
							}

						}, { offset: function () { return $(this).offset().top < $(window).scrollTop() ? -($(this).outerHeight()) : $.waypoints('viewportHeight'); } });
					}
				});

				// animate work region height to new list height
				dynContent.animate({
					height: dynContent.find(':first-child').height()
				}, 500, function ()
				{
					// let waypoints know we have changed the height of the page
					$.waypoints('refresh');

					targetOffsetTop = target && target.offset() ? target.offset().top : 0;

					if (scroll && path[2] == 'all')
					{
						targetOffsetTop = scroll;

						scroll = null;
					}

					$.when(animatedScrollTo(targetOffsetTop, Math.max(500, Math.min(1000, Math.round(Math.abs($(window).scrollTop() - targetOffsetTop) * .5)))))
					.then(function ()
					{
						// trigger waypoint
						$('*[id="/js/work/"]').trigger('waypoint', [targetOffsetTop > 1 ? 'down' : 'up']);

						// fade in new list
						dynContent.fadeTo(500, 1, function ()
						{
							// fix aliasing bug in IE
							this.style.filter = '';
						});
					});
				});
			});
		}, function ()
		{
			targetOffsetTop = target && target.offset() ? target.offset().top : 0;

			if (scroll && path[2] == 'all')
			{
				targetOffsetTop = scroll;

				scroll = null;
			}

			animatedScrollTo(targetOffsetTop, Math.max(500, Math.min(1000, Math.round(Math.abs($(window).scrollTop() - targetOffsetTop) * .5))));
		});

		// update page title
		$.address.title([title].concat($.map(e.pathNames, function (n) { return n.substr(0, 1).toUpperCase() + n.substr(1); })).join(' \u2022 '));
	});

	// shout box
	$('#shoutbox').each(function (i)
	{
		$(this).click(function (e)
		{
			e.stopPropagation();
		});

		$('p', this).css({ cursor: 'pointer' }).click(function (e)
		{
			$(this).next('.fields').fadeToggle(200);
		})
		.next('.fields').removeClass('js-hide').fadeOut(0);

		$(document).click(function (e)
		{
			$('#shoutbox .fields').fadeOut(200);
		});

		$(this).submit(function (e)
		{
			e.preventDefault();

			shoutOut($('#name', this).val(), $('#message', this).val());

			$('.fields', this).fadeOut(200).find('input:text').val('');
		})
		.next('.fields').removeClass('js-hide').fadeToggle(0);

		// get messages
		function shoutOut(name, message)
		{
			var data = name && message ? { name: name, message: message} : {}

			$.ajax({
				url: 'handlers/shoutboxmessage.ashx',
				type: 'POST',
				dataType: 'json',
				data: data,
				success: function (data)
				{
					$('#shoutbox .name').text(data.name);
					$('#shoutbox .message').text(data.message);
				}
			});
		}

		setInterval(shoutOut, 10000);
	});

	// main feature slideshow
	$('.slideshow').slideshow();

	// client fader
	$('.client-list').clientFader();

	// external links
	$('body').delegate('a[href^=http]:not([href*="' + location.hostname + '"]), a:[rel~="external"]', 'click', function () { $(this).attr('target', '_blank') });

	// placeholder support for older browsers
	if (!('placeholder' in document.createElement('input')))
	{
		function plhHide()
		{
			var input = $(this);

			if (input.val() == input.attr('placeholder'))
			{
				input.val('');
			}

			input.removeClass('plh-added');

			input = null;
			delete input;
		}

		function plhShow()
		{
			var input = $(this);
			var plhText = input.attr('placeholder');

			if (input.val() == plhText || input.val() == '')
			{
				input.addClass('plh-added').val(plhText);
			}

			input, plhText = null;
			delete input, plhText;
		}

		$('input[placeholder], textarea[placeholder]').each(function (i)
		{
			$(this).focus(plhHide).blur(plhShow)
			.closest('form').submit(function (e)
			{
				$('input[placeholder], textarea[placeholder]', this).each(function (i)
				{
					plhHide.call(this);
				});
			});

			// init
			plhShow.call(this);
		});
	}


	// space ships

	$('div.spaceship-1').data({ angle: 0, centerY: 24, positionX: 26, range: .8, speedY: .035, speedX: .1, bufferX: 10 });
	$('div.spaceship-2').data({ angle: 0, centerY: 41, positionX: 77, range: 3, speedY: .035, speedX: .2, bufferX: 40 });
	$('div.spaceship-3').data({ angle: 0, centerY: 18, positionX: 82, range: 3, speedY: .025, speedX: .25, bufferX: 40 });
	$('div.spaceship-4').data({ angle: 0, centerY: 25, positionX: 50, range: 4, speedY: .04, speedX: .4, bufferX: 80 });
	$('div.planet-1').data({ angle: 1, centerY: 35, positionX: 18, range: .3, speedY: .022, speedX: -.008, bufferX: 10 });
	$('div.planet-2').data({ angle: 0, centerY: 20, positionX: 62, range: .3, speedY: .02, speedX: -.005, bufferX: 10 });

	var ships = $('div[class^="spaceship-"], div[class^="planet-"]');
	var spaceships = function ()
	{
		ships.each(function (i)
		{
			var data = $(this).data();

			data.positionX -= data.speedX;

			if (data.positionX < -data.bufferX)
			{
				data.positionX = 100 + data.bufferX;
			}

			this.style.backgroundPosition = data.positionX + '% ' + (data.centerY + Math.sin(data.angle) * data.range) + '%';

			data.angle += data.speedY;

			$(this).data(data);
		});
	}

	var intv = setInterval(spaceships, 50);
});

// randomise jquery result set
jQuery.fn.randomise = function()
{
	return this.pushStack(jQuery.makeArray([].fisherYates.apply(this, arguments)));
};

Array.prototype.fisherYates = function()
{
	var i = this.length;
	if (i == 0) return this;

	while (--i)
	{
		var j = Math.floor(Math.random() * (i + 1));
		var tempi = this[i];
		var tempj = this[j];
		this[i] = tempj;
		this[j] = tempi;
	}

	return this;
};

// fader
$.fn.clientFader = function ()
{
	return this.each(function (i)
	{
		var fader = $(this);
		var hidden = $.makeArray($('li:gt(8)', fader).detach().find('img'));
		var visible = $.makeArray($('li', fader));

		function rinseAndRepeat()
		{
			$(visible.fisherYates().pop())
			.prepend($(hidden.fisherYates().pop()))
			.find('img:last-child').fadeOut(1400, function ()
			{
				visible.push($(this).parent()[0]);
				hidden.push($(this).detach().show()[0]);
			});

			fader.animate({ _delay: 1 }, 700, rinseAndRepeat);
		}

		rinseAndRepeat();
	});
}
/*
$.fn.clientFader = function ()
{
	function crossFadeAll()
	{
		var hidden = $.makeArray($('li img:hidden', this).detach());

		if (!hidden.length)
		{
			hidden = $.makeArray($('li:gt(8) img', this).detach().hide());
		}

		$('li:lt(9)', this).each(function (i)
		{
			if (hidden.length)
			{
				// prepend a random hidden img;
				$(this).prepend($(hidden.fisherYates().pop()).show());

				// fadeout existing image
				$('img:last-child', this).fadeOut(1000);
			}
		});

		$(this).animate({ _delay: 1 }, 3000, crossFadeAll);
	}

	return this.each(function (i)
	{
		$(this).animate({ _delay: 1 }, 3000, crossFadeAll);
	});
}
*/

// slideshow
$.fn.slideshow = function ()
{
	return this.each(function (i)
	{
		var slideshow = this;

		// next
		var next = function ()
		{
			$('.pager li.current + li a, .pager li:first-child:not(.current) a', slideshow).last().trigger('mousedown');
		}

		// timer
		var interval = setInterval(next, 7000);

		// reset timer
		var resetInterval = function ()
		{
			clearInterval(interval);

			interval = setInterval(next, 7000);
		}

		$('.slides ul', this).width($('.slides li', this).length * $('.slides li', this).width());

		// set up iScroll if the device supports touch
		var iScroller = ("ontouchstart" in document.documentElement) ? new iScroll('scroller', { hScrollbar: false, vScrollbar: false, vScroll: false, bounce: false, snap: true, momentum: false, onScrollEnd: function ()
		{
			$('.pager li:eq(' + this.currPageX + ')', slideshow).addClass('current').siblings('li.current').removeClass('current');
		}
		}) : null;

		$('.pager a', this).bind('touchstart mousedown MozTouchDown', function (e)
		{
			e.preventDefault();

			$(this).closest('li').addClass('current').siblings('li.current').removeClass('current');

			if (iScroller)
			{
				iScroller.scrollToPage($(this).closest('li').index(), 0, 300);
			}
			else
			{
				$(this).closest('.slideshow').find('.slides').stop(true).animate({
					scrollLeft: $(this).closest('li').index() * $(this).closest('.slideshow').width()
				}, 300);
			}

			resetInterval();
		})
		.bind('click', function (e) { e.preventDefault(); })
		.first()
		.mousedown();
	});
}
