/**
 * Clase que gestiona los votos en el web
 *
 * @author Javier Mateo
 * @date 2009-10
 */
var CommentsAjaxLoader = new Class({

	path: null,
	_comments : null,
	/**
     * Constructor de la clase
     *
     * @param {Object} path
     * @param {Object} options
     */
    initialize: function(path){
		this.path = path;
        this._comments = new Hash();
    },
	
	/**
     * Añadimos contenedores al array
     *
     * @param idContent id
     * @param contenedor string
     */
    addNoComments : function(idContent, contenedor) {
        if (!$defined(idContent)) {
                return;
        }
    	this._comments.include(idContent,contenedor);
    },
    
    /**
     * Ejecutamos la clase cuando se ha cargado el web
     */
    process : function() {
    	var salida = [];
    	$each(this._comments, function(key, value) {
    		salida.include(value);
    	});
    	salida.join(',');
    	this.requestCommentsNumber(salida);
    },
    
    /**
     * Crea la primera petición con los comentarios actuales del contenido
     *
     * @param identificadores string de id's (2,3,4,5)
     */
    requestCommentsNumber: function(identificadores){
    	if (!$defined(identificadores)) {
                return;
        }
        new Request.XML({
        	'url': this.path + '/index.php/services/comments',
            'method': 'post'
		}).addEvent('success', this.handleRequestCommentsNumber.bindWithEvent(this)).send('action=requestNoComments&content=' + identificadores);
    },
    
    /**
     * Recoge los valores de la respuesta Ajax y llama a render
     *
     * @param {Object} text
     * @param {Object} xml
     */
    handleRequestCommentsNumber: function(text, xml){
    	var erres = xml.getElements('r');
    	
    	$each(this._comments, function(key, value) {
    		this.renderNoComments(key, '0');
		}, this);
		$each(erres, function(key, value) {
	        var total = key.getElementsByTagName('total');
	        if (total.length == 0) {
	            return;
	        }
	        total = total[0].firstChild.nodeValue;
	        this.renderNoComments(this._comments[key.get('id')], total);	
		}, this);
		
    },
    
    /**
     * Pintamos las estrellitas y añadimos los eventos
     * 
     * @param id identificador
     * @param {Object} total
     * @param {Object} resultado

     */
    renderNoComments: function(id, total){
        $each($$(id), function(el){
        	var texto = '';
        	if(total == 0) {
        		texto = '¡comenta!';
        	}
        	else if(total == 1) {
        		texto = total + ' comentario';
        	}
        	else {
        		texto = total + ' comentarios';
        	}
        	el.set('html', texto);
		}, this);
    }
});
