$(document).ready(function () {
	
	// Cálculo de contraste
	if ($('#botonCalcularContraste')) {herramientaContraste();}
	
	// Validación de formularios
	if ($("#validado").length==1) {$("#validado").validate();}
	
	// Bordes para campos activos
	borde1 = new Bordecampo();
	borde1.selector = 'input[type=text]';
	borde1.alternaBorde();
	
	borde2 = new Bordecampo();
	borde2.selector = 'input[type=password]';
	borde2.alternaBorde();
	
	borde3 = new Bordecampo();
	borde3.selector = 'textarea';
	borde3.alternaBorde();
	
	// Ventanas modales
	vm1 = new Ventanamodal();
	vm1.arrancaModal();
	
	vm2 = new Ventanamodal();
	vm2.atribRel = 'superbox-definicion';
	vm2.arrancaModal();
	
	// Desplegables
	desp1 = new Desplegable();
	desp1.alternaBloque();
	
	// Combo
	combo1 = new ComboRedireccion();
	combo1.salto();
	
	//Login
	//login1 = new Login();
	//login1.inicia();
});


// Login
function Login () {
	this.campo1 = '#c_usuario';
	this.name1 = 'usuario';
	this.campo2 = '#c_clave';
	this.name2 = 'clave'
	this.id2 = 'c_clave'
	this.antes = '#login p.boton';
	
	this.inicia = function () {
		var that = this;
		var campo = $(this.campo2).parent();
		$(this.campo2).remove();
		campo.append('<input type="password" name="'+this.name2+'" id="'+this.id2+'" class="ofuscado" />');
		$(this.antes).eq(0).before('<p class="check clear"><label for="c_ofuscacion"><input type="checkbox" name="inocuo" id="c_ofuscacion" checked="checked" /><span>Ocultar contraseña</span></label></p>');
		
		$('#c_ofuscacion').change(function () {
			if ($(that.campo2).hasClass('visible')) {clase='ofuscado'; tipo='password';}
			else {clase='visible'; tipo='text';}
			valor = $(that.campo2).val();
			$(that.campo2).remove();
			campo.append('<input type="'+tipo+'" name="'+that.name2+'" id="'+that.id2+'" class="'+clase+'" value="'+valor+'" />');
		})
	}
}

// Clase de combo
function ComboRedireccion () {
	this.clase = 'redirecciona';
	this.salto = function () {
		var that = this;
		$('input.'+this.clase).each(function () {
			$(this).css({'display':'none'});
		});
		$('select.'+this.clase).change(function () {
			$(this).closest('form').submit();
		});
	}
}

// Clase de borde activo
function Bordecampo () {
	this.selector = '';
	this.clase = 'campoActivo';
	
	this.alternaBorde = function () {
		var that = this;
		$(this.selector).focus(function () {
			$(this).addClass(that.clase);
		});
		$(this.selector).blur(function () {
			$(this).removeClass(that.clase);
		});	
	}
}


