var alreadyThere;
var answerInput;
var answerButton;

var questionId;
var terminationId;
var answersSkip = 0;
var answersPPage = 0;

var answersVoted;

var QUESTION_LOADED = false;

var KEEP_ANSWERS_OPEN = false;
var SHOW_SCREEN_ANSWER = true;

var KEEP_FORMS_ON = false;
var SCREEN_MASK_OPACITY = .93;

var questionPool;

var screenAnswer;
var screenPresent;

var QUESTIONS_CACHE_TRIGGER = 1;
var QUESTIONS_CACHE_SIZE = 200;
var QUESTIONS_CACHE_LOAD_FACTOR = 0.2;

var aMngr;
var qMngr;

var QuestionManager = function() {

  mng = this;
  this.cnt = 0;
  this.activeQuestion;
  this.questions = [];

  this.questionTextElement;
  this.questionChangeBtn;

  this.init = function() {
    logg("QuestionManager.init()");
    this.questionTextElement = $("#q_text");
    this.questionChangeBtn = $("#btn_change");
    this.questionChangeBtn.click(function() {
        qMngr.nextQuestion();
        //restartSubmitTimeout();
        return false;
    });

    mng.initRequestedQuestion();
    qMngr.redrawAddQuestionForm();
  };

  this.activateQuestion = function(question) {
    logg("QuestionManager.activateQuestion(" + question + ")");
    // validate maybe?
    qMngr.questionTextElement.text(question.getFullDescription());
    qMngr.activeQuestion = question;

    // fill the querystring in
    var qs = "#q-" + question.getId();
    if (question.getTermId() > 0) {
      qs = qs + "-" + question.getTermId();
    }

    window.location = qs;

    if (submitTimeoutRunning) {
      aMngr.restartSubmitTimeout();
    } else {
      aMngr.initSaveFormForceTimeout();
    }
  };

  this.getActiveQuestion = function() {
    return this.activeQuestion;
  };

  this.initRequestedQuestion = function() {
    logg("QuestionManager.initRequestedQuestion()");
    var qs = (window.location + "").toString();
    qs = qs.substr(qs.lastIndexOf("#")+1);
    logg("query string: " + qs);

    var qs_bits = qs.split("-");
    if (qs_bits[0] == "q") {

      // id of the question
      if (qs_bits.length < 2 || isNaN(parseInt(qs_bits[1])) || parseInt(qs_bits[1]) < 1) {
        logg("malformed URL");
        window.location = "#";
        return;
      }
      var id = parseInt(qs_bits[1]);
      termId = 0;
      if (qs_bits.length > 2) { // complex question
        termId = parseInt(qs_bits[2]);
      }

      // load question
      qMngr.loadQuestion(id, termId);
    } else {
      /*// no question requested, so add params of existing to the URL
      var qs = "#q-" + questionId;
      if (terminationId > 0) {
        qs += "-" + terminationId;
      }

      window.location = qs;*/
      // no question requested, so load a random one

      qMngr.loadQuestion();
    }
  };

  this.loadQuestion = function (id, termId) {
    logg("QuestionManager.loadQuestion(" + id + ", " + termId + ")");

    this.cnt = this.cnt + 1;

    var postData = "";
    if (!isNaN(id) && parseInt(id) > 0) {
      postData = "question_id=" + parseInt(id);
      if (!isNaN(termId) && parseInt(termId) > 0) {
        postData += "&termination_id=" + parseInt(termId);
      }
    }

    led.on();
    var requestUrl = CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "question_load";

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "json",
      success: function(response) {
        led.off();
        if (response.status) {
          if (parseInt(response.question.id) == 0) {
            return;
          }
          aMngr.cleanAnswerTextField();
          qMngr.activateQuestion(new Question(response.question.id,
              response.question.desc, response.question.termination_id, ""));

          initAfterQuestionLoaded();

          //answerList();
          aMngr.list(mng.getActiveQuestion());

          aMngr.focusOnAnswerTextField();

          updateQuestionRating(response.question.rating);

          flushAnswersBeingVoted();
        } else {
          messageError(response.msg_text);
        }


      },
      error: function(request, error) {
        led.off();
        messageError("Something went terribly wrong");
      }
    });
  };

  this.loadQuestions = function() {
    logg("QuestionManager.loadQuestions()");

    led.on();
    var postData = "amount=" + QUESTIONS_CACHE_SIZE;
    var requestUrl = CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "questions_load";

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "json",
      success: function(response) {
        led.off();
        if (response.status) {
          for (var i = 0; i < response.questions.length; i++) {
            var q = new Question(
                response.questions[i].id,
                response.questions[i].desc,
                response.questions[i].termId,
                response.questions[i].term);
            qMngr.questions.unshift(q);
          }
        } else {
          //messageError(response.msg_text);
        }


      },
      error: function(request, error) {
        led.off();
        //messageError("Something went terribly wrong");
      }
    });
  };

  this.nextQuestion = function() {
    logg("QuestionManager.nextQuestion()");

    logg("questions length: " + qMngr.questions.length + ", trigger: "
        + Math.floor(QUESTIONS_CACHE_SIZE*QUESTIONS_CACHE_LOAD_FACTOR));

    //logg("list: ");
    //for (var i = 0; i < qMngr.questions.length; i++) {
    //  logg("---" + qMngr.questions[i]);
    //}

    if (qMngr.cnt > QUESTIONS_CACHE_TRIGGER && (qMngr.questions.length < 1
        || qMngr.questions.length < Math.floor(QUESTIONS_CACHE_SIZE*QUESTIONS_CACHE_LOAD_FACTOR))) {
      qMngr.loadQuestions();
    }

    if (qMngr.questions.length > 0) {
      qMngr.activateQuestion(this.questions.pop());
      aMngr.list(qMngr.getActiveQuestion());
    } else {
      qMngr.loadQuestion();
    }
  };

  this.redrawAddQuestionForm = function() {
    if (LOGD == false) {
      $("#add_question_wrap").addClass("register");
      $("#btn_add").mouseover(function() {
        var btn = $(this);
        $("#tooltip_body").find("p").html($("#message_register_to_add").val());
        //alert(btn.offset().right);
        $("#tooltip").addClass("flip").css({
          left: btn.offset().left-181 + "px",
          //right: ($(document).width()-btn.offset().left)+ 50 + "px",
          top: btn.offset().top-$("#tooltip").height()-15 + "px"
        }).show();
      }).mouseout(function() {
        $("#tooltip").removeClass("flip").hide();
      });
    } else {
      $("#btn_add").unbind("mouseover").unbind("mouseout");
      $("#add_question_wrap").removeClass("register");
    }
  };
};

