var hideEntities = true;
//var showInactive = false;
var estadoActivas = "";

var isCheckedKG=false;
var isCheckedOF=false;
var isCheckedKN=false;
var isCheckedCW=false;
  
var contChecks = 4;

jQuery(document).ready(function(){
	var props={
			type:"ok",
			delay:800,
			goTop:false,
			block:false,
			closeLink:true
	};
	
	//debugger;
	$("#searchActivasSi").prop('checked',true);
	estadoActivas = controlChecksActiva(); //ver que se marca en pantalla el activa por defecto y modificar el arbol (su construccion parametros.)
	
	
	$("#search_avisos").rup_feedback(props);
	
	$.rup_date({
		from : "searchDateAfter",
		to : "searchDateBefore",
		duration : "fast"
	});
	
	pintarFecha();
	
	$("#y42bSearchCleanDateAfter").click(function () {
        $("#searchDateAfter").val("");
        $("#searchDateBefore").rup_date("destroy"); //destruir la parte del hasta
        pintarFecha(); //repintar
        
    });
	$("#y42bSearchCleanDateBefore").click(function () {
        $("#searchDateBefore").val("");
        $("#searchDateAfter").rup_date("destroy"); //destruir la parte del hasta
        pintarFecha(); //repintar
    });
	
	loadTree();
	bindTreeRadioButtons();
	initLabels();
	initItemGrid();
	
	$("#search_bt_editar_etiquetas").click(function(){
		$("#capaEtiquetas").rup_dialog("destroy");
		$("#capaEtiquetas").rup_dialog({
			width: "600",
			modal: true,
			resizable: false,
			url: "/y42bVistaWar/etiqueta/vista?entidadId=-2",
			type:$.rup.dialog.AJAX,
			autoOpen: true
		});
	});
	
	$("#searchEnvelopeType").rup_combo({
		source : [{i18nCaption: "etiquetas_3x8",value:"3x8",style:""},
		          {i18nCaption: "etiquetas_2x8",value:"2x8",style:""}
				],
		width:"200",
		blank:"0"
	});
	
	$("#searchExcelCombo").rup_combo({
		source : [{i18nCaption: "entidades",value:"E",style:""},
		          {i18nCaption: "entidades_grupos",value:"EG",style:""}
				],
		width:"250",
		blank:"0"
	});
	
	
	
	
	
	bindActionButtons();
	
	$("#lista_etiquetas").dynatree({
		initAjax: {
			url: "../search/lista_etiquetas",
			data: {key: "root", // Optional arguments to append to the url
					mode: "all"
				  }
		},
		activeVisible: true, // Make sure, active nodes are visible (expanded).
		checkbox: true, // Show checkboxes.
		selectMode: 2, // 1:single, 2:multi, 3:multi-hier
		onClick: function(node, event) {
			// We should not toggle, if target was "checkbox", because this
			// would result in double-toggle (i.e. no toggle)
			if( node.getEventTargetType(event) == "title" ) {
				node.toggleSelect();
			}
			
		},
		onSelect: function(select, node) {
			// Display list of selected nodes
			var selNodes = node.tree.getSelectedNodes();
			// convert to key array
			var keyList = $.map(selNodes, function(node){
				return node.data.key;
			});
			
			$("#etiquetasIdList").val(keyList);
			
		},
		// The following options are only required, if we have more than one tree on one page:
		cookieId: "group_list_dynatree",
		idPrefix: "group_list_dynatree"
	});
	
	//botones contraer y expandir arbol 
	$("#y42bsearchtree_expandir").click(function () {
		$("#search_tree").dynatree("getRoot").visit(function(node){
			 node.expand(true);
		});
		return false;
	}); 

	$("#y42bsearchtree_contraer").click(function () {
		$("#search_tree").dynatree("getRoot").visit(function(node){
			 node.expand(false);
		});
		return false;
	}); 
	
	y42bSearch_PintarComboProvincia();
	y42bSearch_PintarComboMunicipio();
	y42bSearch_PintarComboLocalidad();
	//pais
	y42bSearch_PintarComboPais();
	
	$("#y42bSearchTodos").attr("checked", "checked");
	y42bSearch_eventoClickTodos();
	
	if (y42bSearch_UsuarioTipoAcceso != $("#y42bSearch_CteTipoAcceso_Administrador").val()){
		y42bSearchSoloConsulta();
	}
	
	
});

