
/* jQuery slideshow method
 *	- invoke on the container of the elements to animate
 *
 * selection	- jQuery selector used by jQuery's find
 * speed, delay	- in ms
 * endDelay	- extra delay to put on at the 'end' of each cycle
 */
jQuery.fn.slideshow = function (selection, speed, delay, endDelay)
	{
	var parent, slides_JQ, index, len;
	parent = this;
	slides_JQ = parent.find(selection);
	len = slides_JQ.length;

	function next_slide()
		{
		if (index != len)
			{
			slides_JQ.eq(index).fadeIn(speed, function ()
				{
				++index;
				setTimeout(next_slide, delay);
				});
			}
		else
			{
			setTimeout(function ()
				{
				slides_JQ.slice(1, len-1).hide();
				slides_JQ.eq(len-1).fadeOut(speed, function ()
					{
					index = 1;
					setTimeout(next_slide, delay);
					});
				}, endDelay);
			}
		}
		
	slides_JQ.slice(1).hide();
	index = 1;
	setTimeout(next_slide, delay);
	};

/* jQuery text zoom in/out method
 * 	- invoke on the first element. After running on this element the next sibling will be moved on to.
 *
 * speed	- in ms
 * newWidth	- as text zooms in, we also zoom the element's width.
 *			NB: we do not reduce the width on zoom out - it remains at newWidth
 */
jQuery.fn.enlargeText = function (speed, newWidth)
	{
	clearTimeout(jQuery.fn.enlargeText.enlargeTextTimeout);
	jQuery(this).stop(true).css('font-size', '100%').animate({fontSize: "200%", width: newWidth}, speed, null, function ()
		{
		var li = this;
		jQuery.fn.enlargeText.enlargeTextTimeout = setTimeout(function ()
			{
			jQuery(li).css('font-size', '200%').animate({fontSize: "100%"}, speed).next().enlargeText(speed, newWidth);
			}, 2000);
		});
	};

// External links
//
function externalLinks()
	{
	var as, i;
	as = document.getElementsByTagName('a');
	for (i=0; i<as.length; ++i)
		{
		if (as[i].hostname != window.location.hostname && as[i].protocol.toLowerCase().substr(0,4) == "http")
			{
			as[i].onclick = function ()
				{
				window.open(this.href);
				return false;
				}
			}
		}
	}

var ieversion, base_href; // Hold base href globally for IE's benefit