var Question = function(id, description, termId, termDescription) {

  this.rating = 0;
  this.id = parseInt(id);
  this.description = description;
  this.termId = parseInt(termId);
  this.termDescription = termDescription;

  this.getId = function() {
    return this.id;
  }

  this.getTermId = function() {
    return this.termId;
  }

  this.getFullDescription = function() {
    return (termId > 0
      ? this.description + " " + this.termDescription
      : this.description + "").trim();
  }

  this.getRating = function() {
    return this.rating;
  }
}

Question.prototype.toString = function() {
  return "([" + this.id + ", " + this.termId + "] " + this.getFullDescription() + ")";
}

/* event section */

$(document).ready(function() {

  CONTEXT_PATH = $("#context_path_value").val();

  initElements();
  initValues();

  initGlobalClick();

  aMngr = new AnswerManager();
  aMngr.init();
  qMngr = new QuestionManager();
  qMngr.init();

  //initLoadQuestionBtn();
  initAddQuestionForm();

  initAlreadyThereBtn();

  //initAnswerSaveBtn();
  //initAnswerList();
  //initAnswerRatingSort();

  initQuestionRating();

  preloadLightImages();

  initScreenAnswer();
  initScreenPresent();

  userOptions = new UserOptions();
  userOptions.init();


  $("#a_timeout").mouseover(function() {
    if (submitTimeoutRunning == false) {
      return;
    }
    var btn = $(this);
    $("#tooltip_body").find("p").html($("#message_submit_timeout").val());
    $("#tooltip").addClass("flip").css({
      left: btn.offset().left-354 + "px",
      top: btn.offset().top-$("#tooltip").height()-4 + "px"
    }).show();
  }).mouseout(function() {
    $("#tooltip").removeClass("flip").hide();
  });

  //initRequestedQuestion();

  if ($.cookie("idh_sa_dont") != null
      && parseInt($.cookie("idh_sa_dont")) > 0) {
    SHOW_SCREEN_ANSWER = false;
  }

  if ($.cookie("idh_answers") != null
      && parseInt($.cookie("idh_answers")) > 0) {
    showAlreadyThere();
  }

});

