Merge remote-tracking branch 'origin/master'

This commit is contained in:
halphass 2017-03-26 12:45:17 +02:00
commit f312ff748e
20 changed files with 582 additions and 492 deletions

View file

@ -1,6 +1,8 @@
App per xm, prende i contenuti dal sito e te li salva nel cellulare. App per xm, prende i contenuti dal sito e te li salva nel cellulare.
<img src="http://git.lattuga.net/hacklabbo/Ilovexm24/raw/174939a682216d735bb1aebd89b547e1912318aa/screenshot1.png" style="border:solid 1px black;border-radius:20px;" /> <img src="https://git.lattuga.net/hacklabbo/Ilovexm24/raw/master/screenshot_post.png" style="width:300px;border:solid 1px black;border-radius:20px;" />
<img src="https://git.lattuga.net/hacklabbo/Ilovexm24/raw/master/screenshot_eventi.png" style="width:300px;border:solid 1px black;border-radius:20px;" />
<img src="https://git.lattuga.net/hacklabbo/Ilovexm24/raw/master/screenshot_menu.png" style="width:300px;border:solid 1px black;border-radius:20px;" />
## Environment ## ## Environment ##
@ -51,6 +53,8 @@ http://www.digitigrafo.it/module/1249
## Build del progetto ## ## Build del progetto ##
### Android ###
`cordova platform rm android` `cordova platform rm android`
Per rimuovere la piattaforma vecchie di Android Per rimuovere la piattaforma vecchie di Android
@ -83,6 +87,18 @@ Per installare il plugin sulla rete che non viene installato in automatico
Per lanciare l'emulatore Android con l'applicazione. Per lanciare l'emulatore Android con l'applicazione.
Ovviamente si deve aver configurato il proprio environment correttamente. Ovviamente si deve aver configurato il proprio environment correttamente.
### iOS ###
Installando `phonegap-plugin-push` se si incontra questo errore:
```
Installing "phonegap-plugin-push" for ios
*Failed to install 'phonegap-plugin-push':undefined*
Error: CocoaPods was not found. Please install version 1.0.1 or greater from https://cocoapods.org/
```
Occore installare `CocoaPods` come descritto sulla [documentazione del plugin](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/INSTALLATION.md#ios-details)
## TODO, ISSUE e FEATURE ## ## TODO, ISSUE e FEATURE ##
Usiamo l'[issue tracker](https://git.lattuga.net/hacklabbo/Ilovexm24/issues) non il wiki. Usiamo l'[issue tracker](https://git.lattuga.net/hacklabbo/Ilovexm24/issues) non il wiki.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

BIN
screenshot_eventi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

BIN
screenshot_menu.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

BIN
screenshot_post.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

View file

@ -28,7 +28,7 @@
/* First breakpoint is 48em (768px). 3 column layout. Tiles 250x250 pixels incl. margin at the breakpoint. */ /* First breakpoint is 48em (768px). 3 column layout. Tiles 250x250 pixels incl. margin at the breakpoint. */
body{ body{
background: url("sfondo.jpg") repeat scroll 0 0 rgba(0, 0, 0, 0) !important; /*background: url("sfondo.jpg") repeat scroll 0 0 rgba(0, 0, 0, 0) !important;*/
} }
.ui-overlay-a, .ui-page-theme-a, .ui-page-theme-a .ui-panel-wrapper { .ui-overlay-a, .ui-page-theme-a, .ui-page-theme-a .ui-panel-wrapper {
@ -395,62 +395,65 @@
max-width: 100%; max-width: 100%;
} }
.ombra
{
.ombra {
box-shadow:10px 10px 15px #888; box-shadow:10px 10px 15px #888;
} }
.ui-navbar li:last-child .ui-btn {
color: black !important; .ui-navbar li:last-child .ui-btn {
} color: black !important;
}
.letterlink { .ui-footer li:last-child .ui-btn {
background-color: white; color: white !important;
border-bottom: solid 1px #666; }
box-shadow: 2px 2px 2px 0px #666;
margin-top: -5px;
}
ul.letterlink li { .letterlink {
display: inline-block; background-color: white;
font-size: 2em; border-bottom: solid 1px #666;
text-transform: uppercase; box-shadow: 2px 2px 2px 0px #666;
color: red; margin-top: -5px;
padding: 2px 0.2em; }
}
ul.letterlink li a.ui-link { ul.letterlink li {
color: red !important; display: inline-block;
text-decoration: none; font-size: 2em;
} text-transform: uppercase;
color: red;
padding: 2px 0.2em;
}
.listatovirgole.listevoci ul li a { ul.letterlink li a.ui-link {
text-transform: initial; color: red !important;
font-size: 1.5em !important; text-decoration: none;
color: #000 !important; }
}
.listatovirgole ul li small, .listatovirgole.listevoci ul li a {
.listatovirgole.listevoci ul li small { text-transform: initial;
font-size: 0.8em !important; font-size: 1.4em !important;
} color: #000 !important;
}
.gifloader:nth-child(2) { .listatovirgole ul li small,
display: none; .listatovirgole.listevoci ul li small {
} font-size: 0.8em !important;
}
img.gifloader:nth-child(3) { .gifloader:nth-child(2) {
display: none; display: none;
} }
ul.aindex.downnav.ui-grid-b { img.gifloader:nth-child(3) {
height: 13px; display: none;
} }
.letterlink { ul.aindex.downnav.ui-grid-b {
padding: 0px 1.5em; height: 13px;
} }
.letterlink {
padding: 0px 1.5em;
}
/*paginazione*/ /*paginazione*/
@ -712,7 +715,7 @@ img.minilogo {
font-size: 1.8em; font-size: 1.8em;
text-transform: uppercase; text-transform: uppercase;
color: #c53f33; color: #c53f33;
margin-bottom: 0.4em; margin-bottom: 0.2em;
} }
p.elements{margin:0px 1.5em !important; p.elements{margin:0px 1.5em !important;
padding: 0em; padding: 0em;
@ -1137,17 +1140,22 @@ width: 150px;}
/*contenuto della pagina presentazioni e come si usa*/ /*contenuto della pagina presentazioni e come si usa*/
.ui-content{margin-top: 1em !important;} .ui-content{
margin-top: 0.7em !important;
padding: 0.7em !important;
}
p:has(> img.panel_logo){
margin: 0.9em 0px;
}
.panel_logo { .panel_logo {
height: 20vh;
margin: 0 50% 10%; margin: 0 50% 10%;
transform: translate(-50%, 0); transform: translate(-50%, 0);
-webkit-transform: translate(-50%, 0); -webkit-transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0); -moz-transform: translate(-50%, 0);
} }
/*footer*/ /*footer*/
#navfooter{ /*max-width: 800px; #navfooter{ /*max-width: 800px;
margin: 0 auto -34px;*/ margin: 0 auto -34px;*/
@ -1173,8 +1181,13 @@ width: 150px;}
max-height: 30px; max-height: 30px;
} }
.my-new-list li { hr.post-divider {
border-bottom: 1px solid gray; margin-left: 15%;
width: 70%;
color: #c53f33;
border-style: dashed;
border-width: 1px;
margin-bottom: 2px;
} }
#outside, .ui-body-a, .ui-page-theme-a .ui-body-inherit, html .ui-bar-a .ui-body-inherit, html .ui-body-a .ui-body-inherit, html body .ui-group-theme-a .ui-body-inherit, html .ui-panel-page-container-a { #outside, .ui-body-a, .ui-page-theme-a .ui-body-inherit, html .ui-bar-a .ui-body-inherit, html .ui-body-a .ui-body-inherit, html body .ui-group-theme-a .ui-body-inherit, html .ui-panel-page-container-a {

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View file

