// 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#>"

queryInfo = prefixes + " SELECT DISTINCT ?g AS ?graph ?uri ?label ?dimension ?consistency ?id ?sigla_registro (group_concat(distinct ?dimension ; separator='<br />') as ?dimensions) ?material (group_concat(distinct ?time_span ;separator='-') as ?time_span) ?location ?uri_owner ?owner ?uri_document ?document ?note \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
GRAPH ?g { ?uri rdfs:label ?label } \
OPTIONAL {?uri crm:P1_is_identified_by ?uri_id . \
?uri_id rdfs:label ?id ; \
crm:P2_has_type 'Segnatura' .} \
OPTIONAL { ?uri crm:P43_has_dimension ?uri_consistency . \
?uri_consistency crm:P2_has_type 'Consistenza carte' ; \
rdfs:label ?consistency } \
OPTIONAL { ?uri crm:P43_has_dimension ?uri_dimension . \
?uri_dimension crm:P2_has_type 'Dimensioni' ; \
rdfs:label ?dimension } \
OPTIONAL { ?uri crm:P139_has_alternative_form ?uri_registro . \
?uri_registro rdfs:label ?sigla_registro; \
crm:P2_has_type 'Sigla registro' . } \
OPTIONAL { ?uri crm:P45_consist_of ?uri_material . \
?uri_material rdfs:label ?material } \
OPTIONAL { ?uri crm:P52_has_current_owner ?uri_owner . \
?uri_owner rdfs:label ?owner . } \
OPTIONAL { ?uri crm:P54_has_current_permanent_location ?location } \
OPTIONAL { ?uri crm:P3_has_note ?uri_note . \
?uri_note rdfs:label ?note } \
OPTIONAL { ?uri crm:P92i_was_brought_into_existence_by ?creation . \
?creation crm:P4_has_time-span ?uri_time_span . \
?uri_time_span rdfs:label ?time_span . } \
OPTIONAL {?uri_document crm:P46_is_composed_of ?uri ; \
rdfs:label ?document .} \
} "

queryContent = prefixes + " SELECT DISTINCT ?g AS ?graph ?uri ?titolo ?tipo (group_concat(distinct ?ref ; separator='<br />') as ?ref) \
WHERE { \
VALUES ?object {<" + thisUrlParams.link + ">} \
?object crm:P128_carries ?uri . \
?uri rdf:type crm:E73_Information_Object . \
GRAPH ?g { ?uri rdfs:label ?label } \
OPTIONAL {?uri crm:P1_is_identified_by ?uri_titolo . \
?uri_titolo rdfs:label ?titolo ; \
rdf:type crm:E35_Title . } \
OPTIONAL { ?uri crm:P2_has_type ?uri_tipo . \
?uri_tipo rdfs:label ?tipo . } \
OPTIONAL { ?uri crm:P67_refers_to ?uri_ref . \
?uri_ref rdfs:label ?ref . } \
FILTER NOT EXISTS {GRAPH <http://dev.restore.ovi.cnr.it:8890/ovi/datini> { ?uri rdfs:label ?label }}. \
}"

queryOviLetter = prefixes + " SELECT DISTINCT ?otherId ?InfObj \
WHERE {  \
VALUES ?uri {<" + thisUrlParams.link + ">}   \
?uri crm:P1_is_identified_by ?uri_id .  \
?uri_id crm:P2_has_type 'Segnatura' ; \
crm:P139_has_alternative_form ?other_id . \
?other_id crm:P2_has_type ?uri_type ; \
rdfs:label ?otherId . \
?uri_type rdfs:label 'Segnatura OVI' . \
OPTIONAL { ?uri crm:P128_carries ?InfObj . \
GRAPH <http://dev.restore.ovi.cnr.it:8890/ovi/datini> {?InfObj rdf:type crm:E73_Information_Object } } \
} "

