(function($) {
	function pdate_show_hide_fields(pfield, update) {
		var precision = $(pfield).val();
        var parent_ul = $(pfield).closest("ul");
		if (precision >= 2) {
			$("input.month", parent_ul).hide();
		}
		else if (update) {
			$("input.month", parent_ul).show();
		}

		if (precision >= 1) {
			$("input.day", parent_ul).hide();
		}
		else if (update) {
			$("input.day", parent_ul).show();
		}
	}

	$(document).ready(function($) {
		// do it for existing fields
        $("input[name$=__end___date_2]").after(
            ' <a class="copy-range-start-date" href="#">Copy start date</a>');
        $(".copy-range-start-date").live('click', function(){
            var end_id = $(this).closest("ul").attr('id').slice(
                'field-group-'.length);
            $('[name^='+end_id+']').each(function(){
                var start_name = $(this).attr('name').replace(
                    '__end__', '__start__')
                var start_element = $('[name='+start_name+']');
                $(this).val(start_element.val());
                if($(this).attr('type') == 'checkbox'){
                    $(this).attr('checked', start_element.attr('checked'));
                }
                $(this).trigger('change');
            });
            return false;
        });
        function update_all_dates(action) {
            if (action === 'undefined') {
                action = false;
            }
            $(".precision").each(function () {
                pdate_show_hide_fields(this, action);
            });
        };
        update_all_dates(false);
		// listen on 'change' event for existing fields as well as newly created ones
		$(".precision").live('change', function(ev) {
			pdate_show_hide_fields(ev.target, true);
		});
        $(document).bind("add_inline_callback", function(e){
            update_all_dates(true);
        });
	});
})(jQuery); // use django.jQuery if we manage to get this file included after the standard mongoadmin js

