/**
 * Clase que gestiona los votos en el web
 *
 * @author Javier Mateo
 * @date 2009-05
 */
var _webUser = null;
var option = 0;
var captchaCode ='';
var errorUsername = false;
var errorLogin = false;

var Comments = new Class({
	
	/**
     * Ejecutamos la clase cuando se ha cargado el web
     */
	
	initialize: function() {
		if ($$('.Comentarios').get('class')=="Comentarios"){
			
			this.getUser();
		
			this.addEvents();
			
			if ($('message')){
				$('message').setStyles({
					'display' : 'none',
					'opacity' : 0
				});
			}
			if ($('messageError')){
				$('messageError').setStyle('display', 'none');
				$('messageError').setStyle('opacity', 0);
			}
			
			if ($('messageErrorFormulario')){
				$('messageErrorFormulario').setStyle('display', 'none');
				$('messageErrorFormulario').setStyle('opacity', 0);
			}
			if ($('errorCheck')){
				$('errorCheck').setStyle('display', 'none');
				$('errorCheck').setStyle('opacity', 0);
			}
			if ($('okCheck')){
				$('okCheck').setStyle('display', 'none');
				$('okCheck').setStyle('opacity', 0);
			}
			if ($('onCheck')){
				$('onCheck').setStyle('display', 'none');
				$('onCheck').setStyle('opacity', 0);
			}

		}
	},
	
	addEvents:function (){

		if ($('frmComentario')){
			$('frmComentario').removeEvents();
			$('frmComentario').addEvent('click', this.clearComment.bindWithEvent(this));
			$('frmComentario').addEvent('keydown', this.countCharacters.bindWithEvent(this));
			$('frmComentario').addEvent('keyup', this.countCharacters.bindWithEvent(this));
		}
		
		if ($('frmNombre')){ 
			$('frmNombre').removeEvents();
			$('frmNombre').addEvent('click', this.clearInput.bindWithEvent(this,$('frmNombre')));
		}
		
		if ($('frmUsuario2')){ 
			$('frmUsuario2').removeEvents();
			$('frmUsuario2').addEvent('click', this.clearInput.bindWithEvent(this,$('frmusuario')));
			$('frmUsuario2').addEvent('blur', this.checkUsername.bindWithEvent(this));
		}
		
		if ($('frmEmail2')){ 
			$('frmEmail2').removeEvents();
			$('frmEmail2').addEvent('click', this.clearInput.bindWithEvent(this,$('frmEmail2')));
			$('frmEmail2').addEvent('blur', this.checkLogin.bindWithEvent(this));
		}
		
		
		if ($('frmEmail')){
			$('frmEmail').removeEvents();
			$('frmEmail').addEvent('click', this.clearInput.bindWithEvent(this,$('frmEmail')));
		}
		
		if ($('frmWeb')){
			$('frmWeb').removeEvents();
			$('frmWeb').addEvent('click', this.clearInput.bindWithEvent(this,$('frmWeb')));
		}

		if ($('formComentarios')){
			$('formComentarios').removeEvents();
			$('formComentarios').addEvent('submit', this.sendForm.bindWithEvent(this));
		}
		
		if ($('aSinRegistro')){
			$('aSinRegistro').removeEvents();
			$('aSinRegistro').addEvent('click', this.showOption.bindWithEvent(this,1));
		}
		if ($('aRegistro')){
			$('aRegistro').removeEvents();
			$('aRegistro').addEvent('click', this.showOption.bindWithEvent(this,2));
		}
		if ($('aLogin')){
			$('aLogin').removeEvents();
			$('aLogin').addEvent('click', this.showOption.bindWithEvent(this,3));
		}
		
		if ($('alogOut')){
			$('alogOut').removeEvents();
			$('alogOut').addEvent('click', this.disconnect.bindWithEvent(this));
		}
		
		if ($('imgCaptchaSinRegistro')){
			$('imgCaptchaSinRegistro').removeEvents();
			$('imgCaptchaSinRegistro').addEvent('click', this.captchaLoad.bindWithEvent(this,[$('imgCaptchaSinRegistro'),$('captchaCodeSinRegistro')]));
		}
		
		if ($('imgCaptchaRegistro')){
			$('imgCaptchaRegistro').removeEvents();
			$('imgCaptchaRegistro').addEvent('click', this.captchaLoad.bindWithEvent(this,[$('imgCaptchaRegistro'),$('captchaCodeRegistro')]));
		}
		
		
		
		

		
	},
	
	
	showOption: function (e,Option){
		if (e){
			new Event(e).stop();
		}
		if ($('frmSinRegistro')){
			$('frmSinRegistro').setStyle('opacity', 0);
			$('frmSinRegistro').setStyle('display', 'none');
			if ($('liSinRegistro')){
				$('liSinRegistro').setStyle('opacity', 0);
				$('liSinRegistro').setStyle('display', 'none');
				$('liSinRegistro').setProperty('class','');
			}
			
		}
		if ($('frmRegistro')){
			$('frmRegistro').setStyle('opacity', 0);
			$('frmRegistro').setStyle('display', 'none');
			if ($('liRegistro')){
				$('liRegistro').setStyle('opacity', 0);
				$('liRegistro').setStyle('display', 'none');
				$('liRegistro').setProperty('class','');
			}
			
		}
		if ($('frmLogin')){
			$('frmLogin').setStyle('opacity', 0);
			$('frmLogin').setStyle('display', 'none');
			if ($('liLogin')){
				$('liLogin').setStyle('opacity', 0);
				$('liLogin').setStyle('display', 'none');
				$('liLogin').setProperty('class','');
			}
			
		}
		if ($('frmEviarComentario')){
			$('frmEviarComentario').setStyle('opacity', 0);
			$('frmEviarComentario').setStyle('display', 'none');
  
			if ($('liEnviarComentario')){
				$('liEnviarComentario').setStyle('opacity', 0);
				$('liEnviarComentario').setStyle('display', 'none');
				$('liEnviarComentario').setProperty('class','');
			}
			
		}
		
		
		switch(Option){
			case 1:
				if ($('frmSinRegistro')){
					this.fadeIn($('frmSinRegistro'));
					if ($('liSinRegistro')){
						this.fadeIn($('liSinRegistro'));
						$('liSinRegistro').setProperty('class','On');
					}
					this.captchaLoad(null,$('imgCaptchaSinRegistro'),$('captchaCodeSinRegistro'));
				}
			break;
			case 2:
				if ($('frmRegistro')){
					if (_webUser.get('id') != 0){
						this.loadUserData();
					}
					this.fadeIn($('frmRegistro'));
					
					if ($('liRegistro')){
						this.fadeIn($('liRegistro'));
						$('liRegistro').setProperty('class','On');
					}
					this.captchaLoad(null,$('imgCaptchaRegistro'),$('captchaCodeRegistro'));
				}
			break;
			case 3:
				if ($('frmLogin')){
					this.fadeIn($('frmLogin'));
					if ($('liLogin')){
						this.fadeIn($('liLogin'));
						$('liLogin').setProperty('class','On');
					}
				}
			break;
			case 4:
				if ($('frmEviarComentario')){
					this.fadeIn($('frmEviarComentario'));
					if ($('liEnviarComentario')){
						this.fadeIn($('liEnviarComentario'));
						$('liEnviarComentario').setProperty('class','On');
					}
					this.captchaLoad(null,$('imgCaptcha'),$('captchaCode'));
				}
			break;
			case 0:
				var _primeroMostrado = false;
				if ($('frmSinRegistro') && !_primeroMostrado){
					this.fadeIn($('frmSinRegistro'));
					if ($('liSinRegistro')){
						$('liSinRegistro').setProperty('class','On');
					}
					this.captchaLoad(null,$('imgCaptchaSinRegistro'),$('captchaCodeSinRegistro'));
					Option = 1;
					_primeroMostrado = true;
				}
				
				if ($('frmLogin') && !_primeroMostrado){
					this.fadeIn($('frmLogin'));
					if ($('liLogin')){
						$('liLogin').setProperty('class','On');
					}
					Option = 3;
					_primeroMostrado = true;
					
				}
				if ($('frmRegistro') && !_primeroMostrado){
					this.fadeIn($('frmRegistro'));
					if ($('liRegistro')){
						$('liRegistro').setProperty('class','On');
					}
					Option = 2;
					_primeroMostrado = true;
				}
				
				
			break;
		}
		//Si no estoy logueado
		if (_webUser.get('id') == 0){
			if ($('liSinRegistro')){
				this.fadeIn($('liSinRegistro'));
			}
			if ($('liLogin')){
				this.fadeIn($('liLogin'));
			}
			if ($('liRegistro')){
				this.fadeIn($('liRegistro'));
			}
			
		}
		option = Option;
		
	},
	
	getUser: function(){
		this.cookieLogin = Cookie.read('login');
		
		//this.cookieLogin = Cookie.read('PUBLISHER2_SESS');
		_webUser = new webUser();

		if(this.cookieLogin != null){ // logueado
			//alert("1");
			this.loadWebUser(this.cookieLogin.split('|')[2],this.cookieLogin.split('|')[0]);
			
    	}
		else{
			//alert("2");
			this.showOption(null,1);
			this.requestComments(null,thispage);
		}
	},

	sendCommentRegister:function(){
		new Request({
            'url': path + '/index.php/services/register/WS/',
            'method': 'post'
        }).addEvent('success', this.handleSendCommentRegister.bindWithEvent(this)).send('action=loadUser&login='+ this.cookieLogin.split('|')[2] + '&id='+ this.cookieLogin.split('|')[0] );
	},
	
	
	handleSendCommentRegister:function(text, xml){
		_error = false;
    	if (xml.getElement("register") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}      
    	}
    	else{
    		if (xml.getElement('register r resultado').get('text') == 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}    
    	}
    	
    	if (!_error){
    		
    		var id = xml.getElementsByTagName('id');
    		
    	    if (id[0].firstChild != null) {
    	    	_webUser.set('id',id[0].firstChild.nodeValue);
    	    	
    	    }
    	    var nick = xml.getElementsByTagName('name');
    	    if (nick[0].firstChild != null) {
    	    	_webUser.set('nick',nick[0].firstChild.nodeValue);
    	    	
    	    }
    	    var email = xml.getElementsByTagName('login');
    	    if (email[0].firstChild != null) {
    	    	_webUser.set('email',email[0].firstChild.nodeValue);
    	    }
    	    var password = xml.getElementsByTagName('passwd');
    	    if (password[0].firstChild != null) {
    	    	_webUser.set('password',password[0].firstChild.nodeValue);
    	    }
    	    var urlweb = xml.getElementsByTagName('urlusuario');
    	    if (urlweb[0].firstChild != null) {
    	    	_webUser.set('urlweb',urlweb[0].firstChild.nodeValue);
    	    }
    	    if ($('spanIdUsuario')){
    			$('spanIdUsuario').set('text',_webUser.get('nick'));
    		}
    	    this.sendComment(null);
    	    this.disconnect();
    	}
    	else{
    		this.showOption(null,1);
    	}
	

    },
	
	countCharacters: function (e){
		n = $('frmComentario').value.length;
		t = 500;
		if (n > t) {
			$('frmComentario').value = $('frmComentario').value.substring(0, t);
		}
		else {
			$('totalCharacters').set('text','(' + (t-n) + '/' + t + ')');
		}
	},
	
	requestComments: function(e,page){
		if (e){
			new Event(e).stop();
		} 
        new Request.HTML({
            'url': path + '/index.php/es/services/comments',
            'method': 'post',
            'update': $$('.ListaComentarios')[0]
        }).addEvent('success', this.handleRequestComments.bindWithEvent(this)).send('action=getComments&idcontent=' + idContent + '&page=' + page + '&cant=' + cant + '&idUser=' + _webUser.get('id'));
        thispage = page;

    },
    
    
    captchaLoad: function(e,img,input){
    	if (e){
			new Event(e).stop();
		} 
    	if (img){
    		img.set('src',  path + '/index.php/es/captcha/show?' + Date());
    	}
    	if (input){
    		input.set('value','');
    	}
    },

	
	/**
     * Manda la votación del usuario
     *
     * @param {Object} e
     * @param {Object} idComment
     * @param {Object} vote
     */
	
    sendVote: function(e,idComment,vote){
        new Event(e).stop();
        new Request({
            'url': path + '/index.php/es/services/comments',
            'method': 'post'
        }).addEvent('success', this.handleSendingVote.bindWithEvent(this)).send('action=vote&idcomment=' + idComment + '&idUser=' + _webUser.get('id') +'&vote=' + vote);
    },

	  /**
     * Manda el comentario del usuario
     *
     * @param {Object} e
     * @param {Object} idComment
     * @param {Object} vote
     */

    sendComment: function(e){
    	if (e){
    		new Event(e).stop();
    	}
    	this.clearComment();
        new Request({
            'url': path + '/index.php/es/services/comments',
            'method': 'post'
        }).addEvent('success', this.handleSendingComment.bindWithEvent(this)).send('action=create&idcontent=' + idContent + '&comment=' + $('frmComentario').get('value') + '&nick=' +  _webUser.get('nick') + '&idUser=' + _webUser.get('id') + '&urlWeb=' + _webUser.get('urlweb') + '&email=' + _webUser.get('email') + '&captchacode=' + captchaCode + '&className=' + cmsClass + '&classType=' + cmsType);
    },
    
    /**
     * Envía la solicitud de login
     *
     * @param {Object} e
     * @param {Object} idComment
     * @param {Object} vote
     */

    register: function(e){
    	new Event(e).stop();

        new Request({
            'url': path + '/index.php/services/register/WS/',
            'method': 'post'
        }).addEvent('success', this.handleRegister.bindWithEvent(this)).send('action=register&login='+ _webUser.get('nick') +'&email='+ _webUser.get('email') +'&password='+ _webUser.get('password') + '&urlUsuario=' + _webUser.get('urlweb') + '&captchacode=' + captchaCode );

    },
    
    /**
     * Envía la solicitud de login
     *
     * @param {Object} e
     * @param {Object} idComment
     * @param {Object} vote
     */

    checkLogin: function(e){
    	if ($('frmEmail2').get('value')!=''){
	    	new Event(e).stop();
	    	$('onCheck').set('text', 'Comprobando correo electrónico...');
	    	this.fadeIn($('onCheck'));
	        new Request({
	            'url': path + '/index.php/services/register/WS/',
	            'method': 'post'
	        }).addEvent('success', this.handleCheckLogin.bindWithEvent(this)).send('action=checkLogin&login='+ $('frmEmail2').get('value') );
    	}
    },
    
    /**
     * Envía la solicitud de login
     *
     * @param {Object} e
     * @param {Object} idComment
     * @param {Object} vote
     */

    checkUsername: function(e){
    	if ($('frmUsuario2')){
	    	if ($('frmUsuario2').get('value')!=''){
		    	new Event(e).stop();
		    	$('onCheck').set('text', 'Comprobando usuario...');
		    	this.fadeIn($('onCheck'));
		        new Request({
		            'url': path + '/index.php/services/register/WS/',
		            'method': 'post'
		        }).addEvent('success', this.handleCheckUserName.bindWithEvent(this)).send('action=checkUsername&Username='+ $('frmUsuario2').get('value') );
	    	}
    	}

    },
    
    clearUser: function (){
		_webUser.set('id', 0);
		_webUser.set('nick', '');
		_webUser.set('email', '');
		_webUser.set('password', '');
		_webUser.set('urlweb', '');
		
	},
    
    loadWebUser: function(login,id){
		new Request({
            'url': path + '/index.php/services/register/WS/',
            'method': 'post'
        }).addEvent('success', this.handleLoad.bindWithEvent(this)).send('action=loadUser&login='+ login + '&id='+ id );
	},
	
	handleLoad: function(text, xml){
		_error = false;
    	if (xml.getElement("register") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}      
    	}
    	else{
    		if (xml.getElement('register r resultado').get('text') == 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}    
    	}
    	
    	if (!_error){
    		
    		var id = xml.getElementsByTagName('id');
    		
    	    if (id[0].firstChild != null) {
    	    	_webUser.set('id',id[0].firstChild.nodeValue);
    	    	
    	    }
    	    var nick = xml.getElementsByTagName('name');
    	    if (nick[0].firstChild != null) {
    	    	_webUser.set('nick',nick[0].firstChild.nodeValue);
    	    	
    	    }
    	    var email = xml.getElementsByTagName('login');
    	    if (email[0].firstChild != null) {
    	    	_webUser.set('email',email[0].firstChild.nodeValue);
    	    }
    	    var password = xml.getElementsByTagName('passwd');
    	    if (password[0].firstChild != null) {
    	    	_webUser.set('password',password[0].firstChild.nodeValue);
    	    }
    	    var urlweb = xml.getElementsByTagName('urlusuario');
    	    if (urlweb[0].firstChild != null) {
    	    	_webUser.set('urlweb',urlweb[0].firstChild.nodeValue);
    	    }
    	    if ($('spanIdUsuario')){
    			$('spanIdUsuario').set('text',_webUser.get('nick'));
    		}
    	    this.showOption(null,4);
    	    this.requestComments(null,thispage);
    	}
    	else{
    		this.showOption(null,1);
    		this.requestComments(null,thispage);
    	}
	

    },
    
    showNegative: function(e,idComment){
    	new Event(e).stop();
    	$each($$('.Comentario'),function(key,value) {
    		if (key.get('idComment') == idComment){
	    		key.set('class', 'Comentario');
    		}
    	}, this);
    },
    
    clearComment: function(){
    	if ($('frmComentario')){
	        if ($('frmComentario').get('value') == 'introduce tu comentario'){
	        	$('frmComentario').set('value','');
	        }
    	}
    },

    clearInput: function(e,input){
		new Event(e).stop();

        if (input){
        	input.value='';
        }
    },
    
    handleSendingComment: function(text, xml){
    	if (xml.getElement("comments") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			this.errorMessage(xml.getChildren()[0].getChildren()[1].getChildren()[0]);
    		}
    		else{
		    	$('frmComentario').value = 'introduce tu comentario';
		    	this.message('Comentario enviado');
		    	this.clearForms();
		    	this.requestComments(null,thispage);
	    	}    
    		
    	}
    	else{
    		if (xml.getElement('comments r resultado').get('text') == 'Error'){
    			this.errorMessage(xml.getElements('comments r errors error'));
	    	}
	    	else{
		    	$('frmComentario').value = 'introduce tu comentario';
		    	this.message('Comentario enviado');
		    	this.clearForms();
		    	this.requestComments(null,thispage);
	    	}    
    	}
    	
    	this.showOption(null,option);
    },
    
    handleRequestComments: function (){
    	$('totalCharacters').set('text','(500/500)');
    	this.assignNavigation();
    	this.assignVotes();
    	this.assignShowNegatives();
    	
    },
    
    handleRegister: function(text, xml){
    	var _error = '';
    	var _idUser = '';
    	if (xml.getElement("register") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			_error=xml.getChildren()[0].getChildren()[1].getChildren()[0].getChildren()[2].get('text');
    		}
	    	else{
	    		_idUser = xml.getChildren()[0].getChildren()[1].getChildren()[0].get('text');
	    	}   
    	}
    	else{
    		if (xml.getElement('register r resultado').get('text') == 'Error'){
    			_error=xml.getElements('register r errors error userMessage').get('text');
	    	}
	    	else{
	    		_idUser = xml.getElements('register r data idUser').get('text');
	    	}    
    	}
    		
		if (_error!=''){
			this.errorFormMessage(_error);
		}
		else{
			var avisos = null;
			avisos = new Avisos({
				'modal' : true,
				'clickToCancel' : true,
				'autoclose' : 5
			});
			var handle = avisos.getHandle();
			handle.empty();
			$('UsuarioRegistrado').injectInside(handle);
			avisos.show();
			this.createCookie('login', _idUser + '|' + _webUser.get('nick') + '|' + _webUser.get('email') + '|' + false, false, null);
			this.sendCommentRegister();
    	}    
    		
    	
    	
    },
    
    handleCheckUserName: function(text, xml){
    	this.fadeOut($('onCheck'));
    	this.displayNone.delay(200,this,$('onCheck'));
    	if (xml.getElement("register") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}      
    	}
    	else{
    		if (xml.getElement('register r resultado').get('text') == 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}    
    	}
    	
    	if (_error){
    		$('errorCheck').set('text', 'Este usuario ya existe. Prueba con otro.');
	    	this.fadeIn($('errorCheck'));
	    	this.fadeOut.delay(3000,this,$('errorCheck'));
	    	this.displayNone.delay(3200,this,$('errorCheck'));
	    	if ($('frmUsuario2')){
	    		$('frmUsuario2').setProperty('class', 'Corto Incompleto');
	    	}
	    	errorUsername = true;
    	}
    	else{
    		$('okCheck').set('text', 'Usuario disponible');
			this.fadeIn($('okCheck'));
	    	this.fadeOut.delay(3000,this,$('okCheck'));
	    	this.displayNone.delay(3200,this,$('okCheck'));
	    	if ($('frmUsuario2')){
	    		$('frmUsuario2').setProperty('class', 'Corto');
	    	}
	    	errorUsername = false;
    	}
	

    },
    
    handleCheckLogin: function(text, xml){
    	this.fadeOut($('onCheck'));
    	this.displayNone.delay(200,this,$('onCheck'));
    	if (xml.getElement("register") == null){
    		if(xml.getChildren()[0].getChildren()[0].get('text')== 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}      
    	}
    	else{
    		if (xml.getElement('register r resultado').get('text') == 'Error'){
    			_error=true;
	    	}
	    	else{
	    		_error=false;
	    	}    
    	}
    	
    	if (_error){
    		$('errorCheck').set('text', 'Este correo electrónico ya existe. Prueba con otro.');
	    	this.fadeIn($('errorCheck'));
	    	this.fadeOut.delay(3000,this,$('errorCheck'));
	    	this.displayNone.delay(3200,this,$('errorCheck'));
	    	$('frmEmail2').setProperty('class', 'Incompleto');
	    	errorLogin = true;
    	}
    	else{
    		$('okCheck').set('text', 'Correo electrónico disponible');
			this.fadeIn($('okCheck'));
	    	this.fadeOut.delay(3000,this,$('okCheck'));
	    	this.displayNone.delay(3200,this,$('okCheck'));
	    	$('frmEmail2').setProperty('class', '');
	    	errorLogin = false;
    	}
	

    },
    
    
    assignNavigation: function (){
    	$each($$('.linkPagina'),function(key,value) {
    		key.addEvent('click', this.requestComments.bindWithEvent(this,key.get('text')));
    	}, this);

    	if ($('linkPosterior')){
    		$('linkPosterior').addEvent('click', this.requestComments.bindWithEvent(this,thispage.toInt() + 1));
    	}
    	if ($('linkAnterior')){
    		$('linkAnterior').addEvent('click', this.requestComments.bindWithEvent(this,thispage.toInt() - 1));
    	}
    	
    },
    
    assignVotes: function (){
    	
    	$$('.Positivo').each(function(key,value) {
    		if (key.get('idComment')){
	    		key.addEvent('click', this.sendVote.bindWithEvent(this,[key.get('idComment'),+1]))
	    			.setStyle('cursor', 'pointer');
    		}
    	}, this);
    	
    	$$('.Negativo').each(function(key,value) {
    		if (key.get('idComment')){
	    		key.addEvent('click', this.sendVote.bindWithEvent(this,[key.get('idComment'),-1]))
	    			.setStyle('cursor', 'pointer');
    		}
    	}, this);

    	
    },
    
    assignShowNegatives: function (){
    	$each($$('.MostrarComentario'),function(key,value) {
    		if (key.get('idComment')){
	    		key.addEvent('click', this.showNegative.bindWithEvent(this,[key.get('idComment')]));
	    		key.setStyle('cursor', 'pointer');
    		}
    	}, this);
    },
    

    
    handleSendingVote: function(){
    	this.requestComments(null,thispage);
    },
    
    errorMessage: function(xml){

    	if (xml.getElement('userMessage')!=null){
    		var userMessage=xml.getElement('userMessage').get('text');
    	}
    	else{
    		var userMessage=xml.getChildren()[3].get('text');
    	}
    	if (userMessage!=''){
    		var box = $('messageError');
	    	box.style.display="block";
	    	box.set('text', userMessage)
	    	var myFx = new Fx.Scroll(window).set(box.getPosition().x,box.getPosition().y);
	    	this.fadeIn(box);
	    	this.fadeOut.delay(3000,this,box);
	    	this.displayNone.delay(3200,this,box);
    	}
    },
    
    message: function(xml){
    	var box = $('message');
    	box.style.display="block";
    	var myFx = new Fx.Scroll(window).set(box.getPosition().x,box.getPosition().y);
    	this.fadeIn(box);
    	this.fadeOut.delay(3000,this,box);
    	this.displayNone.delay(3200,this,box);
    },
    
    errorFormMessage: function(userMessages){
    	var box = $('messageErrorFormulario');
    	box.style.display="block";
    	var message='';
    	
	    	if (userMessages.length > 1){
	    		message = 'Hay varios errores en el formuario';
	    	}
	    	else{
	    		message = userMessages;
	    	}
    	
    	
    	box.set('text', message)
    	this.fadeIn(box);
    	this.fadeOut.delay(3000,this,box);
    	this.displayNone.delay(3200,this,box);
    },
    
    fadeIn: function(box){
    	if (box){
	    	box.style.display="block";
	    	box.fade('in');
    	}
    },
    
    fadeOut: function(box){
    	if (box){
    		box.fade('out');
    	}
    	
    },
    
    displayNone: function(box){
    	box.style.display="none";
    },
    
    
    /**
     * Recogemos las variables del formulario
     */
    fillVars : function(e) {
    	new Event(e).stop();
    	_webUser.set('email',$('frmUsuario').get('value'));
    	_webUser.set('password',$('frmPassword').get('value'));
    	this.remenberPassword = $('frmRecuerdaPassword');

    	this.requestLogin();
    },
    
    /**
     * Crea la primera petición con la votación actual del contenido
     */
    requestLogin: function(){
        new Request({
            'url': frontGlob['rel_path'] + '/index.php/services/loginWeb',
            'method': 'post'
		}).addEvent('success', this.handleRequestLogin.bindWithEvent(this)).send('user=' + _webUser.get('email') + '&password=' + _webUser.get('password') + '&remenber=' + this.remenberPassword.get('checked'));
    },
    
    
    /**
     * Recoge los valores de la respuesta Ajax y llama a render
     *
     * @param {Object} text
     * @param {Object} xml
     */
    handleRequestLogin: function(text, xml){
		
		var status = xml.getElementsByTagName('status');
	    if (status != null) {
	    	status = status[0].firstChild.nodeValue;
	    }
	    
		var msg = xml.getElementsByTagName('msg');
	    if (msg[0].firstChild != null) {
	    	msg = msg[0].firstChild.nodeValue;
	    }
	    
		var idUser = xml.getElementsByTagName('idUser');
	    if (idUser[0].firstChild != null) {
	    	idUser = idUser[0].firstChild.nodeValue;
	    }
	    		
		var user = xml.getElementsByTagName('user');
	    if (user[0].firstChild != null) {
	    	user = user[0].firstChild.nodeValue;
	    }
	    
	    var email = xml.getElementsByTagName('email');
	    if (email[0].firstChild != null) {
	    	email = email[0].firstChild.nodeValue;
	    }
	    
	    var cookieDuration = xml.getElementsByTagName('cookieDuration');
	    if (cookieDuration[0].firstChild != null) {
	    	cookieDuration = cookieDuration[0].firstChild.nodeValue;
	    }
	    
	    var sections = xml.getElementsByTagName('sections');
	    if (sections[0].firstChild != null) {
	    	sections = sections[0].firstChild.nodeValue;
	    	if(sections == 0) {
	    		sections = '';
	    	}
	    }
	    
	    this.renderLogin(status, msg, idUser, user, email, cookieDuration, sections);
    },
    
    /**
     * Muestra mensaje ok/Nok y creamos cookie
     *
     * @param status string
     * @param msg string
     * @param idUser int
     * @param user string
     * @param email string
     */
    renderLogin : function(status, msg, idUser, user, email, cookieDuration, sections) {
    	if(status == 'ok') {
    		
    		if(sections == 0) {
    			sections = '';
    		}
    	    		
    		this.createCookie('login', idUser + '|' + user + '|' + email + '|' + cookieDuration, cookieDuration, sections);
    		this.clearForms();
    		this.showOption(null,4);
    		
    	}
    	else {
    		
    		this.errorFormMessage('Nombre de usuario o contraseña incorrecta');
    		//this.deleteCookie('login');
    		$('frmUsuario').setProperty('class', 'Corto Incompleto');
    		$('frmPassword').setProperty('class', 'Incompleto');
    	}
    },
    
    
    /**
	 * Crea una cookie
	 * 
	 * @param {Object} name
	 * @param {Object} value
	 * @param {Object} days
	 */
	createCookie : function(name, value, cookieDuration, section){
		
		// si viene seccion la añadimos
		if(typeof(section) != 'undefined' && section != '') {
			if(this.cookieLogin != null && this.cookieLogin.contains('#')) {
				value += ';' + section;
			}
			else {
				value += '#' + section;
			}
		}
		
		var expires = '';
		if (cookieDuration == 'true') {
			expires = 30;
		}
		
		Cookie.write(name, value, {duration: expires, path: '/'});
		this.getUser();
	},
	
	
	
	/**
	 * Borra una cookie
	 *
	 * @param {Object} name
	 */
	deleteCookie : function(name) {
		Cookie.write(name, this.cookieLogin, {duration: -1, path: '/'});
		this.getUser();
		
		/* 
		@TODO
		Cookie.dispose(name, this.cookieLogin);
		*/
	},
	
	disconnect: function(e){
		if (e){
			new Event(e).stop();
		} 
		
		this.deleteCookie('login');
		this.requestComments(null,thispage);
		
	},
	
	checkEmail: function (mail){
		return mail.test("^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$");
	},
	
	
    
    sendForm: function(e){
    	if (e){
			new Event(e).stop();
		} 
    	captchaCode = '';
    	switch(option){
    		case 1:
    			_webUser.set('nick', $('frmNombre').get('value'));
    			if ($('frmWeb').get('value')!='http://'){
    				_webUser.set('urlweb', $('frmWeb').get('value'));
    			}
    			_webUser.set('email', $('frmEmail').get('value'));
    			captchaCode= $('captchaCodeSinRegistro').get('value');
    			var errores= new Array();
    			$('frmEmail').setProperty('class', '');
    			$('frmNombre').setProperty('class', 'Corto');
    			if ($('frmNombre').get('value') == ''){
    				errores.include('Introduce un nombre para el comentario');
    				$('frmNombre').setProperty('class', 'Corto Incompleto');
    				
    			}   
    			if (!this.checkEmail($('frmEmail').get('value'))){
    				errores.include('Introduzca una dirección de email válida');
    				$('frmEmail').setProperty('class', 'Incompleto');
    			}   
    			if ($('frmCondicionesUso').get('checked') == false){
    				errores.include('Debe aceptar las condiciones de uso');
    			}   	
    			if (!errores.length){
    				this.sendComment(e);
    			}
    			else{
    				this.errorFormMessage(errores);
    			}
    				
    			break;
    			
    		case 2:
    			var errores= new Array();
    			_webUser.set('nick',$('frmUsuario2').get('value'));
    			_webUser.set('password',$('frmPassword2').get('value'));
    			_webUser.set('email',$('frmEmail2').get('value'));
    			captchaCode= $('captchaCodeRegistro').get('value');
    			_webUser.set('urlweb',$('frmWeb2').get('value'));
    			$('frmRepitePassword2').setProperty('class', '');
    			$('frmPassword2').setProperty('class', '');
    			$('frmEmail2').setProperty('class', '');
    			$('frmUsuario2').setProperty('class', 'Corto');
    			
    			if (errorLogin){
    				errores.include('El correo electrónico ya está en uso');
    				$('frmEmail2').setProperty('class', 'Incompleto');
    			}
    			if (errorUsername){
    				errores.include('El nombre ya está en uso');
    				$('frmUsuario2').setProperty('class', 'Corto Incompleto');
    			}
    			
    			if ($('frmPassword2').get('value') != $('frmRepitePassword2').get('value')){
    				errores.include('Los password no son iguales');
    				$('frmPassword2').setProperty('class', 'Incompleto');
    				$('frmRepitePassword2').setProperty('class', 'Incompleto');
    			}
    			if ($('frmPassword2').get('value')==''){
    				errores.include('El password no puede estar vacío');
    				$('frmPassword2').setProperty('class', 'Incompleto');
    				$('frmRepitePassword2').setProperty('class', 'Incompleto');
    			}
    			if (!this.checkEmail($('frmEmail2').get('value'))){
    				errores.include('Introduzca una dirección de email válida');
    				$('frmEmail2').setProperty('class', 'Incompleto');
    			}
    			if ($('frmCondicionesUso2').get('checked') == false){
    				errores.include('Debe aceptar las condiciones de uso');
    			}   	
    			this.clearComment();
    			if (!$('frmComentario').get('value')!=''){ 
    				errores.include('Has de escribir un comentario');
    			}
    			
    			if (!errores.length){
   					this.register(e);
    			}
    			else{
	    			
	    			this.errorFormMessage(errores);
    			}
    			break;
    		case 3:
    			this.fillVars(e);
    			break;
			case 4:
				this.sendComment(e);
				break;
    	}
			
    },
    
    loadUserData:function(){
    	$('frmusuario').set('value',_webUser.get('nick'));
    	$('frmEmail2').set('value',_webUser.get('email'));
    	$('frmWeb2').set('value',_webUser.get('urlweb'));
    },
    
    
	clearForms:function(){
    	if ($('frmUsuario')){
    		$('frmUsuario').set('value', '');
    	}
    	if ($('frmPassword')){
    		$('frmPassword').set('value', '');
    	}
    	if ($('frmUsuario2')){
    		$('frmUsuario2').set('value', '');
    	}
    	if ($('frmEmail2')){
    		$('frmEmail2').set('value', '');
    	}
    	if ($('frmPassword2')){
    		$('frmPassword2').set('value', '');
    	}
    	if ($('frmRepitePassword2')){
    		$('frmRepitePassword2').set('value', '');
    	}
    	if ($('captchaCodeRegistro')){
    		$('captchaCodeRegistro').set('value', '');
    	}
    	if ($('frmWeb2')){
    		$('frmWeb2').set('value', 'http://');
    	}
    	if ($('frmNombre')){
    		$('frmNombre').set('value', '');
    	}
    	if ($('frmWeb')){
    		$('frmWeb').set('value', 'http://');
    	}
    	if ($('frmEmail')){
    		$('frmEmail').set('value', '');
    	}
    	if ($('captchaCodeSinRegistro')){
    		$('captchaCodeSinRegistro').set('value', '');
    	}
    	
    	

    	
	}


});



var webUser = new Class({
	_id : 0,
	_nick : '',
	_email : '',
	_password : '',
	_urlweb : '',
	
	get: function(data){
		switch (data){
			case 'id':
				return this._id;
				break;
			case 'nick':
				return this._nick;
				break;
			case 'email':
				return this._email;
				break;
			case 'password':
				return this._password;
				break;
			case 'urlweb':
				return this._urlweb;
				break;
		}
	},
	
	set: function(data, value){
		switch (data){
			case 'id':
				
				this._id = value;
				
				break;
			case 'nick':
				this._nick = value;
				break;
			case 'email':
				this._email = value;
				break;
			case 'password':
				this._password = value;
				break;
			case 'urlweb':
				this._urlweb = value;
				break;
		}
	}
	


	
});



window.addEvent('domready', function(){
	//Si no está instanciado en otra parte como noticias protegidas con login...
	$$('.Comentarios').setProperty('class', 'Comentarios');
	new Comments();
	
	//***************************************************************************
	

});

