$(document).ready(function () {

	// ********** variables **********
	// css properties
	var teaser = $('#teaser');
	var teaser_width = teaser.css('width');
	var window = $('#teaser_window', teaser);
	var window_width = window.css('width');
	var dots = $('#teaser_dots', teaser);
	var dot_width = $('div', dots).css('width');
	
	// state machine
	var states = $('div.content', window).length;
	var state = 0;
	var old_state = 0;
	var direction = 0;
	
	// setup dots
	var dots_width = dot_width*states;
	var dots_position = (teaser_width-dots_width)/2;
	dots.css({ 'width': dots_width, 'left': dots_position });
	
	// animation
	var autoscroll_speed = 6000;
	var duration = 500;
	var easing_type = 'easeSine';
	
	// ********** functions **********
	
	// initialize autoscroll
	var doScroll = function () {
		if (direction == 0) {
			nextTeaser();
		}
		else {
			prevTeaser();
		}
	};
	
	// change to previous teaser
	var prevTeaser = function () {
		old_state = state;
		state = (states+state-1) % states;
		direction = 1;
		updatePosition();
	};
	
	// change to next teaser
	var nextTeaser = function () {
		old_state = state;
		state = (state+1) % states;
		direction = 0;
		updatePosition();
	};
	
	// perform scroll animation
	var updatePosition = function () {
		if (direction) {
			$('#content'+state, window).stop().css('left', '-' + window_width).animate({ 'left': 0}, {easing: easing_type, duration: duration});
			$('#content'+old_state, window).stop().css('left', 0).animate({ 'left': window_width}, {easing: easing_type, duration: duration});
		}
		else {
			$('#content'+state, window).stop().css('left', window_width).animate({ 'left': 0}, {easing: easing_type, duration: duration});
			$('#content'+old_state, window).stop().css('left', 0).animate({ 'left': '-' + window_width}, {easing: easing_type, duration: duration});
		}
		updateDots();
	};
	
	// show active state
	var updateDots = function () {
		$('div:eq('+old_state+')', dots).removeClass('active');
		$('div:eq('+state+')', dots).addClass('active');
	};
	
	// ********** functionality **********
	
	// show active state
	$('#content'+state, window).stop().css("left", 0);
	updateDots();
	
	// previous page
	$('#teaser_prev', teaser).click(prevTeaser);
	
	// next page
	$('#teaser_next', teaser).click(nextTeaser);
	
	// initialize autoscroll
	teaser.everyTime(autoscroll_speed, 'teaser_scroll', doScroll);
	
	// stop autoscroll when hover over teaser
	teaser.hover( function () {
		$(this).stopTime('teaser_scroll');
	},
	function () {
		$(this).everyTime(autoscroll_speed, 'teaser_scroll', doScroll);
	});
});


jQuery.extend( jQuery.easing, {
	easeSine: function (p, t, s, e, d) {
		return e*Math.sin(t/d*Math.PI/2) + s;
	}
});