function pintarFecha(){
    $.rup_date({
        from : "searchDateAfter",
        to : "searchDateBefore",
        duration : "fast"
    });
}
function loadTree(){	
	//alert(">>"+estadoActivas+"<<");
	$("#search_tree").dynatree({
		initAjax: {
			url: "../search/tree",
			data: {
				mode: "funnyMode" ,
				estadoActivas: estadoActivas, //showInactive,
				hideEntities: hideEntities
			}
		},
		activeVisible: true, // Make sure, active nodes are visible (expanded).
		checkbox: true, // Show checkboxes.
		selectMode: 3, // 1:single, 2:multi, 3:multi-hier
	    onPostInit: function(isReloading, isError) {
	    	$("#search_tree").dynatree("getRoot").visit(function(node){
				 node.expand(false);
			});
			return false;
	    },
		onClick: function(node, event) {
			// We should not toggle, if target was "checkbox", because this
			// would result in double-toggle (i.e. no toggle)
			if( node.getEventTargetType(event) == "title" ) {
				node.toggleSelect();
			}
		},
		onSelect: function(select, node) {						
			// Display list of selected nodes
			var selNodes = node.tree.getSelectedNodes();
			
			// get group key array
			var keyListG = $.map(selNodes, function(node){				
				var myKey=node.data.key;
				if (myKey == "ROOT"){
					return "ROOT";
				}
				//alert('myKeyG'+myKeyG);
				if (myKey.indexOf("G_")>-1){
					return node.data.key;
				}
				if (myKey.indexOf("E_")>-1){
					return node.data.key;
				}
			});
			$("#searchGroupIdList").val(keyListG);
			// get entity key array
			/*var keyListE = $.map(selNodes, function(node){
				var myKeyE=node.data.key;
				alert('myKeyE'+myKeyE);
				if (myKeyE.lastIndexOf("E_")>-1){
					return node.data.key;
				}
			});*/
			$("#searchEntityIdList").val(keyListG);
		}
	});
}

function reloadTree(){
	$("#search_tree_container").html("<div id=\"search_tree\"></div>");
	$("#searchGroupIdList").val("");
	$("#searchEntityIdList").val("");
	loadTree();
//	$("#search_tree").dynatree("getTree").reload();
}



$("#y41bConsultaEdicionSexoH").attr('checked', true);

function controlChecksActiva(){
	
	if ($("#searchActivasSi").prop("checked") == true && $("#searchActivasNo").prop("checked") == false){
		estadoActivas = "A"; //activas
	}else if ($("#searchActivasSi").prop("checked") == false && $("#searchActivasNo").prop("checked") == true){
		estadoActivas = "I"; //inactivas
	}else{
		estadoActivas = "T"; //todas
	}
	return estadoActivas;
}


function bindTreeRadioButtons(){
	
	$("#searchActivasSi").click(function(){
		controlChecksActiva();
		reloadTree();
	});
	
	$("#searchActivasNo").click(function(){
		controlChecksActiva();
		reloadTree();
	});
		
	//$("#searchShowInactiveEntities").click(function(){
	//	if(this.checked == true) { 
	//		showInactive = true;
	//	}else{
	//		showInactive = false;
	//	}
	//	reloadTree();
	//});	

	$("#searchEntidad").click(function(){
		//alert("entidad");
		hideEntities = true;
		reloadTree();
		$("#searchDIVExcelCombo").show();
	});
	
	$("#searchContact").click(function(){
		//alert("contacto");
		hideEntities = false;
		reloadTree();
		$("#searchDIVExcelCombo").hide();
	});
}

function initLabels(){
}

var contador=0;
var setPreselected = false;

