/* prevent selection of invalid dates through the select controls */
function checkLinkedDays(obj) {
    var daysInMonth = 32 - new Date($(obj).find('.calYear').val(), $(obj).find('.calMonth').val() - 1, 32).getDate();
    $(obj).find('.calDay option').attr('disabled', '');
    $(obj).find('.calDay option:gt(' + (daysInMonth - 1) +')').attr('disabled', 'true');
    if($(obj).find('.calDay').val() > daysInMonth){
        $(obj).find('.calDay').val(daysInMonth);
    }
}
/* prepare to show a date picker linked to three select controls */
function readLinked() {
	var selMonth = $(this).parent().parent().find('.calMonth');
	var selDay = $(this).parent().parent().find('.calDay');
	var selYear = $(this).parent().parent().find('.calYear');
	if($(selMonth).val() != "" && $(selDay).val() != "" && $(selYear).val() != ""){
	    $(this).val($(selMonth).val() + '/' + $(selDay).val() + '/' + $(selYear).val());
   	}else{
   		 $(this).val('');
   	}
    return {};
}
/* update select controls to match a date picker selection */
function updateLinked(date) {
    $(this).parent().parent().find('.calMonth').val(date.substring(0, 2));
    $(this).parent().parent().find('.calDay').val(date.substring(3, 5));
    $(this).parent().parent().find('.calYear').val(date.substring(6, 10));
    talkback();
}

$(document).ready(function() {
	$('.calTemp').each(function(){
		/* get timespan from formfield */
		var minYear = $(this).parent().find(".calYear option:eq(0)").val();
		var maxYear = $(this).parent().find(".calYear option:last").val();
		/* set calendar options */
		var predefinedDatepickerOptions = {
		    minDate: new Date(minYear, 1 - 1, 5),
		    maxDate: new Date(maxYear, 12 - 1, 10),
		    yearRange: '-99:+99',
		    beforeShow: readLinked,
		    onSelect: updateLinked,
			showOn: 'button',
	    	buttonImage: '/js/ui-datepicker/calendar-gray.gif',
	    	buttonImageOnly: true
		}
		if(typeof customDatepickerOptions == 'object'){
			/* use customDatepickerOptions = {}; in html-file to use custom settings for all calendars on page */
			var datepickerOptions = $.extend(predefinedDatepickerOptions, customDatepickerOptions); /* combine options */
		}else{
			var datepickerOptions = predefinedDatepickerOptions;
		}
		$(this).datepicker(datepickerOptions); /* initialize datepicker */
	});
	$('.calMonth, .calYear, .calDay').change(function(){checkLinkedDays($(this).parent());});
});