$(document).ready(function(){

    var m = $('#month').val();
    var y = $('#year').val();
    var d = $('#day').val();

    // remove a day from the date as the date object works 0-11
    m--;

    var startDate=new Date();
    startDate.setFullYear(y,m,d);
    
    // Datepicker
    $('#formdate').replaceWith('<div id="datepicker"></div>');

    $('#datepicker').datepicker({
        inline: true,
        gotoCurrent: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy/m/d',
        yearRange: '1995:2011',
        defaultDate: startDate,
        beforeShowDay: dateLoading,
        onSelect: changePage
    });
});

function changePage(dateText,inst)
{
    var path = $('#modulePath').val();
    window.location.href = path + dateText;
}

var path = $('#modulePath').val();
var cached_days = [];
var cached_months = [];

function dateLoading(date) 
{
    var year_month = ""+ (date.getFullYear()) +"-"+ (date.getMonth()+1) +"";
    var year_month_day = ""+ year_month+"-"+ date.getDate()+"";
    var opts = "";
    var i = 0;
    var ret = false;
    i = 0;
    ret = false;
     
     
    for (i in cached_months) 
    {
        if (cached_months[i] == year_month)
        {
            // if found the month in the cache
            ret = true;
            break;
        };
    };
     
    // check if the month was not caached
    if (ret == false)
    {
        //  load the month via .ajax
        opts = {month: (date.getMonth()+1), year: date.getFullYear()};
        // we will use the "async: false" because if we use async call, the datapicker will wait for the data to be loaded
        
        $.ajax(
        {
            type: 'GET',
            url: '/archive/',
            data: opts,
            dataType: "json",
            async: false,
            success: function(data)
                     {
                        // add the month to the cache
                        cached_months[cached_months.length]= year_month ;
                        $.each(    data.days, function(i, day)
                            {
                                cached_days[cached_days.length]= year_month +"-"+ day.day +"";
                            }
                        );
                    },
            error: function(data,testStatus,errorThrown) { if (console.log) { console.log(errorThrown) } }
        });
    };
    
    i = 0;
    ret = false;
     
    // check if date from datapicker is in the cache otherwise return false
    // the .ajax returns only days that exists
    for (i in cached_days) 
    {
        if (year_month_day == cached_days[i])
        {
            ret = true;
        };
    };
    return [ret, ''];    
}