function initItemGrid(){
	var searchResultGridWidth = $("#panelDchoBotton").width() - 15;
	$("#searchResultGrid").rup_grid({
		width: searchResultGridWidth,
//		mtype: "POST",
		url:"../search/",
		pagerName: "searchResultGridPager",
		rowNum: "10",
		rowList: [10,20,30,40,50,100,200,500,1000,2000,5000],
		sortorder: "asc",
		sortname: "nombre",
		loadOnStartUp: false,
		multiselect: true,
		multiselectWidth: "15",
		multiboxonly: false,
		colNames:[
			$.rup.i18n.app.contact_grid.id,
			$.rup.i18n.app.contact_grid.nombre,
			$.rup.i18n.app.contact_grid.localizacion,
			$.rup.i18n.app.contact_grid.telefono,
			$.rup.i18n.app.contact_grid.email,
			""
		],
		colModel:[
			{
				name: "itemRef",
				index: "itemRef",
				hidden: true,
				formatter: y42bFormateadorRojo
			},
			{
				name: "nombre",
				index: "nombre",
				width: funcPercentage(35,searchResultGridWidth),
				formatter: y42bFormateadorRojo
				
			},
			{
				name: "nombreLocalizacion",
				index: "nombreLocalizacion",
				width: funcPercentage(25,searchResultGridWidth),
				align: "center",
				formatter: y42bFormateadorRojo
			},
			{
				name: "telefono",
				index: "telefono",
				width: funcPercentage(15,searchResultGridWidth),
				align: "right",
				formatter: y42bFormateadorRojo
			},
			{
				name: "email",
				index: "email",
				width: funcPercentage(25,searchResultGridWidth),
				align: "center",
				formatter: y42bEmailFormateadorLink
				,formatter: y42bFormateadorRojo
			},
			{
				name: "activa",
				index: "activa",
				hidden: true,
				width: funcPercentage(10,searchResultGridWidth),
				align: "center",
				formatter: y42bFormateadorRojo
			}
		],
		onPaging: function(id, select, e) { //al paginar resetea el contador, ya que se pierde la seleccion
			resetSeleccionados(false);
			contador = 0;
			y42bPintaPagerSeleccionados(contador);
		},
		onSortCol: function(index, iCol, sortorder) { //al ordenar por columna resetea el contador, ya que se pierde la seleccion
			resetSeleccionados(false);
			contador = 0;
			y42bPintaPagerSeleccionados(contador);
		},
		onSelectRow : function(id, select, e) {
			if (select){
				contador++;
			}else{
				contador--;
			}
			y42bPintaPagerSeleccionados(contador);

			toggleRowItemStatus(id, select);
		},
		onSelectAll : function(aRowids, select){
			if (select){
				contador = aRowids.length; 
			}else{
				contador = 0; 
			}
			y42bPintaPagerSeleccionados(contador);

			for(var i=0; i<aRowids.length; i++) {
				toggleRowItemStatus(aRowids[i], select);
			}
		},
		gridComplete : function(){
	     
			if(setPreselected) {
				var idArray = $("#searchResultGrid").rup_grid("getDataIDs");
				for(var i=0; i<idArray.length; i++) {
					$("#searchResultGrid").rup_grid("setSelection", idArray[i]);
				}
			}
		}
	});
	
	
	
	
	
	function y42bFormateadorRojo(cellvalue, options, rowObject) {
		if (cellvalue!=null)
			if (rowObject.activa == "N"){
				return "<label style='color: red;'>"+cellvalue+"</label>";
			}else{
				return cellvalue;
			}
		else
			return "";
	}
	
	
	
	//FIXME Migracion UDA V.2.4.4 (201504) - Añadimos el rup_maint para el corrcto funcionamiento de la tabla
	$("#multi").rup_maint({
        jQueryGrid: "searchResultGrid",
        primaryKey: "itemRef",
		toolbar:{
	    	defaultAdd: false,
	    	defaultEdit: false,
	    	defaultDelete: false,
	    	defaultFilter: false
    	}
	});    
}

function y42bEmailFormateadorLink(cellvalue, options, rowObject) {
	if (null!=cellvalue){
		return "<a href='#' onClick='y42bFunMailTo("+ options.rowId  +");'>" + cellvalue + "</a>";
	}else{
		return "";
	}
}

function y42bFunMailTo(rowid){
	var fila = $("#searchResultGrid").rup_grid("getRowData", rowid);
	var email = y42bEliminarHref(fila.email);
		
	if (null!=email){
		var mailto_link = "mailto:"+ email;
		window.location.href = mailto_link;
	}
}

//funcion mailto
function y40aFunTabDetalleSolicitanteMailTo(email){
	if (null!=email){
		var html = "<a  href=mailto:"+email+">"+email+"</a>";
		$(html).appendTo($("#y40aTabDetalleSolicitanteContactoEmail"));
	}
}

function y42bPintaPagerSeleccionados(contador){
	$('#searchResultGridPager_left').html("");
	$('#searchResultGridPager_left').append( $('<div/>').addClass('ui-paging-selected').html(contador+" " + $.rup.i18n.base.rup_grid.pager.selected));
}

function toggleRowItemStatus(rowId, select){
	var row = $("#searchResultGrid").rup_grid("getRowData", rowId);
	//debugger;
	if(select){
		selectRow(stripHTML(row.itemRef));
	} else {
		unselectRow(stripHTML(row.itemRef));
	}
}

function selectRow(itemRef){
	$.ajax({
		type : 'GET',
		url : "/y42bVistaWar/search/select?itemRef="+itemRef +"&envioId="+$("#searchEnvioId").val(),
		error : function(jqXHR, textStatus, errorThrown) {
			/*$("#search_avisos").rup_feedback("option", "delay",null);
			$("#search_avisos").rup_feedback("set",textStatus + ": error", "error");*/
		},
		success : function(data, textStatus, jqXHR) {
			//$("#search_avisos").rup_feedback("option", "delay",800);
			//$("#search_avisos").rup_feedback("set", "ok", "ok");
		}
	});
}