// Clase de ventana modal
function Ventanamodal () {
	this.atribRel = 'superbox';
	this.cssTop = 10; //Porcentaje de altura entre top del viewport y modal
	this.cssAncho = 38; // en EM
	this.idOver = 'tiny-over'; // id de la capa translúcida
	this.idBox = 'tiny-tbox'; // id de la capa modal
	this.idInterior = 'estrecho'; // id de la capa principal de la página que se carga
	this.cssOpacidad = 50; // De 0 (transparente) a 100 (opaco)
	
	// Función de la modal
	this.arrancaModal = function  () {
		idOver = this.idOver;
		idBox = this.idBox;
		idInterior = this.idInterior;
		cssOpacidad = this.cssOpacidad;
		cssAncho = this.cssAncho;
		cssTop = this.cssTop;
	$('a[rel="'+this.atribRel+'"]').click(function () {
		// Scroll: se quita el scroll y se cuida que el contenido no se mueva
		anchoOriginal = $(window).width(); // Ancho de viewport antes de quitar scroll
		$('html').eq(0).css('overflow','hidden'); // Se quita el scroll
		margen = (($(window).width())-anchoOriginal)/10; // la diferencia de anchos con/sin scroll para que el contenedor principal no se mueva
		$('body').eq(0).css('padding-right',margen+'em'); // se añade la diferencia
		
		// Vertical: se posiciona verticalmente la modal, y se cuida que cuando el documento tiene menos altura que el viewport el comportamiento sea el mismo. Las medidas se dividen entre 10, presuponiendo que en la CSS 10px=1em
		alturaDoc = ($(document).height())/10; // Altura del documento
		alturaVista = ($(window).height())/10; // Altura del viewport
		alturaOver = alturaDoc; if (alturaVista>alturaDoc) {alturaOver = alturaVista;} // Altura de la capa translúcida
		posicionVertical = (alturaVista/100)*cssTop; // Posición vertical
		
		// Horizontal: se posiciona al centro, calculando la distancia a los lados
		posicionHorizontal = (($(window).width()/10)-cssAncho)/2;
		
		// Capa translúcida: se inserta
		$('body').eq(0).append('<div id="'+idOver+'" style="filter:alpha(opacity='+cssOpacidad+'); height:'+alturaOver+'em; opacity:'+(cssOpacidad/100)+'; "></div>');
		
		// Capa modal: se inserta y se carga una página dentro
		$('body').eq(0).append('<div id="'+idBox+'" style=" left:'+posicionHorizontal+'em; top:'+posicionVertical+'em;"></div>');
		
		// Carga de la página enlazada
		
		$('#'+idBox).load($(this).attr('href'), { ajax: "si" },function () {
			// Botón de cierre de la modal
			$('#'+idInterior).append('<p class="cerrar"><strong><a href="#" id="cerrarModal"><img src="img/08_modal_cerrar.png" alt="Cerrar" /></a></strong><span class="oculto">.</span></p>'); // Inserción del botón de cerrar
			$('#cerrarModal').mouseover(function() {$(this).children('img').eq(0).attr('src','img/08_modal_cerrar_hover.png')}); // hover del botón de cerrar
			$('#cerrarModal').mouseout(function() {$(this).children('img').eq(0).attr('src','img/08_modal_cerrar.png')});
			
			// Cierre de la modal
			$('#cerrarModal').click(function(){
				$('#'+idBox).remove();
				$('#'+idOver).remove();
				$('body').eq(0).css('padding-right','');
				$('html').eq(0).css('overflow','');
				return false;
			});
			
			// funciones dependientes
			if ($('#contraste')) {herramientaContraste();}
			
		} );
		return false;
	});
	}
}

function Desplegable () {
	// Debe haber dos contenedores: el que contiene al elemento que contendrá el enlace, y elque le sigue como elemento hermano, que es el que se pliega/despliega
	/* Ejemplo:
		<div class="tituloPauta"><h4>Texto del título</h4></div>
		<div class="puntosPauta">[...]</div>
	*/
	this.selEnlace = '#listaPuntos h4:not(.expandido)'; // Selector del elemento que va a contener el enlace
	this.selBloqueDesplegable = 'div.puntosPauta:not(.expandido)'; // Selector del elemento cuya visibilidad se va a alternar
	this.selBloqueTitulo = '.tituloPauta'; // Selector del elemento que contiene a selEnlace
	this.atribRel = 'pauta'; // Valor del atributo 'rel' del enlace
	this.claseEnlace = 'plegado'; // Clase del enlace en estado plegado
	this.textoTituloDesplegar = LISTA_AMPLIAR; // Valor del 'title' del enlace
	this.textoTituloPlegar = LISTA_PLEGAR; // Valor del 'title' del enlace
	
	// Función de alternancia
	this.alternaBloque = function () {
		
		atribRel = this.atribRel;
		selBloqueTitulo = this.selBloqueTitulo;
		claseEnlace = this.claseEnlace;
		textoTituloDesplegar = this.textoTituloDesplegar;
		textoTituloPlegar = this.textoTituloPlegar;
		
		// Se inserta el enlace
		$(this.selEnlace).each(function (i) {
			$(this.childNodes).eq(0).wrap('<a rel="'+atribRel+'" title="'+textoTituloDesplegar+'" href="#" class="'+claseEnlace+'"></a>');
		});
		
		// Se oculta el bloque desplegable
		$(this.selBloqueDesplegable).each(function (i) {
			$(this).css('display','none');
		});
		
		$("a[rel='"+this.atribRel+"']").click(function () {
			$(this).toggleClass(claseEnlace);
			titulo = $(this).attr('title');
			velocidad = 'fast';
			if (titulo==textoTituloPlegar) {
				$(this).attr('title',textoTituloDesplegar);
				$(this).closest(selBloqueTitulo).next().fadeOut(velocidad);
			} else {
				$(this).attr('title',textoTituloPlegar);
				$(this).closest(selBloqueTitulo).next().fadeIn(velocidad);
			}
			
			return false;
		});
	}
}

