$(document).ready(function() {
	initDetailer($('#p1m-product-detailer'));
	$("#tabs").tabs();
});

jQuery.fn.slowEach = function( interval, callback ) {
	var array = this;
	if( ! array.length ) return;
	var i = 0;
	next();
	function next() {
	    if( callback.call( array[i], i, array[i] ) !== false )
			if( ++i < array.length )
				setTimeout( next, interval );
}
}; 

function initDetailer(element)
{
	// Set random start Product
	var $areas = $("#p1m-product-detailer map area"),
		stopAnimation = false;

	/**
	 * When an element is hovered over, update detail pane (if defined) 
	 */
	function hoverAnimation(element, speed)
	{
		if (!speed)
			speed = 150;
			
		$(".details").queue(function() {
			$(this).fadeOut(speed);
			$(this).animate({opacity:1}, 0, function() { changeContent(element) });
			$(this).dequeue();
			$(this).fadeIn(speed);
		});
	}
	
	/*
	 * Changes the detail pane's content 
	 */
	function changeContent(element)
	{
		var contentId = element.attr('class');
		var content = $('.product-content #'+contentId);
		var contentHolder = $('#p1m-product-detailer .details');
		contentHolder.find('h1').html(content.find('h1').html());
		var newImageSrc = content.find('img:first').attr('src') ? content.find('img:first').attr('src') : "";
		 
		contentHolder.find('img:first').attr('src', newImageSrc);
		contentHolder.find('ul').html(content.find('ul').html());
	}

	// hook up hover and nav button events
	$areas.hover(function() {
		stopAnimation = true;
		hoverAnimation($(this));
	});
	
	$areas.slowEach(2000, function() {
		if (!stopAnimation)
			hoverAnimation($(this), 1000); 
	});
	$(".product-content").accordion();
	$(".details-header").addClass("ui-corner-all");
	$(".product-content img").addClass("ui-corner-all");
	$(".product-content ul").addClass("ui-corner-all");
}