$(document).ready(function(event){

	var COUNTDAYS = 7,
		scrolledTimes = 0,
		scrolledTimesLeft = 0;
	
	$('.carousel_left ul').css('width', (175*VISIBLEWEEKS)+'px'); 
	$('.cal_scroll ul').css('width', (455*VISIBLEWEEKS)+'px'); 
		
	checkViewDate();

	
	weeksGenerate();
	arrowsStatus();
	
	definePeriod();
	definePeriod(1);
	
/* Check viewDate */
function checkViewDate() {
	var temp1 = new Date(), tempNow = new Date();
	
	temp1.setTime(nowDate.getTime());   
                   
	if(nowDate.getDay()) {
		temp1.setDate(nowDate.getDate() + (VISIBLEWEEKS * COUNTDAYS) - nowDate.getDay());
	}
	else {
		temp1.setDate(nowDate.getDate() + (VISIBLEWEEKS * COUNTDAYS) - COUNTDAYS);
	}																		//temp - последний день n-недельного периода
//	console.log(temp1);
	if ((viewDate < nowDate)||(viewDate > temp1)) {
		viewDate.setTime(nowDate.getTime());
	}
	else {
		temp1.setTime(nowDate.getTime());
		if(nowDate.getDay()) {
			temp1.setDate(nowDate.getDate() - nowDate.getDay() + 1);             //temp - первый день n-недельного периода
		} else {
			temp1.setDate(nowDate.getDate() - COUNTDAYS + 1);   
		}
		
		tempNow.setTime(viewDate.getTime());
		if(viewDate.getDay()) {
			tempNow.setDate(viewDate.getDate() - viewDate.getDay() + 1);             // понедельник недели viewDate
		} else {
			tempNow.setDate(viewDate.getDate() - COUNTDAYS + 1);   
		}

		
		scrolledTimes = Math.round(((tempNow - temp1) / (1000 * 60 * 60 * 24))/7);
		$('.carousel>ul').css('margin-left', ((455 * scrolledTimes)*(-1)));
//		console.log(scrolledTimes);
	}
}
/* Defines the period for visible week */
function definePeriod(left)
{
	var begin = new Date(), 
		end = new Date(),
		left; 
	
	if (left) {
		begin.setTime(nowDate.getTime());
		end.setTime(nowDate.getTime());
		if(nowDate.getDay()) {												// определяем начальный день, отнимем от текущего числа день недели
			begin.setDate(nowDate.getDate() - (nowDate.getDay() - 1));
			end.setDate(nowDate.getDate() + COUNTDAYS - nowDate.getDay());
		}
		else {
			begin.setDate(nowDate.getDate() - COUNTDAYS);
			end.setDate(nowDate.getDate());
		}	
		if(scrolledTimesLeft) {
			begin.setDate(begin.getDate() + (COUNTDAYS * scrolledTimesLeft));
			end.setDate(end.getDate() + (COUNTDAYS * scrolledTimesLeft));
		}
		
		if (begin.getMonth() === end.getMonth()) 
			$('.calendar>.date').html( begin.getDate() + ' &ndash; ' + end.getDate() + ' ' + MONTHS[end.getMonth()]);
		else 
			$('.calendar>.date').html( begin.getDate() + ' ' + MONTHS[begin.getMonth()] + ' &ndash; ' + end.getDate() + ' ' + MONTHS[end.getMonth()]);
	}
	else {
		begin.setTime(nowDate.getTime());
		end.setTime(nowDate.getTime());
		if(nowDate.getDay()) {												// определяем начальный день, отнимем от текущего числа день недели
			begin.setDate(nowDate.getDate() - (nowDate.getDay() - 1));
			end.setDate(nowDate.getDate() + COUNTDAYS - nowDate.getDay());
		}
		else {
			begin.setDate(nowDate.getDate() - COUNTDAYS + 1);
			end.setDate(nowDate.getDate());
		}	
//		console.log(begin+'   '+end);
		if(scrolledTimes) {
			begin.setDate(begin.getDate() + (COUNTDAYS * scrolledTimes));
			end.setDate(end.getDate() + (COUNTDAYS * scrolledTimes));
		}
		
		if (begin.getMonth() === end.getMonth()) 
			$('.date_cur_afisha').html( begin.getDate() + ' &ndash; ' + end.getDate() + ' ' + MONTHS[end.getMonth()]);
		else 
			$('.date_cur_afisha').html( begin.getDate() + ' ' + MONTHS[begin.getMonth()] + ' &ndash; ' + end.getDate() + ' ' + MONTHS[end.getMonth()]);
	}
}
/* Check left/right arrows for enable/disable */	
function arrowsStatus()
{
	$('.cal_scroll>.r_arr, .cal_scroll>.l_arr, .carousel_left_prev, .carousel_right_prev').removeClass('disabled');
	
	if(scrolledTimes == 0) {
		$('.cal_scroll>.l_arr').addClass('disabled');
		$('.cal_scroll>.r_arr').removeClass('disabled');
	}
	if(scrolledTimes == (VISIBLEWEEKS - 1)) {
		$('.cal_scroll>.l_arr').removeClass('disabled');
		$('.cal_scroll>.r_arr').addClass('disabled');
	}		

	if(scrolledTimesLeft == 0) {
		$('.carousel_left_prev').addClass('disabled');
		$('.carousel_left_next').removeClass('disabled');
	}
	if(scrolledTimesLeft == (VISIBLEWEEKS - 1)) {
		$('.carousel_left_prev').removeClass('disabled');
		$('.carousel_left_next').addClass('disabled');
	}	
}

/* Click arrows main */
$('.r_arr').click(function(){
    if (!$('.cal_scroll>.r_arr').hasClass('disabled')) {
		scrolling(-455, '.carousel>ul', 800, 0);
	    scrolledTimes++;
	    arrowsStatus();
        definePeriod();
    }
});

$('.l_arr').click(function(){
    if (!$('.cal_scroll>.l_arr').hasClass('disabled')) {
		scrolling(455, '.carousel>ul', 800, 0);
		scrolledTimes--;
		arrowsStatus();
        definePeriod();
    }
});
/* Click arrows left*/
$('.carousel_left_next').click(function(){
    if (!$('.carousel_left_next').hasClass('disabled')) {
		scrolling(-175, '.carousel_left>ul', 700, 1);
	    scrolledTimesLeft++;
	    arrowsStatus();
	    definePeriod(1);
    }
});
$('.carousel_left_prev').click(function(){
    if (!$('.carousel_left_prev').hasClass('disabled')) {
	    scrolling( 175, '.carousel_left>ul', 700, 1);
	    scrolledTimesLeft--;
	    arrowsStatus();
	    definePeriod(1);
	}
});

/* Scrolling */
function scrolling(offset, selector, speed, left)
{
    var step, offset, selector, speed, left;
    $(selector).stop(true, true);
    if (left){
        $(selector).animate({marginLeft: (parseInt( $(selector).css('margin-left') ) + offset) + 'px'}, {duration: speed });
    } else {
        $(selector).animate({marginLeft: (parseInt( $(selector).css('margin-left') ) + offset) + 'px'}, {duration: speed });
    }
}

/* addPrefixZero (from "1" to "01") */
function addPrefixZero(number)
{
	var number;
	if(number < 10) return '0' + number;
	else return number;
}

/* Generate HTML for Left and Main Afisha */
function weeksGenerate()
{
	var listDates = new Array(),
		weeksBegin = new Date(),
		weeksHtml = '',
		weeksHtmlLeft = '',
		wasNowDayFlag = 0;
		
	weeksBegin.setTime(nowDate.getTime());
	
	if(nowDate.getDay()) {												// определяем начальный день, отнимем от текущего числа день недели
		weeksBegin.setDate(nowDate.getDate() - (nowDate.getDay() - 1));
	}
	else {
		weeksBegin.setDate(nowDate.getDate() - (COUNTDAYS - 1));
	}
	
	for(i = 0; i < (COUNTDAYS * VISIBLEWEEKS); i++){
		listDates[i] = [weeksBegin.getDate(), weeksBegin.getMonth(), weeksBegin.getFullYear(), weeksBegin.getDay()];
		weeksBegin.setDate(weeksBegin.getDate() + 1);
	}	

//	генерим код для афиш 
	wasNowDayFlag = 0;
	for ( i in listDates ) {
		if((listDates[i][2] == nowDate.getFullYear())&&(listDates[i][1] == nowDate.getMonth())&&(parseInt(listDates[i][0]) == nowDate.getDate())) {    // текущий день
//			генерим код для основной афиши 
			if(viewDate > nowDate) { //centerAfishaUrl
				weeksHtml += '<li><a class="day" href="'+centerAfishaUrl.replace( '%date%', (listDates[i][0]+'.'+(listDates[i][1] + 1)+'.'+listDates[i][2] ))+'"><span>'+addPrefixZero(listDates[i][0])+'</span>'+WEEKDAYS[listDates[i][3]]+'</a></li>';
			} else {
				weeksHtml += '<li><a class="day active" href="'+centerAfishaUrl.replace('%date%', (listDates[i][0]+'.'+(listDates[i][1] + 1)+'.'+listDates[i][2]))+'"><span>'+addPrefixZero(listDates[i][0])+'</span>'+WEEKDAYS[listDates[i][3]]+'</a></li>';
			}
				
//			генерим код для левой афиши 
			weeksHtmlLeft += '<li><a class="day active" href="'+leftAfishaUrl.replace('%date%', (listDates[i][0]+'.'+(listDates[i][1] + 1)+'.'+listDates[i][2]))+'">'+WEEKDAYS[listDates[i][3]]+'</a></li>';

			wasNowDayFlag = 1;
			continue;
		}
		if(wasNowDayFlag == 0) {								// прошедший день
//			генерим код для основной афиши 
			weeksHtml += '<li><div class="day"><span>'+addPrefixZero(listDates[i][0])+'</span>'+WEEKDAYS[listDates[i][3]]+'</div></li>';

//			генерим код для левой афиши 
			weeksHtmlLeft += '<li><div class="day">'+WEEKDAYS[listDates[i][3]]+'</div></li>';

			continue;
		}
// 		будущий день		
		
//		генерим код для основной афиши 		
		weeksHtml += '<li><a class="day ';
		if((listDates[i][2] == viewDate.getFullYear())&&(listDates[i][1] == viewDate.getMonth())&&(parseInt(listDates[i][0]) == viewDate.getDate())) {    // текущий день
			weeksHtml += 'active';
		}
		weeksHtml += '" href="'+   centerAfishaUrl.replace( '%date%', (listDates[i][0]+'.'+(listDates[i][1] + 1)+'.'+listDates[i][2]))   +'"><span>'+addPrefixZero(listDates[i][0])+'</span>'+WEEKDAYS[listDates[i][3]]+'</a></li>';

//		генерим код для левой афиши 
		weeksHtmlLeft += '<li><a class="day" href="'+leftAfishaUrl.replace('%date%', (listDates[i][0]+'.'+(listDates[i][1] + 1)+'.'+listDates[i][2]))+'">'+WEEKDAYS[listDates[i][3]]+'</a></li>';
	}
//	обновляем див основной афиши	
	$('.carousel>ul').html(weeksHtml);
	
//	обновляем див левой афиши	
	$('.carousel_left>ul').html(weeksHtmlLeft);
}	
});
