Ilovexm24/www/js/main.js

900 lines
No EOL
32 KiB
JavaScript

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
///VARIABILI GLOBALI///
var FONTE = FONTE || {};
FONTE.dbName = "xm24";
FONTE.dbHandler;
FONTE.tagsPageInitiated = false;
FONTE.categoriesList = [8, 497];
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.hrefseguente = "";
FONTE.ajaxError = false;
/*
* data ultimo aggiornamento
*/
function ultimoAggiornamento() {
var lastUpdate = window.localStorage.getItem('db_update_date');
if (lastUpdate) {
var data = lastUpdate.split('T');
var datagiorno = data[0];
var dataora = data[1];
$("#datadiritti").empty();
$("#datadirittiora").empty();
display_results("#datadiritti", datagiorno)
display_results("#datadirittiora", dataora)
if (data) {
$("#boxdata").css("display", "block");
}
} else {
alert('ERRORE, manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.');
}
};
var paginacorrente = "";
function alterContent(url) {
paginacorrente = $("body").pagecontainer("getActivePage").attr("id");
switch (url) {
case '#index':
$("#navheader").addClass("hide");
$("#navfooter").addClass("hide");
break;
case '#ilove':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonCategory(497, "#mostralista");
/* myJsonPage(3452, '#prestitle', '#mostrapres');*/
break;
case '#info':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonCategory(8, "#mostralistainfo");
break;
case '#aggiorna':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
// ultimoAggiornamento();
break;
case '#ultime':
case '#tag':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
break;
case '#quotidiano':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');
break;
};
// Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url
$.mobile.navigate(url);
};
/*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)")
, results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function display_results(contenitore, messaggio) {
$(contenitore).text(messaggio);
};
$(function () {
$("form").submit(function () {
return false;
});
});
function benvenuta() {
$("#benvenuta").popup("open");
};
function aggiornaora() {
$("#aggiornaora").popup("open");
};
function setFirstRun() {
initStorage();
overlayblock();
if (window.localStorage.getItem('has_run') != 'true') {
//do some stuff if has not loaded before
overlayblock();
benvenuta();
if (checkConnection()) {
partialUpdate();
//window.localStorage.setItem('has_run', 'true');
}
}
};
/*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio
function onDeviceReady() {
// console.log('deviceready');
createDB();
setFirstRun();
$("#navheader").addClass("hide");
$("#navfooter").addClass("hide");
$("a.nav").on("click", function (event) {
// Prevent the usual navigation behavior
event.preventDefault();
hrefseguente = $(this).attr("href");
alterContent(hrefseguente);
});
};
function overlayblock() {
$(".overlaynero").toggleClass("hide");
}
/*per network info*/
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
if (states[networkState] == 'Unknown connection' || states[networkState] == 'No network connection') {
//alert('Non sei connesso ad internet, connettiti ad una rete per procedere.');
return false
} else {
return true
}
}
/*///////////////fine utilities//////////////*/
var weburl = "http://www.ecn.org/xm24/";
var arrayTag = [];
/*/////finite variabili globali////////*/
function intercettaUrl() {
// LETTURA - Log the results of the navigate event
$(window).on("navigate", function (event, data) {
idPost = getParameterByName('id');
if (idPost != "") {
myJsonPost(idPost, "#titolosingle", "#mostracontentsingle");
}
});
};
function postInList() {
//SCRITTURA
$("body").on('click', '.listevoci li > a', function (event) {
// console.log("HUU_post in list");
var idOra = $(this).attr("data-post");
$("#titolosingle").empty();
$("#mostracontentsingle").empty();
//console.log(idOra);
myJsonPost(idOra, "#titolosingle", "#mostracontentsingle");
// Prevent the usual navigation behavior
event.preventDefault();
/*se serve idTAg, mettiamolo nell'url!! e anche nella page!*/
$("#singleQpost").attr("id", '#singleQpost?id=' + idOra)
$(":mobile-pagecontainer").pagecontainer("load", '#singleQpost' + idOra, {
showLoadMsg: false
});
location.hash = '#singleQpost?id=' + idOra;
});
};
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 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 myJsonPost(Qid, div_title, div_content) {
FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ?;", [Qid], 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>");
}
}, function (error) {
console.log(error);
});
};
function myJsonPage(Qid, div_title, div_content) {
$.mobile.loading('show');
var pageId = parseInt(Qid);
FONTE.dbHandler.executeSql("SELECT * 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);
//key mi dice l'indice'
$(div_content).html("<p>" + content + "</p>");
}
});
$.mobile.loading('hide');
};
function myJsonRandomPost(div_title, div_content) {
$.mobile.loading('show');
FONTE.dbHandler.executeSql("SELECT * 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 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 myJsonCategory(Qcategory, div, addTagCategory) {
$.mobile.loading('show');
FONTE.dbHandler.executeSql("SELECT * 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 time = val.modified;
var title = val.title.rendered;
var url = val.guid.rendered;
var splitTime = time.split("T");
var cleanTime = splitTime[0];
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("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
}
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
}).prependTo(div);
});
$.mobile.loading('hide');
};
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 * 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 * 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');
};
function cercaMe() {
var input_text = $("input.cerca").val();
input_text = encodeURIComponent(input_text);
var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&search=" + input_text + "";
$(".listresult").empty();
$("body").pagecontainer("change", "#ricerca");
$.mobile.loading('show');
var lastUpdate = window.localStorage.getItem('db_update_date');
if (lastUpdate) {
var lastUpdateDate = Date.parse(lastUpdate);
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
var items = [];
$.each(data, function (key, val) {
var id = val.id;
var time = val.modified;
var title = val.title.rendered;
var url = val.guid.rendered;
var tag = data.tags;
var splitTime = time.split("T");
var cleanTime = splitTime[0];
var dTime = new Date(time);
if (dTime.getTime() <= lastUpdateDate) {
//key mi dice l'indice'
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
} else {
items.push("<p><a href='#' onclick='aggiornaora();' style='color:#666;' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</p>");
}
});
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
}).prependTo(".listresult");
$.mobile.loading('hide');
}
, error: JSONErrorHandler
});
} else {
alert('ERR_NOUPDATE');
}
}
function resetAndUpdate() {
var storage = window.localStorage;
//resetto la data e droppo le tabelle
storage.setItem('db_update_date', null);
FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_posts;');
FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, category, post)');
partialUpdate();
}
function update() {
FONTE.dbHandler.executeSql('SELECT COUNT(*) AS numPosts FROM xm24_posts', [], function (resultSet) {
var numPosts = resultSet.rows.item(0).numPosts;
if (numPosts < 300) { //questo numero e' scelto in maniera arbitraria, ricordati Cri.
resetAndUpdate()
} else {
partialUpdate();
}
});
}
function partialUpdate() {
//feedback
$("#aggiorna").attr("src", "./image/icona_aggiorna.gif");
var storage = window.localStorage;
var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&categories=";
FONTE.updatedCategoriesCount = 0;
FONTE.updatedPostsCount = 0;
FONTE.neededPostsCount = 0;
for (var index in FONTE.categoriesList) {
aggiornaSingleCategory(FONTE.categoriesList[index])
}
FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_tags;');
// FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_tags_to_posts;');
FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_pages;');
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)');
aggiornaTags(1);
aggiornaPages();
var firstTime = storage.getItem('db_lastnews_firsttime');
if (firstTime == null) storage.setItem('db_lastnews_firsttime', 'yes');
if (firstTime == 'yes') storage.setItem('db_lastnews_firsttime', 'no');
$("#benvenuta").popup("close");
checkloader();
};
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) {
alert('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.modified;
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);
alert('Aggiornati ' + FONTE.updatedPostsCount + ' articoli.');
//feedback
$("#aggiorna").attr("src", "./image/aggiorna.png");
ultimoAggiornamento();
} //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) {
alert('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
});
};
function aggiornaSingleCategory(category) {
//resetta la variabile d'errore per le chiamate ajax asincrone
FONTE.ajaxError = false;
var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100";
var storage = window.localStorage;
var lastUpdate = storage.getItem('db_update_date');
if (lastUpdate) jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate;
getSinglePageRecur(jsonurl, category, 1)
};
function checkloader() {
myJsonLastPage('#mostralistaultime');
var mieultime = $("#mostralistaultime").html();
// console.log("ultime" + mieultime);
if (mieultime == "<span>Non ci sono nuovi contenuti.</span>") {
//feedback
$("#aggiorna").attr("src", "./image/aggiorna.png");
ultimoAggiornamento();
return true
//console.log("ultime2");
}
// console.log("ultime3");
return false
}
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 aggiornaPages() {
var jsonurl = weburl + "wp-json/wp/v2/pages/";
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
$.each(data, function (key, val) {
var id = val.id;
var time = val.modified;
var title = val.title.rendered;
var content = val.content.rendered;
FONTE.dbHandler.executeSql('INSERT INTO xm24_pages VALUES (?,?,?,?)', [id, title, time, content], function (resultSet) {
console.log('resultSet.insertId: ' + resultSet.insertId);
console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function (error) {
console.log('INSERT error: ' + error.message);
});
});
}
, error: JSONErrorHandler
});
};
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, category, post)');
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)');
}, function () {
console.log('error');
console.log(arguments);
});
};
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 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;
}
}
/* scriversi le cose nel local storage*/
function initStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
function findImg(htmlString) {
var pos = htmlString.indexOf('<img ');
while (pos != -1) {
pos += 5;
htmlString = [htmlString.slice(0, pos), ' onerror="imgNotFound(this);" ', htmlString.slice(pos)].join('');
pos = htmlString.indexOf('<img ', pos);
}
return htmlString;
};
function imgNotFound(img) {
var parent = $(img).parent();
parent.empty();
parent.append('<span>Immagine disponibile online.</span>')
};
function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
if (!FONTE.ajaxError) {
alert('AAAAAAHHHH ' + textStatus);
FONTE.ajaxError = true;
}
};
function cerca() {
if (checkConnection()) {
cercaMe();
return true;
} else {
alert('ERR_CERCA');
return false;
}
};
function segnalaBug() {
if (checkConnection())
return true;
else {
alert('ERR_SEGNALA');
return false;
}
};
function mostraEsperto() {
if (checkConnection()) {
myJsonPage(2167, '#espertotitle', '#mostraesperto');
return true;
} else {
alert('ERR_ESPERTO');
return false;
}
};
function checkAndUpdate() {
if (checkConnection()) {
update();
return true;
} else {
alert('ERR_UPDATE');
return false;
}
};
function checkAndReset() {
if (checkConnection()) {
resetAndUpdate();
return true;
} else {
alert('ERR_RESET');
return false;
}
};
var my_media = {};
function spengimi() {
my_media.stop();
$("#spegni-musica").hide();
}
function onDeviceReadyPush() {
var push = PushNotification.init({
android: {
senderID: "667898382143"
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
/*
* registra l'id univoco dell'installazione su xm.bus.pm
*/
push.on('registration', function(registration) {
console.log(JSON.stringify(registration));
var url = "https://xm.bus.pm/api/d/c?device=" + registration.registrationId;
$.get(url, function( data ) {
console.log(JSON.stringify(data));
});
});
/*
* gestisce la notifica ricevuta
*/
push.on('notification', function(data) {
console.log(JSON.stringify(data));
// alert(JSON.stringify(data));
$("body").pagecontainer("change", "#alert");
$("#alert-title").html(data.title);
$("#alert-message").html(data.message);
// /*
// * suona l'allarme
// */
// my_media = new Media("/android_asset/www/media/alarm.wav",
// // success callback
// function () {
// console.log("play(): Success");
// },
// // error callback
// function (err) {
// console.log("play(): Error: " + JSON.stringify(err));
// }
// );
// my_media.play();
});
push.on('error', function(e) {
console.log(JSON.stringify(e));
});
};
document.addEventListener('deviceready', onDeviceReadyPush, true);