Compare commits

...

2 commits

Author SHA1 Message Date
41d21c5eb0 Fix #19. Passato il codice con Jshint 2017-03-25 16:32:18 +01:00
1918f6d643 Spostate altre funzioni in file autonomi 2017-03-25 16:30:49 +01:00
11 changed files with 390 additions and 411 deletions

View file

@ -40,9 +40,10 @@
<!--script src="js/swipe-page.js"></script-->
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/util.js"></script>
<script type="text/javascript" src="js/query.js"></script>
<script type="text/javascript" src="js/update.js"></script>
<script type="text/javascript" src="js/tag.update.js"></script>
<script type="text/javascript" src="js/tag.js"></script>
<script type="text/javascript" src="js/events.js"></script>
<script type="text/javascript" src="js/crud.events.js"></script>
<script type="text/javascript" src="js/push.js"></script>
@ -74,7 +75,11 @@
<!--footer -->
<div data-position="fixed" id="navfooter" data-role="footer" data-theme="b" role="contentinfo" class="hide ui-footer ui-bar-a ui-footer-fixed slideup">
<ul>
<li><a data-rel="back" href="#" data-ajax="false"><h3>INDIETRO</h3></a></li>
<li>
<a data-rel="back" href="#" data-ajax="false">
<h3>INDIETRO</h3>
</a>
</li>
</ul>
</div>
@ -82,9 +87,10 @@
<div data-role="header" data-position="fixed" id="navheader">
<div data-role="navbar" id="nav2" data-iconpos="left" data-theme="a">
<ul class="downnav">
<li><a class="ui-mini" href="#outside" data-icon="bars">
<img src="image/xm-logo.png" class="rwd" />
</a>
<li>
<a class="ui-mini" href="#outside" data-icon="bars">
<img src="image/xm-logo.png" class="rwd" />
</a>
</li>
</ul>
</div>
@ -95,7 +101,7 @@
<div role="main" class="ui-content">
<div class="ui-body">
<p class="introlettera">News</p>
<p id="mostralistainfo" class="listatovirgole listevoci">
<p id="mostralistainfo" class="news listatovirgole listevoci">
<span class="preload">
<i>Non è stato attalmente caricato alcun contenuto</i>
</span>
@ -110,7 +116,7 @@
<div role="main" class="ui-content">
<div class="ui-body">
<p class="introlettera">I love Xm24</p>
<p id="mostralista" class="listatovirgole listevoci">
<p id="mostralistalove" class="news listatovirgole listevoci">
<span class="preload">
<i>Non è stato attalmente caricato alcun contenuto</i>
</span>
@ -121,7 +127,6 @@
</div>
</div><!-- chiude pagina -->
</div>
<div data-role="page" id="events" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
@ -134,51 +139,41 @@
</ul>
</div>
<div id="single" >
<p id="mostralista-34" class="listatovirgole listevoci">
</p>
<p id="mostralista-34" class="listatovirgole listevoci"></p>
</div>
<div id="repeat" >
<p id="mostralista-87" class="listatovirgole listevoci">
</p>
<p id="mostralista-87" class="listatovirgole listevoci"></p>
</div>
</div>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
</div><!--chiude content -->
<div data-role="page" id="about" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
<p class="introlettera">About I love XM24</p>
<p id="mostralistaabout" class="listatovirgole listevoci">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="quotidiano" data-transition="slide" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body"><img onclick='myJsonRandomPost("#titolosingleR", "#mostracontentsingleR");' src="./image/RICARICA.png" style="float:right;width:80px;cursor:pointer;" />
<div class="ui-body">
<img onclick="myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');" src="./image/RICARICA.png" style="float:right;width:80px;cursor:pointer;" />
<p class="introlettera">Un diritto al giorno:</p>
<p id="mostrapostrandom">
<p class="introlettera" id="titolosingleR"></p>
<p id="mostracontentsingleR" class="listatovirgole"><img class="gifloader" src="./image/ajax_loader_red_512.gif" /></p>
<p id="mostracontentsingleR" class="listatovirgole">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p>
</p>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
</div><!--chiude content -->
<div data-role="page" id="singleQpost" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
@ -191,25 +186,20 @@
</p>
<button onclick="shareMeNow('ciao', 'testo', 'http://www.enc.org/xm24')">Text Share</button>
</div>
<!-- chiude body-->
</div>
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="ultime" data-transition="slide" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
<p class="introlettera">ultime novità</p>
<p id="mostralistaultime" class="listatovirgole listevoci">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="tag" data-transition="slide" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
@ -217,15 +207,10 @@
<p id="mostralistaTag" class="listatovirgole">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p>
<script>
// D
</script>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="posttag" data-transition="slide" data-prev="" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
@ -235,41 +220,35 @@
<img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="ricerca" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body">
<p class="introlettera">Risultati della ricerca</p>
<p class="listresult listatovirgole listevoci">
<p class="listresult listatovirgole listevoci"></p>
</div>
<div data-role="popup" id="aggiornaora" data-dismissible="false">
<p>Questa voce è nuova ed è disponibile online. Aggiorna ora gli articoli locali della tua app:</p>
<input type="button" value="OK" onclick='$( "#aggiornaora" ).popup( "close" );update();alterContent("#info")' />
<input type="button" value="OK" onclick="$( '#aggiornaora' ).popup( 'close' );update();alterContent('#info')" />
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
<div data-role="page" id="alert" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content">
<div class="ui-body" style="text-align: center">
<p><img src="image/xm-logo.png" class="rwd" /></p>
<p>
<img src="image/xm-logo.png" class="rwd" />
</p>
<h1 class="introlettera" id="alert-title"></h1>
<h2 id="alert-message"></h2>
</div>
<!-- chiude body-->
</div>
<!--chiude content -->
</div>
<!-- chiude pagina -->
</div><!-- chiude pagina -->
</body>
</html>

