function is_leap_year(yr) {
    return new Date(Number(yr),2-1,29).getDate()==29;
}

// This function was taken from Google closure.js (string.js module).
function string_subs(str, var_args) {
    for (var i = 1; i < arguments.length; i++) {
        var replacement = String(arguments[i]).replace(/\$/g, '$$$$');
        str = str.replace(/\%s/, replacement);
    }
    return str;
}
        
function update_days () {
    month = $('#id_date_of_birth_0').val();
    
    // First show all dates.
    $('#id_date_of_birth_1 option').show();
    if (!is_leap_year($('#id_date_of_birth_2').val())){
        $('#id_date_of_birth_1 option[value=29]').hide();
    }
    
    switch(month) {
        case '4':
        case '6':
        case '9':
        case '11':
            $('#id_date_of_birth_1 option[value=31]').hide();
            break;
        case '2':// Hide the 30th and 31st.
            $('#id_date_of_birth_1 option[value=30]').hide();
            $('#id_date_of_birth_1 option[value=31]').hide();
            break;
    }    
}
        
$(document).ready(function() {
    
    $('#id_date_of_birth_0').change(update_days);
    $('#id_date_of_birth_2').change(update_days);
    $('#id_first_name').keyup(function() {
        $('#hero-label span').html($(this).val());
    });
    $('#id_first_name').blur(function() {
        $('#hero-label span').html($(this).val());
    });
    
    // Add a counter for the dedication.
    $('#id_dedication_message').parent().append(string_subs('<div class="field-help-text"><span id="id_chars_left"></span> %s.</div>', js_strings.characters_left));
    $('#id_dedication_message').limit('160', '#id_chars_left');
    
    if (!photo_url) {
        $('#id_dedication_image').parent().append(string_subs('<div class="field-help-text"><a href="javascript:show_example();"">%s</a></div>', js_strings.what_is_this));
        $('#photo-explained').jqm({overlay:50});
    }
    else {
        $('#id_dedication_image').parent().append(string_subs('<a class="field-help-text" id="dedication-image" href="'+photo_url+'" target="_blank">%s</a>', js_strings.view_photo));
        $('#id_dedication_image').parent().append(string_subs('<div class="field-help-text"><a id="remove-image" href="javascript:remove_image();">%s</a></div>', js_strings.remove_photo));
    }

    $('#processing').jqm({overlay:50, modal:true});

    $('#step-1-form').submit(function() {
        if ($('#id_dedication_image').val()) {
            // Show an overlay.
            $('#processing').jqmShow();
        }
    });

    $('.gender_combo').parents('ul').addClass('gender-combo');
});

function show_example() {
    $('#photo-explained').jqmShow();
}

function remove_image() {
    $('#dedication-image').remove();
    $('#remove-image').remove();
    jQuery.post(remove_image_url, 'spi='+spi_id);
}