function unselectRow(itemRef){
	$.ajax({
		type : 'GET',
		url : "/y42bVistaWar/search/unselect?itemRef="+itemRef +"&envioId="+$("#searchEnvioId").val(),
		error : function(jqXHR, textStatus, errorThrown) {
			/*$("#search_avisos").rup_feedback("option", "delay",null);
			$("#search_avisos").rup_feedback("set",textStatus + ": error", "error");*/
		},
		success : function(data, textStatus, jqXHR) {
			//$("#search_avisos").rup_feedback("option", "delay",800);
			//$("#search_avisos").rup_feedback("set", "ok", "ok");
		}
	});
}

function bindActionButtons(){
	$("#searchCodeSelectionButton").click(function(){
		loadCodeSelectionDialog();
	});
	
	$("#searchSearchButton").click(function(){
		$("#searchResultGrid").rup_grid("resetSelection");
		search();
	});
	
	$("#searchCleanButton").click(function(){
		
		cleanSearch();
		
	});
	
	$("#searchMassiveActionButton").click(function(){
		loadMassiveActionDialog();
	});
	
	$("#searchEnvelopesButton").click(function(){
		getEnvelopes();
	});
	
	$("#searchExcelButton").click(function(){
		getExcel();
	});
	
	$("#searchSendEmailButton").click(function(){
		loadSendEmailDialog();
	});
	
	$("#searchDetailButton").click(function(){
		if($("#searchResultGrid").rup_grid("getSelectedRows").length > 1
				|| $("#searchResultGrid").rup_grid("getSelectedRows").length == 0){
			alert($.rup.i18n.app.search_dialog.detailMultipleSelection);
		} else {
			loadDetailDialog();
		}
	});
}

var botonBuscarPulsado = false;

function search() {
	
	if (!botonBuscarPulsado){      
        //comprobar que llegan entidades en la lista
              
        var  cadenaEntidades = $("#searchEntityIdList").val();
        cadenaEntidades = cadenaEntidades.indexOf("E_");        
        
        if ( (cadenaEntidades ==-1) && ($("#searchContact").attr('checked') == "checked") ){
        	$("#search_avisos").rup_feedback("option", "delay", 800);
			$("#search_avisos").rup_feedback("set", $.rup.i18n.app.msg.arbolSinEntidades, "warning");
			$("#searchResultGrid").rup_grid("clearGridData");
        }else{
        	botonBuscarPulsado = true;
    		//Añadimos la imagen de carga en el contenedor
        	$('#y42bSearchDivContent').html('<img src="'+$.rup.APP_STATICS+'/images/loading.gif"/>');
        	$('#y42bSearchDivContent').css("display","inline");
            //$('#y42bSearchDivContent').html('<div><img src="'+$.rup.APP_STATICS+'/images/loading.gif"/></div>');
            
        	$.ajax({
				type : 'POST',
				url : "/y42bVistaWar/search/busqueda", //ññ en el busqueda construye los items asi que ahi meter el activa para el item, en el load recuperar parala tabla el activa y en funcion de el poner a rojo
				dataType : "json",
				data : $('#searchForm').serialize(),
				error : function(jqXHR, textStatus, errorThrown) {
					botonBuscarPulsado = false;
					//$('#y42bSearchDivContent').html('');
					$('#y42bSearchDivContent').css("display","none");
					
					$("#search_avisos").rup_feedback("option", "delay", null);
					$("#search_avisos").rup_feedback("set", $.rup.i18n.app.msg.errorbusqueda, "error");
				},
				success : function(data, textStatus, jqXHR) {
					//alert("data.envioId= "+$.toJSON(data.envioId));
					loadGridResults(data.envioId, false);
					//alert("envio id: "+data.envioId);
					botonBuscarPulsado = false;
					//$('#y42bSearchDivContent').html('');
					$('#y42bSearchDivContent').css("display","none");
				}
			});
        }
	}
}

function loadGridResults(envioId, setSelected){
	
	$("#searchResultGrid").rup_grid("clearGridData");
	$("#searchEnvioId").val(envioId);
	$("#searchResultGrid").rup_grid("setGridParam", {url: "../search/items?envioId="+$("#searchEnvioId").val()});
	$("#searchResultGrid").rup_grid("reloadGrid");
	
	setPreselected = setSelected;

	$('#searchResultGridPager_left').html("");	
	$('#searchResultGridPager_left').append( $('<div/>').addClass('ui-paging-selected').html("0 " + $.rup.i18n.base.rup_grid.pager.selected));
	contador=0;
	
	
}

