function myJsonCategory(Qcategory, div, addTagCategory) {
    FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
        var items = [];
        for (var i = 0; i < resultSet.rows.length; i++) {
            var val = JSON.parse(resultSet.rows.item(i).post);
            var id = val.id;
            var date = val.date;
            var title = val.title.rendered;
            var url = val.guid.rendered;
            var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
            var tag = '';
            var cattag = '';
            /* if (addTagCategory) {
                 $.each(val.tags, function (index, value) {
                     if (value == 43) {

                     }
                     if (value == 36) {

                     }
                 });
                 //key mi dice l'indice'
                 items.push("<li class='"+ cattag +"'><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small><span>" + tag + "</span>|</li>");
             }
            else {*/
                items.push(getLiPost(id, title, cleanTime));
        }
        $("<ul/>", {
            "class": "my-new-list",
            html: items.join("")
        }).prependTo(div);
        $.mobile.loading('hide');
    });
}

var getLiPostNotPresent = function(id, title, cleanTime, url, style){
    //TODO:var onclick = " onclick='"+getWpPost()+ "' ";
    var li =  "<li>"+
                "<a style='"+ style +"' href='" + url + "' rel='external'>" + 
                    title + 
                "</a>"+
                "<br/>"+
                "<small>" + cleanTime + "</small>"+
                "<hr class='post-divider'>"+
              "</li>";
                
    return li;
};

var getLiPost = function(id, title, cleanTime){
    var li =  "<li>"+
                    "<a href='#singleQpost' data-post='" + id + "'>" + 
                        title + 
                    "</a>"+
                    "<br/>"+
                    "<small>" + cleanTime + "</small>"+
                    "<hr class='post-divider'>"+
                "</li>";
                
    return li;
};

var drawListPost = function(div, resultSet, position) {
    var items = [];
    for (var i = 0; i < resultSet.rows.length; i++) {
        var val = JSON.parse(resultSet.rows.item(i).post);
        var id = val.id;
        var date = val.date;
        var title = val.title.rendered;
        var url = val.guid.rendered;
        var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);

        items.push(getLiPost(id, title, cleanTime));
    }

    var ul = $("<ul/>", {
        html: items.join("")
    });

    if(position == 'append'){
        ul.appendTo(div);
    } else if(position == 'prepend'){
        ul.prependTo(div);
    }
    
    setTimeout(function () {
        $.mobile.loading('hide');
    }, 1000);
};

var appendPostList = function(div, resultSet, categories, fallback) {
    var type = getObjKey(FONTE.categories, categories);
    
    if (resultSet.rows.length > 0) {
        FONTE.page_loaded[type]++;
        drawListPost(div, resultSet, 'append');
    } else if (fallback) {
        fallback();
    } else {
        $.mobile.loading('hide');
        toastr.info("Non ci sono altri articoli da visualizzare");
    }
};

var prependPostsList = function(div, resultSet, categories, fallback) {
    var type = getObjKey(FONTE.categories, categories);
    
    //$(div).empty();
    if (resultSet.rows.length > 0) {
        FONTE.page_loaded[type]++;
        drawListPost(div, resultSet, 'prepend');
    } else if (fallback) {
        fallback(div, categories);
    } else {
        drawNoPostsFound(div);
    }
};

function drawNoPostsFound(div) {
    $(div).empty();
    $(div).append('<span>Non ci sono nuovi contenuti.</span>');
    $.mobile.loading('hide');
}

function sqlErrHandler(error){
    $.mobile.loading('hide');
    console.log(error.message);
}

var getCategoryWhere = function(categories) {
    var catsWhere = "";
    for(var i = 0, len = categories.length; i < len; i++) {
        var cat = categories[i];
        var c = 'catid = '+ cat + ' ';
        if(i === 0) {
            catsWhere = '(' + c;
        } else if(i == len -1) {
            catsWhere += 'OR ' + c + ')';
        } else {
            catsWhere += 'OR ' + c;
        }
    }
    
    return catsWhere;
};

