// Navegador
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;
// Popups
//------------------------------------------------------------------------------------------------

function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	if (ie) {    
		window.open(cual, nombre, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+scroll+',resizable='+ajustable+',copyhistory=no,width='+ancho+', height='+alto+', top=0, left=0');
	} else if (ns) {
		window.open(cual, nombre,'width=740,height=500,location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars=yes, status=no');		
	} else {
		window.open(cual, nombre, 'left=0,top=0,width='+ancho+',height='+(alto+5)+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+scroll+', status=no');
	}
}

// función GENÉRICA para cualquier formulario
//------------------------------------------------------------------------------------------------
function chekea(cual) {
	var i, tipo, valor;
	if (cual.elements) {
		for (i=0; i<cual.elements.length; i++) {
			if (cual.elements[i].name.substr(0,4) == "chk|") {
				tipo = cual.elements[i].name.split("|");
				valor = cual.elements[i].value;
				//if (valor != null) alert(valor);
				switch (tipo[2]) {
					case "editor":
						valor = tinyMCE.getContent();
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							tinyMCE.execCommand("mceFocus", cual.elements[i].name);// ERROR: no sitúa el cursor
							return false;
						}
						// Después veo si es menor que el mínimo
						if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]+" caracteres");				
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (valor.length > parseInt(tipo[4],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "str":
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]+" caracteres");				
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (valor.length > parseInt(tipo[4],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "int":
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea NUMÉRICO
						if (!(esnumerico(valor))) {
							alert("El campo \""+tipo[6]+"\" debe ser NUMÉRICO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (parseInt(valor,10) < parseInt(tipo[3],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor que "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (parseInt(valor,10) > parseInt(tipo[4],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser mayor que "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						break;
					case "date":
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea FECHA
						if (esfecha(valor) != "si" && valor != "") {
							alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA\n"+esfecha(valor));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (convierteFecha(valor) < convierteFecha(tipo[3])) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es mayor que el máximo
						if (convierteFecha(valor) > convierteFecha(tipo[4])) {
							alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "eml":	//E-mail
						// Primero veo si es obligatorio RELLENARLO
						if ((tipo[5] == "true") && (valor.length == 0)) {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea EMAIL válido
						if ((esMail(valor)!=true) && (valor!="")){
							alert("El campo \""+tipo[6]+"\" debe ser una dirección de correo válida");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "alf": // Es el tipo alfanumérico
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]+" caracteres");				
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (valor.length > parseInt(tipo[4],10)) {
							alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea alfanumerico
						if ((esAlfanumerico(valor)!=true) && (valor!="")){
							alert("El campo \""+tipo[6]+"\" debe estar formado por letras y numeros");
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					default:
						alert("No existen restricciones de tipo \""+tipo[2]+"\"");
						return false;
						break;
				}
			}
		}
	}
	return true;
}

//COMPRUEBA que el campo sea fecha
//------------------------------------------------------------------------------------------------
function esfecha(dato) {
	var fecha_split;
	var i;
	var tdia, tmes, tano;

	fecha_split = dato.split('.');

	if(fecha_split.length != 3) {return "Debe tener DD.MM.AAAA";}
	
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);

	if ((fecha_split[0].length!=2) || (!esNumeroEstricto(fecha_split[0])) ) {return "El día no es correcto. Formato: DD.MM.AAAA";}
	if ((fecha_split[1].length!=2) || (!esNumeroEstricto(fecha_split[1])) ) {return "El mes no es correcto. Formato: DD.MM.AAAA";}
	if ((fecha_split[2].length!=4) || (!esNumeroEstricto(fecha_split[2])) ) {return "el año no es correcto. Formato: DD.MM.AAAA";}

	// Comprobamos que sean 3 elementos
		// Comprobamos que no sean ceros
		for (i=0; i<fecha_split.length; i++) {
			if (parseInt(fecha_split[i],10) == 0) return "No existe la fecha: 0";
		}
		// Comprobamos que el AÑO tenga 4 dígitos
		//if(fecha_split[2].length != 4) aux="El año debe tener 4 dígitos: AAAA";
		// Comprobamos que sea dia/mes/año: 28/02/1997
		var f = convierteFecha(dato);
		if(f.getDate() != tdia) return "El día no es correcto";
		if(f.getMonth() != (tmes-1)) return "El mes no es correcto";
		if(f.getFullYear() != tano) return "El año no es correcto";

	return "si";
}


//DEVUELVE una FECHA
//------------------------------------------------------------------------------------------------
function convierteFecha(quien) {
	var fecha_split;	
	var tdia, tmes, tano;

	fecha_split = quien.split('.');


	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}

//COMPRUEBA que el dato sea un número
//------------------------------------------------------------------------------------------------
function esNumeroEstricto(dato){
	var i;
	for(i=0;i<dato.length;i++){
		if (dato.charAt(i)>'9' || dato.charAt(i)<'0') { return false;}
	}
	return true;
}

// Recarga la página añadiendo una variable al querystring
// -----------------------------------------------------------------------------------------------
function recargaPagina(todo, varQuery, varQueryValor) {
	window.location = ""+todo+"&"+varQuery+"="+varQueryValor;
}

// MUESTRA o no una capa mediante la propiedad display
// ------------------------------------------------------------------------------------------------
function abrirCerrarCapa(capa){
	if(document.getElementById(capa).style.display=='none'){
		document.getElementById(capa).style.display='block';
		if(document.getElementById("btnAbrirCerrar")){
			document.getElementById("btnAbrirCerrar").src="img/btnFlechaAr.gif";
		}
	}else{
		document.getElementById(capa).style.display='none';
		if(document.getElementById("btnAbrirCerrar")){
			document.getElementById("btnAbrirCerrar").src="img/btnFlechaAb.gif";
		}
	}
}

// VALIDA un email
//------------------------------------------------------------------------------------------------
function esMail(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@", 0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
	if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (valido == true) && (texto.indexOf("..",0) == -1)){
    	valido = true;
	}else{
		valido = false;
	}
    return valido;
}


// REDIRIGE un banner
//------------------------------------------------------------------------------------------------
function abreBanner(enlace){
	window.open(enlace);
//	window.location = enlace;
}

//	MUESTRA un banner con enlaces (se llama directamente desde el banner)
//----------------------------------------------------------------------------------------------------------------------
function muestraBannerEnlaces(enlaces){
	var aux, clase;
	aux=desordenar(enlaces);
	document.write("<table cellpadding=\"0\" cellspacing=\"0\" class=\"tblBannerEnlaces\" border=\"0\">");
	for(i=0;i<aux.length;i++){
		if(i<aux.length-1){clase="separador"}else{clase="";}
		document.write("<tr><td class=\""+clase+"\">"+aux[i]+"</td></tr>");
	}
	document.write("</table>"); 
}

//	DESORDENAR un array
//----------------------------------------------------------------------------------------------------------------------
function desordenar(array){
    var aux=array;
	var i=aux.length;
	var j;
	var tmp;
    while(i--){
        j=Math.floor( Math.random() * (i+1) );
        tmp=aux[i];
        aux[i]=aux[j];
        aux[j]=tmp;
    }
	return aux;
}

// VALIDA un texto de tipo alfanumerico
// -----------------------------------------------------------------------------------------------
function esAlfanumerico(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890";
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
    return valido;
}

// INICIA el editor de textos para textareas
// -----------------------------------------------------------------------------------------------
function iniciaEditor(btnMostrar, cssMostrar, hojaCss, enlace){
	tinyMCE.init({
	mode : "textareas",							//dónde actuará
	editor_selector : "mceEditor",				//<textarea class="mceEditor"> convierte un textarea en editor
	entity_encoding : "raw", 					//para que no sustituya tildes por &...
	theme : "plexus", 							//tipo
	language : "es",							//idioma
	docs_language : "es",						//idioma de la ayuda
	convert_newlines_to_brs : false,
	force_br_newlines : false,
	popups_css : hojaCss,						//hoja de estilos que cogerán las pop-ups
	//auto_resize : true,						//el editor se redimensiona para ocupar todo el espacio del q dispone (quita el scroll)
	theme_plexus_layout_manager: "SimpleLayout",//para redimensionar
	theme_plexus_statusbar_location :"bottom",	//para redimensionar
	theme_plexus_resizing : true,				//para redimensionar
	theme_plexus_resize_horizontal : false,		//para no redimensionar horizontalmente
	theme_plexus_path : false,					//no queremos path
	content_css : hojaCss,
	theme_plexus_styles : cssMostrar,			// estilos para el combo
	theme_plexus_buttons1 : btnMostrar, 		//botones activos
	theme_enlace: enlace,
	relative_urls: false,  						// El path debe ser absoluto
	plugins : "searchreplace",					//plugins: botón de reemplazar
	height : "200",
	width:"625",
//	etiquetas válidas e inválidas
//	valid_elements : "strong/b,em/i,strike,-ul,-li"
//	invalid_elements como referencia porque el script funciona con las que que son válidas
//	invalid_elements : "-div[id|dir|class|align|style]"
	invalid_elements : ""
	});
}
