Ilovexm24/www/js/main.js

451 lines
14 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* 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.');
}
};
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").addClass("hide");
myJsonCategory(8, "#mostralistainfo");
break;
case '#events':
$("#navheader").removeClass("hide");
$("#navfooter").addClass("hide");
//$("#navfooter").removeClass("hide");
EVENTS.render();
break;
case '#aggiorna':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
// ultimoAggiornamento();
break;
case '#ultime':
case '#tag':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
break;
case '#quotidiano':
$("#navheader").removeClass("hide");
$("#navfooter").removeClass("hide");
myJsonRandomPost('#titolosingleR', '#mostracontentsingleR');
break;
};
// Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url
$.mobile.navigate(url);
};
/*///////////////utilities//////////////http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)")
, results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function display_results(contenitore, messaggio) {
$(contenitore).text(messaggio);
};
$(function () {
$("form").submit(function () {
return false;
});
});
function benvenuta() {
$("#benvenuta").popup("open");
};
//function aggiornaora() {
// $("#aggiornaora").popup("open");
//};
function setFirstRun() {
initStorage();
overlayblock();
if (window.localStorage.getItem('has_run') != 'true') {
//do some stuff if has not loaded before
overlayblock();
benvenuta();
if (checkConnection()) {
partialUpdate();
//window.localStorage.setItem('has_run', 'true');
}
}
};
/*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio
$(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
if(current == 'info' || current == 'events'){
$("#navfooter").addClass("hide");
}
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 () {});
});
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);
});
// eliminare le due righe:
$("body > [data-role='header']").toolbar();
$("[data-role='navbar']").navbar();
alterContent("#info");
};
function overlayblock() {
$(".overlaynero").toggleClass("hide");
}
/*per network info*/
function checkConnection(code, msgConnect) {
var msgTitle = "Non sei connesso";
msgConnect = msgConnect || "Occore essere connessi per poter ricevere i nuovi articoli";
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
if (states[networkState] == 'Unknown connection' || states[networkState] == 'No network connection') {
toastr.warning(msgConnect, msgTitle);
console.log(code);
return false
} else {
return true
}
}
/*///////////////fine utilities//////////////*/
var weburl = "http://www.ecn.org/xm24/";
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
});
$("#navfooter").removeClass("hide");
location.hash = '#singleQpost?id=' + idOra;
});
};
function postInListTag(div) {
$(div).on('click', 'li > a', function () {
var idTag = $(this).attr("data-post");
var titleTag = $(this).html();
$("#tagpostlist").empty();
myJsonPostByTagList(idTag, '#tagpostlist');
$("#tagtitle").empty();
$("#tagtitle").append(titleTag);
// Prevent the usual navigation behavior
event.preventDefault();
$("#posttag").attr("id", '#posttag?idT=' + idTag)
$(":mobile-pagecontainer").pagecontainer("load", '#posttag' + idTag, {
showLoadMsg: false
});
location.hash = '#posttag?idT=' + idTag;
});
};
function cercaMe() {
var input_text = $("input.cerca").val();
input_text = encodeURIComponent(input_text);
var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=100&search=" + input_text + "";
$(".listresult").empty();
$("body").pagecontainer("change", "#ricerca");
$.mobile.loading('show');
var lastUpdate = window.localStorage.getItem('db_update_date');
if (lastUpdate) {
var lastUpdateDate = Date.parse(lastUpdate);
$.ajax({
dataType: "json"
, url: jsonurl
, success: function (data) {
var items = [];
$.each(data, function (key, val) {
var id = val.id;
var time = val.modified;
var title = val.title.rendered;
var url = val.guid.rendered;
var tag = data.tags;
var splitTime = time.split("T");
var cleanTime = splitTime[0];
var dTime = new Date(time);
if (dTime.getTime() <= lastUpdateDate) {
//key mi dice l'indice'
items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
} else {
items.push("<p><a href='#' onclick='aggiornaora();' style='color:#666;' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></p>");
}
});
$("<ul/>", {
"class": "my-new-list"
, html: items.join("")
}).prependTo(".listresult");
$.mobile.loading('hide');
}
, error: JSONErrorHandler
});
} else {
toastr.error('Err: ERR_NOUPDATE');
}
}
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);
FONTE.ajaxError = true;
}
};
function cerca() {
var ret = checkConnection('ERR_CERCA');
if (ret) {
cercaMe();
}
return ret;
};
function segnalaBug() {
return checkConnection('ERR_SEGNALA');
};
function mostraEsperto() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
myJsonPage(2167, '#espertotitle', '#mostraesperto');
}
return ret;
};
function checkAndUpdate() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
update();
}
return ret;
};
function checkAndReset() {
var ret = checkConnection('ERR_ESPERTO');
if (ret) {
resetAndUpdate();
}
return ret;
};