<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">

<head th:replace="~{layouts/common.html :: head}"></head>

<link th:href="@{/js/gijgo/css/gijgo.min.css}" rel="stylesheet"/>
<link th:href="@{/js/jquery/datatables.min.css}" rel="stylesheet"/>
<link th:href="@{/js/frappe-gantt/frappe-gantt.min.css}" rel="stylesheet"/>

<style>
	table.tableizer-table {
		font-size: 12px;
		border: 1px solid #CCC; 
		font-family: Arial, Helvetica, sans-serif;
	} 
	
	.tableizer-table td {
		padding: 4px;
		margin: 3px;
		border: 1px solid #CCC;
	}

	.tableizer-table th {
		background-color: #1B3552; 
		color: #FFF;
		font-weight: bold;
	}

	.chart-container{
		min-height:150px;
	}

	.gantt-container{
		height: calc(100vh - 250px);
	}

	.dropdown-colvis ~ .dropdown-menu {
		transform: translate(-100px, 0px);
	}
</style>

<body id="page-top">

	<!-- Navigation -->
	<nav th:replace="~{layouts/common.html :: navbar}"></nav>
 
 	<!-- Content -->
	<div class="content uv-content d-flex" id="uv-wrapper">
		<div class="bg-light border-right" id="uv-sidebar-wrapper" th:replace="~{layouts/sidebar.html :: sidebar}"></div>
		
		<div class="container uv-home-section navVisible" id="uv-content-wrapper">
			<div class="uv-loading-spinner" th:text="#{global.loading}"></div>
			<div class="col-sm-12"></div>
			<div class="uv-container">
				<div class="row">
                     <div class="col-sm-10">
                         <h5 style="margin-top:10px;"><span style="text-transform: uppercase;" th:text="${#locale.language} == 'es' ? ${organ.nomCas}:${organ.nomVal}">nombre centro</span></h5>
                     </div>
                     <div class="col-sm-2" style="padding:0;">
                     	<img th:src="@{${'/logos/C' + organ.lugar +'.png'}}" class="float-right img-responsive img-rounded" style="width:80px;margin-top:0px;">
                     </div>
                 </div>
				<div class="clearfix"></div>
                <div class="row" style="margin-top:5px;">
                    <div class="card card-default card-body" style="padding: 0 !important;">
                        <ul id="tabsJustified" class="nav nav-tabs nav-justified">
                        	<li class="nav-item">
                                <a class="nav-link active" href="" data-target="#tab3" data-toggle="tab" th:text="#{dashboard.menu.tits}">Titulaciones</a>
                            </li>
                        	<li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab0" data-toggle="tab" th:text="#{dashboard.menu.summary}">Resumen</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab1" data-toggle="tab" th:text="#{dashboard.menu.procedures}">Procedimientos SAIC</a>
                            </li>
							<li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab2" data-toggle="tab" th:text="#{dashboard.menu.docs}">Seguimiento/Acreditación</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab4" data-toggle="tab" th:text="#{dashboard.menu.managers}">Responsables</a>
                            </li>
                        </ul>
                        <!--/tabs-->
                        <br>
                        <div id="viewTabsProcYears" class="tab-content">
                        	<div class="tab-pane" id="tab0">  
                        		<div class="row">
	                        		<div class="col-lg-12" style="margin-top:-10px;margin-bottom:5px;padding-left:30px;padding-right:30px;">  
										<span class="gantt-legend-done"><span th:text="#{dashboard.summary.legend.active}">Finalizado</span></span>
										<span class="gantt-legend-active"><span th:text="#{dashboard.summary.legend.ontime}">En curso</span></span>
										<span class="gantt-legend-expired"><span th:text="#{dashboard.summary.legend.delayed}">Atrasado</span></span>
										<span class="gantt-legend-closed"><span th:text="#{dashboard.summary.legend.closed}">Cerrado</span></span>
										<div class="input-group" style="text-align:right;float:right;margin-right:0px;width:auto !important;">
										    <div class="input-group-prepend">
										    	<span class="input-group-text"><span th:text="#{dashboard.gantt.selector}">Procedimientos de</span></span>
										    </div>
									    	<select class="form-control pointer" id="ganttOrigin" style="max-width:300px;" onchange="changeGanttOrigin();">
												<option th:each="item : ${titulacions}" th:text="${#locale.language} == 'es' ? ${item.nomCas}:${item.nomVal}" th:attr="value=${item.ruct}">Tit 1</option>
											</select>
									  	</div>
	                            	</div> 
	                                <div class="col-lg-12" style="position:relative;z-index:0;">  
	                            		<svg id="gantt"></svg>     
	                            	</div>  
                        		</div>		    
                            </div>
                            <div class="tab-pane" id="tab1">  
                            	<div class="col-lg-12" style="margin-top:-10px;margin-bottom:20px;">  
									<span class="gantt-legend-done"><span th:text="#{dashboard.summary.legend.active}">Finalizado</span></span>
									<span class="gantt-legend-active"><span th:text="#{dashboard.summary.legend.ontime}">En curso</span></span>
									<span class="gantt-legend-closed"><span th:text="#{dashboard.summary.legend.closed}">Cerrado</span></span>
									<div class="input-group" style="text-align:right;float:right;margin-right:0px;width:auto !important;">
									    <div class="input-group-prepend">
									    	<span class="input-group-text">Procedimientos de:</span>
									    </div>
								    	<select class="form-control pointer" id="reportsOrigin" style="max-width:300px;" onchange="changeReportsOrigin();">
											<option selected th:value="${organ.ruct}" th:text="#{dashboard.data.legend.2}">Centre</option>
											<option th:each="item : ${titulacions}" th:text="${#locale.language} == 'es' ? ${item.nomCas}:${item.nomVal}" th:attr="value=${item.ruct}">Tit 1</option>
										</select>
								  	</div>
                            	</div> 
                                <div class="col-lg-12">  
                            		<div id="treeProcedures"></div>      
                            	</div>      
                            </div>
							<div class="tab-pane" id="tab2">
								<span th:if="${editable}" class="btn btn-primary pointer" style="z-index:100;float:right;margin-right:25px;font-size:75%;padding: 5px 8px 3px 8px;" onclick="$('#newDocumentModal').modal('toggle');"><i class="fa fa-plus"></i></span>
								<span th:if="${editable}" class="btn btn-warning pointer" style="z-index:100;float:right;margin-right:10px;font-size:75%;padding: 5px 8px 3px 8px;" onclick="$('#hideDocumentsModal').modal('toggle');"><i class="fas fa-eye-slash"></i></span>
								<div class="row" style="padding-left:25px;width:100%;">  	
                            		<div class="col-lg-12" style="margin-left:-5px;">
                           				<strong th:text="#{dashboard.acred.docs.title}">Documentación</strong>
                           				<div id="treeDocuments"></div>
                            		</div>         
                            	</div> 
                            </div>
                            <div class="tab-pane active" id="tab3">
                            	<div class="col-lg-12" style="margin-left:0px;margin-top:-15px;width:100%;position:relative;z-index:0;">  
									<table id="titsTable" class="table table-striped table-bordered display responsive no-wrap" style="width:100%;position:relative;z-index:0;">
									    <thead>
									        <tr>
									        	<th class="uv-table" th:text="#{dashboard.tits.ruct}">RUCT</th>
									        	<th class="uv-table" th:text="#{dashboard.tits.codes}">Códigos</th>
												<th class="uv-table" th:text="#{dashboard.tits.centre}">Centro</th>
									        	<th class="uv-table" th:text="#{dashboard.tits.tit}">Titulación</th>
									        	<th class="uv-table" th:text="#{dashboard.tits.type}">Tipo</th>
									        	<th class="uv-table" th:text="#{dashboard.acred.table.next}">Próx Accr.</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.acred}">Fecha Accr.</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.renov}">Renovación</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.segui}">Seguimiento</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.verif}">Verificación</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.impla}">Implantación</th>
										        <th class="uv-table" th:text="#{dashboard.acred.table.inter}">InterUniv.</th>
									        </tr>
									    </thead>
										<tbody>
											<tr th:each="item,inRowID : ${titulacions}">
												<td>
													<span th:text="${item.ruct}"></span>
												</td>
												<td>
													<span th:text="${item.codis2}"></span>
												</td>
												<td>
													<a target="_blank" th:href="${'/dashboard/'+item.ruct2}"><span th:text="${#locale.language} == 'es' ? ${item.nomCas2}:${item.nomVal2}"></span></a>
												</td>
												<td>
													<a target="_blank" th:href="${'/dashboard/'+item.ruct}"><span th:text="${#locale.language} == 'es' ? ${item.nomCas}:${item.nomVal}"></span></a>
												</td>
												<td>
													<span th:text="${item.tambit == 'M' ? 'Máster' : item.tambit == 'G' ? 'Grado' : 'Doctorado'}"></span>
												</td>
												<td>
													<span th:text="${item.acreditacio?.grupCurs+' - '+item.acreditacio?.grup}"></span>
												</td>
												<td>
													<span th:text="${#temporals.format(item.acreditacio?.dataAcred, 'dd/MM/yyyy')}"></span>
												</td>
												<td>
													<span th:text="${#temporals.format(item.acreditacio?.dataRenov, 'dd/MM/yyyy')}"></span>
												</td>
												<td>
													<span th:text="${#temporals.format(item.acreditacio?.dataSegui, 'dd/MM/yyyy')}"></span>
												</td>
												<td>
													<span th:text="${#temporals.format(item.acreditacio?.dataVerif, 'dd/MM/yyyy')}"></span>
												</td>
												<td>
													<span th:text="${item.acreditacio?.cursImpla}"></span>
												</td>
												<td>
													<span th:if="${item.acreditacio != null}" th:text="${item.acreditacio?.inter ? 'SI' : 'NO'}"></span>
												</td>
											</tr>
										</tbody>
									</table>
	                            </div>
                            </div>
                            <div class="tab-pane" id="tab4">
                                <div class="uv-table-group" th:if="${results}" style="cursor: auto;">
									<div class="col-sm-12 uv-table-section" th:each="item : ${resp_titulacions}" style="margin-top:20px;">
										<strong><span th:text="${#locale.language} == 'es' ? ${item.rol.descripcioCas}:${item.rol.descripcioVal}"></span>: </strong> 
										<a th:href="'mailto:'+${item.usuari.email}" th:title="${item.usuari.email}" th:text="${item.usuari.nom + ' ' + item.usuari.cognoms}"></a> (<small><span th:text="#{managers.since}">Desde el</span> <span th:text="${item.inici}"></span></small>)
									</div>
									<div class="col-sm-12 uv-table-section" th:each="item : ${resp_centres}">
										<strong th:text="${#locale.language} == 'es' ? ${item.rol.descripcioCas}:${item.rol.descripcioVal}"></strong>
										<br>
										<a th:href="'mailto:'+${item.usuari.email}" th:title="${item.usuari.email}" th:text="${item.usuari.nom + ' ' + item.usuari.cognoms}"></a> (<small><span th:text="#{managers.since}">Desde el</span> <span th:text="${item.inici}"></span></small>)
									</div>
								</div>
                            </div>
                        </div>
                        <!--/tabs content-->
                    </div><!--/card-->
                </div><!--/col-->
			</div>
		</div>
	</div>
	
	<div th:if="${editable}" class="modal fade" id="newDocumentModal" tabindex="-1" role="dialog" aria-labelledby="newDocumentModal" aria-hidden="true">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
		    <div class="modal-header">
		        <h5 class="modal-title">Añadir documento</h5>
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		        	<span aria-hidden="true">&times;</span>
		        </button>
	        </div>
	        <div class="modal-body">
	        	<div class="container-fluid">
			    	<form id="newDocumentForm" style="margin-top:25px;">
			    		<input type="hidden" id="fileLugar" name="lugar" th:value="${organ.lugar}">  
			    		<input type="hidden" id="fileTlugar" name="tlugar" th:value="${organ.tlugar}">  
						<div class="uv-table-group-procedure" id="categoryContainer">
							<label>Categoría</label>
							<select class="form-control selectpicker" id="categorySelector" name="category" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" required>
						    	<option th:each="item : ${categories}" th:text="${#locale.language} == 'es' ? ${item.nomCas}:${item.nomVal}" th:attr="value=${item.idCategoria}">
						    </select>
						</div>
						<div class="uv-table-group-procedure documentSelectorContainer">
							<label>Documento</label>
							<select class="form-control selectpicker" id="documentSelector" name="idCategoria" data-showContent="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" required>
						    </select>
						</div>
						<div class="uv-table-group-procedure documentSelectorContainer">
							<br>
							<div class="custom-file">
								<input type="file" class="custom-file-input pointer" id="customFile" name="file" required>
								<label class="custom-file-label pointer" for="customFile">Seleccionar archivo</label>
							</div>
						</div>
					</form>
				</div>
			</div>
			<div class="modal-footer">
		        <button type="button" class="btn btn-secondary" data-dismiss="modal" th:text="#{global.cancel}">Cancelar</button>
		        <button class="btn btn-success" type="submit" form="newDocumentForm" th:text="#{global.confirm}">Confirmar</button>
	        </div>
	    </div>
	  </div>
	</div>
	
	<div th:if="${editable}" class="modal fade" id="hideDocumentsModal" tabindex="-1" role="dialog" aria-labelledby="hideDocumentsModal" aria-hidden="true">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
		    <div class="modal-header">
		        <h5 class="modal-title">Ocultar todos los documentos visibles</h5>
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
		        	<span aria-hidden="true">&times;</span>
		        </button>
	        </div>
	        <div class="modal-body">
	        	<div class="container-fluid">
			    	<p>Se ocultarán todos los documentos visibles.</p>
				</div>
			</div>
			<div class="modal-footer">
		        <button type="button" class="btn btn-secondary" data-dismiss="modal" th:text="#{global.cancel}">Cancelar</button>
		        <button class="btn btn-success" th:text="#{global.confirm}" onclick="hideAllDocuments();">Confirmar</button>
	        </div>
	    </div>
	  </div>
	</div>

	<!-- contactModal -->
	<div th:replace="~{layouts/common.html :: contactModal}"></div>
	
	<!-- Footer -->
	<footer class="uv-footer uv-footer-text" th:replace="~{layouts/common.html :: footer}"></footer>
	
	<script th:src="@{/js/jquery/jquery.min.js}"></script>
	<script th:src="@{/js/fa/all.js}"></script>
	<script th:src="@{/js/jquery/datatables.min.js}"></script>
	<script th:src="@{/js/jquery-easing/jquery.easing.min.js}"></script>
	<script th:src="@{/js/bootstrap-select/bootstrap-select.js}"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-es_ES.js}" th:if="${#locale.language} == 'es'"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-ca_CA.js}" th:if="${#locale.language} != 'es'"></script>
	<script th:src="@{/js/gijgo/gijgo.min.js}"></script>
	<script th:src="@{/js/frappe-gantt/frappe-gantt.min.js}"></script>
	<script th:src="@{/js/chartjs/chart.js}"></script>
	<script th:src="@{/js/saic.js}"></script>
  
  	<script th:if="${editable}" type="text/javascript">
  		function editableSettings(){
  			$(".custom-file-input").on("change", function() {
  				var fileName = $(this).val().split("\\").pop();
  				$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
  			});
  			
  			$("#newDocumentForm").submit(function(e) {
  			    e.preventDefault();
  			    var formData = new FormData(this);    
  			    $.ajax({
  			        url: "/dashboard/documents",
  			        type: "POST",
  			        data: formData,
  			        processData: false,
  			        contentType: false,
  			        success: function(data){
  			        	treeDocuments.reload();
  			        }
  			    });
  			    $('#categorySelector').val('').trigger('change');
  			    $('#documentSelector').val('').trigger('change');
  			    $('#customFile').val('').trigger('change');
  				$('#newDocumentModal').modal('toggle');
  			});
  		}
  		
  		function hideAllDocuments(){
  			$.post("/dashboard/documents/archive", {tlugar:tlugar, lugar:lugar}, function(){treeDocuments.reload();});
  			$('#hideDocumentsModal').modal('toggle');
  		}
  	</script>
  	
  	<script th:if="${!editable}" type="text/javascript">
  		function editableSettings(){}
  		function hideAllDocuments(){}
  	</script>
  
	<script type="text/javascript">
		var locale = '[[${#locale.language}]]';
		var lugar = '[[${organ.lugar}]]';
		var tlugar = '[[${organ.tlugar}]]';
		var ruct = '[[${organ.ruct}]]';
		var tambit = '[[${organ.tambit}]]';
		var treeProcedures, treeDocuments, ganttChart;
		var tasks = [];
		var inds = [];
		var cursorPosition;
		var tableAcreds, tableTits;
				
		$(document).ready(function(){  
			layout = new Layout("");
			initTables();
			
			$('.data-inds-2').hide();
			$('.chart-container').hide();
			
			$('#categorySelector').val('').trigger('change');
			$('#categorySelector').change(getChildCats);
			
			$('.data-selector-orig').on('change', function(){
				//changeDataOrig($(this).val());
			});
			
			$('.data-selector-group').on('change', function(){
				//toggleDataView($(this).val());
			});
			
			$('.data-selector-orig').trigger('change');
			
			treeDocuments = $('#treeDocuments').tree({
				  cascadeSelection: false,
				  cascadeCheck: false,
				  selectionType: 'single',
				  dataSource: '/dashboard/documents/'+ruct
			});
			drawReports(ruct);
			drawGantt(ruct);
			editableSettings();
			
			layout.closeLoadingSpinner(".uv-loading-spinner");
		});	
		
		function initTables(){
			
			$('#titsTable thead tr')
		        .clone(true)
		        .addClass('filters')
				.addClass('titsFilters')
		        .appendTo('#titsTable thead');
			
			tableTits = $('#titsTable').DataTable({
				paging: true, 
				buttons: [
					{
						extend: "pageLength",
					},
					{
						extend: 'excelHtml5',
						text: '<span><i class="fas fa-file-excel"></i></span>',
						titleAttr: 'Exportar Excel',
						title: 'ListadoTitulaciones',
						exportOptions: {
							columns: ':visible'
						}
					},
					{
						extend: 'csvHtml5',
						text: '<span><i class="fas fa-file-csv"></i></span>',
						titleAttr: 'Exportar CSV',
						title: 'ListadoTitulaciones',
						exportOptions: {
							columns: ':visible'
						}
					},
					{
						extend: 'pdfHtml5',
						text: '<span><i class="fas fa-file-pdf"></i></span>',
						titleAttr: 'Exportar PDF',
						title: 'ListadoTitulaciones',
						exportOptions: {
							columns: ':visible'
						}
					},
					{
						extend: 'colvis',
						text: '<span><i class="fas fa-eye"></i></span>',
						className: 'dropdown-colvis',
						titleAttr: 'Mostrar/Ocultar columnas'
					}
				],
				layout: {
					topStart: null,
			        topEnd: 'buttons'
			    },
				"language":{
					"lengthMenu": "[[#{admin.stats.table.lengthMenu}]]", 
		            "zeroRecords": "[[#{admin.stats.table.zeroRecords}]]",
		            "info": "[[#{admin.stats.table.info}]]",
		            "infoEmpty": "[[#{admin.stats.table.infoEmpty}]]",
		            "infoFiltered": "[[#{admin.stats.table.infoFiltered}]]",
		            "paginate": {
		                "previous": "[[#{admin.stats.table.previous}]]",
		                "next": "[[#{admin.stats.table.next}]]"
		            },
					"buttons": {
						"pageLength": "%d [[#{admin.stats.table.lengthMenu}]]"
					}
				},
				bAutoWidth: false, 
				aoColumns : [
					{ sWidth: '5%' },
					{ sWidth: '5%' },
				    { sWidth: '35%' },
				    { sWidth: '50%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' },
				    { sWidth: '5%' }
				],
				searching: true,
				order:[ [2, 'asc'], [4, 'asc'], [3, 'asc'] ],
				orderCellsTop: true,
				//fixedHeader: true, // Not compatible with android
				info: false,
				responsive: false,
				scrollX: true,
				lengthMenu: [10, 25, 50, 100, { label: 'All', value: -1 }],
				initComplete: function () {
					var api = this.api();
		        	this.api()
		        	.columns()
	                .eq(0)
	                .each(function (colIdx) {
	                    var cell = $('.filters.titsFilters th').eq(
	                        $(api.column(colIdx).header()).index()
	                    );
	                    var title = $(cell).text();
	                    $(cell).html('<input type="text" placeholder="' + title + '" />');
	                    $('input', $('.filters.titsFilters th').eq($(api.column(colIdx).header()).index()))
	                        .off('keyup change')
	                        .on('change', function (e) {
	                            $(this).attr('title', $(this).val());
	                            var regexr = '({search})'; 
	                            cursorPosition = this.selectionStart;
	                            api.column(colIdx)
	                               .search(   
	                                    this.value != ''
	                                        ? regexr.replace('{search}', '(((' + this.value + ')))')	
	                                        : '',
	                                    this.value != '',
	                                    this.value == ''
	                                )
	                                .draw();
	                        })
	                        .on('keyup', function (e) {
								e.preventDefault();
	                            e.stopPropagation();
	                            $(this).trigger('change');
	                            $(this)
	                                .focus()[0]
	                                .setSelectionRange(cursorPosition, cursorPosition);
	                        });
	                });
	                api.column(0).visible(false);
	                api.column(1).visible(false);
	                api.column(5).visible(false);
	                api.column(6).visible(false);
	                api.column(7).visible(false);
	                api.column(8).visible(false);
	                api.column(9).visible(false);
	                api.column(10).visible(false);
	                api.column(11).visible(false);
	                
				}
			});
		}	
		
		function drawGantt(ructAttr){
			$.get('/dashboard/gantt/'+ructAttr, function(data){
				data.forEach(function(d){d.id = 'Task '+d.id;});
				data.at(-1).custom_class += ' gantt-task-last';
				tasks = data;
				ganttChart = new Gantt("#gantt", tasks, {
					on_click: function (task) {
						window.open("/procedure/"+task.id.replace('Task_', ''));
					},
					on_date_change: function(task, start, end) {
						return false;
					},
					on_progress_change: function(task, progress) {
						return false;
					},
					on_view_change: function() {
						var bars = document.querySelectorAll("#gantt" + " .bar-group");
						for (var i = 0; i < bars.length; i++) {
							bars[i].addEventListener("mousedown", stopEvent, true);
						}
						var handles = document.querySelectorAll("#gantt" + " .handle-group");
						for (var i = 0; i < handles.length; i++) {
							handles[i].remove();
						}
					},
					bar_height: 20, 
					bar_corner_radius: 10, 
					arrow_curve: 10, 
					padding: 15,
					view_mode: "Month",
					date_format: "YYYY-MM-DD",
					language: locale,
					draggable: false, 
		            hasArrows: false,
		            highlight_weekend: false,
		            readonly: true,
		            popup: function(task) {
		                return `
		                  <div class="details-container">
		                    <h6>${task.name}</h6>
		                    <p>${task._start.toLocaleDateString()} - ${task._end.toLocaleDateString()}</p>
		                  </div>
		                `;
		        	},
				});
				ganttChart.change_view_mode("Month");
				$('.today-button').trigger('click');
				$('.gantt-task-last').get(0).scrollIntoView({
				            behavior: 'auto',
				            block: 'center',
				            inline: 'center'
				        });
				$(window).scrollTop(0);
			});
		}
		
		function getGraphData(){
			$.get('/dashboard/graphs/inds/'+ruct+'/'+$('.data-selector-orig').val(), function(data){
				$('.chart-inds').html('');
				$('.data-inds').html('');
				createDataTables();
				inds.filter(d => d.estudi.toLowerCase() == $('.data-selector-orig').val().toLowerCase()).forEach(function(o){
					var datasets = [], labels = [];
					var vals = data.filter(d => d.dimension+'_'+d.indicador === o.idGrafica);
					if(vals.length < 1){ console.log(o.idGrafica); return; }
					createChartCanvas(o);
					vals.forEach(function(v){
						var values = [];
						v.valores.forEach(function(v, k){
							values.push(v.valor);
							labels.push(v.curso);
						});
						if(v.ambit === 'C'){
							datasets.push({
						        label: locale == 'es' ? 'Centro' : 'Centre',
						        data: values,
						        borderWidth: 1.2,
						        lineTension: 0.6,
						        borderColor: "rgba(154,240,41,1)",
						        backgroundColor: "rgba(154,240,41,0.5)",
							});
							drawTr(o, values.at(-1), values.at(-2));
						}
						if(v.ambit === 'U'){
							datasets.push({
						        label: locale == 'es' ? 'Universidad' : 'Universitat',
						        data: values,
						        borderWidth: 1.2,
						        lineTension: 0.6,
						        borderColor: "rgba(255,0,0,1)",
						        backgroundColor: "rgba(240,41,67,0.5)",
							});
						}
					});
					labels = Array.from(new Set(labels)).sort();
					drawChart(o, datasets, labels);
					$('.data-selector-group').val(2).trigger('change');
				});			
			});
		}
		
		function createChartCanvas(i){
			 $(`.chart-inds-${i.g}`).append(`<div class="col-lg-4 chart-container"> 
						     			   	     <canvas id="chart_${i.idGrafica}"></canvas>	    
						             	     </div>`);
		}
				
		function createDataTables(){
			$('.data-inds').html('');
			$('.data-inds').each(function(idx){
				var i = $(this).attr('data-id');
				var group = inds.filter(d => d.estudi.toLowerCase() == $('.data-selector-orig').val().toLowerCase()).filter(o => o.g == i);
				var trs = '';
				group.forEach(function(g){
					trs += `<tr id="tr_${g.idGrafica}"></tr>`; 
				});
				$(this).html(`<table class="tableizer-table" style="width:100%;">
					<thead>
						<tr class="tableizer-firstrow">
							<th></th>
							<th style="width:50px;text-align: center;">Actual</th>
							<th style="width:50px;text-align: center;">Anterior</th>
							<th style="width:50px;text-align: center;">Desv.</th>
						</tr>
					 </thead>
					 <tbody>
						 ${trs}
					</tbody>
                </table>`);	
			});
		}
		
		function drawTr(obj, value1, value2){
			var color = (value2 == undefined) ? 'black' : value1 - value2 < 0 ? 'red' : 'green';
			if(obj.negate){
				color = (color == 'black') ? color : value1 - value2 > 0 ? 'red' : 'green';
			}
			$('#tr_'+obj.idGrafica).html(`<td>${locale == 'es' ? obj.nomCas : obj.nomVal}</td>
							   <td>${parseFloat(value1).toFixed(2)}${obj.unitats}</td>
							   <td>${value2 == undefined ? '---' : parseFloat(value2).toFixed(2)+obj.unitats}</td>
							   <td style="color:${color}">${value2 == undefined ? '---' : (value1 - value2).toFixed(2)+obj.unitats}</td>`);
		}
		
		function drawChart(obj, values, labels){
			if(typeof Chart.getChart('chart_'+obj.idGrafica) !== 'undefined'){
				Chart.getChart('chart_'+obj.idGrafica).destroy();
			}
			const ctx = document.getElementById('chart_'+obj.idGrafica);
			var callback;
			if(obj.unitats == '%'){
				callback = function(value, index, values){return value + " %";};
			}
			else{
				callback = function(value, index, values){return value;};
			}
			new Chart(ctx, {
			    type: 'line',
			    data: {
			      labels: labels,
			      datasets: values
			    },
			    options: {
			    	responsive: true,
			        maintainAspectRatio: false,
			    	plugins: {
			    		title: {
			                display: true,
			                text: locale == 'es' ? obj.nomCas : obj.nomVal
			            },
			            legend: {
			                display: false
			            },
			            labels: {
			                render: () => {}
			            }
			        },
					scales: {
					  y: {
						max: obj.likert ? 5 : null,
						min: 0,
					    beginAtZero: true,
					    ticks: {
					    	beginAtZero: true,
					    	autoSkip: !obj.likert,
					    	stepSize: obj.likert ? 1 : null,
					    	stepValue: obj.likert ? 1 : null,
					    	callback: callback
					    },
					    grid: {
					        drawBorder: true
					    },
					    gridLines: {
					        display: true,
					        color: "rgba(255,99,132,0.2)"
					      },
					    stacked: false,
					  }
					}
			    }
			  });
		}
		
		function getChildCats(){
			$.get('/dashboard/documents/catsu/'+$(this).val()+'/'+tambit, function(data){
				$('#documentSelector').html('');
				data.forEach(function(d){
					$(`<option value="${d.idCategoria}" data-content="${locale == 'es' ? d.nomCas : d.nomVal}">${locale == 'es' ? d.nomCas : d.nomVal}</option>`)
					.appendTo($('#documentSelector'));
				});
				$('#documentSelector').selectpicker('refresh');
			});
		}
		
		function toggleDataView(id){
			$('.data-inds').hide();
			$('.data-inds-'+id).show();
			$('.chart-inds').hide();
			$('.chart-inds-'+id).show();
		}
		
		function changeDataOrig(id){
			$('option[data-group]').hide();
			$(`option[data-group*='${id}']`).show();
			getGraphData();
		}
		
		function stopEvent(event) {
			event.preventDefault();
		}
		
		function changeGanttOrigin(){
			ganttChart.clear();
			$('.gantt-container').parent().html('<svg id="gantt"></svg>')
			drawGantt($('#ganttOrigin').val());
		}
		
		function changeReportsOrigin(){
			treeProcedures.destroy();
			drawReports($('#reportsOrigin').val());
		}
		
		function drawReports(ructAttr){
			treeProcedures = $('#treeProcedures').tree({
				  cascadeSelection: false,
				  cascadeCheck: false,
				  selectionType: 'single',
				  dataSource: '/dashboard/procedures/'+ructAttr
			});
		}

	</script>

</body>

</html>