// Raccatto i parametri dall'URL -- mi aspetto un parametro di nome 'link'!
thisUrlParams = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    thisUrlParams[key] = value;
});
console.log('URL get params: ', thisUrlParams);

// Funzioni per eseguire le queries
function prepareQueryURL(query){
    sparqlEndpoint = 'http://dev.restore.ovi.cnr.it:8890/sparql/';
    sparqlUrlParams = '?default-graph-uri=&query=' + encodeURIComponent(query) + '&output=json&callback=?';
    return sparqlEndpoint + sparqlUrlParams;
}

function doJsonQuery(query){

    queryURL = prepareQueryURL(query);

    response = $.ajax({//OGGETTO

        url: queryURL,
        dataType: "json",
        success: function (data){},
        error: function (e) {}
    });

    return response;

}

// Funzioni per raccattare + stringhificare l'output
queryStringOutput = "";
function stringifyResponse(val){
    resultArray = val['results']['bindings'];
    out = "";
    for(i = 0; i < resultArray.length; i++){
        out = out + JSON.stringify(resultArray[i])
    }
    queryStringOutput = (queryStringOutput + out).replace("}{",",");
}

prefixes = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \
PREFIX crm: <http://www.cidoc-crm.org/cidoc-crm/> \
PREFIX owl: <http://www.w3.org/2002/07/owl#> \
PREFIX schema: <http://schema.org/> \
PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
PREFIX person: <http://www.w3.org/ns/person#>"

query = prefixes + " SELECT DISTINCT ?place ?label ?coordinates \
WHERE { \
{?pc crm:P02_has_range <" + thisUrlParams.link + "> . \
?event_from crm:P01_has_domain ?pc ; \
rdf:type crm:EL3_Receive_Letter; \
crm:P26_moved_to ?place_from . \
?place_from rdf:type crm:E53_Place ; \
owl:sameAs ?place . \
?place rdfs:label ?label ; \
crm:P168_place_is_defined_by ?coordinates . \
} UNION { \
?pc crm:P02_has_range <" + thisUrlParams.link + "> . \
?event_from crm:P01_has_domain ?pc ; \
rdf:type crm:EL2_Send_Letter; \
crm:P27_moved_from ?place_from . \
?place_from rdf:type crm:E53_Place ; \
owl:sameAs ?place . \
?place rdfs:label ?label ; \
crm:P168_place_is_defined_by ?coordinates . \
} \
}"

queryInfo = prefixes + " SELECT DISTINCT ?graph ?label ?identifier ?name ?givenName ?familyName ?alias (GROUP_CONCAT(DISTINCT CONCAT(?variant, '| ', ?otherName) ; SEPARATOR = ';') AS ?variants) ?gender ?Birth_Date ?Birth_Place ?Death_Date ?Death_Place ?patronymic ?occupation (group_concat(distinct ?relative1 ;separator=', ') as ?relatives) ?qualification ?group \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
GRAPH ?graph {?uri rdfs:label ?label} \
?uri foaf:name ?name . \
OPTIONAL {?uri crm:P1_is_identified_by ?id . \
?id rdfs:label ?identifier } \
OPTIONAL {?uri foaf:givenName ?givenName} \
OPTIONAL {?uri foaf:familyName ?familyName} \
OPTIONAL {?uri foaf:gender ?gender} \
OPTIONAL {?uri person:patronymicName ?patronymic } \
OPTIONAL {?uri schema:hasOccupation ?uriOccupation . \
?uriOccupation rdf:type schema:Occupation; \
rdfs:label ?occupation } \
OPTIONAL {?uri schema:honorificPrefix ?qualification} \
OPTIONAL {?uri schema:relatedTo ?uriRel1 . \
?uriRel1 rdfs:label ?relative1} \
OPTIONAL {?uri crm:P100i_died_in ?Death . \
?Death crm:P4_has_time-span ?Death_TS; \
crm:P7_took_place_at ?Place_D .\
?Death_TS rdfs:label ?Death_Date . \
?Place_D rdfs:label ?Death_Place } \
OPTIONAL {?uri crm:P98i_was_born ?Birth . \
?Birth crm:P4_has_time-span ?Birth_TS; \
crm:P7_took_place_at ?Place_B . \
?Birth_TS rdfs:label ?Birth_Date . \
?Place_B rdfs:label ?Birth_Place } \
OPTIONAL {?uri crm:P107i_is_current_or_former_member_of ?uriGroup . \
?uriGroup rdfs:label ?group } \
OPTIONAL {?uri schema:alternateName ?alias . } \
OPTIONAL {?uri owl:sameAs ?variant . \
?variant foaf:name ?otherName . } \
} \
GROUP BY ?graph ?label ?identifier ?name ?givenName ?familyName ?alias ?gender ?Birth_Date ?Birth_Place ?Death_Date ?Death_Place ?patronymic ?occupation ?qualification ?group \
LIMIT 1 "

