var y42bIdGrupo = ""; //variable para guardar el id del grupo padre  cuando seleccionamos un nuevo grupo	
var y42bNuevaEntidad = false; //variable para saber si es una nueva entidad	
var y42bNuevoContacto = false; //variable para saber si es un nuevo contacto
var y42bVarNodoSeleccionadoId = "";
var y42bVarNodoSeleccionadoDesc = "";
var y42bVarGrupoPadreId = "";
var y42bVarBotonNuevoClickado = false;
var y42bAltaEntidadOK = false;
var y42bVarMinodekey = "";
var y42bVarBotonRefrescarPulsado = false;
var y42bVarCalleModal = ""; //variable para controlar la busqueda de calle desde que pagina se realiza
var y42bVarEnvioId = ""; //variable para saber el id del envio al procesar un email (desde la busqueda como estaba toma el valor searchenvioid, desde el envio para ver el email el del pinchado en la tabla)
var y42bVarDeEnvio = false; //variable que controla si se llega al email popup desde la pantalla de envio (o de la busqueda)
var y42bVarNodoDeArbolClickado = false;
var y42bVar_FormChanged = false; //variable para comprobar si se ha producido algun cambio en la pagina actual
var y42bVar_EntraFunNumCheck = false;
var y42bVar_BoolChecks = false; //variable para el perfil modificacion - tablas de grupos en entidades mant
var y42bVar_EtiquetasEntidad = false; //variable controla modaletiquetas abierto desde entidad mant


jQuery(document).ready(function(){
	
	$("#rup_dept_logo").attr("src", $.rup.APP_STATICS + "/images/dept_logo_" + $.rup.lang + ".gif");
	var vertical = false;
	
	// Script para el menu izquierda cuando lo tenga
//	$('.entidad_colapsor ul').collapsor();
	
	//rastro de migas
	$("#y42bVistaWar_migas").rup_breadCrumb({
		breadCrumb: {
			"vista":{
				"i18nCaption" : "mantenimiento",
				"url"   : "/y42bVistaWar/app/vista"
			},
			"load":{
				"i18nCaption" : "buscador",
				"url"   : "/y42bVistaWar/app/search"	
			},		
			"seguimiento":{
				"i18nCaption" : "seguimiento",
				"url"   : "/y42bVistaWar/app/seguimiento"
			}
		}
	});
	
	//idioma
	$("#y42bVistaWar_language").rup_language({languages: ["es", "eu"]});
	
	$("#y42bVistaWar_menu").rup_menu({
		display: (vertical ? 'vertical' : 'horizontal'),
		menu: [
			{"i18nCaption":"menu1", "url" : "mant/vista" },
			{"i18nCaption":"menu2", "url" : "search/load" },
			{"i18nCaption":"menu3", "url" : "envio/seguimiento" }
		]
	});
});

/* ********************************************************************************************
 * Funcion para calcular los puntos en función del %
 * ********************************************************************************************
 */
function funcPercentage(porcentajeColumna, widthTabla){

//	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
//	
//	if (is_chrome){
//		
//	}else{
	    var x = (porcentajeColumna*widthTabla)/100;
	    //console.log("Percentage:" + porcentajeColumna + " - " + widthTabla + " - " + x);
	    return x;
//	}
}

function showModalaviso(){
	
	$("#modal_aviso").rup_dialog({
		modal: true,
		autoOpen: true,
		resizable: false,
		width: "700",
		height: "auto",
		title: $.rup.i18n.app.comun.Kontsumobide,
		url: "/y42bVistaWar/avisolegal",  
		type:$.rup.dialog.AJAX
	});		
}

function showModalprivacidad(){
		$("#modal_privacidad").rup_dialog({
			modal: true,
			resizable: false,
			autoOpen: true,
			width: "700",
			height: "auto",
			title: $.rup.i18n.app.comun.Kontsumobide,
			url: "/y42bVistaWar/privacidad",    
			type:$.rup.dialog.AJAX
		});	
}		

