/// <reference path="Date.js" />

// Disable the datepicker
jQuery.fn.disableDatePicker = function() {
    $(this).datepicker('disable');
    return this;
}

// Enable the datepicker
jQuery.fn.enableDatePicker = function() {
    $(this).datepicker('enable');
    return this;    
}

///
/// Creates a calendar image button next to an input field and sets the day and month year select list value
/// to the selected date value.
///
jQuery.fn.attachDatePicker = function(daySelector, monthYearSelector, maxDate, selectionChangedHandler, beforeShowHandler)
{
	$(this).datepicker(
                    {
                    	dateFormat: 'ddmmyy',
                    	minDate: "0d",
                    	maxDate: maxDate,
                    	showStatus: true,
                    	showWeeks: true,
                    	highlightWeek: true,
                    	showOn: "button",
                    	numberOfMonths: 1,
                    	firstDay: 1,
                    	buttonImage: CalendarButtonImage,
                    	buttonImageOnly: true,
                    	showOptions: { origin: ["top", "left"] },
                    	onSelect: function(date)
                    	{

                    		var dateString = date.toString();

                    		var day = parseInt(dateString.substr(0, 2));
                    		var monthYear = dateString.substr(2, dateString.length - 2);


                    		$(daySelector).val(day);
                    		$(monthYearSelector).val(monthYear);

                    		selectionChangedHandler();
                    	},
                    	beforeShow: function()
                    	{

                    		var day = $(daySelector).getDay();
                    		var month = $(monthYearSelector).getMonth();
                    		var year = $(monthYearSelector).getYear();

                    		var dateString = padDigits(day, 2) + padDigits(month, 2) + padDigits(year, 4);

                    		$(this).val(dateString);

                    		if (beforeShowHandler != undefined)
                    		{
                    			beforeShowHandler();
                    		}
                    	}

                    }
                );
	return this;
}


// Pads a string with a number of digits
function padDigits(n, totalDigits) {
    n = n.toString();
    var pd = '';
    if (totalDigits > n.length) {
        for (i = 0; i < (totalDigits - n.length); i++) {
            pd += '0';
        }
    }
    return pd + n.toString();
} 

///
/// Gets the selected day from a day select list
///
jQuery.fn.getDay = function() {

    var dayPart = $(this).val();
    var day = parseInt(dayPart, 10);

    return day;
}

///
/// Gets the selected month from a month year select list
///
jQuery.fn.getMonth = function() {

    var id = this.id;
    var monthYear = $(this).val();
    var monthPart = monthYear.substr(0, 2);
    var month = parseInt(monthPart, 10);
    return month
}

///
/// Gets the selected year from a month year select list
///
jQuery.fn.getYear = function() {

    var monthYear = $(this).val();
    var yearPart = monthYear.substr(2, 4);
    var year = parseInt(yearPart, 10);

    return year
}

///
/// Ensures that the selected day is not greater than the number of days with in  the month
///
jQuery.fn.constrainDayToCalendarDay = function(month, year) {

    var day = $(this).getDay();

    // Get the total number of days in the month allow for leap years
    var totalDaysInMonth = Date.getDaysInMonth(year, month - 1);

    // check that the origin selected day is not greater than the number of days in the selected month
    if (day > totalDaysInMonth) {
        //Set the day drop down equal to the
        $(this).val(totalDaysInMonth);
    }

    return this;
}

//
// Handler that ensures that only a valid day can be selected
//
function originDayHandler(originDaySelector, originMonthYearSelector,
                                            destinationDaySelector, destinationMonthYearSelector) {
    // Get the origin month day year
    var originDay = $(originDaySelector).getDay();
    var originMonth = $(originMonthYearSelector).getMonth();
    var originYear = $(originMonthYearSelector).getYear();

    // Get the destination month day year
    var destinationDay = $(destinationDaySelector).getDay();
    var destinationMonth = $(destinationMonthYearSelector).getMonth();
    var destinationYear = $(destinationMonthYearSelector).getYear();

    // Ensure that the day is constrained to a actual calendar day
    $(originDaySelector).constrainDayToCalendarDay(originMonth, originYear);

    // now check if the destination day is less than the origin. but not set to none
    if (destinationDay < originDay & destinationDay != 0) {
        // Make the destination day the same
        $(destinationDaySelector).val($(originDaySelector).val());
    }

}

///
/// Handler that ensures that the correct day is selected based on the selected month year
///
function originMonthYearHandler(originDaySelector, originMonthYearSelector,
                                                destinationDaySelector, destinationMonthYearSelector) {

    // Get the origin month day year
    var originDay = $(originDaySelector).getDay();
    var originMonth = $(originMonthYearSelector).getMonth();
    var originYear = $(originMonthYearSelector).getYear();

    // Get the destination month day year
    var destinationDay = $(destinationDaySelector).getDay();
    var destinationMonth = $(destinationMonthYearSelector).getMonth();
    var destinationYear = $(destinationMonthYearSelector).getYear();

    // Set the day to the first if days is none and a valid month is selected
    if (originDay == 0 & originMonth != 0) {
        $(originDaySelector).val("01");
    }

    // Ensure that the day is constrained to a actual calendar day
    $(originDaySelector).constrainDayToCalendarDay(originMonth, originYear);

    // Ensure that the destination date selections are not less than the origin date selections provided
    // that the destination is not nothing
    if (destinationDay != 0) {
        var originDate = new Date(originYear, originMonth, originDay)
        var destinationDate = new Date(destinationYear, destinationMonth, destinationDay)

        if (originDate > destinationDate) {
            // Make the destination date the same as the origin
            $(destinationDaySelector).val($(originDaySelector).val());
            $(destinationMonthYearSelector).val($(originMonthYearSelector).val());
        }

    }

}