queryPersone = prefixes + " SELECT DISTINCT ?uri_person ?name ?p_type ?note \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
{?uri crm:P46_is_composed_of ?card . \
?card crm:P2_has_type 'Scheda anagrafica' . \
?document crm:P141_assigned ?card ; \
crm:P67_refers_to ?uri_person . \
?uri_person foaf:name ?name ; \
crm:P2_has_type ?person_type . \
?person_type rdfs:label ?p_type . \
} UNION { \
?document crm:P141_assigned ?uri ; \
crm:P67_refers_to ?uri_person . \
?uri_person foaf:name ?name ; \
crm:P2_has_type ?person_type . \
?person_type rdfs:label ?p_type . \
} UNION { \
?uri crm:P92i_was_brought_into_existence_by ?creation . \
?creation crm:P67_refers_to ?uri_person . \
?uri_person foaf:name ?name ; \
crm:P67.1_type ?person_type . \
OPTIONAL {?uri_person crm:P3_has_note ?note } \
?person_type rdfs:label ?p_type . \
} \
}"

queryAssocDocs = prefixes + " SELECT DISTINCT ?card ?doc_type ?name_card \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri crm:P46_is_composed_of ?card . \
?card rdfs:label ?name_card . \
OPTIONAL {?card crm:P2_has_type ?doc_type } \
OPTIONAL {?document crm:P141_assigned ?card ; \
crm:P67_refers_to ?uri_person . \
?uri_person foaf:name ?name ; \
crm:P2_has_type ?person_type . \
?person_type rdfs:label ?type . \
} \
}"

queryContrassegni = prefixes + " SELECT DISTINCT ?uri_contrassegno ?contrassegno \
WHERE {VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri crm:P46_is_composed_of ?uri_paper . \
?uri_documentation crm:P141_assigned ?uri_paper ; \
crm:P140_assigned_attribute_to ?uri_contrassegno . \
?uri_contrassegno rdfs:label ?contrassegno . \
}"

queryEventiGettatelli = prefixes + " SELECT DISTINCT ?uri_obj ?object ?name_event ?event_type ?uri_person ?label ?role ?time_span ?uri_place ?place \
WHERE {VALUES ?uri {<" + thisUrlParams.link + ">} \
OPTIONAL {?uri crm:P46_is_composed_of ?uri_paper . } \
{?uri_paper crm:P128_carries ?uri_doc } \
UNION \
{?uri crm:P128_carries ?uri_doc } \
?uri_doc crm:P70_documents ?event ; \
rdfs:label ?document . \
?uri_obj crm:P128_carries ?uri_doc . \
?uri_doc rdfs:label ?object . \
?event rdfs:label ?name_event . \
?event crm:P2_has_type ?uri_event_type . \
?uri_event_type rdfs:label ?event_type . \
?event crm:P01_has_domain ?domain . \
?domain crm:P02_has_range ?uri_person ; \
crm:P14.1_in_the_role_of ?uri_role . \
?uri_role rdfs:label ?role . \
?uri_person rdfs:label ?label . \
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_place owl:sameAs ?uri_location ; \
crm:P168_place_is_defined_by ?coords; \
rdfs:label ?place . } \
}"

queryURL = prepareQueryURL(queryInfo);

queryINF = prepareQueryURL(queryContent);

queryOVI = prepareQueryURL(queryOviLetter);

queryPERS = prepareQueryURL(queryPersone);

queryDOC = prepareQueryURL(queryAssocDocs);

queryCON = prepareQueryURL(queryContrassegni);

queryEV = prepareQueryURL(queryEventiGettatelli);


