//////////////////////////////////////////////////////
// FUNCIONES COMPARTIDAS ADM - FRONT
//////////////////////////////////////////////////////

// revisa si un valor es nulo
function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
	}
	return true;
}

// revisa si una cadena es valida para Web
function ValidaNombre(nombre, caract_extra) {  

	var ubicacion;
	var caracteres = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ_-" + caract_extra;
	var existe_invalido = false;

	for (var i=0; i < nombre.length; i++) {  
		ubicacion = nombre.substring(i, i + 1)  
		if (caracteres.indexOf(ubicacion) == -1) {
			existe_invalido = true;
		}  // fin busqueda caracter
	}  // fin recorrida
	
	if(existe_invalido) {
		return true;
	} else {
		return false;
	}
			
}  

// comprueba si un e-mail está es válido
function validar_email(valor, aviso) {
	if(valor!="") {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
			return true;
		} else {
			if(aviso!=undefined){alert(aviso);}
			return false;
		}
	} else {
		return false;
	}
}

// COMPROBAR REPETIDO
// devuelve true si el valor ya existe en la tabla sino false
// tabla donde va a buscar el campo (* depende del tipo)
// campo donde se buscara el valor
// idelemento: id del elemento que tiene el valor a comprobar si esta repetido
// tipo: utilizada para definir el tipo de búsqueda: 1: campo - 2 tabla - campo y tabla (debe especificar en el parametro tabla las dos tablas donde se buscara separadas por coma)
function verificar_repetido(tabla, campo, idelemento, tipo) {
	
	// defino la ruta si es desde el adm o del front
	direccion_web = document.location.href;
	ruta_script = direccion_web.indexOf("/adm/")==-1 ? SITIO_MASTER+"adm/" : ADM_MASTER;
	
	// inicializo parametros
	tipo = tipo == undefined ? 1 : tipo;

	if(tabla.indexOf(",")!=-1) {
		tablas = tabla.split(",");
		tabla = tablas[0].replace(/^\s+|\s+$/g,"");
		tabla_campos = tablas[1].replace(/^\s+|\s+$/g,"");
	} else {		
		tabla_campos = "";
	}

	// preparo parámetros
	var parametros = "&valor="+$('#'+idelemento).val();
	parametros = parametros + "&tabla="+tabla;
	parametros = parametros + "&campo="+campo;
	parametros = parametros + "&tipo="+tipo;
	parametros = parametros + "&tabla_campos="+tabla_campos;

	resultado = $.ajax({
		type: "GET",
		async: false,
		url: ruta_script + "inc/ajax/verificar_repetido.php",
		data: parametros
	}).responseText; // fin del ajax
	
	if(resultado==0){
		return false;
	} else {
		return true;
	}

}		

// para limitar caracteres en un campo
function limitar_caracteres(textid, limite, infodiv, texto_cantidad, texto_final)
{
	var text = $('#'+textid).val();	
	var textlength = text.length;
	if(textlength > limite)
	{
		$('#' + infodiv).html(texto_final);
		$('#'+textid).val(text.substr(0,limite));
		return false;
	}
	else
	{
		$('#' + infodiv).html(texto_cantidad.replace('{caracteres}', limite - textlength));
		return true;
	}
}

// FUNCIÓN PARA VALIDAR SI ES UN NÚMERO
function validarSiNumero(numero){
	if (!/^([0-9])*$/.test(numero)){
		return false;
	} else {
		return true;
	}
}

// para ir a anclas con animación - jquery
anchor = {
	init : function() {
		$("a.anchorLink").click(function () {
			elementClick = $(this).attr("href")
			destination = $(elementClick).offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100 );
			return false;
		})
	}
}

// ALERTA ESPECIAL DE VALIDACIÓN
function alerta(mensaje, id_campo){
	$('#mensajes_alertas').html(mensaje).dialog({
		modal: true,
		title: 'AVISO',
		close: function(){
			if(id_campo!=undefined){
				$('#'+id_campo).focus();
			}
		},
		buttons: {
		'Aceptar': function() {
			$(this).dialog('close');
		}}});
}

// abre la hoja de impresión
function imprime(funcion, tipo, op, id, ancho, alto, tipo_impresion){
	
	URL = urlMaster+"inc/impresion.php?f="+funcion+"&id="+id+"&op="+op+"&tipo="+tipo;
	
	// impresión por popup
	if(tipo_impresion==1) {
	
		imprimir = window.open(URL, "_blank", "toolbar=no ,location=no, status=no, menubar=no, resizable=no, scrollbars=yes, width="+ancho+", height="+alto);
		imprimir.moveTo((screen.availWidth/2)-(ancho/2),(screen.availHeight/2)-(alto/2));
		
	// impresión oculta
	} else {
		
		// Creo un iFrame
		var jFrame = $("<iframe name=\"pagina_impresion\">");

		// lo oculto y lo agrego al cuerpo del sitio
		jFrame
			.css( "width", "1px" )
			.css( "height", "1px" )
			.css( "position", "absolute" )
			.css( "left", "-9999px" )
			.appendTo( $( "body:first" ) )
			.attr( "src", URL);
		
		setTimeout(
			function(){
				jFrame.remove();
			}, (60 * 1000) );
	
	} // fin tipo_impresion

}
