var LIGHT_SECTION_PATH = "light/";
var orderAnswers = "date";
var orderQuestions = "date";
var orderOrder = "desc";
var userOptions;

var submitTimeout = 20;
var origSubmitTimeout = 20;
var submitTimeoutRunning = false;

$(document).ready(function() {
  var ati = $("#answer_timeout");
  if (ati.is("input")) {
    submitTimeout = origSubmitTimeout = parseInt(ati.val());
  }
});

var answersBeingVoted = [];

var AnswerListOrder = {
  DATE: "date",
  RATING: "rating",
  RANDOM: "rand",
  SHORT: "short",
};

var AnswerListOrderDir = {
  DESC: "desc",
  ASC: "asc"
};

var runSubmitTimeout = function() {
  aMngr.runSubmitTimeout();
}

document.onkeydown = function(e) {

  var code = -1;

  try {
    code = e.which;
  } catch (e) {
    if (e.keyCode) {
      code = e.keyCode;
    } else if (window.event.keyCode) {
      code = window.event.keyCode;
    }
  }

  if (code == KBD.ESC) {
    escapePressed();
  }
}

var UserOptions = function() {

  this.show_screen = false;
  this.accept_mail = false;
  this.get_max = false;

  this.init = function() {
    var s = $("#uo_screen");
    if (s.is("input")) this.show_screen = Boolean(parseInt(s.val()));
    s = $("#uo_accept");
    if (s.is("input")) this.accept_mail = Boolean(parseInt(s.val()));
    s = $("#uo_max");
    if (s.is("input")) this.get_max = Boolean(parseInt(s.val()));

    var o = $("#options");
    if (o.is("div")) {
      o.find("#chk_show_screen").attr("checked", userOptions.show_screen)
        .click(function() {
          userOptions.show_screen = true;
          userOptions.save();
        });
      o.find("#chk_accept_mail").attr("checked", userOptions.accept_mail)
        .click(function() {
          userOptions.accept_mail = true;
          userOptions.save();
        });
      o.find("#chk_get_max").attr("checked", userOptions.get_max)
        .click(function() {
          userOptions.get_max = true;
          userOptions.save();
        });
    }
  }

  this.save = function() {
    var postData =
      "uo_screen=" + (userOptions.show_screen?"1":"0") +
      "&uo_accept=" + (userOptions.accept_mail?"1":"0") +
      "&uo_get_max=" + (userOptions.get_max?"1":"0");
    var requestUrl = CONTEXT_PATH + "x/" + "options_save";

    led.on();

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "json",
      success: function(response) {
        led.off();
        if (response.status) {
          messageOkay(response.msg_text, false);
        } else {
        }
      },
      error: function(request, error) {

        led.off();

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

var AnswerManager = function() {

  mng = this;

  this.skip = 0;
  this.orderBy = AnswerListOrder.DATE;
  this.orderByDir = AnswerListOrderDir.DESC;

  this.answersWrap;
  this.answerTextField;
  this.answerSubmitButton;

  // initialization methods

  this.init = function() {
    logg("AnswerManager.init()");

    this.answerTextField = $("#a_input");
    this.answerSubmitButton = $("#a_submit");
    this.answersWrap = $("#sol_list");

    aMngr.cleanAnswerTextField();
    aMngr.initAnswerSortBtns();
    aMngr.initSaveBtn();

//    this.answerTextField.focus(function() {
//      $("#answer_label").fadeTo(300, .2);
//    }).blur(function() {
//      $("#answer_label").fadeTo(300, 1);
//    });
  };

  this.initAnswerList = function() {
    logg("AnswerManager.initAnswerList()");

    this.skip = parseInt($("#answers_skip").val());
    aMngr.initPgnPrevBtn();
    aMngr.initPgnNextBtn();

    if (parseInt($("#answers_real").val()) <= answersPPage) {
      aMngr.hidePgnPrevBtn();
    } else {
      aMngr.showPgnPrevBtn();
    }

    if (this.skip > 0) {
      aMngr.showPgnNextBtn();
    } else {
      aMngr.hidePgnNextBtn();
    }

    this.initAnswersRating();
    this.initAnswerAuthors();
    this.showRatingBtns();

    if (SPACEY) {
      initAnswerEditBtns();
      initAnswerRemoveBtns();
      initAnswerSpaceyForms();
    }
  };

  this.initAnswerSortBtns = function() {
    logg("AnswerManager.initAnswerSortBtns()");

    $("#sort_chooser").find("span").click(function() {
      $("#sort_chooser").find("span.slct").removeClass("slct");
      var span = $(this);
      var currentSortMethod = aMngr.orderBy;
      var orderBtnVal = span.attr("id").split("_")[2]; // btn_sort_%METHOD%

      switch (orderBtnVal) {
        case "rand":
          aMngr.orderBy = AnswerListOrder.RANDOM;
          break;
        case "rating":
          aMngr.orderBy = AnswerListOrder.RATING;
          break;
        case "date":
        default:
          aMngr.orderBy = AnswerListOrder.DATE;
      }

      if (currentSortMethod == aMngr.orderBy) {
        if (aMngr.orderByDir == AnswerListOrderDir.DESC) {
          aMngr.orderByDir = AnswerListOrderDir.ASC;
        } else {
          aMngr.orderByDir = AnswerListOrderDir.DESC;
        }
      } else {
        aMngr.orderByDir = AnswerListOrderDir.DESC;
      }
      aMngr.skip = 0;
      aMngr.list(qMngr.getActiveQuestion());
      span.addClass("slct");
    });
  };

  this.initPgnPrevBtn = function() {
    $("#sol_pgn>.prev").unbind("click").click(function() {
      aMngr.skip = aMngr.skip+answersPPage;
      aMngr.list(qMngr.getActiveQuestion());
    });
  };

  this.initPgnNextBtn = function() {
    $("#sol_pgn>.next").unbind("click").click(function() {
      aMngr.skip = (aMngr.skip-answersPPage) > 0 ? aMngr.skip-answersPPage : 0;
      aMngr.list(qMngr.getActiveQuestion());
    });
  };

  this.initAnswersRating = function() {
    logg("AnswerManager.initAnswersRating()");

    this.answersWrap.find("#answers").eq(0).find("b")
      .each(function() {
        var btn = $(this);
        // add tooltip if not logged in
        if (LOGD != true) {
          //btn.hide();
          btn.addClass("alwoff");
          aMngr.initRegistrationTooltip(btn);
          return;
        }
        // don't init button for own answers
        if (SPACEY != true && parseInt(btn.parent().find(".a_a").val())
            == parseInt($("#logd_id").val())) {
          if (typeof PROFILE_PAGE != "undefined" && PROFILE_PAGE == true) {
            btn.hide();
          } else {
            btn.addClass("alwoff");
          }
          return;
        }

        btn.removeClass("alwoff");
        aMngr.initAnswerRateUpBtn(btn);
      });

    this.answersWrap.find("#answers").eq(0).find("i")
      .each(function() {
        var btn = $(this);
        if (btn.hasClass("notthati")) {
            return;
        }
        if (LOGD != true) {
          //btn.hide();
          btn.addClass("alwoff");
          aMngr.initRegistrationTooltip(btn);
          return;
        }
        // don't init button for own answers
        if (SPACEY != true && parseInt(btn.parent().find(".a_a").val())
            == parseInt($("#logd_id").val())) {
          if (typeof PROFILE_PAGE != "undefined" && PROFILE_PAGE == true) {
            btn.hide();
          } else {
            btn.addClass("alwoff");
          }
          return;
        }
        btn.removeClass("alwoff");
        aMngr.initAnswerRateDownBtn(btn);
      });
  };

  this.initAnswerRateUpBtn = function(btn) {
    btn.click(function() {
      if (btn.hasClass("rated")) {
        return false;
      }
      var el_id;
      if (typeof PROFILE_PAGE != "undefined" && PROFILE_PAGE == true) {
        el_id = btn.parent().attr("id")
      } else {
        el_id = btn.parent().parent().parent().attr("id");
      }
      var ans_id = el_id.split("_")[1];
      aMngr.rate(ans_id, 1);

      return false
    });
  };

  this.initAnswerRateDownBtn = function(btn) {
    btn.click(function() {
      if (btn.hasClass("notthati")) {
          return false;
      }
      if (btn.hasClass("rated")) {
        return false;
      }
      var el_id;
      if (typeof PROFILE_PAGE != "undefined" && PROFILE_PAGE == true) {
        el_id = btn.parent().attr("id")
      } else {
        el_id = btn.parent().parent().parent().attr("id");
      }
      var ans_id = el_id.split("_")[1];
      aMngr.rate(ans_id, -1);

      return false
    });
  };

  this.initAnswerAuthors = function() {
    logg("AnswerManager.initAnswerAuthors()");
    this.answersWrap.find("span.by").each(function() {
      var author = $(this);
      aMngr.initAuthorTooltip(author);
      author.click(function() {
        window.location = CONTEXT_PATH + "users/" + encodeURIComponent(author.attr("by")) + "/";
      });
    });
  };

  this.initRegistrationTooltip = function(btn) {
    //logg("AnswerManager.initRegistrationTooltip()");
    var answers = $("#answers");
    btn.mouseover(function() {
      if (answers.hasClass("short")) {
        return;
      }
      var offset = btn.offset();
      $("#tooltip_body").find("p").html($("#message_register_vote_a").val());
      $("#tooltip").css({
        left: offset.left-2 + "px",
        top: offset.top-$("#tooltip").height()+6 + "px"
      }).show();
    }).mouseout(function() {
      if (answers.hasClass("short")) {
        return;
      }
      $("#tooltip").hide();
    });
  };

  this.initSaveBtn = function() {
    $("#a_comment").blur(function() {
      var cmtTxt = $(this);
      if (cmtTxt.val().trim()  === "") {
        cmtTxt.val($("#label_comment").val());
      }
    }).focus(function() {
      var cmtTxt = $(this);
      if (cmtTxt.val() === $("#label_comment").val()) {
        cmtTxt.val("");
      }
    });

    //aMngr.initSaveFormForceTimeout();
  };

  this.initSaveFormForceTimeout = function() {

    logg("initSaveFormForceTimeout");
    var tmo = $("#a_timeout");
    if (LOGD) {
      tmo.stop(true, true);
      submitTimeout = 0;
      $("#a_submit").fadeTo(1, 1);
      $("#a_form").unbind("submit").submit(function() {
        aMngr.send();
        return false;
      });

      tmo.hide();

    } else {
      tmo.show();
      tmo.stop(true, true);
      logg("unbinding submit");
      $("#a_form").unbind("submit").submit(function() {
        return false;
      });
      $("#a_submit").fadeTo(1, .2);
      submitTimeout = origSubmitTimeout;


      runSubmitTimeout();

      /*$("#a_submit").fadeTo(20000, 1, function() {
        $("#a_form").submit(function() {
          aMngr.send();
          return false;
        })
      });*/
    }
  };

  this.restartSubmitTimeout = function() {
    submitTimeout = origSubmitTimeout;
  };

  this.runSubmitTimeout = function() {
    logg("runSubmitTimeout(" + submitTimeout + ")");
    var tmo = $("#a_timeout");
    tmo.text(submitTimeout);
    submitTimeout = parseInt(submitTimeout) - 1;
    if (submitTimeout < 0) {
      tmo.stop(true, true);
      submitTimeoutRunning = false;
      $("#a_submit").fadeTo(300, 1, function() {
        $("#a_form").unbind("submit").submit(function() {
          aMngr.send();
          return false;
        })
      });
      submitTimeout = origSubmitTimeout;
    } else {
      submitTimeoutRunning = true;
      logg("else");
      //alert('fuckme');
      setTimeout(runSubmitTimeout, 1000);
      //tmo.show(1000, function() {
      //  aMngr.runSubmitTimeout();
      //});
    }

  };

  this.initAuthorTooltip = function(answer) {
    //logg("AnswerManager.initAuthorTooltip(" + answer + ")");
    answer.mouseover(function() {
      var offset = answer.offset();
      $("#tooltip_body").find("p").html(answer.attr("by"));
      $("#tooltip").css({
        left: offset.left+12 + "px",
        top: offset.top-$("#tooltip").height()+6 + "px"
      }).show();
    }).mouseout(function() {
      $("#tooltip").hide();
    });
  };

  this.showAnswersLoading = function() {
    $("#answers").css("display", "none");
    $("#sol_loading").css("display", "block");
    aMngr.blink = true;
    aMngr.alBlinkHide();
  };

  this.hideAnswersLoading = function() {
    var answerss = $("#answers");
    aMngr.blink = false;
    $("#sol_loading").stop(false, true);
    $("#sol_loading").css("display", "none");
    answerss.slideUp(0, function() {
      answerss.css("display", "block");
      answerss.slideDown(200);
    });

  };

  this.blink = false;

  this.alBlinkShow = function() {
    if (aMngr.blink == false) {
      return;
    }
    $("#sol_loading").fadeTo(250, 1, function() {
      aMngr.alBlinkHide();
    });
  };

  this.alBlinkHide = function() {
    if (aMngr.blink == false) {
      return;
    }
    $("#sol_loading").fadeTo(250, 0, function() {
      aMngr.alBlinkShow();
    });
  };

  this.rate = function(id, rate) {

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

    setAnswerBeingVoted(id);

    if (!rate) {
      rate = 1;
    }

    var postData =
      "answer_id=" + id +
      "&rate=" + rate;
    var requestUrl = CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_rate";

    led.on();

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "json",
      success: function(response) {

        led.off();

        if (response.status) {

          // update answer's rating

          var ratingEl;
          if (typeof PROFILE_PAGE != "undefined" && PROFILE_PAGE == true) {
            ratingEl = $("#a_" + id).eq(0).find("span").eq(0);
          } else {
            ratingEl = $("#a_" + id).find("p>span").eq(0);
          }

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

          var rateUpBtn = $("#a_" + id).find("b");
          var rateDnBtn = $("#a_" + id).find("i");
          var userRating = $("#user_rating");
          if (rate > 0) {
            if (rateDnBtn.hasClass("rated")) { // was -1, became 0
              rateDnBtn.removeClass("rated");
              aMngr.initAnswerRateDownBtn(rateDnBtn);
            } else { // was 0, became 1
              if (!SPACEY) {
                rateUpBtn.unbind("click");
                rateUpBtn.addClass("rated");
              }
            }
            if (userRating.is("h4")) {
              var r = parseInt(userRating.text());
              r = r+1;
              userRating.text(r);
            }
          } else {
            if (rateUpBtn.hasClass("rated")) { // was 1, became 0
              rateUpBtn.removeClass("rated");
              aMngr.initAnswerRateUpBtn(rateUpBtn);
            } else { // was 0, became -1
              if (!SPACEY) {
                rateDnBtn.unbind("click");
                rateDnBtn.addClass("rated");
              }
            }
            if (userRating.is("h4")) {
              var r = parseInt(userRating.text());
              r = r-1;
              userRating.text(r);
            }
          }

          removeAnswerBeingVoted(id);

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

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

  this.send = function() {

    // ajax call

    var answer = this.answerTextField.val();
    var answerComment = $("#a_comment").val();
    if (answerComment === $("#label_comment").val()) {
      answerComment = "";
    }
    var postData =
      "answer=" + encodeURIComponent(answer) +
      "&answer_comment=" + encodeURIComponent(answerComment) +
      "&question_id=" + qMngr.getActiveQuestion().getId() +
      "&termination_id=" + qMngr.getActiveQuestion().getTermId() +
      "&user_id=" + 0;
    var requestUrl = CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_save";

    led.on();

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "json",
      success: function(response) {
        led.off();

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

          if (response.answer_present) {
            showScreenPresent();
          } else {
            showScreenAnswer();
          }
          $("#a_comment").val($("#label_comment").val());

          // refresh answers
          aMngr.list(qMngr.getActiveQuestion());

        } else {
          messageError(response.msg_text);
        }


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

    return false;
  };

  this.cleanAnswerTextField = function() {
    this.answerTextField.val("");
  };

  this.focusOnAnswerTextField = function() {
    this.answerTextField.focus();
  };

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

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

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

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

  this.list = function(question) {
    logg("AnswerManager.list(" + question + ", " + this.skip + ")");

    var postData =
      "question_id=" + question.getId() +
      "&termination_id=" + question.getTermId() +
      "&skip=" + this.skip +
      "&sorting=" + this.orderBy +
      "&order=" + this.orderByDir;
    var requestUrl = CONTEXT_PATH + "x/" + LIGHT_SECTION_PATH + "answer_list";

    aMngr.showAnswersLoading();

    //led.on();

    $.ajax({
      type: "POST", url: requestUrl, data: postData, dataType: "html",
      success: function(response) {

        //led.off();

        //if (response.status) {

        //updateAnswerList(response);

        // response is the html of the answers list
        $("#answers").replaceWith(response);
        aMngr.initAnswerList();

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

        aMngr.hideAnswersLoading();



      },
      error: function(request, error) {

        led.off();

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

  this.showRatingBtns = function() {
    this.answersWrap.find("i,b").each(function() {
      $(this).show();
    });
  };

};

var addLogoutBtn = function(username) {

  var logoutBtnWrap = $(document.createElement("span"));
  logoutBtnWrap.attr("id", "btn_logout_wrap");

  var logoutBtn = $(document.createElement("a"));
  logoutBtn.attr("id", "btn_logout");
  logoutBtn.attr("href", CONTEXT_PATH + "logout/");
  logoutBtn.text("Выйти");

  logoutBtnWrap.append(logoutBtn);

  var usernameWrap = $(document.createElement("a"));
  usernameWrap.text(username);
  usernameWrap.attr("href", CONTEXT_PATH + "users/" + username);

  var span = $(document.createElement("span"));
  span.text(" (");
  logoutBtnWrap.append(span.clone());
  logoutBtnWrap.append(usernameWrap);
  span.text(")");
  logoutBtnWrap.append(span);

  return logoutBtnWrap;
}

var flushAnswersBeingVoted = function() {
  answersBeingVoted = [];
}

var answerBeingVoted = function(id) {
  id = parseInt(id);
  for (var i = 0; i < answersBeingVoted.length; i++) {
    if (id == answersBeingVoted[i]) {
      return true;
    }
  }
  return false;
}

var setAnswerBeingVoted = function(id) {
  if (answerBeingVoted() == false) {
    answersBeingVoted.push(id);
  }
}

var removeAnswerBeingVoted = function(id) {
  for (var i = 0; i < answersBeingVoted.length; i++) {
    if (id == answersBeingVoted[i]) {
      answersBeingVoted.splice(i,1);
    }
  }
}



