var community;
if (!community || typeof community != "object") throw new Error("Не загружен модуль Community");

Community.Survey.Vote = Class.create({
  initialize: function(element,vote,options)
  {
  if (!options) options = {};
  this.hide_title = options.hide_title || false;
  this.can_view_result = options.can_view_result || false;
  this.id = Community.Survey.Vote.id++;
  this.write = options.write || false;
  this.element = element;
  this.vote = vote;
  if (this.write)
  {
    if (!vote) this.write = false;
    else this.init_vote(vote);
    community.init.add(this.init.bind(this));
  }
  else this.init();
  community.init.add_unload(this.clean.bind(this));
  },

  init: function()
  {
  this.element = $(this.element);
  if (!this.element) throw new Error("Отсутствует контейнер для голосования!");
  if (this.vote)
  {
    if (!this.write) this.init_vote(this.vote);
  }
  else
  {
    this.element.update("Идет загрузка...").show();
    new Ajax.Request(community.url.survey_results_ajax,
       {
        parameters: {cmd:"get_vote"},
        onSuccess: this.init_success.bind(this),
        onFailure: community.ajax_failure.bind(community)
       });
  }
  },

  clean: function(element)
  {
  this.element = null;
  },

  init_success: function(transport)
  {
  var response = transport.responseText.split(" ");
  if (response[0] != "OK") { this.element.hide(); return; }
  response.splice(0,1);
  this.init_vote(response.join(" "));
  },

  init_vote: function(results)
  {
   results = $H(results.evalJSON(true));
   if (!Number(results.get("can_answer")))
   {
     new Community.Survey.Vote.Results(this.element,0,results.get("r_survey"),{write:this.write,hide_title:this.hide_title});
   }
   else
   {
    new Community.Survey.Answer(this.element,0,0,results.get("r_survey"),{write:this.write,hide_title:this.hide_title,can_view_result:this.can_view_result});
   }
  }

});

Community.Survey.Vote.id = 0;

//------------------------------------------------------------------------------------------------------------------

Community.Survey.Vote.Results = Class.create({
  initialize: function(element,survey_id,results,options)
  {
   if (!options) options = {};
   this.id = Community.Survey.Vote.Results.id++;
   this.write = options.write || false;
   this.hide_title = options.hide_title || false;
   this.can_answer = options.can_answer || false;
   this.element = element;
   this.survey_id = survey_id;
   if (results)
   {
    if (typeof results == "string") this.results = $H(results.evalJSON(true));
    else this.results = $H(results);
    this.unfilter_results();
   }
   if (this.write)
   {
    if (!this.results) this.write = false;
    else document.write(this.html());
    community.init.add(this.init.bind(this));
   }
   else this.init();
   community.init.add_unload(this.clean.bind(this));
  },

  unfilter_results: function()
  {
   this.results.set("label",community.unfilter_body(this.results.get("label")));
   var issues_length = this.results.get("issues").length;
   for (var issue_index=0;issue_index<issues_length;issue_index++)
   {
    var issue = this.results.get("issues")[issue_index];
    issue.label = community.unfilter_body(issue.label);
    issue.answer = community.unfilter_body(issue.answer);
    var answers_length = issue.answers.length;
    for (var answer_index=0;answer_index<answers_length;answer_index++)
    {
     var answer = issue.answers[answer_index];
     answer.answer = community.unfilter_body(answer.answer);
    }
   }
  },

  init: function()
  {
   this.element = $(this.element);
   if (!this.element) throw new Error("Отсутствует контейнер для результатов голосования!");
   if (!this.results)
   {
    new Ajax.Request(community.url.survey_results_ajax,
       {
        parameters: {cmd:"get_vote_results",survey_id:this.survey_id},
        onSuccess: this.init_success.bind(this),
        onFailure: community.ajax_failure.bind(community)
       });
    this.element.update("Идет загрузка...").show();
   }
   else
   {
    this.display(this.write);
   }
  },

  clean: function(element)
  {
   this.stop();
   this.element = null;
  },

  stop: function()
  {
   var answer_button_element = $(this.answer_button_id());
   if (answer_button_element) answer_button_element.stopObserving("click");
  },

  answer_button_id: function() { return "Community_Survey_Vote_Results_AnswerButton_"+this.id; },

  init_success: function(transport)
  {
   var response = transport.responseText.split(" ");
   if (response[0] != "OK") { alert("Ошибка: "+transport.responseText); return; }
   response.splice(0,1);
   this.results = $H(response.join(" ").evalJSON(true));
   this.unfilter_results();
   this.display();
  },

  display: function(after_write)
  {
   if (!after_write) this.element.update(this.html()).show();
   if (this.can_answer)
   {
     $(this.answer_button_id()).observe("click",this.answer.bind(this));
   }
  },

  html: function()
  {
   var value = '';
   if (this.results.get("label"))
   {
    value += '<i>'+community.filter_body(this.results.get("label"))+'</i><br />';
   }
   var t_this = this;
   $A(this.results.get("issues")).each(function(issue,index)
          {
          value += t_this.issue_html(index);
          });
   value += '<div class="clear mt10">Всего проголосовало: <strong>'+this.results.get("user_count")+'</strong></div>';
   return value;
  },

  issue_html: function(issue_index)
  {
   var value='<div>';
   var answer = community.filter_body(this.results.get("issues")[issue_index].answer);
   var label = community.filter_body(this.results.get("issues")[issue_index].label);
   if (answer || label) value=value+'<p class="mb5 mt5">'+(answer ? answer : label)+'</p>';
   value += '<table>';
   var t_this = this;
   var leaders = $A(this.results.get("issues")[issue_index].leaders);
   $A(this.results.get("issues")[issue_index].answers).each(function(val,index)
    {
      value += t_this.variant_html(issue_index,index,(leaders.indexOf(String(index+1)) != -1));
    });
   value += '</table>';
   if (this.can_answer)
   {
    value += '<a class="button" id="'+this.answer_button_id()+'">ответить</a>';
   }
   value += '</div>';
   return value;
  },

  variant_html: function(issue_index,variant_index,is_leader)
  {
   var value=' ';
   var variant = community.filter_body(this.results.get("issues")[issue_index].answers[variant_index].answer);
   var total = this.results.get("issues")[issue_index].total;
   var cnt = this.results.get("issues")[issue_index].answers[variant_index].cnt;
   if (is_leader) value += '<tr class="VoteMax">';
   else value += '<tr class="Vote">';
   value += '<td>'+variant+'</td><td>';
   if (Number(total)) { var width = Math.round(115*(cnt/total)) || 1; var percent = (100*cnt/total).toFixed(2) }
   else { var width = 1; var percent = 0; }

   if (is_leader)
   {
    value += '&nbsp;<img class="vote" src="/i/comm/skin' + community.prop.skin + '/vote_leader_bg.gif" style="height: 10px; width:'+width+'px;" />';
   }
   else value+='&nbsp;<img class="vote" src="/i/comm/skin1/vote_bg.gif" style="height: 10px; width:'+width+'px;">';
   value+='&nbsp;<strong>'+cnt+'</strong> ('+percent+'%)';
   value=value+'</td></tr>';
   return value;
  },

  answer: function()
  {
    this.stop();
    new Community.Survey.Answer(this.element,this.survey_id,community.prop.user_id,'',{hide_title:this.hide_title,can_view_result:true});
  }
});

Community.Survey.Vote.Results.id = 0;