function loadCodeSelectionDialog(){	
		$("#searchCodeSelectionDialog").rup_dialog("destroy");
		$("#searchCodeSelectionDialog").rup_dialog({
			modal: true,
			resizable: false,
		    height: "auto",
		    width: 800,
		    title: $.rup.i18n.app.search_dialog.codeSelection,
			url: "../search/selectByCodes",
			type:$.rup.dialog.AJAX,
			autoOpen: true
		});
}


function loadMassiveActionDialog(){
	if($("#searchResultGrid").rup_grid("getSelectedRows").length == 0){
		alert($.rup.i18n.app.msg.errorEnvioNoExiste);
	} else {
		var envioId=$("#searchEnvioId").val();
		if (envioId!=""){ 
			if($("#searchResultGrid").rup_grid("getSelectedRows").length > 0){
				var url = "../envio/accionesmasivas/"+$("#searchEnvioId").val();
				$("#searchMassiveActionDialog").rup_dialog("destroy");
				$("#searchMassiveActionDialog").rup_dialog({
				      modal: true,
				      resizable: false,        
				      height: "auto",
				      width: 700,
				      url: url,
				      title: $.rup.i18n.app.search_dialog.massiveAction,
				      type:$.rup.dialog.AJAX,
				      autoOpen: true
				});
			
			}else{
				
			}	
		}else{
			alert($.rup.i18n.app.msg.errorEnvioNoExiste);
		}
	}
}

function loadSendEmailDialog(){	
	if($("#searchResultGrid").rup_grid("getSelectedRows").length == 0){
		alert($.rup.i18n.app.search_dialog.detailMultipleSelectionMail);
	} else {		
		y42bVarEnvioId = $("#searchEnvioId").val();
		y42bVarDeEnvio = false;
		$("#searchSendEmailDialog").rup_dialog("destroy");
		$("#searchSendEmailDialog").rup_dialog({
			height: "auto",
			resizable: false,
		    width: 882,
			modal: true,
			url: "../search/sendMail/"+$("#searchEnvioId").val(),
			type:$.rup.dialog.AJAX,
			title: $.rup.i18n.app.search_dialog.sendEmail,
			autoOpen: true,
			beforeclose: function(){
				$("#searchResultGrid").rup_grid("resetSelection");
				search();			
			}
		});
	}
}

function loadDetailDialog(){
	//var rowId = $("#searchResultGrid").rup_grid("getSelectedRows")[0];
	//FIXME Migracion UDA V.2.4.4 (201504) - Modificamos el modo en que se recupera el rowId
	var rowId=$("#searchResultGrid").jqGrid("getGridParam", "selrow");		
	var selectedRow=$("#searchResultGrid").rup_grid("getRowData", rowId);
	
	
	
	$.ajax({
		type : 'GET',
		url : "../envio/"+$("#searchEnvioId").val(),
		dataType : "json",
		error : function(jqXHR, textStatus, errorThrown) {
			$("#search_avisos").rup_feedback("option", "delay",
					null);
			$("#search_avisos").rup_feedback("set",
					textStatus + ": error", "error");
		}, 
		success : function(data, textStatus, jqXHR) {			
			var url;
			var title;
			if("E" == data.tipo){
				url = '../search/entityDetail?entityId=' + stripHTML(selectedRow.itemRef); 
				title = $.rup.i18n.app.search_dialog.entityDetail;
			} else {
				url = '../search/contactDetail?contactId=' + stripHTML(selectedRow.itemRef);
				title = $.rup.i18n.app.search_dialog.contactDetail;
			}
			Cerrar = $.rup.i18n.app.search_dialog.close;
						
			
			
			$("#searchDetailDialog").rup_dialog("destroy");			
			$('#searchDetailDialog').rup_dialog({
		        modal: true,
		        resizable: false,
		        url: url,     
		        height: 600,
		        width: 800,
		        title: title,
		        type:$.rup.dialog.AJAX,
		        autoOpen: true,
				buttons: {
		        	Cerrar: function() {
		        		$(this).dialog("close");
		        	}
				}
		    });
		}
	});
}

function getEnvelopes(){
	if($("#searchResultGrid").rup_grid("getSelectedRows").length > 0){
		if ($("#searchEnvioId").val()==""){
			alert($.rup.i18n.app.msg.errorEnvioNoExiste);
		}else if (($("#searchEnvelopeType").val()!="2x8" && $("#searchEnvelopeType").val()!="3x8") ){
			alert($.rup.i18n.app.msg.errorEtiquetasTamañoExiste); 
		}else{	
			var urlEnvelopes="../envio/etiquetas/" + $("#searchEnvioId").val() + "/"+$("#searchEnvelopeType").val();
			window.open(urlEnvelopes);
		}
	}else{
		alert($.rup.i18n.app.msg.errorEnvioNoExiste);
	}	
}

