/**
 * Плагин для построения календаря
 */
(function($){
	var dates = {
		11: '',
		13: '',
		22: ''
	}
	var object = null;
    var currentdate = new Date();
    var months = new Array( "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь",
                   "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" );
    var weekday = new Array( "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс" );
	var currentmonth = currentdate.getMonth();
	var currentyear  = currentdate.getFullYear();
	var monthcountday = new Array( 31, (((currentyear%4) == 0 ) ? 29 : 28), 
                                       31, 30, 31, 30, 31, 31, 30, 31, 30 ,31 );
	var firstday = ((new Date(currentyear,currentmonth,1)).getDay()+6)%7;

	var methods = {
		// Функция инициализации
		init: function(){
			object = $(this);

			methods.loadDates();

			$('.calendarPrevMonth').live('click', function(){
				if (currentmonth>0){
					currentmonth--;
				}else{
					currentmonth = 11;
					currentyear--;
				}
				firstday = ((new Date(currentyear,currentmonth,1)).getDay()+6)%7;
				methods.loadDates();
				return false;
			});

			$('.calendarNextMonth').live('click', function(){
				if (currentmonth<11){
					currentmonth++;
				}else{
					currentmonth = 0;
					currentyear++;
				}
				firstday = ((new Date(currentyear,currentmonth,1)).getDay()+6)%7;
				methods.loadDates();
				return false;
			});

			$('.event').live('click',function(){
				window.location.href = '/dates/:tpl_page-dates?day='+$(this).text()+'&month='+(currentmonth+1)+'&year='+currentyear;
			});

			return this;
		},
		draw: function(){
			// Формируем шапку
        	html = 	  "<div class='calendarHeader'>Календарь<br />экологических дат</div>"
        			+ "<div class='calendarCurrentDate'><a href='' class='calendarPrevMonth'>«</a> "+months[currentmonth]+" "+(currentyear)+" <a href='' class='calendarNextMonth'>»</a></div>"
                    + "<div class='calendarTable'><table><thead><tr>";
			// Вставляем дни недели
	        for(i=0;i<7;i++)
	            html += "<th>" + weekday[ i ] + "</th>";
			html += "</tr></thead>";

			// Вставляем пробел для первого дня
	        if( firstday != 0 )
	            html += "<tr><td colspan='" + firstday + "'>&nbsp;</td>";

			// Вставляем дни
	        for(i=0;i<monthcountday[currentmonth];i++)
	        {
	            if((i+firstday)%7==0)
	                html += "</tr><tr>";

				if ((i+1) in dates){
					html += "<td class='event'>" + (i+1) + "</td>";
				}else{
					html += "<td>" + (i+1) + "</td>";
				}
			}
			// Вставляем пробел для последнего дня
	        if( (monthcountday[currentmonth]+firstday)%7 != 0 )
	            html += "<td colspan='" + (7-((monthcountday[currentmonth]+firstday)%7)) + "'>&nbsp;</td>";
	        html += "</tr></table>";

	        object.html(html);
		},
		loadDates: function(){
			jQuery.post(
				'/news/:tpl_page-getDates?currentyear='+currentyear+'&currentmonth='+(currentmonth+1),
				'',
				function (dat){
					dates = dat;
					methods.draw();
				},
				'json'
			);
		}
		
	}
	
	
	$.fn.calendar = function ( method ) {
		if ( methods[method] ) {
		  return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
		  return methods.init.apply( this, arguments );
		} else {
		  $.error( 'Method ' +  method + ' does not exist on jQuery.calendar' );
		} 
	};
	
})( jQuery );
