Date.prototype.dateFormat = function(format) {
    var result = "";
    for (var i = 0; i < format.length; ++i) {
        result += this.dateToString(format.charAt(i));
    }
    return result;
}

Date.prototype.dateToString = function(character) {
    switch (character) {
    case "Y":
        return this.getFullYear();
    case "d":
        if(this.getDate() <  10 ) {
            return "0"+this.getDate();
        }
        return this.getDate();
    case "m":
        if(this.getMonth() < 10 ) {
            return "0"+(this.getMonth()+1);
        }
    	    return (this.getMonth()+1);
    default:
        return character;
    }
}


var start_date = null;
var end_date = null;

function take(d) {
    $.post("/take.php", { date: d },
	function(data) {
	
	    $('.white').html(data);
	    $('#calendar .td.node').click(function() {

		a = parseInt($(this).text());
		
		if(a < 10) {
		    a = '0' + a;
		}

		click_date = parseDate(d+'-'+a);
		
		if(start_date && end_date) {
		    start_date = null;
		    end_date = null;
		}
		if(start_date == null) {
		    start_date = click_date;
		}
		else if(start_date > click_date ) {
		    end_date = start_date;
		    start_date = click_date;
		}else {
		    //console.info('aaa');
		    end_date =  click_date;
		}
		start_date = new Date(start_date);

		if(end_date) {
		    end_date = new Date(end_date);
		}
		
//		console.info(start_date.dateFormat("Y-m-d"))
		if(start_date) {
		    $('#start-date-container').html(start_date.dateFormat("Y-m-d"));
		    $('#start-date').val(start_date.dateFormat("Y-m-d"));
		}else {
		    $('#start-date-container').html("");
		    $('#start-date').val("");
		}
		
		
		if(end_date) {
		    $('#end-date-container').html(end_date.dateFormat("Y-m-d"));
		    $('#end-date').val(end_date.dateFormat("Y-m-d"));
		}else {
		    $('#end-date-container').html("");
		    $('#end-date').val("");
		}
	})
	if(!$.cookie('kontrast')) {

	if($('#calendar').height()>$('#content-in').height())	
	$('#content-in').height($('#calendar').height());	
	}
    });    
}
//startowy kalendarz
$(document).ready(
    function() {
	var now = new Date();
	
	month =  now.getMonth();
	month++;
	if( month < 10 ) {
	    month = '0' + (month);
	}else {
	    month = month;
	}
	
	var str = now.getFullYear() + '-' + month;
	take(str);
	
	$('#calendar-submit-form').click(function(){
	
	    if(!$('#start-date').val()) {
		return false;
	    }
	
	    data =  $('#start-date').val();
	    
	    if($('#end-date').val()) {
		data = data + " - " +$('#end-date').val();
	    }else {
		data = data + " - " +$('#start-date').val();
	    }
	    
	    window.location = '/kalendarz.html?date='+data;
	
	})

    }
    
);

function parseDate(str) {

    a = str.split('-');

    d = new Date();
    d.setFullYear(a[0]);
    d.setMonth(a[1]-1);
    d.setDate(a[2]);

    return d;

}