queryLetters = prefixes + " SELECT DISTINCT ?type ?segnatura ?document_uri ?document_name ?time_span ?InfObj \
WHERE {?pc crm:P02_has_range <" + thisUrlParams.link + "> . \
?ev_move crm:P01_has_domain ?pc ; \
rdfs:label ?type ; \
rdfs:subClassOf ?event . \
?document_uri crm:P25i_moved_by ?event ; \
rdfs:label ?document_name . \
?document_uri crm:P1_is_identified_by ?uriSegnatura . \
?uriSegnatura crm:P2_has_type 'Segnatura' ; \
rdfs:label ?segnatura . \
OPTIONAL {GRAPH <http://dev.restore.ovi.cnr.it:8890/ovi/datini> {?document_uri crm:P128_carries ?InfObj . \
?InfObj rdf:type crm:E73_Information_Object} }. \
OPTIONAL {?ev_move crm:P4_has_time-span ?uri_ts . \
?uri_ts rdfs:label ?time_span . } \
}"

queryNetwork = prefixes + " SELECT DISTINCT COUNT(?event) AS ?count ?uri2 SAMPLE(?label2) AS ?text \
WHERE { \
{?event rdf:type crm:EL1_Exchange_Letters . \
?event_to rdfs:subClassOf ?event; \
rdf:type crm:EL2_Send_Letter ; \
crm:P01_has_domain ?pc_to . \
?pc_to crm:P02_has_range ?uri . \
?uri rdfs:label ?label . \
?event_from rdfs:subClassOf ?event; \
rdf:type crm:EL3_Receive_Letter; \
crm:P01_has_domain ?pc_from . \
?pc_from crm:P02_has_range ?uri2 . \
?uri2 rdfs:label ?label2 . \
FILTER (?uri = <" + thisUrlParams.link + ">) \
} UNION { \
?event rdf:type crm:EL1_Exchange_Letters . \
?event_to rdfs:subClassOf ?event; \
rdf:type crm:EL3_Receive_Letter ; \
crm:P01_has_domain ?pc_from . \
?pc_from crm:P02_has_range ?uri . \
?uri rdfs:label ?label . \
?event_from rdfs:subClassOf ?event; \
rdf:type crm:EL2_Send_Letter; \
crm:P01_has_domain ?pc_to . \
?pc_to crm:P02_has_range ?uri2 . \
?uri2 rdfs:label ?label2 . \
FILTER (?uri = <" + thisUrlParams.link + ">) \
} \
} ORDER BY DESC (?count)"

queryURL = prepareQueryURL(query);

queryNet = prepareQueryURL(queryNetwork);

query = prepareQueryURL(queryInfo);

queryEx = prepareQueryURL(queryLetters);

response = $.ajax({

    url: query,
    dataType: "json",
    success: function (data){
      handle_data(data);
    },
    error: function (e) {}
});

response = $.ajax({

    url: queryURL,
    dataType: "json",
    success: function (data){
    	handle_map(data);
    },
    error: function (e) {}
});

