// Chrome sucks, this makes life easier:
jQuery.fn.aPosition = function() {
	thisLeft = this.offset().left;
	thisTop = this.offset().top;
	thisParent = this.parent();
	parentLeft = thisParent.offset().left;
	parentTop = thisParent.offset().top;
	return {
		left: thisLeft-parentLeft,
		top: thisTop-parentTop
	}
}

// And here we go
function homepageSlideshow(what, icon, rotationTime, bidirectional) {

	if ($(what).size() <= 0) return;

	var el = what;
	var current;
	var container = $("<div class=\"slider_container\"></div>");
	var items = $(el).children();
	var totalWidth = 0;
	var totalInited = 0;
	var rotationTimer;
	var rotationPointer = 1;
	var scrollKilled = false;

	// add a container to put the images in
	el.append(container);

	// Arrange el overflow, handle loading
	items.each(function() {

		var item = this;

		// Fix sliding
		$(item).css({
			'float': 'left',
			'clear' : 'none'
		});

		// Push elements into container
		$(container).append(item);

		if (!$(item).is('img')) {
			item = $('img', item).get(0);
		}

		// handle loading
		$(item).load(function() {
			totalWidth += $(this).width();
			$(container).css('width',totalWidth);
			totalInited++;

			// If we're all loaded, it's time to run the slider
			if (totalInited >= $(items).size()) {
				$(iconsHolder).fadeIn('fast');
			}
		});

		if (item.complete) {
			$(item).trigger("load");
		}
	});

	// Fix slider sliding issues
	el.css({
		'float' : 'left',
		'overflow' : 'hidden',
		'clear' : 'none'
	});

	// rearrange the icons container
	var iconsHolder = $("#slideshow .toggles");
	//$(el).append(iconsHolder);
	// Hide holder until we're fully loaded?
	//$(iconsHolder).hide();

	var animate = function(who) {

		if (current == who) return;			
		current = who;

		// Fade out icons
		$('#slideshow .slider_icon').css('opacity', 0.5);
		$(current).css('opacity', 1);

		if (!bidirectional) {
			var e2 = $($(who).data('show'));
			$(container).append(e2);
			$(el).scrollLeft(0);
		}
		// Slide
		$(el).animate({ scrollLeft : $($(who).data('show')).aPosition().left }, "slow");
	}

	// Add icons
	items.each(function() {
		var that = this;
		var itemIcon = $("<img class=\"slider_icon\" src=\""+icon+"\" />");
		itemIcon.data('show', that).css({'opacity' : 0.5});

		$(itemIcon).click(function() {
			animate(this);

			// Kill the interval
			clearInterval(rotationTimer);
		});
		iconsHolder.append(itemIcon);
	});

	// Hilight first icon, make it current
	$(".slider_icon:first").css("opacity",1);
	current = $(".slider_icon:first").get(0);

	// Start timer?
	if (rotationTime && rotationTime >= 250) {
		rotationTimer = setInterval(function() {
			animate($('.slider_icon:nth-child('+(rotationPointer+1)+')'));

			if (rotationPointer < $(items).size()-1) {
				rotationPointer++;
			}
			else {
				rotationPointer = 0;
			}
		}, rotationTime);
	}

}


