$dr(document).ready(function(){
	
	$dr('.mainpage-slider').each(function(){
		var slider = $dr(this);
		var slides = slider.find('.mainpage-slides').children('ul').children('li');
		var slinks = slider.find('.mainpage-slider-menu').children('ul').children('li');
		var sprev = slider.find('.mainpage-slides').children('.mainpage-slider-prev').children('a');
		var snext = slider.find('.mainpage-slides').children('.mainpage-slider-next').children('a');
		var inAction = false;
		var sliderTimer;
		var sliderTimerTime = 4000;
		
		if (slides.length > 0) {
			var currentSlide = 0;
			slides.css('display', 'none');
			slides.eq(0).css('display', 'block');
			slinks.removeClass('current');
			slinks.eq(0).addClass('current');
			
			var setSlide = function (s1, s2) {
				if (s1 != s2 && !inAction) {
					inAction = true;
					slinks.removeClass('current');
					slinks.eq(s2).addClass('current');
					slides.eq(s1).fadeOut('normal');
					slides.eq(s2).fadeIn('normal', function() {
						inAction = false;
					});
					currentSlide = s2;
				}
			}
			var nextSlide = function () {
				if (currentSlide+1 >= slides.length) {
					setSlide (currentSlide, 0);
				} else {
					setSlide (currentSlide, currentSlide+1);
				}
			}
			var prevSlide = function () {
				if (currentSlide-1 < 0) {
					setSlide (currentSlide, slides.length-1);
				} else {
					setSlide (currentSlide, currentSlide-1);
				}
			}
			
			sprev.click(function(el){
				el.preventDefault();
				prevSlide();
			});
			snext.click(function(el){
				el.preventDefault();
				nextSlide();
			});
			
			slinks.each(function(){
				var lnk = $dr(this);
				lnk.children('a').click(function(el){
					el.preventDefault();
					setSlide (currentSlide, lnk.index());
				});
			});
			
			sliderTimer = setInterval(function(){
				nextSlide();
			}, sliderTimerTime);
			slides.mousemove(function (){clearInterval (sliderTimer);});
			slinks.mousemove(function (){clearInterval (sliderTimer);	});
			sprev.mousemove(function (){clearInterval (sliderTimer);});
			snext.mousemove(function (){clearInterval (sliderTimer);});
			slides.mouseout(function (){
				sliderTimer = setInterval(function(){
					nextSlide();
				}, sliderTimerTime);
			});
			slinks.mouseout(function (){
				sliderTimer = setInterval(function(){
					nextSlide();
				}, sliderTimerTime);
			});
			sprev.mouseout(function (){
				sliderTimer = setInterval(function(){
					nextSlide();
				}, sliderTimerTime);
			});
			snext.mouseout(function (){
				sliderTimer = setInterval(function(){
					nextSlide();
				}, sliderTimerTime);
			});
		}
	});
	
});