// 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 ?tipo ?coordinates COUNT(?pc) AS ?count \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
{?pc crm:P02_has_range ?uri . \
?event_from crm:P01_has_domain ?pc ; \
rdf:type crm:EL3_Receive_Letter; \
rdfs:label ?tipo ; \
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 ?uri . \
?event_from crm:P01_has_domain ?pc ; \
rdf:type crm:EL2_Send_Letter; \
rdfs:label ?tipo ; \
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 . \
} UNION { \
  ?uri crm:P100i_died_in ?uri_death . \
  ?uri_death crm:P7_took_place_at ?uri_place . \
  ?uri_place rdf:type crm:E53_Place ; \
  owl:sameAs ?place .  \
  ?place rdfs:label ?label ;  \
  crm:P168_place_is_defined_by ?coordinates . \
  } UNION { \
    ?uri crm:P98i_was_born ?uri_birth . \
  ?uri_birth crm:P7_took_place_at ?uri_place . \
  ?uri_place rdf:type crm:E53_Place ; \
  owl:sameAs ?place . \
  ?place rdfs:label ?label ;  \
  crm:P168_place_is_defined_by ?coordinates . \
  } \
}"

queryInfo = prefixes + " SELECT DISTINCT ?uri ?graph ?label ?identifier ?id_type ?name ?givenName ?familyName ?relative2 ?relative3 ?provenienza (GROUP_CONCAT(DISTINCT CONCAT(?variant, '| ', ?otherName) ; SEPARATOR = ';') AS ?variants) ?gender ?Birth_Date ?Birth_Place ?Death_Date ?Death_Place ?patronymic ?occupation ?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 ; \
crm:P2_has_type ?id_type .} \
OPTIONAL {?uri foaf:givenName ?givenName} \
OPTIONAL {?uri foaf:familyName ?familyName} \
OPTIONAL {?uri foaf:gender ?gender} \
OPTIONAL {?uri person:patronymicName ?patronymic } \
OPTIONAL {?uri crm:P74_has_current_or_former_residence ?uri_provenienza . \
?uri_provenienza crm:P2_has_type 'Provenienza'; \
rdfs:label ?provenienza . } \
OPTIONAL {?uri crm:P2_has_type ?uri_person_type . \
?uri_person_type rdfs:label ?person_type } \
OPTIONAL {?uri schema:hasOccupation ?uriOccupation . \
?uriOccupation rdf:type schema:Occupation; \
rdfs:label ?occupation } \
OPTIONAL {?uri schema:honorificPrefix ?qualification} \
OPTIONAL {?uri crm:P100i_died_in ?Death . \
OPTIONAL {?Death crm:P4_has_time-span ?Death_TS . \
?Death_TS rdfs:label ?Death_Date . } \
OPTIONAL {?Death crm:P7_took_place_at ?Place_D .  \
?Place_D rdfs:label ?Death_Place } \
} \
OPTIONAL {?uri crm:P98i_was_born ?Birth . \
OPTIONAL {?Birth crm:P4_has_time-span ?Birth_TS . \
?Birth_TS rdfs:label ?Birth_Date . } \
OPTIONAL {?Birth crm:P7_took_place_at ?Place_B . \
?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 . } \
OPTIONAL {?relation2 crm:P141_assigned ?uri ; \
crm:P42_assigned ?uri_rel_type2 . \
?uri_rel_type2 rdfs:label 'Avo di secondo grado' . \
?uri_relative2 crm:P141_assigned ?relation2; \
rdfs:label ?relative2 .} \
OPTIONAL {?relation3 crm:P141_assigned ?uri ; \
crm:P42_assigned ?uri_rel_type3 . \
?uri_rel_type3 rdfs:label 'Avo di terzo grado' . \
?uri_relative3 crm:P141_assigned ?relation3; \
rdfs:label ?relative3 .} \
} \
GROUP BY ?graph ?uri ?label ?identifier ?id_type ?name ?givenName ?familyName ?relative2 ?relative3 ?provenienza ?gender ?Birth_Date ?Birth_Place ?Death_Date ?Death_Place ?patronymic ?occupation ?qualification ?group \
LIMIT 1  "

queryInfoGettatelli = prefixes + " SELECT DISTINCT ?card ?uri_card \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?documentation crm:P67_refers_to ?uri ; \
crm:P141_assigned ?uri_card . \
?uri_card rdfs:label ?card . \
} "

