$(document).ready(function(){
    
    /* common info */
    
    var f = {
        'head': "#form-blog-posts-edit input[name='head']",
        'content': "#form-blog-posts-edit textarea[name='content']",
        'cntrs': "#form-blog-posts-edit .submit input",
        'id': "#form-blog-posts-edit input[name='id']"
    };
    
    $(f['head'] + ", " + f['content']).keyup( function() {
        var head = $(f['head']);
        var content = $(f['content']);
        var cntrs = $(f['cntrs']);
        // если хоть че-нить введено
        if(head.val() != "" || content.val() != "") {
            // активируем контролы
            cntrs.attr("disabled", false);
            // добавим пост, если это добавление
            if($(f['id']).val() == 0) {
                // нужно поставить блок, чтоб 100500 раз не добавился пост
                $(f['id']).val(-1);
                // отправляем форму, ток на добавление
                return fpage({
                    plugin: 'blog',
                    form: 'form-blog-posts-edit'
                }, {
                    action: 'add'
                });
            }
        }
        // ничего не введено, хуёво
        else {
            // если был поставлен блок, его нужно снять
            if($(f['id']).val() == -1)
                $(f['id']).val(0);
            cntrs.attr("disabled", true);
        }
    });

    $("#form-blog-posts-edit .input-tags")
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON( "/?page=tags&action=search", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
    
    /* addons */
    
    $(".posts.edit .addons-cntrls a").click(function(){
        switch($(this).attr("href")) {
            case '#images': {
                $(".posts.edit .addon.images").show();
            } break;
            default: {
                $(".posts.edit .addon").hide();
            } break;
        }
        $(".posts.edit .addons-cntrls a").removeClass("active");
        $(this).addClass("active");
    });
    
    /* addons: images */

    // инициализировали аплоадер
    uploader("form-blog-posts-edit-image", "input-file-image", {
        'action': "edit",
        'item': "image"
    }, {
        'plugin': "blog"
    }, {}, {
        'multi': true
    });
    
    /* scs */

    pl_blog.appoint("scs", "add", function(data, params, opts){
        ;
    });

    pl_blog.appoint("scs", "delete", function(data, params, opts){
        ;
    });

    pl_blog.appoint("scs", "edit", function(data, params, opts){

        switch(params['item']) {
            // редактируем фотки поста
            case 'image': {
                $(".posts.edit .addon.images .list").append(data.html);
            } break;
            // редактируем сам пост
            default: break;
            
        }

    });

    /* msgs */
    
    pl_blog.appoint("msg", "add", function(data, params, opts){
        $(f['id']).val(data.output.post.id);
    });
    
    pl_blog.appoint("msg", "edit", function(data, params, opts){

        switch(params['item']) {
            // редактируем фотки поста
            case 'image': {
                ;
            } break;
            // редактируем сам пост
            default: {
                if(data.msgs[0].type == "s" && !params['where'])
                    location.href = "/id" + data.output.post.id;
            } break;
            
        }
        
    });

    pl_blog.appoint("msg", "delete", function(data, params, opts){

        switch(params['item']) {
            // удаляем фотки поста
            case 'image': {
                if(data.msgs[0].type == "s")
                    $("#post-image-" + params['image']).hide();
            } break;
            // удаляем сам пост
            default: break;
            
        }

    });

});
