<!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-bottom:3px;"><span style="text-transform: uppercase;" th:text="${#locale.language} == 'es' ? ${organ.nomCas}:${organ.nomVal}">nombre centro</span></h5>
                         <h6 ><small style="font-weight: bold;">RUCT: </small><small style="font-weight: bold;" th:text="${organ.ruct}"></small></h6>
                     </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="#tab0" data-toggle="tab" th:text="#{dashboard.menu.summary}" onclick="window.location.hash = 'tab0'">Resumen</a>
                            </li>
                        	<li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab1" data-toggle="tab" th:text="#{dashboard.menu.procedures}" onclick="window.location.hash = 'tab1'">Procedimientos SAIC</a>
                            </li>
                            <li class="nav-item" onclick="adjustTableHeader();">
                                <a class="nav-link" href="" data-target="#tab2" data-toggle="tab" th:text="#{dashboard.menu.docs}" onclick="window.location.hash = 'tab2';">Seguimiento/Acreditación</a>
                            </li>
							<li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab3" data-toggle="tab" th:text="#{dashboard.menu.data}" onclick="window.location.hash = 'tab3'">Indicadores</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="" data-target="#tab4" data-toggle="tab" th:text="#{dashboard.menu.managers}" onclick="window.location.hash = 'tab4'">Responsables</a>
                            </li>
                        </ul>
                        <!--/tabs-->
                        <br>
                        <div id="viewTabsProcYears" class="tab-content">
                        	<div class="tab-pane active" 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 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" 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" th:text="#{dashboard.tree.selector.title}">Ver 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.tree.selector.centre}">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="reportsSpinner"></div>
                            		<div id="treeProcedures"></div>      
                            	</div>      
                            </div>
                            <div class="tab-pane" id="tab2">
								<div th:if="${editable}" style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; width: 100%;">
									<span class="btn btn-info pointer" 
										style="font-size:75%; padding: 5px 8px 3px 8px; margin-left: 25px;" 
										onclick="editOrgan(this)"
										th:attr="data-lugar=${organ.lugar},
												data-tlugar=${organ.tlugar},
												data-nomcas=${organ.nomCas},
												data-nomval=${organ.nomVal},
												data-ruct=${organ.ruct}">
										<i class="fas fa-edit"></i>
									</span>

									<div style="display: flex; gap: 10px; margin-right: 25px;">
										<span class="btn btn-warning pointer" style="font-size:75%; padding: 5px 8px 3px 8px;" onclick="$('#hideDocumentsModal').modal('toggle');">
											<i class="fas fa-eye-slash"></i>
										</span>
										<span class="btn btn-primary pointer" style="font-size:75%; padding: 5px 8px 3px 8px;" onclick="$('#newDocumentModal').modal('toggle');">
											<i class="fa fa-plus"></i>
										</span>
									</div>
								</div>
								<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 class="col-lg-12" id="acredita-container" style="margin-left:0px;margin-top:0px;min-width:100%;width:100%;position:relative;z-index:0;"> 
                            			<strong th:text="#{dashboard.acred.table.title}" style="margin-bottom:50px;">Titulaciones del centro</strong>
										<table id="titsTable" class="table table-striped table-bordered display responsive no-wrap" style="min-width:100%;width:100%;position:relative;z-index:0;">
										    <thead style="min-width:100%;width:100%;">
										        <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.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.codis}"></span>
													</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>
                            <div class="tab-pane" id="tab3">
                            	<div class="row" style="margin-left:0px;">  
                            		<div class="col-lg-4">
                            			<div style="margin-bottom:5px;">
                            				<select class="form-control pointer data-selector data-selector-orig">
                            					<option value="G" selected th:text="#{dashboard.data.sel.g}" th:if="${organ.lugar != 62}">Grado</option>
                            					<option value="M" th:text="#{dashboard.data.sel.m}" th:if="${organ.lugar != 62}">Máster</option>
                            					<option value="D" selected th:text="#{dashboard.data.sel.d}" th:if="${organ.lugar == 62}">Doctorado</option>
                            				</select>
                            				<select class="form-control pointer data-selector data-selector-group">
                            					<option value="2" data-group="G" th:text="#{dashboard.data.sel.estud1}" selected>Satisfacción Estudiantes 1º</option>
                            					<option value="2" data-group="MD" th:text="#{dashboard.data.sel.estud}">Satisfacción Estudiantes</option>
                            					<option value="3" data-group="G" th:text="#{dashboard.data.sel.estud3}">Satisfacción Estudiantes 3º</option>
                            					<option value="4" data-group="GMD" th:text="#{dashboard.data.sel.gradu}">Satisfacción Graduados</option>
                            					<option value="5" data-group="GMD" th:text="#{dashboard.data.sel.prof}">Satisfacción Profesorado</option>
                            					<option value="6" data-group="GMD" th:text="#{dashboard.data.sel.ptgas}">Satisfacción PTGAS</option>
                            					<option value="7" data-group="GMD" th:text="#{dashboard.data.sel.eval}">Evaluación Docente</option>
                            				</select>
                            			</div>
	                            		<div class="data-inds data-inds-2" data-group="GMD" data-id="2"></div>
	                            		<div class="data-inds data-inds-3" data-group="G" data-id="3"></div>
	                            		<div class="data-inds data-inds-4" data-group="GMD" data-id="4"></div>
	                            		<div class="data-inds data-inds-5" data-group="GMD" data-id="5"></div>
	                            		<div class="data-inds data-inds-6" data-group="GMD" data-id="6"></div>
	                            		<div class="data-inds data-inds-7" data-group="GMD" data-id="7"></div>
                            		</div>
	                                <div class="col-lg-8">  
	                                	<div class="data-legend row" style="margin-top:-15px;">
	                                		<div class="col-lg-4" style="text-align:right;">
	                                			<small>
	                                				<span><span class="btn data-legend-c"></span> <span>Centro</span></span>
	                                			</small>
	                                		</div>
	                                		<div class="col-lg-4" style="text-align:right;">
	                                			<small>
	                                				<span><span class="btn data-legend-u"></span> <span>Universidad</span></span>
	                                			</small>
	                                		</div>
	                            		</div>
	                                	<div class="row chart-inds chart-inds-2" data-group="GMD" data-id="2"></div>
	                                	<div class="row chart-inds chart-inds-3" data-group="G" data-id="3"></div>
	                                	<div class="row chart-inds chart-inds-4" data-group="GMD" data-id="4"></div>
	                                	<div class="row chart-inds chart-inds-5" data-group="GMD" data-id="5"></div>
	                                	<div class="row chart-inds chart-inds-6" data-group="GMD" data-id="6"></div>
	                                	<div class="row chart-inds chart-inds-7" data-group="GMD" data-id="7"></div>
	                            	</div> 
	                            </div>
                            </div>
                            <div class="tab-pane" id="tab4">
								<span class="btn btn-primary pointer" id="btnAddManager" style="z-index:100;float:right;margin-right:25px;font-size:75%;padding: 5px 8px 3px 8px;" data-toggle="modal" data-target="#newRoleModal"><i class="fa fa-plus"></i></span>
								<div class="uv-table-group" th:if="${results}" style="cursor: auto; width: 90%;">
									<div class="col-sm-12 uv-table-section" th:each="item : ${resp_titulacions}" style="display: flex; align-items: flex-start; margin-bottom: 15px;">
    									<form id="deleteUserForm" enctype='multipart/form-data' onsubmit="deleteUserRole(event)" style="margin-right: 15px;">
											<div class="form-group">
												<input type="hidden" name="idRol" th:value="${item.rol.idRol}">
												<input type="hidden" name="usuari" th:value="${item.usuari.usuari}">
												<input type="hidden" name="tlugar" th:value="${item.organ.tlugar}">
												<input type="hidden" name="lugar" th:value="${item.organ.lugar}">
												<button class="btn" style="width:40px; height:38px; color: red;" th:title="#{admin.action.delete}" >
													<i class="fas fa-times"></i>
												</button>
											</div>
										</form>

										<div>
											<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 class="col-sm-12 uv-table-section" th:each="item : ${resp_centres}" style="display: flex; align-items: flex-start; margin-bottom: 15px;">
    									<form id="deleteUserForm" enctype='multipart/form-data' onsubmit="deleteUserRole(event)" style="margin-right: 15px;">
											<div class="form-group">
												<input type="hidden" name="idRol" th:value="${item.rol.idRol}">
												<input type="hidden" name="usuari" th:value="${item.usuari.usuari}">
												<input type="hidden" name="tlugar" th:value="${item.organ.tlugar}">
												<input type="hidden" name="lugar" th:value="${item.organ.lugar}">
												<button class="btn" style="width:40px; height:38px; color: red;" th:title="#{admin.action.delete}" >
													<i class="fas fa-times"></i>
												</button>
											</div>
										</form>

										<div>
											<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>
                        </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>

	<div th:if="${editable}" class="modal fade" id="editCentreModal" tabindex="-1" role="dialog" aria-labelledby="editCentreModal" aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title">Editar centro</h5>
					<button type="button" class="close" data-dismiss="modal">&times;</button>
				</div>
				<div class="modal-body">
					<div class="container-fluid">
						<form id="editOrganForm">
							<input type="hidden" id="editLugar" name="lugar">
    						<input type="hidden" id="editTLugar" name="tlugar">
							<div class="uv-table-group-procedure">
								<label>Nombre Castellano</label>
								<input type="text" class="form-control" id="editNomCas" name="nomCasTit">
							</div>
							<div class="uv-table-group-procedure">
								<label>Nombre Valenciano</label>
								<input type="text" class="form-control" id="editNomVal" name="nomValTit">
							</div>
							<div class="uv-table-group-procedure">
								<label>RUCT</label>
								<input type="number" class="form-control" id="editRuct" name="ructTit">
							</div>
						</form>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
					<button class="btn btn-success" type="submit" form="editOrganForm">Confirmar Edición</button>
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade" id="newRoleModal" tabindex="-1" role="dialog" aria-labelledby="newRoleModal" aria-hidden="true" th:if="${#authentication.principal.isAdmin() or #authentication.principal.isGranted()}">
	  <div class="modal-dialog modal-lg">
	    <div class="modal-content">
		    <div class="modal-header">
		        <h5 class="modal-title" th:text="#{admin.managers.newRole}">Añadir responsable</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="newRoleForm" enctype='multipart/form-data' onsubmit="addUserRole(event)" style="margin-top:25px;">
						<input type="hidden" name="centre" th:value="${organ.lugar2}">
						<input type="hidden" name="titulacio" th:value="${organ.lugar}">
						<div class="form-group">
							<label th:text="#{admin.managers.user}">Usuario</label>&nbsp;&nbsp;&nbsp;<span class="pointer" style="color:#007bff;" onclick="newUser();" th:title="#{admin.managers.newUser}"><i id="addUserIcon" class="fas fa-plus"></i></span>
							<div id="userSelectorContainer">
								<select class="selectpicker" id="userSelector" name="usuari" data-dropup-auto="false" data-live-search="true" data-width="100%" data-actions-box="true" required>
							        <option th:each="item : ${users}" th:text="${item.nom}+' '+${item.cognoms}+' ('+${item.email}+')'" th:attr="value=${item.usuari}"></option>
							    </select>
						    </div>
						    <div class="form-group" id="newUserContainer">
						    	<div class="row">
							    	<div class="form-group col-6">
							    		<label  th:text="#{admin.managers.firstname}">Nombre</label>
							    		<input class="form-control" type="text" value="" name="firstname" id="firstname">
							    	</div>
							    	<div class="form-group col-6">
							    		<label th:text="#{admin.managers.lastname}">Apellidos</label>
							    		<input class="form-control" type="text" value=""  name="lastname" id="lastname">
							    	</div>
							    	<div class="form-group col-6">
							    		<label th:text="#{admin.managers.user}">Usuario</label>
							    		<input class="form-control" type="text" value="" name="username" id="username" onkeyup="setEmail();">
							    	</div>
							    	<div class="form-group col-6">
							    		<label  th:text="#{admin.managers.email}">Email</label>
							    		<input class="form-control" type="email" value="" name="email" id="email"> 
							    	</div>
						    	</div>
						    </div>
						</div>
						<div class="form-group">
							<label th:text="#{admin.managers.role}">Rol</label>
							<select class="selectpicker" id="roleSelector" name="idRol" data-dropup-auto="false" data-live-search="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}" required>
						        <option th:each="item : ${roles}" th:text="${#locale.language} == 'es' ? ${item.descripcioCas}:${item.descripcioVal}" th:attr="value=${item.idRol}"></option>
						    </select>
						</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="newRoleForm" th:text="#{global.confirm}">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 = [];
				
		$(document).ready(function(){ 
			layout = new Layout("");
			initTables();
			layout.closeLoadingSpinner(".uv-loading-spinner");	
			
			$('.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');

			$('#newUserContainer').hide();
			$('#userSelector').val('').trigger('change');
			
			treeDocuments = $('#treeDocuments').tree({
				  cascadeSelection: false,
				  cascadeCheck: false,
				  selectionType: 'single',
				  dataSource: '/dashboard/documents/'+ruct
			});

			$('#editOrganForm').on('submit', function(e) {
				e.preventDefault();
				const datosCargados = Object.fromEntries(new FormData(this));
        		console.log("Enviando estos datos:", datosCargados);
				
				$.ajax({
					url: '/organ/centre',
					type: 'POST',
					data: new FormData(this),
					processData: false,
					contentType: false,
					success: function() { 
						$('#editTitulacionModal').modal('hide');
						window.location.href = "/dashboard/" + ruct;
					}
				});
			});
			drawReports(ruct);
			drawGantt(ruct);
			$.get('/dashboard/graphs/list/'+ruct, function(data){
				inds = data;
				inds = inds.map((e, i) => ({...e, idGrafica: data[i].idGrafica.idGrafica, estudi: data[i].idGrafica.estudi}));
				getGraphData();	
			});
					
			editableSettings();

			var hash = window.location.hash;
			if(hash){
				$('.nav-link').removeClass('active');
				$('.tab-pane').removeClass('active');
				$('.nav-link[href="'+hash+'"]').addClass('active');
				$(hash).addClass('active');
			}
			
		});		
		
	function initTables(){
							
		$('#titsTable thead tr')
	        .clone(true)
	        .addClass('filters')
			.addClass('titsFilters')
	        .appendTo('#titsTable thead');
		
		
		tableTits = $('#titsTable').DataTable({
			paging: false, 
			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: '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);
				            
			}
		});
		//setTimeout(function(){$('#titsTable').DataTable().columns.adjust();}, 3000);
		}
		
		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,
					infinite_padding: false,
		            readonly: true,
					//column_width: 20,
		            popup: function(task) {
		                return `
		                  <div class="details-container">
							<h6>${task.titCas}</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: obj.likert ? 1 : 0,
						    beginAtZero: obj.likert ? true : false,
						    ticks: {
						    	beginAtZero: obj.likert ? true : false,
						    	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/cats/'+$(this).val()+'/'+tambit, function(data){
				$('#documentSelector').html('');
				data = data.length > 0 ? data : [];
				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();
			$('.data-selector-group option:not([style*="display: none"]):first')
				.attr('selected', true)
				.siblings()
			  	.removeAttr("selected");
			$(".data-selector-group").val($('.data-selector-group option:not([style*="display: none"]):first').val());
			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){
			openReportsSpinner();
			treeProcedures = $('#treeProcedures').tree({
				  cascadeSelection: false,
				  cascadeCheck: false,
				  selectionType: 'single',
				  lazyLoading: true,
				  dataSource: '/dashboard/procedures/'+ructAttr,
				  dataBinding: function (e) {
					closeReportsSpinner();
				  }
			});
		}

		function openReportsSpinner(){
			var spinner = `<div class="d-flex justify-content-center" style="position:fixed;z-index:9999;top:0;left:0;right:0;bottom:0;margin:auto;width:100%;height:100%;background:rgba(0,0,0,0.25);align-items: center;justify-content:center;">
								<div class="spinner-border text-primary" role="status" style="font-size:150%;text-align:center;width:100px;height:100px;display:flex;margin:0 auto;">
									<span class="sr-only">Loading...</span>
								</div>
							</div>
						  `;
			$('#reportsSpinner').html(spinner);
		}

		function closeReportsSpinner(){
			$('#reportsSpinner').html('');
		}

		function adjustTableHeader(){
			setTimeout(() => {
				$('#titsTable').DataTable().columns.adjust();
			}, 100);
		}

		function editOrgan(button) {
			const data = $(button).data();
			$('#editLugar').val(data.lugar);
			$('#editTLugar').val(data.tlugar);
			$('#editNomCas').val(data.nomcas);
			$('#editNomVal').val(data.nomval);
			$('#editRuct').val(data.ruct);;
			
			$('#editCentreModal').modal('show');
		}

		function newUser(){
			if(!$('#newUserContainer').is(":visible")){
				$('#firstname').val('').attr('required', true);
				$('#lastname').val('').attr('required', true);
				$('#username').val('').attr('required', true);
				$('#email').val('').attr('required', true);
				$('#newUserContainer').show();
				$('#userSelector').attr('required', false);
				$('#userSelectorContainer').hide();
				$('#addUserIcon').removeClass('fa-plus');
				$('#addUserIcon').addClass('fa-minus');
			}
			else{
				$('#firstname').val('').attr('required', false);
				$('#lastname').val('').attr('required', false);
				$('#username').val('').attr('required', false);
				$('#email').val('').attr('required', false);
				$('#newUserContainer').hide();
				$('#userSelector').attr('required', true);
				$('#userSelectorContainer').show();
				$('#addUserIcon').removeClass('fa-minus');
				$('#addUserIcon').addClass('fa-plus');
			}	
		}

		function setEmail(){
			$('#email').val($('#username').val()+'@uv.es');
		}


		function addUserRole(event){
		event.preventDefault(); // Evita que la página se recargue

		const form = document.getElementById('newRoleForm');
		const formData = new FormData(form);

		$.ajax({
			type: "POST",
			url: "/admin/userrole/new",
			data: formData,
			processData: false, // Necesario para FormData
			contentType: false, // Necesario para FormData
			success: function(response) {
				if (response === true) {
					location.reload(); 
				} else {
					alert("Error al añadir el rol");
				}
			},
			error: function() {
				alert("No se pudo conectar con el servidor");
			}
		});
	}

	function deleteUserRole(event){
		event.preventDefault(); // Evita que la página se recargue

		const form = document.getElementById('deleteUserForm');
		const formData = new FormData(form);

		$.ajax({
			type: "POST",
			url: "/admin/userrole/remove",
			data: formData,
			processData: false, // Necesario para FormData
			contentType: false, // Necesario para FormData
			success: function(response) {
				if (response === true) {
					location.reload(); 
				} else {
					alert("Error al eliminar el rol");
				}
			},
			error: function() {
				alert("No se pudo conectar con el servidor");
			}
		});
	}
	</script>

</body>

</html>
