var dp_for;

function DataPickerStart(temp) {
	dp_for = temp;
	$('.datapicker').show('slow');
	$('.datapicker').css('position', 'absolute');
	$('.datapicker').css('left', $('.'+dp_for).offset().left + 10);
	$('.datapicker').css('top', $('.'+dp_for).offset().top + 10);
}

$(document).ready(function() {
						  
	var date = new Date();
	var c_day = date.getDate();
	var c_month = date.getMonth();
	var c_year = date.getFullYear();
	
	var name_months = ['Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paź', 'Lis', 'Gru'];
	
	var days_in_month;
	var lk;
	var style;
	
	
	$('.dp_prev_year').click(function() {
		c_year--;
		create_calendar();
	});
	
	$('.dp_prev_month').click(function() {
		c_month--;
		create_calendar();
	});
	
	$('.dp_next_year').click(function() {
		c_year++;
		create_calendar();
	});
	
	$('.dp_next_month').click(function() {
		c_month++;
		create_calendar();
	});
	
	$('.datapicker .dp_date').click(function() {
											 
		$('.dp_show_days').hide('slow');
		$('.dp_show_months').show('slow');
		
	});
	
	$('.datapicker .dp_today').click(function() {
	
		date = new Date();
		c_day = date.getDate();
		c_month = date.getMonth();
		c_year = date.getFullYear();
		create_calendar();
		$('.dp_show_months').hide('slow');
		$('.dp_show_days').show('slow');
		
	});
	
	$('.datapicker .show_month').click(function() {
	
		c_month = $(this).attr('name');
		c_year = parseInt($('.dp_input_year').val());
		create_calendar();
		$('.dp_show_months').hide('slow');
		$('.dp_show_days').show('slow');
	
	});
		
	function daysInMonth(month, year) {
		return new Date(year, month, 0).getDate();
	}
	
	function create_calendar() {
		
		$('.datapicker .days').fadeOut('fast');
		
		$('.datapicker .days').html('');
		
		if(c_month == 12) {
			c_month = 0;
			c_year++;
		}
		if(c_month == -1) {
			c_year--;
			c_month = 11;
		}
		
		days_in_month = daysInMonth(c_month+1, c_year);
				
		temp_date = date.setFullYear(c_year+1, c_month, 0);
		lk = date.getDay() - 1 ;
		
		if(lk == -1) lk = 6;
		
		$('.datapicker .dp_date').html(name_months[c_month] +', '+ c_year);
		
		for(x = 0; x < lk; x++) {
			$('.datapicker .days').append('<div class="row"></div>');
		}
		
		date = new Date();
		
		for(x = 1; x <= days_in_month; x++) { 
		
			style = '';
			if(x == date.getDate() && c_month == date.getMonth() && c_year == date.getFullYear())
				style = 'today';
			else if(lk == 5)
				style = 'saturday';
			else if(lk == 6)
				style = 'sunday noborder';
		
			$('.datapicker .days').append('<div class="row select_day '+style+'">'+x+'</div>');
			
			lk++;
			if(lk % 7 == 0 && lk != 0)
				lk = 0;
			
		}
		
		$('.datapicker .days').fadeIn('fast');
	
	}
	
	create_calendar();
	
	$('.datapicker .select_day').live('click', function() {
	
		$('.datapicker').hide('slow');
		$('.'+dp_for).val($(this).text() + '-' + (parseInt(c_month)+1) + '-' + c_year);
	
	});

});
