function aggiornaTagsToPosts(id, tagId) {
    FONTE.dbHandler.executeSql('INSERT INTO xm24_tags_to_posts VALUES (?,?)', [id, tagId], function (resultSet) {
        console.log('resultSet.insertId: ' + resultSet.insertId);
        console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
    }, function (error) {
        console.log('INSERT error: ' + error.message);
        //feedback
        $("#aggiorna").attr("src", "./image/aggiorna.png");
    });
}

function aggiornaTags(pagenum) {
    var jsonurl = weburl + "wp-json/wp/v2/tags?per_page=100&page=" + pagenum;
    $.ajax({
        dataType: "json",
        url: jsonurl,
        success: function (data, status, xhr) {
            var totalPages = parseInt(xhr.getResponseHeader("X-WP-TotalPages"));
            $.each(data, function (key, val) {
                var name = val.name;
                var slug = val.slug;
                var id = val.id;
                var blob = JSON.stringify(val);
                FONTE.dbHandler.executeSql('INSERT INTO xm24_tags VALUES (?,?,?)', [id, slug, blob], function (resultSet) {
                    console.log('resultSet.insertId: ' + resultSet.insertId);
                    console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
                }, function (error) {
                    console.log('INSERT error: ' + error.message);
                });
            });
            pagenum += 1;
            if (pagenum <= totalPages) aggiornaTags(pagenum);
        },
        error: JSONErrorHandler
    });
}

function myJsonPostByTagList(idTag, div) {
    $.mobile.loading('show');
    var tagid = parseInt(idTag);
    FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags_to_posts WHERE tagid = ?;", [tagid], function (resultSet) {
        var items = [];
        var finishCounter = 0;
        for (var i = 0; i < resultSet.rows.length; i++) {
            var val = resultSet.rows.item(i);
            FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ? ORDER BY title COLLATE NOCASE ASC;", [val.id], function (resultSetPost) {
                finishCounter++;
                for (var n = 0; n < resultSetPost.rows.length; n++) {
                    var val = JSON.parse(resultSetPost.rows.item(n).post);
                    var id = val.id;
                    var time = val.modified;
                    var title = val.title.rendered;
                    var url = val.guid.rendered;
                    var splitTime = time.split("T");
                    var cleanTime = splitTime[0];
                    //key mi dice l'indice'
                    items.push({
                        item: "<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</li>",
                        title: title
                    });
                }
                // fallo solo quando items è stato riempito
                if (finishCounter >= resultSet.rows.length - 1) {
                    $(div).empty();
                    $("<ul/>", {
                        "class": "my-new-list",
                        html: function () {
                            function compare(a, b) {
                                if (a.title < b.title) return -1;
                                if (a.title > b.title) return 1;
                                return 0;
                            }
                            items.sort(compare);
                            var finalHtml = "";
                            for (var i = 0; i < items.length; i++) {
                                finalHtml += items[i].item;
                            }
                            return finalHtml;
                        }()
                    }).prependTo(div);
                }
            });
        }
    }, function (error) {
        console.log(error);
    });
    $.mobile.loading('hide');
}

function initTag(div) {
    $.mobile.loading('show');
    FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags ORDER BY date COLLATE NOCASE DESC;", [], function (resultSet) {
        var items = [];
        for (var i = 0; i < resultSet.rows.length; i++) {
            var val = JSON.parse(resultSet.rows.item(i).tag);
            var name = val.name;
            var slug = val.slug;
            var id = val.id;
            items.push("<li><img src='./image/virgolette_1.png' class='epuntato'/><a href='#posttag' data-post='" + id + "' >" + name + "</a><br/></li>");
        }
        $(div).empty();
        $("<ul/>", {
            "class": "my-new-list",
            html: items.join("")
        }).prependTo(div);
    }, function (error) {
        console.log(error);
    });
    $.mobile.loading('hide');
}

function postInListTag(div) {
    $(div).on('click', 'li > a', function () {
        var idTag = $(this).attr("data-post");
        var titleTag = $(this).html();
        $("#tagpostlist").empty();
        myJsonPostByTagList(idTag, '#tagpostlist');
        $("#tagtitle").empty();
        $("#tagtitle").append(titleTag);
        // Prevent the usual navigation behavior
        event.preventDefault();
        $("#posttag").attr("id", '#posttag?idT=' + idTag);
        $(":mobile-pagecontainer").pagecontainer("load", '#posttag' + idTag, {
            showLoadMsg: false
        });
        location.hash = '#posttag?idT=' + idTag;
    });
}

function initTagsPage() {
    if (!FONTE.tagsPageInitiated) {
        initTag("#mostralistaTag"); // questo mostra i tag
        postInListTag("#mostralistaTag"); // questo ti sposta alla specifica lista dei post di un tag
        FONTE.tagsPageInitiated = true;
    }
}