/**
 * jQuery Slider
 * 
 * Simple slider to slide between lists of promotions and
 * Classified entries
 * 
 * @author Koos van Egmond
 */

// Set configurations and variables used in the slider
var sliderConfig = {
	animationSpeed: 450,
	timeoutHandler: false,
	activeIndex: 0,
	slideCount: 0,
	slideInterval: 6000,
	slideWidth: 642
};


// Start functioning when DOM is ready
$(function () {
	
	// Build up the dots
	$('.slideContainer ul li').each(function(i) {
		
		// CSS hacks to fix dimensions
		/*$('tr', this)
			.width(250)
			.height(110);
		$('.summary', this)
			.width(235)
			.height(110);
		$('.priceColumn').width(105);*/
		
		// Set the html
		var slideBullet = $('<a/>')
			.attr('href', 'javascript:void(0);')
			.html('&bull;');
		
		// Add active class to first one only
		if (i == 0) slideBullet.addClass('active');
		
		// Add to slideDots div
		$('.slideDots').append(slideBullet);
		
		// Increment the slideCount
		sliderConfig.slideCount++;
	});
	
	// Bind slide open function to bullets
	$('.slideDots a').click(function() {
		
		// Get the index of the current bullet
		var index = $('.slideDots a').index(this);
		
		// Open the correct slide
		openSlide(index, true);
		return false;
	});
	
	// Start the slideshow when done loading and initializing
	startSlideShow(sliderConfig.slideInterval);
});

function openSlide(no, pause) {
	
	// Math correct offset to slide to
	var offsetLeft = 0 - (no * sliderConfig.slideWidth);
	
	// If a timeout has been set, clear it
	if (sliderConfig.timeoutHandler && pause) {
		clearTimeout(sliderConfig.timeoutHandler);
	}
	
	// Set correct bullet to active
	$('.slideDots a.active').removeClass('active');
	$('.slideDots a:eq('+no+')').addClass('active');
	
	// Set new active slider
	sliderConfig.activeIndex = no;
	
	// Animate the slider
	$('.slideContainer ul')
		.stop()
		.animate({
			marginLeft: offsetLeft
		}, sliderConfig.animationSpeed, function() {
			
			// Start slideshow again after 5 seconds
			if (pause) startSlideShow(4000);
		});
}

function nextSlide() {
	
	// Increment current index
	sliderConfig.activeIndex++;
	
	// Check if the index is not overriding the max
	if (sliderConfig.activeIndex >= sliderConfig.slideCount) {
		sliderConfig.activeIndex = 0;
	}
	
	// Open the slide
	openSlide(sliderConfig.activeIndex);
}

function startSlideShow(timeout) {
	
	// Start the timeout
	sliderConfig.timeoutHandler = setTimeout(function() {
		
		// Open the next slide
		nextSlide();
		
		// Start again after {interval} seconds
		startSlideShow(sliderConfig.slideInterval);
	}, timeout);
}