responseNet = $.ajax({

    url: queryNet,
    dataType: "json",
    success: function (data){
      handle_network(data);
    },
    error: function (e) {}
});

responseLet = $.ajax({

    url: queryEx,
    dataType: "json",
    success: function (data){
      handle_Letters(data);
    },
    error: function (e) {}
});



function handle_data(json) {

  console.log(json['results']['bindings']);

  var graph = "";
  var label = "";

  if ("givenName" in json.results.bindings) {
          givenName = value['givenName']['value'];
        }


  $.each(
      json['results']['bindings'],
      function (index, value) {
        var graph = value['graph']['value'];
        var label = value['label']['value'];
        var name = value['name']['value'];
        var givenName = "";
        var familyName = "";
        var alias = "";
        var gender = "";
        var patronymic = "";
        var occupation = "";
        var relative = "";
        var identifier = "";
        var birth_date = "";
        var birth_place = "";
        var death_date = "";
        var death_place = "";
        var qualification = "";
        var group = "";

        var variants = "";


        if (value.hasOwnProperty('givenName')) {
          $("#givenName").css("display", "flex");
          givenName = value['givenName']['value'];
        }
        if (value.hasOwnProperty('familyName')) {
          $("#familyName").css("display", "flex");
          familyName = value['familyName']['value'].toLowerCase();
          familyName = familyName.charAt(0).toUpperCase() + familyName.slice(1)
        }
        if (value.hasOwnProperty('alias')) {
          $("#aliasName").css("display", "flex");
          alias = value['alias']['value'];
        }
        if (value.hasOwnProperty('gender')) {
          $("#gender").css("display", "flex");
          gender = value['gender']['value'];
        }
        if (value.hasOwnProperty('patronymic')) {
          $("#patronymic").css("display", "flex");
          patronymic = value['patronymic']['value'];
        }
        if (value.hasOwnProperty('occupation')) {
          $("#occupation").css("display", "flex");
          occupation = value['occupation']['value'];
        }
        if (value.hasOwnProperty('relatives')) {
          if (value['relatives']['value'] != "") {
            relative = value['relatives']['value'];
          }
        }
        if (value.hasOwnProperty('qualification')) {
          $("#honorific").css("display", "flex");
          qualification = value['qualification']['value'];
        }
        if (value.hasOwnProperty('Birth_Date')) {
          $("#BirthDate").css("display", "flex");
          birth_date = value['Birth_Date']['value'];
        }
        if (value.hasOwnProperty('Birth_Place')) {
          $("#BirthPlace").css("display", "flex");
          birth_place = value['Birth_Place']['value'];
        }
        if (value.hasOwnProperty('Death_Date')) {
          $("#DeathDate").css("display", "flex");
          death_date = value['Death_Date']['value'];
        }
        if (value.hasOwnProperty('Death_Place')) {
          $("#DeathPlace").css("display", "flex");
          death_place = value['Death_Place']['value'];
        }
        if (value.hasOwnProperty('group')) {
          $("#groups").css("display", "flex");
          group = value['group']['value'];
        }
        if (value.hasOwnProperty('variants')) {
          $("#otherNames").css("display", "flex");
          let strings = value['variants']['value'];
          variants = strings.split(";");
        }
        
        var dataset = get_dataset_name(graph);
        var second_name = patronymic + " " + relative;

        var first_name = "";

        if ((givenName != "") || (second_name != " ") || (familyName != "")) {
          first_name = givenName + " " + second_name + " " + familyName;
        } else {
          first_name = name;
        }

        var name_string = "";

        if (variants.length>0) {
          for (var i=0; i<variants.length; i++) {
            let chunk = variants[i].split("| ");
            name_string = name_string + "<a href='" + chunk[0] + "'>" + chunk[1] + "</a><br />";
          }
        }

        console.log(variants);

        /*for (var i=0; i<l; i++) {
          names_string = names_string + "<a href='" + variants[i][0] + "'>" + variants[i][1] + "</a>";
        }*/

        document.getElementById("grafo").innerHTML = dataset;
        document.getElementById("nome_persona").innerHTML = first_name;
        document.getElementById("nome").innerHTML = name;
        document.getElementById("genere").innerHTML = gender;
        document.getElementById("nome_proprio").innerHTML = givenName;
        document.getElementById("nome_famiglia").innerHTML = familyName;
        document.getElementById("alias").innerHTML = alias;
        document.getElementById("variants").innerHTML = name_string;
        document.getElementById("patronimico").innerHTML = second_name;
        document.getElementById("qualifica").innerHTML = qualification;
        document.getElementById("occupazione").innerHTML = occupation;
        document.getElementById("data_nascita").innerHTML = birth_date;
        document.getElementById("data_morte").innerHTML = death_date;
        document.getElementById("luogo_nascita").innerHTML = birth_place;
        document.getElementById("luogo_morte").innerHTML = death_place;
        document.getElementById("gruppi_appartenenza").innerHTML = group;

        const collection = document.getElementsByClassName("PN");
        for (var i=0; i<collection.length; i++) {
          collection[i].innerHTML = first_name;
        }
        
      });
  
}