@ -40,9 +40,10 @@
<!--script src="js/swipe-page.js"></script--> <!--script src="js/swipe-page.js"></script-->
<script type="text/javascript" src="js/main.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/query.js"></script>
<script type="text/javascript" src="js/update.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/events.js"></script>
<script type="text/javascript" src="js/crud.events.js"></script> <script type="text/javascript" src="js/crud.events.js"></script>
<script type="text/javascript" src="js/push.js"></script> <script type="text/javascript" src="js/push.js"></script>
@ -54,7 +55,7 @@
<body> <body>
<!--panel --> <!--panel -->
<div data-role="panel" data-position="right" id="outside" data-theme="a" data-position-fixed="true" data-display="overlay" data-swipe-close="true"> <div data-role="panel" data-position="right" id="outside" data-theme="a" data-position-fixed="true" data-display="overlay" data-swipe-close="true">
<p><img src="image/ilovexm24_puzzle-300x300.jpg" class="panel_logo" /></p> <p><img src="image/ilovexm24_menu.png" class="panel_logo" /></p>
<ul data-role="listview"> <ul data-role="listview">
<li><a class="nav" href="#info">Home</a></li> <li><a class="nav" href="#info">Home</a></li>
<li><a class="nav" href="#ilove">I love XM24</a></li> <li><a class="nav" href="#ilove">I love XM24</a></li>
@ -74,7 +75,11 @@
<!--footer --> <!--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"> <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> <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> </ul>
</div> </div>
@ -82,9 +87,10 @@
<div data-role="header" data-position="fixed" id="navheader"> <div data-role="header" data-position="fixed" id="navheader">
<div data-role="navbar" id="nav2" data-iconpos="left" data-theme="a"> <div data-role="navbar" id="nav2" data-iconpos="left" data-theme="a">
<ul class="downnav"> <ul class="downnav">
<li><a class="ui-mini" href="#outside" data-icon="bars"> <li>
<img src="image/xm-logo.png" class="rwd" /> <a class="ui-mini" href="#outside" data-icon="bars">
</a> <img src="image/xm-logo.png" class="rwd" />
</a>
</li> </li>
</ul> </ul>
</div> </div>
@ -95,7 +101,7 @@
<div role="main" class="ui-content"> <div role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">News</p> <p class="introlettera">News</p>
<p id="mostralistainfo" class="listatovirgole listevoci"> <p id="mostralistainfo" class="news listatovirgole listevoci">
<span class="preload"> <span class="preload">
<i>Non è stato attalmente caricato alcun contenuto</i> <i>Non è stato attalmente caricato alcun contenuto</i>
</span> </span>
@ -110,7 +116,7 @@
<div role="main" class="ui-content"> <div role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">I love Xm24</p> <p class="introlettera">I love Xm24</p>
<p id="mostralista" class="listatovirgole listevoci"> <p id="mostralistalove" class="news listatovirgole listevoci">
<span class="preload"> <span class="preload">
<i>Non è stato attalmente caricato alcun contenuto</i> <i>Non è stato attalmente caricato alcun contenuto</i>
</span> </span>
@ -121,7 +127,6 @@
</div> </div>
</div><!-- chiude pagina --> </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 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 role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
@ -135,50 +140,80 @@
</div> </div>
<div id="single" > <div id="single" >
<p id="mostralista-34" class="listatovirgole listevoci"> <p id="mostralista-34" class="listatovirgole listevoci">
<i>Non sono stati attalmente caricati eventi.</i>
</p> </p>
</div> </div>
<div id="repeat" > <div id="repeat" >
<p id="mostralista-87" class="listatovirgole listevoci"> <p id="mostralista-87" class="listatovirgole listevoci">
<i>Non sono stati attalmente caricati eventi.</i>
</p> </p>
</div> </div>
</div> </div>
</div> </div>
<!-- chiude body-->
</div> </div>
<!--chiude content --> </div><!--chiude content -->
</div>
<div data-role="page" id="about" data-dom-cache="true" data-theme="a" class="ui-page">
<div data-role="page" id="about" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
<div role="main" class="ui-content"> <div role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">About I love XM24</p> <center>
<p id="mostralistaabout" class="listatovirgole listevoci"> <img src="image/xm-logo.png"/>
<img class="gifloader" src="./image/ajax_loader_red_512.gif" /> </center>
<p class="introlettera">About</p>
<p class="listatovirgole listevoci">
Xm24 è uno spazio pubblico autogestito di Bologna posizionato
da 15 anni nel quartiere popolare Bolognina a pochi passi a
nord della stazione. Quartiere che amiamo e di cui siamo orgogliosi.
</p>
<p class="listatovirgole listevoci">
Il cuore dell'autogestione di Xm24 è l'assemblea pubblica che
avviene ogni martedì. Xm24 organizza, grazie ai suoi collettivi,
numerosi laboratori settimanali completamente gratuiti.
Xm24 non ha mai preso denaro dal comune, per le sue attività
si autofinanzia mediante iniziative culturali, sociali e ludiche.
</p>
<p class="listatovirgole listevoci">
Il 30 dicembre l'amministrazione di Bologna non ha rinnovato
ad Xm24 la convenzione e ha inviato il 25 gennaio un avviso
allo spazio dove lo invita a lasciare lo spazio adducendo
come motivazioni menzogne smentite più volte.
<p class="listatovirgole listevoci">
</p>
La realtà è che il comune di Bologna pensa ad una bolognina
non più popolare ma cuore nevralgico del capitalismo.
<br><br>
Per saperne di più vi rimandiamo agli articoli che potete leggere
sul <a href="http://www.ecn.org/xm24">sito</a> o con questa applicazione.
</p>
<p class="listatovirgole listevoci">
Abbiamo creato questa applicazione per migliorare la nostra
capacità comunicativa, utilizzando i nuovi strumenti
tecnologici, sia per i giorni di routine, ma anche per allertare,
se mai ce ne dovesse essere bisogno, le persone solidali in
caso di emergenza. Grazie!
<br><br>
<b>Noi non ce ne andiamo!</b>
<br><br>
<button id="init-btn" class="nav" href="#info">Avanti</button>
</p> </p>
</div> </div>
<!-- chiude body-->
</div> </div>
<!--chiude content --> </div><!-- chiude pagina -->
</div>
<!-- chiude pagina -->
<!-- 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 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 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 class="introlettera">Un diritto al giorno:</p>
<p id="mostrapostrandom"> <p id="mostrapostrandom">
<p class="introlettera" id="titolosingleR"></p> <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> </div>
<!-- chiude body-->
</div> </div>
<!--chiude content --> </div>--><!--chiude content -->
</div>
<div data-role="page" id="singleQpost" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page"> <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"> <div role="main" class="ui-content">
@ -189,27 +224,21 @@
<i>Non è stato attalmente caricato alcun contenuto</i> <i>Non è stato attalmente caricato alcun contenuto</i>
</span> </span>
</p> </p>
<button onclick="shareMeNow('ciao', 'testo', 'http://www.enc.org/xm24')">Text Share</button>
</div> </div>
<!-- chiude body-->
</div> </div>
</div> </div><!-- chiude pagina -->
<!-- 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 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 role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">ultime novità</p> <p class="introlettera">ultime novità</p>
<p id="mostralistaultime" class="listatovirgole listevoci"> <p id="mostralistaultime" class="listatovirgole listevoci">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" /> <img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p> </p>
</div> </div>
<!-- chiude body-->
</div> </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 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 role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
@ -217,59 +246,48 @@
<p id="mostralistaTag" class="listatovirgole"> <p id="mostralistaTag" class="listatovirgole">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" /> <img class="gifloader" src="./image/ajax_loader_red_512.gif" />
</p> </p>
<script>
// D
</script>
</div> </div>
<!-- chiude body-->
</div> </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 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 role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">TAG:</p> <p class="introlettera">TAG:</p>
<p class="introlettera" id="tagtitle"></p> <p class="introlettera" id="tagtitle"></p>
<p id="tagpostlist" class="listatovirgole listevoci"> <p id="tagpostlist" class="listatovirgole listevoci">
<img class="gifloader" src="./image/ajax_loader_red_512.gif" /> <!-- <img class="gifloader" src="./image/ajax_loader_red_512.gif" /> -->
</p> </p>
</div> </div>
<!-- chiude body-->
</div> </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 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 role="main" class="ui-content">
<div class="ui-body"> <div class="ui-body">
<p class="introlettera">Risultati della ricerca</p> <p class="introlettera">Risultati della ricerca</p>
<p class="listresult listatovirgole listevoci"> <p class="listresult listatovirgole listevoci"></p>
</div> </div>
<div data-role="popup" id="aggiornaora" data-dismissible="false"> <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> <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> </div>
<!-- chiude body-->
</div> </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 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 role="main" class="ui-content">
<div class="ui-body" style="text-align: center"> <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> <h1 class="introlettera" id="alert-title"></h1>
<h2 id="alert-message"></h2> <h2 id="alert-message"></h2>
</div> </div>
<!-- chiude body-->
</div> </div>
<!--chiude content --> </div><!-- chiude pagina -->
</div>
<!-- chiude pagina -->
</body> </body>
</html> </html>