var preloadLightImages = function() {
  var images = new Array(
    CONTEXT_PATH + "static/img/answer_submit_ac.png",
    CONTEXT_PATH + "static/img/answer_submit_hl.png",
    CONTEXT_PATH + "static/img/btn_q_add_ac.png",
    CONTEXT_PATH + "static/img/btn_q_add_hl.png",
    CONTEXT_PATH + "static/img/btn_q_change_ac.png",
    CONTEXT_PATH + "static/img/btn_q_change_hl.png",
    CONTEXT_PATH + "static/img/light_a_rate_down_ac.png",
    CONTEXT_PATH + "static/img/light_a_rate_down_hl.png",
    CONTEXT_PATH + "static/img/light_a_rate_up_ac.png",
    CONTEXT_PATH + "static/img/light_a_rate_up_hl.png",
    CONTEXT_PATH + "static/img/light_pgn_next_ac.png",
    CONTEXT_PATH + "static/img/light_pgn_next_hl.png",
    CONTEXT_PATH + "static/img/light_pgn_prev_ac.png",
    CONTEXT_PATH + "static/img/light_pgn_prev_hl.png",
    CONTEXT_PATH + "static/img/light_rating_star_hl.png",
    CONTEXT_PATH + "static/img/light_rating_bg_hl.png",
    CONTEXT_PATH + "static/img/light_wordwar_plus_hl.png"
  );

  $.preloadImages(images);
}

/* init section */

var initElements = function() {
  alreadyThere = $("#solutions_wrap");
  answerButton = $("#a_submit");
  answerInput = $("#a_input");

  answerInput.val("").focus();
  showAlreadyThere();
  //alreadyThere.hide(0, function() { $(this).css("display", "block") });

  if (LOGD) {
    $("#btn_password_change").show();
  }
}

var initValues = function() {
  questionId = parseInt($("#q_id").val());
  terminationId = parseInt($("#q_t_id").val());

  answersPPage = parseInt($("#answers_per_page").val());


  answersVoted = new Array();

  if ($.cookie("idh_l_av") != null) {
    answersVoted = $.cookie("idh_l_av").split("_");
  }
}

var initGlobalClick = function() {
  $("#body_light").click(function() {
    if (KEEP_FORMS_ON == false) {
      escapePressed();
      answerInput.focus();
    }
  });

  $("#form_register")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#form_login")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#form_forgot")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#form_password_change")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#add_question_wrap")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#change_pass_wrap")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#screen_answer,#screen_present")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#a_comment")
    .mouseover(function() { KEEP_FORMS_ON = true })
    .mouseout(function() { KEEP_FORMS_ON = false });

  $("#sol_list")
    .mouseenter(function() { KEEP_FORMS_ON = true })
    .mouseleave(function() { KEEP_FORMS_ON = false });

}

