123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912 |
- /*
- * 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));
- /*
- {
- "title": "ciaooo",
- "message": "ciaone",
- "additionalData": {
- "google.message_id": "0:1489146072171053%91acc10daee52ff4",
- "coldstart": false,
- "collapse_key": "ciaooo",
- "foreground": true
- }
- }
- */
- $("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);
|