$(function(){
    function select( obj, with_children, with_father ){
        obj.addClass( 'selected' );
        $("#text_" + obj.attr('id')).show();

        if( with_children ) {
            $( "." + obj.attr('id') ).each( function() { select( $(this), true, false ); } );
        }

        if( with_father ) {
            $.each( obj.attr('class').split(' '), function() { 
                if( this.indexOf('genre_') === 0 && this != 'genre_parent' ) {
                    var obj = $('#' + this);
                    select( obj, false, true );
                }
            } );
        }
    }
    function unselect( obj ){
        obj.removeClass( 'selected' );
        $("#text_" + obj.attr('id')).hide();

        $( "." + obj.attr('id') ).each( function() { unselect( $(this) ); } );
    }
    $(".genre").click( function() {
        var obj = $(this);
        if( obj.hasClass('selected')) {
            unselect(obj);
        } else {
            select(obj, true, true);
        }
    } );

    $("#form_genres").submit( function(event) {
        event.preventDefault();
        var data = new Array();
        $(".selected").each( function() {
            data.push( $(this).attr('id').split('_')[1] );
        } );
        $("#selected_genres").val( data );
        $.submit_ajax( "#form_genres", $("#form_result_none"), false, function( status, msg ) { if(status){ document.location.href = msg;} } );
    });

    $(".remove-song").click(function(event){
        event.preventDefault();
        var id=$(this).attr('data-id');
        $.post($(this).attr('href'), {'id':id});
        $(this).parents('.emn').fadeOut();
    });
});