var initScreenAnswer = function() {
  screenAnswer = $("#screen_answer");
  screenAnswer.find(".screen_mask").fadeTo(1, SCREEN_MASK_OPACITY);
  screenAnswer.find("#sa_close").click(function() {
    hideScreenAnswer();
    answerInput.val("");
  });

  screenAnswer.find("#sa_change").click(function() {
    hideScreenAnswer();
    qMngr.nextQuestion();
    //questionLoad();
  });

  screenAnswer.find("#sa_hardcore").click(function() {
    window.location = "http://wordwar.ru" + CONTEXT_PATH + "ultrahyper";
  });

  screenAnswer.find("#sa_quit").click(function() {
    // whoopsie, quick and dirty
    var quitsies = new Array(
      "http://www.ljubo.ru/",
      "http://www.vioo.ru/",
      "http://ideasthatrock.ru/404",
      "http://oos.moxiecode.com/examples/reflex/");
    var rand = Math.floor(Math.random() * quitsies.length);
    window.location.replace(quitsies[rand]);
  });

  screenAnswer.find("#sa_dont").click(function() {
    if ($(this).attr("checked") == true) {
      if (LOGD) {
        userOptions.show_screen = false;
        userOptions.save();
      }
      $.cookie("idh_sa_dont", 1, { expires:20 }); // 20 days
      SHOW_SCREEN_ANSWER = false;
    }
  });
}

var initScreenPresent = function() {
  screenPresent = $("#screen_present");
  screenPresent.find(".screen_mask").fadeTo(1, SCREEN_MASK_OPACITY);
  screenPresent.find("#sp_close").click(function() {
    hideScreenPresent();
    answerInput.val("");
  });
}

var initAlreadyThereBtn = function() {
  $("#btn_already_there").click(toggleAlreadyThere);
}

var initAnswerSaveBtn = function() {
  //answerButton.click(answerSend);
  $("#a_form").submit(function() {
    answerSend();
    return false;
  });
};

var initAfterQuestionLoaded = function() {
  if (QUESTION_LOADED) { return; }

  $("#q_text").removeClass("loading");
  $("#solutions_hide").css("display", "block");
  $("#a_form").css("display", "block");
  $("#q_rating_wrap").css("display", "block");

  QUESTION_LOADED = true;
}

var initPgnPrevBtn = function() {
  $("#sol_pgn>.prev").unbind("click").click(function() {
    answerList(answersSkip+answersPPage);
  });
}

var initPgnNextBtn = function() {
  $("#sol_pgn>.next").unbind("click").click(function() {
    answerList((answersSkip-answersPPage) > 0 ? answersSkip-answersPPage : 0);
  });
}

var initQuestionRating = function() {

  redrawQuestionRating();

  if (LOGD) {

    $("#q_rating_wrap").removeClass("off").unbind("mouseover").unbind("mouseout");

    $("#q_rating_wrap>img")
    .mouseover(function() {
      var star = $(this);
      var id = star.attr("id").split("_")[1];
      $("#q_rating_wrap>img").attr("src", CONTEXT_PATH + "static/img/light_rating_star.png");
      for (var i = 0; i <= id; i++) {
        $("#qr_" + i).attr("src", CONTEXT_PATH + "static/img/light_rating_star_hl.png");
      }
    })
    .mouseout(function() {
      $("#q_rating_wrap>img").each(function() {
        var starr = $(this);
        if (starr.hasClass("hl")) {
          starr.attr("src", CONTEXT_PATH + "static/img/light_rating_star_hl.png");
        } else {
          starr.attr("src", CONTEXT_PATH + "static/img/light_rating_star.png");
        }
      });
     })
    .click(function() {
      questionRate(parseInt($(this).attr("id").split("_")[1])+1);
    });

  } else {
    $("#q_rating_wrap").mouseover(function() {
      var qWrap = $(this);
      $("#tooltip_body").find("p").html($("#message_register_vote_q").val());
      $("#tooltip").css({
        left: qWrap.offset().left+41 + "px",
        top: qWrap.offset().top-$("#tooltip").height()+4 + "px"
      }).show();
    }).mouseout(function() {
      $("#tooltip").hide();
    });
  }
}

