var routerTimeout = 50000; //See router.js; (TODO)
var apyKey = '';
var ajaxRunning = false;
var ajaxRef = null;
var homeHash = 'dashboard';
var rtl = false;
var appWebSocket;
var wsData = null;
var wsConnectionCounter = 0;
var wsRequestDataDreamPDF = null;

//Reset to refresh
var gobalUpload = null;
var globalUploadInProgress = false;
var globalUploadList = [];
var globalUploadCounter = 0;
var globalUploadTimeout = null;
var gloabalUploadErrorHandling = false;

var globalICD10List = [];

//TODO: delete
var globalUploadInterval = null;
var globalUploadBytesPerItem = 0;

var apiKeyElement = document.getElementById('api-key');
if (apiKeyElement !== null) {
	apyKey = document.getElementById('api-key').value;
}

window.addEventListener('online',  function() {
	$('#tm-status-label').html('Online');
});

window.addEventListener('offline', function() {
	$('#tm-status-label').html('Offline');
});

/*window.onbeforeunload = function() {
  return "";
}*/

$(document).ready(function () {
	resizeTranfer();

	//Timer event listener
	setInterval(function() {

		//Start: Patient age
		if($('.check-birth-type').length > 0) {
			var ageType = $('.check-birth-type:checked').val();

			if (ageType == 'date') {
				var dateYear = parseInt($('#request_birth_year').val());
				var dateMonth = parseInt($('#request_birth_month').val());
				var dateDay = parseInt($('#request_birth_month_day').val());
				var dateNow = new Date();
				var dateNowYear = dateNow.getFullYear();
				var dateNowMonth = dateNow.getMonth();
				var dateNowDay = dateNow.getDate();
				var age = dateNowYear - dateYear;
				var ageTime = glbYearsLabel;
				var ageString = '';

				if (dateYear == 0 || dateMonth == 0 || dateDay == 0) {
					$('#calculated-age-number').empty();
					return;
				}

				if (dateNowMonth < (dateMonth - 1)) {
					age--;
				}

				if (((dateMonth - 1) == dateNowMonth) && (dateNowDay < dateDay)) {
					age--;
				}

				if (age == 0) {
					if (dateNowMonth > dateMonth) {
						age = dateNowMonth - dateMonth;
					} else {
						age = dateMonth - dateNowMonth;
					}

					if (dateYear == dateNowYear) {
						age = dateNowMonth - dateMonth;
					} else {
						age = (12-dateMonth)+dateNowMonth;
					}

					ageTime = glbMonthsLabel;
				}

				if (age > 0) {
					ageString = age+' '+ageTime.toLowerCase().substr(0, 1);
				} else {
					ageString = '';
				}

				$('#calculated-age-number').html(ageString);
			} else {
				$('#calculated-age-number').empty();
			}

		}
		//End: Patient age

	}, 100);

});

$(window).resize(function() {
	resizeTranfer();
});