View file

@ -3,7 +3,7 @@ var EVENTS = EVENTS || {};
EVENTS.table = {
single : 'xm24_events_single',
repeat : 'xm24_events_repeat',
}
};
EVENTS.dateFormat = {
store : {
@ -14,7 +14,7 @@ EVENTS.dateFormat = {
date: "DD-MM-YYYY",
hour: "HH:mm"
}
}
};
EVENTS.storeDateFormat = EVENTS.dateFormat.store.date + " " + EVENTS.dateFormat.store.hour;
EVENTS.displayDateFormat = EVENTS.dateFormat.display.date + " " + EVENTS.dateFormat.display.hour;
@ -23,7 +23,7 @@ EVENTS.formatDate = function(date, format) {
var mdate = moment(date);
return mdate.isValid() ? mdate.format(format) : "";
}
};
EVENTS.render = function() {
var ret = checkConnection('ERR_EVENT');
@ -34,7 +34,7 @@ EVENTS.render = function() {
EVENTS.loadFromDb('#mostralista-'+ ai1ec.cats.single, ai1ec.cats.single);
EVENTS.loadFromDb('#mostralista-'+ ai1ec.cats.repeat, ai1ec.cats.repeat);
}
}
};
EVENTS.getDataAndLoad = function (type) {
type = type || ai1ec.cats.single;
@ -107,26 +107,26 @@ EVENTS.loadFromDb = function (containerId, type) {
var evFrom = "Da: " + evInitDate;
var evTo = "";
if(evEndDate != "") {
if(evEndDate !== "") {
evTo = "<br/>" + " A: " + evEndDate;
}
var li = "<li>" +
//"<img src='./image/virgolette_1.png' class='epuntato'/>" +
"<a class='event-"+type+"' href='#event' data-post='" + item.id + "' >"
+ item.title +
"<a class='event-"+type+"' href='#event' data-post='" + item.id + "' >" +
item.title +
"</a>" +
"<br/>" +
evFrom +
evTo
evTo +
"</li>";
items.push(li);
}
$(containerId).empty();
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
"class": "my-new-list",
html: items.join("")
}).prependTo(containerId);
$.mobile.loading('hide');
}, function (error) {

View file

@ -9,10 +9,10 @@ var ai1ec = (function(){
var getCleanId = function(uid){
var initChar = uid.indexOf('-'),
endChar = uid.indexOf('@')
endChar = uid.indexOf('@');
return uid.substr(initChar+1, uid.length - uid.substr(endChar -1).length - initChar );
}
};
//Parser di un evento dell'array tornato da getXmlData
API.event = {

View file

@ -20,23 +20,24 @@
var FONTE = FONTE || {};
FONTE.dbName = "xm24";
FONTE.dbHandler;
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.tagsPageInitiated = false;
FONTE.categoriesList = [8, 497];
FONTE.categories = {
ilove : [497,647,590], //ilove, 4mar, solid
info : [8,42,68,3], //ilove, 4mar, solid
}
};
FONTE.page_loaded = {
ilove : 0,
info : 0,
};
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.hrefseguente = "";
FONTE.contentListId = '#mostralistainfo';
FONTE.contentListClass = '.news';
FONTE.ajaxError = false;
/*
* data ultimo aggiornamento
@ -49,15 +50,16 @@ function displayLastUpdateDate() {
var dataora = data[1];
$("#datadiritti").empty();
$("#datadirittiora").empty();
display_results("#datadiritti", datagiorno)
display_results("#datadirittiora", dataora)
display_results("#datadiritti", datagiorno);
display_results("#datadirittiora", dataora);
if (data) {
$("#boxdata").css("display", "block");
}
} else {
toastr.warning('Warn: manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.');
}
};
}
var paginacorrente = "";
function alterContent(url) {
@ -69,19 +71,17 @@ function alterContent(url) {
break;
case '#ilove':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonCategory(497, "#mostralista");
/* myJsonPage(3452, '#prestitle', '#mostrapres');*/
$("#navfooter").addClass("hide");
postsUpdate(FONTE.categories.ilove);
break;
case '#info':
$("#navheader").removeClass("hide");
$("#navfooter").addClass("hide");
myJsonCategory(8, "#mostralistainfo");
postsUpdate(FONTE.categories.info);
break;
case '#events':
$("#navheader").removeClass("hide");
$("#navfooter").addClass("hide");
//$("#navfooter").removeClass("hide");
EVENTS.render();
break;
case '#aggiorna':
@ -99,17 +99,17 @@ function alterContent(url) {
$("#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);
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
@ -117,7 +117,7 @@ function getParameterByName(name, url) {
function display_results(contenitore, messaggio) {
$(contenitore).text(messaggio);
};
}
$(function () {
$("form").submit(function () {
@ -127,7 +127,7 @@ $(function () {
function benvenuta() {
$("#benvenuta").popup("open");
};
}
//function aggiornaora() {
// $("#aggiornaora").popup("open");
@ -137,18 +137,17 @@ function run() {
initStorage();
overlayblock();
if (checkConnection()) {
partialUpdate(FONTE.categories['info']);
postsUpdate(FONTE.categories.info);
} else {
renderLastNews(FONTE.contentListId, FONTE.categories['info']);
renderLastNews(FONTE.contentListClass, FONTE.categories.info);
}
};
}
/*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio
$(document).on("mobileinit", function () {
$("body").pagecontainer({
defaults: true
});
@ -156,13 +155,13 @@ $(document).on("mobileinit", function () {
$(".ui-loader").loader({
defaults: true
});
$("input").button();
});
$(document).on("pagecontainerchange", function () {    
var current = $(".ui-page-active").prop("id");     // Remove active class from nav buttons
if(current == 'info' || current == 'events'){
if(current == 'info' || current == 'ilove' || current == 'events'){
$("#navfooter").addClass("hide");
} else {
$("#navfooter").removeClass("hide");
@ -177,7 +176,6 @@ $(document).on("pagecontainerchange", function () {    
$(this).addClass("ui-btn-active");        
}    
});
});
$(document).on("pagecreate", function () {
@ -197,19 +195,15 @@ var Site = function () {
};
Site.prototype.init = function () {
var self = this;
$(document).ready(function () {
// default page if no hash given
// this changes the hash, so the event is fired
// no need to call self.navigate
window.location.hash = self.homepage;
});
};
// On document ready
$(function () {
// intercettaUrl();
@ -230,35 +224,15 @@ function onDeviceReady() {
// eliminare le due righe:
$("body > [data-role='header']").toolbar();
$("[data-role='navbar']").navbar();
alterContent("#info");
};
//Non uso pageContent per non lanciare 2 volte il recupero dei dati da internet
$("#navheader").removeClass("hide");
$("#navfooter").addClass("hide");
}
function overlayblock() {
$(".overlaynero").toggleClass("hide");
}
/*per network info*/
function checkConnection(code, msgConnect) {
var msgTitle = "Non sei connesso";
msgConnect = msgConnect || "Occore essere connessi per poter ricevere i nuovi articoli";
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') {
toastr.warning(msgConnect, msgTitle);
console.log(code);
return false
} else {
return true
}
}
/*///////////////fine utilities//////////////*/
var weburl = "http://www.ecn.org/xm24/";
@ -268,11 +242,11 @@ function intercettaUrl() {
// LETTURA - Log the results of the navigate event
$(window).on("navigate", function (event, data) {
idPost = getParameterByName('id');
if (idPost != "") {
if (idPost !== "") {
myJsonPost(idPost, "#titolosingle", "#mostracontentsingle");
}
});
};
}
function postInList() {
//SCRITTURA
@ -287,32 +261,14 @@ function postInList() {
// Prevent the usual navigation behavior
event.preventDefault();
/*se serve idTAg, mettiamolo nell'url!! e anche nella page!*/
$("#singleQpost").attr("id", '#singleQpost?id=' + idOra)
$("#singleQpost").attr("id", '#singleQpost?id=' + idOra);
$(":mobile-pagecontainer").pagecontainer("load", '#singleQpost' + idOra, {
showLoadMsg: false
});
$("#navfooter").removeClass("hide");
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 cercaMe() {
var input_text = $("input.cerca").val();
@ -327,9 +283,9 @@ function cercaMe() {
var lastUpdateDate = Date.parse(lastUpdate);
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
dataType: "json",
url: jsonurl,
success: function (data) {
var items = [];
$.each(data, function (key, val) {
var id = val.id;
@ -348,34 +304,18 @@ function cercaMe() {
}
});
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
"class": "my-new-list",
html: items.join("")
}).prependTo(".listresult");
$.mobile.loading('hide');
}
, error: JSONErrorHandler
},
error: JSONErrorHandler
});
} else {
toastr.error('Err: ERR_NOUPDATE');
}
}
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) {
@ -384,13 +324,13 @@ function findImg(htmlString) {
pos = htmlString.indexOf('<img ', pos);
}
return htmlString;
};
}
function imgNotFound(img) {
var parent = $(img).parent();
parent.empty();
parent.append('<span>Immagine disponibile online.</span>')
};
parent.append('<span>Immagine disponibile online.</span>');
}
function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
if (!FONTE.ajaxError) {
@ -401,7 +341,7 @@ function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
toastr.error(errMsg);
FONTE.ajaxError = true;
}
};
}
function cerca() {
var ret = checkConnection('ERR_CERCA');
@ -411,11 +351,11 @@ function cerca() {
}
return ret;
};
}
function segnalaBug() {
return checkConnection('ERR_SEGNALA');
};
}
function mostraEsperto() {
var ret = checkConnection('ERR_ESPERTO');
@ -424,7 +364,7 @@ function mostraEsperto() {
}
return ret;
};
}
function checkAndUpdate() {
var ret = checkConnection('ERR_ESPERTO');
@ -433,7 +373,7 @@ function checkAndUpdate() {
}
return ret;
};
}
function checkAndReset() {
var ret = checkConnection('ERR_ESPERTO');
@ -442,4 +382,4 @@ function checkAndReset() {
}
return ret;
};
}

