Date.prototype.getMDay = function()
{
    return (this.getDay() + 6) % 7;
}

Date.prototype.getISOYear = function()
{
    var thu = new Date(this.getFullYear(), this.getMonth(), this.getDate() + 3 - this.getMDay());
    return thu.getFullYear();
}

Date.prototype.getISOWeek = function()
{
    var onejan = new Date(this.getISOYear(), 0, 1);
    var wk = Math.ceil((((this - onejan) / 86400000) + onejan.getMDay() + 1) / 7);
    if (onejan.getMDay() > 3) wk--; return wk;
}

jQuery(document).ready(function()
{
    // Set default date into calendar
    var current_date = new Date();

    set_departure_date(current_date.getDate(), current_date.getMonth()+1, current_date.getFullYear());

    jQuery.datepicker.regional['fi'];
    jQuery('#calendar_date').datepicker(
    {
        beforeShowDay: function(date)
        {
            // Create the array to return and
            // Define if selectable
            var show = new Array(true, '');
            var today = new Date();
            // Convert the date
            today = new Date(today.toDateString());

            if (date.getTime() < today.getTime())
            {
                show[0] = false;
            }

            return show;
        },
        firstDay: 1,
        showOtherMonths: true,
        showWeek: true,
        onSelect: function(dateText, inst)
        {
            // Parse dates
            var dates = dateText.match(/([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{2,4})/);

            // If no date matches where found
            if(typeof dates == 'null')
            {
                return;
            }

						jQuery('#selectedSchedules').attr('checked', true); 


            // Set the parsed dates
            set_departure_date(dates[1], dates[2], dates[3]);
        }
    });

    // Initialize submit of the form
    jQuery('#calendar_search form').submit(function()
    {
				if(!jQuery('#input_from').val() || !jQuery('#input_to').val()) {
          alert('Syötä ensin lähtö- ja määräpaikka.'); 
          return false; 
        }

        jQuery(this).attr('target', 'form_target');
        
        window.open('', 'form_target', 'width=805,height=600,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes');
        return true;
    });

});

/**
 * Set the departure dates in the form
 *
 * @param day   int     - day of month
 * @param month int     - month of year
 * @param year  int     - year
 */
function set_departure_date(day, month, year)
{
    jQuery('input#day').attr('value', day);
    jQuery('input#month').attr('value', month);
    jQuery('input#year').attr('value', year);
}

