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

Community.Survey.Answer = Class.create({
  initialize: function(element,survey_id,author_id,results,options)
  {
  if (!options) options = {};
  this.hide_title = options.hide_title || false;
  this.id = Community.Survey.Answer.id++;
  this.write = options.write || false;
  this.can_view_result = options.can_view_result || false;
  this.element = element;
  this.survey_id = survey_id;
  this.author_id = author_id;

  if (results)
  {
    if (typeof results == "string") this.results = results.evalJSON(true);
    else this.results = results;

    this.survey = new Community.Survey(this.results.survey);
    this.r_survey = $H(this.results.r_survey);
    this.r_survey.set("groups",$H(this.r_survey.get("groups")));
    this.r_survey.set("issues",$H(this.r_survey.get("issues")));
    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.survey.set("title",community.unfilter_body(this.survey.get("title")));
   this.survey.set("label",community.unfilter_body(this.survey.get("label")));
   var groups_length = this.survey.get("groups").length;
   for (var group_index=0;group_index<groups_length;group_index++)
   {
    var group = this.survey.get("groups")[group_index];
    group.set("title",community.unfilter_body(group.get("title")));
    group.set("label",community.unfilter_body(group.get("label")));
    var issues_length = group.get("issues").length;
    for (var issue_index=0;issue_index<issues_length;issue_index++)
    {
     var issue = group.get("issues")[issue_index];
     issue.set("title",community.unfilter_body(issue.get("title")));
     issue.set("comment",community.unfilter_body(issue.get("comment")));
     issue.set("value",community.unfilter_body(issue.get("value")));
     issue.set("label",community.unfilter_body(issue.get("label")));
     issue.set("answer",community.unfilter_body(issue.get("answer")));
     issue.set("default",community.unfilter_body(issue.get("default")));
     var issue_id = issue.get("issue_id");
     var r_issue = this.r_survey.get("issues").get(issue_id);
     if (r_issue) r_issue.result = community.unfilter_body(r_issue.result);
    }
   }
  },

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

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

  stop: function()
  {
  var survey_save_element = $(this.survey_save_button_id());
  if (survey_save_element) survey_save_element.stopObserving("click");
  var survey_result_element = $(this.survey_result_button_id());
  if (survey_result_element) survey_result_element.stopObserving("click");
  var t_this = this;
  this.survey.get("groups").each(function(group,group_index)
    {
      t_this.survey.group_get(group_index,"issues").each(function(issue,issue_index)
      {
       var issue_answer_element = $(t_this.issue_answer_id(group_index,issue_index));
       if (issue_answer_element) issue_answer_element.stopObserving();
       var issue_answer_slist_element = $(t_this.issue_answer_slist_id(group_index,issue_index));
       if (issue_answer_slist_element) issue_answer_slist_element.stopObserving("change");
       var issue_noanswer_element = $(t_this.issue_noanswer_id(group_index,issue_index));
       if (issue_noanswer_element) issue_noanswer_element.stopObserving("click");
      });
    });
  },

  survey_rd_acc_id: function() { return "Community_Survey_Answer_Survey_RdAcc_"+this.id; },
  group_rd_acc_id: function(group_index) { return "Community_Survey_Answer_Group_RdAcc_"+group_index+"_"+this.id; },
  survey_save_button_id: function() { return "Community_Survey_Answer_Save_"+this.id; },
  survey_result_button_id: function() { return "Community_Survey_Answer_Result_"+this.id; },

  issue_answer_id: function(group_index,issue_index) 
  {
  return "Community_Survey_Answer_Answer_"+group_index+"_"+issue_index+"_"+this.id;
  },
  issue_noanswer_id: function(group_index,issue_index) 
  {
  return "Community_Survey_Answer_NoAnswer_"+group_index+"_"+issue_index+"_"+this.id;
  },
  issue_answer_slist_id: function(group_index,issue_index) 
  {
  return "Community_Survey_Answer_SList_"+group_index+"_"+issue_index+"_"+this.id;
  },
  issue_check_id: function(group_index,issue_index) 
  {
  return "Community_Survey_Answer_Check_"+group_index+"_"+issue_index+"_"+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 = response.join(" ").evalJSON(true);
  this.survey = new Community.Survey(this.results.survey);
  this.r_survey = $H(this.results.r_survey);
  this.r_survey.set("groups",$H(this.r_survey.get("groups")));
  this.r_survey.set("issues",$H(this.r_survey.get("issues")));
  this.unfilter_results();
  this.display();
  },

  display: function(after_write)
  {
  if (!after_write)
  {
    this.element.update(this.html()).show();
    if ($(this.survey_rd_acc_id())) makeSelectBox("#"+this.survey_rd_acc_id());
  }
  $(this.survey_save_button_id()).observe("click",this.save.bindAsEventListener(this));
  if (this.can_view_result) {
    $(this.survey_result_button_id()).observe("click",this.result.bindAsEventListener(this));
  }

  var t_this = this;
  this.survey.get("groups").each(function(group,group_index)
    {
      if ($(t_this.group_rd_acc_id(group_index))) makeSelectBox("#"+t_this.group_rd_acc_id(group_index));
      t_this.survey.group_get(group_index,"issues").each(function(issue,issue_index)
      {
        t_this.observe_issue(group_index,issue_index);
      });
    });
  },

  observe_issue: function(group_index,issue_index)
  {
  var html=this.survey.issue_get(group_index,issue_index,"html");
  if (html == "text" || html == "textarea" || html == "select_s")
  {
    $(this.issue_answer_id(group_index,issue_index)).observe("keyup",this.issue_changed.bindAsEventListener(this,group_index,issue_index));
    $(this.issue_answer_id(group_index,issue_index)).observe("change",this.issue_changed.bindAsEventListener(this,group_index,issue_index));

    if (this.survey.issue_get(group_index,issue_index,"check_type") == "date") {
      jQuery('#'+this.issue_answer_id(group_index,issue_index)).datepicker();
    }
  }
  else if (html == "radio" || html == "checkbox")
  {
    $(this.issue_answer_id(group_index,issue_index)).observe("click",this.issue_changed.bindAsEventListener(this,group_index,issue_index));
  }
  else if (html == "select" || html == "select_m")
  {
    $(this.issue_answer_id(group_index,issue_index)).onchange=this.issue_changed.bindAsEventListener(this,group_index,issue_index);
    makeSelectBox('#'+this.issue_answer_id(group_index,issue_index));
  }
  if (html == "select_s")
  {
    $(this.issue_answer_slist_id(group_index,issue_index)).observe("change",this.issue_slist_changed.bindAsEventListener(this,group_index,issue_index));
  }
  if ($(this.issue_noanswer_id(group_index,issue_index)))
  {
    $(this.issue_noanswer_id(group_index,issue_index)).observe("click",this.disable_issue.bindAsEventListener(this,group_index,issue_index));
  }
  },

  issue_changed: function(event,group_index,issue_index)
  {
  var result = community.$RF(this.issue_answer_id(group_index,issue_index));
  if (this.check_issue(this.survey.group_get(group_index,"issues")[issue_index],result))
  {
    $(this.issue_check_id(group_index,issue_index)).hide();
  }
  else
  {
    $(this.issue_check_id(group_index,issue_index)).show();
  }
  },

  check_issue: function(issue,result)
  {
  if (!result) return 1;
  switch(issue.get("check_type"))
  {
    case "email":   return community.re_email.test(result);
    case "url":   return community.re_url.test(result);
    case "date":   return community.is_valid_date(result);
    case "time":   return community.is_valid_time(result);
    case "phone":   return community.re_phone.test(result);
    case "number": return community.re_num.test(result);
    case "fnumber":return community.re_fnum.test(result);
    case "regexp": var re = new RegExp(issue.get("value"));
       return re.test(result);
    default:   return 1;
  }
  return 1;
  },

  issue_slist_changed: function(event,group_index,issue_index)
  {
  var value = community.$RF(this.issue_answer_slist_id(group_index,issue_index));
  if (value != "--другое--")
  {
    $(this.issue_answer_id(group_index,issue_index)).value=value || "";
  }
  },

  disable_issue: function(event,group_index,issue_index)
  {
  $(this.issue_answer_id(group_index,issue_index)).disabled = !($(this.issue_answer_id(group_index,issue_index)).disabled);
  },

  html: function()
  {
  var t_this = this;
  var value='';
  if (this.r_survey.get("survey").can_edit == "1")
  {
    value += '<div class="clear" id="visibleLevelWrap"><label>Могут смотреть:</label><span class="por fl"><select class="selectbox" id="'+this.survey_rd_acc_id()+'">';
    community.acc_title.each(function(pair)
          {
      value += '<option value="'+pair.key+'"';
      if (pair.key == t_this.r_survey.get("survey").rd_acc) value += ' selected="selected"';
      value += '>'+pair.value+'</option>';
          }
         );
    value=value+'</select></span></div><div class="clear"></div>';
  }
  if (!this.hide_title)
  {
    value += '<h3 class="mb30 pt5 mt0">'+community.filter_body(this.survey.get("title"))+'</h3>';
  }

  this.survey.get("groups").each(function(group,index)
          {
          value += t_this.group_html(index);
          });
  value += '<a class="button" id="'+this.survey_save_button_id()+'">отправить</a>';
  if (this.can_view_result) { value += '<a class="button" id="'+this.survey_result_button_id()+'">результаты</a>'; }
  return value;
  },

  group_html: function(group_index)
  {
  var value='<div class="border">';
  if (this.survey.group_get(group_index,"label"))
  {
    value += '<i>'+community.filter_body(this.survey.group_get(group_index,"label"))+'</i><br />';
  }
  var group_id = this.survey.group_get(group_index,"group_id");
   if (this.survey.get("groups").length > 1 &&
      (!(this.r_survey.get("groups").get(group_id)) ||
       this.r_survey.get("groups").get(group_id).can_edit == "1"
      )
     )
  {
    value += 'Могут смотреть: <select id="'+this.group_rd_acc_id(group_index)+'">';
    var t_this = this;
    community.acc_title.each(function(pair)
          {
      value += '<option value="'+pair.key+'"';
      if (t_this.r_survey.get("groups").get(group_id))
      {
        if (pair.key == t_this.r_survey.get("groups").get(group_id).rd_acc)
        {
          value += ' selected="selected"';
        }
      }
      else
      {
        if (pair.key == "all") value += ' selected="selected"';
      }
      value += '>'+pair.value+'</option>';
          }
         );
    value += '</select>';
  }
  var t_this = this;
  this.survey.group_get(group_index,"issues").each(function(issue,index)
          {
          value += t_this.issue_html(group_index,index);
          });
  value += '</div>';
  return value;
  },

  issue_html: function(group_index,issue_index)
  {
  var issue_id = this.survey.issue_get(group_index,issue_index,"issue_id");
  var group_id = this.survey.group_get(group_index,"group_id");
  if (this.r_survey.get("issues").get(issue_id) &&
      (this.r_survey.get("groups").get(group_id).can_change != "1")
     ) return "";

  var label = this.survey.issue_get(group_index,issue_index,"label");
  var comment = this.survey.issue_get(group_index,issue_index,"comment");
  var type=this.survey.issue_get(group_index,issue_index,"type");
  var check_type=this.survey.issue_get(group_index,issue_index,"check_type");
  var width=this.survey.issue_get(group_index,issue_index,"width");
  var height=this.survey.issue_get(group_index,issue_index,"height");
  var issue_value=community.filter_body(this.survey.issue_get(group_index,issue_index,"value"));
  var issue_result;
  var no_answer = 0;
  var required = this.survey.issue_get(group_index,issue_index,"required");
  if (this.r_survey.get("groups").get(this.survey.issue_get(group_index,issue_index,"group_id")) &&
      !this.r_survey.get("issues").get(issue_id) && !required
     ) no_answer=1;
  if (this.r_survey.get("issues").get(issue_id))
  {
    issue_result=community.filter_body(this.r_survey.get("issues").get(issue_id).result);
  }
  issue_default=community.filter_body(this.survey.issue_get(group_index,issue_index,"default"));

  var html=this.survey.issue_get(group_index,issue_index,"html");

  var value = '<div class="mb10">';
  /*if (this.survey.issue_get(group_index,issue_index,"required") == "1")
  {
    value += "(@) ";
  }*/
  if (label) value += '<p class="mb5">'+community.filter_body(label)+'</p>';
  if (comment) value += '<small>'+community.filter_body(comment)+'</small>';
  if (html == "text")
  {
    value += '<form><input class="inp_text" type="text"';
    if (width != "0") value += ' size="'+width+'" ';
    else value += ' size="40"';
    value += 'id="'+this.issue_answer_id(group_index,issue_index)+'"';
    if (issue_result) value += ' value="'+issue_result+'"';
	else if (issue_default) value += ' value="'+issue_default+'"';
    else if (check_type == "time") value += ' value="00:00:00"';
    else if (check_type == "date") value += ' value="'+community.current_date()+'"';
    value += ' />';
    value += '</form><div class="clear"></div>';
  }
  else if (html == "textarea")
  {
    value += '<form style="float:left;width:100%;"><textarea class="inp_text"';
    if (width != 0) value += ' cols="'+width+'"';
    else value += ' cols="40"';
    if (height != 0) value += ' rows="'+height+'"';
    else value += ' rows="5"';
    value += ' id="'+this.issue_answer_id(group_index,issue_index)+'"';
    value=value+'>';
    if (issue_result) value += issue_result.gsub("<br />","&#10;");
    else if (issue_default) value += issue_default.gsub("<br />","&#10;");
    value += '</textarea>';
    value += '</form><div class="clear"></div>';
  }
  else if (html == "checkbox")
  {
    value += '<form><input type="checkbox" value="on" id="'+this.issue_answer_id(group_index,issue_index)+'"';
    if (issue_result == "1") value += ' checked="checked"';
    if (no_answer == 1) value += ' disabled="disabled"';
    value=value+'></input><label>'+issue_value+'</label>';
    if (required == "0")
    {
      value += '<br /><input type="checkbox" id="'+this.issue_noanswer_id(group_index,issue_index)+'"';
      if (no_answer == 1) value += ' checked="checked"';
      value += '></input><label>Нет ответа</label>';
    }
    value += '</form>';
  }
  else if (html == "checkbox_m")
  {
    var list = $A(issue_value.split("<br />"));
    var issue_result_list;
    if (issue_result) issue_result_list = $A(issue_result.split(","));
    else issue_result_list = new Array();
    var put_id = false;
    value += '<form>';
    var t_this = this;
    list.each(function(cur_value,index)
        {
        value += '<input type="checkbox" value="'+(index+1)+'" name="'+t_this.issue_answer_id(group_index,issue_index)+'"';
        if (!put_id)
        {
          value += ' id="'+t_this.issue_answer_id(group_index,issue_index)+'"';
          put_id = true;
        }
        if (issue_result_list.indexOf(String(index+1)) != -1) value += ' checked="checked"';
        value += '></input><label>'+cur_value+'</label><br />';
        });
    value += '</form>';
  }
  else if (html == "radio")
  {
    var list = $A(issue_value.split("<br />"));
    value += '<form><ul>';
    var put_id = false;
    if (required == "0")
    {
      value += '<li><input type="radio" value="0" name="'+this.issue_answer_id(group_index,issue_index)+'" id="'+this.issue_answer_id(group_index,issue_index)+'"';
      if (!issue_result) value += ' checked="checked"';
      value += '></input><label>Нет ответа</label></li>';
      put_id = true;
    }
    var t_this = this;
    list.each(function(cur_value,index)
        {
        value += '<li><input type="radio" value="'+(index+1)+'" name="'+t_this.issue_answer_id(group_index,issue_index)+'"';
        if (!put_id)
        {
          value += ' id="'+t_this.issue_answer_id(group_index,issue_index)+'"';
          put_id = true;
        }
        if (issue_result == (index+1)) value += ' checked="checked"';
        value += '></input><label>'+cur_value+'</label></li>';
        });
    value += '</ul></form>';
  }
  else if (html == "select")
  {
    var list = $A(issue_value.split("<br />"));
    value += '<form class="por"><select id="'+this.issue_answer_id(group_index,issue_index)+'">';
    value += '<option value="0"';
    if (!issue_result) value += ' selected="selected"';
    if (required == "0") value += '>--нет ответа--</option>';
    else value += '>--выберите ответ--</option>';
    list.each(function(cur_value,index)
        {
        value += '<option value="'+(index+1)+'"';
        if (issue_result == (index+1)) value += ' selected="selected"';
        value += '>'+cur_value+'</option>';
        });
    value += '</select></form>';
  }
  else if (html == "select_m")
  {
    var list = $A(issue_value.split("<br />"));
    var issue_result_list;
    if (issue_result) issue_result_list = $A(issue_result.split(","));
    else issue_result_list = new Array();
    value += '<form><select id="'+this.issue_answer_id(group_index,issue_index)+'" multiple="multiple"';
    if (height != 0) ' size="'+height+'"';
    else ' size="5"';
    value += '>';
    list.each(function(cur_value,index)
        {
        value += '<option value="'+(index+1)+'"';
        if (issue_result_list.indexOf(String(index+1)) != -1) value += ' selected="selected"';
        value += '>'+cur_value+'</option>';
        });
    value += '</select></form>';
  }
  else if (html == "select_s")
  {
    var list = $A(issue_value.split("<br />"));
    value += '<form><select id="'+this.issue_answer_slist_id(group_index,issue_index)+'"';
    value += '>';
    var is_other = 1;
    value += '<option value="0"';
    if (!issue_result) { value += ' selected="selected"'; is_other = 0; }
    if (required == "0") value += '>--не выбрано--</option>';
    else value += '>--выберите ответ--</option>';
    list.each(function(cur_value,index)
        {
        if (index == 0) return;
        value += '<option value="'+cur_value+'"';
        if (issue_result == cur_value) { value += ' selected="selected"'; is_other = 0; }
        value += '>'+cur_value+'</option>';
        });
    value=value+'<option value="--другое--"';
    if (is_other == 1) value += ' selected="selected"';
    value += '>--другое--</option>';
    value += '</select><br />';
    value += '<input type="text" size="'+width+'" id="'+this.issue_answer_id(group_index,issue_index)+'"';
    if (issue_result) value += ' value="'+issue_result+'"';
    value += ' /></form>';
  }
  else if (html == "html")
  {
    value += issue_value;
  }
  value += '</div>';
  value += '<div id="'+this.issue_check_id(group_index,issue_index)+'" style="display: none;"><span style="color:red;">Неверное значение!</span></div>';
  return value;
  },

  save: function()
  {
  var is_success = true;
  if ($(this.survey_rd_acc_id())) this.r_survey.get("survey").rd_acc = $F(this.survey_rd_acc_id());
  var t_this = this;
  this.survey.get("groups").each(function(group,group_index)
    {
      var group_id = group.get("group_id");
      t_this.survey.group_get(group_index,"issues").each(function(issue,issue_index)
        {
          var result=community.$RF(t_this.issue_answer_id(group_index,issue_index));
          var issue_id = issue.get("issue_id");
          if (!result && issue.get("required") == "1")
          {
            alert("Не на все обязательные вопросы были даны ответы!");
            is_success = false;
            throw $break;
          }
          if (result && !t_this.check_issue(issue,result))
          {
            alert("Не все ответы являются верными!");
            is_success = false;
            throw $break;
          }
          if (!t_this.r_survey.get("issues").get(issue_id))
          {
            t_this.r_survey.get("issues").set(issue_id,{issue_id:issue_id,result:result});
          }
          else
          {
            t_this.r_survey.get("issues").get(issue_id).result=result;
          }
        });
      if (!is_success) throw $break;
      if (!t_this.r_survey.get("groups").get(group_id))
      {
        var myrd_acc = t_this.r_survey.get("survey").rd_acc;
        if ($(t_this.group_rd_acc_id(group_index)))
        {
          myrd_acc = $F(t_this.group_rd_acc_id(group_index));
        }
        t_this.r_survey.get("groups").set(group_id,{group_id:group_id,rd_acc:myrd_acc});
      }
      else if (t_this.r_survey.get("groups").get(group_id) &&
         $(t_this.group_rd_acc_id(group_index))
        )
      {
        t_this.r_survey.get("groups").get(group_id).rd_acc=$F(t_this.group_rd_acc_id(group_index));
      }
    });

  if (!is_success) return;

  new Ajax.Request(community.url.survey_answer_ajax,
     {
        parameters:{survey_id:this.survey.get("survey_id"),cmd:"save",r_survey_json:this.r_survey.toJSON(),vote:((this.survey.get("type") == "vote" || this.survey.get("type") == "vote_spec") ? 1 : 0),check:community.prop.check},
        onSuccess: this.save_success.bind(this),
        onFailure: community.ajax_failure.bind(community)
     });
  },

  save_success: function(transport)
  {
   var response = transport.responseText.split(" ");
   if (response[0] != "OK") { alert("Ошибка сохранения: "+transport.responseText); return; }

   response.splice(0,1);
   response=response.join(" ");
   this.stop();
   if (this.survey.get("type") == "vote" || this.survey.get("type") == "vote_spec") new Community.Survey.Vote.Results(this.element,0,response,{hide_title:this.hide_title});
   else new Community.Survey.Results(this.element,0,0,response,{hide_title:this.hide_title});
  },

  result: function()
  {
   this.stop();
   if (this.survey.get("type") == "vote" || this.survey.get("type") == "vote_spec") new Community.Survey.Vote.Results(this.element,this.survey.get("survey_id"),'',{hide_title:this.hide_title, can_answer:true});
   else new Community.Survey.Results(this.element,this.survey.get("survey_id"),community.prop.user_id,'',{hide_title:this.hide_title,can_answer:true});
  }

});

Community.Survey.Answer.id = 0;