View file

@ -43,7 +43,7 @@ function onDeviceReadyPush() {
push.on('error', function(e) {
console.log(JSON.stringify(e));
});
};
}
document.addEventListener('deviceready', onDeviceReadyPush, true);

View file

@ -29,12 +29,12 @@ function myJsonCategory(Qcategory, div, addTagCategory) {
}
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
"class": "my-new-list",
html: items.join("")
}).prependTo(div);
});
$.mobile.loading('hide');
};
}
var drawListPost = function(div, resultSet, position) {
var items = [];
@ -52,14 +52,14 @@ var drawListPost = function(div, resultSet, position) {
var ul = $("<ul/>", {
"class": "my-new-list",
html: items.join("")
})
});
if(position == 'append'){
ul.appendTo(div);
} else if(position == 'prepend'){
ul.prependTo(div);
}
}
};
var appendPostList = function(div, resultSet, categories, fallback) {
var type = getObjKey(FONTE.categories, categories);
@ -90,7 +90,7 @@ var prependPostsList = function(div, resultSet, categories, fallback) {
function drawNoPostsFound(div) {
$(div).empty();
$(div).append('<span>Non ci sono nuovi contenuti.</span>')
$(div).append('<span>Non ci sono nuovi contenuti.</span>');
}
function sqlErrHandler(error){
@ -102,7 +102,7 @@ var getCategoryWhere = function(categories) {
for(var i = 0, len = categories.length; i < len; i++) {
var cat = categories[i];
var c = 'catid = '+ cat + ' ';
if(i == 0) {
if(i === 0) {
catsWhere = '(' + c;
} else if(i == len -1) {
catsWhere += 'OR ' + c + ')';
@ -112,13 +112,13 @@ var getCategoryWhere = function(categories) {
}
return catsWhere;
}
};
var POST = POST || {};
POST.sql = {
init: "SELECT * FROM xm24_posts JOIN xm24_cats_to_posts USING(id) WHERE ",
end : "ORDER BY date COLLATE NOCASE DESC LIMIT ?"
}
};
var selectLastNews = function(div, categories) {
var catsWhere = getCategoryWhere(categories);
@ -127,12 +127,13 @@ var selectLastNews = function(div, categories) {
FONTE.dbHandler.executeSql(sql, [REST_PARAMS.max_page], function (resultSet) {
prependPostsList(div, resultSet, categories);
}, sqlErrHandler);
}
};
function renderLastNews(div, categories) {
var storage = window.localStorage;
var lastnewsDate = storage.getItem('db_lastnews_date');
var firstTime = storage.getItem('db_lastnews_firsttime');
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);
@ -149,7 +150,7 @@ function renderLastNews(div, categories) {
} else {
drawNoPostsFound(div);
}
};
}
function renderPrevNews(div, categories, page, callback){
var sql = POST.sql.init + getCategoryWhere(categories) + POST.sql.end + ', ?';
@ -181,23 +182,23 @@ function myJsonLastPage(div) {
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>");
}
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
"class": "my-new-list",
html: items.join("")
}).prependTo(div);
} else {
$(div).empty();
$(div).append('<span>Non ci sono nuovi contenuti.</span>')
$(div).append('<span>Non ci sono nuovi contenuti.</span>');
}
});
} else {
$(div).empty();
$(div).append('<span>Tutti i contenuti sono nuovi.</span>')
$(div).append('<span>Tutti i contenuti sono nuovi.</span>');
}
} else {
$(div).empty();
$(div).append('<span>Tutti i contenuti sono nuovi.</span>')
$(div).append('<span>Tutti i contenuti sono nuovi.</span>');
}
};
}
function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
$.mobile.loading('show');
@ -217,14 +218,14 @@ function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
}
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
"class": "my-new-list",
html: items.join("")
}).prependTo(div);
}, function (error) {
console.log('errore myJsonCategoryPaginated: ' + error);
});
$.mobile.loading('hide');
};
}
function drawPost(div_title, div_content, resultSet){
for (var i = 0; i < resultSet.rows.length; i++) {
@ -275,7 +276,7 @@ function myJsonPost(Qid, div_title, div_content, _class) {
}, function (error) {
console.log(error);
});
};
}
function myJsonPage(Qid, div_title, div_content) {
$.mobile.loading('show');
@ -294,7 +295,7 @@ function myJsonPage(Qid, div_title, div_content) {
}
});
$.mobile.loading('hide');
};
}
function myJsonRandomPost(div_title, div_content) {
$.mobile.loading('show');
@ -313,87 +314,13 @@ function myJsonRandomPost(div_title, div_content) {
}
});
$.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 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 createDB() {
//crea il databse per i posts se non esiste
FONTE.dbHandler = window.sqlitePlugin.openDatabase({
name: FONTE.dbName
, location: 'default'
name: FONTE.dbName,
location: 'default'
}, function () {
FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, post)');
@ -410,7 +337,7 @@ function createDB() {
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) {
@ -425,31 +352,31 @@ function insertOrUpdateCatToPost(id, catId) {
function deleteDB() {
window.sqlitePlugin.deleteDatabase({
name: FONTE.dbName
, location: 'default'
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) {
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;
if (pagenum == totalPages || totalPages === 0) FONTE.updatedCategoriesCount += 1;
FONTE.neededPostsCount += data.length;
if (FONTE.updatedCategoriesCount >= FONTE.categoriesList.length && FONTE.neededPostsCount == 0) {
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')
var lastUpdate = window.localStorage.getItem('db_update_date');
window.localStorage.setItem('db_update_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate);
@ -473,7 +400,7 @@ function getSinglePageRecur(url, category, pagenum) {
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')
var lastUpdate = window.localStorage.getItem('db_update_date');
window.localStorage.setItem('db_update_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate);
@ -498,9 +425,9 @@ function getSinglePageRecur(url, category, pagenum) {
});
if (pagenum < totalPages) {
pagenum += 1;
getSinglePageRecur(url, category, pagenum)
getSinglePageRecur(url, category, pagenum);
}
}
, error: JSONErrorHandler
},
error: JSONErrorHandler
});
};
}

View file

@ -1,20 +1,20 @@
function shareMeNow(message, subject, url) {
// this is the complete list of currently supported params you can pass to the plugin (all optional)
var options = {
message: message || 'share this', // not supported on some apps (Facebook, Instagram)
subject: subject || 'the subject', // fi. for email
//files: ['', ''], // an array of filenames either locally or remotely
url: url || 'https://www.website.com/foo/#bar?a=b',
}
message: message || 'share this', // not supported on some apps (Facebook, Instagram)
subject: subject || 'the subject', // fi. for email
//files: ['', ''], // an array of filenames either locally or remotely
url: url || 'https://www.website.com/foo/#bar?a=b',
};
var onSuccess = function(result) {
console.log("Share completed? " + result.completed); // On Android apps mostly return false even while it's true
console.log("Shared to app: " + result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
}
console.log("Share completed? " + result.completed); // On Android apps mostly return false even while it's true
console.log("Shared to app: " + result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
};
var onError = function(msg) {
console.log("Sharing failed with message: " + msg);
}
console.log("Sharing failed with message: " + msg);
};
window.plugins.socialsharing.shareWithOptions(options, onSuccess, onError);
}

136
www/js/tag.js Normal file
View file

@ -0,0 +1,136 @@
function aggiornaTagsToPosts(id, tagId) {
FONTE.dbHandler.executeSql('INSERT INTO xm24_tags_to_posts VALUES (?,?)', [id, tagId], function (resultSet) {
console.log('resultSet.insertId: ' + resultSet.insertId);
console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function (error) {
console.log('INSERT error: ' + error.message);
//feedback
$("#aggiorna").attr("src", "./image/aggiorna.png");
});
}
function aggiornaTags(pagenum) {
var jsonurl = weburl + "wp-json/wp/v2/tags?per_page=100&page=" + pagenum;
$.ajax({
dataType: "json",
url: jsonurl,
success: function (data, status, xhr) {
var totalPages = parseInt(xhr.getResponseHeader("X-WP-TotalPages"));
$.each(data, function (key, val) {
var name = val.name;
var slug = val.slug;
var id = val.id;
var blob = JSON.stringify(val);
FONTE.dbHandler.executeSql('INSERT INTO xm24_tags VALUES (?,?,?)', [id, slug, blob], function (resultSet) {
console.log('resultSet.insertId: ' + resultSet.insertId);
console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function (error) {
console.log('INSERT error: ' + error.message);
});
});
pagenum += 1;
if (pagenum <= totalPages) aggiornaTags(pagenum);
},
error: JSONErrorHandler
});
}
function myJsonPostByTagList(idTag, div) {
$.mobile.loading('show');
var tagid = parseInt(idTag);
FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags_to_posts WHERE tagid = ?;", [tagid], function (resultSet) {
var items = [];
var finishCounter = 0;
for (var i = 0; i < resultSet.rows.length; i++) {
var val = resultSet.rows.item(i);
FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ? ORDER BY title COLLATE NOCASE ASC;", [val.id], function (resultSetPost) {
finishCounter++;
for (var n = 0; n < resultSetPost.rows.length; n++) {
var val = JSON.parse(resultSetPost.rows.item(n).post);
var id = val.id;
var time = val.modified;
var title = val.title.rendered;
var url = val.guid.rendered;
var splitTime = time.split("T");
var cleanTime = splitTime[0];
//key mi dice l'indice'
items.push({
item: "<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</li>",
title: title
});
}
// fallo solo quando items è stato riempito
if (finishCounter >= resultSet.rows.length - 1) {
$(div).empty();
$("<ul/>", {
"class": "my-new-list",
html: function () {
function compare(a, b) {
if (a.title < b.title) return -1;
if (a.title > b.title) return 1;
return 0;
}
items.sort(compare);
var finalHtml = "";
for (var i = 0; i < items.length; i++) {
finalHtml += items[i].item;
}
return finalHtml;
}()
}).prependTo(div);
}
});
}
}, function (error) {
console.log(error);
});
$.mobile.loading('hide');
}
function initTag(div) {
$.mobile.loading('show');
FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags ORDER BY date COLLATE NOCASE DESC;", [], function (resultSet) {
var items = [];
for (var i = 0; i < resultSet.rows.length; i++) {
var val = JSON.parse(resultSet.rows.item(i).tag);
var name = val.name;
var slug = val.slug;
var id = val.id;
items.push("<li><img src='./image/virgolette_1.png' class='epuntato'/><a href='#posttag' data-post='" + id + "' >" + name + "</a><br/></li>");
}
$(div).empty();
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).prependTo(div);
}, function (error) {
console.log(error);
});
$.mobile.loading('hide');
}
function postInListTag(div) {
$(div).on('click', 'li > a', function () {
var idTag = $(this).attr("data-post");
var titleTag = $(this).html();
$("#tagpostlist").empty();
myJsonPostByTagList(idTag, '#tagpostlist');
$("#tagtitle").empty();
$("#tagtitle").append(titleTag);
// Prevent the usual navigation behavior
event.preventDefault();
$("#posttag").attr("id", '#posttag?idT=' + idTag);
$(":mobile-pagecontainer").pagecontainer("load", '#posttag' + idTag, {
showLoadMsg: false
});
location.hash = '#posttag?idT=' + idTag;
});
}
function initTagsPage() {
if (!FONTE.tagsPageInitiated) {
initTag("#mostralistaTag"); // questo mostra i tag
postInListTag("#mostralistaTag"); // questo ti sposta alla specifica lista dei post di un tag
FONTE.tagsPageInitiated = true;
}
}

