/*	gallery.js
 *	- provides functions to support the gallery
 *
 *	Copyright Al Twohill - Oxynet Ltd (c) 2009
 */
var imagesArray = [];
var x = 0;
var timer;
$(function(){
  //Get our elements for faster access and set overlay width
  var div = $('div.film-strip'),
               ul = $('ul.gallery-layout'),
               // unordered list's left margin
               ulPadding = 15;


  //Get menu width
  var divWidth = div.width();

  //Remove scrollbars
  div.css({overflow: 'hidden'});

  //Find last image container
  var lastLi = ul.find('li:last-child');

  //When user move mouse over menu
  div.mousemove(function(e){

    //As images are loaded ul width increases,
    //so we recalculate it each time
    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
    div.scrollLeft(left);
  });

	$('div.film-strip a').each(function(){
			imagesArray[imagesArray.length] = this;
			$(this).bind('click',function(){
				clearTimeout(timer); show(this); return false;
			});
		});
	showNext();
	});

function showNext() {
	show(imagesArray[x]);
	$('div.film-strip').scrollTo($(imagesArray[x]), {duration: 1000});
	x++;
	if (x ==  imagesArray.length) x = 0;
	timer = setTimeout('showNext()', 5000);
	
	
}
function show(el) {
	$('div.film-strip a').each(function(){ $(this).removeClass('active')});
	$(el).addClass('active');
	href = $(el).attr('href');
	$('#pictureContainer').fadeOut("slow", function() {preload(href)});

}
function preload(url) {
$('#fullImage').remove();
	img = new Image();
	img.onload = function(){
				var correctSizes = fitToArea(img.width,img.height);
				img.width = correctSizes['width'];
				img.height = correctSizes['height'];
				// Need that small delay for the anim to be nice
				$('#pictureContainer').append(img);
			};
	img.src = url;
	img.id = 'fullImage';
}
function showImage(){
	$('#pictureContainer').fadeIn("slow");
}
function fitToArea(width, height){
			maxHeight = 345;
			maxWidth = 815;
			imageWidth = width;
			imageHeight = height;
			while( (imageWidth > maxWidth) || (imageHeight > maxHeight) ) {
					// Get the original geometry and calculate scales
					var xscale = maxWidth / width;
					var yscale = maxHeight / height;
				

				// Recalculate new size with default ratio
				if (yscale>xscale){
					imageWidth = Math.round(imageWidth * (1/yscale));
					imageHeight = Math.round(imageHeight * (1/yscale));
				} else {
					imageWidth = Math.round(imageWidth * (1/xscale));
					imageHeight = Math.round(imageHeight * (1/xscale));
				};
			};
		var projectedLeft = ((maxWidth - imageWidth) / 2) + 25;
			var projectedTop	= ((maxHeight - imageHeight) / 2);
		$('#pictureWrapper').animate({'height':imageHeight,'width':imageWidth,'left':projectedLeft,'top':projectedTop}, "slow", showImage);
	return {
				width:imageWidth,
				height:imageHeight
			};
}