var initAddQuestionForm = function() {
  logg("initAddQuestionForm");

  initAddQuestionBtn();
  var addQuWrap = $("#add_question_wrap");

  addQuWrap.css({opacity: 0, display: "none"});
  //addQuWrap.css({opacity: 1, display: "block"});

  $("#btn_add").click(function() {
    if (addQuWrap.hasClass("register")) {
      return;
    }
    if (addQuWrap.css("display") == "block") { // hide
      addQuWrap.css("opacity", 0);
      addQuWrap.css("display", "none");
    } else { // show
      KEEP_FORMS_ON = true
      addQuWrap.css("opacity", 1);
      addQuWrap.css("display", "block");
    }
    $("#add_question").val("");
  });
}

var initAddQuestionBtn = function () {

  $("#add_question_form").submit(function() {

    var q = $("#add_question").val();
    saveQuestion(q);

    return false;

  });
}

/* data consistency section */

var updateQuestionId = function(id, termination_id) {
  questionId = parseInt(id);
  $("#q_id").val(questionId);

  termination_id = parseInt(termination_id);

  terminationId = termination_id > 0
    ? termination_id
    : 0;

  $("#q_t_id").val(termination_id);

  var qs = "#q-" + questionId;
  if (terminationId > 0) {
    qs += "-" + terminationId;
  }

  window.location = qs;
}

var updateAnswersSkip = function(skip) {
  answersSkip = parseInt(skip);
  $("#answers_skip").val(answersSkip);
}

var updateAnswersVoted = function(id, rating) {
  //answersVoted.push(id);
  //$.cookie("idh_l_av", answersVoted.join("_"), { expires: 120 });
}

/* functional section */

var showScreenAnswer = function() {
  if (LOGD && userOptions.show_screen == false
      || !LOGD && SHOW_SCREEN_ANSWER == false) {
    answerInput.val("");
    return;
  }
  //screenAnswer.css("display", "block").fadeTo(
  screenAnswer.show();
}

var hideScreenAnswer = function() {
  screenAnswer.hide();
}

var showScreenPresent = function() {
  screenPresent.show();
}

var hideScreenPresent = function() {
  screenPresent.hide();
}


var toggleAlreadyThere = function() {
  alreadyThere.slideToggle(100, function() {
    var list = $(this);
    if (list.css("display") == "none") {
      $("#sort_chooser").css("display", "none");
      $.cookie("idh_answers", "0", { expires: 120});
    } else {
      $("#sort_chooser").css("display", "block");
      $.cookie("idh_answers", "1", { expires: 120});
    }
  });
}

var showAlreadyThere = function() {
  $.cookie("idh_answers", "1", { expires: 120});
  $("#sort_chooser").css("display", "block");
  alreadyThere.stop(true,true).slideDown(100);
}

var hideAlreadyThere = function() {
  $.cookie("idh_answers", "0", { expires: 120});
  $("#sort_chooser").css("display", "none");
  alreadyThere.stop(true,true).slideUp(100);
}

var updateQuestionText = function(desc) {
  $("#q_text").text(desc);
}

var updateQuestionRating = function(rating) {
  logg("updateQuestionRating(" + rating + ")");
  $("#q_rating_wrap").removeClass("rated").find("img").removeClass("hl");
  for (var i = 0; i < rating; i++) {
    $("#qr_" + i).addClass("hl");
  }

  redrawQuestionRating();
}

var redrawQuestionRating = function() {
  $("#q_rating_wrap").find("img")
  .each(function() {
    var starr = $(this);
    if (starr.hasClass("hl")) {
      starr.attr("src", CONTEXT_PATH + "static/img/light_rating_star_hl.png");
    }

  })
  /*.mouseover(function() {
    var star = $(this);
    var id = star.attr("id").split("_")[1];
    $("#q_rating_wrap>img").attr("src", CONTEXT_PATH + "static/img/light_rating_star.png");
    for (var i = 0; i <= id; i++) {
      $("#qr_" + i).attr("src", CONTEXT_PATH + "static/img/light_rating_star_hl.png");
    }
  })*/;
}

var updateAnswerList = function(answers_html) {
  logg("updateAnswerList");
  $("#answers").replaceWith(answers_html);
}