View file

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

View file

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

View file

@ -20,23 +20,24 @@
var FONTE = FONTE || {}; var FONTE = FONTE || {};
FONTE.dbName = "xm24"; FONTE.dbName = "xm24";
FONTE.dbHandler; FONTE.dbHandler;
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.tagsPageInitiated = false; FONTE.tagsPageInitiated = false;
FONTE.categoriesList = [8, 497]; FONTE.categoriesList = [8, 497];
FONTE.categories = { FONTE.categories = {
ilove : [497,647,590], //ilove, 4mar, solid ilove : [497,647,590], //ilove, 4mar, solid
info : [8,42,68,3], //ilove, 4mar, solid info : [8,42,68,3], //ilove, 4mar, solid
} };
FONTE.page_loaded = { FONTE.page_loaded = {
ilove : 0, ilove : 0,
info : 0, info : 0,
}; };
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.hrefseguente = ""; FONTE.hrefseguente = "";
FONTE.contentListId = '#mostralistainfo'; FONTE.contentListId = '#mostralistainfo';
FONTE.contentListClass = '.news';
FONTE.ajaxError = false; FONTE.ajaxError = false;
/* /*
* data ultimo aggiornamento * data ultimo aggiornamento
@ -49,39 +50,46 @@ function displayLastUpdateDate() {
var dataora = data[1]; var dataora = data[1];
$("#datadiritti").empty(); $("#datadiritti").empty();
$("#datadirittiora").empty(); $("#datadirittiora").empty();
display_results("#datadiritti", datagiorno) display_results("#datadiritti", datagiorno);
display_results("#datadirittiora", dataora) display_results("#datadirittiora", dataora);
if (data) { if (data) {
$("#boxdata").css("display", "block"); $("#boxdata").css("display", "block");
} }
} else { } else {
toastr.warning('Warn: manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.'); toastr.warning('Warn: manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.');
} }
}; }
var paginacorrente = "";
function alterContent(url) { function alterContent(url) {
paginacorrente = $("body").pagecontainer("getActivePage").attr("id"); var paginacorrente = $("body").pagecontainer("getActivePage").attr("id");
switch (url) { switch (url) {
case '#index': case '#index':
$("#navheader").addClass("hide"); $("#navheader").addClass("hide");
$("#navfooter").addClass("hide"); $("#navfooter").addClass("hide");
break; break;
case '#about':
$("#navheader").removeClass("hide");
$("#navfooter").addClass("hide");
if(window.localStorage.getItem('app_firsttime') === "false") {
$("#init-btn").addClass("hide");
} else {
window.localStorage.setItem('app_firsttime', false);
}
break;
case '#ilove': case '#ilove':
$("#navheader").removeClass("hide"); $("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide"); $("#navfooter").addClass("hide");
myJsonCategory(497, "#mostralista"); postsUpdate(FONTE.categories.ilove);
/* myJsonPage(3452, '#prestitle', '#mostrapres');*/
break; break;
case '#info': case '#info':
$("#navheader").removeClass("hide"); $("#navheader").removeClass("hide");
$("#navfooter").addClass("hide"); $("#navfooter").addClass("hide");
myJsonCategory(8, "#mostralistainfo"); postsUpdate(FONTE.categories.info);
break; break;
case '#events': case '#events':
$("#navheader").removeClass("hide"); $("#navheader").removeClass("hide");
$("#navfooter").addClass("hide"); $("#navfooter").addClass("hide");
//$("#navfooter").removeClass("hide");
EVENTS.render(); EVENTS.render();
break; break;
case '#aggiorna': case '#aggiorna':
@ -99,17 +107,17 @@ function alterContent(url) {
$("#navfooter").removeClass("hide"); $("#navfooter").removeClass("hide");
myJsonRandomPost('#titolosingleR', '#mostracontentsingleR'); myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');
break; break;
}; }
// Alter the url according to the anchor's href attribute, and // Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url // store the data-foo attribute information with the url
$.mobile.navigate(url); $.mobile.navigate(url);
}; }
/*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/ /*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/
function getParameterByName(name, url) { function getParameterByName(name, url) {
if (!url) url = window.location.href; if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&"); name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)") var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
, results = regex.exec(url); results = regex.exec(url);
if (!results) return null; if (!results) return null;
if (!results[2]) return ''; if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " ")); return decodeURIComponent(results[2].replace(/\+/g, " "));
@ -117,7 +125,7 @@ function getParameterByName(name, url) {
function display_results(contenitore, messaggio) { function display_results(contenitore, messaggio) {
$(contenitore).text(messaggio); $(contenitore).text(messaggio);
}; }
$(function () { $(function () {
$("form").submit(function () { $("form").submit(function () {
@ -127,28 +135,25 @@ $(function () {
function benvenuta() { function benvenuta() {
$("#benvenuta").popup("open"); $("#benvenuta").popup("open");
}; }
//function aggiornaora() { //function aggiornaora() {
// $("#aggiornaora").popup("open"); // $("#aggiornaora").popup("open");
//}; //};
function run() { function initMainPage() {
initStorage();
overlayblock();
if (checkConnection()) { if (checkConnection()) {
partialUpdate(FONTE.categories['info']); postsUpdate(FONTE.categories.info);
} else { } else {
renderLastNews(FONTE.contentListId, FONTE.categories['info']); renderLastNews(FONTE.contentListClass, FONTE.categories.info);
} }
}; }
/*per link in browser di default */ /*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false); document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio //le cose all'inizio
$(document).on("mobileinit", function () { $(document).on("mobileinit", function () {
$("body").pagecontainer({ $("body").pagecontainer({
defaults: true defaults: true
}); });
@ -156,13 +161,13 @@ $(document).on("mobileinit", function () {
$(".ui-loader").loader({ $(".ui-loader").loader({
defaults: true defaults: true
}); });
$("input").button(); $("input").button();
}); });
$(document).on("pagecontainerchange", function () {     $(document).on("pagecontainerchange", function () {
var current = $(".ui-page-active").prop("id");     // Remove active class from nav buttons var current = $(".ui-page-active").prop("id");     // Remove active class from nav buttons
if(current == 'info' || current == 'events'){ if(current == 'about' || current == 'info' || current == 'ilove' || current == 'events'){
$("#navfooter").addClass("hide"); $("#navfooter").addClass("hide");
} else { } else {
$("#navfooter").removeClass("hide"); $("#navfooter").removeClass("hide");
@ -177,7 +182,6 @@ $(document).on("pagecontainerchange", function () {    
$(this).addClass("ui-btn-active");         $(this).addClass("ui-btn-active");        
}     }    
}); });
}); });
$(document).on("pagecreate", function () { $(document).on("pagecreate", function () {
@ -197,19 +201,15 @@ var Site = function () {
}; };
Site.prototype.init = function () { Site.prototype.init = function () {
var self = this; var self = this;
$(document).ready(function () { $(document).ready(function () {
// default page if no hash given // default page if no hash given
// this changes the hash, so the event is fired // this changes the hash, so the event is fired
// no need to call self.navigate // no need to call self.navigate
window.location.hash = self.homepage; window.location.hash = self.homepage;
}); });
}; };
// On document ready // On document ready
$(function () { $(function () {
// intercettaUrl(); // intercettaUrl();
@ -220,45 +220,36 @@ $(function () {
function onDeviceReady() { function onDeviceReady() {
// console.log('deviceready'); // console.log('deviceready');
createDB(); createDB();
run(); initStorage();
if(window.localStorage.getItem('app_firsttime') !== "false") {
alterContent('#about');
} else {
initMainPage();
}
overlayblock();
$("a.nav").on("click", function (event) { $("a.nav").on("click", function (event) {
// Prevent the usual navigation behavior // Prevent the usual navigation behavior
event.preventDefault(); event.preventDefault();
hrefseguente = $(this).attr("href"); alterContent($(this).attr("href"));
alterContent(hrefseguente); });
$("button.nav").on("click", function (event) {
alterContent($(this).attr("href"));
}); });
// eliminare le due righe: // eliminare le due righe:
$("body > [data-role='header']").toolbar(); $("body > [data-role='header']").toolbar();
$("[data-role='navbar']").navbar(); $("[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() { function overlayblock() {
$(".overlaynero").toggleClass("hide"); $(".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//////////////*/ /*///////////////fine utilities//////////////*/
var weburl = "http://www.ecn.org/xm24/"; var weburl = "http://www.ecn.org/xm24/";
@ -268,11 +259,11 @@ function intercettaUrl() {
// LETTURA - Log the results of the navigate event // LETTURA - Log the results of the navigate event
$(window).on("navigate", function (event, data) { $(window).on("navigate", function (event, data) {
idPost = getParameterByName('id'); idPost = getParameterByName('id');
if (idPost != "") { if (idPost !== "") {
myJsonPost(idPost, "#titolosingle", "#mostracontentsingle"); myJsonPost(idPost, "#titolosingle", "#mostracontentsingle");
} }
}); });
}; }
function postInList() { function postInList() {
//SCRITTURA //SCRITTURA
@ -287,32 +278,14 @@ function postInList() {
// Prevent the usual navigation behavior // Prevent the usual navigation behavior
event.preventDefault(); event.preventDefault();
/*se serve idTAg, mettiamolo nell'url!! e anche nella page!*/ /*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, { $(":mobile-pagecontainer").pagecontainer("load", '#singleQpost' + idOra, {
showLoadMsg: false showLoadMsg: false
}); });
$("#navfooter").removeClass("hide"); $("#navfooter").removeClass("hide");
location.hash = '#singleQpost?id=' + idOra; 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() { function cercaMe() {
var input_text = $("input.cerca").val(); var input_text = $("input.cerca").val();
@ -327,9 +300,9 @@ function cercaMe() {
var lastUpdateDate = Date.parse(lastUpdate); var lastUpdateDate = Date.parse(lastUpdate);
$.ajax({ $.ajax({
dataType: "json" dataType: "json",
, url: jsonurl url: jsonurl,
, success: function (data) { success: function (data) {
var items = []; var items = [];
$.each(data, function (key, val) { $.each(data, function (key, val) {
var id = val.id; var id = val.id;
@ -348,34 +321,18 @@ function cercaMe() {
} }
}); });
$("<ul/>", { $("<ul/>", {
"class": "my-new-list" "class": "my-new-list",
, html: items.join("") html: items.join("")
}).prependTo(".listresult"); }).prependTo(".listresult");
$.mobile.loading('hide'); $.mobile.loading('hide');
} },
, error: JSONErrorHandler error: JSONErrorHandler
}); });
} else { } else {
toastr.error('Err: ERR_NOUPDATE'); 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) { function findImg(htmlString) {
var pos = htmlString.indexOf('<img '); var pos = htmlString.indexOf('<img ');
while (pos != -1) { while (pos != -1) {
@ -384,13 +341,13 @@ function findImg(htmlString) {
pos = htmlString.indexOf('<img ', pos); pos = htmlString.indexOf('<img ', pos);
} }
return htmlString; return htmlString;
}; }
function imgNotFound(img) { function imgNotFound(img) {
var parent = $(img).parent(); var parent = $(img).parent();
parent.empty(); parent.empty();
parent.append('<span>Immagine disponibile online.</span>') parent.append('<span>Immagine disponibile online.</span>');
}; }
function JSONErrorHandler(jqXHR, textStatus, errorThrown) { function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
if (!FONTE.ajaxError) { if (!FONTE.ajaxError) {
@ -401,7 +358,7 @@ function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
toastr.error(errMsg); toastr.error(errMsg);
FONTE.ajaxError = true; FONTE.ajaxError = true;
} }
}; }
function cerca() { function cerca() {
var ret = checkConnection('ERR_CERCA'); var ret = checkConnection('ERR_CERCA');
@ -411,11 +368,11 @@ function cerca() {
} }
return ret; return ret;
}; }
function segnalaBug() { function segnalaBug() {
return checkConnection('ERR_SEGNALA'); return checkConnection('ERR_SEGNALA');
}; }
function mostraEsperto() { function mostraEsperto() {
var ret = checkConnection('ERR_ESPERTO'); var ret = checkConnection('ERR_ESPERTO');
@ -424,7 +381,7 @@ function mostraEsperto() {
} }
return ret; return ret;
}; }
function checkAndUpdate() { function checkAndUpdate() {
var ret = checkConnection('ERR_ESPERTO'); var ret = checkConnection('ERR_ESPERTO');
@ -433,7 +390,7 @@ function checkAndUpdate() {
} }
return ret; return ret;
}; }
function checkAndReset() { function checkAndReset() {
var ret = checkConnection('ERR_ESPERTO'); var ret = checkConnection('ERR_ESPERTO');
@ -442,4 +399,4 @@ function checkAndReset() {
} }
return ret; return ret;
}; }

View file

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

View file

@ -29,37 +29,45 @@ function myJsonCategory(Qcategory, div, addTagCategory) {
} }
$("<ul/>", { $("<ul/>", {
"class": "my-new-list" "class": "my-new-list",
, html: items.join("") html: items.join("")
}).prependTo(div); }).prependTo(div);
}); });
$.mobile.loading('hide'); $.mobile.loading('hide');
}; }
var drawListPost = function(div, resultSet, position) { var drawListPost = function(div, resultSet, position) {
var items = []; var items = [];
for (var i = 0; i < resultSet.rows.length; i++) { for (var i = 0; i < resultSet.rows.length; i++) {
var val = JSON.parse(resultSet.rows.item(i).post); var val = JSON.parse(resultSet.rows.item(i).post);
var id = val.id; var id = val.id;
var date = val.modified; var date = val.date;
var title = val.title.rendered; var title = val.title.rendered;
var url = val.guid.rendered; var url = val.guid.rendered;
var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date); var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
//key mi dice l'indice'
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>"); var li = "<li>"+
"<a href='#singleQpost' data-post='" + id + "'>" +
title +
"</a>"+
"<br/>"+
"<small>" + cleanTime + "</small>"+
"<hr class='post-divider'>"+
"</li>";
items.push(li);
} }
var ul = $("<ul/>", { var ul = $("<ul/>", {
"class": "my-new-list",
html: items.join("") html: items.join("")
}) });
if(position == 'append'){ if(position == 'append'){
ul.appendTo(div); ul.appendTo(div);
} else if(position == 'prepend'){ } else if(position == 'prepend'){
ul.prependTo(div); ul.prependTo(div);
} }
} };
var appendPostList = function(div, resultSet, categories, fallback) { var appendPostList = function(div, resultSet, categories, fallback) {
var type = getObjKey(FONTE.categories, categories); var type = getObjKey(FONTE.categories, categories);
@ -90,7 +98,7 @@ var prependPostsList = function(div, resultSet, categories, fallback) {
function drawNoPostsFound(div) { function drawNoPostsFound(div) {
$(div).empty(); $(div).empty();
$(div).append('<span>Non ci sono nuovi contenuti.</span>') $(div).append('<span>Non ci sono nuovi contenuti.</span>');
} }
function sqlErrHandler(error){ function sqlErrHandler(error){
@ -102,7 +110,7 @@ var getCategoryWhere = function(categories) {
for(var i = 0, len = categories.length; i < len; i++) { for(var i = 0, len = categories.length; i < len; i++) {
var cat = categories[i]; var cat = categories[i];
var c = 'catid = '+ cat + ' '; var c = 'catid = '+ cat + ' ';
if(i == 0) { if(i === 0) {
catsWhere = '(' + c; catsWhere = '(' + c;
} else if(i == len -1) { } else if(i == len -1) {
catsWhere += 'OR ' + c + ')'; catsWhere += 'OR ' + c + ')';
@ -112,13 +120,13 @@ var getCategoryWhere = function(categories) {
} }
return catsWhere; return catsWhere;
} };
var POST = POST || {}; var POST = POST || {};
POST.sql = { POST.sql = {
init: "SELECT * FROM xm24_posts JOIN xm24_cats_to_posts USING(id) WHERE ", init: "SELECT * FROM xm24_posts JOIN xm24_cats_to_posts USING(id) WHERE ",
end : "ORDER BY date COLLATE NOCASE DESC LIMIT ?" end : "ORDER BY date COLLATE NOCASE DESC LIMIT ?"
} };
var selectLastNews = function(div, categories) { var selectLastNews = function(div, categories) {
var catsWhere = getCategoryWhere(categories); var catsWhere = getCategoryWhere(categories);
@ -127,12 +135,13 @@ var selectLastNews = function(div, categories) {
FONTE.dbHandler.executeSql(sql, [REST_PARAMS.max_page], function (resultSet) { FONTE.dbHandler.executeSql(sql, [REST_PARAMS.max_page], function (resultSet) {
prependPostsList(div, resultSet, categories); prependPostsList(div, resultSet, categories);
}, sqlErrHandler); }, sqlErrHandler);
} };
function renderLastNews(div, categories) { function renderLastNews(div, categories) {
var storage = window.localStorage; var storage = window.localStorage;
var lastnewsDate = storage.getItem('db_lastnews_date'); var type = getObjKey(FONTE.categories, categories);
var firstTime = storage.getItem('db_lastnews_firsttime'); var lastnewsDate = storage.getItem('db_last_' + type + '_date');
var firstTime = storage.getItem('db_last_' + type + '_firsttime');
if (firstTime == 'yes') { if (firstTime == 'yes') {
selectLastNews(div, categories); selectLastNews(div, categories);
@ -149,7 +158,7 @@ function renderLastNews(div, categories) {
} else { } else {
drawNoPostsFound(div); drawNoPostsFound(div);
} }
}; }
function renderPrevNews(div, categories, page, callback){ function renderPrevNews(div, categories, page, callback){
var sql = POST.sql.init + getCategoryWhere(categories) + POST.sql.end + ', ?'; var sql = POST.sql.init + getCategoryWhere(categories) + POST.sql.end + ', ?';
@ -181,23 +190,23 @@ function myJsonLastPage(div) {
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>"); items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>");
} }
$("<ul/>", { $("<ul/>", {
"class": "my-new-list" "class": "my-new-list",
, html: items.join("") html: items.join("")
}).prependTo(div); }).prependTo(div);
} else { } else {
$(div).empty(); $(div).empty();
$(div).append('<span>Non ci sono nuovi contenuti.</span>') $(div).append('<span>Non ci sono nuovi contenuti.</span>');
} }
}); });
} else { } else {
$(div).empty(); $(div).empty();
$(div).append('<span>Tutti i contenuti sono nuovi.</span>') $(div).append('<span>Tutti i contenuti sono nuovi.</span>');
} }
} else { } else {
$(div).empty(); $(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) { function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
$.mobile.loading('show'); $.mobile.loading('show');
@ -217,28 +226,38 @@ function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>"); items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
} }
$("<ul/>", { $("<ul/>", {
"class": "my-new-list" "class": "my-new-list",
, html: items.join("") html: items.join("")
}).prependTo(div); }).prependTo(div);
}, function (error) { }, function (error) {
console.log('errore myJsonCategoryPaginated: ' + error); console.log('errore myJsonCategoryPaginated: ' + error);
}); });
$.mobile.loading('hide'); $.mobile.loading('hide');
}; }
function drawPost(div_title, div_content, resultSet){ function drawPost(div_title, div_content, resultSet){
for (var i = 0; i < resultSet.rows.length; i++) { for (var i = 0; i < resultSet.rows.length; i++) {
var val = JSON.parse(resultSet.rows.item(i).post); var val = JSON.parse(resultSet.rows.item(i).post);
var id = val.id; var id = val.id;
var time = val.modified; var time = val.date;
var title = val.title.rendered; var title = val.title.rendered;
var url = val.guid.rendered; var url = val.guid.rendered;
var content = val.content.rendered; var content = val.content.rendered;
var tags = val.tags;
content = findImg(content); content = findImg(content);
$(div_title).html(title); $(div_title).html(title);
//key mi dice l'indice'
var shareButton = $('<button>', {
class : "share-btn ui-btn ui-shadow ui-corner-all",
text: "Condividi"
}).click(function(){
shareMeNow(title, '',url);
});
$('.share-btn').remove();
$(div_content).html("<p>" + content + "</p>"); $(div_content).html("<p>" + content + "</p>");
$(div_content).after(shareButton);
} }
} }
@ -255,8 +274,17 @@ function drawEvent(div_title, div_content, resultSet){
var geo = val.geo; var geo = val.geo;
$(div_title).html(title); $(div_title).html(title);
//key mi dice l'indice'
$(div_content).html("<p>" + content + "</p>"); var shareButton = $('<button>', {
class : "share-btn ui-btn ui-shadow ui-corner-all",
text: "Condividi"
}).click(function(){
shareMeNow(title, evInitDate + " "+ evEndDate, url);
});
$('.share-btn').remove();
$(div_content).html("<small>" + evInitDate +"-" + evEndDate +"</small><p>" + content + "</p>");
$(div_content).after(shareButton);
} }
} }
@ -275,7 +303,7 @@ function myJsonPost(Qid, div_title, div_content, _class) {
}, function (error) { }, function (error) {
console.log(error); console.log(error);
}); });
}; }
function myJsonPage(Qid, div_title, div_content) { function myJsonPage(Qid, div_title, div_content) {
$.mobile.loading('show'); $.mobile.loading('show');
@ -294,7 +322,7 @@ function myJsonPage(Qid, div_title, div_content) {
} }
}); });
$.mobile.loading('hide'); $.mobile.loading('hide');
}; }
function myJsonRandomPost(div_title, div_content) { function myJsonRandomPost(div_title, div_content) {
$.mobile.loading('show'); $.mobile.loading('show');
@ -313,87 +341,13 @@ function myJsonRandomPost(div_title, div_content) {
} }
}); });
$.mobile.loading('hide'); $.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() { function createDB() {
//crea il databse per i posts se non esiste //crea il databse per i posts se non esiste
FONTE.dbHandler = window.sqlitePlugin.openDatabase({ FONTE.dbHandler = window.sqlitePlugin.openDatabase({
name: FONTE.dbName name: FONTE.dbName,
, location: 'default' location: 'default'
}, function () { }, function () {
FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, post)'); FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, post)');
@ -410,7 +364,7 @@ function createDB() {
console.log('error'); console.log('error');
console.log(arguments); console.log(arguments);
}); });
}; }
function insertOrUpdateCatToPost(id, catId) { function insertOrUpdateCatToPost(id, catId) {
FONTE.dbHandler.executeSql('INSERT OR REPLACE INTO xm24_cats_to_posts VALUES (?,?)', [id, catId], function (resultSet) { FONTE.dbHandler.executeSql('INSERT OR REPLACE INTO xm24_cats_to_posts VALUES (?,?)', [id, catId], function (resultSet) {
@ -425,31 +379,31 @@ function insertOrUpdateCatToPost(id, catId) {
function deleteDB() { function deleteDB() {
window.sqlitePlugin.deleteDatabase({ window.sqlitePlugin.deleteDatabase({
name: FONTE.dbName name: FONTE.dbName,
, location: 'default' location: 'default'
}); });
var storage = window.localStorage; var storage = window.localStorage;
storage.setItem('db_update_date', null); storage.setItem('db_update_date', null);
storage.setItem('db_lastnews_date', null); storage.setItem('db_lastnews_date', null);
createDB(); createDB();
}; }
function getSinglePageRecur(url, category, pagenum) { function getSinglePageRecur(url, category, pagenum) {
$.ajax({ $.ajax({
dataType: "json" dataType: "json",
, url: url + "&categories=" + category + "&page=" + pagenum url: url + "&categories=" + category + "&page=" + pagenum,
, success: function (data, textStatus, jqXHR) { success: function (data, textStatus, jqXHR) {
var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages'); 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; 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.'); toastr.info('Nessun nuovo articolo.');
var date = new Date(); var date = new Date();
var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2); 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); 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_update_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate); window.localStorage.setItem('db_lastnews_date', lastUpdate);
@ -459,7 +413,7 @@ function getSinglePageRecur(url, category, pagenum) {
} }
$.each(data, function (key, val) { $.each(data, function (key, val) {
var id = val.id; var id = val.id;
var time = val.modified; var time = val.date;
var title = val.title.rendered; var title = val.title.rendered;
var tags = val.tags; var tags = val.tags;
var blob = JSON.stringify(val); var blob = JSON.stringify(val);
@ -473,7 +427,7 @@ function getSinglePageRecur(url, category, pagenum) {
var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2); 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); 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_update_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate); window.localStorage.setItem('db_lastnews_date', lastUpdate);
@ -498,9 +452,9 @@ function getSinglePageRecur(url, category, pagenum) {
}); });
if (pagenum < totalPages) { if (pagenum < totalPages) {
pagenum += 1; 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) { function shareMeNow(message, subject, url) {
// this is the complete list of currently supported params you can pass to the plugin (all optional) // this is the complete list of currently supported params you can pass to the plugin (all optional)
var options = { var options = {
message: message || 'share this', // not supported on some apps (Facebook, Instagram) message: message || '', // not supported on some apps (Facebook, Instagram)
subject: subject || 'the subject', // fi. for email subject: subject || 'Share this:', // fi. for email
//files: ['', ''], // an array of filenames either locally or remotely //files: ['', ''], // an array of filenames either locally or remotely
url: url || 'https://www.website.com/foo/#bar?a=b', url: url || 'https://www.ecn.org/xm24',
} };
var onSuccess = function(result) { var onSuccess = function(result) {
console.log("Share completed? " + result.completed); // On Android apps mostly return false even while it's true 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("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) { 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); 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() { function aggiornaPages() {
var jsonurl = weburl + "wp-json/wp/v2/pages/"; var jsonurl = weburl + "wp-json/wp/v2/pages/";
$.ajax({ $.ajax({
dataType: "json" dataType: "json",
, url: jsonurl url: jsonurl,
, success: function (data) { success: function (data) {
$.each(data, function (key, val) { $.each(data, function (key, val) {
var id = val.id; var id = val.id;
var time = val.modified; var time = val.modified;
@ -20,10 +20,10 @@ function aggiornaPages() {
console.log('INSERT error: ' + error.message); console.log('INSERT error: ' + error.message);
}); });
}); });
} },
, error: JSONErrorHandler error: JSONErrorHandler
}); });
}; }
function aggiornaSingleCategory(category) { function aggiornaSingleCategory(category) {
//resetta la variabile d'errore per le chiamate ajax asincrone //resetta la variabile d'errore per le chiamate ajax asincrone
@ -35,12 +35,12 @@ function aggiornaSingleCategory(category) {
var lastUpdate = storage.getItem('db_update_date'); var lastUpdate = storage.getItem('db_update_date');
if (lastUpdate) jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate; 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() { function aggiornaora() {
$("#aggiornaora").popup("open"); $("#aggiornaora").popup("open");
}; }
function resetAndUpdate() { function resetAndUpdate() {
var storage = window.localStorage; var storage = window.localStorage;
@ -48,34 +48,23 @@ function resetAndUpdate() {
storage.setItem('db_update_date', null); storage.setItem('db_update_date', null);
FONTE.dbHandler.executeSql('DROP TABLE IF EXISTS xm24_posts;'); 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)'); FONTE.dbHandler.executeSql('CREATE TABLE IF NOT EXISTS xm24_posts (id INTEGER PRIMARY KEY, title, date, category, post)');
partialUpdate(); postsUpdate();
} }
function update() { function update() {
FONTE.dbHandler.executeSql('SELECT COUNT(*) AS numPosts FROM xm24_posts', [], function (resultSet) { FONTE.dbHandler.executeSql('SELECT COUNT(*) AS numPosts FROM xm24_posts', [], function (resultSet) {
var numPosts = resultSet.rows.item(0).numPosts; var numPosts = resultSet.rows.item(0).numPosts;
if (numPosts < 300) { //questo numero e' scelto in maniera arbitraria, ricordati Cri. if (numPosts < 300) { //questo numero e' scelto in maniera arbitraria, ricordati Cri.
resetAndUpdate() resetAndUpdate();
} else { } else {
partialUpdate(); postsUpdate();
} }
}); });
} }
var getObjKey = function(obj, val){ function postsUpdate(categories) {
var key = null;
for(var k in obj){
if(obj[k] == val){
key = k;
break;
}
}
return key;
}
function partialUpdate(categories) {
var storage = window.localStorage; 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(','); var jsonurl = weburl + "wp-json/wp/v2/posts?" + REST_PARAMS.per_page + "&categories=" + categories.join(',');
FONTE.updatedCategoriesCount = 0; FONTE.updatedCategoriesCount = 0;
@ -84,29 +73,29 @@ function partialUpdate(categories) {
FONTE.ajaxError = false; FONTE.ajaxError = false;
var lastUpdate = storage.getItem('db_update_date'); var lastUpdate = storage.getItem('db_update_' + type + '_date');
if (lastUpdate) if (lastUpdate)
jsonurl += "&after=" + lastUpdate; jsonurl += "&after=" + lastUpdate;
//jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate; //jsonurl += "&filter[date_query][column]=post_modified_gmt&filter[date_query][after]=" + lastUpdate;
var firstTime = storage.getItem('db_lastnews_firsttime'); var firstTime = storage.getItem('db_last_' + type + '_firsttime');
if (firstTime == null) storage.setItem('db_lastnews_firsttime', 'yes'); if (firstTime === null) storage.setItem('db_last_' + type + '_firsttime', 'yes');
if (firstTime == 'yes') storage.setItem('db_lastnews_firsttime', 'no'); if (firstTime == 'yes') storage.setItem('db_last_' + type + '_firsttime', 'no');
getLastSinglePageRecur(jsonurl, 1, categories); getLastSinglePageRecur(jsonurl, 1, categories);
}; }
var updateLocalStorageDate = function(){ var updateLocalStorageDate = function(type){
var date = new Date(); var date = new Date();
var currentUpdate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2); 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); 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_update_' + type + '_date', currentUpdate);
window.localStorage.setItem('db_lastnews_date', lastUpdate); window.localStorage.setItem('db_last_' + type + '_date', lastUpdate);
} };
var getPrevNews = function(div, categories, page) { var getPrevNews = function(div, categories, page) {
var storage = window.localStorage; var storage = window.localStorage;
@ -122,13 +111,13 @@ var getPrevNews = function(div, categories, page) {
jsonurl += "&before=" + oldest_date; jsonurl += "&before=" + oldest_date;
getPrevSinglePageRecur(jsonurl, 1, FONTE.categories[type]); getPrevSinglePageRecur(jsonurl, 1, FONTE.categories[type]);
} };
function loadMore(type) { function loadMore(type) {
var categories = FONTE.categories[type]; var categories = FONTE.categories[type];
renderPrevNews(FONTE.contentListId, categories, FONTE.page_loaded[type], function(){ renderPrevNews(FONTE.contentListClass, categories, FONTE.page_loaded[type], function(){
getPrevNews(FONTE.contentListId, categories, FONTE.page_loaded[type]) getPrevNews(FONTE.contentListClass, categories, FONTE.page_loaded[type]);
}); });
} }
@ -137,22 +126,22 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
console.log('url:'+url); console.log('url:'+url);
$.ajax({ $.ajax({
dataType: "json" dataType: "json",
, url: url + "&page=" + pagenum url: url + "&page=" + pagenum,
, success: function (data, textStatus, jqXHR) { success: function (data, textStatus, jqXHR) {
var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages'); var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
FONTE.neededPostsCount += data.length; FONTE.neededPostsCount += data.length;
if (FONTE.neededPostsCount == 0) { if (FONTE.neededPostsCount === 0) {
toastr.info('Non ci sono altri alticoli da visualizzare in questa sezione'); 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'); var oldest_date = window.localStorage.getItem('db_oldest_' + type + '_date');
$.each(data, function (key, val) { $.each(data, function (key, val) {
var id = val.id; var id = val.id;
var time = val.modified; var time = val.date;
var title = val.title.rendered; var title = val.title.rendered;
var tags = val.tags; var tags = val.tags;
var postCategories = val.categories; var postCategories = val.categories;
@ -162,7 +151,7 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
FONTE.updatedPostsCount++; FONTE.updatedPostsCount++;
oldest_date = time; oldest_date = time;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) { if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
updateLocalStorageDate(); updateLocalStorageDate(type);
window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date); window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date);
toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.'); toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.');
loadMore(type); loadMore(type);
@ -170,7 +159,7 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
}, function (error) { }, function (error) {
n_error++; n_error++;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) { if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
updateLocalStorageDate(); updateLocalStorageDate(type);
window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date); window.localStorage.setItem('db_oldest_' + type + '_date', oldest_date);
toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.'); toastr.info('Caricati altri ' + FONTE.updatedPostsCount + ' articoli.');
loadMore(type); loadMore(type);
@ -181,36 +170,36 @@ function getPrevSinglePageRecur(url, pagenum, categories) {
insertOrUpdateCatToPost(id, val); insertOrUpdateCatToPost(id, val);
}); });
}); });
} },
, error: JSONErrorHandler error: JSONErrorHandler
}); });
}; }
function getLastSinglePageRecur(url, pagenum, categories) { function getLastSinglePageRecur(url, pagenum, categories) {
var type = getObjKey(FONTE.categories, categories); var type = getObjKey(FONTE.categories, categories);
console.log('url:'+url); console.log('url:'+url);
$.ajax({ $.ajax({
dataType: "json" dataType: "json",
, url: url + "&page=" + pagenum url: url + "&page=" + pagenum,
, success: function (data, textStatus, jqXHR) { success: function (data, textStatus, jqXHR) {
var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages'); var totalPages = jqXHR.getResponseHeader('X-WP-TotalPages');
FONTE.neededPostsCount += data.length; FONTE.neededPostsCount += data.length;
if (FONTE.neededPostsCount == 0) { if (FONTE.neededPostsCount === 0) {
toastr.info('Nessun nuovo articolo.'); toastr.info('Nessun nuovo articolo.');
updateLocalStorageDate(); updateLocalStorageDate(type);
if(FONTE.page_loaded[type] == 0) { if(FONTE.page_loaded[type] === 0) {
renderLastNews(FONTE.contentListId, categories); renderLastNews(FONTE.contentListClass, categories);
} }
} }
var n_error = 0 var n_error = 0;
var oldest_date = window.localStorage.getItem('db_oldest_' + type + '_date'); var oldest_date = window.localStorage.getItem('db_oldest_' + type + '_date');
var older_date = null; var older_date = null;
$.each(data, function (key, val) { $.each(data, function (key, val) {
var id = val.id; var id = val.id;
var time = val.modified; var time = val.date;
var title = val.title.rendered; var title = val.title.rendered;
var tags = val.tags; var tags = val.tags;
var postCategories = val.categories; var postCategories = val.categories;
@ -221,22 +210,22 @@ function getLastSinglePageRecur(url, pagenum, categories) {
console.log('Voci aggiornate: ' + FONTE.updatedPostsCount); console.log('Voci aggiornate: ' + FONTE.updatedPostsCount);
older_date = time; older_date = time;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) { if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
updateLocalStorageDate(); updateLocalStorageDate(type);
if(! oldest_date) if(! oldest_date)
window.localStorage.setItem('db_oldest_' + type + '_date', older_date); window.localStorage.setItem('db_oldest_' + type + '_date', older_date);
toastr.info('Ci sono ' + FONTE.updatedPostsCount + ' nuovi articoli.'); 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. } //manca il caso in cui sono stati cancellati dei post online, vanno cancellati anche dall'app.
}, function (error) { }, function (error) {
n_error++; n_error++;
if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) { if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
updateLocalStorageDate(); updateLocalStorageDate(type);
if(! oldest_date) if(! oldest_date)
window.localStorage.setItem('db_oldest_' + type + '_date', older_date); window.localStorage.setItem('db_oldest_' + type + '_date', older_date);
toastr.info('Aggiornati ' + FONTE.updatedPostsCount + ' nuovi articoli.'); 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); 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;
};