function selectCategory(level, category_id, selected, has_children, only_safe) {
    if (!only_safe) {
        var only_safe = 0;
    }

    $(".loader").show();

    jQuery.each($("#categories div"), function(i, val) {
        if ($(val).attr("x:level") >= level) {
            $(val).remove();
        }
    });

    if (has_children == 0) {
        enableSelect(category_id);
        return;
    }

    disableSelect();

    $("#next").attr("disabled", true);

    var handler = $('#categories');

    var div = $('<div x:level="'+level+'"></div>');
    var sel = $('<select size="2"></select>');

    $.getJSON(url + "/item/get_children?category_id=" + category_id + "&only_safe=" + only_safe, function(json) {
        jQuery.each(json.categories, function(i, e) {
            sel.append('<option id="option_' + e.category_id + '" value="' + e.category_id + '" x:has_children="' + e.has_children + '">' + e.name + (e.has_children == 1 ? ' »' : '') + '</option>');
        });

        sel.val(selected);

        div.append(sel);

        initCategories(only_safe);

        $(".loader").hide();
    });

    handler.append(div);
}

function enableSelect(category_id) {
    $("#category_id").val(category_id);
    $(".loader").hide();
    $("#next").attr("disabled", false);
}

function disableSelect() {
    $("#next").attr("disabled", true);
}

function initCategories(only_safe) {
    $("#categories select").unbind('click').click(function() {
        sel = $(this);
        var opt = $("#option_" + sel.val());


        var level = parseInt(sel.parent().attr("x:level"));
        var category_id = sel.val();

        selectCategory(level+1, category_id, null, opt.attr('x:has_children'), only_safe);
    });
}

$(document).ready(function() {
    var active   = url + "/design/img/star_active.png";
    var inactive = url + "/design/img/star_inactive.png";

    $(".star img").click(function() {
        $.post(url + "/favorite/toggle", { 'item_id': parseInt($(this).attr('x:item_id')) });

        if ($(this).hasClass('inactive')) {
            $(this).removeClass('inactive');
            $(this).attr('src', active);
        }
        else {
            $(this).addClass('inactive');
            $(this).attr('src', inactive);
        }
    });
});