var showPgnPrevBtn = function() {
  $("#sol_pgn>.prev").show();
}

var hidePgnPrevBtn = function() {
  logg("hidePgnPrevBtn");
  $("#sol_pgn>.prev").hide();
}

var showPgnNextBtn = function() {
  logg("showPgnPrevBtn");
  $("#sol_pgn>.next").show();
}

var hidePgnNextBtn = function() {
  $("#sol_pgn>.next").hide();
}

var hideAddQuestionForm = function() {
  $("#add_question_wrap").hide();
}

var escapePressed = function() {
  hideLoginForm();
  hideForgotForm();
  hideRegisterForm();
  hidePasswordChangeForm();

  hideAddQuestionForm();

  hideScreenAnswer();
  hideScreenPresent();

  if (SPACEY) {
    revertAllAnswerSpaceys();
  }
}

var loginOkay = function(response) {
  logg("loginOkay()");

  $("#logd_id").val(response.user.id);

  var logoutBtnWrap = addLogoutBtn(response.user.username);

  $("#form_login").remove();
  $("#form_register").remove();
  $("#form_forgot").remove();

  $("#login_register_wrap").empty();

  //var profileBtn = $(document.createElement("a"));
  //profileBtn.text($("#label_profile").val());
  //profileBtn.attr("href", CONTEXT_PATH + "users/" + response.user.username);
  //$("#login_register_wrap").append(profileBtn);
  //$("#login_register_wrap").append($(document.createElement("br")));

  $("#login_register_wrap").append(logoutBtnWrap);

  $("#btn_password_change").show();


  LOGD = true;

  //answerList();
  initQuestionRating();
  //answerInput.focus();
  aMngr.list(qMngr.getActiveQuestion());
  qMngr.redrawAddQuestionForm();
  aMngr.initSaveFormForceTimeout();
}

/* data access section */

var questionLoad = function(reqQuestionId, reqTerminationId) {

  logg("questionLoad(" + reqQuestionId + ", " + reqTerminationId + ")");

  var postData = "";
  if (!isNaN(reqQuestionId) && parseInt(reqQuestionId) > 0) {
    postData = "question_id=" + parseInt(reqQuestionId);
    if (!isNaN(reqTerminationId) && parseInt(reqTerminationId) > 0) {
      postData += "&termination_id=" + parseInt(reqTerminationId);
    }
  }

    //"question_id=" + questionId +
    //"termination_id=" + terminationId;

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "question_load",
    data: postData,
    dataType: "json",
    success: function(response) {

      led.off();

      if (response.status) {

        //hideAlreadyThere();

        // clean up answer

        if (parseInt(response.question.id) == 0) {
          // quesiton with requested ID not found
          return;
        }

        answerInput.val("");

        // update question

        updateQuestionText(response.question.desc);
        updateQuestionId(response.question.id, response.question.termination_id);

        initAfterQuestionLoaded();

        answerList();

        answerInput.focus();

        updateQuestionRating(response.question.rating);

        flushAnswersBeingVoted();
      } else {
        messageError(response.msg_text);
      }


    },
    error: function(request, error) {

      led.off();

      messageError("Something went terribly wrong");
    }
  });

  return false;
}

var questionRate = function(rate) {

  logg("questionRate(" + rate + ")");

  var postData =
    "question_id=" + qMngr.getActiveQuestion().getId() +
    "&rate=" + rate;

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "question_rate",
    data: postData,
    dataType: "json",
    success: function(response) {

      led.off();

      if (response.status) {

        updateQuestionRating(rate);
        answerInput.focus();

        $("#q_rating_wrap").addClass("rated")

      } else {
        messageError(response.msg_text);
      }


    },
    error: function(request, error) {

      led.off();

      messageError("Something went terribly wrong");
    }
  });

  return false;
}

