function preloadPhotos(photos) {
    $(photos).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}


function rotatePhotos(rotatePool) {

	var timePeriod = 5000;
	var fadeDuration = 'medium';
	var cnt = 0;

	if (rotatePool == null || rotatePool.length == 0) {
		return;
	}

	preloadPhotos(rotatePool);

	// Prevent rotation on product pages
	if ($('#product-gallery').length > 0) {
		return;
	}

	rotatePool.sort(function() {return 0.5 - Math.random()});
	$("#photo").css('backgroundImage', 'url(' + rotatePool[0] + ')');

	if (rotatePool.length == 1) {
		return; // Prevent blinking effect
	}

	$('#photo').everyTime(timePeriod, function() {
		cnt++;
		cnt = cnt % rotatePool.length;
        $("#photo")
    	.fadeOut(fadeDuration, function () {
    		$("#photo").css('backgroundImage', 'url(' + rotatePool[cnt] + ')');
    	})
    	.fadeIn(fadeDuration, function () {
    	});
	}, 0);
}

$(document).ready(function() {
	// Add carousel effect
	$('#product-gallery').jcarousel();

	// Add accordion effect
	$("#branches").accordion({
		autoHeight: false
	});

	// Add fancybox effect
	$("a.fancybox.photo").fancybox({
		'padding'		: 0,
		'titleShow'     : true,
		'titlePosition'	: 'inside'
	});
	$("a.fancybox.youtube").click(function() {
		$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 640,
			'height'		: 385,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
				'wmode'				: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
		return false;
	});
	$("a.fancybox.vimeo").click(function() {
		$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 640,
			'height'		: 385,
			'href'			: this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
			'type'			: 'swf',
			'swf'			: {
				'wmode'				: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
		return false;
	});

	$("#button-contact").fancybox({
		'width'				: 600,
		'height'			: 600,
        'autoScale'     	: false,
		'type'				: 'iframe',
		'scrolling'         : 'no'
	});

	$('input[placeholder],textarea[placeholder]').placeholder();

});

// Show full product images on click
$(document).ready(function() {
	$('#product-gallery a').click(function() {
		var t = this;
        $("#photo")
        	.fadeOut("medium", function () {
        		$("#photo").css('backgroundImage', 'url(' + t.href + ')');
        	})
        	.fadeIn("medium", function () {
        	});
        return false;
    });
});

$(document).ready(function() {
   setTimeout(function() {
	   $('#content').jScrollPane();
   }, 400);
});