function validateProperty(beanName, object, feedBack) {

	VALIDATE_MESSAGE = "";
	var t=0;
	
	for (field in object) {
		$.ajax({
				type : "GET",
				async : false,
				url : "/y42bVistaWar/validate?bean=" + beanName + "&property="
						+ field + "&value=" + object[field],
				dataType : "json",
				
				statusCode : {
					200 : function() {
							
					},
					406 : function(data) {
						
						var message = "";
						var response = $.parseJSON(data.responseText);
						var errors = $.parseJSON(response[1]);
						var error = null;
						
						for(name in errors) {
							
							error = errors[name];
							break;
						}
						
						for(var e=0; e<error.length; e++) {
						
							for(assertion in error[e]) {
								
								VALIDATE_MESSAGE += "<li>" + error[e][assertion] + "</li>\n";
							}
							
						}
							
						
						t++;
					}
				}
		});
			
	}
	
	if(t>0) {
		$("#" + feedBack).rup_feedback("option", "delay", null);
		$("#" + feedBack).rup_feedback("set", "<ul>" + VALIDATE_MESSAGE + "</ul>", "error");
		
		return false;
		
	} else {
		
		return true;
	}
};

function validateBean(beanName, object, group, feedBack) {
	
	VALIDATE_MESSAGE = "";
	var t=0;
		$.ajax({
			type : "GET",
			async : false,
			url : "/y42bVistaWar/validate?bean=" + beanName + "&group="+ group,
			dataType : "json",
			data : {data:$.toJSON(object)},
			contentType : 'application/json',
			statusCode : {
				200 : function() {
				},
				406 : function(data) {
				
					var message = "";
					var response = $.parseJSON(data.responseText);
					var errors = $.parseJSON(response[1]);
					var error = null;
					for(name in errors) {
						
						error = errors[name];
						for(var e=0; e<error.length; e++) {
							
							for(assertion in error[e]) {
								
								VALIDATE_MESSAGE += "<li>" + error[e][assertion] + "</li>\n";
							}
						}
					}
					
					
					t++;
				},
				500 : function(data) {
					
					var message = "";
					var response = $.parseJSON(data.responseText);
					var errors = $.parseJSON(response[1]);
					
					VALIDATE_MESSAGE += "<li>" + "Error 500" + "</li>\n";
					t++;
				}	
			}
		});
	
	if(t>0) {
		$("#" + feedBack).rup_feedback("option", "delay", null);
		$("#" + feedBack).rup_feedback("set", "<ul>" + VALIDATE_MESSAGE + "</ul>", "error");
		return false;
		
	} else {	
		return true;
	}
}

function validateBean(beanName, object, group, feedBack, arrayErrores) {
		
	VALIDATE_MESSAGE = "";
	var t=0;
		$.ajax({
			type : "GET",
			async : false,
			url : "/y42bVistaWar/validate?bean=" + beanName + "&group="+ group,
			dataType : "json",
			data : {data:$.toJSON(object)},
			contentType : 'application/json',
			statusCode : {
				200 : function() {
				},
				406 : function(data) {
					var message = "";
					var response = $.parseJSON(data.responseText);
					var errors = $.parseJSON(response[1]);
					var error = null;
					for(name in errors) {
						
						error = errors[name];
						for(var e=0; e<error.length; e++) {
							
							for(assertion in error[e]) {
								
								VALIDATE_MESSAGE += "<li>" + error[e][assertion] + "</li>\n";
							}
						}
					}
					
					
					t++;
				}
			}
		});
	
	if(arrayErrores != null) {
		for (i=0; i<arrayErrores.length;i++)
		{
			VALIDATE_MESSAGE += "<li>" + arrayErrores[i] + "</li>\n";
			t++;
		}
	}
	
	if(t>0) {
		$("#" + feedBack).rup_feedback("option", "delay", null);
		$("#" + feedBack).rup_feedback("set", "<ul>" + VALIDATE_MESSAGE + "</ul>", "error");
		return false;
		
	} else {
		return true;
	}
}




