jQuery(document).ready(function() {
	//only swap is focus on window
	var focusFlag = 1;
	jQuery(window).bind("focus", function(event){
		focusFlag = 1;
	});
	jQuery(window).bind("blur", function(event){
		focusFlag = 0;
	});

	jQuery('.carousel_wrap').each(function() {
		var firstLi = jQuery(this).children('ul').children('li')[0];
		jQuery(firstLi).addClass('act');

		var width = jQuery(firstLi).css('width');

		var ul = jQuery(this).children('ul')[0];
		jQuery(ul).css('width', jQuery(this).children('ul').children('li').size() * parseInt(width.substr(0, (width.length -2))) + 'px');

		setTimeout(timelyMovement, 7000);
	});
	jQuery('.carousel_wrap').bind('mouseover', function() {
		this.hovering = true; });
	jQuery('.carousel_wrap').bind('mouseout', function() {
		this.hovering = false; });

	jQuery('.carousel_nav_prev').bind('click', function() { navigate(this, 'backwards') });
	jQuery('.carousel_nav_next').bind('click', function() { navigate(this, 'forward') });

	function timelyMovement() {
		jQuery('.act .carousel_nav_prev').each(function() {
			if (focusFlag == 1){
				navigate(this, 'auto');
			}
		});
		setTimeout(timelyMovement, 7000);
	}

	function navigate(sourceObject, direction) {
		var carousel = jQuery(sourceObject).closest('div.carousel_wrap');
		var active = -1;

		if (direction == 'auto' && carousel.get(0).hovering == true) return;

		jQuery(carousel).children('ul').each(function() {

			for(var i = 0; i < this.childNodes.length; i++) {
				if (jQuery(this.childNodes[i]).hasClass('act')) {
					active = i;
					break;
				}
			}

			var list = jQuery(carousel).children('ul')[0];
			var firstLi = jQuery(list).children('li')[0];
			var itemWidth = jQuery(firstLi).css('width');
			itemWidth = parseInt(itemWidth.substr(0, (itemWidth.length -2)));

			if (direction == 'auto') {
				if (this.lastKnownDirection == null) this.lastKnownDirection = 'forward';
				if((active+1) == jQuery(this).children().size()) {
					direction = 'backwards';
				} else if (active == 0) {
					direction = 'forward';
			   	} else {
					direction = this.lastKnownDirection;
				}
				if (this.lastKnownDirection != direction) this.lastKnownDirection = direction;
			}


			switch(direction) {
				case 'forward':
					if((active+1) != jQuery(this).children().size()) {

						jQuery('.act', this).removeClass('act').next('li').addClass('act');

						jQuery(list).animate({
							left: '-=' + itemWidth
						},600);
					}

					break;
				case 'backwards':
					if(active >= 1) {
						jQuery('.act', this).removeClass('act').prev('li').addClass('act');

						jQuery(list).animate({
							left: '+=' + itemWidth
						},600);
					}

					break;
			}

			return;
		});
	}

});

