(function($) {
	var dialog_box;
	var openDialog = false;
	var frm;
	var frm_submit;
	
	$.fn.dialogDynForm = function(options) {
		
		opts = $.extend({}, $.fn.dialogDynForm.defaults, options);
		
		dialog_box = $('<div></div>');
		dialog_box.attr('id',opts['dialogBoxId']);
		dialog_box.attr('title',opts['boxTitle']);
		dialog_box.css('padding','0px');
		
		$(this).parent().append(dialog_box);
		
		$(this).click(function(){
			
			if( !openDialog ) // Inizializzazione del dialog
				$(this).initDynDialog();
			
			dialog_box.dialog('open');
			openDialog = true;
		});
		
		return $(this);
	};
	
	$.extend($.fn, {
		initDynDialog : function(){
			
			dialog_box.dialog({
				autoOpen: false, 
				modal: true, 
				draggable: false, 
				resizable: false, 
				width: opts['boxWidth'], 
				height: opts['boxHeight'], 
				buttons: {
					"Invia": function() {
						$(this).sendDynFormContent();
					},
					"Annulla": function() {
						$(this).destroyDynForm();
					}
				},
				open: function(){
					if(!openDialog){
						$("[aria-labelledby=ui-dialog-title-"+opts['dialog_box_id']+"] .ui-widget-header").removeClass('ui-widget-header-red');	
						dialog_box.empty();
						$(this).initDynFormDialogContent();
					}
				}, 
				close: function(){
					$(this).destroyDynForm();
				}
			});
		}, 

		
		initDynFormDialogContent : function(){
			
			dialog_box.append('<div style="text-align:center; padding-top:50px;"><span>Caricamento dati</span><br/><img src="/img/loading11.gif"/></div>');
			
			//*** VALORIZZO LA DIALOG BOX
			$.ajax({
				type: "GET",
				async: false, 
				url: "/ajax/"+opts['formGetAction'],
				dataType: 'json', 
				success: function(val) {
					
					dialog_form = $('<form>'+val.page+'</form>');
					dialog_form.attr('id',opts['formGetAction']);
					dialog_form.attr('action',opts['formSendAction']);
					dialog_form.css('padding','0px');
					dialog_box.empty();
					dialog_box.append(dialog_form);
					
					validator = $("#"+opts['formGetAction']).validate({
						errorClass: "orange", 
						errorElement: "div", 
						errorPlacement: function(error, element) {
							error.appendTo(element.next('.err_validator'));
						}
					});
					
					// Rigenero il captcha
					if( $('#captcha_renew').size() > 0 ) {
						$('#captcha_renew').click(function(){
							
							$('#captcha_renew').html('<img src="/img/loading.gif" />');
							
							$.ajax({
								type: "POST",
								url: '/ajax/generate-captcha',
								dataType: 'json', 
								success: function(json){
									$('input[name="captcha_id"]').val(json.captcha_id);
									$('img[title="captcha"]').attr('src',json.captcha_img);
									$('#captcha_renew').html('rigenera');
								}, 
								error: function(msg){
								}
							});
						});
					}
					
				}
			});
			
			return true;
		}, 
		
		
		sendDynFormContent: function(){
			
			if( frm_submit )
				return false;
			
			if( $("#"+opts['formGetAction']).valid() ){
				
				//*** SETTO IL FLAG DI INVIO
				frm_submit = true;
				
				//*** VISUALIZZO L'IMMAGINE DEL LOADING
				$("[aria-labelledby=ui-dialog-title-"+opts['dialogBoxId']+"] .ui-dialog-buttonpane").html('Invio dati in corso... <img src="/img/loading.gif" />');
				
				$.ajax({
					type: "GET",
					async: false, 
					url: "/ajax/"+opts['formSendAction'],
					data: $("#"+opts['formGetAction']).serialize(),
					dataType: "json",
					success: function(ret) {
						$(this).openResponseDialog(ret);
						
						//*** LIBERO IL FORM
						frm_submit = false;
					}
				});
				
			}
			
			
		},
		
		openResponseDialog: function(ret){
			
			var invite_str = '';
			dialog_box.empty();
			
			if( ret.esito == true )
				invite_str = ret.error;
			else if( ret.esito == false ) {
				$('[aria-labelledby="ui-dialog-title-'+opts['dialogBoxId']+'"] .ui-widget-header').addClass('ui-widget-header-red');	
				invite_str = ret.error;
//				invite_str = '<b>Nessuna</b> segnalazione inviato con successo';
			}
			else {
				$("[aria-labelledby=ui-dialog-title-"+opts['dialogBoxId']+"] .ui-widget-header").addClass('ui-widget-header-red');	
				invite_str = '<b>ERRORE</b>';
			}
				
			
			dialog_box.append('<table style="width:100%; height:100%;"><tr><td align="center" valig="middle">'+invite_str+'</td></tr></table>');
			dialog_box.dialog('option','buttons',{ 
				'Esci': function(){
					$(this).destroyDynForm();
				},
				'Indietro': function(){
					$(this).destroyDynForm();
					$(this).initDynDialog();
					dialog_box.dialog('open');
				}
			});
		
			dialog_box.dialog('open');
		},
		
		destroyDynForm: function(){
			dialog_box.dialog('destroy');
			dialog_box.empty();
			openDialog = false;
		}
		
	});
	
	
	$.fn.dialogDynForm.defaults = {
		boxTitle: '',
		boxWidth: 600,
		boxHeight: 450, 
		dialogBoxId: '',
		formGetAction: '',
		formSendAction: '',
		formOkAction: '',
		formKoAction: ''
	};
	
})(jQuery); 