var POST = POST || {};
POST.sql = {
    init: "SELECT DISTINCT * FROM xm24_posts JOIN xm24_cats_to_posts USING(id) WHERE ",
    end : "ORDER BY date COLLATE NOCASE DESC LIMIT ?"
};

POST.table = "xm24_posts";

var selectLastNews = function(div, categories) {
    var catsWhere = getCategoryWhere(categories);
    
    var sql = POST.sql.init + catsWhere + POST.sql.end;
    FONTE.dbHandler.executeSql(sql, [REST_PARAMS.max_page], function (resultSet) {
        prependPostsList(div, resultSet, categories);
    }, sqlErrHandler);    
};

function renderLastNews(div, categories) {
    var storage = window.localStorage;
    var type = getObjKey(FONTE.categories, categories);
    var lastnewsDate = storage.getItem('db_last_' + type + '_date');
    var firstTime = storage.getItem('db_last_' + type + '_firsttime');
    
    if (firstTime == 'yes') {
        selectLastNews(div, categories);
    } else if (firstTime == 'no') {
        if (lastnewsDate) {
            var sql = POST.sql.init + "date > ? AND " + getCategoryWhere(categories) + POST.sql.end;
            FONTE.dbHandler.executeSql(sql, [lastnewsDate, REST_PARAMS.max_page], function (resultSet) {    
                prependPostsList(div, resultSet, categories, selectLastNews);
            }, sqlErrHandler);
        } else {
            selectLastNews(div, categories);
            toastr.info("Non ci sono nuovi contenuti");
        }
    } else {
        drawNoPostsFound(div);
    }
}

function renderPrevNews(div, categories, page, callback){
    var sql = POST.sql.init + getCategoryWhere(categories) + POST.sql.end + ', ?';
    FONTE.dbHandler.executeSql(sql, [page * REST_PARAMS.max_page, (page+1) * REST_PARAMS.max_page], function (resultSet) {
        appendPostList(div, resultSet, categories, callback);
    }, sqlErrHandler);
}

function myJsonLastPage(div) {
    var storage = window.localStorage;
    var lastnewsDate = storage.getItem('db_lastnews_date');
    var firstTime = storage.getItem('db_lastnews_firsttime');
    if (firstTime != 'yes') {
        if (lastnewsDate) {
            FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM xm24_posts WHERE date > ? ORDER BY date COLLATE NOCASE DESC LIMIT 40;", [lastnewsDate], function (resultSet) {
                var items = [];
                $(div).empty();
                if (resultSet.rows.length > 0) {
                    for (var i = 0; i < resultSet.rows.length; i++) {
                        var val = JSON.parse(resultSet.rows.item(i).post);
                        var id = val.id;
                        var time = val.modified;
                        var title = val.title.rendered;
                        var url = val.guid.rendered;
                        // console.log(Url);
                        var splitTime = time.split("T");
                        var cleanTime = splitTime[0];
                        //key mi dice l'indice'
                        items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>");
                    }
                    $("<ul/>", {
                        "class": "my-new-list",
                        html: items.join("")
                    }).prependTo(div);
                } else {
                    $(div).empty();
                    $(div).append('<span>Non ci sono nuovi contenuti.</span>');
                }
            });
        } else {
            $(div).empty();
            $(div).append('<span>Tutti i contenuti sono nuovi.</span>');
        }
    } else {
        $(div).empty();
        $(div).append('<span>Tutti i contenuti sono nuovi.</span>');
    }
}

function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
    $.mobile.loading('show');
    FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
        var items = [];
        $(div).empty();
        for (var i = 0; i < resultSet.rows.length; i++) {
            var val = JSON.parse(resultSet.rows.item(i).post);
            var id = val.id;
            var time = val.modified;
            var title = val.title.rendered;
            var url = val.guid.rendered;
            var tag = val.tags;
            var splitTime = time.split("T");
            var cleanTime = splitTime[0];
            //key mi dice l'indice'
            items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
        }
        $("<ul/>", {
            "class": "my-new-list",
            html: items.join("")
        }).prependTo(div);
    }, function (error) {
        console.log('errore myJsonCategoryPaginated: ' + error);
    });
    $.mobile.loading('hide');
}

