<!DOCTYPE html>
<html>
<%- include partial/head.ejs %>
  <body>
    <div class="container-fluid" id="container">
      <div class="row row-offcanvas row-offcanvas-left">
<%- include partial/stranski-menu.ejs %>
        <div class="container-fluid main col-sm-12">
          <div id="opozorilo"></div>
          <div class="page-header">
            <h1><%= title %></h1>
          </div>
<%- include partial/iskalnik.ejs %>
          <h2>Priljubljeni organi</h2>
          <div id="graf-organi"><canvas id="canvasOrgani" height="150" width="600"></canvas><div>
          <div class="row">
            <div class="col-sm-5" id="graf-pie-organi"><canvas id="piechart-organi"></canvas></div>
            <div class="col-sm-7">
              <table class="table" id="organi">
                <thead>
                  <tr>
                    <th>Naziv</th>
                    <th>Šifra proračunskega uporabnika</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                </tbody>                
              </table>
            </div>
          </div>
          <h2>Priljubljena podjetja</h2>
          <div id="graf-podjetja"><canvas id="canvas" height="150" width="600"></canvas></div>
          <!-- vsebina -->
          <div class="row">
            <div class="col-sm-5" id="graf-pie-podjetja"><canvas id="piechart-podjetja"></canvas></div>
            <div class="col-sm-7">
              <table class="table" id="podjetja">
                <thead>
                  <tr>
                    <th>Naziv</th>
                    <th>Davčna številka</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                </tbody>                
              </table>
            </div>
          </div>
          <p>
            <button class="btn btn-outline-success" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
              Upravljaj lokalno shrambo
            </button>
          </p>
          <div class="collapse" id="collapseExample">
            <div class="card card-body">
              <p>Aplikacija uporablja lokalno shrambo (localStorage) za shranjevanje podatkov o priljubljenih državnih organih in podjetjih. Če želite podatke odstraniti,
                jih lahko pobrišete z uporabo spodnjega gumba - s tem bodo izbrisani vsi podatki, ki jih na vaš računalnik shranjuje aplikacija. Brisanja ni mogoče razveljaviti.</p>
              
              <p>Pobriši lokalno shrambo: <button id="pobrisi-shrambo" class="btn btn-secondary btn-sm" type="button"><i class="fa fa-trash-o"></i> Pobriši</button></p>
            </div>
          </div>
          <!--/row-->
        </div>
      </div>
    </div>
    <script>
      <%
        var mesec = ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "avg", "sep", "okt", "nov", "dec"];
        var labels = [];
        var trenutnoLeto = new Date().getFullYear();
        var trenutniMesec = ((new Date().getFullYear() - 2003) * 12 + new Date().getMonth()) + 1;
        for (var i = 0; i < trenutniMesec; i++) {
          if(i%12 == 0) {
            labels.push((Math.round(i/12) + 2003).toString() + ' ' + (mesec[i%12]).toString());
          } else labels.push((mesec[i%12]).toString());
        }
      %>
      var randomColorFactor = function() {
        return Math.round(Math.random() * 255);
      };

      var barChartData = {
        labels: <%- JSON.stringify(labels) %>,
        datasets: []
      };

      var barChartDataOrgani = {
        labels: <%- JSON.stringify(labels) %>,
        datasets: []
      };

      window.onload = function() {
        var ctx = document.getElementById("canvas").getContext("2d");
        var elmnt = document.getElementById("graf-podjetja");
        ctx.canvas.height = 500;
        ctx.canvas.width = elmnt.clientWidth;
        window.myBar = new Chart(ctx, {
          type: 'bar',
          data: barChartData,
          options: {
            title:{
              display:true,
              text:"Transakcije priljubljenih podjetij"
            },
            tooltips: {
              mode: 'label'
            },
            responsive: true,
            scales: {
              xAxes: [{
                stacked: true,
              }],
              yAxes: [{
                stacked: true
              }]
            }
          }
        });

        var ctxOrgani = document.getElementById("canvasOrgani").getContext("2d");
        var elmnt = document.getElementById("graf-organi");
        ctxOrgani.canvas.height = 500;
        ctxOrgani.canvas.width = elmnt.clientWidth;
        window.myBarOrgani = new Chart(ctxOrgani, {
          type: 'bar',
          data: barChartDataOrgani,
          options: {
            title:{
              display:true,
              text:"Transakcije priljubljenih organov"
            },
            tooltips: {
              mode: 'label'
            },
            responsive: true,
            scales: {
              xAxes: [{
                stacked: true,
              }],
              yAxes: [{
                stacked: true
              }]
            }
          }
        });

        var ctxPodjetjaPie = document.getElementById("piechart-podjetja").getContext("2d");
        var elmnt = document.getElementById("graf-pie-podjetja");
        ctxPodjetjaPie.canvas.height = 500;
        ctxPodjetjaPie.canvas.width = elmnt.clientWidth;
        window.myPiePodjetja = new Chart(ctxPodjetjaPie, {
          type: 'doughnut',
          data: {
            datasets: [{
              data: [],
              backgroundColor: [],
              davcna: [],
            }],
            labels: []
          },
          options: {
              responsive: true
          }
        });

        var ctxOrganiPie = document.getElementById("piechart-organi").getContext("2d");
        var elmnt = document.getElementById("graf-pie-organi");
        ctxOrganiPie.canvas.height = 500;
        ctxOrganiPie.canvas.width = elmnt.clientWidth;
        window.myPieOrgani = new Chart(ctxOrganiPie, {
          type: 'doughnut',
          data: {
            datasets: [{
              data: [],
              backgroundColor: [],
              sifrapu: [],
            }],
            labels: []
          },
          options: {
              responsive: true
          }
        });
      };

      $(document).ready(function() {
        var podjetja = localStorage.getItem("podjetja")
        if(podjetja && podjetja.length > 0) {
          var podjetjaArray = podjetja.split(',')        

          $.getJSON('/api/priljubljenaPodjSums/'+podjetja, function(dataM) {
            var barve = ['red', 'blue', 'yellow', 'green', 'silver', 'orange', 'magenta', 'pink', 'black', 'grey', 'brown']
            for(var i = 0; i < dataM.seti; i++) {
              barChartData.datasets.push({
                data: dataM.data[i],
                label: dataM.imena[i].popolnoime.substring(0,20)+'...',
                davcna: dataM.davcne[i],
                backgroundColor: 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)'
              })
            }
            window.myBar.update();
          })

          $.getJSON('/api/priljubljenaPodjSestevki/'+podjetja, function(dataM) {
            myPiePodjetja.config.data.datasets[0].data = dataM.znesek;
            for(var i = 0; i < dataM.znesek.length; i++) {
              myPiePodjetja.config.data.datasets[0].backgroundColor.push('rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)')
              myPiePodjetja.config.data.labels.push(dataM.podjetje[i].substring(0,20));
              myPiePodjetja.config.data.datasets[0].davcna.push(dataM.davcna[i])
            }
            window.myPiePodjetja.update();
          })

          var tabela = $('#podjetja').DataTable({
            "ajax": {
              "url": '/api/priljubljenaPodj/'+podjetja,
              "cache": "true"
            },
            "columnDefs": [{
              "targets": 2,
              "data": null,
              "defaultContent": "<button type='button' class='btn btn-outline-danger icon-delete'><i class='fa fa-trash-o'></i> Izbriši</button>"
            },
            {
              className: "dt-right", "targets": [ 1, 2 ]
            }],
            "columns": [
              {"data": "popolnoime"},
              {"data": "davcna"},
            ],
            "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
              $('td:eq(0)', nRow).html('<a href="/podj/' + aData.davcna + '">' + aData.popolnoime + '</a>');
              return nRow;
            },
            language: {
              decimal:        ",",
              thousands:      ".",
              processing:     "Obdelava v teku...",
              search:         "Išči:",
              lengthMenu:     "Prikaži _MENU_ elementov",
              info:           "Elementi od _START_ do _END_ od skupaj _TOTAL_ elementov",
              infoEmpty:      "Ni elementov za prikaz",
              infoFiltered:   "(filtrirano od _MAX_ elementov)",
              infoPostFix:    "",
              loadingRecords: "Rezultati se nalagajo ...",
              zeroRecords:    "Noben element ne ustreza",
              emptyTable:     "Ni podatkov za prikaz",
              paginate: {
                first:      "Prva",
                previous:   "&lt;",
                next:       "&gt;",
                last:       "Zadnja"
              },
              aria: {
                sortAscending:  ": razvrsti naraščajoče",
                sortDescending: ": razvrsti padajoče"
              }
            }
          })
        }
        
        var organi = localStorage.getItem("organi")
        if(organi && organi.length > 0) {
          var organiArray = organi.split(',')

          $.getJSON('/api/priljubljeniOrganiSums/'+organi, function(dataN) {
            for(var i = 0; i< dataN.seti; i++) {
              barChartDataOrgani.datasets.push({
                data: dataN.data[i],
                label: dataN.imena[i].naziv.substring(0,20)+'...',
                sifrapu: dataN.sifrepu[i],
                backgroundColor: 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)'
              })
            }
            window.myBarOrgani.update();
          })

          $.getJSON('/api/priljubljeniOrganiSestevki/'+organi, function(dataM) {
            myPieOrgani.config.data.datasets[0].data = dataM.znesek;
            for(var i = 0; i < dataM.znesek.length; i++) {
              myPieOrgani.config.data.datasets[0].backgroundColor.push('rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)')
              myPieOrgani.config.data.labels.push(dataM.organ[i].substring(0,20));
              myPieOrgani.config.data.datasets[0].sifrapu.push(dataM.sifrapu[i])
            }
            window.myPieOrgani.update();
          })

          var tabelaOrgani = $('#organi').DataTable({
            "ajax": {
              "url": '/api/priljubljeniOrgani/'+organi,
              "cache": "true"
            },
            "columnDefs": [{
              "targets": 2,
              "data": null,
              "defaultContent": "<button type='button' class='btn btn-outline-danger icon-delete2'><i class='fa fa-trash-o'></i> Izbriši</button>"
            },
            {
              className: "dt-right", "targets": [ 1, 2 ]
            }],
            "columns": [
              {"data": "naziv"},
              {"data": "sifra_pu"},
            ],
            "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
              $('td:eq(0)', nRow).html('<a href="/organ/' + aData.sifra_pu + '">' + aData.naziv + '</a>');
              return nRow;
            },
            language: {
              decimal:        ",",
              thousands:      ".",
              processing:     "Obdelava v teku...",
              search:         "Išči:",
              lengthMenu:     "Prikaži _MENU_ elementov",
              info:           "Elementi od _START_ do _END_ od skupaj _TOTAL_ elementov",
              infoEmpty:      "Ni elementov za prikaz",
              infoFiltered:   "(filtrirano od _MAX_ elementov)",
              infoPostFix:    "",
              loadingRecords: "Rezultati se nalagajo ...",
              zeroRecords:    "Noben element ne ustreza",
              emptyTable:     "Ni podatkov za prikaz",
              paginate: {
                first:      "Prva",
                previous:   "&lt;",
                next:       "&gt;",
                last:       "Zadnja"
              },
              aria: {
                sortAscending:  ": razvrsti naraščajoče",
                sortDescending: ": razvrsti padajoče"
              }
            }
          })
        }

        $('#podjetja tbody').on( 'click', 'button.icon-delete', function () {
          var idx = tabela.row($(this).parents('tr')).data().davcna
          tabela
            .row($(this).parents('tr'))
            .remove()
            .draw()
          var id = podjetjaArray.indexOf(idx)
          podjetjaArray.splice(id, 1)
          localStorage.setItem("podjetja", podjetjaArray)

          var indexDavcna = -1;
          for(var i = 0; i < barChartData.datasets.length; i++) {
            if(barChartData.datasets[i].davcna.replace(/'/g, '') == idx) indexDavcna = i
          }
          if(indexDavcna >= 0) {
            barChartData.datasets.splice(indexDavcna, 1)
            window.myBar.update();
          }

          indexDavcna = -1;
          for(var i = 0; i < window.myPiePodjetja.data.datasets[0].davcna.length; i++) {
            if(window.myPiePodjetja.data.datasets[0].davcna[i] == idx) {
              indexDavcna = i
            }
          }
          if(indexDavcna >= 0) {
            window.myPiePodjetja.data.datasets[0].davcna.splice(indexDavcna, 1)
            window.myPiePodjetja.data.datasets[0].data.splice(indexDavcna, 1)
            window.myPiePodjetja.data.datasets[0].backgroundColor.splice(indexDavcna, 1)
            window.myPiePodjetja.data.labels.splice(indexDavcna, 1)
            window.myPiePodjetja.update()
          }
        });
        
        $('#organi tbody').on( 'click', 'button.icon-delete2', function () {
          var idxx = tabelaOrgani.row($(this).parents('tr')).data().sifra_pu
          tabelaOrgani
            .row($(this).parents('tr'))
            .remove()
            .draw()
          var idm = organiArray.indexOf(idxx)
          organiArray.splice(idm, 1)
          localStorage.setItem("organi", organiArray)

          var indexSifrapu = -1;
          for(var i = 0; i < barChartDataOrgani.datasets.length; i++) {
            if(barChartDataOrgani.datasets[i].sifrapu.replace(/'/g, '') == idxx) indexSifrapu = i
          }
          if(indexSifrapu >= 0) {
            barChartDataOrgani.datasets.splice(indexSifrapu, 1)
            window.myBarOrgani.update();
          }

                    indexSifrapu = -1;
          for(var i = 0; i < window.myPieOrgani.config.data.datasets[0].sifrapu.length; i++) {
            if(window.myPieOrgani.config.data.datasets[0].sifrapu[i] == idxx) {
              indexSifrapu = i
            }
          }
          if(indexSifrapu >= 0) {
            window.myPieOrgani.config.data.datasets[0].sifrapu.splice(indexSifrapu, 1)
            window.myPieOrgani.config.data.datasets[0].data.splice(indexSifrapu, 1)
            window.myPieOrgani.config.data.datasets[0].backgroundColor.splice(indexSifrapu, 1)
            window.myPieOrgani.config.data.labels.splice(indexSifrapu, 1)
            window.myPieOrgani.update()
          }
        })

        $('#pobrisi-shrambo').click(function () {
          localStorage.clear();
          $('#opozorilo').html(
            '<div class="alert alert-success alert-dismissible fade show" role="alert">'+
            '  <button type="button" class="close" data-dismiss="alert" aria-label="Close">'+
            '    <span aria-hidden="true">&times;</span>'+
            '  </button>'+
            '  <strong>Uspeh:</strong> Lokalna shramba je izbrisana.'+
            '</div>'
          );
        })
      })      
    </script>
<%- include partial/eof.ejs %>
  </body>
</html>
