
jQuery(function($) {
	
	initRupI18nPromise.then(function () {
		initFilter();
		initTable();
	});
	
	const initFilter = () => {
		
		$('#fBaja40_detail_table').rup_date({
			mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true
		});
		$('#fBaja41_detail_table').rup_date({
			mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true
		});
		
		var propertiesTipoAviso={
				feedback:$("#tiposAviso_dialog_feedback"),
				liveCheckingErrors: false,
				showFieldErrorAsDefault: true,
				showErrorsInFeedback: true,
				showFieldErrorsInFeedback: true,
			  rules:{
			      "descEs40":{required:true},
			      "descEu40":{required:true}
			 }
		};
		$("#tiposAviso_detail_form").rup_validate(propertiesTipoAviso);
		
		let tipoAviso_dialog = $("#tiposAviso_detail_div");
		let tipoAviso_dialog_feedback = $("#tiposAviso_dialog_feedback");
		
		try {
			tipoAviso_dialog.rup_dialog("destroy");
		} catch (error) {}
		
		tipoAviso_dialog = $("#tiposAviso_detail_div");
		tipoAviso_dialog_feedback = $("#tiposAviso_dialog_feedback");
		
		tipoAviso_dialog_feedback.rup_feedback (
			{
			  type: "ok",
			  block: false,
			}
		);	
		
		tipoAviso_dialog.rup_dialog( {
			type: $.rup.dialog.DIV,
			autoOpen: false,
			modal: true,
			closeOnEscape: true,
			resizable: true,
			//width:600,
			//height:600,
			dialogClass: 'custom_mid_dialog',
			title: $.rup.i18n.app.botonera.add,
			buttons : [ 
                {
                    text:$.rup.i18n.app.botonera.aceptar,
                    id:"tipoAviso_aceptar_btn",
                    class: 'btn-material btn-material-primary-high-emphasis',
                    click:  () => {
                    	if ($("#tiposAviso_detail_form").valid()){
                    		const tipoAviso = $("#tiposAviso").rup_table("getSelectedRows");
                    		
                    		let data =  $('#tiposAviso_detail_form').rup_form("formToJson");

                    		let url = $('#tiposAviso_detail_form').attr("action") + "/";
                    		url += data["idTipoAviso40"] != null && data["idTipoAviso40"] != "" ? "edit" : "add";
                    		let type = data["idTipoAviso40"] != null && data["idTipoAviso40"] != "" ? "PUT" : "POST";
                    		
                    		$("#tiposAviso_detail_form").rup_validate("resetElements");
                    		
                        	$.rup_ajax({
        			            url: url,
                        	    type: type,
        			            contentType: "application/json",
        			            data: JSON.stringify(data),             	
        			            success: function (data){ 
        			            	// Inicializar el feedback
        							
        			            	$("#tiposAviso").rup_table("reload");
        			            	tipoAviso_dialog.rup_dialog("close");
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	$("#rup_feedback_tiposAviso").rup_feedback('set', $.rup.i18n.app.feedback.operacionOK, "ok"); 
        			            },
        			            beforeSend: function(){
        			            	Ad74aUtils.cerrarFeedbacks();
        			            	Ad74aUtils.bloquearInterfaz();
        						},
        						error:function(data){
        							
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	$("#tiposAviso_dialog_feedback").rup_feedback('set', data.responseText, "error");
        			            }
        			        });
                    	}
 					}
                 },
				{
					text : $.rup.i18n.app.botonera.cancelar,
					click : () => {
						tipoAviso_dialog.rup_dialog("close");
					},
					btnType : $.rup.dialog.LINK
				}
			],
			open: function(){
				const tipoAviso = $("#tiposAviso").rup_table("getSelectedRows");  
			},
			close: function(){
				$("#tiposAviso_detail_form").rup_form("clearForm");
				$("#tiposAviso_detail_form").rup_validate("resetElements");
				tipoAviso_dialog_feedback.rup_feedback("close");
			}		    
		});
		
		var propertiesSubtipoAviso={
				feedback:$("#subtiposAviso_detail_feedback"),
				liveCheckingErrors: false,
				showFieldErrorAsDefault: true,
				showErrorsInFeedback: true,
				showFieldErrorsInFeedback: true,
			  rules:{
			      "descEs41":{required:true},
			      "descEu41":{required:true}
			 }
		};
		$("#subtiposAviso_detail_form").rup_validate(propertiesSubtipoAviso);
		
		let subtipoAviso_dialog = $("#subtiposAviso_detail_div");
		let subtipoAviso_dialog_feedback = $("#subtiposAviso_detail_feedback");
		
		try {
			subtipoAviso_dialog.rup_dialog("destroy");
		} catch (error) {}
		
		subtipoAviso_dialog = $("#subtiposAviso_detail_div");
		subtipoAviso_dialog_feedback = $("#subtiposAviso_detail_feedback");
		
		subtipoAviso_dialog_feedback.rup_feedback (
			{
			  type: "ok",
			  block: false,
			}
		);	
		
		subtipoAviso_dialog.rup_dialog( {
			type: $.rup.dialog.DIV,
			autoOpen: false,
			modal: true,
			closeOnEscape: true,
			resizable: true,
			//width:600,
			//height:600,
			dialogClass: 'custom_mid_dialog',
			title: $.rup.i18n.app.botonera.add,
			buttons : [ 
                {
                    text:$.rup.i18n.app.botonera.aceptar,
                    id:"subtipoAviso_aceptar_btn",
                    class: 'btn-material btn-material-primary-high-emphasis',
                    click:  () => {
                    	const subtipoAviso = $("#subtiposAviso").rup_table("getSelectedRows");
                    	const tipoAviso = $("#tiposAviso").rup_table("getSelectedRows");
                    	let data = $('#subtiposAviso_detail_form').rup_form("formToJson");
                    	data.maestroTiposAviso = tipoAviso;
                    	
                    	let url = $('#subtiposAviso_detail_form').attr("action") + "/";
                		url += data["idSubTipoAviso41"] != null && data["idSubTipoAviso41"] != "" ? "edit" : "add";
                		let type = data["idSubTipoAviso41"] != null && data["idSubTipoAviso41"] != "" ? "PUT" : "POST";

                    	$.rup_ajax({
    			            url: url,
                    	    type: type,
    			            contentType: "application/json",
    			            data: JSON.stringify(data),             	
    			            success: function (data){    			            	
    			            	$("#subtiposAviso").rup_table("reload");
    			            	subtipoAviso_dialog.rup_dialog("close");
    			            	Ad74aUtils.desBloquearInterfaz();
    			            	$("#rup_feedback_subtiposaviso").rup_feedback('set', $.rup.i18n.app.feedback.operacionOK, "ok"); 
    			            },
    			            beforeSend: function(){
    			            	Ad74aUtils.cerrarFeedbacks();
    			            	Ad74aUtils.bloquearInterfaz();
    						},
    			            error:function(data){
    			            	Ad74aUtils.desBloquearInterfaz();
    			            	subtipoAviso_dialog_feedback.rup_feedback('set', data.responseText, "error");
    			            }
    			        });
 					}
                 },
				{
					text : $.rup.i18n.app.botonera.cancelar,
					click : () => {
						subtipoAviso_dialog.rup_dialog("close");
					},
					btnType : $.rup.dialog.LINK
				}
			],
			open: function(){
				const subtipoAviso = $("#subtiposAviso").rup_table("getSelectedRows");  
			},
			close: function(){
				$("#subtiposAviso_detail_form").rup_form("clearForm");
				$("#subtiposAviso_detail_form").rup_validate("resetElements");
				subtipoAviso_dialog_feedback.rup_feedback("close");
			}		    
		});
	}
	
	const initTable = () => {
		
		let tipoAviso_dialog = $("#tiposAviso_detail_div");
		let tipoAviso_dialog_feedback = $("#tiposAviso_dialog_feedback");
		let subtipoAviso_dialog = $("#subtiposAviso_detail_div");
		let subtipoAviso_dialog_feedback = $("#subtiposAviso_detail_feedback");
		
		const getColumnsModelTipoAviso = function(){
			const getColumnModelTipoAviso = function (name, index, editable, hidden, orderable) {
				return {
					name: name,
					index: index,
					editable: editable,
					hidden: hidden,
					orderable: orderable
				}
			};
			let columnsModelTipoAviso = [];
			columnsModelTipoAviso.push(getColumnModelTipoAviso("idTipoAviso40", "idTipoAviso40", false, false, true));
			columnsModelTipoAviso.push(getColumnModelTipoAviso("descEs40", "descEs40", true, false));
			columnsModelTipoAviso.push(getColumnModelTipoAviso("descEu40", "descEu40", true, false));
			columnsModelTipoAviso.push(getColumnModelTipoAviso("fBaja40", "fBaja40", false, false));
			return columnsModelTipoAviso;
		};

		const getColumnsDefsTipoAviso = function () {
			return [ 
			];
		};
		
		const getCustomButtonsTipoAviso = function () {
			let customButonsTipoAviso = [];	
			
			const FN_editarTipoAviso = {};
			FN_editarTipoAviso.test  = function(){
				const selectedRows  = $("#tiposAviso").rup_table("getSelectedRows");	
				// 1 seleccionado
				if ( selectedRows.length == undefined) {
					return true;
				}
				return false;
			};
			const anadirButton = {
					text: function () {
						return $.rup.i18n.app.botonera.add;
					},
					id: 'anadirTipoAviso', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-plus",
					displayRegex: /^\d+$/,				
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						tipoAviso_dialog.rup_dialog("open");
						const divTitleDialog = $("div[aria-describedby='tiposAviso_detail_div'] .ui-dialog-title");
						divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.edit+'</i>');
						$("#idTipoAviso40_detail_table").val("");
						tipoAviso_dialog_feedback.rup_feedback("close");
					}				
			};	
			customButonsTipoAviso.push(anadirButton);
			
			const editButton = {
					text: function () {
						return $.rup.i18n.app.botonera.edit;
					},
					id: 'editarTipoAviso', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-playlist-edit",
					displayRegex: FN_editarTipoAviso,		
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						$.rup_ajax({
				              url: $.rup.CTX_PATH +"maestrotiposaviso/"+ $('#tiposAviso').rup_table('getSelectedRows')['idTipoAviso40'],
				              type: "GET",            
				              dataType: 'json',
				              contentType: 'application/json',
				              beforeSend: function() {
				            	  Ad74aUtils.bloquearInterfaz();
				              },
				              complete: function() {
				            	  Ad74aUtils.desBloquearInterfaz();
				              },
				              success: function (data){
				              	 tipoAviso_dialog.rup_dialog("open");
				              	 const divTitleDialog = $("div[aria-describedby='tiposAviso_detail_div'] .ui-dialog-title");
								 divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.edit+'</i>');
				              	 $.rup_utils.populateForm($.rup_utils.jsontoarray(data), "#tiposAviso_detail_form");	
				              },
				              error: function(error){ 
				                  alert("error")
				              }
				        });
					}		
			};
			customButonsTipoAviso.push(editButton);
			
			return customButonsTipoAviso;
		};

		$("#tiposAviso").rup_table({
			colReorder: {
				fixedColumnsLeft: 0
			},
			colModel: getColumnsModelTipoAviso(),
			columnDefs: getColumnsDefsTipoAviso(),
			primaryKey: "idTipoAviso40",
	     	filter:"noFilter",
	     	createTooltipBody: false,// No muestra el tooltip automático de las columnas de la tabla
	   		select: {
	       		activate: true,
	       		multiSelect:false,
	       		deleteDoubleClick:true
	   		},
			buttons: {
				activate: true,
				blackListButtons: ['reportsButton', 'addButton', 'editButton', 'cloneButton', 'deleteButton', 'copyButton'],
				myButtons: getCustomButtonsTipoAviso()
			},
			columnOrderArrows: {
			    showOnlyActive: false,
			    display: 'inline'
			},
			order: [[0, "asc"]]
		});
		
		const getColumnsModelSubTipoAviso = function(){
			const getColumnModelSubTipoAviso = function (name, index, editable, hidden, orderable) {
				return {
					name: name,
					index: index,
					editable: editable,
					hidden: hidden,
					orderable: orderable
				}
			};
			let columnsModelSubTipoAviso = [];
			columnsModelSubTipoAviso.push(getColumnModelSubTipoAviso("idSubTipoAviso41", "idSubTipoAviso41", false, false, true));
			columnsModelSubTipoAviso.push(getColumnModelSubTipoAviso("maestroTiposAviso.idTipoAviso40", "maestroTiposAviso.idTipoAviso40", true, true, false));
			columnsModelSubTipoAviso.push(getColumnModelSubTipoAviso("descEs41", "descEs41", true, false));
			columnsModelSubTipoAviso.push(getColumnModelSubTipoAviso("descEu41", "descEu41", true, false));
			columnsModelSubTipoAviso.push(getColumnModelSubTipoAviso("fBaja41", "fBaja41", false, false));
			return columnsModelSubTipoAviso;
		};

		const getColumnsDefsSubTipoAviso = function () {
			return [ 
			];
		};
		
		const getCustomButtonsSubTipoAviso = function () {
			let customButonsSubTipoAviso = [];	
			
			const FN_editarSubTipoAviso = {};
			FN_editarSubTipoAviso.test  = function(){
				const selectedRows  = $("#subtiposAviso").rup_table("getSelectedRows");	
				// 1 seleccionado
				if ( selectedRows.length == undefined) {
					return true;
				}
				return false;
			};
			
			const FN_anyadirSubTipoAviso = {};
			FN_anyadirSubTipoAviso.test  = function(){
				const selectedRows  = $("#tiposAviso").rup_table("getSelectedRows");	
				// 1 seleccionado
				if ( selectedRows.length == undefined) {
					return true;
				}
				return false;
			};
			const anadirButton = {
					text: function () {
						return $.rup.i18n.app.botonera.add;
					},
					id: 'anadirSubTipoAviso', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-plus",
					displayRegex: FN_anyadirSubTipoAviso,				
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						subtipoAviso_dialog.rup_dialog("open");
						const divTitleDialog = $("div[aria-describedby='subtiposAviso_detail_div'] .ui-dialog-title");
						divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.add+'</i>');
						$("#idSubTipoAviso41_detail_table").val("");
						subtipoAviso_dialog_feedback.rup_feedback("close");
					}				
			};	
			customButonsSubTipoAviso.push(anadirButton);
			
			const editButton = {
					text: function () {
						return $.rup.i18n.app.botonera.edit;
					},
					id: 'editarSubTipoAviso', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-playlist-edit",
					displayRegex: FN_editarSubTipoAviso,			
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						$.rup_ajax({
				              url: $.rup.CTX_PATH +"maestrosubtiposaviso/"+ $('#subtiposAviso').rup_table('getSelectedRows')['idSubTipoAviso41'],
				              type: "GET",            
				              dataType: 'json',
				              contentType: 'application/json',
				              beforeSend: function() {
				            	  Ad74aUtils.bloquearInterfaz();
				              },
				              complete: function() {
				            	  Ad74aUtils.desBloquearInterfaz();
				              },
				              success: function (data){
				              	 subtipoAviso_dialog.rup_dialog("open");
				              	 const divTitleDialog = $("div[aria-describedby='subtiposAviso_detail_div'] .ui-dialog-title");
								 divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.edit+'</i>');
				              	 $.rup_utils.populateForm($.rup_utils.jsontoarray(data), "#subtiposAviso_detail_form");	
				              },
				              error: function(error){ 
				                  alert("error")
				              }
				        });
					}		
			};
			customButonsSubTipoAviso.push(editButton);
			
			return customButonsSubTipoAviso;
		};

		$("#subtiposAviso").rup_table({
			loadOnStartUp: false,
			colReorder: {
				fixedColumnsLeft: 1
			},
			colModel: getColumnsModelSubTipoAviso(),
			columnDefs: getColumnsDefsSubTipoAviso(),
			primaryKey: "idSubTipoAviso41",
			filter:{
	  	  		id:"subtiposAviso_filter_form",
	  	  		filterToolbar:"subtiposAviso_filter_toolbar",
	  	  		collapsableLayerId:"subtiposAviso_filter_fieldset",
	  	  		showHidden: true
	     	},
	     	createTooltipBody: false,// No muestra el tooltip automático de las columnas de la tabla
	   		select: {
	       		activate: true,
	       		multiSelect:false,
	       		deleteDoubleClick:true
	   		},
			buttons: {
				activate: true,
				blackListButtons: ['reportsButton', 'addButton', 'editButton', 'cloneButton', 'deleteButton', 'copyButton'],
				myButtons: getCustomButtonsSubTipoAviso()
			},
			columnOrderArrows: {
			    showOnlyActive: false,
			    display: 'inline'
			},
			order: [[1, "asc"]],
			masterDetail: {
	            master: '#tiposAviso',
	            masterPrimaryKey: 'maestroTiposAviso.idTipoAviso40'
	    	},
	    	seeker : {}
		});
	}
});