queryRelazioni = prefixes + " SELECT DISTINCT ?relation_type ?note ?uri_person ?name ?givenName ?familyName ?patronymic ?provenienza \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri crm:P141_assigned ?relation . \
?relation crm:P42_assigned ?uri_type ; \
crm:P141_assigned ?uri_person . \
?uri_type rdfs:label ?relation_type . \
OPTIONAL {?uri_type crm:P3_has_note ?note } \
?uri_person foaf:name ?name . \
OPTIONAL {?uri_person foaf:givenName ?givenName} \
OPTIONAL {?uri_person foaf:familyName ?familyName} \
OPTIONAL {?uri_person person:patronymicName ?patronymic } \
OPTIONAL {?uri_person crm:P74_has_current_or_former_residence ?uri_provenienza . \
?uri_provenienza crm:P2_has_type 'Provenienza'; \
rdfs:label ?provenienza . } \
} "

queryRelazioniInverse = prefixes + " SELECT DISTINCT ?relation_type ?note ?uri_person SAMPLE(?name) AS ?name ?givenName ?familyName ?patronymic ?provenienza \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?relation crm:P141_assigned ?uri; \
crm:P42_assigned ?uri_type . \
?uri_person crm:P141_assigned ?relation . \
?uri_type rdfs:label ?relation_type . \
OPTIONAL {?uri_type crm:P3_has_note ?note } \
OPTIONAL {?uri_person foaf:name ?name } \
OPTIONAL {?uri_person foaf:givenName ?givenName} \
OPTIONAL {?uri_person foaf:familyName ?familyName}  \
OPTIONAL {?uri_person person:patronymicName ?patronymic } \
OPTIONAL {?uri_person crm:P74_has_current_or_former_residence ?uri_provenienza . \
?uri_provenienza crm:P2_has_type 'Provenienza'; \
rdfs:label ?provenienza . } \
} "

queryLetters = prefixes + " SELECT DISTINCT ?type ?segnatura ?document_uri ?document_name ?time_span ?InfObj \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
{?pc crm:P02_has_range ?uri . \
} UNION { \
?group crm:P107_has_current_or_former_member ?uri; \
crm:P2_has_type 'Gruppo scrittura lettera' . \
?pc crm:P02_has_range ?group . \
} \
?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 . } \
}"

queryDocuments = prefixes + " SELECT DISTINCT ?role ?document ?label ?id (group_concat(distinct ?time_span ;separator='-') as ?time_span) \
WHERE { \
?document ?property ?event ; \
crm:P1_is_identified_by ?uri_id ; \
rdfs:label ?label . \
?uri_id rdfs:label ?id ; \
crm:P2_has_type 'Segnatura' . \
OPTIONAL { \
{?event crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span . \
} UNION { \
?sub_event rdfs:subClassOf ?event ; \
crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span . } \
} \
?event crm:P01_has_domain ?domain . \
?domain crm:P02_has_range <" + thisUrlParams.link + "> ; \
crm:P14.1_in_the_role_of ?uri_role . \
?uri_role rdfs:label ?role . \
} \
GROUP BY ?document ?label ?id ?role "

queryOtherDoc = prefixes + " SELECT DISTINCT ?document ?label ?id (group_concat(distinct ?time_span ;separator='-') as ?time_span) \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + "> } \
{?domain crm:P02_has_range ?uri . \
?event crm:P01_has_domain ?domain . \
?document crm:P92i_was_brought_into_existence_by ?event ; \
crm:P1_is_identified_by ?uri_id ; \
rdfs:label ?label . \
?uri_id crm:P2_has_type 'Segnatura'; \
rdfs:label ?id . \
} UNION { \
?event crm:P67_refers_to ?uri . \
?document crm:P92i_was_brought_into_existence_by ?event ; \
rdfs:label ?label ; \
crm:P1_is_identified_by ?uri_id . \
?uri_id rdfs:label ?id ; \
crm:P2_has_type 'Segnatura' . \
} UNION { \
?event crm:P67_refers_to ?uri . \
?documentation crm:P67_refers_to ?uri ; \
crm:P141_assigned ?card . \
?document crm:P46_is_composed_of ?card ; \
rdfs:label ?label ; \
crm:P1_is_identified_by ?uri_id . \
?uri_id rdfs:label ?id ; \
crm:P2_has_type 'Segnatura' . \
} \
OPTIONAL {?event crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span} \
} "