//funcion que devuelve el tamño de un string
function y42bFunTamanyoString(cadena){
	return cadena.length;	
}

//funcion que elimina de una cadena el href
function y42bEliminarHref(cadena){
	var primero = cadena.indexOf(">");
	var ultimo = cadena.lastIndexOf("<");
	
	return cadena.substring(primero+1,ultimo);
}
function y42bFunEliminarPrefijo(cadena){
	return cadena.replace("G_","");
}

//function NumCheck(e, field){ 
//	key = e.keyCode ? e.keyCode : e.which;
//
//			// backspace 
//			if (key == 8) 
//				return true; 
//			// 0-9 
//			if (key > 47 && key < 58) 
//			{ 
//				if (field.value == "") return true; 
//					regexp = /,[0-9]{2}$/ ; 
//					return !(regexp.test(field.value)); 
//			} 
//				if (key == 44) 
//					{ 
//					if (field.value == "") 
//						return false ;
//						regexp = /^[0-9]+$/;
//					
//							return regexp.test(field.value); 
//							} 
//				// other key 
//				return false; 
//}
	
// funcion numcheck con control de cambios 

function NumCheck(e, field) 
{ 
	key = e.keyCode ? e.keyCode : e.which;
	var miBoolean = false;
	// backspace 
	if (key == 8) {
		miBoolean = true;
	}
	// left arrow 
	if (key == 37) {
		miBoolean = true;
	}
	// up arrow 
	if (key == 38) {
		miBoolean = true;
	}
	// right arrow 
	if (key == 39) {
		miBoolean = true;
	}
	// down arrow 
	if (key == 40) {
		miBoolean = true;
	}
	// 0-9 
	if (key > 47 && key < 58){ 
		if (field.value == ""){
			miBoolean = true;
		}else{
			miBoolean = true;!(regexp.test(field.value)); 
		}
	} 
	//,
	if (key == 44){ 
		if (field.value == "") {
			miBoolean = false ;
		}else{
			miBoolean = true;//regexp.test(field.value); 
		}
	}
	
	if (miBoolean){
 		y42bVar_FormChanged = true;
 	}
	y42bVar_EntraFunNumCheck = true;
	
	return miBoolean;
}



function y42bValidarEmail(email) {
	  if (/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/.test(email)){
		  return true;
	  } else {
		  return false;
	  }
}

function y42bValidarURL(url) {
	
	    
	if ( /^http:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/.test(url)) { 
		return true;
	} else {
		return false;
	  }
}

function y42bAbrirVentana(url){
	window.open(url);
}


function controlY42bUDAException(data, feedBack) {
	var VALIDATE_MESSAGE = "";
	var errors = $.parseJSON(data.responseText);
	var error = null;
	for(name in errors) {
		error = errors[name];
		VALIDATE_MESSAGE += "<li>" + char_convert(error) + "</li>\n";
	}
	$("#" + feedBack).rup_feedback("option", "delay",null);
	$("#" + feedBack).rup_feedback("set","<ul>" + VALIDATE_MESSAGE + "</ul>", "error");
}

function char_convert(cadena){
	  
	// Sustituyo caracteres en la cadena final
	cadena = cadena.replace(/Ã¡/g, "&aacute;");
	cadena = cadena.replace(/Ã©/g, "&eacute;");
	cadena = cadena.replace(/Â®/g, "&reg;");
	cadena = cadena.replace(/Ã­/g, "&iacute;");
	cadena = cadena.replace(/ï¿½/g, "&iacute;");
	cadena = cadena.replace(/Ã³/g, "&oacute;");
	cadena = cadena.replace(/Ãº/g, "&uacute;");
	cadena = cadena.replace(/n~/g, "&ntilde;");
	cadena = cadena.replace(/Âº/g, "&ordm;");
	cadena = cadena.replace(/Âª/g, "&ordf;");
	cadena = cadena.replace(/ÃƒÂ¡/g, "&aacute;");
	cadena = cadena.replace(/Ã±/g, "&ntilde;");
	cadena = cadena.replace(/Ã‘/g, "&Ntilde;");
	cadena = cadena.replace(/ÃƒÂ±/g, "&ntilde;");
	cadena = cadena.replace(/n~/g, "&ntilde;");
	cadena = cadena.replace(/Ãš/g, "&Uacute;");
	return cadena;
}