function getExcel(){
	var envioId=$("#searchEnvioId").val();
	//alert("javi env_id:"+envioId);
	//debugger;
	if($("#searchResultGrid").rup_grid("getSelectedRows").length > 0){
		if ($("#searchEnvioId").val()==""){
			alert($.rup.i18n.app.msg.errorEnvioNoExiste);
		}else if ($("#searchEntidad").attr('checked') == 'checked'){
			
			if (($("#searchExcelCombo").val()!="E" && $("#searchExcelCombo").val()!="EG") ){
				alert($.rup.i18n.app.msg.errorTipoExcel); 
			}else{	
				var urlExcel="../search/excel/"+$("#searchEnvioId").val()+"?tipoExcel="+$("#searchExcelCombo").val();
				window.open(urlExcel);
			}
		}else if ($("#searchContact").attr('checked') == 'checked'){
			var urlExcel="../search/excel/"+$("#searchEnvioId").val();
			window.open(urlExcel);
		}
	}else{
		alert($.rup.i18n.app.search_dialog.detailMultipleSelectionExcel);
	}	
	
	
	
	
	
	
//	if($("#searchResultGrid").rup_grid("getSelectedRows").length > 0){
//		var urlExcel="../search/excel/"+$("#searchEnvioId").val()+"?tipoExcel="+$("#searchExcelCombo").val();
//		window.open(urlExcel);
//	}else{
//		alert($.rup.i18n.app.search_dialog.detailMultipleSelectionExcel);
//	}
}

function cleanSearch(){
		resetSeleccionados(false);
		hideEntities = true;
		//showInactive = false;
		estadoActivas = "";
		reloadTree();
		$("#searchEntidad").attr('checked', true);
		$("#searchDIVExcelCombo").show();
		$("#searchContact").attr('checked', false);
		//$("#searchShowInactiveEntities").attr('checked', false);
		
		$("#searchName").val("");
	
		$("#searchKontsumoGest").attr('checked', true);
		$("#searchFormativa").attr('checked', true);
		$("#searchKontsumoNet").attr('checked', true);
		$("#searchConsultaWeb").attr('checked', true);
		contChecks = 4;
		
		$("#y42bSearch_RBCualquiera").attr('checked', true);
		
		
		
		$("#searchLocationRadioTodas").click();
		
		$("#y42bSearch_ComboProvincia").rup_combo("select", "");
//		$("#searchProvinceId").rup_combo("select", "");
//		$("#searchMunicipalityId").rup_combo("select", "");
//		$("#searchLocalityId").rup_combo("select", "");
		$("#searchCP").val("");
		$("#searchPaisCP").val("");
//		$("#searchCountryId").rup_combo("select", "");
		$("#y42bSearch_ComboPais").rup_combo("select", "");
		$("#y42bSearch_Direccion").val("");
		$("#searchPC").val("");
		$("#searchCalleId").val("");
		$("#searchLocalidadInterId").val("");
		
		$("#etiquetas").val("");
		$("#etiquetasIdList").val("");
		
	    $("#searchDateAfter").val("");
	    $("#searchDateBefore").rup_date("destroy"); //destruir la parte del hasta
	    pintarFecha(); //repintar
	    
	    $("#searchDateBefore").val("");
	    $("#searchDateAfter").rup_date("destroy"); //destruir la parte del hasta
	    pintarFecha(); //repintar
	
		$("#searchResultGrid").rup_grid("clearGridData");
		
		$("#y42bSearchTodos").attr("checked", "checked");
		y42bSearch_eventoClickTodos();
}


// Resetear seleccionados
function resetSeleccionados(boolSeleccionado){
	if ($("#searchEnvioId").val()!=""){
		var jqxhr = $.ajax({
			type : 'DELETE',
			url : "../search/updateSeleccion/" + $("#searchEnvioId").val()+ "/"+ boolSeleccionado,
			error: function (jqXHR, textStatus, errorThrown){
				switch(jqXHR.status){		
					case 406:
	//					alert("eliminar seleccion ko 1");
	//					$("#search_avisos").rup_feedback("option", "delay",null);
	//					$("#search_avisos").rup_feedback("set",jqXHR.responseText, "error");
						break;
						
					//case 500:	
					default:
	//					alert("eliminar seleccion ko 2");
	//					$("#search_avisos").rup_feedback("option", "delay",null);
	//					$("#search_avisos").rup_feedback("set",$.rup.i18n.app.msg.errorModifDatos, "error");
						break;
				}
			},
			success : function(data) {
	//					$("#search_avisos").rup_feedback("option", "delay",800);
	//					$("#search_avisos").rup_feedback("set", "ok", "ok");
			}
		});
	}
	$("#searchResultGrid").rup_grid("resetSelection");
}



