$(function(){
    $('#id_category').change(function(){
        var target = $('#id_subcategory');
        if (!target.length)
            return;
        target = target[0];
        var sel = target.value;
        $.post('/reference/get_subcategories_ajax/',
            {'category': $(this).val()},
            function(json){
                eval("var data = " + json);
                if (data){
                    for(var count = target.options.length - 1; count >= 0; count--){
                        target.options[count] = null;
                    }
                    for (var i = 0; i < data['subcategories'].length; i++){
                        if (data['subcategories'][i][0] == sel)
                            target.options.add(new Option('' + data['subcategories'][i][1], '' + data['subcategories'][i][0], true));
                        else
                            target.options.add(new Option('' + data['subcategories'][i][1], '' + data['subcategories'][i][0]));
                    }
                    if (typeof(RecreateSelect) != 'undefined') RecreateSelect('id_subcategory');
                }
            });
    });
});

