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

<head th:replace="~{layouts/common.html :: head}"></head>
<body id="page-top">

 	<!-- Content -->
	<div class="content uv-content d-flex" id="uv-wrapper" style="margin-top:-20px !important">
		
		<div class="container uv-home-section" 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="uv-table-group-procedure-info">
					<div class="uv-table-title">
						<span><strong>Borradores disponibles de la tarea:</strong></span>

						<div class="row">
							<div class="col-8">
								<select class="selectpicker" id="versionSelector" name="versions" 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,i : ${versions}" th:value="${item.dataMod}" th:text="${item.usuari + ' - ' + item.dataMod}"></option>
								</select>
							</div>
							<div class="col-4"><span class="btn btn-primary pointer" onclick="restoreDraft();">Restaurar</span></div>
						</div>


					</div>
					<hr class="uv-procedure-hr">
				</div>
				<div class="uv-table-group">
					<textarea id="editor" name="evidencia_text" th:text="''"></textarea>
				</div>
				<div class="uv-accordion" style="margin-top:20px;text-align:center;">
					
				</div> 
			</div>
		</div>
	</div>
    <input type="hidden" id="idInstanciaTasca" th:value="${idInstanciaTasca}">

	
	<!-- 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/bootstrap/bootstrap.min.js}"></script>
	<script th:src="@{/js/fa/all.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.responsive.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.rowReorder.min.js}"></script>
	<script th:src="@{/js/bootstrap/dataTables.bootstrap4.min.js}"></script>
	<script th:src="@{/js/jquery-easing/jquery.easing.min.js}"></script>
	<script th:src="@{/js/saic.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:inline="javascript">
	    if (!window.Worker) {
	    	alert(/*[[#{procedures.nosupported}]]*/);
			window.location = '/';
    	}
    	var aliveWorker; 
		var saveWorker;
    	function confirmDelete(){ }
	    function confirmClear(){ }
	    function setSaveInterval(){
	    	console.log('AutoSave enabled');
	    	saveWorker = new Worker(/*[[@{/js/workers/autosave_worker.js}]]*/);
	    	saveWorker.onmessage = triggerSave;
	    }
	    function setAliveInterval(){
	    	console.log('KeepAlive enabled');
	    	aliveWorker = new Worker(/*[[@{/js/workers/alive_worker.js}]]*/);
	    	aliveWorker.onmessage = keepalive;
	    }
	    var tinyplugins = 'preview importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists charmap quickbars checklist tinycomments';
	    var tinytoolbar = 'save | undo redo | bold italic underline strikethrough | forecolor backcolor | fontfamily fontsize | removeformat | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | showcomments | charmap | topdf | fullscreen ';
    	var tinymenu = 'file edit';
    	var tinytable = 'tableinsertrowbefore tableinsertrowafter tabledeleterow';
    	var tinycontextmenu = '';
    	var tinytableappearance = false;
    	var tinytableclass = [];
    	var tinytableresizebars = false;
    	var tinyadvtab = false;
    	var tinyobjectresizing = false;
    	function tinyconfigure(editor){
    		editor.on('keydown', function(e) {
				if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete keycodes
                    try {
                        var elem = tinymce.activeEditor.selection.getNode(); //current caret node
                        console.log(elem);
                        if (elem.classList.contains("mceNonEditable")) {
                        	e.preventDefault();
                            return false;
                        }
                    } catch (e) {console.log(e);}
                }
			});		
			
			editor.ui.registry.addIcon('save', '<i style="font-size:125%;" class="fas fa-save"></i>')
				
			editor.ui.registry.addButton('topdf', {
				icon: 'print',
				tooltip: 'Imprimir a PDF',
		      	onAction: function(_){ 
		      		print_to_pdf(editor.getContent());
		      	}
		    });	
			
			editor.on('FullscreenStateChanged', function () {
				if(tinymce.activeEditor.plugins.fullscreen.isFullscreen()){
					var e = '<span id="exitFullScreen" class="btn btn-primary pointer" style="position:absolute;display:none;float:right;right:15px;top:25px;color:white;background-color:#007bff;padding:8px;cursor:pointer;" onclick="tinymce.activeEditor.execCommand('+"'mceFullScreen'"+');">Volver a SAIC <i class="fas fa-compress-arrows-alt"></i></span>';
					$(e).appendTo($($('.tox-editor-container').get(0)));
					$('#exitFullScreen').show();
				}
				else{
					$('#exitFullScreen').remove();	
					
				}
			});	
    	}
	</script>

  	<script type="text/javascript">

    var locale = "[[${#locale.language}]]";
	var fileInvalid = "[[#{procedures.extensionAlert}]]";
	var fullname = "[[${#authentication.principal.nom + ' ' + #authentication.principal.cognoms}]]";
	var username = "[[${#authentication.principal.usuari}]]";
	var msgsave = "[[#{procedures.editor.msgsave}]]";
	var expiredTxt = "[[#{procedures.session.expired}]]";
	var layout;
	var lastActiveTime = new Date().getTime();
	var manualDraftSave = false;

        $(document).ready(function(){
            layout = new Layout("");
            layout.initTableLayout({paging:false});
            layout.closeLoadingSpinner(".uv-loading-spinner");
            $('#versionSelector').change(getDraft);

            tinymce.init({ 
                selector: '#editor',
                language: locale,
                browser_spellcheck: true,
                plugins: tinyplugins,
                menubar: tinymenu,
                toolbar: tinytoolbar,
                table_toolbar: tinytable,
                tinycomments_author: username,
                tinycomments_author_name: fullname,
                tinycomments_mode: 'embedded',
                tinycomments_can_delete: function(req, done, fail){ done({canDelete: true}); },
                table_advtab: tinyadvtab,
                table_row_advtab: tinyadvtab,
                table_cell_advtab: tinyadvtab,
                table_sizing_mode: 'fixed',
                table_default_styles: {
                    width: '297mm'
                },
                content_style: "body { width: 297mm; max-width: 297mm; font-size: 10pt; font-family: Verdana, Geneva, sans-serif; font-style: normal; font-variant: normal;}",
                font_formats: "Arial=arial,helvetica,sans-serif; Verdana=verdana,geneva;", 
                font_size_formats: '8pt 10pt 12pt 14pt 16pt 18pt 24pt',
                setup: tinyconfigure,
                save_onsavecallback: function(){save_content();},
                content_langs: [
                    {title: 'Español', code: 'es'},
                    {title: 'Valencià', code: 'ca'}],   
                image_advtab: true,
                importcss_append: true,
                height: 700,
                image_caption: true,
                quickbars_selection_toolbar: '',
                toolbar_mode: 'sliding',
                contextmenu: tinycontextmenu,
                table_appearance_options: tinytableappearance,
                table_class_list: tinytableclass,
                table_resize_bars: tinytableresizebars
		    });

			window.setTimeout(getDraft, 2000);

        });

        function getDraft(){
            $.get(`/procedure/draft/${$('#idInstanciaTasca').val()}`, {dataMod: $('#versionSelector').val()}, function(obj){
				var data = $($.parseHTML(obj.text)).find('#editorContent').html();
				tinymce.activeEditor.setContent(obj.text);
			});
        }

		function restoreDraft(){
			$.post(`/procedure/draft/${$('#idInstanciaTasca').val()}`, {dataMod: $('#versionSelector').val()}, function(data){
				if(data === '1'){
					alert('Borrador restaurado correctamente. Cierre esta ventana y actualice la página del procedimiento para ver los cambios.');
				}
				else{
					alert('No se ha podido restaurar el borrador.');
				}
			});

		}

    </script>

</body>

</html>