View file

@ -1,36 +0,0 @@
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
});
};

View file

@ -5,9 +5,9 @@ REST_PARAMS.per_page = 'per_page=' + REST_PARAMS.max_page;
function aggiornaPages() {
var jsonurl = weburl + "wp-json/wp/v2/pages/";
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
dataType: "json",
url: jsonurl,
success: function (data) {
$.each(data, function (key, val) {
var id = val.id;
var time = val.modified;
@ -20,10 +20,10 @@ function aggiornaPages() {
console.log('INSERT error: ' + error.message);
});
});
}
, error: JSONErrorHandler
},
error: JSONErrorHandler
});
};
}
function aggiornaSingleCategory(category) {
//resetta la variabile d'errore per le chiamate ajax asincrone
@ -35,12 +35,12 @@ function aggiornaSingleCategory(category) {
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)
};
getSinglePageRecur(jsonurl, category, 1);
}
function aggiornaora() {
$("#aggiornaora").popup("open");
};
}
function resetAndUpdate() {
var storage = window.localStorage;
@ -48,34 +48,23 @@ function resetAndUpdate() {
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();
postsUpdate();
}
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()
resetAndUpdate();
} else {
partialUpdate();
postsUpdate();
}
});
}
var getObjKey = function(obj, val){
var key = null;
for(var k in obj){
if(obj[k] == val){
key = k;
break;
}
}
return key;
}
function partialUpdate(categories) {
function postsUpdate(categories) {
var storage = window.localStorage;
var type = getObjKey(FONTE.categories, categories);
var jsonurl = weburl + "wp-json/wp/v2/posts?" + REST_PARAMS.per_page + "&categories=" + categories.join(',');
FONTE.updatedCategoriesCount = 0;
@ -84,29 +73,29 @@ function partialUpdate(categories) {
FONTE.ajaxError = false;
var lastUpdate = storage.getItem('db_update_date');
var lastUpdate = storage.getItem('db_update_' + type + '_date');
if (lastUpdate)
jsonurl += "&after=" + lastUpdate;
//jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate;
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');
var firstTime = storage.getItem('db_last_' + type + '_firsttime');
if (firstTime === null) storage.setItem('db_last_' + type + '_firsttime', 'yes');
if (firstTime == 'yes') storage.setItem('db_last_' + type + '_firsttime', 'no');
getLastSinglePageRecur(jsonurl, 1, categories);
};
}
var updateLocalStorageDate = function(){
var updateLocalStorageDate = function(type){
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')
var lastUpdate = window.localStorage.getItem('db_update_' + type + '_date');
window.localStorage.setItem('db_update_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate);
}
window.localStorage.setItem('db_update_' + type + '_date', currentUpdate);
window.localStorage.setItem('db_last_' + type + '_date', lastUpdate);
};
var getPrevNews = function(div, categories, page) {
var storage = window.localStorage;
@ -122,13 +111,13 @@ var getPrevNews = function(div, categories, page) {
jsonurl += "&before=" + oldest_date;
getPrevSinglePageRecur(jsonurl, 1, FONTE.categories[type]);
}
};
function loadMore(type) {
var categories = FONTE.categories[type];
renderPrevNews(FONTE.contentListId, categories, FONTE.page_loaded[type], function(){
getPrevNews(FONTE.contentListId, categories, FONTE.page_loaded[type])
renderPrevNews(FONTE.contentListClass, categories, FONTE.page_loaded[type], function(){
getPrevNews(FONTE.contentListClass, categories, FONTE.page_loaded[type]);
});
}
@ -137,18 +126,18 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
console.log('url:'+url);
$.ajax({
dataType: "json"
, url: url + "&page=" + pagenum
, success: function (data, textStatus, jqXHR) {
dataType: "json",
url: url + "&page=" + pagenum,
success: function (data, textStatus, jqXHR) {
var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
FONTE.neededPostsCount += data.length;
if (FONTE.neededPostsCount == 0) {
if (FONTE.neededPostsCount === 0) {
toastr.info('Non ci sono altri alticoli da visualizzare in questa sezione');
updateLocalStorageDate();
updateLocalStorageDate(type);
}
var n_error = 0
var n_error = 0;
var oldest_date = window.localStorage.getItem('db_oldest_' + type + '_date');
$.each(data, function (key, val) {
var id = val.id;
@ -162,7 +151,7 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
FONTE.updatedPostsCount++;
oldest_date = time;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
updateLocalStorageDate();
updateLocalStorageDate(type);
window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date);
toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.');
loadMore(type);
@ -170,7 +159,7 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
}, function (error) {
n_error++;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
updateLocalStorageDate();
updateLocalStorageDate(type);
window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date);
toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.');
loadMore(type);
@ -181,31 +170,31 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
insertOrUpdateCatToPost(id, val);
});
});
}
, error: JSONErrorHandler
},
error: JSONErrorHandler
});
};
}
function getLastSinglePageRecur(url, pagenum, categories) {
var type = getObjKey(FONTE.categories, categories);
console.log('url:'+url);
$.ajax({
dataType: "json"
, url: url + "&page=" + pagenum
, success: function (data, textStatus, jqXHR) {
dataType: "json",
url: url + "&page=" + pagenum,
success: function (data, textStatus, jqXHR) {
var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
FONTE.neededPostsCount += data.length;
if (FONTE.neededPostsCount == 0) {
if (FONTE.neededPostsCount === 0) {
toastr.info('Nessun nuovo articolo.');
updateLocalStorageDate();
if(FONTE.page_loaded[type] == 0) {
renderLastNews(FONTE.contentListId, categories);
updateLocalStorageDate(type);
if(FONTE.page_loaded[type] === 0) {
renderLastNews(FONTE.contentListClass, categories);
}
}
var n_error = 0
var n_error = 0;
var oldest_date = window.localStorage.getItem('db_oldest_' + type + '_date');
var older_date = null;
$.each(data, function (key, val) {
@ -221,22 +210,22 @@ function getLastSinglePageRecur(url, pagenum, categories) {
console.log('Voci aggiornate: ' + FONTE.updatedPostsCount);
older_date = time;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
updateLocalStorageDate();
updateLocalStorageDate(type);
if(! oldest_date)
window.localStorage.setItem('db_oldest_' + type + '_date', older_date);
toastr.info('Ci sono ' + FONTE.updatedPostsCount + ' nuovi articoli.');
renderLastNews(FONTE.contentListId, categories);
renderLastNews(FONTE.contentListClass, categories);
} //manca il caso in cui sono stati cancellati dei post online, vanno cancellati anche dall'app.
}, function (error) {
n_error++;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
updateLocalStorageDate();
updateLocalStorageDate(type);
if(! oldest_date)
window.localStorage.setItem('db_oldest_' + type + '_date', older_date);
toastr.info('Aggiornati ' + FONTE.updatedPostsCount + ' nuovi articoli.');
renderLastNews(FONTE.contentListId, categories);
renderLastNews(FONTE.contentListClass, categories);
}
});
@ -248,7 +237,7 @@ function getLastSinglePageRecur(url, pagenum, categories) {
insertOrUpdateCatToPost(id, val);
});
});
}
, error: JSONErrorHandler
},
error: JSONErrorHandler
});
};
}

44
www/js/util.js Normal file
View file

@ -0,0 +1,44 @@
/* scriversi le cose nel local storage*/
function initStorage() {
try {
return 'localStorage' in window && window.localStorage !== null;
} catch (e) {
return false;
}
}
/*per network info*/
function checkConnection(code, msgConnect) {
var msgTitle = "Non sei connesso";
msgConnect = msgConnect || "Occore essere connessi per poter ricevere i nuovi articoli";
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') {
toastr.warning(msgConnect, msgTitle);
console.log(code);
return false;
} else {
return true;
}
}
var getObjKey = function(obj, val) {
var key = null;
for(var k in obj){
if(obj[k] == val){
key = k;
break;
}
}
return key;
};