jQuery(document).ready(function() {
	contrasteColores();
});

function contrasteColores() {
	jQuery.extend({
		brillo: function(color) {
			return ((parseInt(color.substr(0,2),16) * 299) + (parseInt(color.substr(2,2),16) * 587) + (parseInt(color.substr(4,2),16) * 114)) / 1000;
		},
		
		difColor: function(color1, color2) {
			return 	Math.abs(parseInt(color1.substr(0,2),16) - parseInt(color2.substr(0,2),16))+
							Math.abs(parseInt(color1.substr(2,2),16) - parseInt(color2.substr(2,2),16))+
							Math.abs(parseInt(color1.substr(4,2),16) - parseInt(color2.substr(4,2),16));
		}
	});
	
	jQuery("button").bind("click", function() {
		if (!jQuery("#colorFondo").validateColor()) return false;
		if (!jQuery("#colorTexto").validateColor()) return false;
		
		jQuery("p#texto").css("background-color", "#"+jQuery("#colorFondo").val());
		jQuery("p#texto").css("color", "#"+jQuery("#colorTexto").val());
		
		var colorFondo = jQuery("#colorFondo").val();
		var colorTexto = jQuery("#colorTexto").val();
		var brilloFondo = jQuery.brillo(colorFondo);
		var brilloTexto = jQuery.brillo(colorTexto);
		var difBrillo = Math.abs(brilloTexto - brilloFondo);
		
		jQuery("#difBrillo").html(Math.round(difBrillo));
		
		var difColor = jQuery.difColor(colorFondo, colorTexto);
		jQuery("#difColor").html(difColor);
		
		if (difBrillo >= 125) {
			if (difColor >= 500) {
				jQuery("#semaforo").addClass("verde");
				jQuery("#semaforo").removeClass("amarillo");
				jQuery("#semaforo").removeClass("rojo");
			} else {
				jQuery("#semaforo").removeClass("verde");
				jQuery("#semaforo").addClass("amarillo");
				jQuery("#semaforo").removeClass("rojo");
			}
		} else {
			if (difColor >= 500) {
				jQuery("#semaforo").removeClass("verde");
				jQuery("#semaforo").addClass("amarillo");
				jQuery("#semaforo").removeClass("rojo");
			} else {
				jQuery("#semaforo").removeClass("verde");
				jQuery("#semaforo").removeClass("amarillo");
				jQuery("#semaforo").addClass("rojo");
			}
		}
	});
	
}
