var CredibilityVote=Class.create({
  initialize: function(id){
    if(typeof(id)!='object'){
      this.holder=$('alert-'+id);
      this.up=this.holder.down('.cred-up');
      //this.down=this.holder.down('.thumbs-down');
      this.cred_field=this.holder.down('.cred-value');
      //this.cred_field=this.holder.down('strong.credibility-red')||this.holder.down('strong.credibility-green');
      this.alert_id=id;
    }else Object.extend(this,id);

    this.loading_url='/images/loading.gif';
    this.red_class='cred';
    this.green_class='cred-green';

    this.old_tu=this.up.src;
    //this.old_td=this.down.src;

    this.up_obvserver=this.clicked.curry(1).bind(this);
    //this.down_observer=this.clicked.curry(0).bind(this);

    this.up.observe('click',this.up_obvserver);
    //this.down.observe('click',this.down_observer);
  },

  clicked: function(type){
    if(this.requesting)
      return;
    this.requesting=true;

    //this.up.src=this.down.src=this.loading_url;
    new Ajax.Request('/alerts/credibility_vote',{method: 'POST', parameters: {alert_id: this.alert_id, vote: type},onComplete: this.request_finished.bind(this)});
  },

  clear_points: function(){
    this.up.style.display='none';
    //this.up.style.visibility='hidden';
   	//this.down.style.visibility='hidden';
    this.up.stopObserving('click',this.up_obvserver);
    //this.down.stopObserving('click',this.down_observer);
  },

  request_finished: function(transport){
    var res;
    this.requesting=false;
    this.up.src=this.old_tu;
    //this.down.src=this.old_td;

    if(transport.status!=200){
      alert('Request failed: '+transport.status+' '+transport.statusText);
      return;
    }

    if(!(res=transport.responseJSON)){
      alert('Server error');
      return;
    }

    //if(res.force_remove)
    this.clear_points();

    if(res.error){
      alert(res.error);
      return;
    }

    this.request_finished_ui(res.credibility);
  },

  request_finished_ui: function(credibility){
	    this.cred_field.update(credibility);
	    this.cred_field.parentNode.className=((credibility>=50)?this.green_class:this.red_class);
	    $('descred_'+this.alert_id).setStyle('display:none');
	    this.cred_field.highlight();
	    this.clear_points();
  }
});
