$(document).ready(function() {

    var date  = new Date();
    var year  = date.getFullYear();
    var month = date.getMonth();
    var day   = 0;

    var re = window.location.href.match(new RegExp('events/([0-9]{4})/([a-z]{3})/([0-9]{1,})/'));
    if (re) {
        if (re[1]) year = re[1];
        if (re[2])
        {
            month  = zDate.monthFromAbbr(re[2]);
        }
        if (re[3]) day = re[3];
    }

    loadCalendar(year,month,day);

    function loadCalendar(year,month,day)
    {
        month_abbr = zDate.monthAbbr(month);

        $('#eventcal').load('/events/' + year + '/' + month_abbr + '/ tbody tr',function(){
            $('#eventcal').children(":first").remove();
            $(".calendar .inner h4").text(month_abbr);

            $.each($("#eventcal th"),function(k,item){
                $(item).text($(item).text().substring(0,1));
            });

            $.each($("#eventcal tr td a"),function(k,item){
                var url = $(item).attr("href");
                url = url.replace("http://www.thealternateside.org/events/bestbets/","");
                url = url.replace("http://thealternateside.org/events/bestbets/","");
                $(item).attr("href",'/events/' + year + '/' + month_abbr + '/' + url);
                if ($(item).text() == day)
                    $(item).addClass("selected");
            });
        });

        $("#current_month").val(month);
        $("#current_year").val(year);

    }

    $("#next_month").click(function(){
        month = $("#current_month").val();
        year = $("#current_year").val();

        month = parseInt(month) + 1;
        if (month > 11)
        {
            month = 0;
            year = parseInt(year) + 1;
        }
        loadCalendar(year,month,0);

        return false;
    });

    $("#prev_month").click(function(){
        month = $("#current_month").val();
        year = $("#current_year").val();

        month = parseInt(month) - 1;
        if (month < 0)
        {
            month = 11;
            year = parseInt(year) - 1;
        }
        loadCalendar(year,month,0);

        return false;
    });


});