var wasPressed = false;

var existUnsavedData = false;
var riseResetForumSawDate = false;
$(document).ready(function () {
  document.onkeydown = fkey;
  document.onkeypress = fkey;
  document.onkeyup = fkey;
  function fkey(e) {
    e = e || window.event;
    if (wasPressed) return;
    if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82) /*ctrl+r*/) {
      wasPressed = true;
      ResetEvent(false);
    }
  }

  this.riseResetForumSawDate = false;

  function ResetEvent(on) {
    this.riseResetForumSawDate = on;
    console.log("riseResetForumSawDate set " + this.riseResetForumSawDate);
  }

  // add event listner to top window
  if (window.addEventListener) {
    window.removeEventListener("message", listener);
    window.addEventListener("message", listener, false);
  } else {
    window.detachEvent("onmessage", listener);
    window.attachEvent("onmessage", listener);
  }

  // function, that call on post message to main browser window
  function listener(event) {
    if (event.data != null) {
      if (event.data == "createunsaveddata") {
        existUnsavedData = true;
      } else if (event.data == "unsaveddatawassave") {
        existUnsavedData = false;
      }
    }
  }

  $(".b-forum-message__body")
    .find("a")
    .each(function () {
      //58312
      if (location.hostname === this.hostname || !this.hostname.length) {
        $(this).attr("target", "_parent");
      } else {
        $(this).attr("target", "_blank");
      }
    });

  var isChrome =
    /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
  var isFF =
    /Firefox[\/\s](\d+)/.test(navigator.userAgent) &&
    new Number(RegExp.$1) >= 4;

  window.onunload = function () {
    if (this.riseResetForumSawDate == true) {
      if (isFF) {
        console.log("firefox");
        ReserSawDate();
        return null;
      } else {
        console.log("NON-firefox");
        ReserSawDate();
        return null;
      }
    } else {
      console.log("riseResetForumSawDate is false");
    }
  };

  if (isChrome || isFF) {
    window.onbeforeunload = window.onunload;
  }

  function ReserSawDate() {
    $.ajax({
      url:
        "service/resetforumsawdate.php?oguid=" +
        GForumOGUID +
        (typeof gIDBranch === "undefined" ? "" : "idbranch=" + gIDBranch),
      type: "get",
      success: function () {
        console.log("ok, is reseted.");
      },
    });
  }

  if (window.parent != null) {
    $(window.parent).mouseleave(function () {
      ResetEvent(true);
    });
    $(window.parent).mouseenter(function () {
      ResetEvent(false);
    });
  } else {
    $(window).mouseleave(function () {
      ResetEvent(true);
    });
    $(window).mouseenter(function () {
      ResetEvent(false);
    });
  }

  $("#sendForm").submit(function (event) {
    if (
      typeof $("#file").val() == "undefined" ||
      $("#file").val().trim() == ""
    ) {
      if (
        $("#cke_forummessage iframe").contents().find("body").text().trim() ==
          "" &&
        // ei check img
        CKEDITOR.instances.forummessage.document
          .getBody()
          .getHtml()
          .indexOf("<img src=") < 0 &&
        CKEDITOR.instances.forummessage.document
          .getBody()
          .getHtml()
          .indexOf("<img data-cke-saved-src") < 0
      ) {
        alert(GForumEmprtyMessageAlert);
        event.preventDefault();
        return false;
      }
    }
    parent.postMessage("unsaveddatawassave", "*");
    ShowModalWindow(true);
    $("#buttonSendForm").attr("disabled", "disabled");
  });

  $(".forum-inline-message").click(function () {
    var myImage = new Image();
    myImage.src = $(this).attr("src");
    myImage.style.border = "none";
    myImage.style.outline = "none";
    myImage.style.position = "fixed";
    myImage.style.left = "0";
    myImage.style.top = "0";
    myImage.onload = function () {
      var left = Math.round(screen.width / 2 - myImage.width / 2.2);
      var top = Math.round(screen.height / 2 - myImage.height / 1.8);

      var newWindow = window.open(
        "",
        "",
        "width=" +
          myImage.width +
          ",height=" +
          myImage.height +
          ",left=" +
          left +
          ",top=" +
          top
      );
      if (newWindow) {
        newWindow.document.write(myImage.outerHTML);
      } else {
        var a = window.document.createElement("a");
        a.target = "_blank";
        a.href = $(this).attr("src");
        var e = window.document.createEvent("MouseEvents");
        e.initMouseEvent(
          "click",
          true,
          true,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
        a.dispatchEvent(e);
      }
    };
  });

  var editor = CKEDITOR.replace("forummessage", {
    language: gShortLang,
    contentsCss: "ckeditor/contents.css",
    // instanceReady
    on: {
      instanceReady: function (ev) {
        if (!GNewPageOpen) {
          return;
        } else {
          ev.editor.focus();
          if (GIsReply) {
            return;
          }

          var s = ev.editor.getSelection();
          var selected_ranges = s.getRanges();
          var node = selected_ranges[0].startContainer;
          var parents = node.getParents(true);
          node = parents[parents.length - 2].getFirst();
          while (true) {
            var x = node.getNext();
            if (x == null) {
              break;
            }
            node = x;
          }
          s.selectElement(node);
          selected_ranges = s.getRanges();
          selected_ranges[0].collapse(false);
          s.selectRanges(selected_ranges);

          var doc = $(ev.editor.document.$);
          doc.scrollTop(doc.height());
        }

        var tags = ["p", "ol", "ul", "li"];

        for (var key in tags) {
          ev.editor.dataProcessor.writer.setRules(tags[key], {
            indent: false,
            breakBeforeOpen: false,
            breakAfterOpen: false,
            breakBeforeClose: false,
            breakAfterClose: false,
          });
        }
        $(ev.editor.document.$).keyup(function (e) {
          if (e.keyCode == 27) {
            window.location = GForumLocation;
          }
        });
      },
    },
    // instanceReady end
    toolbar: [
      ["Bold", "Italic", "Underline", "Strike", "-", "Link", "Unlink", "Image"],
    ],
  });
  CKEDITOR.config.autoParagraph = false;
  CKEDITOR.config.linkShowAdvancedTab = false;
  CKEDITOR.config.linkShowTargetTab = false;
  CKEDITOR.config.DefaultLinkTarget = "_blank";
  CKEDITOR.config.defaultLanguage = gShortLang;
  CKEDITOR.config.language = gShortLang;
  var chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
  var edge = /Edge\/\d./i.test(navigator.userAgent.toLowerCase());

  if (chrome || edge) {
    CKEDITOR.config.extraPlugins = "pastebase64";
  } else {
    CKEDITOR.config.extraPlugins = "pastebase64ie";
  }

  CKEDITOR.instances.forummessage.on("change", function () {
    parent.postMessage("createunsaveddata", "*");
    postMessage("createunsaveddata", "*");
  });

  CKEDITOR.instances.forummessage.on("contentDom", function () {
    //66326
    CKEDITOR.instances.forummessage.document.on("keyup", function (event) {
      if (event.data.getKeystroke() == CKEDITOR.CTRL + 13) {
        event.data.preventDefault();
        $("#sendForm").submit();
      }
    });
  });

  CKEDITOR.timestamp = Math.random().toString(36).substr(2, 9);

  $(document).keyup(function (e) {
    if (e.keyCode == 27) {
      window.location = GForumLocation;
    }
  });

  //64016
  $(".forum-selfopen-link").click(function () {
    event.preventDefault();
    if (!existUnsavedData || confirm(gConfirmsavelesValue)) {
      parent.postMessage("unsaveddatawassave", "*");
      existUnsavedData = false;
      window.location = $(this).attr("jshref");
    } else {
      return false;
    }
  });
  //62126
  $(window).scrollTo("#selected-forumid");
});
