main.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. ///VARIABILI GLOBALI///
  20. var FONTE = FONTE || {};
  21. FONTE.dbName = "xm24";
  22. FONTE.dbHandler;
  23. FONTE.tagsPageInitiated = false;
  24. FONTE.categoriesList = [8, 497];
  25. FONTE.updatedCategoriesCount;
  26. FONTE.updatedPostsCount;
  27. FONTE.neededPostsCount;
  28. FONTE.hrefseguente = "";
  29. FONTE.ajaxError = false;
  30. /*
  31. * data ultimo aggiornamento
  32. */
  33. function ultimoAggiornamento() {
  34. var lastUpdate = window.localStorage.getItem('db_update_date');
  35. if (lastUpdate) {
  36. var data = lastUpdate.split('T');
  37. var datagiorno = data[0];
  38. var dataora = data[1];
  39. $("#datadiritti").empty();
  40. $("#datadirittiora").empty();
  41. display_results("#datadiritti", datagiorno)
  42. display_results("#datadirittiora", dataora)
  43. if (data) {
  44. $("#boxdata").css("display", "block");
  45. }
  46. } else {
  47. alert('ERRORE, manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.');
  48. }
  49. };
  50. var paginacorrente = "";
  51. function alterContent(url) {
  52. paginacorrente = $("body").pagecontainer("getActivePage").attr("id");
  53. switch (url) {
  54. case '#index':
  55. $("#navheader").addClass("hide");
  56. $("#navfooter").addClass("hide");
  57. break;
  58. case '#ilove':
  59. $("#navheader").removeClass("hide");
  60. $("#navfooter").removeClass("hide");
  61. myJsonCategory(497, "#mostralista");
  62. /* myJsonPage(3452, '#prestitle', '#mostrapres');*/
  63. break;
  64. case '#info':
  65. $("#navheader").removeClass("hide");
  66. $("#navfooter").removeClass("hide");
  67. myJsonCategory(8, "#mostralistainfo");
  68. break;
  69. case '#aggiorna':
  70. $("#navheader").removeClass("hide");
  71. $("#navfooter").removeClass("hide");
  72. // ultimoAggiornamento();
  73. break;
  74. case '#ultime':
  75. case '#tag':
  76. $("#navheader").removeClass("hide");
  77. $("#navfooter").removeClass("hide");
  78. break;
  79. case '#quotidiano':
  80. $("#navheader").removeClass("hide");
  81. $("#navfooter").removeClass("hide");
  82. myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');
  83. break;
  84. };
  85. // Alter the url according to the anchor's href attribute, and
  86. // store the data-foo attribute information with the url
  87. $.mobile.navigate(url);
  88. };
  89. /*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/
  90. function getParameterByName(name, url) {
  91. if (!url) url = window.location.href;
  92. name = name.replace(/[\[\]]/g, "\\$&");
  93. var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)")
  94. , results = regex.exec(url);
  95. if (!results) return null;
  96. if (!results[2]) return '';
  97. return decodeURIComponent(results[2].replace(/\+/g, " "));
  98. }
  99. function display_results(contenitore, messaggio) {
  100. $(contenitore).text(messaggio);
  101. };
  102. $(function () {
  103. $("form").submit(function () {
  104. return false;
  105. });
  106. });
  107. function benvenuta() {
  108. $("#benvenuta").popup("open");
  109. };
  110. function aggiornaora() {
  111. $("#aggiornaora").popup("open");
  112. };
  113. function setFirstRun() {
  114. initStorage();
  115. overlayblock();
  116. if (window.localStorage.getItem('has_run') != 'true') {
  117. //do some stuff if has not loaded before
  118. overlayblock();
  119. benvenuta();
  120. if (checkConnection()) {
  121. partialUpdate();
  122. //window.localStorage.setItem('has_run', 'true');
  123. }
  124. }
  125. };
  126. /*per link in browser di default */
  127. document.addEventListener("deviceready", onDeviceReady, false);
  128. //le cose all'inizio
  129. function onDeviceReady() {
  130. // console.log('deviceready');
  131. createDB();
  132. setFirstRun();
  133. $("#navheader").addClass("hide");
  134. $("#navfooter").addClass("hide");
  135. $("a.nav").on("click", function (event) {
  136. // Prevent the usual navigation behavior
  137. event.preventDefault();
  138. hrefseguente = $(this).attr("href");
  139. alterContent(hrefseguente);
  140. });
  141. };
  142. function overlayblock() {
  143. $(".overlaynero").toggleClass("hide");
  144. }
  145. /*per network info*/
  146. function checkConnection() {
  147. var networkState = navigator.connection.type;
  148. var states = {};
  149. states[Connection.UNKNOWN] = 'Unknown connection';
  150. states[Connection.ETHERNET] = 'Ethernet connection';
  151. states[Connection.WIFI] = 'WiFi connection';
  152. states[Connection.CELL_2G] = 'Cell 2G connection';
  153. states[Connection.CELL_3G] = 'Cell 3G connection';
  154. states[Connection.CELL_4G] = 'Cell 4G connection';
  155. states[Connection.CELL] = 'Cell generic connection';
  156. states[Connection.NONE] = 'No network connection';
  157. if (states[networkState] == 'Unknown connection' || states[networkState] == 'No network connection') {
  158. //alert('Non sei connesso ad internet, connettiti ad una rete per procedere.');
  159. return false
  160. } else {
  161. return true
  162. }
  163. }
  164. /*///////////////fine utilities//////////////*/
  165. var weburl = "http://www.ecn.org/xm24/";
  166. var arrayTag = [];
  167. /*/////finite variabili globali////////*/
  168. function intercettaUrl() {
  169. // LETTURA - Log the results of the navigate event
  170. $(window).on("navigate", function (event, data) {
  171. idPost = getParameterByName('id');
  172. if (idPost != "") {
  173. myJsonPost(idPost, "#titolosingle", "#mostracontentsingle");
  174. }
  175. });
  176. };
  177. function postInList() {
  178. //SCRITTURA
  179. $("body").on('click', '.listevoci li > a', function (event) {
  180. // console.log("HUU_post in list");
  181. var idOra = $(this).attr("data-post");
  182. $("#titolosingle").empty();
  183. $("#mostracontentsingle").empty();
  184. //console.log(idOra);
  185. myJsonPost(idOra, "#titolosingle", "#mostracontentsingle");
  186. // Prevent the usual navigation behavior
  187. event.preventDefault();
  188. /*se serve idTAg, mettiamolo nell'url!! e anche nella page!*/
  189. $("#singleQpost").attr("id", '#singleQpost?id=' + idOra)
  190. $(":mobile-pagecontainer").pagecontainer("load", '#singleQpost' + idOra, {
  191. showLoadMsg: false
  192. });
  193. location.hash = '#singleQpost?id=' + idOra;
  194. });
  195. };
  196. function postInListTag(div) {
  197. $(div).on('click', 'li > a', function () {
  198. var idTag = $(this).attr("data-post");
  199. var titleTag = $(this).html();
  200. $("#tagpostlist").empty();
  201. myJsonPostByTagList(idTag, '#tagpostlist');
  202. $("#tagtitle").empty();
  203. $("#tagtitle").append(titleTag);
  204. // Prevent the usual navigation behavior
  205. event.preventDefault();
  206. $("#posttag").attr("id", '#posttag?idT=' + idTag)
  207. $(":mobile-pagecontainer").pagecontainer("load", '#posttag' + idTag, {
  208. showLoadMsg: false
  209. });
  210. location.hash = '#posttag?idT=' + idTag;
  211. });
  212. };
  213. function initTag(div) {
  214. $.mobile.loading('show');
  215. FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags ORDER BY date COLLATE NOCASE DESC;", [], function (resultSet) {
  216. var items = [];
  217. for (var i = 0; i < resultSet.rows.length; i++) {
  218. var val = JSON.parse(resultSet.rows.item(i).tag);
  219. var name = val.name;
  220. var slug = val.slug;
  221. var id = val.id;
  222. items.push("<li><img src='./image/virgolette_1.png' class='epuntato'/><a href='#posttag' data-post='" + id + "' >" + name + "</a><br/></li>");
  223. }
  224. $(div).empty();
  225. $("<ul/>", {
  226. "class": "my-new-list"
  227. , html: items.join("")
  228. }).prependTo(div);
  229. }, function (error) {
  230. console.log(error);
  231. });
  232. $.mobile.loading('hide');
  233. }
  234. function myJsonPost(Qid, div_title, div_content) {
  235. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ?;", [Qid], function (resultSet) {
  236. for (var i = 0; i < resultSet.rows.length; i++) {
  237. var val = JSON.parse(resultSet.rows.item(i).post);
  238. var id = val.id;
  239. var time = val.modified;
  240. var title = val.title.rendered;
  241. var url = val.guid.rendered;
  242. var content = val.content.rendered;
  243. content = findImg(content);
  244. $(div_title).html(title);
  245. //key mi dice l'indice'
  246. $(div_content).html("<p>" + content + "</p>");
  247. }
  248. }, function (error) {
  249. console.log(error);
  250. });
  251. };
  252. function myJsonPage(Qid, div_title, div_content) {
  253. $.mobile.loading('show');
  254. var pageId = parseInt(Qid);
  255. FONTE.dbHandler.executeSql("SELECT * FROM xm24_pages WHERE id = ?;", [pageId], function (resultSet) {
  256. for (var i = 0; i < resultSet.rows.length; i++) {
  257. var data = resultSet.rows.item(i);
  258. var id = data.id;
  259. var time = data.time;
  260. var title = data.title;
  261. var content = data.page;
  262. content = findImg(content);
  263. $(div_title).html(title);
  264. //key mi dice l'indice'
  265. $(div_content).html("<p>" + content + "</p>");
  266. }
  267. });
  268. $.mobile.loading('hide');
  269. };
  270. function myJsonRandomPost(div_title, div_content) {
  271. $.mobile.loading('show');
  272. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts ORDER BY RANDOM() LIMIT 1;", [], function (resultSet) {
  273. for (var i = 0; i < resultSet.rows.length; i++) {
  274. var val = JSON.parse(resultSet.rows.item(i).post);
  275. var id = val.id;
  276. var time = val.modified;
  277. var title = val.title.rendered;
  278. var url = val.guid.rendered;
  279. var content = val.content.rendered;
  280. content = findImg(content);
  281. $(div_title).html(title);
  282. //key mi dice l'indice'
  283. $(div_content).html("<p>" + content + "</p>");
  284. }
  285. });
  286. $.mobile.loading('hide');
  287. };
  288. function myJsonPostByTagList(idTag, div) {
  289. $.mobile.loading('show');
  290. var tagid = parseInt(idTag);
  291. FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags_to_posts WHERE tagid = ?;", [tagid], function (resultSet) {
  292. var items = [];
  293. var finishCounter = 0;
  294. for (var i = 0; i < resultSet.rows.length; i++) {
  295. var val = resultSet.rows.item(i);
  296. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ? ORDER BY title COLLATE NOCASE ASC;", [val.id], function (resultSetPost) {
  297. finishCounter++;
  298. for (var n = 0; n < resultSetPost.rows.length; n++) {
  299. var val = JSON.parse(resultSetPost.rows.item(n).post);
  300. var id = val.id;
  301. var time = val.modified;
  302. var title = val.title.rendered;
  303. var url = val.guid.rendered;
  304. var splitTime = time.split("T");
  305. var cleanTime = splitTime[0];
  306. //key mi dice l'indice'
  307. items.push({
  308. item: "<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</li>"
  309. , title: title
  310. });
  311. }
  312. // fallo solo quando items è stato riempito
  313. if (finishCounter >= resultSet.rows.length - 1) {
  314. $(div).empty();
  315. $("<ul/>", {
  316. "class": "my-new-list"
  317. , html: function () {
  318. function compare(a, b) {
  319. if (a.title < b.title) return -1;
  320. if (a.title > b.title) return 1;
  321. return 0;
  322. }
  323. items.sort(compare);
  324. var finalHtml = "";
  325. for (var i = 0; i < items.length; i++) {
  326. finalHtml += items[i].item;
  327. }
  328. return finalHtml;
  329. }()
  330. }).prependTo(div);
  331. }
  332. });
  333. }
  334. }, function (error) {
  335. console.log(error);
  336. });
  337. $.mobile.loading('hide');
  338. }
  339. function myJsonCategory(Qcategory, div, addTagCategory) {
  340. $.mobile.loading('show');
  341. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
  342. var items = [];
  343. for (var i = 0; i < resultSet.rows.length; i++) {
  344. var val = JSON.parse(resultSet.rows.item(i).post);
  345. var id = val.id;
  346. var time = val.modified;
  347. var title = val.title.rendered;
  348. var url = val.guid.rendered;
  349. var splitTime = time.split("T");
  350. var cleanTime = splitTime[0];
  351. var tag = '';
  352. var cattag = '';
  353. /* if (addTagCategory) {
  354. $.each(val.tags, function (index, value) {
  355. if (value == 43) {
  356. }
  357. if (value == 36) {
  358. }
  359. });
  360. //key mi dice l'indice'
  361. items.push("<li class='"+ cattag +"'><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|<span>" + tag + "</span>|</li>");
  362. }
  363. else {*/
  364. items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
  365. }
  366. $("<ul/>", {
  367. "class": "my-new-list"
  368. , html: items.join("")
  369. }).prependTo(div);
  370. });
  371. $.mobile.loading('hide');
  372. };
  373. function myJsonLastPage(div) {
  374. var storage = window.localStorage;
  375. var lastnewsDate = storage.getItem('db_lastnews_date');
  376. var firstTime = storage.getItem('db_lastnews_firsttime');
  377. if (firstTime != 'yes') {
  378. if (lastnewsDate) {
  379. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE date > ? ORDER BY date COLLATE NOCASE DESC LIMIT 40;", [lastnewsDate], function (resultSet) {
  380. var items = [];
  381. $(div).empty();
  382. if (resultSet.rows.length > 0) {
  383. for (var i = 0; i < resultSet.rows.length; i++) {
  384. var val = JSON.parse(resultSet.rows.item(i).post);
  385. var id = val.id;
  386. var time = val.modified;
  387. var title = val.title.rendered;
  388. var url = val.guid.rendered;
  389. // console.log(Url);
  390. var splitTime = time.split("T");
  391. var cleanTime = splitTime[0];
  392. //key mi dice l'indice'
  393. items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|");
  394. }
  395. $("<ul/>", {
  396. "class": "my-new-list"
  397. , html: items.join("")
  398. }).prependTo(div);
  399. } else {
  400. $(div).empty();
  401. $(div).append('<span>Non ci sono nuovi contenuti.</span>')
  402. }
  403. });
  404. } else {
  405. $(div).empty();
  406. $(div).append('<span>Tutti i contenuti sono nuovi.</span>')
  407. }
  408. } else {
  409. $(div).empty();
  410. $(div).append('<span>Tutti i contenuti sono nuovi.</span>')
  411. }
  412. };
  413. function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
  414. $.mobile.loading('show');
  415. FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
  416. var items = [];
  417. $(div).empty();
  418. for (var i = 0; i < resultSet.rows.length; i++) {
  419. var val = JSON.parse(resultSet.rows.item(i).post);
  420. var id = val.id;
  421. var time = val.modified;
  422. var title = val.title.rendered;
  423. var url = val.guid.rendered;
  424. var tag = val.tags;
  425. var splitTime = time.split("T");
  426. var cleanTime = splitTime[0];
  427. //key mi dice l'indice'
  428. items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
  429. }
  430. $("<ul/>", {
  431. "class": "my-new-list"
  432. , html: items.join("")
  433. }).prependTo(div);
  434. }, function (error) {
  435. console.log('errore myJsonCategoryPaginated: ' + error);
  436. });
  437. $.mobile.loading('hide');
  438. };
  439. function cercaMe() {
  440. var input_text = $("input.cerca").val();
  441. input_text = encodeURIComponent(input_text);
  442. var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&search=" + input_text + "";
  443. $(".listresult").empty();
  444. $("body").pagecontainer("change", "#ricerca");
  445. $.mobile.loading('show');
  446. var lastUpdate = window.localStorage.getItem('db_update_date');
  447. if (lastUpdate) {
  448. var lastUpdateDate = Date.parse(lastUpdate);
  449. $.ajax({
  450. dataType: "json"
  451. , url: jsonurl
  452. , success: function (data) {
  453. var items = [];
  454. $.each(data, function (key, val) {
  455. var id = val.id;
  456. var time = val.modified;
  457. var title = val.title.rendered;
  458. var url = val.guid.rendered;
  459. var tag = data.tags;
  460. var splitTime = time.split("T");
  461. var cleanTime = splitTime[0];
  462. var dTime = new Date(time);
  463. if (dTime.getTime() <= lastUpdateDate) {
  464. //key mi dice l'indice'
  465. items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
  466. } else {
  467. items.push("<p><a href='#' onclick='aggiornaora();' style='color:#666;' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</p>");
  468. }
  469. });
  470. $("<ul/>", {
  471. "class": "my-new-list"
  472. , html: items.join("")
  473. }).prependTo(".listresult");
  474. $.mobile.loading('hide');
  475. }
  476. , error: JSONErrorHandler
  477. });
  478. } else {
  479. alert('ERR_NOUPDATE');
  480. }
  481. }
  482. function resetAndUpdate() {
  483. var storage = window.localStorage;
  484. //resetto la data e droppo le tabelle
  485. storage.setItem('db_update_date', null);
  486. FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_posts;');
  487. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, category, post)');
  488. partialUpdate();
  489. }
  490. function update() {
  491. FONTE.dbHandler.executeSql('SELECT COUNT(*) AS numPosts FROM xm24_posts', [], function (resultSet) {
  492. var numPosts = resultSet.rows.item(0).numPosts;
  493. if (numPosts < 300) { //questo numero e' scelto in maniera arbitraria, ricordati Cri.
  494. resetAndUpdate()
  495. } else {
  496. partialUpdate();
  497. }
  498. });
  499. }
  500. function partialUpdate() {
  501. //feedback
  502. $("#aggiorna").attr("src", "./image/icona_aggiorna.gif");
  503. var storage = window.localStorage;
  504. var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&categories=";
  505. FONTE.updatedCategoriesCount = 0;
  506. FONTE.updatedPostsCount = 0;
  507. FONTE.neededPostsCount = 0;
  508. for (var index in FONTE.categoriesList) {
  509. aggiornaSingleCategory(FONTE.categoriesList[index])
  510. }
  511. FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_tags;');
  512. // FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_tags_to_posts;');
  513. FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_pages;');
  514. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags (id INTEGER PRIMARY KEY, title, tag)');
  515. // FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags_to_posts (id, tagid)');
  516. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_pages (id INTEGER PRIMARY KEY, title, date, page)');
  517. aggiornaTags(1);
  518. aggiornaPages();
  519. var firstTime = storage.getItem('db_lastnews_firsttime');
  520. if (firstTime == null) storage.setItem('db_lastnews_firsttime', 'yes');
  521. if (firstTime == 'yes') storage.setItem('db_lastnews_firsttime', 'no');
  522. $("#benvenuta").popup("close");
  523. checkloader();
  524. };
  525. function getSinglePageRecur(url, category, pagenum) {
  526. $.ajax({
  527. dataType: "json"
  528. , url: url + "&categories=" + category + "&page=" + pagenum
  529. , success: function (data, textStatus, jqXHR) {
  530. var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
  531. if (pagenum == totalPages || totalPages == 0) FONTE.updatedCategoriesCount += 1;
  532. FONTE.neededPostsCount += data.length;
  533. if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.neededPostsCount == 0) {
  534. alert('Nessun nuovo articolo.');
  535. var date = new Date();
  536. var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
  537. currentUpdate += 'T' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ':' + ('0' + date.getSeconds()).slice(-2);
  538. var lastUpdate = window.localStorage.getItem('db_update_date')
  539. window.localStorage.setItem('db_update_date', currentUpdate);
  540. window.localStorage.setItem('db_lastnews_date', lastUpdate);
  541. //feedback
  542. $("#aggiorna").attr("src", "./image/aggiorna.png");
  543. }
  544. $.each(data, function (key, val) {
  545. var id = val.id;
  546. var time = val.modified;
  547. var title = val.title.rendered;
  548. var tags = val.tags;
  549. var blob = JSON.stringify(val);
  550. FONTE.dbHandler.executeSql('INSERT OR REPLACE INTO xm24_posts VALUES (?,?,?,?,?)', [id, title, time, category, blob], function (resultSet) {
  551. FONTE.updatedPostsCount += 1;
  552. console.log('Voci aggiornate: ' + FONTE.updatedPostsCount);
  553. if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
  554. window.localStorage.setItem('has_run', 'true');
  555. var date = new Date();
  556. var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
  557. currentUpdate += 'T' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ':' + ('0' + date.getSeconds()).slice(-2);
  558. var lastUpdate = window.localStorage.getItem('db_update_date')
  559. window.localStorage.setItem('db_update_date', currentUpdate);
  560. window.localStorage.setItem('db_lastnews_date', lastUpdate);
  561. alert('Aggiornati ' + FONTE.updatedPostsCount + ' articoli.');
  562. //feedback
  563. $("#aggiorna").attr("src", "./image/aggiorna.png");
  564. ultimoAggiornamento();
  565. } //manca il caso in cui sono stati cancellati dei post online, vanno cancellati anche dall'app.
  566. }, function (error) {
  567. FONTE.updatedPostsCount += 1;
  568. if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
  569. alert('Aggiornati ' + FONTE.updatedPostsCount + ' articoli.');
  570. //feedback
  571. $("#aggiorna").attr("src", "./image/aggiorna.png");
  572. }
  573. });
  574. $.each(tags, function (key, val) {
  575. aggiornaTagsToPosts(id, val);
  576. });
  577. });
  578. if (pagenum < totalPages) {
  579. pagenum += 1;
  580. getSinglePageRecur(url, category, pagenum)
  581. }
  582. }
  583. , error: JSONErrorHandler
  584. });
  585. };
  586. function aggiornaSingleCategory(category) {
  587. //resetta la variabile d'errore per le chiamate ajax asincrone
  588. FONTE.ajaxError = false;
  589. var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100";
  590. var storage = window.localStorage;
  591. var lastUpdate = storage.getItem('db_update_date');
  592. if (lastUpdate) jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate;
  593. getSinglePageRecur(jsonurl, category, 1)
  594. };
  595. function checkloader() {
  596. myJsonLastPage('#mostralistaultime');
  597. var mieultime = $("#mostralistaultime").html();
  598. // console.log("ultime" + mieultime);
  599. if (mieultime == "<span>Non ci sono nuovi contenuti.</span>") {
  600. //feedback
  601. $("#aggiorna").attr("src", "./image/aggiorna.png");
  602. ultimoAggiornamento();
  603. return true
  604. //console.log("ultime2");
  605. }
  606. // console.log("ultime3");
  607. return false
  608. }
  609. function aggiornaTagsToPosts(id, tagId) {
  610. FONTE.dbHandler.executeSql('INSERT INTO xm24_tags_to_posts VALUES (?,?)', [id, tagId], function (resultSet) {
  611. console.log('resultSet.insertId: ' + resultSet.insertId);
  612. console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
  613. }, function (error) {
  614. console.log('INSERT error: ' + error.message);
  615. //feedback
  616. $("#aggiorna").attr("src", "./image/aggiorna.png");
  617. });
  618. }
  619. function aggiornaTags(pagenum) {
  620. var jsonurl = weburl + "wp-json/wp/v2/tags?per_page=100&page=" + pagenum;
  621. $.ajax({
  622. dataType: "json"
  623. , url: jsonurl
  624. , success: function (data, status, xhr) {
  625. var totalPages = parseInt(xhr.getResponseHeader("X-WP-TotalPages"));
  626. $.each(data, function (key, val) {
  627. var name = val.name;
  628. var slug = val.slug;
  629. var id = val.id;
  630. var blob = JSON.stringify(val);
  631. FONTE.dbHandler.executeSql('INSERT INTO xm24_tags VALUES (?,?,?)', [id, slug, blob], function (resultSet) {
  632. console.log('resultSet.insertId: ' + resultSet.insertId);
  633. console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
  634. }, function (error) {
  635. console.log('INSERT error: ' + error.message);
  636. });
  637. });
  638. pagenum += 1
  639. if (pagenum <= totalPages) aggiornaTags(pagenum)
  640. }
  641. , error: JSONErrorHandler
  642. });
  643. };
  644. function aggiornaPages() {
  645. var jsonurl = weburl + "wp-json/wp/v2/pages/";
  646. $.ajax({
  647. dataType: "json"
  648. , url: jsonurl
  649. , success: function (data) {
  650. $.each(data, function (key, val) {
  651. var id = val.id;
  652. var time = val.modified;
  653. var title = val.title.rendered;
  654. var content = val.content.rendered;
  655. FONTE.dbHandler.executeSql('INSERT INTO xm24_pages VALUES (?,?,?,?)', [id, title, time, content], function (resultSet) {
  656. console.log('resultSet.insertId: ' + resultSet.insertId);
  657. console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
  658. }, function (error) {
  659. console.log('INSERT error: ' + error.message);
  660. });
  661. });
  662. }
  663. , error: JSONErrorHandler
  664. });
  665. };
  666. function createDB() {
  667. //crea il databse per i posts se non esiste
  668. FONTE.dbHandler = window.sqlitePlugin.openDatabase({
  669. name: FONTE.dbName
  670. , location: 'default'
  671. }, function () {
  672. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, category, post)');
  673. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags (id INTEGER PRIMARY KEY, title, tag)');
  674. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_tags_to_posts (id, tagid)');
  675. FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_pages (id INTEGER PRIMARY KEY, title, date, page)');
  676. }, function () {
  677. console.log('error');
  678. console.log(arguments);
  679. });
  680. };
  681. function deleteDB() {
  682. window.sqlitePlugin.deleteDatabase({
  683. name: FONTE.dbName
  684. , location: 'default'
  685. });
  686. var storage = window.localStorage;
  687. storage.setItem('db_update_date', null);
  688. storage.setItem('db_lastnews_date', null);
  689. createDB();
  690. }
  691. function initTagsPage() {
  692. if (!FONTE.tagsPageInitiated) {
  693. initTag("#mostralistaTag"); // questo mostra i tag
  694. postInListTag("#mostralistaTag"); // questo ti sposta alla specifica lista dei post di un tag
  695. FONTE.tagsPageInitiated = true;
  696. }
  697. }
  698. /* scriversi le cose nel local storage*/
  699. function initStorage() {
  700. try {
  701. return 'localStorage' in window && window['localStorage'] !== null;
  702. } catch (e) {
  703. return false;
  704. }
  705. };
  706. function findImg(htmlString) {
  707. var pos = htmlString.indexOf('<img ');
  708. while (pos != -1) {
  709. pos += 5;
  710. htmlString = [htmlString.slice(0, pos), ' onerror="imgNotFound(this);" ', htmlString.slice(pos)].join('');
  711. pos = htmlString.indexOf('<img ', pos);
  712. }
  713. return htmlString;
  714. };
  715. function imgNotFound(img) {
  716. var parent = $(img).parent();
  717. parent.empty();
  718. parent.append('<span>Immagine disponibile online.</span>')
  719. };
  720. function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
  721. if (!FONTE.ajaxError) {
  722. alert('AAAAAAHHHH ' + textStatus);
  723. FONTE.ajaxError = true;
  724. }
  725. };
  726. function cerca() {
  727. if (checkConnection()) {
  728. cercaMe();
  729. return true;
  730. } else {
  731. alert('ERR_CERCA');
  732. return false;
  733. }
  734. };
  735. function segnalaBug() {
  736. if (checkConnection())
  737. return true;
  738. else {
  739. alert('ERR_SEGNALA');
  740. return false;
  741. }
  742. };
  743. function mostraEsperto() {
  744. if (checkConnection()) {
  745. myJsonPage(2167, '#espertotitle', '#mostraesperto');
  746. return true;
  747. } else {
  748. alert('ERR_ESPERTO');
  749. return false;
  750. }
  751. };
  752. function checkAndUpdate() {
  753. if (checkConnection()) {
  754. update();
  755. return true;
  756. } else {
  757. alert('ERR_UPDATE');
  758. return false;
  759. }
  760. };
  761. function checkAndReset() {
  762. if (checkConnection()) {
  763. resetAndUpdate();
  764. return true;
  765. } else {
  766. alert('ERR_RESET');
  767. return false;
  768. }
  769. };
  770. var my_media = {};
  771. function spengimi() {
  772. my_media.stop();
  773. $("#spegni-musica").hide();
  774. }
  775. function onDeviceReadyPush() {
  776. var push = PushNotification.init({
  777. android: {
  778. senderID: "667898382143"
  779. },
  780. browser: {
  781. pushServiceURL: 'http://push.api.phonegap.com/v1/push'
  782. },
  783. ios: {
  784. alert: "true",
  785. badge: "true",
  786. sound: "true"
  787. },
  788. windows: {}
  789. });
  790. /*
  791. * registra l'id univoco dell'installazione su xm.bus.pm
  792. */
  793. push.on('registration', function(registration) {
  794. console.log(JSON.stringify(registration));
  795. var url = "https://xm.bus.pm/api/d/c?device=" + registration.registrationId;
  796. $.get(url, function( data ) {
  797. console.log(JSON.stringify(data));
  798. });
  799. });
  800. /*
  801. * gestisce la notifica ricevuta
  802. */
  803. push.on('notification', function(data) {
  804. // console.log(JSON.stringify(data));
  805. // alert(JSON.stringify(data));
  806. /*
  807. {
  808. "title": "ciaooo",
  809. "message": "ciaone",
  810. "additionalData": {
  811. "google.message_id": "0:1489146072171053%91acc10daee52ff4",
  812. "coldstart": false,
  813. "collapse_key": "ciaooo",
  814. "foreground": true
  815. }
  816. }
  817. */
  818. $("body").pagecontainer("change", "#alert");
  819. $("#alert-title").html(data.title);
  820. $("#alert-message").html(data.message);
  821. /*
  822. * suona l'allarme
  823. */
  824. my_media = new Media("/android_asset/www/media/alarm.wav",
  825. // success callback
  826. function () {
  827. console.log("play(): Success");
  828. },
  829. // error callback
  830. function (err) {
  831. console.log("play(): Error: " + JSON.stringify(err));
  832. }
  833. );
  834. my_media.play();
  835. });
  836. push.on('error', function(e) {
  837. console.log(JSON.stringify(e));
  838. });
  839. };
  840. document.addEventListener('deviceready', onDeviceReadyPush, true);