queryOpere = prefixes + " SELECT DISTINCT ?subject ?label ?nct (group_concat(distinct ?time_span ;separator='-') as ?time_span) \
WHERE {?subject rdf:type crm:E22_Man-Made_Object ; \
rdfs:label ?label ; \
crm:P1_is_identified_by ?uri_nct . \
?uri_nct rdfs:label ?nct . \
?production crm:P108_has_produced ?subject . \
OPTIONAL {?production crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span } \
?pc crm:P01_has_domain ?production ; \
crm:P02_has_range <" + thisUrlParams.link + "> } \
GROUP BY ?subject ?label ?nct "

queryGettatelliEv = prefixes + " SELECT DISTINCT ?event_type ?time_span \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri crm:P12i_was_present_at ?event . \
?event crm:P2_has_type ?uri_event_type ; \
crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span . \
?uri_event_type rdfs:label ?event_type . \
} "

queryEventi = prefixes + " SELECT DISTINCT ?event_type ?role ?time_span ?place ?uri_place ?document ?uri_document \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?domain crm:P02_has_range ?uri ; \
crm:P14.1_in_the_role_of ?uri_role . \
?uri_role rdfs:label ?role . \
?event crm:P01_has_domain ?domain ; \
crm:P2_has_type ?uri_event_type . \
?uri_event_type rdfs:label ?event_type . \
OPTIONAL {?event crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span .} \
OPTIONAL {?event crm:P7_took_place_at ?uri_location . \
?uri_location rdfs:label ?place . \
OPTIONAL {?uri_place owl:sameAs ?uri_location . \
?uri_place crm:P168_place_is_defined_by ?coords }} \
?document_info crm:P70_documents ?event . \
?uri_document crm:P128_carries ?document_info ; \
rdfs:label ?document . \
} "

queryCompagnia = prefixes + " SELECT DISTINCT ?denomination ?occupation ?uri_sede ?uri_place ?sede \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri rdf:type crm:E74_Group . \
?uri crm:P2_has_type ?denomination . \
OPTIONAL {?uri schema:hasOccupation ?uri_Occupation . \
?uri_Occupation rdfs:label ?occupation .} \
OPTIONAL {?uri crm:P74_has_current_or_former_residence ?uri_sede . \
?uri_sede rdfs:label ?sede . \
OPTIONAL {?uri_sede owl:sameAs ?uri_place . \
?uri_place crm:P168_place_is_defined_by ?coords .} \
} \
}"

queryURL = prepareQueryURL(query);

queryOt = prepareQueryURL(queryOtherDoc);

queryOA = prepareQueryURL(queryOpere);

query = prepareQueryURL(queryInfo);

queryEx = prepareQueryURL(queryLetters);

queryGt = prepareQueryURL(queryGettatelliEv);

queryInfoGt = prepareQueryURL(queryInfoGettatelli);

queryRel = prepareQueryURL(queryRelazioni);

queryRelIn = prepareQueryURL(queryRelazioniInverse);

queryCom = prepareQueryURL(queryCompagnia);

queryEv = prepareQueryURL(queryEventi);

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