//
// Handler that ensures that only a valid day can be selected
//
function destinationDayHandler(originDaySelector, originMonthYearSelector,
                                            destinationDaySelector, destinationMonthYearSelector) {

    // Get the origin month day year
    var originDay = $(originDaySelector).getDay();
    var originMonth = $(originMonthYearSelector).getMonth();
    var originYear = $(originMonthYearSelector).getYear();

    // Get the destination month day year
    var destinationDay = $(destinationDaySelector).getDay();
    var destinationMonth = $(destinationMonthYearSelector).getMonth();
    var destinationYear = $(destinationMonthYearSelector).getYear();

    // Reset the month to none if the day is none
    if (destinationDay == 0 & destinationMonth != 0) {
        $(destinationMonthYearSelector).val("00");
        destinationMonth = 0;
    }

    // Ensure that the day is constrained to a actual calendar day
    $(destinationDaySelector).constrainDayToCalendarDay(destinationMonth, destinationYear);

    // Set the destination month to the origin if day selected and the month is not
    if (destinationDay != 0 & destinationMonth == 0) {
        destinationMonth = originMonth;
        destinationYear = originYear;
        $(destinationMonthYearSelector).val($(originMonthYearSelector).val());
    }

    // Ensure that the destination date selections are not less than the origin date selections provided
    // that the destination is not nothing
    if (destinationMonth != 0) {
        var originDate = new Date(originYear, originMonth, originDay)
        var destinationDate = new Date(destinationYear, destinationMonth, destinationDay)

        if (originDate > destinationDate) {
            // Make the destination date the same as the origin
            $(destinationDaySelector).val($(originDaySelector).val());
            $(destinationMonthYearSelector).val($(originMonthYearSelector).val());
        }

    }


}


///
/// Handler that ensures that the correct day is selected based on the selected month year
///
function destinationMonthYearHandler(originDaySelector, originMonthYearSelector,
                                                destinationDaySelector, destinationMonthYearSelector) {

    // Get the origin month day year
    var originDay = $(originDaySelector).getDay();
    var originMonth = $(originMonthYearSelector).getMonth();
    var originYear = $(originMonthYearSelector).getYear();

    // Get the destination month day year
    var destinationDay = $(destinationDaySelector).getDay();
    var destinationMonth = $(destinationMonthYearSelector).getMonth();
    var destinationYear = $(destinationMonthYearSelector).getYear();

    // Set the day to the first if days is none and a valid month is selected
    if (destinationDay == 0 & destinationMonth != 0) {
        destinationDay = 1;
        $(destinationDaySelector).val("01");
    }

    // Reset the destination day to none if month is none
    if (destinationDay != 0 & destinationMonth == 0) {
        $(destinationDaySelector).val("00");
    }


    // Ensure that the day is constrained to a actual calendar day
    $(destinationDaySelector).constrainDayToCalendarDay(destinationMonth, destinationYear);

    // Ensure that the destination date selections are not less than the origin date selections provided
    // that the destination is not nothing
    if (destinationDay != 0) {
        var originDate = new Date(originYear, originMonth, originDay)
        var destinationDate = new Date(destinationYear, destinationMonth, destinationDay)

        if (originDate > destinationDate) {
            // Make the destination date the same as the origin
            $(destinationDaySelector).val($(originDaySelector).val());
            $(destinationMonthYearSelector).val($(originMonthYearSelector).val());
        }

    }

}

///
/// Events used to constrain the date drop down entry
///
function attachDateDropDownEvents(originDaySelector, originMonthYearSelector,
                                            destinationDaySelector, destinationMonthYearSelector)
{

            $(originDaySelector).unbind("change").click(function() {
                originDayHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });

            $(originDaySelector).unbind("keyup").keyup(function() {
                originDayHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });
            

            $(originMonthYearSelector).unbind("change").click(function() {
                originMonthYearHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });
            
            $(originMonthYearSelector).unbind("keyup").keyup(function() {
                originMonthYearHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });


            $(destinationDaySelector).unbind("change").click(function() {
                destinationDayHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });

            $(destinationDaySelector).unbind("keyup").keyup(function() {
                destinationDayHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });

            $(destinationMonthYearSelector).unbind("change").click(function() {
                destinationMonthYearHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });

            $(destinationMonthYearSelector).unbind("keyup").keyup(function() {
                destinationMonthYearHandler(originDaySelector, originMonthYearSelector, destinationDaySelector, destinationMonthYearSelector);
                return false;
            });

}
