dojo.provide("parus.loginDialog");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.database");
dojo.require("parus.changePasswordDialog");
dojo.require("parus.openIDRegistrationDialog");
dojo.require("parus.negotiateRegistrationDialog");

dojo.declare("parus.loginDialog", [parus.Dialog], {

  task: null,

  sizeable: null,

  title: "Начать сеанс",

  sessionUserName: null,

  sessionUserHandler: null,

  sessionPassword: null,

  sessionNegotiate: null,
  sessionSSLCert: null,

  postCreate: function() {

    this.inherited(arguments);

    parus.loginDialog.instance = this;

    var negotiateAuthEnabled = false;
    var sslCertAuthEnabled = false;

    dojo.xhrGet({
      handleAs: "xml",
      sync: true,
      headers: {
        "Disable-Basic-Auth": "yes"
      },
      preventCache: true,
      url: "../.system/contents.xml",
      load: dojo.hitch(this, function(response) {
        parus.parus8._hasInstantMessagesHandler = false;

        (function(node) {
          var nodes = node.childNodes;
          for (var j = nodes.length - 1; j >= 0; j--) {
            if (nodes[j].nodeType == 1) arguments.callee(nodes[j]);
            else {
              node.removeChild(nodes[j]);
            }
          }
        })(response.documentElement);

        for (var i = 0; i < response.documentElement.childNodes.length; i++) {
          var node = response.documentElement.childNodes[i];
          if ((node.getAttribute("class").toString() == parus.parus8.CLASS_InstantMessageHandler.toString()) && ((node.getAttribute("disabled") || 0).toString() != "1")) {
            parus.parus8._hasInstantMessagesHandler = node.getAttribute("ID");
          }
          else if (((node.getAttribute("class").toString() == parus.parus8.CLASS_ParusBalanceContentHandler.toString()) || (node.getAttribute("class").toString() == parus.parus8.CLASS_PPCBalanceContentHandler.toString())) && ((node.getAttribute("disabled") || 0).toString() != "1")) {

            var skip = false;
            var auths = node.childNodes;

            for (var j = 0; j < auths.length; j++)
            if (auths[j].getAttribute("ID") == "parusSessionIdentAuth") skip = true;

            if (!skip) {

              var nodes = node.childNodes[0].childNodes;
              for (var j = 0; j < nodes.length; j++) {
                if (nodes[j].childNodes[0]) if (nodes[j].childNodes[0].getAttribute("value"))

                this.databaseSelect.addOption({
                  value: node.getAttribute("ID") + ";" + nodes[j].childNodes[0].getAttribute("value"),
                  label: (node.getAttribute("FriendlyName") ? (node.getAttribute("FriendlyName") + " - ") : "") + nodes[j].childNodes[0].getAttribute("value")
                });
              }

              for (var j = 0; j < auths.length; j++) {
                if (auths[j].getAttribute("ID") == "parusOpenIDAuth") {
                  this.incAuthHeight();
                  this.EnterOpenIDDiv.style.display = "";
                  if (node.getAttribute("AllowRegisterOpenIDLogin") == "1") {
                    this.registerOpenIDButton.domNode.style.display = "";
                  }
                } else if (auths[j].getAttribute("ID") == "parusNegotiateAuth") {
                  this.incAuthHeight();
                  this.EnterNegotiateDiv.style.display = "";
                  if (node.getAttribute("AllowRegisterNegotiateLogin") == "1") {
                    this.registerNegotiateButton.domNode.style.display = "";
                  }
                  negotiateAuthEnabled = true;
                }
                else if (auths[j].getAttribute("ID") == "parusSSLCertAuth") {
                  this.incAuthHeight();
                  this.EnterSSLCertDiv.style.display = "";
                  sslCertAuthEnabled = true;
                }
              }
            }
          }
          else if ((node.getAttribute("class").toString() == parus.parus8.CLASS_FolderContentHandler.toString()) && ((node.getAttribute("disabled") || 0).toString() != "1") && (node.getAttribute("ID").toString() == "parusproxyjs") && (navigator.userAgent.split("Windows").length > 1)) {
            this.remoteAccessButton.domNode.style.display = "";
          }

        };
        return (response);
      })
    });

    this.dialog.closeButtonNode.style.display = "none";
    this.dialog.containerNode.style.padding = 0;
    this.loginEdit.attr("value", this.sessionUserName);
    this.databaseSelect.attr("value", this.sessionUserHandler);

    this.headingDiv.appendChild(document.createTextNode(this.task));

    this.passwordEdit.attr("value", this.sessionPassword);
    this.storePassword.attr("checked", this.passwordEdit.value && this.loginEdit.value);

    if (negotiateAuthEnabled || sslCertAuthEnabled) {
      this.negotiateAuth.attr("checked", this.sessionNegotiate);
      this.sslCertAuth.attr("checked", this.sessionSSLCert);
      this.passwordLessAuthClick();
    }

    if (this.passwordEdit.value && this.loginEdit.value) dijit.focus(this.OKButton.focusNode);
    else if (this.loginEdit.value) dijit.focus(this.passwordEdit.focusNode);
    else dijit.focus(this.loginEdit.focusNode);

    if (document.body.clientHeight < 250) {
      this.headingPane.destroyRecursive();
      this.dialog.titleNode.innerHTML = this.dialog.titleNode.innerHTML + String.fromCharCode(160) + String.fromCharCode(34) + this.task + String.fromCharCode(34);
      this.MainBorderContainer.domNode.style.height = "222px";
      this.MainBorderContainer.layout();

    }

    this.dialog.domNode.setAttribute("logindialog", 1);

    var oldHandler = dojo.hitch(this.dialog, this.dialog._onKey);

    dojo.mixin(this.dialog, {
      _onKey: dojo.hitch(this, function(evt) {
        if ((evt.charOrCode || evt.keyCode) == dojo.keys.ESCAPE) return;
        oldHandler(evt);
      })
    });


  },

  apply: function() {
    if (!this.validate()) return;
    if (!this.databaseSelect.value) return;

    var login, password;
    if (!this.negotiateAuth.checked && !this.sslCertAuth.checked) {
      login = this.loginEdit.value;
      password = this.passwordEdit.value;
    }

    if (parus.database.connect(this.databaseSelect.value, login, password, null, null, this.sslCertAuth.checked)) {
      dojo.cookie("loggedUserHandler-c", this.databaseSelect.value, {
        expires: 365
      });
      if (!this.negotiateAuth.checked && !this.sslCertAuth.checked) {
        dojo.cookie("loggedUserName-c", this.loginEdit.value, {
          expires: 365
        });
        if (this.storePassword.checked) dojo.cookie("loggedUserPassword-c", this.passwordEdit.value, {
          expires: 365
        });
        else dojo.cookie("loggedUserPassword-c", "");

        dojo.cookie("loggedAsNegotiate-c", "");
        dojo.cookie("loggedAsSSLCert-c", "");
      }
      else if (this.negotiateAuth.checked) {
        dojo.cookie("loggedAsNegotiate-c", "1");
        dojo.cookie("loggedAsSSLCert-c", "");
      }
      else if (this.sslCertAuth.checked) {
        dojo.cookie("loggedAsNegotiate-c", "");
        dojo.cookie("loggedAsSSLCert-c", "1");
      }

      this.inherited(arguments);
    }
    else {
      if (!parus.database.authException) alert("Регистрационные данные не верны. Проверьте пожалуйста правильность ввода.");
    }

  },

  incAuthHeight: function() {
    dojo.style(this.MainBorderContainer.domNode, {
      height: (parus.parus8.styleSize(this.MainBorderContainer.domNode.style.height) + 20) + "px"
    });
    dojo.style(this.sidebarDiv.domNode, {
      height: (parus.parus8.styleSize(this.sidebarDiv.domNode.style.height) + 20) + "px"
    });
    dojo.style(this.CustomAuthDiv.domNode, {
      height: (parus.parus8.styleSize(this.CustomAuthDiv.domNode.style.height) + 20) + "px"
    });
  },

  changePassword: function() {
    if (!this.validate()) return;
    if (!this.databaseSelect.value) return;
    if (this.negotiateAuth.checked || this.sslCertAuth.checked) return;

    (new parus.changePasswordDialog({
      handler: this.databaseSelect.value,
      login: this.loginEdit.value,
      password: this.passwordEdit.value
    })).show();
  },

  storePasswordClick: function() {
    if (this.storePassword.checked) {
      if (!confirm("Сохраненный пароль может стать достоянием злоумышленников. Вы хотите сохранить введенный пароль?")) this.storePassword.attr("checked", false);
    }
  },

  passwordLessAuthClick: function() {
    if (this.negotiateAuth.checked || this.sslCertAuth.checked) {
      this.loginEdit.attr("value", null);
      this.passwordEdit.attr("value", null);
      this.storePassword.attr("checked", false);
    }
    else {
      this.loginEdit.attr("value", this.sessionUserName);
      this.passwordEdit.attr("value", this.sessionPassword);
      this.storePassword.attr("checked", this.passwordEdit.value && this.loginEdit.value);
    }
    var disable = (this.negotiateAuth.checked || this.sslCertAuth.checked) ? true : false;
    this.loginEdit.attr("disabled", disable);
    this.passwordEdit.attr("disabled", disable);
    this.storePassword.attr("disabled", disable);

    this.registerOpenIDButton.attr("disabled", disable);
    this.registerNegotiateButton.attr("disabled", disable);
  },

  helpButtonClick: function() {
    (new dijit.Dialog({
      href: "../parusjs/parusLoginDialogHelp.html",
      extractContent: true,
      style: "width:80%;height:80%;overflow:scroll",
      title: "Как войти в систему?"
    })).show();
  },

  remoteAccess: function() {
    if (!parus.parus8.remoteAccessDialog) parus.parus8.remoteAccessDialog = new dijit.Dialog({
      href: "../parusproxyjs/proxy.html",
      extractContent: true,
      style: "width:80%;height:80%;overflow:scroll",
      title: "Удаленный доступ для Windows",
      onLoad: function() {
        parus.parus8.buildParusProxyLaunchersList([
        parus.parus8.CLASS_OCIProxyParusBalanceContentHandler, parus.parus8.CLASS_PPCProxyBalanceContentHandler], "../parusproxyjs/Launchers/");
      }
    });

    parus.parus8.remoteAccessDialog.show();
  },

  registerOpenID: function() {
    if (!this.validate()) return;
    if (!this.databaseSelect.value) return;
    if (this.negotiateAuth.checked || this.sslCertAuth.checked) return;

    (new parus.openIDRegistrationDialog({
      handler: this.databaseSelect.value,
      login: this.loginEdit.value,
      password: this.passwordEdit.value
    })).show();
  },

  registerNegotiate: function() {
    if (!this.validate()) return;
    if (!this.databaseSelect.value) return;
    if (this.negotiateAuth.checked || this.sslCertAuth.checked) return;

    var dialog = new parus.negotiateRegistrationDialog({
      handler: this.databaseSelect.value,
      login: this.loginEdit.value,
      password: this.passwordEdit.value
    });

    if (dialog.assignCurrentNegotiateUserName()) {
      dialog.show();
    }
    else {
      dialog.close();
    }
  }

});