var renderShareButton = function(div_content, title, url, content){
    $('.share-btn').remove();
    
    content = content || '';
    
    var shareButton = $('<button>', {
        class : "share-btn ui-btn ui-shadow ui-corner-all",
        text: "Condividi"
    }).click(function(){
        shareMeNow(title, content, url);
    });
    
    $(div_content).after(shareButton);
};

function drawPost(div_title, div_content, resultSet){
    for (var i = 0; i < resultSet.rows.length; i++) {
        var val = JSON.parse(resultSet.rows.item(i).post);
        var id = val.id;
        var time = val.date;
        var title = val.title.rendered;
        var url = val.guid.rendered;
        var content = val.content.rendered;
        var tags = val.tags;
        content = findImg(content);

        $(div_title).html(title);
        $(div_content).html("<p>" + content + "</p>");
        renderShareButton(div_content, title, url, '');
    }
}

function drawEvent(div_title, div_content, resultSet){
    for (var i = 0; i < resultSet.rows.length; i++) {
        var val = resultSet.rows.item(i);
        var evInitDate = EVENTS.formatDate(val.initDate, EVENTS.displayDateFormat);
        var evEndDate = EVENTS.formatDate(val.endDate, EVENTS.displayDateFormat);
        
        var id = val.id;
        var title = val.title;
        var url = val.url;
        var content = entityToHtml(val.description);
        var geo = val.geo;
		var imgUrlThumb = getImageUrl(val.img, 'thumb');

        $(div_title).html(title);
		var img = imgUrlThumb != "" ? "<a href='" + getImageUrl(val.img, 'large') + "'>" +
										"<img src='" + imgUrlThumb + "'/>" +
									  "</a><br>" : "";
        $(div_content).html(img + "<small>" + evInitDate +"-" + evEndDate +"</small><p>" + content + "</p>");
        renderShareButton(div_content, title, url, evInitDate + " "+ evEndDate);
    }
}

function myJsonPost(Qid, div_title, div_content, _class) {
    var table = POST.table;
    if(_class){
        table = EVENTS.table.single;
    }

    FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM " + table + " WHERE id = ?;", [Qid], function(resultSet) {
        if(!_class){
            drawPost(div_title, div_content, resultSet);
        } else {
            drawEvent(div_title, div_content, resultSet);
        }
    }, sqlErrHandler);
}

function myJsonPage(Qid, div_title, div_content) {
    $.mobile.loading('show');
    var pageId = parseInt(Qid);
    FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM xm24_pages WHERE id = ?;", [pageId], function (resultSet) {
        for (var i = 0; i < resultSet.rows.length; i++) {
            var data = resultSet.rows.item(i);
            var id = data.id;
            var time = data.time;
            var title = data.title;
            var content = data.page;
            content = findImg(content);
            $(div_title).html(title);
            $(div_content).html("<p>" + content + "</p>");
        }
    });
    $.mobile.loading('hide');
}

function myJsonRandomPost(div_title, div_content) {
    $.mobile.loading('show');
    FONTE.dbHandler.executeSql("SELECT DISTINCT * FROM xm24_posts ORDER BY RANDOM() LIMIT 1;", [], function (resultSet) {
        for (var i = 0; i < resultSet.rows.length; i++) {
            var val = JSON.parse(resultSet.rows.item(i).post);
            var id = val.id;
            var time = val.modified;
            var title = val.title.rendered;
            var url = val.guid.rendered;
            var content = val.content.rendered;
            content = findImg(content);
            $(div_title).html(title);
            //key mi dice l'indice'
            $(div_content).html("<p>" + content + "</p>");
        }
    });
    $.mobile.loading('hide');
}