/* ********************************************************************************************
 * Funcion que devuelve la letra a agregar al nombre del campo idiomatico en funcion del idioma 
 * ********************************************************************************************
 */
function recuperarLetraIdioma(){
	var letra ="";
	if ("eu"==$.rup_utils.get("language")){
		letra="e";
	}	
	return letra;
}


/* ********************************************************************************************
 * Funcion que elimina las etiquetas
 * ********************************************************************************************
 */
function stripHTML(cadena)
{
   return cadena.replace(/<[^>]+>/g,'');
}



//quita <p></p>
function stripHTMLP(cadena)
{
   cadena.replace('<p>','');
   cadena.replace('</p>','');
   return cadena;
}


function recuperarLetraIdiomaCE(){
	var letra ="C";
	if ("eu"==$.rup_utils.get("language")){
		letra="E";
	}	
	return letra;
}


function escapeSpecialChars(cadena){
    return cadena.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
}



function htmlEscape(str) {
	if(str==null){
    	return "";
    }
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
    		.replace(/à/g, '&agrave;')
    		.replace(/À/g, '&Agrave;')
    		.replace(/â/g, '&acirc;')
    		.replace(/Â/g, '&Acirc;')
    		.replace(/ä/g, '&auml;')
    		.replace(/Ä/g, '&Auml;')
    		.replace(/å/g, '&aring;')
    		.replace(/Å/g, '&Aring;')
    		.replace(/æ/g, '&aelig;')
    		.replace(/Æ/g, '&AElig;')
    		.replace(/ç/g, '&ccedil;')
    		.replace(/Ç/g, '&Ccedil;')
    		.replace(/é/g, '&eacute;')
    		.replace(/É/g, '&Eacute;')
    		.replace(/è/g, '&egrave;')
    		.replace(/È/g, '&Egrave;')
    		.replace(/ê/g, '&ecirc;')
    		.replace(/Ê/g, '&Ecirc;')
    		.replace(/ë/g, '&euml;')
    		.replace(/Ë/g, '&Euml;')
    		.replace(/ï/g, '&iuml;')
    		.replace(/Ï/g, '&Iuml;')
    		.replace(/ô/g, '&ocirc;')
    		.replace(/Ô/g, '&Ocirc;')
    		.replace(/ö/g, '&ouml;')
    		.replace(/Ö/g, '&Ouml;')
    		.replace(/ø/g, '&oslash;')
    		.replace(/Ø/g, '&Oslash;')
    		.replace(/ß/g, '&szlig;')
    		.replace(/ù/g, '&ugrave;')
    		.replace(/Ù/g, '&Ugrave;')
    		.replace(/û/g, '&ucirc;')
    		.replace(/Û/g, '&Ucirc;')
    		.replace(/ü/g, '&uuml;')
    		.replace(/Ü/g, '&Uuml;')
    		.replace(/®/g, '&reg;')
    		.replace(/©/g, '&copy;')
    		.replace(/€/g, '&euro;')
    		// be carefull with this one (non-breaking whitee space)
    		.replace(/ /g, '&nbsp;');
    
}