response = $.ajax({

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

response_info = $.ajax({

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

response_info = $.ajax({

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

response_people = $.ajax({

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

response_contrassegni = $.ajax({

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

response_eventi = $.ajax({

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


function handle_objectData(json) {

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

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var graph = value['graph']['value'];
        var label = value['label']['value'];
        var uri = value['uri']['value'];
        var identifier = "";
        var dimensions = "";
        var consistence = "";
        var materials = "";
        var description = "";
        var button_ext = "";
        var button_owner = "";
        var current_owner = "";
        var uri_owner = "";
        var dates = "";
        var uri_composed = "";
        var composed = "";
        var button_doc = "";

        var dataset = get_graph_name(graph);

        if (value.hasOwnProperty('id')) {
          $("#ID").css("display", "flex");
          identifier = value['id']['value'];
        }
        if (value.hasOwnProperty('dimension')) {
            $("#dimensione").css("display", "flex");
            dimensions = value['dimensions']['value'];
        }
        if (value.hasOwnProperty('consistency')) {
            $("#consistenza").css("display", "flex");
            consistence = value['consistency']['value'];
        }
        if (value.hasOwnProperty('condition')) {
          $("#STCC").css("display", "flex");
          condition = value['condition']['value'];
        }
        if (value.hasOwnProperty('material')) {
          $("#materia").css("display", "flex");
          materials = value['material']['value'];
        }
        if (value.hasOwnProperty('uri_owner')) {
          $("#current_owner").css("display", "flex");
          current_owner = value['owner']['value'];
          uri_owner = value['uri_owner']['value'];
        }
        if (value.hasOwnProperty('time_span')) {
          if (value['time_span']['value'] != ""){
            $("#time_span_object").css("display", "flex");
            dates = value['time_span']['value'];
          }
        }
        if (value.hasOwnProperty('note')) {
          $("#notes").css("display", "flex");
          description = value['note']['value'];
        }
        if (value.hasOwnProperty('uri_document')) {
          uri_composed = value['uri_document']['value'];
        }
        if (value.hasOwnProperty('document')) {
          $("#composed").css("display", "flex");
          composed = value['document']['value'];
        }

        if (identifier != "") {
          button_ext = '<a href= "' + uri + '">' + identifier + '</a>';
        }

        if (uri_composed != "") {
          button_doc = '<button id="' + uri_composed + '" class="object btn btn-default" type="button" title="Bene culturale" > \
          <i class="fa fa-book" aria-hidden="true">	<p class="btn-text">Bene culturale</p></i></button>';
        }

        if (owner != "") {
          button_owner = '<a href= "' + uri_owner + '">' + current_owner + '</a>';
        }

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


        document.getElementById("grafo").innerHTML = dataset;
        document.getElementById("nome_oggetto").innerHTML = label;
        document.getElementById("identifier").innerHTML = button_ext;
        document.getElementById("nota").innerHTML = description;
        document.getElementById("dimensions").innerHTML = dimensions;
        document.getElementById("materials").innerHTML = materials;
        document.getElementById("consistence").innerHTML = consistence;
        document.getElementById("owner").innerHTML = button_owner;
        document.getElementById("timeSpan").innerHTML = dates;
        document.getElementById("superDoc").innerHTML = composed;
        document.getElementById("btn_superDoc").innerHTML = button_doc;
        document.getElementById("link_buttons").innerHTML = Buttons;
       
        
      });
  
}

function get_graph_name(graph) {
  var dataset = "Scheda Oggetto";

  if (graph == "http://dev.restore.ovi.cnr.it:8890/aspo/ospedale") {
    dataset = dataset + " / Ospedale";
  } else if (graph == "http://dev.restore.ovi.cnr.it:8890/aspo/datini") {
    dataset = dataset + " / Datini";
  } else if (graph == "http://dev.restore.ovi.cnr.it:8890/aspo/marcovaldi") {
    dataset = dataset + " / Marcovaldi";
  } else if (graph == "http://dev.restore.ovi.cnr.it:8890/aspo/gettatelli") {
    dataset = dataset + " / Gettatelli";
  } else {
    dataset = dataset;
  }
  return dataset;
}

function handle_objectInfo(json) {

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

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

        var title = "";
        var type = "";
        var subject = "";
        

        if (value.hasOwnProperty('titolo')) {
          $("#titolo").css("display", "flex");
          title = value['titolo']['value'];
        }
        if (value.hasOwnProperty('tipo')) {
          $("#tipo").css("display", "flex");
          type = value['tipo']['value'];
        }

        if (value.hasOwnProperty('ref')) {
          if (value['ref']['value'] != "") {
            $("#argomento").css("display", "flex");
            subject = value['ref']['value'];
          }
        }
        
        document.getElementById("title").innerHTML = title;
        document.getElementById("type").innerHTML = type;
        document.getElementById("subject").innerHTML = subject;
        
        
      });
  
}

function handle_oviLetter(json) {

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

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

        var other_id = "";
        var uri = "";
        var button_letter = "";

        if (value.hasOwnProperty('otherId')) {
          $("#IDbis").css("display", "flex");
          other_id = value['otherId']['value'];
        }
        if (value.hasOwnProperty('InfObj')) {
          uri = value['InfObj']['value'];
        }

        if (uri != "") {
          button_letter = '<button type="button" id="' + uri + 
					'" class="lettera btn btn-default" alt="lettera"><i class="fa fa-envelope"></i><p class="btn-text">Scheda Lettera</p></button>';
        }
        
        document.getElementById("other_identifier").innerHTML = other_id;
        document.getElementById("btn_other_identifier").innerHTML = button_letter;
        
      });

}

/*
function handle_citedPeople(json) {
  
  console.log(json);

  var Relazioni = "";
  const myArray = []

  $.each(
    json['results']['bindings'],
    function (index, value) {
        var uri_person = value['uri_person']['value'];
        var name = value['name']['value'];
        var tipo = "";
        var nota = "";
      
        if (value.hasOwnProperty('p_type')) {
          tipo = value['p_type']['value'];
        }
        if (value.hasOwnProperty('note')) {
          nota = "<br /><span class='nota_menzione'><i>" + value['note']['value'] + "</i></span>";
        }
      
      var string = name + nota; 

      myArray.push([tipo, string, uri_person, nota]);
   
    });

  if (myArray.length == 0) {
    $("#placeholder_people").css("display", "none");
  }

  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( "#placeholder_people" );

  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 declaration = "" 
          if (myArray[i][3] != "") {
            declaration = "myMargin";
          }
          var rel = myArray[i][0].replaceAll(" ", "_");
          if (par == rel) {
              var col = createColRelazione(text, link, "persona", "fa fa-user", "Scheda Persona", declaration);
              Colums = Colums + col;
          }
      }
      document.getElementById(par).innerHTML = Colums;
  }

}

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

  var Sezioni = "";
  const myArray = []

  $.each(
    json['results']['bindings'],
    function (index, value) {
        var uri = value['card']['value'];
        var name = value['name_card']['value'];
        var tipo = "";
      
        if (value.hasOwnProperty('doc_type')) {
          tipo = value['doc_type']['value'];
        }
        
      myArray.push([tipo, name, uri]);
   
    });

  if (myArray.length == 0) {
    $("#placeholder_documents").css("display", "none");
  }

  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);
    Sezioni = Sezioni + rel;
  }

  $(Sezioni).insertAfter( "#placeholder_documents" );

  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, "object", "fa fa-book", "Scheda Oggetto", "");
              Colums = Colums + col;
          }
      }
      document.getElementById(par).innerHTML = Colums;
  }

} 

function handle_associatedDocuments(json) {

  console.log(json);

  const docs = [];

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var uri = value['card']['value'];
        var label = value['name_card']['value'];
        var tipo = "";
      
        if (value.hasOwnProperty('doc_type')) {
          tipo = value['doc_type']['value'];
        }

        docs.push([uri, label, tipo]);
        
      });

  var Docs = "";

  for (var i=0; i<docs.length; i++) {
    var object = '<div class="col-8"><p><span id="' + docs[i][0] + '" class="title_doc object">'+ docs[i][1] + '</span>';
    if (docs[i][2] != "") {
      object = object + "<br />Documento: " + docs[i][2];
    }
    object = object + '</p></div>';

    var object_button  = '<button type="button" id="' + docs[i][0] + 
      '" class="object btn btn-default" alt="oggetto" title="' + docs[i][1] + 
      '"><i class="fa fa-book"></i><p class="btn-text">Scheda Oggetto</p></button>';

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

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

function handle_citedPeople(json) {

  console.log(json);

  const people = [];

  $.each(
    json['results']['bindings'],
    function (index, value) {
        var uri = value['uri_person']['value'];
        var name = value['name']['value'];
        var tipo = "";
        var nota = "";
      
        if (value.hasOwnProperty('p_type')) {
          tipo = value['p_type']['value'];
        }
        if (value.hasOwnProperty('note')) {
          nota = value['note']['value'];
        } 

      people.push([uri, name, tipo, nota]);
      
    });

    var Person = "";

    for (var i=0; i<people.length; i++) {
      var object = '<div class="col-8"><p><span id="' + people[i][0] + '" class="title_doc persona">'+ people[i][1] + '</span>';
      if (people[i][2] != "") {
        object = object + "<br />Ruolo: " + people[i][2];
      }
      if (people[i][3] != "") {
        object = object + "<br />Nota: " + people[i][3];
      }

      object = object + '</p></div>';
    
      Person +=  '<div class="row res">' + object +
      '<div class="col d-flex align-items-start justify-content-end"><button type="button" id="' + people[i][0] + '" class="persona btn btn-default" alt="persona" title="' +
      people[i][1] + '"><i class="fa fa-user"></i><p class="btn-text">Scheda Persona</p></button>' +
      '<button type="button" value="Persona" id="' + people[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="Persona" type="button" id="' + people[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/?' + people[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_pp").innerHTML = people.length;
    document.getElementById("cited_people").innerHTML = Person;
  
    if (people.length==0) {
      var messaggio = "<p class='no-results'>Nessun risultato trovato</p>";
      document.getElementById("cited_people").innerHTML = messaggio;
    }

}

function handle_contrassegni(json) {

  console.log(json);

  const cons = [];

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var uri = value['uri_contrassegno']['value'];
        var label = value['contrassegno']['value'];
        
        cons.push([uri, label]);
        
      });

  var Marks = "";

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

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

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

function handle_eventiGettatelli(json) {

  console.log(json);

  const evGett = [];

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var uri = value['uri_obj']['value'];
        var label = value['object']['value'];
        var name_event = value['name_event']['value'];
        var event_type = value['event_type']['value'];
        var uri_person = value['uri_person']['value'];
        var person = value['label']['value'];
        var role = value['role']['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'];
        } 
        
        evGett.push([name_event, uri_person, person, role, time_span, uri_place, place]);
        
      });

      var thead = 
      '<div class="col-4">Evento registrato</div>' +
      '<div class="col-2">Persona</div>' +
      '<div class="col-2">Ruolo</div>' +
      '<div class="col-2">Data</div>' +
      '<div class="col-2">Luogo</div>';
    
      var EventsTable = "";
    
      for (var i=0; i<evGett.length; i++) {
        EventsTable += '<div class="row res">' +
        '<div class="col-4">' + evGett[i][0] + '</div>' +
        '<div id="' + evGett[i][1] + '" class="col-2 persona title_doc">' + evGett[i][2] + '</div>' +
        '<div class="col-2">' + evGett[i][3] + '</div>' +
        '<div class="col-2">' + evGett[i][4] + '</div>' +
        '<div id="' + evGett[i][5] + '" class="col-2 luogo title_doc">' + evGett[i][6] + '</div>' +
        '</div>';
      }
    
      if (events.length != 0) {
        document.getElementById("thead_ev").innerHTML = thead;
        document.getElementById("section_events").innerHTML = EventsTable;
      } else {
        document.getElementById("section_events").innerHTML = "Nessun evento trovato";
      }
  
}

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, tipo, fa, tab, decl) {
  htmlCode = '\
    <div class="row"> \
        <div class="col <CLASS>"><NAME></div> \
        <div class="col-auto"> \
            <button class="<TIPO> btn btn-default" type="button" id="<URI>">\
	            	<i class="<BUTTON>" aria-hidden="true">\
			              <p class="btn-text"><TAB></p>\
	        	    </i>\
		          </button>\</div> \
    </div>\
		'.replace("<NAME>", text).replace("<URI>", link).replace("<TIPO>", tipo).replace("<BUTTON>", fa).replace("<TAB>", tab).replace("<CLASS>", decl);
	return htmlCode;
}

$(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", ".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", ".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", ".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 schedaASPO(info){
    window.open(info);
  }

  $(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");
  
  });

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