jQuery(document).ready(function()
	{
	// Background image. Note multiples of 100 to ease load on phpThumb
	function backdrop(blankingFlag)
		{
		var viewportWidth, viewportHeight, imageUrl, image;
		
		if(window.innerWidth != undefined)
			{
			viewportWidth = window.innerWidth;
			viewportHeight = window.innerHeight;
			}
		else if (document.documentElement)
			{
			viewportWidth = document.documentElement.clientWidth;
			viewportHeight = document.documentElement.clientHeight;
			}
		else	
			{
			viewportWidth = null;
			viewportHeight = null;
			}

		if (viewportWidth)
			{
			if (blankingFlag) document.body.style.background = 'white';	// Blank background while waiting for page to load
											// (safeguards against pointlessly loading default background on page load)
			
			imageURL = "../../../../phpThumb/phpThumb.php?src=../assets/images/Backdrops/SkyeAlltDearg.jpg&zc=T&h="+(50 * Math.ceil(viewportHeight/50))+"&w="+(50 * Math.ceil(viewportWidth/50)).toString()+"&fltr[]=brit|96&fltr[]=blur|1&q=55";

			image = new Image();
			image.onload = function ()
				{
				document.body.style.background = "url("+imageURL+") fixed no-repeat top center";
				};

			image.src = imageURL
			}
		}

	// Portfolio list; set div.image heights and hide all but the first image in each set.
	function portfolioListImages()
		{	
		jQuery('.portfolio-list:last li').each(function()
			{
			jQuery(this).find('img').each(function(index)
				{
				function portfolioImagesHeight()
					{
					if (ieversion != null && ieversion <= 6)
						image.parentNode.parentNode.style.minHeight = Math.max(image.height, image.parentNode.parentNode.offsetHeight)+'px';
					else
						image.parentNode.parentNode.style.height = Math.max(image.height, image.parentNode.parentNode.offsetHeight)+'px';
					if (index) image.style.display = 'none';
					}
					
				var image = this;
				image.onload = portfolioImagesHeight;
				portfolioImagesHeight();
				});
			});
		}


	var base; // base href for IE
	var navLinks, activeLinks, defaultTextSection_JQ; // Tabs
	var cookieName, cookiePosn, cookieHref; // Cookies!
	var as, i;
	
	// Test for IE
	// -----------
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) //test for MSIE x.x;
		ieversion=new Number(RegExp.$1);
	else
		ieversion = null;
		
	// base href for IE
	// ----------------
	base = document.getElementsByTagName('base');
	if (base && base[0] && base[0].href) base_href = base[0].href;
	else base_href = 'http://'+document.domain+'/';

	// Bind click functions to tabs if > 1 tab
	navLinks = jQuery('#nav a');
	if (navLinks.length > 1  && (ieversion === null || ieversion >= 7))
		{
		/* Function to animate text section transitions
		 * 
		 * html			- the new text/html
		 * callbackOnInsertion	- function to call when text inserted into DOM i.e. before the animation
		 * callback		- function to call when animation complete
		 */
		function newTextSection(html, callback, callbackOnInsertion)
			{
			var lastTextSection;
			lastTextSection = jQuery('.text-section:last');

			if (jQuery.browser.safari)
				{
				// Need to scroll up otherwise Safari messes up the page when animations indirectly cause scrolling
				window.scroll(0,0);
				while (document.documentElement.scrollTop) { };
				}

			// Insert into DOM
			lastTextSection.after(html);
			externalLinks();
			if (typeof(callbackOnInsertion) == 'function') callbackOnInsertion();
		
			// Animate
			lastTextSection.slideUp(800, function() { jQuery(this).remove(); }).next().css('display', 'none').show(1000, function ()
				{
				// IE7 - remove filter attribute to enable cleartype
				if (jQuery.browser.msie) this.style.removeAttribute('filter');
				// Focus on any inputs
				jQuery(this).find('input:first').focus();
				// Callback
				if (typeof(callback) == 'function') callback();
				});
			}
		
		/* Function to make an ajax request for a text section
		 *
		 * link		- The anchor containing the href. 
		 *		  On finishing the request, link.textsection contains the new html
		 * callback	- function to call on completion
		 */
		function fetchTextSection(link, callback)
			{
			if (link.textSection)
				{
				callback(link.textSection);
				}
			else
				{
				jQuery.ajax({
					url: link.href+'?ajax=1',
					datatype: 'html',
					success: function (html) {
						link.textSection = html;
						callback(html);
						}
					});
				}
			}
		
		// Portfolio text zooming
		function portfolioTextEnlarge()
			{
			setTimeout(function()
				{
				var lis_JQ, liWidth;
				lis_JQ = jQuery('.text-section .richtext-container ul li');
				liWidth = lis_JQ.eq(0).parent().width();
				lis_JQ.width(liWidth >> 1);
				lis_JQ.eq(0).enlargeText(300, liWidth);
				}, 1500);
			}
		
		// Bind click functions to links on the single-item portfolio 'page'
		function portfolioSingleViewLinks()
			{
			jQuery('.prev-jump-next a').click(function ()
				{
				if (this.getAttribute('href') == 'portfolio')
					{
					// Index page (portfolio) links
					jQuery('#nav li.active a').click(); // As it will be cached there - we must have come via this page already.
					}
				else
					{
					// Prev/Next links
					fetchTextSection(this, function (html)
						{
						newTextSection(html,
							function () // Callback after animation; invokes text zoom in/out.
							{
							portfolioTextEnlarge();
							},
							function () // Callback on insertion into DOM; binds events to links.
							{
							portfolioSingleViewLinks();
							});
						});
					}			
				return false;
				});

			if (jQuery.browser.safari)
				{				
				// All links - need to scroll up first for Safari's benefit (animation issues when back button used)
				jQuery('.portfolio-section a').click(function ()
					{
					window.scroll(0,0);
					});
				}
			}
		
		// Bind events to links for the portfolio list so that they animate to the single-item portfolio views.
		function portfolioList()
			{
			jQuery('.portfolio-list:last').find('a').each(function()
				{
				this.onclick = function ()
					{
					fetchTextSection(this, function (html)
						{
						newTextSection(html,
							function () // Callback after animation; invokes text zoom in/out.
							{
							portfolioTextEnlarge();
							},
							function () // Callback on insertion into DOM; binds events to links.
							{
							portfolioSingleViewLinks();
							});
						})
					return false;
					};
				});
			}

		// Cache default text section
		activeLinks = jQuery('#nav li.active a');
		if (activeLinks.length)
			{
			defaultTextSection_JQ = jQuery('.text-section');
			activeLinks.get(0).textSection = '<div id="'+defaultTextSection_JQ.attr('id')+'" class="'+defaultTextSection_JQ.attr('class')+'">'+jQuery('.text-section').html()+'</div';
			}

		navLinks.click(function()
			{
			this.blur(); // Avoid another Safari animation problem
		
			document.cookie = 'TS'+window.location.href+'='+this.href;
		
			jQuery(this.parentNode.parentNode).find('.active').removeClass('active');
			jQuery(this.parentNode).addClass('active');

			fetchTextSection(this, function (html)
				{
				newTextSection(html,
					function () // Callback after animation
					{
					jQuery('.portfolio-list div.images').each(function()
						{
						// Fading slideshow
						jQuery(this).slideshow('img', 2000, 2000, 0);
						});
					}, 
					function () // Callback on insertion to DOM
					{
					portfolioList();
					portfolioListImages();
					});
				});
			return false;
			});
		
		// Have we been here before? If so - which text section was displayed?
		// This is stored in a cookie so when a user goes 'back' they end up
		// on the 'page' last viewed i.e. the text-section last viewed.
		cookieName = 'TS'+window.location.href;
		if (document.cookie && (cookiePosn = document.cookie.indexOf(cookieName+'=')) != -1)
			{
			cookieHref = document.cookie.substr(cookiePosn+(cookieName+'=').length);
			if (cookieHref.indexOf(';') != -1) cookieHref = cookieHref.substr(0, cookieHref.indexOf(';'));

			jQuery('#nav li').each(function ()
				{
				if (jQuery(this).find('a').get(0).href == cookieHref)
					{
					jQuery(this).find('a').click();
					}
				});
			}
		else
			{
			// Not been before - but could be a direct link to portfolio?
			portfolioList();
			}
	
		jQuery(window).load(function()
			{
			setTimeout(function()
				{
				// Preload portfolio images
				// ------------------------
				jQuery.ajax({
					url: 'ajax-image-cache',
					datatype: 'xml',
					success: function (imageXml)
						{
						jQuery(imageXml).find('img').each(function()
							{
							var image;
							image = new Image();
							image.src = this.getAttribute('src');
							});
						}
					});
				}, 3000); // Delay to enable animations to run before causing further load on the browser
			});
		}

	portfolioListImages();
	
	backdrop(true);
	
	jQuery(window).resize(function () { backdrop(false); } );
	
	externalLinks();
	});