function htmlUnescape(value){
    if(value==null){
    	return "";
    }
	return String(value)
    .replace(/&amp;/g, '&')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
	.replace(/&agrave;/g, 'à')
	.replace(/&Agrave;/g, 'À')
	.replace(/&acirc;/g, 'â')
	.replace(/&Acirc;/g, 'Â')
	.replace(/&auml;/g, 'ä')
	.replace(/&Auml;/g, 'Ä')
	.replace(/&aring;/g, 'å')
	.replace(/&Aring;/g, 'Å')
	.replace(/&aelig;/g, 'æ')
	.replace(/&AElig;/g, 'Æ')
	.replace(/&ccedil;/g, 'ç')
	.replace(/&Ccedil;/g, 'Ç')
	.replace(/&eacute;/g, 'é')
	.replace(/&Eacute;/g, 'É')
	.replace(/&egrave;/g, 'è')
	.replace(/&Egrave;/g, 'È')
	.replace(/&ecirc;/g, 'ê')
	.replace(/&Ecirc;/g, 'Ê')
	.replace(/&euml;/g, 'ë')
	.replace(/&Euml;/g, 'Ë')
	.replace(/&iuml;/g, 'ï')
	.replace(/&Iuml;/g, 'Ï')
	.replace(/&ocirc;/g, 'ô')
	.replace(/&Ocirc;/g, 'Ô')
	.replace(/&ouml;/g, 'ö')
	.replace(/&Ouml;/g, 'Ö')
	.replace(/&oslash;/g, 'ø')
	.replace(/&Oslash;/g, 'Ø')
	.replace(/&szlig;/g, 'ß')
	.replace(/&ugrave;/g, 'ù')
	.replace(/&Ugrave;/g, 'Ù')
	.replace(/&ucirc;/g, 'û')
	.replace(/&Ucirc;/g, 'Û')
	.replace(/&uuml;/g, 'ü')
	.replace(/&Uuml;/g, 'Ü')
	.replace(/&reg;/g, '®')
	.replace(/&copy;/g, '©')
	.replace(/&euro;/g, '€')
	// be carefull with this one (non-breaking whitee space)
	.replace(/&nbsp;/g, ' ');
}



function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}


//Funcion para controlar que haya cambiado un elemento de una pagina HTML
function y42b_FunFormChanged(){
	//Elementos HTML de la pagina

	//*input	
	$("input").keypress(function(e){
		if (!(y42bVar_EntraFunNumCheck)){
			if($(this).attr("readonly") == "readonly"){
				y42bVar_FormChanged = false;
			}else{
				y42bVar_FormChanged = true;
			}
		}
	});
	//*select
//	$("select").change(function(){
//			y42bVar_FormChanged = true;
//	});
//	
	$('select').on('change', function() {
		y42bVar_FormChanged = true;
	});
	
	
	//*textarea
	$("textarea").keypress(function(){
			y42bVar_FormChanged = true;
	});

	//*check  - no esta funcionando con los generados dinamicamente
	 $('input[type="checkbox"]').change(function () {
			y42bVar_FormChanged = true;
	 });
	
	//*radio
	$('input:radio').change(function(){	//o $( "input[type=radio]" ) para tratar todos los radios
	    if(this.checked) {
    		y42bVar_FormChanged = true;
	    }
	});
	//*file
	$(":file").change(function(){
			y42bVar_FormChanged = true;
	});
}


function waitDialog(){
	$.blockUI({ message: "<div class='y4b_modalWait'><img src='" + $.rup.APP_STATICS + "/images/busy.gif' /> "+$.rup.i18n.app.comun.msjeLoading+" </div>" });
	$(".blockUI.blockOverlay").css("z-index",9000);
	$(".blockUI.blockOverlay").css("opacity",0.5);
	$(".blockUI.blockMsg.blockPage").css("z-index",9001);
	$(".blockUI.blockMsg.blockPage").css("opacity",1);
	//setTimeout(function() {$.unblockUI();}, 30000);	
}

function waitDialogStop(){
	$.unblockUI();	
}
	

//quita corchetes de la cadena (para la lista de etiquetas)
function quitaCorchetes(cadena)
{
	return cadena.replace(/[\[\]']+/g,'');
}

// random String
function randomString(length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = length;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
  return randomstring;
}

