Ilovexm24/www/js/main.js

692 lines
24 KiB
JavaScript
Raw Normal View History

2017-03-05 17:31:47 +01:00
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
///VARIABILI GLOBALI///
var FONTE = FONTE || {};
FONTE.dbName = "xm24";
FONTE.dbHandler;
FONTE.tagsPageInitiated = false;
FONTE.categoriesList = [8, 497];
FONTE.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.hrefseguente = "";
FONTE.ajaxError = false;
/*
* data ultimo aggiornamento
*/
function ultimoAggiornamento() {
var lastUpdate = window.localStorage.getItem('db_update_date');
if (lastUpdate) {
var data = lastUpdate.split('T');
var datagiorno = data[0];
var dataora = data[1];
$("#datadiritti").empty();
$("#datadirittiora").empty();
display_results("#datadiritti", datagiorno)
display_results("#datadirittiora", dataora)
if (data) {
$("#boxdata").css("display", "block");
}
} else {
toastr.warning('Warn: manca la data del tuo ultimo aggiornamento. Aggiorna al più presto.');
2017-03-05 17:31:47 +01:00
}
};
var paginacorrente = "";
function alterContent(url) {
paginacorrente = $("body").pagecontainer("getActivePage").attr("id");
switch (url) {
case '#index':
$("#navheader").addClass("hide");
$("#navfooter").addClass("hide");
break;
case '#ilove':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonCategory(497, "#mostralista");
/* myJsonPage(3452, '#prestitle', '#mostrapres');*/
break;
case '#info':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonCategory(8, "#mostralistainfo");
break;
case '#events':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
ai1ec.remote.getAllEvents(ai1ec.cats.single);
ai1ec.remote.getLastEvents(ai1ec.cats.single);
break;
2017-03-05 17:31:47 +01:00
case '#aggiorna':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
// ultimoAggiornamento();
break;
case '#ultime':
case '#tag':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
break;
case '#quotidiano':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');
break;
};
// Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url
$.mobile.navigate(url);
};
/*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)")
, results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function display_results(contenitore, messaggio) {
$(contenitore).text(messaggio);
};
2017-03-18 17:14:26 +01:00
2017-03-05 17:31:47 +01:00
$(function () {
$("form").submit(function () {
return false;
});
});
function benvenuta() {
$("#benvenuta").popup("open");
};
2017-03-18 15:43:44 +01:00
//function aggiornaora() {
// $("#aggiornaora").popup("open");
//};
2017-03-05 17:31:47 +01:00
function setFirstRun() {
initStorage();
overlayblock();
if (window.localStorage.getItem('has_run') != 'true') {
//do some stuff if has not loaded before
overlayblock();
benvenuta();
if (checkConnection()) {
partialUpdate();
//window.localStorage.setItem('has_run', 'true');
}
}
};
2017-03-18 16:15:57 +01:00
2017-03-05 17:31:47 +01:00
/*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio
2017-03-18 17:14:26 +01:00
$(document).on("mobileinit", function () {
$("body").pagecontainer({
defaults: true
});
$(".ui-loader").loader({
defaults: true
});
$("input").button();
});
$(document).on("pagecontainerchange", function () {    
var current = $(".ui-page-active").prop("id");     // Remove active class from nav buttons
    
console.log("current" + current);
$("[data-role='navbar'] a.ui-btn-active").removeClass("ui-btn-active");     // Add active class to current nav button
    
$("[data-role='navbar'] a").each(function () {
var href = $(this).prop("href");        
if (href.indexOf(current, href.length - current.length) !== -1) {            
$(this).addClass("ui-btn-active");        
}    
});
});
$(document).on("pagecreate", function () {
$("body > [data-role='panel']").panel();
$("body > [data-role='panel'] [data-role='listview']").listview();
$("body > [data-role='header']").toolbar();
$("body > [data-role='footer']").toolbar();
$("body > [data-role='navbar']").navbar();
$("#navfooter").navbar();
postInList();
});
/*per inizio navigazione*/
var Site = function () {
this.homepage = "#index"; // the default page that is loaded
this.init();
};
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();
// new Site();
// $(".minibox").click(function () {});
});
2017-03-05 17:31:47 +01:00
function onDeviceReady() {
// console.log('deviceready');
createDB();
setFirstRun();
$("a.nav").on("click", function (event) {
// Prevent the usual navigation behavior
event.preventDefault();
hrefseguente = $(this).attr("href");
alterContent(hrefseguente);
});
2017-03-18 17:14:26 +01:00
// eliminare le due righe:
$("body > [data-role='header']").toolbar();
$("[data-role='navbar']").navbar();
2017-03-18 16:15:57 +01:00
alterContent("#info");
2017-03-05 17:31:47 +01:00
};
2017-03-18 17:14:26 +01:00
2017-03-05 17:31:47 +01:00
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";
2017-03-18 16:15:57 +01:00
2017-03-05 17:31:47 +01:00
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);
2017-03-05 17:31:47 +01:00
return false
} else {
return true
}
}
/*///////////////fine utilities//////////////*/
var weburl = "http://www.ecn.org/xm24/";
var arrayTag = [];
/*/////finite variabili globali////////*/
function intercettaUrl() {
// LETTURA - Log the results of the navigate event
$(window).on("navigate", function (event, data) {
idPost = getParameterByName('id');
if (idPost != "") {
myJsonPost(idPost, "#titolosingle", "#mostracontentsingle");
}
});
};
function postInList() {
//SCRITTURA
$("body").on('click', '.listevoci li > a', function (event) {
// console.log("HUU_post in list");
var idOra = $(this).attr("data-post");
$("#titolosingle").empty();
$("#mostracontentsingle").empty();
//console.log(idOra);
myJsonPost(idOra, "#titolosingle", "#mostracontentsingle");
// Prevent the usual navigation behavior
event.preventDefault();
/*se serve idTAg, mettiamolo nell'url!! e anche nella page!*/
$("#singleQpost").attr("id", '#singleQpost?id=' + idOra)
$(":mobile-pagecontainer").pagecontainer("load", '#singleQpost' + idOra, {
showLoadMsg: false
});
location.hash = '#singleQpost?id=' + idOra;
});
};
function postInListTag(div) {
$(div).on('click', 'li > a', function () {
var idTag = $(this).attr("data-post");
var titleTag = $(this).html();
$("#tagpostlist").empty();
myJsonPostByTagList(idTag, '#tagpostlist');
$("#tagtitle").empty();
$("#tagtitle").append(titleTag);
// Prevent the usual navigation behavior
event.preventDefault();
$("#posttag").attr("id", '#posttag?idT=' + idTag)
$(":mobile-pagecontainer").pagecontainer("load", '#posttag' + idTag, {
showLoadMsg: false
});
location.hash = '#posttag?idT=' + idTag;
});
};
2017-03-18 15:43:44 +01:00
//function initTag(div) {
// $.mobile.loading('show');
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags ORDER BY date COLLATE NOCASE DESC;", [], function (resultSet) {
// var items = [];
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).tag);
// var name = val.name;
// var slug = val.slug;
// var id = val.id;
// items.push("<li><img src='./image/virgolette_1.png' class='epuntato'/><a href='#posttag' data-post='" + id + "' >" + name + "</a><br/></li>");
// }
// $(div).empty();
// $("<ul/>", {
// "class": "my-new-list"
// , html: items.join("")
// }).prependTo(div);
// }, function (error) {
// console.log(error);
// });
// $.mobile.loading('hide');
//}
//function myJsonPost(Qid, div_title, div_content) {
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ?;", [Qid], function (resultSet) {
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// var content = val.content.rendered;
// content = findImg(content);
//
// $(div_title).html(title);
// //key mi dice l'indice'
// $(div_content).html("<p>" + content + "</p>");
// }
// }, function (error) {
// console.log(error);
// });
//};
//
//function myJsonPage(Qid, div_title, div_content) {
// $.mobile.loading('show');
// var pageId = parseInt(Qid);
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_pages WHERE id = ?;", [pageId], function (resultSet) {
// for (var i = 0; i < resultSet.rows.length; i++) {
// var data = resultSet.rows.item(i);
// var id = data.id;
// var time = data.time;
// var title = data.title;
// var content = data.page;
// content = findImg(content);
// $(div_title).html(title);
// //key mi dice l'indice'
// $(div_content).html("<p>" + content + "</p>");
// }
// });
// $.mobile.loading('hide');
//};
//
//function myJsonRandomPost(div_title, div_content) {
// $.mobile.loading('show');
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts ORDER BY RANDOM() LIMIT 1;", [], function (resultSet) {
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// var content = val.content.rendered;
// content = findImg(content);
// $(div_title).html(title);
// //key mi dice l'indice'
// $(div_content).html("<p>" + content + "</p>");
// }
// });
// $.mobile.loading('hide');
//};
//
//function myJsonPostByTagList(idTag, div) {
// $.mobile.loading('show');
// var tagid = parseInt(idTag);
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_tags_to_posts WHERE tagid = ?;", [tagid], function (resultSet) {
// var items = [];
// var finishCounter = 0;
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = resultSet.rows.item(i);
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE id = ? ORDER BY title COLLATE NOCASE ASC;", [val.id], function (resultSetPost) {
// finishCounter++;
// for (var n = 0; n < resultSetPost.rows.length; n++) {
// var val = JSON.parse(resultSetPost.rows.item(n).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// var splitTime = time.split("T");
// var cleanTime = splitTime[0];
// //key mi dice l'indice'
// items.push({
// item: "<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</li>"
// , title: title
// });
// }
// // fallo solo quando items è stato riempito
// if (finishCounter >= resultSet.rows.length - 1) {
// $(div).empty();
// $("<ul/>", {
// "class": "my-new-list"
// , html: function () {
// function compare(a, b) {
// if (a.title < b.title) return -1;
// if (a.title > b.title) return 1;
// return 0;
// }
// items.sort(compare);
// var finalHtml = "";
// for (var i = 0; i < items.length; i++) {
// finalHtml += items[i].item;
// }
// return finalHtml;
// }()
// }).prependTo(div);
// }
// });
// }
// }, function (error) {
// console.log(error);
// });
// $.mobile.loading('hide');
//}
//function myJsonCategory(Qcategory, div, addTagCategory) {
// $.mobile.loading('show');
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
// var items = [];
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// var splitTime = time.split("T");
// var cleanTime = splitTime[0];
// var tag = '';
// var cattag = '';
// /* if (addTagCategory) {
// $.each(val.tags, function (index, value) {
// if (value == 43) {
//
// }
// if (value == 36) {
//
// }
// });
// //key mi dice l'indice'
// items.push("<li class='"+ cattag +"'><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|<span>" + tag + "</span>|</li>");
// }
// else {*/
// items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
//
// }
// $("<ul/>", {
// "class": "my-new-list"
// , html: items.join("")
// }).prependTo(div);
// });
// $.mobile.loading('hide');
//};
//
//function myJsonLastPage(div) {
// var storage = window.localStorage;
// var lastnewsDate = storage.getItem('db_lastnews_date');
// var firstTime = storage.getItem('db_lastnews_firsttime');
// if (firstTime != 'yes') {
// if (lastnewsDate) {
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE date > ? ORDER BY date COLLATE NOCASE DESC LIMIT 40;", [lastnewsDate], function (resultSet) {
// var items = [];
// $(div).empty();
// if (resultSet.rows.length > 0) {
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// // console.log(Url);
// var splitTime = time.split("T");
// var cleanTime = splitTime[0];
// //key mi dice l'indice'
// items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|");
// }
// $("<ul/>", {
// "class": "my-new-list"
// , html: items.join("")
// }).prependTo(div);
// } else {
// $(div).empty();
// $(div).append('<span>Non ci sono nuovi contenuti.</span>')
// }
// });
// } else {
// $(div).empty();
// $(div).append('<span>Tutti i contenuti sono nuovi.</span>')
// }
// } else {
// $(div).empty();
// $(div).append('<span>Tutti i contenuti sono nuovi.</span>')
// }
//};
//
//function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
// $.mobile.loading('show');
// FONTE.dbHandler.executeSql("SELECT * FROM xm24_posts WHERE category = ? ORDER BY date COLLATE NOCASE DESC;", [Qcategory], function (resultSet) {
// var items = [];
// $(div).empty();
// for (var i = 0; i < resultSet.rows.length; i++) {
// var val = JSON.parse(resultSet.rows.item(i).post);
// var id = val.id;
// var time = val.modified;
// var title = val.title.rendered;
// var url = val.guid.rendered;
// var tag = val.tags;
// var splitTime = time.split("T");
// var cleanTime = splitTime[0];
// //key mi dice l'indice'
// items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small>|</li>");
// }
// $("<ul/>", {
// "class": "my-new-list"
// , html: items.join("")
// }).prependTo(div);
// }, function (error) {
// console.log('errore myJsonCategoryPaginated: ' + error);
// });
// $.mobile.loading('hide');
//};
2017-03-05 17:31:47 +01:00
function cercaMe() {
var input_text = $("input.cerca").val();
input_text = encodeURIComponent(input_text);
var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&search=" + input_text + "";
$(".listresult").empty();
$("body").pagecontainer("change", "#ricerca");
$.mobile.loading('show');
var lastUpdate = window.localStorage.getItem('db_update_date');
if (lastUpdate) {
var lastUpdateDate = Date.parse(lastUpdate);
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
var items = [];
$.each(data, function (key, val) {
var id = val.id;
var time = val.modified;
var title = val.title.rendered;
var url = val.guid.rendered;
var tag = data.tags;
var splitTime = time.split("T");
var cleanTime = splitTime[0];
var dTime = new Date(time);
if (dTime.getTime() <= lastUpdateDate) {
//key mi dice l'indice'
2017-03-18 17:54:19 +01:00
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
2017-03-05 17:31:47 +01:00
} else {
2017-03-18 17:54:19 +01:00
items.push("<p><a href='#' onclick='aggiornaora();' style='color:#666;' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></p>");
2017-03-05 17:31:47 +01:00
}
});
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
}).prependTo(".listresult");
$.mobile.loading('hide');
}
, error: JSONErrorHandler
});
} else {
toastr.error('Err: ERR_NOUPDATE');
2017-03-05 17:31:47 +01:00
}
}
function checkloader() {
myJsonLastPage('#mostralistaultime');
var mieultime = $("#mostralistaultime").html();
// console.log("ultime" + mieultime);
if (mieultime == "<span>Non ci sono nuovi contenuti.</span>") {
//feedback
$("#aggiorna").attr("src", "./image/aggiorna.png");
ultimoAggiornamento();
return true
//console.log("ultime2");
}
// console.log("ultime3");
return false
}
function initTagsPage() {
if (!FONTE.tagsPageInitiated) {
initTag("#mostralistaTag"); // questo mostra i tag
postInListTag("#mostralistaTag"); // questo ti sposta alla specifica lista dei post di un tag
FONTE.tagsPageInitiated = true;
}
}
/* scriversi le cose nel local storage*/
function initStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
function findImg(htmlString) {
var pos = htmlString.indexOf('<img ');
while (pos != -1) {
pos += 5;
htmlString = [htmlString.slice(0, pos), ' onerror="imgNotFound(this);" ', htmlString.slice(pos)].join('');
pos = htmlString.indexOf('<img ', pos);
}
return htmlString;
};
function imgNotFound(img) {
var parent = $(img).parent();
parent.empty();
parent.append('<span>Immagine disponibile online.</span>')
};
function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
if (!FONTE.ajaxError) {
var errMsg = "Err: ";
if(jqXHR.status === 404) {
errMsg += "Sito non raggiungibile. ";
}
toastr.error(errMsg);
2017-03-05 17:31:47 +01:00
FONTE.ajaxError = true;
}
};
function cerca() {
var ret = checkConnection('ERR_CERCA');
2017-03-18 16:15:57 +01:00
if (ret) {
2017-03-05 17:31:47 +01:00
cercaMe();
2017-03-18 16:15:57 +01:00
}
return ret;
2017-03-05 17:31:47 +01:00
};
function segnalaBug() {
return checkConnection('ERR_SEGNALA');
2017-03-05 17:31:47 +01:00
};
function mostraEsperto() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
2017-03-05 17:31:47 +01:00
myJsonPage(2167, '#espertotitle', '#mostraesperto');
}
2017-03-18 16:15:57 +01:00
return ret;
2017-03-05 17:31:47 +01:00
};
function checkAndUpdate() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
2017-03-05 17:31:47 +01:00
update();
}
2017-03-18 16:15:57 +01:00
return ret;
2017-03-05 17:31:47 +01:00
};
function checkAndReset() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
2017-03-05 17:31:47 +01:00
resetAndUpdate();
2017-03-18 16:15:57 +01:00
}
return ret;
2017-03-18 15:43:44 +01:00
};