var saveQuestion = function(text, replace_id) {

  logg("save question: " + text);

  var postData =
    "q=" + encodeURIComponent(text);

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/question_add",
    dataType: "json",
    data: postData,
    success: function(response) {

      led.off();

      if (response.status == true) {

        messageOkay(response.msg_text);
        logg("added question: " + response.q_id);

        // put up the new quesiton

        updateQuestionText($("#add_question").val());
        updateQuestionId(response.q_id);
        answerList();

        // clean up & change ids:

        $("#add_question_wrap").hide(); // add question from
        $("#add_question").val("");

      } else {
        messageError(response.msg_text);
      }
    }
  });
}

var answerList = function(skip) {

  logg("answerList(" + skip + ")");

  if (!skip) {
    skip = 0;
  }

  if (!orderAnswers) {
    sorting = "rand";
  } else {
    sorting = orderAnswers;
  }

  if (!orderOrder) {
    order = "desc";
  } else {
    order = orderOrder;
  }

  var postData =
    "question_id=" + questionId +
    "&termination_id=" + terminationId +
    "&skip=" + skip +
    "&sorting=" + sorting +
    "&order=" + order;

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_list",
    data: postData,
    dataType: "html",
    success: function(response) {

      led.off();

      //if (response.status) {

        updateAnswerList(response);
        initAnswerList();

      //} else {
      //  messageError(response.msg_text);
      //}



    },
    error: function(request, error) {

      led.off();

      messageError("Something went terribly wrong");
    }
  });

}

var answerSend = function() {

  // ajax call

  var answer = answerInput.val();
  var postData =
    "answer=" + encodeURIComponent(answer) +
    "&question_id=" + questionId +
    "&termination_id=" + terminationId +
    "&user_id=" + 0;

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_save",
    data: postData,
    dataType: "json",
    success: function(response) {

      led.off();

      if (response.status) {
        messageOkay(response.msg_text);

        if (response.answer_present) {
          showScreenPresent();
        } else {
          showScreenAnswer();
        }

        // refresh answers
        answerList();

      } else {
        messageError(response.msg_text);
      }


    },
    error: function(request, error) {

      led.off();

      messageError("Something went terribly wrong");
    }
  });

  return false;
}

var answerRate = function(id, rate) {

  if (answerBeingVoted(id) != false) {
    return;
  }

  setAnswerBeingVoted(id);

  if (!rate) {
    rate = 1;
  }

  var postData =
    "answer_id=" + id +
    "&rate=" + rate;

  led.on();

  $.ajax({
    type: "POST",
    url: CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_rate",
    data: postData,
    dataType: "json",

    success: function(response) {

      led.off();

      if (response.status) {

        // update answer's rating

        var ratingEl = $("#a_" + id + ">p").eq(0).find("span").eq(0);

        ratingEl.text(parseInt(response.answer.rating));

        var rateUpBtn = $("#a_" + id).find("b");
        var rateDnBtn = $("#a_" + id).find("i");

        if (rate > 0) {
          if (rateDnBtn.hasClass("rated")) { // was -1, became 0
            rateDnBtn.removeClass("rated");
            initAnswerRateDownBtn(rateDnBtn);
          } else { // was 0, became 1
            rateUpBtn.unbind("click");
            rateUpBtn.addClass("rated");
          }
        } else {
          if (rateUpBtn.hasClass("rated")) { // was 1, became 0
            rateUpBtn.removeClass("rated");
            initAnswerRateUpBtn(rateUpBtn);
          } else { // was 0, became -1
            rateDnBtn.unbind("click");
            rateDnBtn.addClass("rated");
          }
        }

        removeAnswerBeingVoted(id);

//        if (rate > 0) {
//          initAnswerRateUpBtn($("#a_" + id).find("b").addClass("rated"));
//          $("#a_" + id).find("i").removeClass("rated")/*.unbind("click")*/;
//        } else if (rate < 0) {
//          initAnswerRateDownBtn($("#a_" + id).find("i").addClass("rated"));
//          $("#a_" + id).find("b").removeClass("rated");
//        }

      } else {
        messageError(response.msg_text);
      }
    },

    error: function(request, error) {

      led.off();

      messageError("Something went terribly wrong");
    }
  });

}