function get_dataset_name(graph) {
  var string = "Scheda Onomastica";
  if (graph == "http://dev.restore.ovi.cnr.it:8890/aspo/onomastica") {
    string = string + " / Onomastica Datini";
  } 
  else if (graph == "http://dev.restore.ovi.cnr.it:8890/mpp/authors"){
    string = string + " / Artisti";
  }
  else {
    string = string;
  }
  return (string);
}

function handle_Letters(json) {

  console.log(json);

  const send = [];
  const receive = [];

  var i=0;
  var j=0;

  $.each(
      json['results']['bindings'],
      function (index, value) {
        type = value['type']['value'];
        uri = value['document_uri']['value'];
        title = value['document_name']['value'];
        segnatura = value['segnatura']['value'];
        var data = "";
        var InfObj = "";
        if (value.hasOwnProperty('time_span')) {
            data = value['time_span']['value'];
        }
        if (value.hasOwnProperty('InfObj')) {
            InfObj = value['InfObj']['value'];
        }
        if (type == "Invio") {
          send.push([uri, title, segnatura, data, InfObj]);
          i++;
        } else {
          receive.push([uri, title, segnatura, data, InfObj]);
          j++;
        }    
      });

  var Send_Letters = "";
  var Receive_Letters = "";

  //POPULATE SEND LETTERS BOX

  for (var i=0; i<send.length; i++) {
    var letter = '<a href=' + send[i][0] + ' target="_blank">' + send[i][1] + '</a>';
    var infObject_button = "";
    if (send[i][2] != "") {
      letter = letter + "<br />Segnatura: " + send[i][2];
    }
    if (send[i][3] != "") {
      letter = letter + "<br />Data invio: " + send[i][3];
    }

    if (send[i][4] != "") {
          infObject_button  += '<button type="button" id="' + send[i][4] + 
          '" class="lettera btn btn-default" alt="lettera" ><i class="fa fa-envelope"></i><p class="btn-text">Scheda Lettera</p></button>';
    } else {
          infObject_button  += '<button type="button" id="' + send[i][0] + 
          '" class="object btn btn-default" alt="oggetto" title="' + send[i][1] + 
          '"><i class="fa fa-book"></i><p class="btn-text">Scheda Oggetto</p></button>';
    }

    Send_Letters += '<div class="row res"><div class="col-8"><p>'+ letter +'</p></div>' + 
        '<div class="col d-flex align-items-start justify-content-end">' + infObject_button +
        '<button type="button" id="' + send[i][0] + '" class="cit btn btn-default" alt="scheda" title="Info"><i class="fa fa-quote-right"></i><p class="btn-text">Citazione</p></button>' +
        '<button type="button" id="' + send[i][0] + '" class="hyp btn btn-default" alt="scheda" title="Info"><i class="fa fa-link"></i><p class="btn-text">Hyperlink</p></button>' +
        '<a href="http://dev.restore.ovi.cnr.it/lodlive/?' + send[i][0] + '" target="_blank"><button type="button" class="btn btn-default info" alt="LOD"><i class="fa fa-share-alt"></i><p class="btn-text">Lod</p></button></a></div></div>';

  }

  //POPULATE RECEIVE LETTERS BOX

  for (var i=0; i<receive.length; i++) {
    var letter = '<a href=' + receive[i][0] + ' target="_blank">' + receive[i][1] + '</a>';
    var infObject_button = "";
    if (receive[i][2] != "") {
      letter = letter + "<br />Segnatura: " + receive[i][2];
    }
    if (receive[i][3] != "") {
      letter = letter + "<br />Data ricezione: " + receive[i][3];
    }

    if (receive[i][4] != "") {
          infObject_button  += '<button type="button" id="' + receive[i][4] + 
          '" class="lettera btn btn-default" alt="lettera" ><i class="fa fa-envelope"></i><p class="btn-text">Scheda Lettera</p></button>';
    } else {
          infObject_button  += '<button type="button" id="' + receive[i][0] + 
          '" class="object btn btn-default" alt="oggetto" title="' + receive[i][1] + 
          '"><i class="fa fa-book"></i><p class="btn-text">Scheda Oggetto</p></button>';
    }

    Receive_Letters += '<div class="row res"><div class="col-8"><p>'+ letter +'</p></div>' + 
        '<div class="col d-flex align-items-start justify-content-end">' + infObject_button +
        '<button type="button" id="' + receive[i][0] + '" class="cit btn btn-default" alt="scheda" title="Info"><i class="fa fa-quote-right"></i><p class="btn-text">Citazione</p></button>' +
        '<button type="button" id="' + receive[i][0] + '" class="hyp btn btn-default" alt="scheda" title="Info"><i class="fa fa-link"></i><p class="btn-text">Hyperlink</p></button>' +
        '<a href="http://dev.restore.ovi.cnr.it/lodlive/?' + receive[i][0] + '" target="_blank"><button type="button" class="btn btn-default info" alt="LOD"><i class="fa fa-share-alt"></i><p class="btn-text">Lod</p></button></a></div></div>';
  }

  document.getElementById("l_send").innerHTML = send.length;
  document.getElementById("l_receive").innerHTML = receive.length;
  document.getElementById("letters_send").innerHTML = Send_Letters;
  document.getElementById("letters_receive").innerHTML = Receive_Letters;

  if (i==0) {
    var messaggio = "<p class='no-results'>Nessun risultato trovato</p>";
    document.getElementById("letters_send").innerHTML = messaggio;
  }

  if (j==0) {
    var messaggio = "<p class='no-results'>Nessun risultato trovato</p>";
    document.getElementById("letters_receive").innerHTML = messaggio;
  }

}


