/* ****************************************************************************************************
 * ken-buist.js
 * Written by Base Creative for Ken Buist
 * 
 */

$(document).ready(function()
{

// for the latest-news header rotator
if (document.getElementById('top-blog-content')) {
	var sInterval = null;
	var topdiff = $('#top-blog-content').height() - $('#top-blog').height();
	$('#top-blog-content').css('position', 'absolute').css('top', '0px');
	var scrollTb = function(dir) {
		var top = $('#top-blog-content').css('top');
		top = dir + parseInt(top.substring(0, top.length-2));
		if (top > 0) top = 0;
		if (top < (0 - topdiff)) {
			top = 0 - topdiff;
		}
		$('#top-blog-content').css('top', top + 'px');
	};
	$('#top-blog-up').mouseenter(function() {
		sInterval = setInterval(function() { scrollTb(3); }, 50);
	}).mouseout(function() {
		clearInterval(sInterval);
	});;
	$('#top-blog-down').mouseenter(function() {
		sInterval = setInterval(function() { scrollTb(-3); }, 50);
	}).mouseout(function() {
		clearInterval(sInterval);
	});;
}

// grab some divs!!
$gWrapper = $('div#gallery-wrapper');
$gHeader = $('div#header', $gallery);
$ghCentre = $('div.fixed-centre:first', $gHeader);
$gFooter = $('div#gallery-footer', $gallery)
$gfCentre = $('div.fixed-centre:first', $gFooter);

// Setup the wrapper element
$gWrapper.css('overflow','hidden').css('position','absolute').css('margin-left', 0);

// Grab the height of the header & footer
var hh = $gHeader.height();
var fh = $gFooter.height();

var galMinHeight = 200;
var galMaxHeight = 600;

var reflectionHeight = 40;

// Default dimensions of the horizontal container
var galHeight = 600;
var galWidth = $gallery.width();

// Set to true while movement is mid-animation
var galleryMoving = false;

// Object to handle scrollbar movement
var scrollbar = { mousedown: false,
		          dragging: false,
		          position: 0,
		          // local mouse x position on mousedown
		          mxOffset: 0,
		          bar: $('#gallery-scrollbar'),
		          // total width of the scrollbar movement area
		          // why doesn't this return a width for gallery-scrollbar??
		          tWidth: ($('#gallery-scroll').width() - 166/*$('#gallery-scrollbar').width()*/)
		         };

// create the reflection containers
for (var i = 0; i < totalPhotos; i++)
{
	photos[i].$.css('position', 'absolute');
	photos[i].$.after('<div class="r-gphoto" id="r-gphoto-' + i + '"></div>');
	photos[i].reflection = $('div#r-gphoto-' + i, $gallery);
	photos[i].$.load(function() {
		var i = parseInt(this.id.substring(7));
		photos[i].isLoaded = true;
		updateReflection(i, photos[i].$.width(), photos[i].$.height(), parseInt(photos[i].$.css('left')), true);
	});

}

//Postpone loading images outside the window view
$('.gphoto', $gallery).lazyload({ 
    placeholder : "/content/themes/kenbuist/images/fade.gif",
    effect : "fadeIn",
    container: $gWrapper,
    event: 'loadImage'
});

//Load images that have appeared within the window view if not allready loaded
galleryLazyLoad = function()
{
	var ww = $(window).width();
	var gxo = Math.abs(parseInt($gallery.css('margin-left')));
	for (var i = 0; i < photos.length; i++) {
		if (photos[i].loaded) continue;
		var il = parseInt(photos[i].$.css('left'));
		var diff = il - gxo;
		if (diff >= 0 && diff < ww) {
			photos[i].loaded = true;
			photos[i].$.trigger('loadImage');
		}
	}
};

// update (and create initally) the actual reflections for a single image
var updateReflection = function(i, iw, ih, il, force)
{
	if (!photos[i].isLoaded) return;
	if (force || !photos[i].reflected) {
		photos[i].reflection.html('');
		var img = document.getElementById(photos[i].id);
		if ($.browser.msie) {
			reflection = $("<img />").attr("src", img.src).css({
				width: iw, height: ih,
				filter: "flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + reflectionHeight + ")"
			})[0];
			photos[i].reflection.append(reflection);
		} else {
			//var i = parseInt(this.id.substring(7));
			var canvas = document.createElement('canvas');
			if (canvas.getContext) {
				var context = canvas.getContext("2d");
				try {
					canvas.width = iw;
					canvas.height = ih;
					context.save();
					context.translate(0, ih-1);
					context.scale(1, -1);
					context.drawImage(img, 0, 0, iw, ih);
					context.restore();
					context.globalCompositeOperation = "destination-out";
					photos[i].reflection.append(canvas);
				} catch(e) {
					//console.log(e);
				}
			}
		}
	}
	photos[i].reflected = true;
	photos[i].reflection.css('height','100px').css('width',iw+'px').css('top',hh+ih+'px').css('left',il+'px');
	$('canvas:first', photos[i].reflection).css('height',ih+'px').css('width',iw+'px');
};

// make the fixed elements behave on scrolls
var updateWindowScroll = function()
{
	var yo = $(window).scrollTop();
	if (yo > 0) {
		$ghCentre.css('margin-top', '-' + yo + 'px');
		$gfCentre.css('margin-top', '-' + yo + 'px');
	} else {
		$ghCentre.css('margin-top', '0');
		$gfCentre.css('margin-top', '0');
	}
};

// update gallery size to fit screen
var updateGallerySize = function()
{
	// update the wrapper element
	wWidth = $(window).width();
	wHeight = $(window).height();
	//if (wWidth < 960) wWidth = 960;
	if (wHeight < (galMinHeight + hh + fh)) wHeight = (galMinHeight + hh + fh);
	$gWrapper.css('width', wWidth + 'px').css('height', wHeight + 'px');

	// find the gallery height
	galWidth = 0;
	galHeight = ($(window).height() - (hh + fh));
	if (galHeight < galMinHeight) galHeight = galMinHeight;
	if (galHeight > galMaxHeight) galHeight = galMaxHeight;
	// update the height of the gallery
	$gallery.css('height', galHeight+'px');
	for (var i = 0; i < totalPhotos; i++)
	{
		// calculate the height and width of each image
		var nw = 0;
		var nh = 0;
		if (photos[i].fixedwidth) {
			nw = photos[i].$.width();
		} else {
			nw = Math.ceil(photos[i].r * galHeight);
		}
		if (photos[i].fixedheight) {
			nh = photos[i].$.height();
		} else {
			nh = galHeight;
		}
		// position the image
		photos[i].$.css('height',nh+'px').css('width',nw+'px').css('left',galWidth+'px');
		updateReflection(i, nw, nh, galWidth);
		// use margin top as place holder for yOffset
		/*if (photos[i].$.css('margin-top')) {
			photos[i].$.css('top', photos[i].$.css('margin-top') + 'px');
		}*/
		galWidth += nw;
	}
	// update the total width of the horizontal gallery
	if (galWidth == 0) {
		$gallery.css('width', '100%');
	} else {
		if (galWidth < $gWrapper.width()) {
			galWidth = $gWrapper.width();
		}
		$gallery.css('width', galWidth + 'px');
	}
	galleryLazyLoad();
	updateWindowScroll();
};

// Control gallery movement left/right snapping to photo edge
var galleryMove = function(direction)
{
	if (galleryMoving) return false;
	var xOffset = Math.abs(parseInt($gallery.css('margin-left')));
	var newXOffset = 0;
	// Make sure we don't scroll past the left bounds
	if (xOffset == 0 || xOffset < photos[0].$.width()) {
		if (direction == 'prev') {
			newXOffset = 0;
		} else if (direction == 'next') {
			newXOffset = photos[0].$.width();
		}
	} else {
		// Find the new photo x-axis offset
		for (var i = 0; i < photos.length; i++) {
			newXOffset += photos[i].$.width();
			if (direction == 'prev') {
				if (newXOffset >= xOffset) {
					newXOffset -= photos[i].$.width();
					break;
				}
			} else if (direction == 'next') {
				if (newXOffset > xOffset) {
					break;
				}
			}
		}
	}
	// Make sure we don't scroll past the right bounds
	if (($gallery.width() - newXOffset) < $(window).width()) {
		newXOffset = $gallery.width() - $(window).width();
	}
	// If there is no different we don't need to animate
	var difference = (newXOffset - xOffset);
	if (difference == 0) return;
	// Animate the gallery with a time relative to the difference
	galleryMoving = true;
	$gallery.stop(true).animate({ marginLeft: '-=' + difference }, Math.abs(difference) + 150, function() {
		galleryMoving = false;
		galleryLazyLoad();
	});

	// Need to move the gallery scrollbar here!
};

var galleryMoveToPercent = function(percent)
{
	var xOffset = Math.abs(parseInt($gallery.css('margin-left')));
	var newXOffset = Math.round((($gallery.width() - $(window).width()) / 100) * percent);
	// Bounds check for left / rigt
	if (xOffset < 0) newXOffset = 0;
	if (($gallery.width() - newXOffset) < $(window).width()) {
		newXOffset = $gallery.width() - $(window).width();
	}
	var difference = (newXOffset - xOffset);
	if (difference == 0) return;

	$gallery.css('margin-left', -newXOffset + 'px');
	galleryLazyLoad();
};

var galleryScrollMove = function(e) {
	// Remember the last mouse position to get direction & speed
	if (!scrollbar.dragging) {
		scrollbar.dragging = true;
		scrollbar.lastX = e.pageX;
		return;
	}
	// Bounds check for mouseX relative to document
	if (scrollbar.lastX < 0) scrollbar.lastX = 0;
	if (scrollbar.lastX > $(window).width()) scrollbar.lastX = $(window).width();
	// Get position of the scrollbar
	scrollbar.position = scrollbar.lastX;
	var extra = 0;
	if ($(window).width() > scrollbar.tWidth) {
		extra = $(window).width() - scrollbar.tWidth;
		scrollbar.position -= Math.round(extra / 2);
		// Bounds check for mouseX relative to scrollbar
		if (scrollbar.position > scrollbar.tWidth) scrollbar.position = scrollbar.tWidth;
		if (scrollbar.position < 0) scrollbar.position = 0;
	}
	// Position the scrollbar
	scrollbar.bar.css('left', scrollbar.position + 'px');
	// Get the percentage amd scroll the gallery to it
	scrollbar.percent = Math.round((100 / scrollbar.tWidth) * scrollbar.position);
	galleryMoveToPercent(scrollbar.percent);
	scrollbar.lastX = e.pageX;
};

//Manage scrollbar movement
$('#gallery-scroll-prev').click(function() {
	galleryMove('prev');
});
$('#gallery-scroll-next').click(function() {
	galleryMove('next');
});

$('#gallery-scrollbar').mousedown(function(e) {
	// Ignore mousedown of scroll-prev / scroll-next
	if (e.target != this) return;
	scrollbar.mousedown = true;
	scrollbar.mxOffset = e.layerX;
	$(document).bind('mousemove', galleryScrollMove);
});

$(document).mouseup(function(e) {
	if (scrollbar.mousedown) {
		scrollbar.dragging = false;
		scrollbar.mousedown = false;
		$(document).unbind('mousemove');
	}
});

// Update on key movement
$(document).keydown(function(e) {
	if (e.keyCode == 37 || e.keyCode == 38) {
		if (galleryMoving) return false;
		galleryMove('prev');
	}
	if (e.keyCode == 39 || e.keyCode == 40) {
		if (galleryMoving) return false;
		galleryMove('next');
	}
});

//Show scrollbars
$('#gallery-scroll').css('display', 'block');

// Update on window resize and scroll
$(window).resize(updateGallerySize);
$(window).scroll(updateWindowScroll);

// Update size on load
updateGallerySize();

// manage albums

//$('.album .description', '#gallery').css('display', 'none');
$('.album img', '#gallery').click(function() {
	var url = $(this).parent().children('h2:first').children('a:first').attr('href');
	if (url) document.location.href = url;
})/*.mouseover(function() {
	$(this).parent().children('.description').show();
}).mouseleave(function() {
	$(this).parent().children('.description').hide();
});*/

});
