/*
 * 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.updatedCategoriesCount;
FONTE.updatedPostsCount;
FONTE.neededPostsCount;
FONTE.tagsPageInitiated = false;
FONTE.categoriesList = [8, 497];
FONTE.categories = {
    ilove : [497,647,590], //ilove, 4mar, solid
    info : [8,42,68,3], //ilove, 4mar, solid
};

FONTE.page_loaded = {
    ilove : 0,
    info : 0,
};

FONTE.hrefseguente = "";
FONTE.contentListId = '#mostralistainfo';
FONTE.contentListClass = '.news';
FONTE.ajaxError = false;

FONTE.back_pressed = false;
/*
 * data ultimo aggiornamento
 */
function displayLastUpdateDate() {
    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.');
    }
}

function alterContent(url) {
    var paginacorrente = $("body").pagecontainer("getActivePage").attr("id");

    var oldUrl = url;

    $( "#outside" ).panel( "close" );
    // Alter the url according to the anchor's href attribute, and
    // store the data-foo attribute information with the url
    $.mobile.navigate(url);

    switch (oldUrl) {
    case '#index':
        $("#navheader").addClass("hide");
        $("#navfooter").addClass("hide");
        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':
        $("#navheader").removeClass("hide");
        $("#navfooter").addClass("hide");
        if(checkConnection()) {
            postsUpdate(FONTE.categories.ilove);
        } else {
            renderLastNews(FONTE.contentListClass, FONTE.categories.ilove);
        }
        break;
    case '#info':
        $("#navheader").removeClass("hide");
        $("#navfooter").addClass("hide");
        if(checkConnection()) {
            postsUpdate(FONTE.categories.info);
        } else {
            renderLastNews(FONTE.contentListClass, FONTE.categories.info);
        }
        break;
    case '#events':
        $("#navheader").removeClass("hide");
        $("#navfooter").addClass("hide");
        EVENTS.render(); //il checkconenction è fatto dentro
        break;
    case '#laboratori':
        $("#navheader").removeClass("hide");
        $("#navfooter").addClass("hide");
        PROJECT.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;
    }
}
/*///////////////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 initMainPage() {
    if (checkConnection()) {
        postsUpdate(FONTE.categories.info);
    } else {
        renderLastNews(FONTE.contentListClass, FONTE.categories.info);
    }
}

/*per link in browser di default */
document.addEventListener("deviceready", onDeviceReady, false);
//le cose all'inizio


$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    FONTE.back_pressed = true;
  }
  else {
    FONTE.back_pressed = false;
  }
});

$(document).on("pagecontainershow", function (e, ui) {
    var pageId = $('body').pagecontainer('getActivePage').prop('id');
    if ((pageId == 'ilove' || pageId == 'info' || pageId == 'events') && !FONTE.back_pressed) {
        $.mobile.loading('show');
    }
});

$(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 == 'about' || current == 'info' || current == 'ilove' || current == 'events' || current == 'cerca' || current == 'laboratori'){
        $("#navfooter").addClass("hide");
    } else {
        $("#navfooter").removeClass("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;
    });
};

function onDeviceReady() {
    //Setto il locale delle plugin delle date
    moment.locale('it'); 
    
    createDB();
    initStorage();
    
    if(window.localStorage.getItem('app_firsttime') !== "false") {
        alterContent('#about');
    } else {
        initMainPage();
    }
    
    overlayblock();
    $("a.nav").on("click", function (event) {
        // Prevent the usual navigation behavior
        event.preventDefault();
        alterContent($(this).attr("href"));
    });
    
    $("button.nav").on("click", function (event) {
        alterContent($(this).attr("href"));
    });
    // eliminare le due righe:
    $("body > [data-role='header']").toolbar();
    $("[data-role='navbar']").navbar();
    
    //Non uso pageContent per non lanciare 2 volte il recupero dei dati da internet
    //per la pagina principale
    $("#navheader").removeClass("hide");
    $("#navfooter").addClass("hide");
}

function overlayblock() {
    $(".overlaynero").toggleClass("hide");
}
/*///////////////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");
        if($(this).attr("rel") === 'external') {
            return true;
        }
        
        var idOra = $(this).attr("data-post");
        var _class = $(this).attr("class");
        $("#titolosingle").empty();
        $("#mostracontentsingle").empty();
        //console.log(idOra);
        myJsonPost(idOra, "#titolosingle", "#mostracontentsingle", _class);
        // 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 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) {
    $.mobile.loading('hide');
    if (!FONTE.ajaxError) {
        var errMsg = "Err: ";
        if(jqXHR.status === 404 ) {
            errMsg += "Sito non raggiungibile. ";
        } else if(jqXHR.status === 0) {
            return checkConnection(jqXHR.status, "Occore essere connessi per poter ricevere altri articoli");
        }
        toastr.error(errMsg);
        FONTE.ajaxError = true;
    }
}

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;
}