function handle_map(json) {
  console.log(json);

  const locations = [];
  const place_names = [];

  var lat = 0;
  var long = 0;
  var i=0;
  var myPlaces = "";

  $.each(
      json['results']['bindings'],
      function (index, value) {
        const loc = []
        var uri = value['place']['value'];
        var label = value['label']['value'];
        var coord = value['coordinates']['value'];
        const coordinates = coord.split(", ");
        loc.push(label);
        myPlaces += "<div class='item-place-person'><div class='clickPlace item-place-person-label' data-point='"+ coordinates + "'>" + label + "</div><div class='item-place-person-action'><div class='luogo' id='" + 
    uri + "'><i class='far fa-map' style='cursor:pointer'></i></div></div></div>";
        loc.push(coordinates[0]);
        lat += parseInt(coordinates[0]);
        loc.push(coordinates[1]);
        long += parseInt(coordinates[1].replace(/^(\.)/,"0.").replace("-.", "-0."));
        locations.push(loc);
        i++;
        
      });

  var latitude = lat/i;
  var longitude = long/i;

  document.getElementById("list_places_person").innerHTML = myPlaces;


  var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png',
        cloudmadeAttribution = 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade, Points &copy 2012 LINZ',
        cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 17, attribution: cloudmadeAttribution}),
        latlng = new L.LatLng(latitude, longitude);

    
  var map = new L.Map('map', {center: latlng, zoom: 5, layers: [cloudmade]});
  mapLink = '<a href="https://openstreetmap.org">OpenStreetMap</a>';

  var markers = new L.MarkerClusterGroup();
  var markerList = [];

  var geo = new L.tileLayer(
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; ' + mapLink + ' Contributors',
      maxZoom: 18,
    }).addTo(map);

  function populate() {
    for (var i = 0; i < locations.length; i++) {
      var a = locations[i];
      var title = a[0];
      var marker = new L.Marker(new L.LatLng(a[1], a[2]), { title: title });
      marker.bindPopup(title);
      markers.addLayer(marker);
      markerList.push(marker);
    }
  }

  populate();

  map.addLayer(markers);

  $('.clickPlace').on('click', function(){
    // parse lat and lng from the divs data attribute
    var latlng = $(this).data().point.split(',');
    var lat = latlng[0];
    var lng = latlng[1];
    var zoom = 10;

    // set the view
    map.setView([lat, lng], zoom);
});
}



