/**
 * Java script file for datepanel component
 *
 * @version 2.0.1
 * @author Eugene A. Kalosha <aristarch@zfort.net>
 */

    function getDaysForMonth(monthNum, yearNum)
    {
        switch (monthNum) {
        	case "1":
        	case "3":
        	case "5":
        	case "7":
        	case "8":
        	case "10":
        	case "12":
        		return 31;
        		break;
            case "2":
        		return (yearNum % 4 != 0) ? 28 : ((yearNum % 400 == 0) ? 29 : ((yearNum % 100 != 0) ? 29 : 28));
        		return 28;
        		break;
        	case "4":
        	case "6":
        	case "9":
        	case "11":
        		return 30;
        		break;

        	default:
        	   return 0;
        		break;
        }

    }


   	/**
   	 * using this function requires that drop down lists with date were declared like:
   	 *
   	 * <php:dropdownlist:ddlMonth class="date-month"  id="date-month-1" />
   	 * <php:dropdownlist:ddlDay class="date-day" id="date-day-1" />
	 * <php:dropdownlist:ddlYear class="date-year" id="date-year-1" />
   	 * You can change only last digit in id attribute. For example: id="date-year-2", id="date-year-3"..id="date-year-n"
   	 */

    jQuery(function()
    {
    	jQuery('.date-month, .date-year').bind("change", function()
	    {
			ddlCurrentId = jQuery(this).attr("id");
			index = ddlCurrentId.substring(ddlCurrentId.lastIndexOf('-')+1,ddlCurrentId.length);

			ddlDay = jQuery('#date-day-'+index);
			ddlMonth = jQuery('#date-month-'+index);
			ddlYear = jQuery('#date-year-'+index);

			currentYear = ddlYear.get(0).options[ddlYear.get(0).options.selectedIndex].value;
			currentMonth = ddlMonth.get(0).options[ddlMonth.get(0).options.selectedIndex].value;
			currentDay = ddlDay.get(0).options[ddlDay.get(0).options.selectedIndex].value;

	        daysInMonth = getDaysForMonth(currentMonth, currentYear);
			if(daysInMonth > 0 && currentYear != 0) {
		        ddlDay.empty();
		        for (i = 1; i <= daysInMonth; i++) {
		            jQuery("<option></option>").attr("value", i).html(i).appendTo(ddlDay);
		        }
		        if (currentDay > daysInMonth) {
		            ddlDay.get(0).options.selectedIndex = 0;
		        } else {
		            ddlDay.get(0).options.selectedIndex = currentDay - 1;
		        }
		    }
		    else {
		    	ddlDay.empty();
		    	jQuery("<option></option>").attr("value", "day").html("day").appendTo(ddlDay);
		    }

	    })
	 });