$("#searchModifyButton").click(function(){
	if($("#searchResultGrid").rup_grid("getSelectedRows").length > 1
			|| $("#searchResultGrid").rup_grid("getSelectedRows").length == 0){
		alert($.rup.i18n.app.search_dialog.detailMultipleSelection);
	} else {
		//var selectedRow = $("#searchResultGrid").rup_grid("getSelectedRows")[0];
		//FIXME Migracion UDA V.2.4.4 (201504) - Modificamos el modo en que se recupera el rowId
		var selectedRow=$("#searchResultGrid").jqGrid("getGridParam", "selrow");	
		row = $("#searchResultGrid").rup_grid("getRowData", selectedRow);
		var codigo = stripHTML(row.itemRef); 
		location.href = "/y42bVistaWar/mant/vista?idBusqueda="+codigo;
	}
});

$("#searchSendEmailToAllButton").click(function(){
	var numeroDeRegistros = $("#searchResultGrid").getGridParam("records");
	if(numeroDeRegistros>0){
		//poner todos los registros resultado del filtraje como seleccionados
		resetSeleccionados(true);
		
		//abrir email
		$("#searchSendEmailDialog").rup_dialog("destroy");
		$("#searchSendEmailDialog").rup_dialog({
			height: "auto",
			resizable: false,
		    width: 850,
			modal: true,
			url: "../search/sendMail/"+$("#searchEnvioId").val(),
			type:$.rup.dialog.AJAX,
			title: $.rup.i18n.app.search_dialog.sendEmail,
			autoOpen: true,
			close:function(event, ui){
				cleanSearch();
			}
		});
	}else{
		$("#search_avisos").rup_feedback("option", "delay",800);
		$("#search_avisos").rup_feedback("set",$.rup.i18n.app.msg.emailtodossintabla, "alert");
	}
});

//RADIO BUTTONS Estado - Extranjero ...
$("#y42bSearchTodos").click(function (){
	y42bSearch_eventoClickTodos();
});

$("#y42bSearchEstado").click(function (){
	y42bSearch_eventoClickEstado();
});
		   
$("#y42bSearchExtranjero").click(function (){		   
	y42bSearch_eventoClickExtranjero();
});

function y42bSearch_eventoClickTodos(){
	y42bSearch_ResetearComboProvincia();
	y42bSearch_ResetearComboMunicipio();
	y42bSearch_ResetearComboLocalidad();
	$("#y42bSearch_ResidenciaExtranjeroSi").css("display", "none");
	$("#y42bSearch_ResidenciaExtranjeroNo").css("display", "none");
	$("#y42bSearch_ResidenciaTodosNo").css("display", "block");
}

function y42bSearch_eventoClickEstado(){
	y42bSearch_PintarComboProvincia();
	y42bSearch_PintarComboMunicipio();
	y42bSearch_PintarComboLocalidad();
	$("#y42bSearch_ResidenciaExtranjeroNo").css("display", "block");
	$("#y42bSearch_ResidenciaExtranjeroSi").css("display", "none");
	$("#y42bSearch_ResidenciaTodosNo").css("display", "none");
}

function y42bSearch_eventoClickExtranjero(){
	y42bSearch_ResetearComboProvincia();
	y42bSearch_ResetearComboMunicipio();
	y42bSearch_ResetearComboLocalidad();
	y42bSearch_PintarComboPais();
	$("#y42bSearch_ResidenciaExtranjeroSi").css("display", "block");
	$("#y42bSearch_ResidenciaExtranjeroNo").css("display", "none");
	$("#y42bSearch_ResidenciaTodosNo").css("display", "none");
}

/* ********************
 * Combo provincia NORA
 * ********************
 */
function y42bSearch_ResetearComboProvincia(){
	$("#y42bSearch_ComboProvincia-button").remove();
	$("#y42bSearch_ComboProvincia-menu").remove();
	$('<select class="rup-combo" id="y42bSearch_ComboProvincia" name="provinciaId"></select>').replaceAll("#y42bSearch_ComboProvincia");
}

function y42bSearch_PintarComboProvincia(){
	y42bSearch_ResetearComboProvincia();
	$("#y42bSearch_ComboProvincia").rup_combo({
		source : "/y42bVistaWar/nora/provinciasTodas",
		blank : "",
		sourceParam : {	label : "dsO", value : "id"	},
		width : 250
	});	
}