// Funciones sin clase :-)



// Herramienta de contraste
function herramientaContraste () {
	$('#botonCalcularContraste').closest('form').submit(function () { // Se lanza el cálculo al enviarse el formulario
	
		velocidad = 'slow'; // Velocidad de los efectos fadein fadeout
		$('#resultadoContraste').fadeIn(velocidad); // Se oculta, si existe, la capa de resultados
		$('#resultadoContraste').remove(); // Se elimina, si existe, la capa de resultados
		color1 = $('#color-1').attr('value'); // Se capta el color de texto
		color2 = $('#color-2').attr('value'); // Se capta el color de fondo
		
		vc1 = ct_validaColor(color1);
		vc2 = ct_validaColor(color2);
		vc = vc1+vc2;
		
		// Si ambos colores validan, se inserta el bloque de resultados
		if (vc==2) {
			listaColores = '<dl><dt>'+CT_COLOR1+':</dt><dd>#'+color1+'</dd><dt>'+CT_COLOR2+':</dt><dd>#'+color2+'</dd></dl>';
			ejemplos = '<p class="ejemplo" style="background-color:#'+color2+'; color:#'+color1+';">'+CT_EJEMPLO_NORMAL+'</p><p class="ejemplo grande" style="background-color:#'+color2+'; color:#'+color1+';">'+CT_EJEMPLO_GRANDE+'</p>';
			contrasteColor = ct_luminosidad(color1,color2);
			htmlResultados = listaColores+ejemplos+contrasteColor;
		} else { // y si alguno no valida, se dan los errores
		
			tag1=Array('',''); tag2='p'; if (vc==0) {tag1=Array('<ul>','</ul>'); tag2='li';}
			error1 = ''; error2 = '';
			if (vc1==0) {error1 = '<'+tag2+'>'+CT_COLOR1+' '+CT_ERRONEO+'.</'+tag2+'>';}
			if (vc2==0) {error2 = '<'+tag2+'>'+CT_COLOR2+' '+CT_ERRONEO+'.</'+tag2+'>';}
			htmlResultados = tag1[0]+error1+error2+tag1[0];
		}
		$('#encabezadoContraste').after('<div style="display:none; outline:0;" tabindex="-1" class="bloque" id="resultadoContraste"><h2>'+CT_RESULTADOS+'</h2>'+htmlResultados+'</div>'); // Se crea la capa de resultados, pero no se muestra
		$('#resultadoContraste').fadeIn(velocidad).focus(); // Se muestra la capa de resultados
		return false;
	});
}

function ct_validaColor (color) {
	// si el color es válido devuelve 1; en caso contrario devuelve 0
	expresion = '^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$';
	expresion = eval("/"+expresion+"/g");
	
	resultado = color.match(expresion);
	if (resultado==null) {return 0;} else {return 1;}

}

