/**
 * Objeto Familia.
 */
var Familia = Class.create({
	/**
	 * Iniciar el objeto.
	 */
	initialize: function(id, nombre, Buscador) {
		this._id = id;
		this._nombre = nombre;
		this._loaded = false;		
		this._cualificaciones = null;
		this._porcentaje = 0;
		this._checked = false;
		this._init();
		this.buscador = Buscador;
	},
	
	_init : function() {
		//Crear el array vacio de cualificaciones
		this._cualificaciones = new Array();
	},
	
	/**
	 * Dibuajr el html de las familias
	 */
	drawHTML : function() {
		/*
		 * Crear el html del filtro
		 */
		var div_container = new Element('div', { 'class': 'container left'});
		var filtro_input = new Element('input', { 'type': 'checkbox', 'id': 'filtro.fam.' + this._id, 'value': this._id, 'name': 'filtro_fam', 'class': 'filtro_fam'});
		var filtro_label = new Element('label', { 'for': 'filtro.fam.' + this._id}).update('&nbsp;' + this._nombre);
		div_container.appendChild(filtro_input);
		div_container.appendChild(filtro_label);
		$('div_familias_filtro').appendChild(div_container);
		
		/*
		 * Crear el html de popup
		 */
		//Crear el elemento
		var div_container = new Element('div', { 'id': 'familia.' + this._id});
		var div_familia = new Element('div', { 'class': 'em_fila txt5'});
		var div_toggle = new Element('div', { 'class': 'em_boton1'});
		var img_toggle = new Element('img', { 'src': 'images/mas.gif', 'id': 'toggle_familia.' + this._id, 'open_src': 'images/mas.gif', 'close_src': 'images/menos.gif'});
		var div_nombre = new Element('div', { 'class': 'em_nombre'}).update(this._nombre);
		var div_avance = new Element('div', { 'class': 'em_boton2'});
		var img_avance = new Element('img', { 'id': 'img_fam_avance.' + this._id, 'src': 'images/ico_p0.gif', '_0pct_src': 'images/ico_p0.gif', '_50pct_src': 'images/ico_p50.gif', '_100pct_src': 'images/ico_p100.gif'});
		var div_cualificaciones = new Element('div', { 'id': 'layer_cualificaciones.' + this._id});
		
		//Juntar los elementos
		div_container.appendChild(div_familia);
		div_familia.appendChild(div_toggle);
		div_toggle.appendChild(img_toggle);
		div_familia.appendChild(div_nombre);
		div_familia.appendChild(div_avance);
		div_avance.appendChild(img_avance);
		div_container.appendChild(div_cualificaciones);
		
		//Ocultar la capa de cualificaciones
		div_cualificaciones.hide();
		
		//Crear los handlers
		img_toggle.observe('click', this._toggleHandler.bindAsEventListener(this));
		
		//Añadir la capa a la lista de familias.
		$('layer_familias').appendChild(div_container);
	},
	
	/**
	 * El handler cuando se hace click en un toggle de una familia
	 * @param {Object} event
	 */
	_toggleHandler : function(event) {		
		//Si se hace click en el, se abre.
		this._toggle();
	},
	
	/**
	 * Abrir o cerrar una rama familia
	 */
	_toggle : function() {
		//Comprobar si esta abiero o cerrado.
		var layer = $('layer_cualificaciones.' + this._id);
		var toggle = $('toggle_familia.' + this._id);

		if (layer.visible()) {
			toggle.src = toggle.getAttribute('open_src');
			layer.hide();
		} else {
			toggle.src = toggle.getAttribute('close_src');
			this.open(true);
			layer.show();
		}
	},

	/**
	 * Seleccionar o deseleccionar la unidad
	 * @param {Boolean} checked
	 */
	setChecked : function(checked) {
		this._checked = checked;
		return this;
	},
	
	/**
	 * Devolver el nombre de la familia
	 */
	getName : function() {
		return this._nombre
	},

	/**
	 * Actualizar el estado de familia
	 */
	updateState : function() {
        //Calcular el porcentaje
        var porcentaje = this.setPercent();
		this.setChecked(porcentaje != 0);
		
		var image = $('img_fam_avance.' + this._id);
		
		var aprendiendo = false;
		var image_src_array = image.src.split('/images/');
		if (image_src_array.length > 0) {
			var image_src = 'images/' + image_src_array[1];
		}
		if ((image_src == 'images/ico_p0100.gif') || (image_src == 'images/ico_p5050.gif')) {
			aprendiendo = true;
		}
		
		switch (porcentaje) {
            case 0:
                image.src = image.getAttribute('_0pct_src');
				if (aprendiendo) {
					image.src = 'images/ico_p0100.gif';
				}
                break;
            case 100:
                image.src = image.getAttribute('_100pct_src');
                break;
            default:
                image.src = image.getAttribute('_50pct_src');
				if (aprendiendo) {
					image.src = 'images/ico_p5050.gif';
				}
                break;
        }
		

        //Poner el valor de porcentaje en el input y actualizar el check.
        if (porcentaje==0) {
			porcentaje = '';
		}
	},
	
    /**
     * Recoger el porcentage de cualificaciones seleccionado es este familia
     */
    setPercent: function(){
        if (this._loaded) {
            var porcentaje_cualificaciones = 0;
            
            //Calcular cuantos realizaciones estan seleccionada 
            var cualificaciones = this._cualificaciones;
            for (var i = 0, len = cualificaciones.length; i < len; ++i) {
                var id = cualificaciones[i];
                var cualificacion = this.buscador.getCualificacion(id);
                porcentaje_cualificaciones = porcentaje_cualificaciones + cualificacion.getPercent();
            }
            porcentaje = (porcentaje_cualificaciones / cualificaciones.length);
        }
        else {
            porcentaje = 0;
        }
        
        this._porcentaje = porcentaje;
        return this._porcentaje;
    },	
	
	/**
	 * Abrir una familia y mostrar sus cualificaciones
	 */
	open : function(async) {
		
		if (!this._loaded) {
			var me = this;
			
			//Comprobar si esta precargada
			if (this.buscador._preloadedFamilias !== null) {
				this.insertCualificaciones(this.buscador._preloadedFamilias);
			} else {			
				//Si la familia no esta cargado, carga sus cualificaciones a traves de Ajax
				new Ajax.Request('lib_asp/ajax_query.asp?a=cualificaciones&id_familia=' + me._id, {
					method: 'get',
					asynchronous: async,
					onCreate: function(){
						$('loading_now').update('familia con id ' + me._id);
						$('loader').show();
					},
					onComplete: function(){
						$('loading_now').update('');
						$('loader').hide();
					},
					onSuccess: function(transport){
						me.insertCualificaciones((transport.responseText).evalJSON(true));
					}
				});
			}
		}
		this._loaded = true;
	},

	/**
	 * Insertar los cualificaciones
	 * @param {Object} cualificaciones
	 */
	insertCualificaciones : function(cualificaciones) {
		for (var i = 0, len = cualificaciones.length; i < len; ++i) {
			var cualificacion = new Cualificacion($H(cualificaciones[i]), this.buscador);
			
			var id = cualificacion.getField('id');
			this._cualificaciones.push(id);
			this.buscador.insertCualificacion(id, cualificacion);
			
			//Dibujar el html de cualificacion
			cualificacion.drawHTML(this._id);
		}
	}
});
