var Commenter = Class.create({
	loadimg:		'/images/mosca.gif',
	rant_id: 		false,
	comments_div: 	false,
	com_link:		false,
	num_img:		false,
	showing:		false,
	num_comments:	false,
	loadimgel:		false,
	
	
	initialize: function(id){
		this.rant_id = id;
		comments_div = $('comments_'+id+'');
		if(!comments_div) throw("No div comments_"+id);
		this.comments_div = comments_div;
		com_link = $('show_comments_link_'+id);
		if(com_link){
/* 		throw("No link show_comments_"+id); */
			this.com_link = com_link;
			Event.observe(com_link, 'click', blog.toggle_comments.bind(blog, id));
		}else{
			button = $('comments_'+id+'_submit');
			if(!button) throw('No link comments y no submit button WTF?');
			Event.observe(button, 'click', function(ev){
			    this.add_comment();
			    Event.stop(ev);
			    return false;
			}.bind(this));
		}
		this.num_img = $('numcomments_'+id);
		loadimgel = $('loading_img');
		if(!loadimgel){
			preim = new Image();
			preim.src = this.loadimg;
			
			Event.observe(window, 'load', function(){
				loadimgel = new Element('img', {'id': 'loading_img', 'src': this.loadimg, 'style': 'display: none; margin: 5px auto;'});
				document.body.appendChild(loadimgel)
				this.loadimgel = loadimgel;
			}.bind(this));
		}
	},
	
	show_comments: function(){
		if(this.showing) return this.hide_comments();
		this.showing = true;
		this.show_loading();
		url='/phpajax/handler.php?comment='+this.rant_id;
		ajax = new Ajax.Request(
			url,
			{
				onSuccess: this.parse_comments_xml.bind(this)
			}
		);
	},

	hide_comments: function(){
		this.showing = false;
		div = this.comments_div;
		nodes = div.childNodes;
		debug(nodes, true);
		manualremove = true;
		for(i= nodes.length-1; i>= 0; i--){
			debug(nodes[i].nodeName);
			node = nodes[i];
			if(nodes[i].nodeName != '#text'){
				manualremove = false;
				new Effect.DropOut(nodes[i], {
					"afterFinish": function(obj){
						node = obj.element;
						debug('hola '+obj.effects.length);
						node = obj.effects[0].element;
						node.parentNode.removeChild(node);
/* 						console.log(this.loadimg); */
						
						wrapname = this.comments_div.id+'_wrapper';
						$(wrapname).style.display = 'none';
/* 						debug(node.nodeName + ' = ' + node.parentNode); */
/* 						node.parentNode.removeChild(node); */
					}.bind(this),
					'duration': 0.5
				})
/* 				div.removeChild(node); */
			}
		}

		if(manualremove){
			wrapname = this.comments_div.id+'_wrapper';
			$(wrapname).style.display = 'none';
		}
		debug('',true);
		formdiv = $('comments_'+this.rant_id+'_form');
		if(formdiv)
			formdiv.parentNode.removeChild(formdiv);
	},

	add_comment: function(){
		id = this.rant_id;
		text = encodeURIComponent($('textarea_'+id).value);
		user = encodeURIComponent($F('user_'+id));
		if($('mail_'+id))
			mail = encodeURIComponent($F('mail_'+id));
		else
			mail = 'NULL';
		
		if(text.blank()){
			alert("Please write a comment");
			$('textarea_'+id).focus();
			return false;
		}
		if(user.blank()){
			alert("Please write your name");
			$('user_'+id).focus();
			return false;
		}
		this.show_loading();
		$('textarea_'+id).select();
		debug(text, true);
		
		debug(user);
		pars = 'rant='+id+'&user='+user+'&comment='+text+'&email='+mail;
		debug(pars);
		url='/phpajax/handler.php';
		ajax = new Ajax.Request(
			url,
			{
				encoding: 'UTF-8',
				method: 'post',
				parameters: pars,
				onSuccess: function(r){this.parse_comments_xml(r, true).bind(this)}.bind(this)
			}
		);
	},

	show_loading: function(){
		if($(this.loadimgel)){
			try{
				document.body.removeChild(this.loadimgel);
			}catch(e){
			
			}
		}
		this.comments_div.appendChild(this.loadimgel);
		wrapname = this.comments_div.id+'_wrapper';
		$(wrapname).style.display = 'block';
/* 		this.loadimgel.style.display = 'block'; */
		this.loadimgel.style.marginLeft = '20%';
		this.comments_div.style,diplay = 'block';
		new Effect.Appear(this.loadimgel, {'duration': 0.5});
	},
	
	hide_loading: function(){
/* 		this.loadimgel.style.display = 'none'; */
		new Effect.Fade(this.loadimgel, {
			afterFinish: function(){
				if(this.loadimgel.parentNode.nodeName != "BODY"){
					this.comments_div.removeChild(this.loadimgel);
					document.body.appendChild(this.loadimgel);
				}
			}.bind(this)
		})
	},

	parse_comments_xml: function(resp, single_com){
		xmlDoc = resp.responseXML;
		xmlitems = xmlDoc.getElementsByTagName('comment');
		if(!xmlitems || xmlitems.length == 0){
			this.hide_loading();		
			xmlitems = xmlDoc.getElementsByTagName('error');
			if(xmlitems.length > 0){
				debug(xmlitems.length);
				debug(xmlitems[0].nodeName);
				alert("An error Ocurred \n"+ xmlitems[0].childNodes[0].nodeValue);
	
				return false;
			}
		}
		this.hide_loading();
		useritems 	= xmlDoc.getElementsByTagName('user');	
		this.userdata = $H({
			user_name:	false,
			user_id:	false,
			edit_own:	false,
			edit_all:	false
		});
		if(useritems[0]){
		    useritems = useritems[0];
		    this.userdata.set('user_id', useritems.getElementsByTagName('id')[0].childNodes[0].nodeValue);
		    this.userdata.set('user_name', useritems.getElementsByTagName('name')[0].childNodes[0].nodeValue);
		    this.userdata.set('edit_own', useritems.getElementsByTagName('can_edit_own')[0].childNodes[0].nodeValue);
		    this.userdata.set('edit_all', useritems.getElementsByTagName('can_edit_all')[0].childNodes[0].nodeValue);
		}
		for(i =0; i < xmlitems.length; i++){
			try{
				myitem = xmlitems[i];
			}catch(e){
	//			item = xmlDoc.all.tags('comment');
				debug(resp.getAllHeaders());
	//			item = item[i];
			}
			if(myitem.getAttribute('rant_id') != this.rant_id) continue;
			commentdata = {
				i:			i,
				author:		false,
				author_id: 	false,
				author_type:false,
				md5_mail:	false,
				month:		false,
				day:		false,
				extra:		false,
				post:		false		
			}
			
			for(e = 0; e < myitem.childNodes.length; e++){
				thisnode = myitem.childNodes[e];
				switch(thisnode.nodeName){
					case 'author':
	//					author = thisnode.childNodes[0].nodeValue;
						try{
							commentdata.author = thisnode.childNodes[1].nodeValue;
							commentdata.author_type = thisnode.getAttribute('type');
							commentdata.md5_mail = thisnode.getAttribute('md5mail');
							if(!isNaN(thisnode.getAttribute('id')))
								commentdata.author_id = thisnode.getAttribute('id');
						}catch(e){
							commentdata.author = thisnode.childNodes[0].nodeValue;
							commentdata.author_type = thisnode.getAttribute('type');
							commentdata.md5_mail = thisnode.getAttribute('md5mail');
							if(!isNaN(thisnode.getAttribute('id')))
								commentdata.author_id = thisnode.getAttribute('id');
						}
						
					break;
					
					case 'post':
						try{
							commentdata.post = thisnode.childNodes[1].nodeValue;
						}catch(e){						
							commentdata.post = thisnode.childNodes[0].nodeValue;
						}
					break;
	
					case 'date':
						commentdata.month = thisnode.getElementsByTagName('month')[0].childNodes[0].nodeValue;
						commentdata.day = thisnode.getElementsByTagName('day')[0].childNodes[0].nodeValue;
						commentdata.extra = thisnode.getElementsByTagName('extra')[0].childNodes[0].nodeValue;
					break;
				}
			}
/* 			console.log(' will call append_comment'); */
			this.append_comment(commentdata);
		}
		if(!single_com){
			this.append_form();
		}
	},
	
	append_comment: function(data){
		user_data = this.user_data;
		classname = (i%2==0)?'par':'non';
    	div = new Element('div', {'class': 'comment '+classname, 'style': 'display: none'});
    	h2 = new Element('h2', {'class': 'comment_author'});
    	datediv = new Element('div', {'class': 'comment_date'});
    	spmonth = new Element('span', {'class': 'month'});
    	spday = new Element('span', {'class': 'day'});
    	spextra = new Element('span', {'class': 'extra'});
    	p = new Element('p');
    	
    	br = new Element('br', {'style': 'clear: both'});
    	data.author = data.author.strip();
    	authorhtml = "<img src='/images/text.php?txt="+data.author+"&fnt=1&bg=lightgrey' alt='"+data.author+"' />";
    	if(data.author_type == 'user'){
	    	authorhtml = "<a href='/author/"+data.author+"'><img src='/images/"+data.author+".png' alt='"+data.author+"' /></a>";
    	}
    	authorhtml = "<span class='gravatar'><img src='http://www.gravatar.com/avatar.php?gravatar_id="+data.md5_mail+"&size=60'/></span>"+authorhtml+"<br class='cl' />";
    	h2.update(authorhtml);
    	spmonth.update(data.month);
    	spday.update(data.day);
    	spextra.update(data.extra);
    	p.update(data.post);
    	
    	div.appendChild(h2);
    	datediv.appendChild(spmonth);
    	datediv.appendChild(spday);
    	datediv.appendChild(spextra);
    	div.appendChild(datediv);
    	div.appendChild(p);
    	p.appendChild(br);
    	this.comments_div.appendChild(div);
		new Effect.SlideDown(div);
	},
	
	append_form: function(){
		userdata = this.userdata;
		div = new Element('div', {'style': 'display: none', 'class': 'commentsform', 'id': 'comments_'+this.rant_id+'_form'});
		p = new Element('p');
		p.update('&iquest;Tu qu&eacute; piensas?');
		text = new Element('textarea', {'id': 'textarea_'+this.rant_id, 'name': 'Comments'});
		user = new Element('input', {'type': 'text', 'id': 'user_'+this.rant_id, 'name': 'User Name'});
		mail = new Element('input', {'type': 'text', 'id': 'mail_'+this.rant_id, 'name': 'email'});
		button = new Element('input', {'type': 'button', 'value': 'Submit!', 'style':'display: block'});
		Event.observe(button, 'click', function(ev){
		    this.add_comment();
		    Event.stop(ev);
		    return false;
		}.bind(this));
		
		namep = new Element('p').update('Tu nombre <br />');
		mailp = new Element('p').update('Tu correo (puedes dejarlo en blanco) <br />');

		if(userdata.get('user_id')){
		    namep.update("Eres: "+userdata.get("user_name")+" <a href='?logout'>Logout</a>");
		    user.value = userdata.get('user_name');
		    mailp = mail = new Element('span');
		    user.type = 'hidden';
		}else{
/* 			console.log(userdata.get('user_id')); */
		}
		
		div.appendChild(p);
		div.appendChild(text);
		div.appendChild(namep);
		div.appendChild(user);
		div.appendChild(mailp);
		div.appendChild(mail);
		div.appendChild(button);
		div.appendChild(new Element('br', {'style': 'clear: both'}));
		$('comments_'+this.rant_id+'_wrapper').appendChild(div);
		new Effect.Appear(div);
	}

});