function ct_luminosidad (c1o,c2o) {
	
	//Se pasan a RGB los colores en hexadecimal; y RsRGB = R8bit/255; GsRGB = G8bit/255; BsRGB = B8bit/255
	c1 = ct_convierteRGB(c1o);
	c2 = ct_convierteRGB(c2o);
	
	/* segunda conversión, que halla el brillo
	if RsRGB <= 0.03928 then R = RsRGB/12.92 else R = ((RsRGB+0.055)/1.055) ^ 2.4
	if GsRGB <= 0.03928 then G = GsRGB/12.92 else G = ((GsRGB+0.055)/1.055) ^ 2.4
	if BsRGB <= 0.03928 then B = BsRGB/12.92 else B = ((BsRGB+0.055)/1.055) ^ 2.4
	*/
	R1 = ct_brillo1(c1[0]);
	G1 = ct_brillo1(c1[1]);
	B1 = ct_brillo1(c1[2]);
	
	R2 = ct_brillo1(c2[0]);
	G2 = ct_brillo1(c2[1]);
	B2 = ct_brillo1(c2[2]);

	//L = 0.2126 * R + 0.7152 * G + 0.0722 * B
	L_A = ct_brillo2(R1,G1,B1);
	L_B = ct_brillo2(R2,G2,B2);
	
	/* y finalmente, el contraste
	(L1 + 0.05) / (L2 + 0.05)  
	L1 es el más claro, L2 el más oscuro
	*/
	if (L_A>L_B) {L1=L_A; L2 = L_B;}
	else {L2=L_A; L1=L_B;}
	
	//contraste = (L1+0.05)/(L2+0.05);
	contrasteColor = (L1+(5/100))/(L2+(5/100));
	
	// redondeo del contraste
	ct = Math.round(contrasteColor*100)/100;
	
	// AA + normal -> 4.5
	if (ct>=4.5) {caso1= CT_SE_CUMPLE; clase1 = 'cumple';} else {caso1= CT_NO_SE_CUMPLE; clase1 = 'noCumple';}
	// AA + grande -> 3
	if (ct>=3) {caso2= CT_SE_CUMPLE; clase2 = 'cumple';} else {caso2= CT_NO_SE_CUMPLE; clase2 = 'noCumple';}
	// AAA + normal -> 7
	if (ct>=7) {caso3= CT_SE_CUMPLE; clase3 = 'cumple';} else {caso3= CT_NO_SE_CUMPLE; clase3 = 'noCumple';}
	// AAA + grande -> 4.5
	if (ct>=4.5) {caso4= CT_SE_CUMPLE; clase4 = 'cumple';} else {caso4= CT_NO_SE_CUMPLE; clase4 = 'noCumple';}
	
	htmlDatos = '<p>'+CT_CONTRASTE+': <strong>'+ct+':1</strong><span class="oculto">.</span></p>';
	htmlDatos = htmlDatos+'<ul>';
	htmlDatos = htmlDatos+'<li class="'+clase1+'"><span class="caso">'+CT_CASO1+' (<span class="oculto">'+CT_REQUIERE_CONTRASTE+' </span>1:4.5):</span> <span>'+caso1+'</span></li>';
	htmlDatos = htmlDatos+'<li class="'+clase2+'"><span class="caso">'+CT_CASO2+' (<span class="oculto">'+CT_REQUIERE_CONTRASTE+' </span>1:3):</span> <span>'+caso2+'</span></li>';
	htmlDatos = htmlDatos+'<li class="'+clase3+'"><span class="caso">'+CT_CASO3+' (<span class="oculto">'+CT_REQUIERE_CONTRASTE+' </span>1:7):</span> <span>'+caso3+'</span></li>';
	htmlDatos = htmlDatos+'<li class="'+clase4+'"><span class="caso">'+CT_CASO4+' (<span class="oculto">'+CT_REQUIERE_CONTRASTE+' </span>1:4.5):</span> <span>'+caso4+'</span></li>';
	htmlDatos = htmlDatos+'</ul>';
	
	
	
	return htmlDatos;
}

function ct_convierteRGB (color) { // Convierte a RGB

	n=2;if (color.length==3) {n=1;} // Se distingue si el color lleva 3 o 6 caracteres
	
	R = ct_hex(ct_hexadecimales(color.substr(0,(1*n))))/255;
	G = ct_hex(ct_hexadecimales(color.substr((1*n),(1*n))))/255;
	B = ct_hex(ct_hexadecimales(color.substr((2*n),(1*n))))/255;
	
	return Array(R,G,B);
}

function ct_hexadecimales (valor) { //Para que el valor hexadecimal sea siempre de dos caracteres cuando el número de color recibido es de tres caracteres
	nuevoValor = valor+valor;
	nuevoValor = nuevoValor.substr(0,2);
	return nuevoValor;
}

function ct_brillo1 (valor) {
	if (valor<=0.03928) {return (valor/12.92);}
	else {return Math.pow(((valor+0.055)/1.055),2.4);}
}

function ct_brillo2 (v1,v2,v3) {
	return ((0.2126*v1)+(0.7152*v2)+(0.0722*v3));
}
function ct_hex (h) {return parseInt(h,16);} // Convierte hexadecimal a decimal
//FIN Herramienta de contraste

