$( function() {
	if( typeof slideWidget === "undefined" )
		return;
		
	var busywidget = false;
	var slideInterval;
	var activeSlide;
	var $mark		= 0;
	var timer		= {};
	var slides		= [];
	var fields		= 'Days Hours Minutes Seconds'.split(/\s+/);
	var llist		= {ru: {days:'День Дня Дней'.split(/\s+/),hours:'Час Часа Часов'.split(/\s+/),
					minutes:'Минута Минуты Минут'.split(/\s+/),seconds:'Секунда Секунды Секунд'.split(/\s+/)},
						en: {days: "Day Days".split(/\s+/), hours: "Hour Hours".split(/\s+/),
							minutes: "Minute, Minutes".split(/\s+/), seconds: "Second Seconds".split(/\s+/)}};
							
	var lang 		= slideWidget.lang || "en";
	
	// кешируем общих родителей для более быстрого последующего поиска элементов внутри них	
	var JqSWIB		= $( '.slidewidgetinfobar' );
	var JqSW		= $( '.slidewidget' );
	var JqSWSW		= $( '.slideswitcher li', JqSW );
	var JqSWST		= $( '.slidestack li', JqSW );
	var JqTLW		= $( '.timeleft-wrapper' );
	var JqLF		= $( '.lotteryfinished' );
	var JqPS		= $( '.purchasebutton' );
	var JqPSC		= $( '.controller', JqPS );
	
	var renderTimeLeft = function() {
		var $$mark = Math.max( ( $mark * 1000  - (new Date()).getTime() ), 0 );
		var timeleft = new Date( $$mark );
		var gettime = timeleft.getTime();
		
		if( slideWidget.authorized ) {
			JqPS.css({ display: (activeSlide.purchase && !( $$mark < 1 )) ? 'block' : 'none' });
			JqPSC.attr({ href: activeSlide.controlhref });
		}
		
		if( $$mark < 1 ) {
			JqTLW.css({display: "none"});
			JqLF.css({display: "block"});
			return;
		}
		
		JqLF.css({display: "none"});
		JqTLW.css({display: "block"});
		$.each( fields, function( index, field ) {
			var $field = field.toLowerCase();
			var count;
			var text;
			
			if( $field == 'days' )
				count =	( gettime >= 86400000 ) ? parseInt( gettime / 86400000 ) : 0;
			else
				count =	timeleft[ 'getUTC' + field ]();
				
			// Обновляем значене только если оно изменилось ( взаимодействие с DOM - лишняя нагрузка )
			if( timer[$field].curCountValue != count ) { 
				timer[$field].count.html( timer[$field].curCountValue = count );
				text = numeral( count, llist[lang][$field] );
				
				// Обновляем значене только если оно изменилось
				if( timer[$field].curTextValue != text )
					timer[$field].text.html( timer[$field].curTextValue = text );
			}
		});
		
	};
	
	var $$render = function() {
		renderTimeLeft();
	};
	
	var numeral = function( value, list ) {
		if( lang == "en" ) {
			if( value == 1 )
				return list[0];
			else
				return list[1];
		}
				
		value = value.toString();
		
		if( value.length > 2 )
			value = value[value.length-2] + value[value.length-1];
			
		if( value.length == 1 )
			value = "0" + value;
			
		if( value[0] == "1" ) // 1*
			return list[2];
			
		if( +value[1] > 1 && +value[1] < 5 ) // *2-4
			return list[1];
			
		if( value[1] == '1' ) //*1
			return list[0];
			
		// ещё тут?
		return list[2]; // *0,*5-9
	};
	
	var setTimerMark = function ( value ) {
		$mark = value;
		renderTimeLeft();
	};
	
	var switchSlide = function( index ) {
		if( activeSlide && activeSlide.index == index ) 
			return;
			
		if( busywidget )
			return;
			
		if( activeSlide ) {
			$$oldContent = activeSlide.content;
			busywidget = true;
			activeSlide.controller.removeClass( 'active' );
			slides[index].controller.addClass( 'active' );
			activeSlide.content.css( 'z-index', 1 );
			setTimerMark( slides[index].mark );
			activeSlide = slides[index];
			setTimerMark( slides[index].mark );
			slides[index].content.css({'z-index':2, 'opacity': .2, 'display': 'block'});
			slides[index].content.animate( {'opacity': 1}, 300, 'linear', function() {
				$$oldContent.css( 'display', 'none' );
				busywidget = false;
			});
		}
		else {
			slides[index].content.css( 'display', 'block' );
			slides[index].controller.addClass( 'active' );
			activeSlide = slides[index];
			setTimerMark( slides[index].mark );
		}

		//renderTimeLeft();

	};
	
	var switchNextSlide = function(){
		var index = activeSlide.index;
		
		if( index > 2 )
			index = 0;
		else 
			index++;
			
		switchSlide( index );	
	};
	
	var $$slide = function(){
		switchNextSlide();
	}
	
	// prgoram begin
	$.each( fields, function( index, field ) {
		var $field		= field.toLowerCase();
		// кешируем общих родителей
		var timeritem	= $( '.timeritem' + $field, JqSWIB ); 
		
		timer[$field]	= {count:$( '.count' , timeritem )	, text:$( '.headline', timeritem )};
	});
	
	JqSWSW.each( function( index, el ) {
		var content = JqSWST.eq( index );
		slides[index] = {controller:$(el), content:content, index:index, mark:content.attr( 'data-timeleft' ), purchase:content.attr( 'data-enabled' ), controlhref:content.attr( 'data-href' ) };
		
		slides[index].controller.click( function(){
			switchSlide( index );
		});
	});
	
	if( !slideWidget.switcherTurnOn ) {
		JqSW.addClass( 'noswitch' );
		$( '.slideswitcher', JqSW ).css( 'display', 'none' );
		switchSlide( 0 );	
		setTimerMark( JqSWST.eq( 0 )
			.css( 'display', 'block' )
			.attr( 'data-timeleft' ) );
	}
	else {		
		JqSW.hover( function(){
			clearInterval( slideInterval );
		}, function(){
			slideInterval = setInterval( $$slide, 5000 );
		});
		slideInterval = setInterval( $$slide, 5000 );
		switchSlide( 0 );	
	}
	
	setInterval( $$render, 1000 );
	
} );
