$(document).ready(function(e) {
	/***********************************************************************************
		MODAL: SHOW PUBLIC FILE URL
	***********************************************************************************/
	$('body').on('click', '.public_link', function(e) {
		$(document).psendmodal();
		var type		= $(this).data('type');
		var id		= $(this).data('id');
		var token	= $(this).data('token');

		if ( type == 'group' ) {
			var link_base = 'https://diagnosticareapp.it/app/public.php?';
			var note_text = 'Invia questa URL a qualcuno per vedere i contenuti dei gruppi consentiti in accordo con le tue impostazioni della privacy.';
		}
		else if ( type == 'file' ) {
			var link_base = 'https://diagnosticareapp.it/app/download.php?';
			var note_text = 'Invia questo URL a qualcuno per scaricare il file senza accedere o iscriversi.';
		}

		var content =  '<div class="public_link_modal">'+
							'<strong>Click per selezionare e copiare</strong>'+
							'<div class="copied">Copiato con successo negli appunti</div>'+
							'<div class="copied_not">Non riesco a copiare il contenuto negli appunti</div>'+
							'<div class="form-group">'+
								'<textarea class="input-large public_link_copy form-control" rows="4" readonly>' + link_base + 'id=' + id + '&token=' + token + '</textarea>'+
							'</div>'+
							'<span class="note">' + note_text + '</span>'+
						'</div>';
		var title 	= 'URL pubblico';
		$('.modal_title span').html(title);
		$('.modal_content').html(content);
	});

	/***********************************************************************************
		APPLY FORM BULK ACTIONS
	***********************************************************************************/
	$("#do_action").click(function(e) {
		var checks = $("td>input:checkbox").serializeArray();
		var action = $('#action').val();
		if (action != 'none') {
							if (action == 'delete') {
					if (checks.length == 0) {
						alert('Seleziona almeno un elemento per procedere.');
						return false;
					}
					else {
						var msg_1 = 'Stai per eliminare';
						var msg_2 = 'elementi. Sei sicuro di voler continuare?';
						if (confirm(msg_1+' '+checks.length+' '+msg_2)) {
							return true;
						} else {
							return false;
						}
					}
				}

							if (action == 'log_clear') {
					var msg = 'Stai per eliminare tutte le attivit&agrave; dal log. Solo quelle utilizzate per le statistiche rimarranno. Sei sicuro di voler continuare?';
					if (confirm(msg)) {
						return true;
					} else {
						return false;
					}
				}

				if (action == 'log_download') {
					$(document).psendmodal();
					//Cookies.set('log_download_started', 0, { expires: 100 });
					//setTimeout(check_log_download_cookie, 1000);
					$('.modal_content').html('<p class="loading-img">'+
												'<img src="https://diagnosticareapp.it/app/img/ajax-loader.gif" alt="Loading" /></p>'+
												'<p class="lead text-center text-info">Per favore attendi mentre rendo disponibile il tuo download.</p>'
											);
					$('.modal_content').append('<iframe src="https://diagnosticareapp.it/app/includes/actions.log.export.php?format=csv"></iframe>');

					return false;
				}

							if (action == 'unassign') {
					var msg_1 = 'Stai per annullare l\’assegnazione';
					var msg_2 = 'file da questo account. Sei sicuro di voler continuare?';
					if (confirm(msg_1+' '+checks.length+' '+msg_2)) {
						return true;
					} else {
						return false;
					}
				}

							if (action == 'zip') {
                    e.preventDefault();
					var checkboxes = $.map($('input:checkbox:checked'), function(e,i) {
						if (e.value != '0') {
							return +e.value;
						}
					});

					$(document).psendmodal();

					Cookies.set('download_started', 0, { expires: 100 });
					setTimeout(check_download_cookie, 1000);
					$('.modal_content').html('<p class="loading-img"><img src="https://diagnosticareapp.it/app/img/ajax-loader.gif" alt="Loading" /></p>'+
												'<p class="lead text-center text-info">Per favore attendi mentre rendo disponibile il tuo download.</p>'+
												'<p class="text-center text-info">Questa operazione potrebbe richiedere alcuni minuti, a seconda della dimensione dei file.</p>'
											);
					$.get('https://diagnosticareapp.it/app/process.php', { do:"zip_download", files:checkboxes },
						function(data) {
							var url = 'https://diagnosticareapp.it/app/process-zip-download.php?ids=' + data;
							$('.modal_content').append("<iframe id='modal_zip'></iframe>");
							$('#modal_zip').attr('src', url);
						}
					);
				}
		}
		else {
			return false;
		}
	});


		/**
	 * Solution to close the modal. Suggested by remez, based on
	 * https://stackoverflow.com/questions/29532788/how-to-display-a-loading-animation-while-file-is-generated-for-download
	 */
	var downloadTimeout;
	var check_download_cookie = function() {
		if (Cookies.get("download_started") == 1) {
			Cookies.set("download_started", "false", { expires: 100 });
			remove_modal();
		} else {
			downloadTimeout = setTimeout(check_download_cookie, 1000);
		}
	};

		var logdownloadTimeout;
	var check_log_download_cookie = function() {
		if (Cookies.get("log_download_started") == 1) {
			Cookies.set("log_download_started", "false", { expires: 100 });
			remove_modal();
		} else {
			logdownloadTimeout = setTimeout(check_log_download_cookie, 1000);
		}
	};


			if ( $.isFunction($.fn.chosen) ) {
			$('.chosen-select').chosen({
				no_results_text	: "Nessun risultato trovato.",
				width			: "100%",
				search_contains	: true
			});
		}


			if ( typeof CKEDITOR !== "undefined" ) {
			CKEDITOR.replaceAll( 'ckeditor' );
		}

});