/* ********************
 * Combo municipio NORA
 * ********************
 */
function y42bSearch_ResetearComboMunicipio(){
	$("#y42bSearch_ComboMunicipio-button").remove();
	$("#y42bSearch_ComboMunicipio-menu").remove();
	$('<select class="rup-combo" id="y42bSearch_ComboMunicipio" name="municipioId"></select>').replaceAll("#y42bSearch_ComboMunicipio");
}

function y42bSearch_PintarComboMunicipio(){
	y42bSearch_ResetearComboMunicipio();
	$("#y42bSearch_ComboMunicipio").rup_combo({
		parent: [ "y42bSearch_ComboProvincia" ],
		source : "/y42bVistaWar/nora/municipios?R01HNoPortal=true",
		blank : "",
		sourceParam : {	label : "dsO",	value : "id"},
		width : 250
	});
}	
	
/* ********************
 * Combo localidad NORA
 * ********************
 */
function y42bSearch_ResetearComboLocalidad(){
	$("#y42bSearch_ComboLocalidad-button").remove();
	$("#y42bSearch_ComboLocalidad-menu").remove();
	$('<select class="rup-combo" id="y42bSearch_ComboLocalidad" name="localidadId"></select>').replaceAll("#y42bSearch_ComboLocalidad");
}

function y42bSearch_PintarComboLocalidad(){
	y42bSearch_ResetearComboLocalidad();
	$("#y42bSearch_ComboLocalidad").rup_combo({
		parent: [ "y42bSearch_ComboProvincia", "y42bSearch_ComboMunicipio" ],
		source : "/y42bVistaWar/nora/localidades?R01HNoPortal=true",
		blank : "",
		sourceParam : {	label : "dsO", value : "id"	},
		width : 250
	});
}

/* Combo Pais */
function y42bSearch_ResetearComboPais(){
	$("#y42bSearch_ComboPais-button").remove();
	$("#y42bSearch_ComboPais-menu").remove();
	$('<select id="y42bSearch_ComboPais" name="esnoraPaisId"></select>').replaceAll("#y42bSearch_ComboPais");
}
	
function y42bSearch_PintarComboPais(){
	y42bSearch_ResetearComboPais();
	$("#y42bSearch_ComboPais").rup_combo({
		blank : "",
		width: "250",
		source : "/y42bVistaWar/nora/paisesExtranjeros",
		sourceParam : {
			label : "dsO",
			value : "id"
		}
	});	
}


function y42bSearchSoloConsulta(){
	
	$("#UPDATE_FORM_BUTTONS_SearchCodes").hide();
	//$("#searchCodeSelectionButton").hide();
	$("#UPDATE_FORM_BUTTONS_MassiveActions").hide();
	//$("#searchMassiveActionButton").hide();
	$("#searchDIVTamanyoSobreCombo").hide();
	//$("#searchDIVExcelCombo").hide();
	$("#searchEnvelopesButton").hide();
	$("#searchSendEmailButton").hide();
	
	 if (y42bSearch_UsuarioTipoAcceso == $("#y42bSearch_CteTipoAcceso_Consulta").val()){
		 $("#searchModifyButton").hide();
	 }
	 $("#y42bVistaWar_menu-2").hide();
}



$("#searchKontsumoGest").click(function () {
	isCheckedKG = $("#searchKontsumoGest").attr("checked");
	if(isCheckedKG){
		contChecks = contChecks +1;
	}else{
		contChecks = contChecks -1;
	}
	muestraDIVRBTipo();
	
});

$("#searchFormativa").click(function () {
	isCheckedOF = $("#searchFormativa").attr("checked");
	if(isCheckedOF){
		contChecks = contChecks +1;
	}else{
		contChecks = contChecks -1;
	}
	muestraDIVRBTipo();
});

$("#searchKontsumoNet").click(function () {
	isCheckedKN = $("#searchKontsumoNet").attr("checked");
	if(isCheckedKN){
		contChecks = contChecks +1;
	}else{
		contChecks = contChecks -1;
	}
	muestraDIVRBTipo();
});

$("#searchConsultaWeb").click(function () {
	isCheckedCW = $("#searchConsultaWeb").attr("checked");
	if(isCheckedCW){
		contChecks = contChecks +1;
	}else{
		contChecks = contChecks -1;
	}
	muestraDIVRBTipo();
});


function muestraDIVRBTipo(){
	if (contChecks>1){
		$("#search_DIVRBTipo").show();
	}else{
		$("#search_DIVRBTipo").hide();
	}
}