responseLet = $.ajax({

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

responseOA = $.ajax({

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

responseOt = $.ajax({

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


responseGet = $.ajax({

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

responseDoc = $.ajax({

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

responseRel = $.ajax({

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

responseRel = $.ajax({

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

responseRel = $.ajax({

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

responseEv = $.ajax({

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


var labelName = "";

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 uri = value['uri']['value'];
        var label = value['label']['value'];
        var name = value['name']['value'];
        var givenName = "";
        var familyName = "";
        var alias = "";
        var gender = "";
        var patronymic = "";
        var occupation = "";
        var relative2 = "";
        var relative3 = "";
        var identifier = "";
        var id_type = "";
        var birth_date = "";
        var birth_place = "";
        var death_date = "";
        var death_place = "";
        var qualification = "";
        var group = "";
        var type = "";
        var provenence = "";

        var variants = "";

        if ((value.hasOwnProperty('identifier')) && (value.hasOwnProperty('id_type'))) {
          $("#identifier").css("display", "flex");
          identifier = value['identifier']['value'];
          id_type = value['id_type']['value'];
        }
        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('provenienza')) {
          $("#PlaceProvenence").css("display", "flex");
          provenence = value['provenienza']['value'];
        }
        if (value.hasOwnProperty('occupation')) {
          $("#occupation").css("display", "flex");
          occupation = value['occupation']['value'];
        }
        if (value.hasOwnProperty('relative2')) {
          relative2 = value['relative2']['value'];
        }
        if (value.hasOwnProperty('relative3')) {
          relative3 = value['relative3']['value'];
        }
        if (value.hasOwnProperty('qualification')) {
          $("#honorific").css("display", "flex");
          qualification = value['qualification']['value'];
        }
        if (value.hasOwnProperty('person_type')) {
          $("#type").css("display", "flex");
          type = value['person_type']['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')) {
          if (value['variants']['value'] != "| ") {
            alert(value['variants']['value']);
            $("#otherNames").css("display", "flex");
            let strings = value['variants']['value'];
            variants = strings.split(";");
          }
        }
        
        var dataset = get_dataset_name(graph);
        var second_name = patronymic + " " + relative2 + " " + relative3;

        var first_name = "";

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

        first_name = first_name.replace(",", "");
        
        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 />";
          }
        }

        labelName = first_name;

        //console.log(variants);

        var Buttons = '<button class="btn btn-default" type="button" onclick="schedaASPO(\'' + uri + '\')"> \
        <i class="fas fa-external-link-alt" aria-hidden="true"></i></button> \
        <button type="button" value="object" id="' + uri + '" class="cit btn btn-default" alt="scheda" title="Citazione"><i class="fa fa-quote-right"></i></button> \
        <button type="button" value="object" id="' + uri + '" class="hyp btn btn-default" alt="scheda" title="Hyperlink"><i class="fa fa-link"></i></button> \
        <a href="http://dev.restore.ovi.cnr.it/lodlive/?' + uri + '" target="_blank"><button type="button" class="btn btn-default info" alt="LOD" title="LodLive"><i class="fa fa-share-alt"></i></button></a></div></div>';


        var id_snippet = "<div class='col-sm-4'><span class='label'>" + id_type + ":</span></div><div class='col' id='identificatore'>" + identifier + "</div>";

        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("provenienza").innerHTML = provenence;
        document.getElementById("identifier").innerHTML = id_snippet;
        document.getElementById("alias").innerHTML = alias;
        document.getElementById("tipologia").innerHTML = type;
        document.getElementById("variants").innerHTML = name_string;
        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;
        document.getElementById("link_buttons").innerHTML = Buttons;

        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_InfoGettatelli(json) {
  
  //console.log(json);

  var card = "";
  var uri_card = "";

  $.each(
      json['results']['bindings'],
      function (index, value) {

        if ((value.hasOwnProperty('uri_card')) && (value.hasOwnProperty('card'))) {
          $("#card").css("display", "flex");
          uri_card = value['uri_card']['value'];
          card = value['card']['value'];
        }
        
      });

  var button_obj = "";

  if (uri_card != "") {
    button_obj = '<button type="button" id="' + uri_card + 
    '" class="object btn btn-default" alt="oggetto" title="' + uri_card + 
    '"><i class="fa fa-book"></i><p class="btn-text">Scheda Oggetto</p></button>';
  }

  document.getElementById("scheda_anagrafica").innerHTML = card;
  document.getElementById("btn_scheda").innerHTML = button_obj;

}

function handle_Gettatelli(json) {
  
  //console.log(json);

  var generic = "";
  var find = "";
  var reunite = "";
  var adoption = "";

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var event_type = value['event_type']['value'];
        var data = value['time_span']['value'];

        if (event_type == "Evento generico") {
          $("#generic_event").css("display", "flex");
          generic = data;
        } 
        else if (event_type == "Ritrovamento") {
          $("#find_event").css("display", "flex");
          find = data;
        } 
        else if (event_type == "Ricongiungimento") {
          $("#reunion_event").css("display", "flex");
          reunite = data;
        } 
        else if (event_type == "Adozione") {
          $("#adoption_event").css("display", "flex");
          adoption = data;
        } 
        
      });

  document.getElementById("anno").innerHTML = generic;
  document.getElementById("ritrovamento").innerHTML = find;
  document.getElementById("ricongiungimento").innerHTML = reunite;
  document.getElementById("adozione").innerHTML = adoption;

}

function handle_Relazioni(json) {
  
  //console.log(json);

  var Relazioni = "";
  const myArray = []

  $.each(
    json['results']['bindings'],
    function (index, value) {
      var tipo = value['relation_type']['value'];
      var uri_person = value['uri_person']['value'];
      var nome = value['name']['value'];
      var principale = "";
      var givenName = "";
      var familyName = "";
      var patronymic = "";
      var provenence = "";
      
      if (value.hasOwnProperty('givenName')) {
        givenName = value['givenName']['value'];
      }
      if (value.hasOwnProperty('note')) {
        principale = " principale";
      }
      if (value.hasOwnProperty('familyName')) {
        familyName = value['familyName']['value'].toLowerCase();
        familyName = familyName.charAt(0).toUpperCase() + familyName.slice(1)
      }
      if (value.hasOwnProperty('patronymic')) {
        patronymic = value['patronymic']['value'];
      }
      if (value.hasOwnProperty('provenienza')) {
        provenence = value['provenienza']['value'];
      } 

      var type = tipo.charAt(0).toUpperCase() + tipo.slice(1) + principale;

      if ((type == "Socio") || (type == "Socio principale")) {
        type = type + " di";
      }

      if (type == "Mano lettera") {
        type = "Altre collaborazioni"
      }

      var first_name = "";

      if ((givenName != "") || (patronymic != "") || (familyName != "") || (provenence != "")) {
        first_name = givenName + " " + patronymic + " " + familyName + " " + provenence;
      } else {
        first_name = nome;
      }

      myArray.push([type, first_name, uri_person]);
   
    });

  const checkRel = [];

  for (var i=0; i<myArray.length; i++) {
      var key = myArray[i][0];
      checkRel.push(key);
  }

  var params = [];
  $.each(checkRel, function(i, el){
    if($.inArray(el, params) === -1) params.push(el);
  });

  for (var i=0; i<params.length; i++) {
    var par = params[i];
    var par_id = par.replaceAll(" ", "_");
    var rel = createDivRelazione(par, par_id);
    Relazioni = Relazioni + rel;
  }

  $(Relazioni).insertAfter( "#groups" );

  for (var j=0; j<params.length; j++) {
      var el = params[j];
      var par = el.replaceAll(" ", "_");
      var Colums = ""; 
      for (var i=0; i<myArray.length; i++) {
          var text = myArray[i][1];
          var link = myArray[i][2];
          var rel = myArray[i][0].replaceAll(" ", "_");
          if (par == rel) {
              var col = createColRelazione(text, link);
              Colums = Colums + col;
          }
      }
      document.getElementById(par).innerHTML = Colums;
  }

}

function handle_RelazioniInverse(json) {
  
  //console.log(json);

  var Relazioni = "";
  const myArray = []

  $.each(
    json['results']['bindings'],
    function (index, value) {
      var tipo = value['relation_type']['value'];
      var uri_person = value['uri_person']['value'];
      var nome = "";
      var principale = "";
      var givenName = "";
      var familyName = "";
      var patronymic = "";
      var provenence = "";
      
      if (value.hasOwnProperty('name')) {
        nome = value['name']['value'];
      }
      if (value.hasOwnProperty('givenName')) {
        givenName = value['givenName']['value'];
      }
      if (value.hasOwnProperty('note')) {
        principale = " principale";
      }
      if (value.hasOwnProperty('familyName')) {
        familyName = value['familyName']['value'].toLowerCase();
        familyName = familyName.charAt(0).toUpperCase() + familyName.slice(1)
      }
      if (value.hasOwnProperty('patronymic')) {
        patronymic = value['patronymic']['value'];
      }
      if (value.hasOwnProperty('provenienza')) {
        provenence = value['provenienza']['value'];
      } 

      var type = tipo.charAt(0).toUpperCase() + tipo.slice(1) + principale + " di";

      if (type == "Socio di") {
        type = "Soci";
      }

      if (type == "Socio principale di") {
        type = "Intestatario principale";
      }

      if (type == "Mano lettera di") {
        type = "Collaboratori";
      }

      var first_name = "";

      if ((givenName != "") || (patronymic != "") || (familyName != "") || (provenence != "")) {
        first_name = givenName + " " + patronymic + " " + familyName + " " + provenence;
      } else {
        first_name = nome;
      }

      myArray.push([type, first_name, uri_person]);
   
    });

  const checkRel = [];

  for (var i=0; i<myArray.length; i++) {
      var key = myArray[i][0];
      checkRel.push(key);
  }

  var params = [];
  $.each(checkRel, function(i, el){
    if($.inArray(el, params) === -1) params.push(el);
  });

  for (var i=0; i<params.length; i++) {
    var par = params[i];
    var par_id = par.replaceAll(" ", "_");
    var rel = createDivRelazione(par, par_id);
    Relazioni = Relazioni + rel;
  }

  $(Relazioni).insertAfter( "#groups" );

  for (var j=0; j<params.length; j++) {
      var el = params[j];
      var par = el.replaceAll(" ", "_");
      var Colums = ""; 
      for (var i=0; i<myArray.length; i++) {
          var text = myArray[i][1];
          var link = myArray[i][2];
          var rel = myArray[i][0].replaceAll(" ", "_");
          if (par == rel) {
              var col = createColRelazione(text, link);
              Colums = Colums + col;
          }
      }
      document.getElementById(par).innerHTML = Colums;
  }

}

function createDivRelazione(type, id){
	htmlCode = '\
      <div class="row mb-2"> \
      <div class="col-sm-4"> \
        <span class="label"><RELATIONSHIP></span> \
      </div> \
      <div class="col record_box" id="<ID_RELATIONSHIP>"></div> \
    </div> \
		'.replace("<RELATIONSHIP>", type).replace("<ID_RELATIONSHIP>", id);
	return htmlCode;
}

function createColRelazione(text, link) {
  htmlCode = '\
    <div class="row"> \
        <div class="col"><NAME></div> \
        <div class="col-auto"> \
            <button class="persona btn btn-default" type="button" id="<URI>">\
	            	<i class="fa fa-user" aria-hidden="true">\
			              <p class="btn-text">Scheda Persona</p>\
	        	    </i>\
		          </button>\</div> \
    </div>\
		'.replace("<NAME>", text).replace("<URI>", link);
	return htmlCode;
}

function handle_Events(json) {

  const events = [];

  $.each(
    json['results']['bindings'],
    function (index, value) {
      var event_type = value['event_type']['value'];
      var role = value['role']['value'];
      var uri_document = value['uri_document']['value'];
      var document = value['document']['value'];
      var time_span = "";
      var uri_place = "";
      var place = "";

      if (value.hasOwnProperty('time_span')) {
        time_span = value['time_span']['value'];
      }
      if (value.hasOwnProperty('uri_place')) {
        uri_place = value['uri_place']['value'];
      } 
      if (value.hasOwnProperty('place')) {
        place = value['place']['value'];
      } 

      const cells = [event_type, role, time_span, uri_place, place, uri_document, document];    
      events.push(cells); 

  });

  var thead = '<div id="ev_thead" class="row">' +
  '<div class="col-2">Evento</div>' +
  '<div class="col-2">Ruolo</div>' +
  '<div class="col-2">Data</div>' +
  '<div class="col-2">Luogo</div>' +
  '<div class="col-4">Documento</div>' +
  '</div>';

  var EventsTable = thead;

  for (var i=0; i<events.length; i++) {
    EventsTable += '<div class="row">' +
    '<div class="col-2">' + events[i][0] + '</div>' +
    '<div class="col-2">' + events[i][1] + '</div>' +
    '<div class="col-2">' + events[i][2] + '</div>' +
    '<div id="' + events[i][3] + '" class="col-2 luogo">' + events[i][4] + '</div>' +
    '<div id="' + events[i][5] + '" class="col-4 object">' + events[i][6] + '</div>' +
    '</div>';
  }

  if (events.length != 0) {
    document.getElementById("res_events").innerHTML = EventsTable;
  } else {
    document.getElementById("res_events").innerHTML = "Nessun evento trovato";
  }

}

function handle_Compagnia(json) {
  
  //console.log(json);

  var denominazione = "";
  var sede = "";
  var uri_sede = "";
  var uri_place = "";

  $.each(
    json['results']['bindings'],
    function (index, value) {
      if (value.hasOwnProperty('denomination')) {
        $("#type_society").css("display", "flex");
        denominazione = value['denomination']['value'];
      }
      if (value.hasOwnProperty('uri_place')) {
        $("#sede").css("display", "flex");
        uri_place = value['uri_place']['value'];
      }
      if (value.hasOwnProperty('uri_sede')) {
        $("#sede").css("display", "flex");
        uri_sede = value['uri_sede']['value'];
      }
      if (value.hasOwnProperty('sede')) {
        sede = value['sede']['value'];
      }

  });
      

  var workPlace_button = "";

  if (uri_place != "") {
    workPlace_button = '<button type="button" id="' + uri_place + 
    '" class="luogo btn btn-default" alt="luogo" ><i class="far fa-map"></i><p class="btn-text">Scheda Luogo</p></button>';
  } else {
    workPlace_button = '<button class="btn btn-default" type="button" onclick="schedaASPO(' + uri_sede 
    + ')"><i class="fa fa-link" aria-hidden="true">	<p class="btn-text">Link</p></i></button>';
  }

  document.getElementById("society").innerHTML = denominazione;
  document.getElementById("workPlace").innerHTML = sede;
  document.getElementById("workPlace_btn").innerHTML = workPlace_button;
      
}

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 = "";
    var infObject_button = "";
    var object_type = "";

    if (send[i][4] != "") {
          letter = '<div class="col-8"><p><span id="' + send[i][0] + '" class="title_doc lettera">'+ send[i][1] + '</span>';
          object_type = "lettera";
          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 {
          letter = '<div class="col-8"><p><span id="' + send[i][0] + '" class="title_doc object">'+ send[i][1] + '</span>';
          object_type = "object";
          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>';
    }

    if (send[i][2] != "") {
      letter = letter + "<br />Segnatura: " + send[i][2];
    }
    if (send[i][3] != "") {
      letter = letter + "<br />Data: " + send[i][3];
    }

    letter = letter + '</p></div>';

    Send_Letters += '<div class="row res">'+ letter + 
        '<div class="col d-flex align-items-start justify-content-end">' + infObject_button +
        '<button type="button" value="' + object_type + '" 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" value="' + object_type + '" 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 = "";
    var infObject_button = "";
    var object_type = "";

    if (receive[i][4] != "") {
          letter = '<div class="col-8"><p><span id="' + receive[i][0] + '" class="title_doc lettera">'+ receive[i][1] + '</span>';
          object_type = "lettera";
          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 {
          letter = '<div class="col-8"><p><span id="' + receive[i][0] + '" class="title_doc object">'+ receive[i][1] + '</span>';
          object_type = "object";
          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>';
    }

    if (receive[i][2] != "") {
      letter = letter + "<br />Segnatura: " + receive[i][2];
    }
    if (receive[i][3] != "") {
      letter = letter + "<br />Data: " + receive[i][3];
    }

    letter = letter + '</p></div>';

    Receive_Letters += '<div class="row res">'+ letter + 
        '<div class="col d-flex align-items-start justify-content-end">' + infObject_button +
        '<button type="button" value="' + object_type + '" 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" value="' + object_type + '" 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 (send.length==0) {
    var messaggio = "<p class='no-results'>Nessun risultato trovato</p>";
    document.getElementById("letters_send").innerHTML = messaggio;
  }

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

}


function handle_Artwork(json) {

  //console.log(json);

  const oa = [];

  $.each(
      json['results']['bindings'],
      function (index, value) {
        uri = value['subject']['value'];
        label = value['label']['value'];
        nct = value['nct']['value'];
        var data = "";
        
        if (value.hasOwnProperty('time_span')) {
            data = value['time_span']['value'];
        }

        oa.push([uri, label, nct, data]);
        
      });

  var Artworks = "";

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

    var object_button  = '<button type="button" id="' + oa[i][0] + 
      '" class="artwork btn btn-default" alt="opera d\'arte" title="' + oa[i][1] + 
      '"><i class="fas fa-paint-brush"></i><p class="btn-text">Scheda Opera d\'Arte</p></button>';

    Artworks += '<div class="row res"><div class="col-8"><p>'+ artwork +'</p></div>' + 
    '<div class="col d-flex align-items-start justify-content-end">' + object_button +
    '<button value="OA" type="button" id="' + oa[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 value="OA" type="button" id="' + oa[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/?' + oa[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("n_oa").innerHTML = oa.length;
  document.getElementById("object_oa").innerHTML = Artworks;

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

}

function handle_Other_Documents(json) {

  //console.log(json);

  const doc = [];

  $.each(
      json['results']['bindings'],
      function (index, value) {
        uri = value['document']['value'];
        label = value['label']['value'];
        var data = "";
        var id = "";
        if (value.hasOwnProperty('time_span')) {
            data = value['time_span']['value'];
        }
        if (value.hasOwnProperty('id')) {
            id = value['id']['value'];
        }

        doc.push([uri, label, id, data]);
        
      });

  var Documents = "";

  for (var i=0; i<doc.length; i++) {
    var paper = '<div class="col-8"><p><span id="' + doc[i][0] + '" class="title_doc object">'+ doc[i][1] + '</span>';
    var object_button = '<button type="button" id="' + doc[i][0] + 
          '" class="object btn btn-default" alt="oggetto" title="' + doc[i][1] + 
          '"><i class="fa fa-book"></i><p class="btn-text">Scheda Oggetto</p></button>';

    if (doc[i][2] != "") {
      paper = paper + "<br />Segnatura: " + doc[i][2];
    }
    if (doc[i][3] != "") {
      paper = paper + "<br />Data: " + doc[i][3];
    }

    paper = paper + '</p></div>';

      Documents += '<div class="row res">'+ paper + 
    '<div class="col d-flex align-items-start justify-content-end">' + object_button +
    '<button value="object" type="button" id="' + doc[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 value="object" type="button" id="' + doc[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/?' + doc[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("n_ass").innerHTML = doc.length;
  document.getElementById("other_documents").innerHTML = Documents;

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

}

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

  const locations = [];
  const place_names = [];
  const place_events = [];
  const luoghi = [];

  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'];
        var evento = value['tipo']['value']
        var count = value['count']['value']
        place_events.push([uri, evento, count]);
        if (!place_names.includes(uri)) {
          place_names.push(uri);
          const coordinates = coord.split(", ");
          loc.push(uri);
          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++;
        }
        
      });

  for (var k=0; k<locations.length; k++) {
    const tempArray = [];
    var nomeLuogo = locations[k][1];
    var lt = locations[k][2];
    var lg = locations[k][3];
    tempArray.push(nomeLuogo);
    tempArray.push(lt);
    tempArray.push(lg);
    for (var y=0; y<place_events.length; y++) {
      var ev = place_events[y][1];
      var number = place_events[y][2]
      var dict = ev + ": " + number;
      if (locations[k][0] == place_events[y][0]) {
        tempArray.push(dict);
      }
    }
    luoghi.push(tempArray);
  }
    
  //console.log(luoghi);
  var latitude = lat/i;
  var longitude = long/i;

  var mapIcon = "<div id='map_icon' class='no_info_icon'> \
  <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 576 512'> \
  <!--! Font Awesome Pro 6.1.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d='M408 120C408 174.6 334.9 271.9 302.8 311.1C295.1 321.6 280.9 321.6 273.2 311.1C241.1 271.9 168 174.6 168 120C168 53.73 221.7 0 288 0C354.3 0 408 53.73 408 120zM288 152C310.1 152 328 134.1 328 112C328 89.91 310.1 72 288 72C265.9 72 248 89.91 248 112C248 134.1 265.9 152 288 152zM425.6 179.8C426.1 178.6 426.6 177.4 427.1 176.1L543.1 129.7C558.9 123.4 576 135 576 152V422.8C576 432.6 570 441.4 560.9 445.1L416 503V200.4C419.5 193.5 422.7 186.7 425.6 179.8zM150.4 179.8C153.3 186.7 156.5 193.5 160 200.4V451.8L32.91 502.7C17.15 508.1 0 497.4 0 480.4V209.6C0 199.8 5.975 190.1 15.09 187.3L137.6 138.3C140 152.5 144.9 166.6 150.4 179.8H150.4zM327.8 331.1C341.7 314.6 363.5 286.3 384 255V504.3L192 449.4V255C212.5 286.3 234.3 314.6 248.2 331.1C268.7 357.6 307.3 357.6 327.8 331.1L327.8 331.1z'/> \
  </svg> \
  <p>Nessun luogo trovato</p> \
  </div>";

  if (locations.length == 0) {
    $("#references_persona").css("display", "none");
    document.getElementById("map").innerHTML = mapIcon;
  }

  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 < luoghi.length; i++) {
      var a = luoghi[i];
      var len = a.length;
      var title = "<b>" + a[0] + "</b>";
      for (var k=3; k<len; k++) {
        title = title + "<br />" + a[k];
      }
      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);
});
}


$(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;
    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 baseurl = window.location.origin+window.location.pathname;
  let slash = baseurl.lastIndexOf("/");
  var type = $(this).val() + '.html';
  var link = this.id;
  var url = baseurl.substr(0, slash+1) + type + "?link="+link;
  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'>" +
    url + "</div><button id='copy_btn' class='btn btn-theme-primary btn-md' onclick='myFunction()'>Copia</button>");

});

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

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

$(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 baseurl = window.location.origin+window.location.pathname;
  let slash = baseurl.lastIndexOf("/");
  var type = $(this).val() + '.html';
  var link = this.id;
  var url = baseurl.substr(0, slash+1) + type + "?link="+link;
  //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;" + url + "&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);
}
