function btnDelegati(){
	if($('.delegato').length >= $('#n_delegati').val() * 1)
		$('#delegati-add').hide();
	else
		$('#delegati-add').show();	
}

function confDelegato(serv_cod,anagr_id,deleg_id){
	var qs = '/servizi/diag/add_delegato/?serv='+serv_cod+'&anagr_id='+anagr_id;
	if(deleg_id)
		qs += '&id='+deleg_id;
	dialog(qs);
}

function addDelegato(deleg_id,anagr,serv_cod,anagr_id){
	var $row = $('<div class="delegato m-top-5" />')
	.append( 
		$('<div class="input-group no-readonly">' +
			'<input id="delegato-'+deleg_id+'" name="deleg['+deleg_id+']" class="form-control" type="text" maxlength="40" value="'+anagr+'" readonly />' +
			'<span class="input-group-btn">' +
				'<button type="button" class="btn btn-warning" onClick="confDelegato(\''+serv_cod+'\','+anagr_id+','+deleg_id+')">' +
					'<span class="glyphicon glyphicon-pencil"></span>' +
				'</button>' +
				'<button type="button" class="btn btn-danger" onClick="remDelegato(this)">' +
					'<span class="glyphicon glyphicon-remove"></span>' +
				'</button>' +
			'</span>' +
		'</div>')
	);
		
	$('#delegati').append($row);
	btnDelegati();
}
function remDelegato(btn){
	var id = $(btn).parent().prev('input').attr('id').replace('delegato-','');
	var url = $(btn).parents('form').attr('action').split('?');
	url = url[0] + '?rdel='+id;
	
	confirm('Sei sicuro di volere rimuovere il delegato?', function(){
		$.get(url,function(data){
			if(data == 'OK'){
				$(btn).parents('.delegato').remove();
				btnDelegati();
			}
			closeDialog();
		});
	});
}
function removeAttach(btn){
	$(btn).parents('.input-group-btn').addClass('hidden')
	.parents('.input-group').find('.f-label, .f-name').val('')
	.prev('span').removeClass('hidden');
}
function attachUploaded(name,doc_id){

	$("input[name='"+name+"']")
	.val("Caricato")
	.prev("span").addClass("hidden")
	.nextAll("span.hidden").removeClass("hidden").find('.show-doc').click(function(){
		goto('/download/?id='+doc_id);
	})
	.parents('.input-group').find("input[type='file']").val("");
}

function servsosp(el){
	var sospendi = $(el).prop('checked');
	var $form = $(el).parents('form');
	var name = $(el).attr('name');
	$form.find('.form-control:not(.no-readonly .form-control)').prop('readonly',sospendi);
	$form.find('.f-name, .btn:not(.modal-footer .btn, .no-readonly .btn, .form-buttons .btn)').prop('disabled',sospendi);
	$form.find('.switch-btn:not([name="'+name+'"])').bootstrapSwitch('readonly',sospendi);
}

var form_changed = false;
function saveBeforeExit(links,inputs,name){

	$(inputs).on('focus',function(){
		changed = true;
	});
	
	$(links).on('click',function(){
		if(changed){
			var url = $(this).attr('href');
			confirm("Vuoi abbandonare la pagina " + (name ? "di <strong>" + $(this).html() + "</strong> " : "" ) + "senza salvare le modifiche?", function(){
				window.location = url;
			});
			return false;
		}
	});
}
