var Poll = {
  init: function() {
    $('#poll_submit').click(function () {
      if (Poll.checkForm())
        Poll.commit();
      else
        alert('Пожалуйста, сделайте выбор!');
    });
  },
  checkForm: function () {
    var checked = false;
    $('#poll_form input').each(function () {
      if ($(this).is(':checked')) {
        checked = true;
      }
      if ($(this).attr('type') == 'text' && $(this).val() != '') {
        checked = true;
      }
    });

    return checked;
  },
  commit: function () {
    var json = false;
    $.post("/poll/commit/", $('#poll_form').serialize() , function (response) {
      var response = response.split('|/|');
      var status = response[0];
      var result = response[1];
      if (status == 'success') {
        $('#poll > div > div').html(result);
      } else if (status == 'error') {
        if (result == 'poll_off') {
          alert('Опрос отключен администратором!');
          location.reload(true);
        }
        if (result == 'change_poll') {
          if (confirm('Текущий опрос изменился, обновить страницу?')) {
            location.reload(true);
          }
        }
        if (result == 'change_modify') {
          if (confirm('В текущий опрос были внесены изменения, обновить страницу?')) {
            location.reload(true);
          }
        }
      } else {
        alert('Ошибка на стороне сервера!');
      }
    });
  }
}

$(function () {
  Poll.init();
})
