$(document).ready(function() {
    var category = new Category();
});

/**
 * Class: Category
 */
function Category() {
    this.initialize.apply(this, arguments);
}
Category.prototype = {
    // Constructor
    initialize: function() {
        var self = this;
        
        this.changeCategory();
        
        // First check
        $('.categoryItem').each(function(){
            $('select:not(:first)', $(this)).hide();
            
            // If selected exist
            $('option:selected:not([value=""])', $(this)).each(function(){
                self.switchCategory($(this).parent().attr('id').replace('category_', ''));
            });
        });
    },
    
    // Select change handler
    changeCategory: function() {
        var self = this;
        
        $('.categoryItem select').each(function(){
            var $select = $(this);
            
            $select.change(function(){
                $('select', $(this).parent()).hide();
                
                var nodeId = $(this).attr('id').replace('category_', '');
                self.switchCategory(nodeId);
                
                var childNodeId = $('option:selected', $(this)).attr('id');
                if (childNodeId) {
                    $('#category_' + childNodeId.replace('hasNode_', '')).show();
                    $('[type=hidden]', $(this).parent()).val('');
                } else {
                    $('[type=hidden]', $(this).parent()).val($(this).val());
                }
                
                $('select:hidden option:selected', $(this).parent()).each(function(){
                    $(this).removeAttr('selected');
                });
            });
        });
    },

    // Switch Action
    switchCategory: function (nodeId) {
        var self = this;
        
        $('#category_' + nodeId).show();
        $('#hasNode_' + nodeId).attr('selected', 'selected');
        
        var parentNodeId = $('#hasNode_' + nodeId).parent().attr('id');
        
        if (parentNodeId) {
            self.switchCategory(parentNodeId.replace('category_', ''));
        }
    }
};
