$(function() {

	$('#hablar').click(comentar);
	$('.stars div').mouseover(function(){
	    idx = $('.stars div').index(this);
	    $('.stars div').slice(0, idx+1).each(function(a){$(this).addClass('star'+$('.stars div').index(this)+'b')});
	    $('.stars div').slice(idx+1, 5).each(function(a){$(this).removeClass('star'+$('.stars div').index(this)+'b')});
	});
	$('.stars').mouseout(function(){
    	$('.stars div').each(function(a){$(this).removeClass('star'+$('.stars div').index(this)+'b')});
	});
	$('.stars div').click(function(){
	    $('.stars div').unbind();
	    $('.stars').unbind();
	    //registrar el voto
	    $.get('ajax/vote', {index:$('.stars div').index(this),image_id:id_image}, function(d){$('.stars').html(d)});
	})

    $("#comentario").countable({
        threshold: .75,
        startOpacity: 0,
        maxLength: 500,
        positiveCopy: " {n}",
        negativeCopy: " -{n}",
        fadeDuration: 100
    });
		  
})

comentar = function(){
	if($('input[name=robot]:checked').val() == 'si' ){
		//mostrando mensaje de que eres un robot!
		$('.roboterror').attr('style','display:show;');
		$('.roboterror').html("si eres un robot, no puedes hacer comentarios!");
	}else if($('#nick').val()==""){
		$('.roboterror').attr('style','display:show;');
		$('.roboterror').html("debes escribir un nick");
	}else if($('#comentario').val()==""){
		$('.roboterror').attr('style','display:show;');
		$('.roboterror').html("debes escribir un comentario");
	}else{
		//esconder mensaje de error
		$('.roboterror').attr('style','display:none;');
		//cargando
		$('#cargando').attr('style','display:show;')
		//dehabilitando boton para evitar sobrecarga
		$('#hablar').attr('disabled','true');
		//enviando ajax
		$.get('ajax/comment', {'id_image':id_image , 'nick':$('#nick').val(), 'comentario':$('#comentario').val()}, comentarBack)
	}
}
comentarBack = function(){
	//hacer que aparezca el post
	$('#trcomentario').after(mostrarComentario($('#nick').val(), $('#comentario').val().replace(/\n/ig,'<br/>')))
	//esconder el cargando
	$('#cargando').attr('style','display:none;')
	//resetear los campos
	$('#nick').val('');
	$('#comentario').val('');
	//habilitar el boton
	$('#hablar').removeAttr('disabled');
}
mostrarComentario = function(nic, com){

ret = '							<tr>'
ret += '								<td class="comentario" colspan="2">';
ret += '									<table width="100%">';
ret += '										<tr>';
ret += '											<td class="marcotags" rowspan="2">&nbsp;</td>';
ret += '											<td style="width:600px;">';
ret += '												<p style="width:600px; word-wrap:break-word;"><b>'+nic+'</b> '+com+'</p>';
ret += '											</td>';
ret += '										</tr>';
ret += '										<tr>';
ret += '											<td class="timeago">hace 2 segundos <td>';
ret += '										</tr>';
ret += '									</table>';
ret += '								</td>';
ret += '							</tr>';
ret += '							<tr>';
ret += '								<td class="hr" colspan="2" align="right">&nbsp;<td>';
ret += '							</tr>';
return ret;
}