dojo.mixin(parus.parus8, {
  remoteAccessDialog: null
});

dojo.mixin(parus.loginDialog, {

  enterOpenID: function() {

    var dialog = dijit.byNode(dojo.query("*[logindialog]")[0]).dialogObject;

    var openIDDialog = new dijit.Dialog({
      title: "Вход через OpenID",
      content: dojo.cache("parus", "openIDLoginDialog.html"),
      perform: dojo.hitch(this, function() {
        var edit = dijit.byNode(dojo.query("*[widgetId]", openIDDialog.domNode)[0]);
        if (!edit.validate()) return;

        var responseFuncton = function(smth, ioArgs) {
          if (ioArgs.xhr.getResponseHeader("X-Location")) {
            window.open(ioArgs.xhr.getResponseHeader("X-Location"), "_self");
          }
          else {
            parus.parus8.errorMessage("Идентификатор не может служить OpenID-идентификатором." + "<br/>" + "Возможно, провайдер не доступен.");
            openIDDialog.hide();
          }
          return smth;
        };

        var handler = dialog.databaseSelect.value;
        var companyName = "";
        var h = handler.split(";");
        if (h.length > 1) {
          handler = h[0];
          companyName = h[1];
        }

        var xhr = dojo.xhrGet({
          handleAs: "xml",
          sync: false,
          headers: {
            "Disable-Basic-Auth": "yes"
          },
          url: "../" + handler + "/sysinfo.xml",
          content: {
            "SessionCompanyName": companyName,
            "openid_identifier": edit.attr("value"),
            "openid_location_header": "X-Location",
            "openid_return_to": document.location.pathname,
            "loggedUserHandler": dialog.databaseSelect.value
          },
          load: responseFuncton,
          error: responseFuncton
        });

      })

    });

    openIDDialog.show();


  }

});