$(function() {
	function setBackgroundMainWrapper() {
		$('#main_wrapper').css('background-position', Math.floor($("#cont").width()) +'px 80px');
	}
	
	setBackgroundMainWrapper();
	setInterval(setBackgroundMainWrapper, 20);

	if($('#info_carousel ul li').length < 2) {
		$('#info_carousel + span a').remove();
	} else {
		$('#info_carousel ul').simpleCarousel({
			btnNext : '.next',
			btnPrev : '.prev',
			auto: true
		});
	}
	
	new function() {
		var 
			current_idx = 0,
			ol = $('.services-accent-wrapper ol'),
			elements = ol.find('li'),
			elements_length = elements.length,
			pages = $('.services-accent-wrapper ul li');
		
		if(pages.length)
		{
			var 
				pages_length = pages.length,
				page_width = Math.floor(($('.services-accent-wrapper').width() - (pages_length - 1)) / pages_length),
				last_page_width = $('.services-accent-wrapper').width() - (pages_length - 1) * ( 1+ page_width ),
				$allow_animated = true,
				$go_to_last = false,
				timeout = null,
				time_for_automatic_change = 7000;
			
			ol.width(elements_length * (elements.first().width() + 10)).css('position', 'relative');
			pages.width(page_width).last().width(last_page_width);
			pages.first().addClass('selected');
			
			pages.click(function(){
				if(!$allow_animated) return;
				var idx = $.inArray(this, pages);
				if(timeout) clearTimeout(timeout);
				if(current_idx != idx) {
					$allow_animated = false;
					
					$($(pages).get(current_idx)).removeClass('selected');
					$($(pages).get(idx)).addClass('selected');
					
					var 
						width = 0,
						elements_to_slice;
					
					if(idx > current_idx) {
						if(idx + 1 == pages_length) {
							elements_to_slice = elements.slice(current_idx * 4, idx * 4 - (4 - elements_length % 4));
						} else {
							elements_to_slice = elements.slice(current_idx * 4, idx * 4);
						}
					} else {
						if(idx == 0) {
							elements_to_slice = [];
							width = Math.abs(parseInt(ol.css('left'))) - 1;
						} else {
							elements_to_slice = elements.slice(idx * 4, current_idx * 4);
						}
					}
					
					$.each(elements_to_slice, function(idx, li){
						width += $(li).width() + parseInt($(li).css('border-left-width'));
					});
					
					ol.animate({left: (current_idx > idx ? '+' : '-')+'='+(width + 1)}, 700, function(){
						$allow_animated = true;
						current_idx = idx;
						timeout = setTimeout(automatic_change, time_for_automatic_change);
					});
				} else {
					timeout = setTimeout(automatic_change, time_for_automatic_change);
				}
			});
			
			function automatic_change() {
				$(pages[current_idx + 1] || pages[0]).trigger('click');
			}
			
			timeout = setTimeout(automatic_change, time_for_automatic_change);
		}
	};

});