function createDB() {
    //crea il databse per i posts se non esiste
    FONTE.dbHandler = window.sqlitePlugin.openDatabase({
        name: FONTE.dbName,
        location: 'default'
    }, function () {
        FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, post)');
        
        FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_cats (catid INTEGER PRIMARY KEY, title, cat)');
        FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_cats_to_posts (id, catid, PRIMARY KEY (id, catid))');
        
        //FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags (id INTEGER PRIMARY KEY, title, tag)');
        //FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags_to_posts (id, tagid)');
        //FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_pages (id INTEGER PRIMARY KEY, title, date, page)');
		FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_events_single');
        FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_events_single (id INTEGER PRIMARY KEY, title, description, initDate, endDate, url, geo, img)');
        //FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags_to_events (id, tagid)');
        //FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_events_repeat (id INTEGER PRIMARY KEY, title, description, initDate, endDate, url, geo)');
    }, function () {
        console.log('error');
        console.log(arguments);
    });
}

function insertOrUpdateCatToPost(id, catId) {
    FONTE.dbHandler.executeSql('INSERT OR REPLACE INTO xm24_cats_to_posts VALUES (?,?)', [id, catId], 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 deleteDB() {
    window.sqlitePlugin.deleteDatabase({
        name: FONTE.dbName,
        location: 'default'
    });
    var storage = window.localStorage;
    storage.setItem('db_update_date', null);
    storage.setItem('db_lastnews_date', null);
    createDB();
}

function getSinglePageRecur(url, category, pagenum) {
    $.ajax({
        dataType: "json",
        url: url + "&categories=" + category + "&page=" + pagenum,
        success: function (data, textStatus, jqXHR) {
            var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
            if (pagenum == totalPages || totalPages === 0) FONTE.updatedCategoriesCount += 1;
            FONTE.neededPostsCount += data.length;
            if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.neededPostsCount === 0) {
                toastr.info('Nessun nuovo articolo.');

                var date = new Date();
                var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
                currentUpdate += 'T' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ':' + ('0' + date.getSeconds()).slice(-2);

                var lastUpdate = window.localStorage.getItem('db_update_date');

                window.localStorage.setItem('db_update_date', currentUpdate);
                window.localStorage.setItem('db_lastnews_date', lastUpdate);

                //feedback
                $("#aggiorna").attr("src", "./image/aggiorna.png");
            }
            $.each(data, function (key, val) {
                var id = val.id;
                var time = val.date;
                var title = val.title.rendered;
                var tags = val.tags;
                var blob = JSON.stringify(val);
                FONTE.dbHandler.executeSql('INSERT OR REPLACE INTO xm24_posts VALUES (?,?,?,?,?)', [id, title, time, category, blob], function (resultSet) {
                    FONTE.updatedPostsCount += 1;
                    console.log('Voci aggiornate: ' + FONTE.updatedPostsCount);
                    if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
                        //window.localStorage.setItem('has_run', 'true');

                        var date = new Date();
                        var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
                        currentUpdate += 'T' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ':' + ('0' + date.getSeconds()).slice(-2);

                        var lastUpdate = window.localStorage.getItem('db_update_date');

                        window.localStorage.setItem('db_update_date', currentUpdate);
                        window.localStorage.setItem('db_lastnews_date', lastUpdate);

                        toastr.info('Aggiornati ' + FONTE.updatedPostsCount + ' articoli.');

                        //feedback
                        $("#aggiorna").attr("src", "./image/aggiorna.png");
                        displayLastUpdateDate();
                    } //manca il caso in cui sono stati cancellati dei post online, vanno cancellati anche dall'app.
                }, function (error) {
                    FONTE.updatedPostsCount += 1;
                    if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
                        toastr.info('Aggiornati ' + FONTE.updatedPostsCount + ' articoli.');
                        //feedback
                        $("#aggiorna").attr("src", "./image/aggiorna.png");
                    }
                });
                $.each(tags, function (key, val) {
                    aggiornaTagsToPosts(id, val);
                });
            });
            if (pagenum < totalPages) {
                pagenum += 1;
                getSinglePageRecur(url, category, pagenum);
            }
        },
        error: JSONErrorHandler
    });
}