function handle_network(json) {
  console.log(json);

  const words = [];
  const tempArray = [];
  var listwords = "";
  var ArrayNames = "";

  var temp = 0;
  var sum = 0;
  var i=0;
  var j=0;

  $.each(
      json['results']['bindings'],
      function (index, value) {
        text = value['text']['value'];
        link = value['uri2']['value'];
        num = parseInt(value['count']['value']);
        /*count = 0;
        if ((num - temp) > 50) {
          count = temp + 12;
        } else {
          count = num;
        }
        words.push([text, count]);
        temp = count;
        sum += temp;*/
        tempArray.push([text, num]);
        ArrayNames += "<div class='item-place-person'><div class='item-place-person-label'>" +
        text + "<br /><span class='num_occ'>[Co-occorrenze: " + num + "]</span></div><div class='item-place-person-action'><div class='persona' id='" +
        link + "'><i class='fa fa-user' style='cursor:pointer'></i></div></div></div></div>";
      });

  if (tempArray.length < 8) {
    for (var k=0; k<tempArray.length; k++) {
      text = tempArray[k][0];
      count = tempArray[k][1] + 36;
      words.push([text, count]);
    }
  } else {
    for (var k=tempArray.length-1; k>=0; k--) {
      text = tempArray[k][0]; 
      num = tempArray[k][1];
      count = 0;
      if ((num - temp) > 50) {
          count = temp + 12;
        } else {
          count = num;
        }
      words.push([text, count]);
      temp = count;
      sum += temp;
      }
    }

  

  document.getElementById("list_person_network").innerHTML = ArrayNames;

  /*var tot = parseInt(words[0][1]);*/

  for (var i in words) {
    var text = words[i][0]
    var count = words[i][1];
    listwords += '{ "word": \"' + text + '\", "size": \"' + count + '\"},';
  }

  let listL = ('[' + listwords + ']').replace(',]', ']');

  const links = JSON.parse(listL);

  console.log(links);

  // List of words
  var myWords = links;
  
  // set the dimensions and margins of the graph
  var margin = {top: 10, right: 10, bottom: 10, left: 10},
      width = 850 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = d3.select("#myWordCloud").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform",
              "translate(" + (width/2-50) + "," + (height/2+20) + ")");

  // Constructs a new cloud layout instance. It run an algorithm to find the position of words that suits your requirements
  // Wordcloud features that are different from one word to the other must be here
  var layout = d3.layout.cloud()
                        .size([width, height])
                        .words(myWords.map(function(d) { return {text: d.word, size:d.size/2}; }))
                        .padding(5)        //space between words
                        .rotate(function() { return ~~(Math.random() * 2);})
                        .fontSize(function(d) { return d.size + 6; })      // font size of words
                        .on("end", draw);
                        layout.start();


  // This function takes the output of 'layout' above and draw the words
  // Wordcloud features that are THE SAME from one word to the other can be here
  function draw(words) {
    var cloud = svg.selectAll("g text")
                          .data(words, function(d) { return d.text; })

          //Entering words
          cloud.enter()
              .append("text")
              .style("font-family", "Impact")
              .attr("text-anchor", "middle")
              .attr('font-size', 1)
              .text(function(d) { return d.text; });

          //Entering and existing words
          cloud
              .transition()
                  .duration(600)
                  .style("font-size", function(d) { return d.size + "px"; })
                  .attr("transform", function(d) {
                      return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                  })
                  .style("fill-opacity", 1);

          //Exiting words
          cloud.exit()
              .transition()
                  .duration(200)
                  .style('fill-opacity', 1e-6)
                  .attr('font-size', 1)
                  .remove();
    }
}