$(document)

	.on('click', 'a', function(e) {
		e.preventDefault();

		var href = $(this).attr('href');
		
		if ($(this).hasClass('external')) {
			var target = $(this).attr('target');
			
			if (target == '_blank') {
				open(href);
			} else {
				document.location.href = href;
			}
			return false;
		}
		
		if ($(this).hasClass('prevent-default')) {
			return false;
		}
		
		if ($(this).hasClass('download')) {
			var forceDownload = parseInt($(this).data('forcedownload'));

			if (forceDownload == 1) {
				document.location.href = href;
			}
			return false;
		}

		//Typically an AJAX link (or link without href)
		if (href == '#' || typeof href === 'undefined') return false;

        if (!isOnline()) {
	    	showMessage(glbAppOffline);
	    } else {
        	window.location.hash = href;
			return false;
		}
	})
	
	.on('click', '.btn-run-process', function() {
		//var processPath = $(this).data('processpath');
		
		//L'elmento process-path si trova nell'element wizard-oto (è una modale)
		
		if ($('#process-path').length > 0) {
			var processPath = $('#process-path').val();
						
			showConfirmCancel(glbAppTitle, glbRunProcess, function() {
			    wsSend(JSON.stringify({op:"run-process", processpath:processPath}), true);
		    });
		}
	})

	//Login / Logout
	.on('submit', '#form-login', function () {
		request('/api/login/access', $(this).serialize(), function(ret) {
			//gotoDest('success-login');
			showLoader();
			document.location.href = '/dashboard-redirect';
			//loadGlobalVariables();
		});
		return false;
	})

	//Logout in nav bar (user menu)
	.on('click', '.btn-logout', function(e) {
		e.preventDefault();

		showConfirmCancel('Log out', glbLogoutMsg, function() {
			request('/api/login/logout', {}, function(ret) {

				showLoader();

				//Reset Upload Manager
				hideTranfer();

				//gotoDest();
				document.location.href = '/';
			});
		});
	})

	.on('click', '.btn-recovery-password', function() {

		$('#recovery_email').removeClass('is-invalid');
		$('#recovery_email').val('');
		$('.recovery-password-form').show();
		$('.btn-send-temporary-password').show();
		$('.recovery-password-done-msg').hide();

		$('#password-recovery-dialog').modal();
	})
	
		.on('click', '.btn-edit-survey', function(e) {
		e.preventDefault();
		var data = $('#survey-form-edit').serialize();
		
		request('/api/survey/surveySave', data, 
		
		function(ret) {
			
			console.log('send data', ret.data);
			
			showMessage(ret.msg, ret.jsArgs);
			
		}, function(ret) {
				showMessage(ret.msg, ret.jsArgs);
				
				if (typeof ret.class !== 'undefined') 
					$('.'+ret.class).addClass('is-invalid');
					
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
		});
		
		return false;
	})
	
	//Private editing (managers)
	.on('submit', '#survey-form-send', function(e) {
		e.preventDefault();
		request('/api/survey/surveySave', $(this).serialize(), function(ret) {
			
			console.log('send data', ret.data);
		});
		
		return false;
	})
	
	//Public anwer survey
	.on('click', '.btn-public-survey-send', function() {
		
		var input_files = $('.is_fileinput_field');
		var max_size = 1048576*20; //20 MB
		
		if (input_files.length > 0) {
			for (var i in input_files) {
				if (input_files[i].files) {					
					if (input_files[i].files[0]) {						
						if (input_files[i].files[0].size > max_size) {
							
							eModal.alert({
								title:glbAppTitle,
								message:"Il file <b>"+input_files[i].files[0].name+"</b> supera le dimensioni di file consentite (20 MB).",
								buttons: [{text: 'OK', style: 'primary', close: true}]
							});
							
							return;
						}									
					}
				}
			}
		}
		
		if (!$('.is_privacy_field').is(':checked')) {
			eModal.alert({
				title:glbAppTitle,
				message:"Prima di inviare il questionario è necessario confermare di aver ricevuto e accettato l'informativa sul trattamento dei dati personali.",
				buttons: [{text: 'OK', style: 'primary', close: true}]
			});
			
			return;
		}
		
		requestUpload($('#public-survey-send')[0], '/api/survey/surveyPublicSend',  
			function(ret) { //success (ret.status ok)

				$('#public-survey-send').fadeOut('fast', function() {
					$('#survey-success-msg').fadeIn();
				});
				
				//console.log(ret);
	    	    				
				if (typeof ret.log !== 'undefined') 
					console.log(ret.log);
			}, 
			
			function(ret) { //error (ret.status err)		
				//showMessage(ret.msg, ret.jsArgs);
				//showMessage("Errore temporaneo, si prega di riprovare.", ret.jsArgs);
				
				eModal.alert({
					title:glbAppTitle,
					message:"Errore temporaneo, si prega di riprovare.",
					buttons: [
						{text: 'Riprova', style: 'primary', close: true, click:function() {
							$('.btn-public-survey-send').trigger('click');
						}},
						{text: glbCancelButton, style: 'warning', close: true}
					]
				});
					
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})
	
	.on('click', '.btn-survey-preview', function() {
		
		var survey_id = $(this).data('surveyid');
				
		$('#dialog-survey-preview').modal();
		$('#dialog-loader').show();
		$('.modal-body-survey-preview').empty();
		
		request('/api/survey/getSurveyAnswers', {survey_id:survey_id}, 
		
			function(ret) { //success (ret.status ok)
				console.log(ret);
				$('#dialog-loader').hide();
				$('.modal-body-survey-preview').html(ret.html);
			}, 
			
			function(ret) { //error (ret.status err)				
				showMessage(ret.msg, ret.jsArgs);	
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			},
			false
		);
	})
	
	.on('click', '.btn-edit-survey-preview', function() {
		
		var survey_type_id = $('#survey_type_list').val();
		
		if (survey_type_id > 0) {
				
			$('#dialog-survey-preview').modal();
			$('#dialog-loader').show();
			$('.modal-body-survey-preview').empty();
			
			request('/api/survey/getSurveyEmptyForm', {survey_type_id:survey_type_id}, 
			
				function(ret) { //success (ret.status ok)
					$('#dialog-loader').hide();
					$('.modal-body-survey-preview').html(ret.html);
				}, 
				
				function(ret) { //error (ret.status err)				
					showMessage(ret.msg, ret.jsArgs);	
					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
				},
				false
			);
		
		}
	})
	
	.on('click', '.btn-survey-resend', function() {
		var survey_id = $(this).data('surveyid');
		var survey_recipient = $(this).data('recipient');
		var survey_uuid = $(this).data('surveyuuid');
		
		eModal
			.alert({
				message:"Reinviare il questionario <b>#"+survey_id+"</b> a <b>"+survey_recipient+"</b>?",
				title:glbAppTitle, 
				buttons: [
					{text: 'Reinvia', style: 'primary',   close: true, click: function() {
						
						request('/api/survey/sendbackSurveyMessage', {survey_uuid:survey_uuid, recipient:survey_recipient}, 
						
							function(ret) { //success (ret.status ok)
								showMessage(ret.msg, ret.jsArgs);
								
								if (typeof ret.log !== 'undefined')
									console.log(ret.log);
									
								document.location.reload();
							}, 
							
							function(ret) { //error (ret.status err)				
								showMessage(ret.msg, ret.jsArgs);	
								if (typeof ret.log !== 'undefined')
									console.log(ret.log);
							},
							true
						);
								
					}},
					{text: glbCancelButton, style: 'warning', close: true, click: function() {}}
				]
		});
	})
	
	.on('click', '.btn-survey-delete', function() {
		var survey_id = $(this).data('surveyid');
		var survey_recipient = $(this).data('recipient');
		var survey_uuid = $(this).data('surveyuuid');
		
		
		eModal
			.alert({
				message:"<div class=\"alert alert-danger\">Eliminare il questionario <b>#"+survey_id+"</b> inviato a <b>"+survey_recipient+"</b>?</div>",
				title:glbAppTitle, 
				buttons: [
					{text: 'Elimina', style: 'danger',   close: true, click: function() {
						
						request('/api/survey/deleteSurvey', {survey_uuid:survey_uuid, survey_id:survey_id}, 
						
							function(ret) { //success (ret.status ok)
								showMessage(ret.msg, ret.jsArgs);
								
								if (typeof ret.log !== 'undefined')
									console.log(ret.log);
									
								document.location.reload();
							}, 
							
							function(ret) { //error (ret.status err)				
								showMessage(ret.msg, ret.jsArgs);	
								if (typeof ret.log !== 'undefined')
									console.log(ret.log);
							},
							true
						);
								
					}},
					{text: glbCancelButton, style: 'warning', close: true, click: function() {}}
				]
		});
		
		
	})

	.on('click', '.btn-print-request', function() {
		var requestId = $(this).data('requestid');
		var context = $(this).data('context');
		var operation = $(this).data('op');
		var self = $(this);

		request('/api/request/generatePDF', {requestId:requestId, context:context, operation:operation},

			function(ret) { //success (ret.status ok)
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);

				//console.log(ret.outputFilePath);
				
				if (operation == 'print') {
					var fileTitle = self.data('filetitle');
					$.fancybox.open({
						src : 'print/'+fileTitle+'?fileTitle='+escape(ret.fileTitle)+'&filePath='+escape(ret.outputFilePath),
						type : 'iframe'
					});
				} else {
					showMessage(ret.msg, ret.jsArgs);
				}

			},

			function(ret) { //error (ret.status err)
				alert(ret.msg);
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})
	
	.on('click', '.btn-send-pdf', function() {
		var requestId = $(this).data('requestid');
		var context = $(this).data('context');
		var operation = $(this).data('op');
		var has_attach = parseInt($(this).data('hasattachments'));
		var attach_list = $(this).data('attachments');
		var self = $(this);
		
		var comment = $.trim($('#request-message-text').val());
		
		if (comment != '') {
			showMessage('Prima di inviare la risposta al paziente salvare il nuovo testo inserito o gli eventuali allegati aggiunti.');
			return;
		}
		
		$('#request-attach-list').empty();
		
		if (has_attach == 1) {
			console.log('attach', attach_list);
			
			if (Array.isArray(attach_list)) {
				var html = '<div class="margin-top-20"><small><p>Se necessario, selezionare uno dei seguenti file da allegare all\'e-mail di risposta:</p>';
				
				html += '<ul class="list-no-type">';
				
				for(var i in attach_list) {
					html += '<li><input type="checkbox" class="attach-ids" value="'+attach_list[i].id+'"> '+attach_list[i].file_title+'</li>';
				}
				
				html += '</ul></small></div>';
				
				$('#request-attach-list').html(html);
			}
		}
		
		$('#modal-sendpdf-dialog').modal();
	})
	
	.on('click', '.btn-pdf-perform-send', function() {
		var requestId = $('#request-id').val();
		var context = $(this).data('context');
		var operation = $(this).data('op');
		var attach_ids = [];
		//var delay = $('#pdf_postponed_date').val();
		var delay = '';
				
		if ($('.attach-ids').length > 0) {
			$('.attach-ids').each(function() {
				
				if ($(this).is(':checked')) {
					attach_ids.push($(this).val());
				}
			});			
		}
		
		$('#modal-sendpdf-dialog').modal('hide');
		
		request('/api/request/generatePDF', {requestId:requestId, context:context, operation:operation, attach_ids:attach_ids, delay:delay},

			function(ret) { //success (ret.status ok)
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);


				showMessage(ret.msg, ret.jsArgs);

			},

			function(ret) { //error (ret.status err)
				//alert(ret.msg);
				showMessage(ret.msg);
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
		
		
	})
	
	.on('click', '.btn-delete-survey-msg-queue', function() {
		var date_string = $(this).data('delaytstring');
		var date_iso = $(this).data('delaytiso');
		var request_id = $(this).data('requestid');
		var mail_id = $(this).data('mailid');
		
		showConfirmCancel('Annullamento ricezione', "Annullare la ricezione programmata per il "+date_string+"?", function() {
			request('/api/request/deleteSurveyMailQueue', {request_id:request_id, mail_id:mail_id},
	
				function(ret) { //success (ret.status ok)
					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
	
	
					//showMessage(ret.msg, ret.jsArgs);
					document.location.reload();
	
				},
	
				function(ret) { //error (ret.status err)
					//alert(ret.msg);
					showMessage(ret.msg);
					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
				}
			);
		});
	})

	.on('click', '.btn-show-responders', function() {

		$('#modal-show-responders').modal();
		var requestId = $(this).data('requestid');

		$('#dialog-loader-responders').show();
		$('.modal-body-responders').empty();

		request('/api/request/getRequestResponders', {requestId:requestId},

			function(ret) { //success (ret.status ok)

				$('#dialog-loader-responders').hide();
				$('.modal-body-responders').html(ret.html);

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			},

			function(ret) { //error (ret.status err)
				alert(ret.msg);
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	.on('click', '.btn-send-temporary-password', function() {

		var email = $('#recovery_email').val();

		request('/api/public/recoveryPassword', {email:email},

			function(ret) { //success (ret.status ok)

				$('#recovery_email').removeClass('is-invalid');
				$('.recovery-password-form').hide();

				$('.recovery-password-done-msg').fadeIn('fast', function() {
					$('.btn-send-temporary-password').hide();
				});

				if (typeof ret.debug !== 'undefined')
					console.log(ret.debug);
			},

			function(ret) { //error (ret.status err)
				//showMessage(ret.msg, ret.jsArgs);
				$('#recovery_email').addClass('is-invalid');
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	//Save the profile user information from Profile page
	.on('click', '.btn-edit-profile', function() {
		var formElement = $('#profile-form-edit')[0];

		requestUpload(formElement, '/api/user/editProfile',
			function(ret) { //success (ret.status ok)
				showMessage(ret.msg, ret.jsArgs);

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs)

				if (typeof ret.class !== 'undefined')
					$('.'+ret.class).addClass('is-invalid');

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	//Save the user information from User edit page (only Administrators)
	.on('click', '.btn-edit-user', function() {

		var formElement = $('#user-form-edit')[0];

		requestUpload(formElement, '/api/user/usersSave',
			function(ret) { //success (ret.status ok)
				showMessage(ret.msg, ret.jsArgs);
			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);

				if (typeof ret.class !== 'undefined')
					$('.'+ret.class).addClass('is-invalid');

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	//Save the Clinical Center information <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	.on('click', '.btn-center-save', function() {
		var formElement = $('#center-form')[0];
		requestUpload(formElement, '/api/center/centerSave',
			function(ret) { //success (ret.status ok)
				showMessage(ret.msg, ret.jsArgs);
				handlePage(ret);
				if(typeof rel.log !== 'undefined');
					console.log(ret.log);
			},
			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);
				if (typeof ret.class !== 'undefined')
					$('.'+ret.class).addClass('is-invalid');
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	.on('change', '#profile_continent_code', function() {
		var continent_code = $(this).val();
		console.log(continent_code);
		$('#profile_country_code').attr('disabled');
		$('#profile_country_code').empty();

		request(
			'api/center/filterCountries',
			{continent_code:continent_code},
			function(ret) { //success (ret.status ok)
				//console.log(ret.countries);
				$('#profile_country_code').empty();
				$.each(ret.countries, function(code, name) {
					$('#profile_country_code').append('<option value=' + code + '>' + name + '</option>');
				});
				$('#profile_country_code').removeAttr('disabled');
			},
			function(ret) { //error (ret.status err)
				//showMessage(ret.msg, ret.jsArgs);
				console.log(ret);
				$('#profile_country_code').attr('disabled');
			},
			false
		);
	})

	.on('click', '.btn-all-medical_specialties', function() {
		var action = true;
		if($(this).data("action") == "deselect") action = false;
		$('.medical_specialty').prop('selected', action);
		$('.medical_specialty').trigger('chosen:updated');
	})

	.on('keypress', '.user-search-ctrl', function(event) {
		if (event.which == 13) {
			event.preventDefault();
			var hash = replaceHashParameter(document.location.hash, 1, 5); //Set page 1
			document.location.hash = replaceTimestamp(hash, 2);
		}
	})

	.on('keypress', '.request-search-ctrl', function(event) {
		if (event.which == 13) {
			event.preventDefault();
			//var hash = replaceHashParameter(document.location.hash, 1, 5); //Set page 1
			var hash = replaceTimestamp(document.location.hash, 2);
			document.location.hash = replaceTimestamp(hash, 2);
		}
	})

	.on('click', '.btn-search-clean', function() {
		request('/api/user/searchClean', null,

			function(ret) { //success (ret.status ok)
				document.location.reload();
			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);
				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	.on('change', '#change-language-list', function() {
		var lang = $(this).val();
		request('/api/login/changeLang', {passedLng:lang}, function(ret) {
			location.reload();
		});
	})

	.on('click', '.btn-dash-show-sess', function() {
		request('/api/dashboard/loadLastSessions', {}, function(ret) {
			$('#admin-last-sessions').html(ret.html);
		});
	})

	.on('click', '.btn-dash-show-subscrip', function() {
		request('/api/dashboard/loadLastSubscriptions', {}, function(ret) {
			$('#admin-last-subscriptions').html(ret.html);
		});
	})

	.on('click', '.btn-dash-show-accesses', function() {
		request('/api/dashboard/loadLastAccesses', {}, function(ret) {
			$('#admin-last-accesses').html(ret.html);
		});
	})

	.on('click', '.btn-load-stats', function() {
		var roleId = $(this).data('roleid');
		request('/api/dashboard/loadStatistics', {roleId:roleId}, function(ret) {
			$('#statistics-'+roleId).html(ret.html);

			//console.log(ret);

			var barOptions = {
		        scales: {
		            yAxes: [{
		                ticks: {
		                    beginAtZero:true
		                }
		            }]
		        },
		        legend: {
					display: false,
					labels: {
						fontColor: 'rgb(0, 0, 0)'
            		}
        		},
        		title: {
					display: false,
					text: ret.chartTitle
        		}
			};

			var triageBar = new Chart($('#triage-bar-char-role-'+roleId), {
			    type: 'bar',
			    data: {
			        labels: ret.barTriageLabels,
			        datasets: [{
			            label: ret.chartTitle,
			            data: ret.TriageValues,
			            backgroundColor: ret.TriageColors,
			            borderColor: ret.TriageBorders,
			            borderWidth: 1
			        }]
			    },
			    options: barOptions
			});

			var triagePie = new Chart($('#triage-doughnut-char-role-'+roleId), {
			    type: 'doughnut',
			    data: {
					datasets: [{
						data: ret.TriagePerc,
						backgroundColor: ret.TriageColors
    				}],

					// These labels appear in the legend and in the tooltips when hovering different arcs
					labels: ret.pieTriageLabels
				},
			    options: null
			});

			var statusBar = new Chart($('#status-bar-char-role-'+roleId), {
			    type: 'bar',
			    data: {
			        labels: ret.barStatusLabels,
			        datasets: [{
			            label: ret.chartTitle,
			            data: ret.StatusValues,
			            backgroundColor: ret.StatusColors,
			            //borderColor: ret.barStatusBorders,
			            //borderWidth: 1
			        }]
			    },
			    options: barOptions
			});

			var statusPie = new Chart($('#status-doughnut-char-role-'+roleId), {
			    type: 'doughnut',
			    data: {
					datasets: [{
						data: ret.StatusPerc,
						backgroundColor: ret.StatusColors
    				}],

					// These labels appear in the legend and in the tooltips when hovering different arcs
					labels: ret.pieStatusLabels
				},
			    options: null
			});

		});
	})

	.on('click', '.goto-link', function(e) {
		e.preventDefault();

		var hash = $(this).data('goto');
		var parent = $(this).parent();

		if (parent.hasClass('nav-item')) {
			$('.nav-item').removeClass('active');
			parent.addClass('active');
		}

		if (hash == 'home') {
			gotoDest(homeHash);
		} else {
			gotoDest(hash);
		}
	})

	.on('focusin', '.form-control', function() {
		$(this).removeClass('is-invalid');
	})

	.on('click', '.recycle-bin-checkbox', function() {
		var counter = $('.recycle-bin-checkbox:checked').length;
		if (counter > 0) {
			$('.btn-recycle-bin').show();
			$('.bin-label').html('('+counter+')');
		} else {
			$('.btn-recycle-bin').hide();
			$('.bin-label').html('');
		}
	})

	.on('click', '.btn-show-tranfer', function(e) {
		e.preventDefault();
		toggleTranfer();
	})

	.on('click', '#tm-arrow', function() {
		hideTranfer();
	})

	.on('click', '#tus-upload-select-dialog', function() {
		var postId = $('#request-id').length > 0 ? parseInt($('#request-id').val()) : -1;
		var postCode = $('#request-unique-code').length > 0 ? $('#request-unique-code').val() : '';

		//Post code is an hidden element in New/Edit Request page (requestEdit.view.php)
	    if (postCode == '') {
		    showMessage(glbNoPostCodeMsg);
		    return;
	    }

		$('#tus-upload-control').trigger('click');
	})

	.on('click', '.btn-delete-upload-item', function() {
		var itemIndex = $(this).data('itemindex');

		if (typeof globalUploadList[itemIndex] !== 'undefined') {
			globalUploadList[itemIndex]['skip'] = true;
			$('#upload-item-btn-delete_'+itemIndex).hide();
			$('#upload-item-row_'+itemIndex).addClass('upload-row-delete-bg');
			$('#upload-item-name_'+itemIndex).addClass('upload-row-deleted-wave');
		}

		//console.log(globalUploadList);
	})

	.on('change', '#tus-upload-control', function(e) {
		//console.log($(this)[0].files);

		prepareFileList($(this)[0].files);
		
		//readSingleFile(e);


	})

	.on('click', '#btn-tus-upload', function() {

	    var file = getCurrentFileToUpload();

		if (file === false) {
		    showMessage(glbFileUploadEmpty);
		    return;
	    }

		uploadTusFile(file);
	})

	.on('dragenter', '#tm-container', function(e) {
		e.stopPropagation();
		e.preventDefault();
	})

	.on('dragover', '#tm-container', function(e) {
		e.stopPropagation();
		e.preventDefault();
		$(this).addClass('drag-hover');
	})

	.on('dragleave', '#tm-container', function(e) {
		$(this).removeClass('drag-hover');
	})

	.on('drop', '#tm-container', function(e) {
		e.stopPropagation();
		e.preventDefault();
		$(this).removeClass('drag-hover');

		var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
		var files = e.target.files || (dt && dt.files);

		if (files) {
			prepareFileList(files);
		}

	})

	.on('dragend', '#tm-container', function(e) {
		$(this).removeClass('drag-hover');
	})

	.on('click', '.btn-clean-upload-list', function() {
		cleanUploadItems();
	})

	.on('change', '.field-file', function() {
		$(this).next('.custom-file-label').html($(this).val().replace(/^.*\\/, ""));
	})

	.on('click', '.btn-countries-hand', function() {
		var leftHandId = $(this).data('lefthand');
		var rightHandId = $(this).data('righthand');
		var ids = [];

		$('#'+leftHandId+' option:selected').each(function(){
			ids.push(this.value);
		});

		if (ids.length > 0) {
			request('api/user/getCCentersByCountries', {ids:ids}, function(ret) {
				$('#'+rightHandId+' option:selected').prop('selected', false);
				$('#'+rightHandId).trigger("chosen:updated");

				for(var i = 0; i<ret.ids.length; i++) {
					$('#'+rightHandId+' option[value="'+ret.ids[i]+'"]').prop('selected', true);
					$('#'+rightHandId).trigger("chosen:updated");
				}
			});
		}
	})

	.on('click', '.check-birth-type', function() {
		var value = $(this).val();

		$('.birth-date-placeholder').hide();
		$('.birth-as-date').removeClass('birth-as-date-visible');

		if (value == 'date') {
			$('.birth-as-date').show();
			$('.birth-as-number').hide();
		} else {
			$('.birth-as-date').hide();
			$('.birth-as-number').show();
		}
	})

	.on('click', '.btn-request-sending-preview', function() {

		$('#request-preview-loader').show();
		$('#request-preview-content').empty();
		$('.btn-request-save-popup').prop('disabled', true);

		var data = $('#request-save').serialize();

		$('#modal-sending-preview').modal();

		request('/api/request/requestPreview', data,

			function(ret) { //success (ret.status ok)

				$('#request-preview-loader').hide();
				$('#request-preview-content').html(ret.html);

				//$('.btn-request-save-popup').prop('disabled', true);

				if (typeof ret.jsonData.userCount !== 'undefined') {
					if (parseInt(ret.jsonData.userCount) > 0) {
						$('.btn-request-save-popup').prop('disabled', false);
					} else {
						$('.btn-request-save-popup').prop('disabled', true);
					}
				}

			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);

				$('#request-preview-loader').show();
				$('#request-preview-content').empty();
				$('.btn-request-save-popup').prop('disabled', true);

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})

	.on('click', '.btn-request-save', function() {

		var data = $('#request-save').serialize();
		var operation = $(this).data('operation');
		var fileCounter = 0;
		var attachment = getCurrentFileToUpload();
		var postCode = $('#request-unique-code').length > 0 ? $('#request-unique-code').val() : null;


		data += '&data%5Boperation%5D%5Bvalue%5D='+operation;
		
		//Count the files to upload (by tus protocol)
		if (globalUploadList.length > 0) {
			for(var i = 0; i < globalUploadList.length; i++) {
				if (typeof globalUploadList[i].skip === 'undefined') {
					if (typeof globalUploadList[i].postCode !== 'undefined') {
						if (globalUploadList[i].postCode == postCode) {
							fileCounter++;
						}
					}
				}
			}
		}

		//Has files or doesn't
		if (fileCounter > 0) {
			data += '&data%5Bhas_files%5D%5Bvalue%5D=1&data%5Bfiles_counter%5D%5Bvalue%5D='+fileCounter;
		} else {
			data += '&data%5Bhas_files%5D%5Bvalue%5D=0&data%5Bfiles_counter%5D%5Bvalue%5D=0';
		}

		//console.log(fileCounter);

		request('/api/request/requestSave', data,
			function(ret) { //success (ret.status ok)
				
				/*if ($('#dream_code').length > 0) {
					var rcode = $('#request-unique-code').val();
					var idCartella = $.trim($('#dream_code').val());
					if (idCartella != '') 
						wsSend(JSON.stringify({op:"write-record", rcode:rcode, username:$('#user-username').val(), idCartella:idCartella}), false);
						
					console.log({op:"write-record", rcode:rcode, username:$('#user-username').val(), idCartella:idCartella});
				}*/

				showMessage(ret.msg, ret.jsArgs);

				/*$('#request-preview-loader').hide();
				$('#request-preview-content').html(ret.html);
				$('#modal-sending-preview').modal();*/

				globalICD10List = [];

				if (attachment !== false) {
					if (!globalUploadInProgress) {
						uploadTusFile(attachment);
					}
			    }

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);

				if (typeof ret.class !== 'undefined')
					$('.'+ret.class).addClass('is-invalid');

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			}
		);
	})
	.on('click', '.delete-attach', function() {
		var attachId = $(this).data('attachid');
		var attachName = $(this).data('attachname');
		var attachTitle = $(this).data('attachtitle');

		showConfirmCancel(glbAppTitle, gblDeleteAttachMsg+'<br><br>'+attachTitle, function() {
			request('/api/request/requestDeleteAttach', {attachId:attachId, attachName:attachName, attachTitle:attachTitle},
	            function(ret) { //Success
		            if (typeof ret.attachId !== 'undefined') {
						$('#attach-row-id-'+ret.attachId).remove();
		            }
	            },
	            function(ret) {
		            showMessage(ret.msg, ret.jsArgs);
	            }, //Error
	            true //Show the loader
	        );
		});
	})

	.on('click', '.btn-icd10-open', function() {
		$('#modal-icd10-dialog').modal();
	})

	//ECD-10 dialog (New/Edit Request)
	.on('click', '.icd10-get-list', function() {
		var icd10Id = $(this).data('icd10id'); //Category id
		var getList = $(this).hasClass('icd10-list-empty') ? true : false;
		var element = $(this);
		var selectedDeseases = [];

		$('#card-body-'+icd10Id).show();
		$('#dialog-loader-'+icd10Id).show();

		//In Draft mode some deseases could be already selected
		if ($('.icd10-selected-desease').length > 0) { //The div list of choosen deseases in ICD-10 box
			$('.icd10-selected-desease').each(function() {
				selectedDeseases.push($(this).data('deseaseid'));
			});
		}

		//Get the deseases list only if the list is currently empty
		if (getList) {
			request('/api/request/requestGetDeseases', {icd10Id:icd10Id, selectedDeseases:selectedDeseases},
				function(ret) { //success (ret.status ok)

					if (typeof ret.html !== 'undefined') {
						element.removeClass('icd10-list-empty');
						$('#desease-list-'+icd10Id).html(ret.html);
					}

					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
				},

				function(ret) { //error (ret.status err)
					showMessage(ret.msg, ret.jsArgs);
				},
				false
			);
		} else {
			if ($('#desease-list-'+icd10Id).is(':visible')) {
				$('#desease-list-'+icd10Id).slideUp();
				$('#card-body-'+icd10Id).hide();
			} else {
				$('#desease-list-'+icd10Id).slideDown();
				$('#card-body-'+icd10Id).show();
			}
		}

	})

	//Click on ICD-10 checkboxes
	.on('click', '.desease-id-checkbox', function() {
		//setDeseaseCheckboxesList();

		var label = $(this).data('label');
		var id = $(this).val();

		if ($(this).is(':checked')) {
			globalICD10List[id] = label;
		} else {
			delete globalICD10List[id];
		}

		$('#icd10-list-content').empty();

		for (var id in globalICD10List) {
			$('#icd10-list-content').append('<div><small><span class="icon-checkmark"></span> '+globalICD10List[id]+'</small></div>');
		}

		//console.log(globalICD10List);
	})

	.on('keyup', '#icd10-search', function(event) {
		if (event.which != 13) {
			var len = $(this).val().length;
			var keyword = $(this).val();
			var elem = $(this);
			var lang = $('input:radio.search-langs:checked').val();
			var selectedDeseases = [];

			//In Draft mode some deseases could be already selected
			if ($('.icd10-selected-desease').length > 0) { //The div list of choosen deseases in ICD-10 box
				$('.icd10-selected-desease').each(function() {
					selectedDeseases.push($(this).data('deseaseid'));
				});
			}

			if (len > 2) {
				$(this).addClass('ajax-loader-search');
				//$(this).prop('readonly', true);

				request('/api/request/requestSearchDesease', {keyword:keyword, lang:lang, selectedDeseases:selectedDeseases},
					function(ret) { //success (ret.status ok)

						elem.removeClass('ajax-loader-search');
						elem.prop('readonly', false);

						if (typeof ret.html !== 'undefined') {
							$('#icd10-search-results').html(ret.html);
						}

						if (typeof ret.log !== 'undefined')
							console.log(ret.log);
					},

					function(ret) { //error (ret.status err)
						//showMessage(ret.msg, ret.jsArgs);
						elem.removeClass('ajax-loader-search');
						elem.prop('readonly', false);
					},
					false
				);

			} else {
				$('#icd10-search-results').empty();
				$(this).removeClass('ajax-loader-search');
				elem.prop('readonly', false);
			}

			//console.log(len);
		}
	})

	.on('click', '.derma-image-wrapper', function() {

		var type = $(this).data('type');
		var checkId = 'derma-position-check-'+type;
		var label = $(this).find('.derma-title').html();
		var wrapperType = $(this).data('wrappertype');
		var checkBoxClass = $(this).data('checkboxclass');

		if (wrapperType == '' || wrapperType == null) {
			wrapperType = 'position-wrapper-derma';
		}

		if (checkBoxClass == '' || checkBoxClass == null) {
			checkBoxClass = 'derma-position-check';
		}

		if ($(this).hasClass('derma-image-selected')) {
			$(this).removeClass('derma-image-selected');
			$('#'+checkId).prop('checked', false);
		} else {
			$(this).addClass('derma-image-selected');
			$('#'+checkId).prop('checked', true);
		}

		setWizardCheckboxesList(checkBoxClass, wrapperType);
	})

	.on('click', '.search-langs', function() {
		$('#icd10-search').val('');
		$('#icd10-search-results').empty();
		$('#icd10-search').focus();
	})
	
	/*.on('click', '.btn-request-choose-op', function() {
		$('#modal-request-choose-op').modal();
	})
	
	.on('click', '.btn-perform-saving', function() {
		var value = $("input[name='choose_save']:checked").val();
		
		alert(value);
	})*/

	.on('click', '.btn-send-message', function() {

		var requestID = $('#request-id').val();
		var centerID = $('#center-id').val();
		var message = $('#request-message-text').val();
		var newStatus = '';
		var attachment = getCurrentFileToUpload();
		var requestSpecialtyList = $('#request-spec-list').val(); //Request medical specialties
		var specialtyFwList = $('#request-fw-spec-list').val(); //Added medical specialties
		var hasAttachments = attachment !== false ? true : false;

		//Check
		var postCode = $('#request-unique-code').length > 0 ? $('#request-unique-code').val() : null;

		if ($('#request-new-status').length > 0) {
			newStatus = $('#request-new-status').val();
		}

		//specialtyList = specialtyFwList != '' ? requestSpecialtyList+','+specialtyFwList : requestSpecialtyList;
		specialtyList = specialtyFwList != '' ? specialtyFwList : '';

		request('/api/request/requestSendMessage', {requestID:requestID, centerID:centerID, message:message, newStatus:newStatus, specialtyList:escape(specialtyList), hasAttachments:hasAttachments},
			function(ret) { //success (ret.status ok)

				if (typeof ret.html !== 'undefined') {
					$('#request-comment-id').val(ret.commentID);
					$('#request-comment-wrapper').html(ret.html);
					$('#request-message-text').val('');

					if (typeof ret.action !== 'undefined' && ret.action == 'refresh') {
						document.location.hash = replaceTimestamp(document.location.hash, 2);
					}

					if (attachment !== false) {
						if (!globalUploadInProgress) {
							uploadTusFile(attachment);
						}
				    }
				}

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);
			},

			function(ret) { //error (ret.status err)
				showMessage(ret.msg, ret.jsArgs);
			},
			true
		);
	})

	.on('click', '.btn-show-referral-list', function() {
		var elem = $(this);
		$('.request-referral-ms-list').slideDown('fast', function() {
			elem.fadeOut();
		});
	})

	//Open the Objective (General) Wizard Dialog
	.on('click', '.btn-wiz-obj-open', function() {
		$('#modal-wizard-objective-dialog').modal();
	})

	.on('click', '.btn-wiz-derma-open', function() {
		$('#modal-wizard-derma-dialog').modal();
	})

	.on('click', '.btn-wiz-oto-open', function() {
		$('#modal-wizard-oto-dialog').modal();
	})

	.on('click', '.btn-wiz-cardio-open', function() {
		$('#modal-wizard-cardio-dialog').modal();
	})

	//Click on the Wizard Dialogs' checkbox (to populate the list in the page)
	.on('click', '.request-exam-checkbox', function() {
		var checkboxClass = $(this).data('checkboxclass');
		var WizardContainer = $(this).data('wizardcontainer');

		setWizardCheckboxesList(checkboxClass, WizardContainer);
	})

	.on('click', '.btn-refresh-list', function() {
		document.location.hash = replaceTimestamp(document.location.hash, 2);
	})

	.on('click', '.btn-cc-dialog', function(e) {
		e.preventDefault();
		var lat = $(this).data('cclat');
		var lng = $(this).data('cclng');

		$('#modal-cc-dialog').one('shown.bs.modal', function() {
			initMap(lat, lng);
		}).modal();
	})

	//Also launched router.js #/requests-edit/
	.on('change', '#request_cc', function() {
		var centerId = parseInt($(this).val());
		var elem = $('#request-referral-ms');
		var elemList = $('#request_referral_ms_chosen .chosen-choices');
		elemList.addClass('chosen-ajax-loader');
		
		if (centerId == 114) { //DREAM_ITALY
			$('.cc-wrapper').removeClass('col-lg-5');
			$('.cc-wrapper').addClass('col-lg-2');
			$('.dream-italy-wrapper').show();
			$('.sportellocura-wrapper').hide();
		} else if (centerId == 7 || centerId == 115 || centerId == 116) { //Sportello Cura
			$('.cc-wrapper').removeClass('col-lg-5');
			$('.cc-wrapper').addClass('col-lg-2');
			$('.dream-italy-wrapper').hide();
			$('.sportellocura-wrapper').show();
		} else {
			$('.cc-wrapper').removeClass('col-lg-2');
			$('.cc-wrapper').addClass('col-lg-5');
			$('.dream-italy-wrapper').hide();
			$('.sportellocura-wrapper').hide();
			//clearCareGiverFields();
		}

		if (!isNaN(centerId)) {
			
			request('/api/request/getSpecialtiesPerCenter', {centerId:centerId},
				function(ret) { //success (ret.status ok)

					if (typeof ret.specialties !== 'undefined') {
						elem.empty();
						$.each(ret.specialties, function() {
							elem.append('<option value="'+ this.value +'">'+ this.text +'</option>');
						});
						elem.trigger("chosen:updated");

						elemList.removeClass('chosen-ajax-loader');
					}

					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
				},

				function(ret) { //error (ret.status err)
					showMessage(ret.msg, ret.jsArgs);
					elemList.removeClass('chosen-ajax-loader');
				},
				false,
				true
			);
		} else {
			elem.empty();
			elem.trigger("chosen:updated");
			elemList.removeClass('chosen-ajax-loader');
		}
	})

	.on('click', '.btn-delete-request', function() {
		showConfirmCancel(glbAppTitle, glbDeleteRequest, function() {

			var requestId = $('.btn-delete-request').data('requestid');

			request('/api/request/requestDelete', {requestId:requestId},
				function(ret) { //success (ret.status ok)

					if (typeof ret.redirect !== 'undefined')
						gotoDest(ret.redirect);

					if (typeof ret.log !== 'undefined')
						console.log(ret.log);
				},

				function(ret) { //error (ret.status err)
					//showMessage(ret.msg, ret.jsArgs);
					alert(ret.msg);
				},
				true
			);
		});
	})
	.on('click', '.btn-ws-send-code', function() {
		var code = $.trim($('#dream_code').val());
		if (code != '') {
			wsSend(JSON.stringify({op:"sending-code", code:code}));
		}
	})
	.on('click', '.btn-request-trigger-open', function() {
		var requestId = $(this).data('requestid');
		$('#btn-open-request-'+requestId).trigger('click');
	})
	.on('click', '.btn-show-dream', function() {
		$('#modal-dream-dialog').modal();

		var requestId = $('.btn-show-dream').data('requestid');

		$('.modal-body-dream').empty();
		$('#dialog-loader-dream').show();

		request('/api/request/getDreamInformation', {requestId:requestId},
			function(ret) { //success (ret.status ok)

				//var MONTHS = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

				if (typeof ret.html !== 'undefined') {
					$('.modal-body-dream').html(ret.html);

					for (var i in ret.chartYears) {

						var currentYear = ret.chartYears[i];

						var config = {
							type: 'line',
							data: {
								labels: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
								datasets: [{
									label: 'TAmin',
									backgroundColor: window.chartColors.red,
									borderColor: window.chartColors.red,
									data: ret.dataValues[currentYear].TAmin,
									fill: false,
									spanGaps: true
								}, {
									label: 'TAmax',
									fill: false,
									backgroundColor: window.chartColors.blue,
									borderColor: window.chartColors.blue,
									data: ret.dataValues[currentYear].TAmax,
									spanGaps: true
								}, {
									label: 'FC',
									fill: false,
									backgroundColor: window.chartColors.green,
									borderColor: window.chartColors.green,
									data: ret.dataValues[currentYear].FC,
									spanGaps: true
								}]
							},
							options: {
								responsive: true,
								title: {
									display: true,
									text: currentYear
								},
								tooltips: {
									mode: 'index',
									intersect: false,
								},
								hover: {
									mode: 'nearest',
									intersect: true
								},
								scales: {
									xAxes: [{
										display: true,
										scaleLabel: {
											display: true,
											labelString: 'Month'
										}
									}],
									yAxes: [{
										display: true,
										scaleLabel: {
											display: true,
											labelString: 'Value'
										}
									}]
								}
							}
						};

						var ctx = document.getElementById('daily-chart-values-'+ret.chartYears[i]).getContext('2d');
						window.myLine = new Chart(ctx, config);

					}

				}

				if (typeof ret.log !== 'undefined')
					console.log(ret.log);

				$('#dialog-loader-dream').hide();
			},

			function(ret) { //error (ret.status err)
				//showMessage(ret.msg, ret.jsArgs);
				alert(ret.msg);
				$('#dialog-loader-dream').hide();
			},
			false
		);
	})
	.on('click', '.btn-rqst-dwnl-logs', function() {
		var userId = $('#rqs-lgs-user').val();
		var reqId = $('#rqs-lgs-id').val();

		document.location.href='/download-logs?userId='+userId+'&reqId='+reqId;
	})
	.on('click', '#checkall', function() {
		$('.check-list-item').prop('checked', $(this).prop('checked'));
	})
	.on('click', '.btn-export-users', function() {
		var formData = $('#users-advanced-search-list').serialize();

		request('/api/user/exportUsers', {formData:formData},
			function(ret) { //success (ret.status ok)
				document.location.href = '/download-userexport/index.php?fileName='+ret.dwnFileName+'&filePath='+ret.dwnFilePath;
				console.log(ret);
			},

			function(ret) { //error (ret.status err)
				//showMessage(ret.msg, ret.jsArgs);
				showMessage(ret.msg, ret.jsArgs);
				console.log(ret);
			},
			true
		);
	})
	.on('click', '.handle-more-details', function() {
		if ($('.field-moredetails').hasClass('show-moredtails')) {
			$('.field-moredetails').removeClass('show-moredtails');
			$('.field-moredetails').addClass('hide-moredtails');
		} else {
			$('.field-moredetails').removeClass('hide-moredtails');
			$('.field-moredetails').addClass('show-moredtails');
		}
	})
	.on('change', '#request_cgprovince', function() {
		
		var province_id = parseInt($(this).val());		
		var selected_city_id = $('#request_cgcity_selected').val()
				
		$('#request_cgcity').empty();
		$('#request_cgcity').prop('disabled', true);
		
		if (province_id > 0) {
			request('/api/request/getCitiesByProvince', {province_id:province_id, selected_city_id:selected_city_id}, 
				function(ret) { //success (ret.status ok)
					$('#request_cgcity').append(ret.html);
					$('#request_cgcity').prop('disabled', false);
				}, 
				
				function(ret) { //error (ret.status err)				
					showMessage(ret.msg, ret.jsArgs);
					$('#request_cgcity').prop('disabled', true);
					console.log(ret);
				},
				false,
				true
			);
		}
		
	})
	
	.on('click', '.btn-sportellocura-send-code', function() {
		var url = $('#sportellocura-endpoint').val();
		var apyKey = $('#sportellocura-apikey').val();
		var survey_id = $('#sportellocura_code').val();
		
		clearCareGiverFields();
		
		request('/api/request/getSportelloCura', {survey_id:survey_id}, 
			function(ret) { //success (ret.status ok)
				console.log(ret);
				var empty_text = 'Vedi scheda paziente';
				
				if (ret.output.status == 'err') {
					showMessage(ret.output.msg);
					$('#sportellocura-survey-data').val('');
					$('#sportellocura_code').val('');
					return;
				}
				
				$('#sportellocura-survey-data').empty();
				
				if (ret.output.survey != null && typeof ret.output.survey.id !== 'undefined') {
					$('#request_name').val(ret.output.survey.name);
					$('#request_surname').val(ret.output.survey.surname);
				}
				
				$('#request_gender').val(ret.output.survey.sex);
				
				///Birt date///
				if (ret.output.survey.birthdate != null) {
					var birthDate = new Date(ret.output.survey.birthdate);
					var year = birthDate.getFullYear();
					var month = parseInt(birthDate.getMonth())+1;
					var day = birthDate.getDate();

					$('#request_birth_year').val(year);
					$('#request_birth_month').val(month);
					$('#request_birth_month_day').val(day);

					$('#birth-as-date-radio').trigger('click');
            	}
            	///Birt date///
            	
            	if (ret.output.survey.notes != null && $.trim(ret.output.survey.notes) != '') {
            		$('.field-request_mainquestion').html(stringfyNull(ret.output.survey.notes));
            	} else {
	            	$('.field-request_mainquestion').html(empty_text);
            	}
            	
            	$('#request_medremarks').html(empty_text);
            	$('#request_medicalhistory').html(empty_text);
            	
            	$('#sportellocura-survey-data').val(JSON.stringify(ret.output.survey));
            	
            	$('#request_cgphone').val(stringfyNull(ret.output.survey.phone));
				$('#request_cgemail').val(stringfyNull(ret.output.survey.email));
				
				//Show more details controls
				if ($('.field-moredetails').hasClass('hide-moredtails')) $('.field-moredetails').removeClass('hide-moredtails');
				if (!$('.field-moredetails').hasClass('show-moredtails')) $('.field-moredetails').addClass('show-moredtails');
				
				$('#request-referral-ms').val('');
					
				$('#request-referral-ms').val(ret.output.survey.ms);
					
				$('#request-referral-ms').trigger('chosen:updated');
				
				$('#request-privacy-0').prop('checked', true);
				
				//Attachments
            	var f_name = '';
            	
            	if (ret.output.attach.length > 0) {
	            	for (var i in ret.output.attach) {
		            			            	
		            	var file_title = ret.output.attach[i].file_title != null ? ret.output.attach[i].file_title : 'file_'+Math.random().toString(36).substr(2, 9);
		            		            			            	
		            	$('#request_cg_file_list').append('<li class="list-group-item">'+file_title+'</li>');
		            	$('#request_cg_input_list').append('<input type="hidden" name="data[cg]['+i+'][filename]" value="'+file_title+'"><input type="hidden" name="data[cg]['+i+'][filedata]" value="'+ret.output.attach[i].data+'">');
	            	}
            	}
				
			}, 
			
			function(ret) { //error (ret.status err)				
				showMessage(ret.msg, ret.jsArgs);
				console.log(ret);
			},
			true
		);
		
	})
	
	.on('click', '.btn-show-sportellocura', function() {
		$('#modal-sportellocura-dialog').modal();
	})
	
	.on('click', '.btn-dream-italy-send-code', function() {
		
		var url = $('#dream-italy-endpoint').val();
		var apyKey = $('#dream-italy-apikey').val();
		var code = $('#dream_italy_code').val();
		
		clearCareGiverFields();
					
		request('/api/request/getDreamItaly', {code:code}, 
			function(ret) { //success (ret.status ok)
				//console.log(ret);
				
				var file_name_numbs = [1, 2, 3, 4, 5, 6];
								
				if (ret.output != null && typeof ret.output.id !== 'undefined') {
					
					$('#request_name').val(ret.output.r_nome);
					$('#request_surname').val(ret.output.r_cognome);
					
					if (ret.output.r_sesso != null) {
						$('#request_gender').val(ret.output.r_sesso.toLowerCase());
					}
					
					///Birt date///
					if (ret.output.r_datanascita != null) {
						var birthDate = new Date(ret.output.r_datanascita);
						var year = birthDate.getFullYear();
						var month = parseInt(birthDate.getMonth())+1;
						var day = birthDate.getDate();

						$('#request_birth_year').val(year);
						$('#request_birth_month').val(month);
						$('#request_birth_month_day').val(day);

						$('#birth-as-date-radio').trigger('click');
	            	}
	            	///Birt date///
	            	
	            	$('#request_medremarks').html(stringfyNull(ret.output.r_patologie)+"\n\n"+stringfyNull(ret.output.r_motivochiamata)+'\n\n'+stringfyNull(ret.output.r_terapia));
	            	
	            	$('#request_cgnamesurname').val($.trim(stringfyNull(ret.output.cg_nome)+' '+stringfyNull(ret.output.cg_cognome)));
	            	$('#request_cgphone').val(stringfyNull(ret.output.r_telefono));
	            	$('#request_cgemail').val(stringfyNull(ret.output.r_email));
	            	
	            	$('#request_cgmmgnamesurname').val($.trim(stringfyNull(ret.output.me_nome)+' '+stringfyNull(ret.output.me_cognome)));
	            	$('#request_cgmmgphone').val(stringfyNull(ret.output.me_telefono));
	            	$('#request_cgmmgemail').val(stringfyNull(ret.output.me_email));
	            	
	            	if (parseInt(ret.output.r_provincia_id) > 0) {
	            		$('#request_cgprovince').val(ret.output.r_provincia_id);
	            		
	            		$('#request_cgprovince').trigger('change');
	            		
	            		setTimeout(function() {
		            		if (parseInt(ret.output.r_provincia_id) > 0) {
		            			$('#request_cgcity').val(ret.output.r_citta_id);
							}
	            		}, 200);
	            		
	            	}
					
					//Show more details controls
	            	if ($('.field-moredetails').hasClass('hide-moredtails')) $('.field-moredetails').removeClass('hide-moredtails');
					if (!$('.field-moredetails').hasClass('show-moredtails')) $('.field-moredetails').addClass('show-moredtails');
	            	
	            	//Attachments
	            	var f_name = '';
	            	for (var i in file_name_numbs) {
		            	if (ret.output['f_'+i] != null && $.trim(ret.output['f_'+i]) != '') {
			            	
			            	f_name = ret.output['f'+i+'_filename'];
			            	
			            	if (f_name == null || $.trim(f_name) == '') f_name = 'f_'+i;
			            	
			            	$('#request_cg_file_list').append('<li class="list-group-item">'+f_name+'</li>');
			            	$('#request_cg_input_list').append('<input type="hidden" name="data[cg]['+i+'][filename]" value="'+f_name+'"><input type="hidden" name="data[cg]['+i+'][filedata]" value="'+ret.output['f_'+i]+'">');
		            	}
	            	}
	            	
					
				} else {
					//alert('');
					$('#dream_italy_code').addClass('is-invalid');
				}
			}, 
			
			function(ret) { //error (ret.status err)				
				showMessage(ret.msg, ret.jsArgs);
				console.log(ret);
			},
			true
		);
		
	})
	
	.on('change', '#simply_viewer', function() {
		var checked = $(this).is(':checked') ? 1 : 0;
				
		request('/api/request/setViewerType', {checked_value:checked}, 
			function(ret) { //success (ret.status ok)
				showConfirmCancel(glbAppTitle, "Per rendere effettive le modifiche è necessario aggiornare la pagina, perdendo eventuali modifiche non ancora salvate. Procedere ora?", function() {
					document.location.hash = replaceTimestamp(document.location.hash, 2);
				});
			}, 
			
			function(ret) { //error (ret.status err)				
				showMessage(ret.msg, ret.jsArgs);
				//console.log(ret);
			},
			true
		);
	});

window.chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)'
};

function randomScalingFactor() {
	var min = -100;
	var max = 100;

	return Math.random() * (max - min) + min;
}

///////// FUNCTIONS /////////

function loadGlobalVariables() {
	var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    $('#global-js-variables').remove();
    $(script).attr('id', 'global-js-variables');
    script.src = '/global-js?t='+new Date().getTime();
    head.appendChild(script);
}

function prepareFileList(files) {
	var postCode = $('#request-unique-code').length > 0 ? $('#request-unique-code').val() : '';

	if (postCode != '') {
		if (files.length > 0) {

			var fileData = null;
			var html = '';
			var percentage = 0;
			var alreadyUplaoded = false;
			var cancelButton = '';
			var index = 0;

			for (var i = 0; i < files.length; i++) {

				files[i].postCode = postCode;

				globalUploadList.push(files[i]);

				index = globalUploadList.length-1;

				fileData = files[i];

				html = '<tr id="upload-item-row_'+index+'">';
					//html += '<td>'+postCode+'</td>';
					html += '<td class="upload-item-icon" id="upload-item-icon_'+index+'"></td>';
					html += '<td><span id="upload-item-name_'+index+'">'+fileData.name+'</span></td>';
					//html += '<td width="1%"><input type="radio" name="fileecg" value="'+index+'"> ECG</td>';
					html += '<td><div class="progress" style="margin-top:3px;"><div class="progress-bar bg-info" id="upload-current-progress_'+index+'" role="progressbar" style="width:'+percentage+'%"></div></div></td>';
					html += '<td>'+numbLocalize((fileData.size/1024/1024).toFixed(2))+'</td>';
					html += '<td class="text-center"><button id="upload-item-btn-delete_'+index+'" type="button" data-itemindex="'+index+'" class="btn btn-danger btn-sm btn-delete-upload-item">&times;</button></td>';
				html += '</tr>';

				$('#tus-upload-file-list tbody').append(html);

			}

			console.log(globalUploadList);

		}
	} else {
		showMessage(glbNoPostCodeMsg);
	}
}

function uploadTusFile(file) {
	//var postId = $('#request-id').length > 0 ? parseInt($('#request-id').val()) : 0; //Deprecated (not used)
	//var postCode = $('#request-unique-code').length > 0 ? $('#request-unique-code').val() : '';
    var groupId = $('#group-id').length > 0 ? parseInt($('#group-id').val()) : 0; //In main layout
    var userId = $('#user-id').length > 0 ? parseInt($('#user-id').val()) : 0; //In main layout
    var commentId = $('#request-comment-id').length > 0 ? parseInt($('#request-comment-id').val()) : 0; //In Request View
    var staticUri = $('#static-uri').val();
    var apiKey = $('#api-key').val();

    if (!isOnline()) {
	    showMessage(glbAppOffline);
	    return;
    }

    if (gloabalUploadErrorHandling) {
	    showConfirmCancel(glbAppTitle, glbUploadBusy, function() {
		    uploadReset();
	    });
	    return;
    }

    //Pause
    if (globalUploadInProgress && gobalUpload !== null) {
	    gobalUpload.abort();
		globalUploadInProgress = false;
	    uploadSetPlayBtn();
	    uploadSetPauseProgress('#upload-current-progress_'+globalUploadCounter);
	    uploadSetItemPauseIcon('#upload-item-icon_'+globalUploadCounter);
	    return;
    }

    //Resume
    if (!globalUploadInProgress && gobalUpload !== null) {
	    gobalUpload.start();
    	uploadSetPauseBtn();
    	return;
    }

    //Start
    if (!globalUploadInProgress && gobalUpload == null) {
    	uploadSetPauseBtn();
	}

	// Create a new tus upload

    gobalUpload = new tus.Upload(file, {
        endpoint: staticUri,
        retryDelays: [0, 1000, 3000, 5000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000],
        metadata: {
            filename: file.name,
            filetype: file.type,
            groupId: groupId,
            userId: userId,
            postCode: file.postCode,
            commentId: commentId,
            apiKey: apiKey, //Required by pre-create hook
            op: 'ght-upload-attach' //Required by post-finish hook
        },
        onError: function(error) {

	        console.log('tus client error: '+error)

	        globalUploadInProgress = false;
	        uploadRemovePauseProgress('#upload-current-progress_'+globalUploadCounter);

            if (error.originalRequest) {

				gloabalUploadErrorHandling = true;

				globalUploadTimeout = setTimeout(function() {
		            gobalUpload.start();
				}, 60000);

	        } else {
		        showMessage(error);
				uploadReset();
	        }
        },
        onProgress: function(bytesUploaded, bytesTotal) {

	        showUploadWarning();
	        $('#btn-tus-upload').show();

	        globalUploadInProgress = true;
	        gloabalUploadErrorHandling = false;

	        uploadRemovePauseProgress('#upload-current-progress_'+globalUploadCounter);

	        $('#upload-item-btn-delete_'+globalUploadCounter).hide();

	        uploadSetItemPlayIcon('#upload-item-icon_'+globalUploadCounter);

            var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
            $('#upload-current-progress_'+globalUploadCounter).css({width:percentage+'%'});

        },
        onSuccess: function() {
            //console.log("Download %s from %s", gobalUpload.file.name, gobalUpload.url);

            //Append the file attach list
            var postCode = globalUploadList[globalUploadCounter].postCode;
            if ($('#attach-list-'+postCode).length > 0) {
	            request('/api/request/requestAttachs', {postCode: postCode},
		            function(ret) { //Success
			            var html = '';
			            if (typeof ret.attachData !== 'undefined') {
				            for(var i = 0; i<ret.attachData.length; i++) {
					            html += '<tr id="attach-row-id-'+ret.attachData[i].id+'">';
					            	html += '<td>';
					            		html += '<a class="download" data-forcedownload="'+ret.attachData[i].forceDownload+'" data-fileext="'+ret.attachData[i].ext+'" href="/downlaod/?attach_id='+ret.attachData[i].id+'">'+ret.attachData[i].title+'</a>';
					            	html += '</td>';

					            	html += '<td width="1%" class="text-right">';
					            		html += '<button type="button" class="btn btn-danger btn-sm rounded-button delete-attach" data-attachtitle="'+ret.attachData[i].title+'" data-attachname="'+ret.attachData[i].name+'" data-attachid="'+ret.attachData[i].id+'"><span class="icon-cross"></span></button>';
					            	html += '</td>';
					            html += '</tr>';
				            }
				            $('#attach-list-'+postCode+' tbody').html(html);
			            }
		            },
		            function() {}, //Error
		            false //Don't show the loader
	            );
            }

            //Mark this file as skipable
            globalUploadList[globalUploadCounter].skip = true;
            gobalUpload = null;
            gloabalUploadErrorHandling = false;

            uploadRemovePauseProgress('#upload-current-progress_'+globalUploadCounter);
            //uploadCleanItemIcons();
            uploadSetItemCheckIcon('#upload-item-icon_'+globalUploadCounter);

            globalUploadCounter++;

            var file = getCurrentFileToUpload();

            if (file !== false) {
	            uploadTusFile(file);

	            //Operations after upload finished

	            //In Request page (Edit/View)
	            if ($('#request-page-type').length > 0) {

		            switch($('#request-page-type').val()) {
			            case 'request-edit':
			            	//Load the attachment list
			            break;

			            case 'request-view':
			            break;
		            }

	            }

            } else {

	            //Upload loop complete

	            uploadSetPlayBtn();

				globalUploadInProgress = false;

	            hideUploadWarning();
	            $('#btn-tus-upload').hide();

	            //Operations after upload loop finished

	            //In Request page (Edit/View)
	            if ($('#request-page-type').length > 0) {

		            switch($('#request-page-type').val()) {
			            case 'request-edit':
			            break;

			            case 'request-view':
			            	document.location.hash = replaceTimestamp(document.location.hash, 2);

			            	//Load all comments to show the attachemts
			            	/*var requestID = $('#request-id').length > 0 ? parseInt($('#request-id').val()) : 0;
							var centerID = $('#center-id').length > 0 ? parseInt($('#center-id').val()) : 0;

							if (requestID > 0 && centerID > 0) {
								request('/api/request/requestLoadAllComments', {requestID:requestID, centerID:centerID},
									function(ret) { //success (ret.status ok)

										if (typeof ret.html !== 'undefined')
											$('#request-comment-wrapper').html(ret.html);

										if (typeof ret.log !== 'undefined')
											console.log(ret.log);
									},

									function(ret) { //error (ret.status err)
									},
									false
								);
							}*/
			            break;
		            }

	            }

	            console.log('List complete');
            }
        }
    });

    // Start the upload
    gobalUpload.start();

}

function uploadReset() {
	if (globalUploadTimeout != null) {
		clearTimeout(globalUploadTimeout);
		globalUploadTimeout = null;
	}
	if (gobalUpload != null) {
		gobalUpload.abort();
		gobalUpload = null;
	}
	globalUploadInProgress = false;
	gloabalUploadErrorHandling = false;

	globalUploadCounter = 0;
	globalUploadList = [];

	uploadSetPlayBtn();
	uploadRemovePauseProgress('#upload-current-progress_'+globalUploadCounter);
	uploadCleanItemIcons();

	$('#tus-upload-control').trigger('reset');
}

function request(url, data, successFunc, errorFunc, allowLoader, synchronous) {

	if (!isOnline()) {
		showMessage(glbAppOffline);
		return false;
	}

	if (typeof allowLoader === 'undefined') allowLoader = true;
	if (typeof synchronous !== 'undefined' && synchronous) ajaxRunning = false;

	//console.log(isOnline());

	if (!ajaxRunning) {
		if (allowLoader) showLoader();
		ajaxRunning = true;
		ajaxRef = $.ajax({
			dataType: 'json',
			url: url,
			data: data,
			headers : {'api-key':apyKey, 'appRequestType':'web'},
			method: 'POST',
			success: function(ret) {

				ajaxRunning = false;
				hideLoader();

				if (ret.status.toLowerCase() == 'ok') {

					if (typeof ret.userLang !== 'undefined') {
						document.documentElement.lang = ret.userLang;
					}

					if (typeof ret.userId !== 'undefined') {
						$('#user-id').val(ret.userId);
					}

					if (typeof ret.groupId !== 'undefined') {
						$('#group-id').val(ret.groupId);
					}

					//For Dream Integration
					if (typeof ret.username !== 'undefined') {
						$('#user-username').val(ret.username);
					}

					successFunc(ret);

				} else {

					if (typeof errorFunc === 'undefined') {
						showMessage(ret.msg, ret.jsArgs);
					} else {
						errorFunc(ret);
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				ajaxRunning = false;
				hideLoader();


				if (XMLHttpRequest.readyState == 4) {
					if (errorThrown != '') {
		            	showMessage(errorThrown);
		            } else {
			            showMessage(glbGenericError+' (Err. cod. 0)');
		            }

		            //showMessage(errorThrown);

		            //showMessage(glbGenericError+' (Err. cod. 0)');
		        }
		        else if (XMLHttpRequest.readyState == 0) {
		            showMessage(glbGenericError+' (Err. cod. 1)');
		        }
		        else {
		            showMessage(glbGenericError+' (Err. cod. 2)');
		        }
			}
		});
	}
}

function requestUpload(formElement, url, successFunc, errorFunc, allowLoader) {

	if (!isOnline()) {
		showMessage(glbAppOffline);
		return false;
	}

	if (typeof allowLoader === 'undefined') allowLoader = true;

	if (!ajaxRunning) {
		if (allowLoader) showLoader();
		ajaxRunning = true;

		var data = new FormData(formElement);

		ajaxRef = $.ajax({
			dataType: 'json',
			url: url,
			data: data,
			headers : {'api-key':apyKey, 'appRequestType':'web'},
			method: 'POST',
			enctype: 'multipart/form-data',
			processData: false,
			contentType: false,
			cache: false,
			success: function(ret) {

				ajaxRunning = false;
				hideLoader();

				if (ret.status.toLowerCase() == 'ok') {
					successFunc(ret);
				} else {
					errorFunc(ret);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				ajaxRunning = false;
				hideLoader();
				showMessage(XMLHttpRequest.statusText);
			}
		});

	}
}

//ICD-10 dialog
//WARNING: this HTML code also is in requestEdit.view (ECD-10 section)
function setDeseaseCheckboxesList() {
	var list = [];

	$('.desease-id-checkbox').each(function() {
		var label = $(this).data('label');
		var id = $(this).val();

		if ($(this).is(':checked')) {
			list.push('<div><small><span class="icon-checkmark"></span> '+label+'</small></div>');
			globalICD10List[id] = label;
		}
	});

	//Also in requestEdit.view!!
	if (list.length > 0) {
		$('#icd10-list-content').empty();
		for(var i = 0; i < list.length; i++) {
			$('#icd10-list-content').append(list[i]);
		}
		$('#icd10-list-content').append('<hr>');
	} else {
		$('#icd10-list-content').empty();
	}
}

//Wizard dialogs
//WARNING: this HTML code also is in requestEdit.view (Wizards section)
function setWizardCheckboxesList(checkboxClass, WizardContainer) {
	var list = [];

	$('.'+checkboxClass).each(function() {
		var label = $(this).data('label');
		if ($(this).is(':checked')) {
			list.push('<div><small><span class="icon-checkmark"></span> '+label+'</small></div>');
		}
	});

	//Also in requestEdit.view!!
	if (list.length > 0) {
		$('#'+WizardContainer).empty();
		for(var i = 0; i < list.length; i++) {
			$('#'+WizardContainer).append(list[i]);
		}
		$('#'+WizardContainer).append('<hr>');
	} else {
		$('#'+WizardContainer).empty();
	}
}

//https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload
function checkImageFile(fileElement) {
	//var fileElement = document.getElementById("your-files");
	if (window.FileReader && window.Blob) {
		var files = fileElement.files

		for (var i = 0; i < files.length; i++) {
	        console.log("Filename: " + files[i].name);
	        console.log("Type: " + files[i].type);
	        console.log("Size: " + (files[i].size/1024).toFixed(2) + " mb");
	    }
	}

	return false;
}

function preparePage() {
	showLoader();
}

function handlePage(ret, element, callbackFunc) {
	if (typeof element === 'undefined' || element == null)
		element = '#main';

	$(element).html(ret.html);

	if (isFunction(callbackFunc))
		callbackFunc();
}

function toggleTranfer() { //Show/Hide Transfer Manager

	var windowHeight = $(window).height();
	$('#transfer-manager').height((windowHeight/1.5));

	var elementHeight = $('#transfer-manager').height();
	var position = $('#transfer-manager').offset();
	var topLimit = (windowHeight-elementHeight);
	var bottomLimit = (windowHeight+elementHeight);
	var toPosition = 0;

	if (position.top <= topLimit) {
		toPosition = bottomLimit;
	} else {
		toPosition = topLimit;
	}

	$('#transfer-manager').animate({
		top:toPosition
	}, 'fast', function() {
		resizeTranfer();
	});
}

function resizeTranfer() {
	var position = $('#transfer-manager').offset();
	var windowHeight = $(window).height();
	var elementHeight = $('#transfer-manager').height();
	var topLimit = (windowHeight-elementHeight);

	if (position.top <= topLimit) {
		$('#transfer-manager').css({top:topLimit});
	}

	$('#upload-list-table-wrapper').height(elementHeight-80);
}

function hideTranfer() {
	var windowHeight = $(window).height();
	var elementHeight = $('#transfer-manager').height();
	var position = $('#transfer-manager').offset();

	$('#transfer-manager').animate({
		top:(windowHeight+elementHeight)
	}, 'fast');
}

function cleanUploadItems() {
	if (globalUploadList.length > 0) {

		var c = 0;

		for(var i = 0; i < globalUploadList.length; i++) {
			if (typeof globalUploadList[i].skip !== 'undefined') {
				$('#upload-item-row_'+i).remove();

				c++;
			}
		}

		if (c == globalUploadList.length) {
			//globalUploadList = [];
		}
	}
}

function uploadReset() {

	if (gobalUpload != null) {
		gobalUpload.abort();
		gobalUpload = null;
	}

	if (globalUploadInterval != null) {
		clearInterval(globalUploadInterval);
		globalUploadInterval = null;
	}

	globalUploadInProgress = false;
	globalUploadList = [];
	globalUploadCounter = 0;

	$('#tus-upload-control').reset();
}

function uploadSetPauseBtn() {
	$('#btn-tus-upload').removeClass('btn-primary').addClass('btn-warning').find('span').removeClass('icon-play2').addClass('icon-pause');
}

function uploadSetPlayBtn() {
	$('#btn-tus-upload').removeClass('btn-warning').addClass('btn-primary').find('span').removeClass('icon-pause').addClass('icon-play2');
}

function uploadSetItemPlayIcon(jQueryElement) {
	//uploadCleanItemIcons();
	$(jQueryElement).html('<span class="icon-play2"></span>');
}

function uploadSetItemPauseIcon(jQueryElement) {
	//uploadCleanItemIcons();
	$(jQueryElement).html('<span class="icon-pause"></span>');
}

function uploadSetItemCheckIcon(jQueryElement) {
	$(jQueryElement).html('<span class="icon-checkmark"></span>');
}

function uploadCleanItemIcons() {
	$('.upload-item-icon').html('');
}

function uploadRemovePauseProgress(jQueryElement) {
	$(jQueryElement).removeClass('progress-bar-animated');
	$(jQueryElement).removeClass('progress-bar-striped');
}

function uploadSetPauseProgress(jQueryElement) {
	$(jQueryElement).addClass('progress-bar-animated');
	$(jQueryElement).addClass('progress-bar-striped');
}

function getCurrentFileToUpload() {

	if (globalUploadList.length > 0) {

		for(var i = globalUploadCounter; i < globalUploadList.length; i++) {

			if (typeof globalUploadList[i].skip === 'undefined') {
				globalUploadCounter = i;
				return globalUploadList[i];
			}

		}

	}

	return false;
}

function gotoDest(destination) {
	if (typeof destination === 'undefined') destination = '';
	document.location.hash = '#/'+destination;
}

function showLoader() {
	$('#loader-wrapper').show();
	$('#overlay').show();
}

function hideLoader() {
	$('#loader-wrapper').fadeOut();
	$('#overlay').hide();
}

function showAnimatedLoader() {
	$('#overlay').show();
}

function hideAnimatedLoader() {
	$('#overlay').hide();
}

function isFunction(functionToCheck) {
	return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

function replaceTimestamp(currentHash, position) {
	var s = currentHash.split('/');
	s[position] = new Date().getTime();
	return s.join('/');
}

function replaceHashParameter(hash, value, position) {
	var s = hash.split('/');
	s[position] = value;
	return s.join('/');
}

function showUploadWarning() {
	$('#upload-warning-wrapper').show();
}

function hideUploadWarning() {
	$('#upload-warning-wrapper').fadeOut();
}

function showMessage(msg, params) {

	var btnData = [{text: 'Ok', style: 'primary', close: true, click: function() {}}];

	if (typeof params !== 'undefined' && params != null) {
		if (typeof params.button !== 'undefined') {
			switch (params.button) {
				case 'login':
					btnData[0].text = glbCancelButton;
					btnData[0].style = 'light';
					btnData.push({text: glbLoginButton, style: 'warning', close: true, click: function() {
						//gotoDest();
						document.location.href = '/';
					}});
				break;

				case 'refresh-page':
					btnData[0].click = function() {
						document.location.reload();
					}
				break;

				case 'refresh-hash':
					btnData[0].click = function() {

						//Update also the record ID in address bar
						if (typeof params.recordId !== 'undefined' && typeof params.idPosition !== 'undefined') {
							var hash = document.location.hash;
							hash = replaceHashParameter(hash, params.recordId, params.idPosition);
							document.location.hash = replaceTimestamp(hash, 2);
						} else {
							//Just update the timestamp
							document.location.hash = replaceTimestamp(document.location.hash, 2);
						}

					}
				break;

				case 'refresh-user-edit':
					btnData[0].click = function() {
						var hash = replaceTimestamp(document.location.hash, 2);
						document.location.hash = replaceHashParameter(hash, params.userId, 3);
					}
				break;

				case 'goto':
					if (typeof params.destination !== 'undefined')
						gotoDest(params.destination);
					/*btnData[0].click = function() {
						if (typeof params.destination !== 'undefined')
							gotoDest(params.destination);
					}*/
				break;
			}
		}

		if (typeof params.dialogType !== 'undefined') {
			switch(params.dialogType) {
				case 'sessionExpired':
					msg = glbSessionExpired;
				break;
			}
		}
	}

	eModal.alert({
		title:glbAppTitle,
		message:msg,
		buttons: btnData
	});
}

function showConfirmCancel(title, msg, callback) {
	eModal.alert({
		title:title,
		message:msg,
		buttons: [
            {text: 'Ok', style: 'primary', close: true, click: function() {
	            callback();
            }},
            {text: glbCancelButton, style: 'warning', close: true, click: function() {}}
        ]
	});
}

function isOnline() {
	return window.navigator.onLine;
}

function getLanguage() {
	var lang = $.trim($('html').attr('lang'));
	if (lang == '') lang = 'en';
	return lang;
}

function numbLocalize(numb) {
	var lang = getLanguage();

	if (lang != 'en') {
		numb = numb.replace('.', ',');
	}

	return numb;
}

function choosenHideDeleteCross() {
	$('.search-choice-close').hide();
	$('.chosen-container-multi .chosen-choices .search-choice').addClass('chosen-remove-padding');
}

// Initialize and add the map
function initMap(lat, lng) {

	if ($('#map').length > 0) {
		var place = {lat: parseFloat(lat), lng: parseFloat(lng)};
		var map = new google.maps.Map(
		  document.getElementById('map'), {zoom: 4, center: place});
		var marker = new google.maps.Marker({position: place, map: map});
    }
}

function wsConnect() {
    if (typeof appWebSocket !== 'undefined') {
        appWebSocket.close();
    }

    //console.log('Connecting...');

    if (typeof appWebSocket !== 'undefined' && appWebSocket.readyState == 1) return; //Already opened

	appWebSocket = new WebSocket(glbWSEndpoint);

	appWebSocket.onmessage = function(event) {

        try {
            wsData = $.parseJSON(event.data); //Global variable
            
            //showDreamForm(wsData.centerName);


            if (wsData.op == 'show-integration') {
				showDreamForm(wsData.centerName);
				
				/*if ($('#process-path').length > 0) {
		            var processPath = $('#process-path').val();
		            wsSend(JSON.stringify({op:"check-process", processpath:processPath}), false);
	            }*/
            
            }
            
            if (wsData.op == 'show-process-button') {
	            if ($('#process-path').length > 0) {
		            var processPath = $('#process-path').val();
		            wsSend(JSON.stringify({op:"check-process", processpath:processPath}), false);
	            }
	        }
            
            if (wsData.op == 'hide-integration') {
	            hideDreamForm();
				hideAnimatedLoader();
	        }

            //wsConnectionCounter++;

            if (wsData.op == 'response-data') {
	            //console.log(data.dreamData)

	            if (typeof wsData.dreamData != 'undefined') {

		            hideAnimatedLoader();

		            if ($('#request_dream_data').length > 0) {
			            $('#request_dream_data').val(JSON.stringify(wsData.dreamData));

			            if (typeof wsData.dreamData.Anagrafica !== 'undefined') {

				            if (!$.isEmptyObject(wsData.dreamData.Anagrafica)) {

					            var registry = wsData.dreamData.Anagrafica;

					            if (typeof registry.Nome !== 'undefined') {
						            $('#request_name').val(registry.Nome.trim());
					            }

					            if (typeof registry.Cognome !== 'undefined') {
						            $('#request_surname').val(registry.Cognome.trim());
					            }

					            if (typeof registry.sesso !== 'undefined') {
						            $('#request_gender').val(registry.sesso.toLowerCase().trim());
					            }


					            if (typeof registry.dataNascita !== 'undefined') {
						            var birthDate = new Date(registry.dataNascita);
						            var year = birthDate.getFullYear();
						            var month = parseInt(birthDate.getMonth())+1;
						            var day = birthDate.getDate();

						            $('#request_birth_year').val(year);
						            $('#request_birth_month').val(month);
						            $('#request_birth_month_day').val(day);

					            	$('#birth-as-date-radio').trigger('click');
					            }
								
								var rcode = $('#request-unique-code').val();
					            wsSend(JSON.stringify({op:"write-record", rcode:rcode, username:$('#user-username').val(), idAnagrafica:registry.idAnagrafica}), false);

				            } else {
					            $('#request_name').val('');
					            $('#request_surname').val('');
					            $('#request_surname').val('');
					            $('#request_birth_year').val('0');
					            $('#request_birth_month').val('0');
					            $('#request_birth_month_day').val('0');
					            $('#request_dream_data').val('');

					            $('#dream_code').addClass('is-invalid');
				            }

			            }
		            }

		            //console.log(wsData.dreamData);
	            }
	        }

	        if (wsData.op == 'response-evt-id') {
		        $('#request-dream-evt-id').val(wsData.evtId);
		        console.log('Evt id: '+wsData.evtId);
		    }

	        if (wsData.op == 'response-data-error') {
	            //console.log(wsData.dreamData)
	            hideAnimatedLoader();
	            showMessage(wsData.msg);
	        }
	        
	        if (wsData.op == 'process-error') {
	            hideAnimatedLoader();
	            showMessage(wsData.msg);
	        }
	        
	        if (wsData.op == 'process-opened') {
	            hideAnimatedLoader();
	        }
	        
	        if (wsData.op == 'process-check') {
		        hideAnimatedLoader();
	            console.log('process', wsData.msg);
	            
	            if (wsData.msg) { //true
		            $('.btn-run-process').show();
	            }
	        }

            $('.ws-cc-code-container').prop('disabled', false);

        } catch (error) {
	        showMessage(error);
            console.log('Parser error: '+error);
            hideAnimatedLoader();
        }

        //console.log(event.data);
    }

    appWebSocket.onopen = function(evt) {
        console.log('WS Opened');
    };

    appWebSocket.onclose = function(evt) {
	    hideDreamForm();
	    $('.btn-run-process').hide();
	    hideAnimatedLoader();
	    //showReconnectBtn();
        console.log('WS Closed');
    };

    appWebSocket.onerror = function(evt) {
       	hideDreamForm();
       	$('.btn-run-process').hide();
	    hideAnimatedLoader();
        console.log('WS Error');
    };
}

function wsSend(message, showLoader) {

	if (typeof showLoader === 'undefined')
		showLoader = true;

	if (typeof appWebSocket === 'undefined') {
		appWebSocket.close();
		wsConnect();
    }

    if (appWebSocket.readyState != 1) {
		appWebSocket.close();
		wsConnect();
    }

    if (typeof appWebSocket !== 'undefined') {
	    if (appWebSocket.readyState == 1) { //Open

		    if (showLoader) {
			    showAnimatedLoader();
			    $('.ws-cc-code-container').prop('disabled', true);
			}

    		appWebSocket.send(message);
    	}
    }
}

function wsClose() {
	if (typeof appWebSocket !== 'undefined') {
    	appWebSocket.close();
    }
}

function hideDreamForm() {
    //Hide the Dream integration in new/edit request page

    //hideReconnectBtn();

    $('.dream-wrapper').hide();
    $('.cc-wrapper').removeClass('col-lg-2');
    $('.cc-wrapper').addClass('col-lg-5');
}

function showDreamForm(centerName) {
	//hideReconnectBtn();
	
	$('.dream-italy-wrapper').hide();

    $('.cc-wrapper').removeClass('col-lg-5');
	$('.cc-wrapper').addClass('col-lg-2');

	$('.ws-cc-name').html(unescape(centerName));

	$('.dream-wrapper').show();
}

function showReconnectBtn() {
	if (wsConnectionCounter > 0)
		$('.ws-reconnect-wrapper').show();
	else
		hideReconnectBtn();
}

function hideReconnectBtn() {
	$('.ws-reconnect-wrapper').hide();
}

function stringfyNull(value) {
	if (value == null) {
		return '';
	} else {
		return value;
	}
}

function clearCareGiverFields() {
	$('#request_cgprovince').val('0');
	$('#request_cgcity').prop('disabled', true).empty();
	
	$('#request_name').val('');
	$('#request_surname').val('');
	$('#request_gender').val('');
	
	$('#request_birth_year').val('0');
	$('#request_birth_month').val('0');
	$('#request_birth_month_day').val('0');
	
	$('#birth-as-date-radio').trigger('click');
	
	$('#request_medremarks').html('');
            	
    $('#request_cgnamesurname').val('');
    $('#request_cgphone').val('');
    $('#request_cgemail').val('');
            	
    $('#request_cgmmgnamesurname').val('');
    $('#request_cgmmgphone').val('');
    $('#request_cgmmgemail').val('');
    
    $('#request_cg_file_list').empty();
    $('#request_cg_input_list').empty();
}

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  console.log(contents);
}
