var renderSearched = function(items, input_text){
    var len =  items.length;
    
    //Forzo la chiusura del pannello che oogni tanto rimane aperto
    $( "#outside" ).panel( "close" );
    
    var htmlItems = items.join("");
    var container = "<ul>";
    if(len === 0) {
        container = "<p>";
        htmlItems = "<i>Non sono stati trovati articoli per la ricerca: " + input_text + ".</i>";
    }
    
    $(container, {
        html: htmlItems
    }).prependTo(".listresult");
    
    $.mobile.loading('hide');
    
    //In caso non ci sia contenuto lo scrivo già nel content, 
    // non c'è bisogno anche del toaster
    if(len > 0)
        toastr.info('Trovati ' + items.length + ' articoli.');
};

function searchWpPosts() {
    var table = POST.table;
    
    var input_text = $("input.cerca").val();
    input_text = encodeURIComponent(input_text);
    var jsonurl = weburl + REST_PARAMS.posts + REST_PARAMS.per_page + "&search=" + input_text + "";
    $(".listresult").empty();
    $("body").pagecontainer("change", "#cerca");
    
    $.mobile.loading('show');
    $.ajax({
        dataType: "json",
        url: jsonurl,
        success: function (data) {
            var items = [];
            var n_error = 0;
            FONTE.updatedPostsCount = 0;
            FONTE.neededPostsCount = data.length;
            
            if(FONTE.neededPostsCount === 0) {
                renderSearched(items, input_text);
                return false;
            }
            
            $.each(data, function (key, val) {
                var id = val.id;
                var date = val.date;
                var title = val.title.rendered;
                var tag = data.tags;
                var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
            
                FONTE.dbHandler.executeSql("SELECT * FROM " + table + " WHERE id = ?;", [id], function(resultSet) {
                    FONTE.updatedPostsCount++;
                    if(resultSet.rows.length > 0) {
                        items.push(getLiPost(id, title, cleanTime));
                    } else {
                        items.push(getLiPostNotPresent(id, title, cleanTime, val.link, 'color:#666;'));
                    }
                    
                    if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
                        renderSearched(items, input_text);
                    }
                }, function (error) {
                    n_error++;
                    if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
                        renderSearched(items, input_text);
                    }
                });            
            });
        },

        error: JSONErrorHandler
    });
}

function cerca() {
    var ret = checkConnection('ERR_CERCA');

    if (ret) {
        searchWpPosts();
    }

    return ret;
}