﻿//Thanx To http://jqueryui.com

//Create global variable
var Itemlist = new Object();

//When done loading page
jQuery(document).ready(function ()
{
    //Get items first load through ajax call
    var date = new Date();
    //ChangeMonthYear(2011, 10, null);
    ChangeMonthYear(date.getFullYear(), date.getMonth()+1, null);
    //console.log(date.getFullYear());
    //console.log(date.getMonth());

    //Add click handler for popup
    jQuery(".calendarBlock").mouseleave(function ()
    {
        jQuery(".calendarBlock").hide();
    });

    //Create datepicker
    jQuery("#date").datepicker(
    {
        changeMonth: true,
        changeYear: true,
        onChangeMonthYear: ChangeMonthYear,
        beforeShowDay: DaysToMark,
        onSelect: Select
    });
});

//Handles the onclick on a date
function Select(dateText, inst)
{
    //Get events for selected day
    var events = Itemlist[inst.selectedDay];

    //Store control in variable
    var calendarBlock = jQuery(".calendarBlock");

    //Clear the block
    //calendarBlock.html("");

    //Create variable to store value in because there is a bug with IE and .append()
    var calendarBlockContent = "";

    //Loop through events and fill in block
    for (var i = 0; i < events.length; i++)
    {
        //Add event to string
        calendarBlockContent += "<a class='moreInfo' href='" + events[i].Link + "'><div class='eventInfo;'>" + events[i].Title + " - " + events[i].Type + "</div></a></div>";
    }

    //Set content to block
    calendarBlock.html(calendarBlockContent);

    //Show block
    calendarBlock.show();
}

//Mark the Days that have events
function DaysToMark(date)
{
    if (Itemlist != null && Itemlist[date.getDate()] != null)
    {
        return [true, "markedDay"];
    }

    return [false];
}

//Get new data for the year
function ChangeMonthYear(year, month, inst)
{
    //Set Itemlist on null
    Itemlist = null;

    //Hide popup block
    jQuery(".calendarBlock").hide();

    jQuery.ajax(
    {
        url: "/Handlers/DatePicker.ashx",
        type: "POST",
        data: { 'params[]': [year, month] },
        dataType: "json",
        success: function (data)
        {
            Itemlist = data;
            jQuery("#date").datepicker("refresh");
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            Itemlist = null;
            jQuery("#date").datepicker("refresh");
        }
    });
}