$(document).on("click", ".luogo", function (ev) {

    var link = this.id;
    //alert(nome_autore);
    //$('#myModal').text("");
    window.open("Luogo.html?link="+this.id);
    

  });

$(document).on("click", ".persona", function (ev) {

    var link = this.id;
    //alert(nome_autore);
    //$('#myModal').text("");
    window.open("Persona.html?link="+this.id);
    

  });

$(document).on("click", ".lettera", function (ev) {

  var link = this.id;
  //alert(nome_autore);
  //$('#myModal').text("");
  window.open("lettera.html?link="+this.id);
  

});

$(document).on("click", ".object", function (ev) {

  var link = this.id;
  //alert(nome_autore);
  //$('#myModal').text("");
  window.open("object.html?link="+this.id);
  

});

$(document).on("click", ".hyp", function (ev) {

  var link = this.id;
  $("#myModal").empty();
  $("#myModal").css("display", "block");
  $('#myModal').append("<div class='modal-content'><div class='modal-close'><span class='close'>&times;</span></div><div id='myInput'>" +
    link + "</div><button id='copy_btn' class='btn btn-theme-primary btn-md' onclick='myFunction()'>Copia</button>");

  

});

$(document).on("click", ".close", function (ev) {

  var link = this.id;
  //alert(nome_autore);
  //$('#myModal').text("");
  $("#myModal").css("display", "none");

});


$(document).on("click", ".back", function (ev) {

  $("#myTab").css("display", "none");

});


$(document).on("click", ".cit", function (ev) {
  
  var author ="RESTORE. smart access to digital heritage and memory"

  var year = new Date().getFullYear()

  var today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
  var yyyy = today.getFullYear();

  today = dd + '/' + mm + '/' + yyyy;

  var link = this.id;
  //alert(nome_autore);
  //$('#myModal').text("");
  $("#myModal").empty();
  $("#myModal").css("display", "block");
  $('#myModal').append("<div class='modal-content'><div class='modal-close'><span class='close'>&times;</span></div><div id='myInput'>" + 
    author + " " + year + ", accesso effettuato: " + today + ", &lt;" + link + "&gt;</div><button id='copy_btn' class='btn btn-theme-primary btn-md' onclick='myFunction()'>Copia</button>");

});


function copyToClipboard(text) {
    var sampleTextarea = document.createElement("textarea");
    document.body.appendChild(sampleTextarea);
    sampleTextarea.value = text; //save main text in it
    sampleTextarea.select(); //select textarea contenrs
    document.execCommand("copy");
    document.body.removeChild(sampleTextarea);
}

function myFunction(){
    var copy = document.getElementById("myInput");
    copyText = copy.textContent;
    copyToClipboard(copyText);

    //copyToClipboard(copyText.value);
}
