"use strict";
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
var YaAuth = {
get observerService() {
return Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
}
,
get params() {
return window.windowArguments;
}
,
get api() {
return this.params.api;
}
,
get auth() {
return this.params.auth;
}
,
get authdefs() {
return this.auth.authdefs;
}
,
get utils() {
var scope = {
};
Cu.import(this.api.Package.resolvePath("/native/fx/modules/utils.jsm"),scope);
delete this.utils;
this.__defineGetter__("utils",function () scope.utils);
return scope.utils;
}
,
get services() {
return this.params.services;
}
,
get branding() {
return this._branding;
}
,
observeServiceEvent: function YaAuth_observeServiceEvent() {

}
,
__stringBundle: null,
get _stringBundle() {
return this.__stringBundle || (this.__stringBundle = this.api.Localization.createStringBundle("/native/fx/welcome.properties"));
}
,
close: function YaAuth_close() {
window.close();
}
,
setPref: function YaAuth_setPref(strPrefName, prefValue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
prefsModule.set(prefFullName,prefValue);
}
,
getPref: function YaAuth_getPref(strPrefName, defaltvalue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
return prefsModule.get(prefFullName,defaltvalue);
}
,
changeMode: function YaAuth_changeMode() {

}
,
fireEvent: function YaAuth_fireEvent(strType, data) {
var clb = this.params.onEvent;
if (clb)
clb({
type: strType,
data: data});
}
,
get usernameText() {
return (document.getElementById("username").value || "").replace(/^\s\s*/,"").replace(/\s\s*$/,"");
}
,
get passwordText() {
return (document.getElementById("password").value || "").replace(/^\s\s*/,"").replace(/\s\s*$/,"");
}
,
onDialogLoad: function YaAuth_onDialogLoad() {
this._branding = this.api.Services.obtainService("ru.yandex.custombar.branding","package",this);
var {name: serviceName, title: serviceTitle, login: login} = this.params.dialogParams;
document.documentElement.setAttribute("yaServiceName",serviceName || "");
document.getElementById("title").setAttribute("value",serviceTitle || "");
var usernameElement = document.getElementById("username");
usernameElement.clickSelectsAll = true;
var usernamePopup = usernameElement.popup;
usernamePopup.addEventListener("mouseup",this,true);
usernamePopup.addEventListener("mousemove",this,true);
usernamePopup.addEventListener("mouseout",this,true);
if (login)
{
usernameElement.value = login;
let passwordElement = document.getElementById("password");
passwordElement.value = "";
passwordElement.click();
}
 else
{
if (login !== "")
{
if (this._showDefaultCredentials() === false)
{
return;
}

}

usernameElement.click();
}

this.checkAcceptButton();
this.auth.addListener("login-state-changed",this);
this._nLoginTry = 0;
if (! ("adjustHeight" in usernamePopup))
return;
usernamePopup.adjustHeight();
try {
this._setupSocialAuthBlock();
}
catch (e) {
this.api.logger.error("Could not setup social auth block. " + e);
this.api.logger.debug(e.stack);
}

this.sizeToContent();
}
,
onDialogUnload: function YaAuth_onDialogUnload() {
this.auth.removeListener("login-state-changed",this);
this.api.Services.releaseService("ru.yandex.custombar.branding","package",this);
var usernamePopup = document.getElementById("username").popup;
usernamePopup.removeEventListener("mouseup",this,true);
usernamePopup.removeEventListener("mousemove",this,true);
usernamePopup.removeEventListener("mouseout",this,true);
}
,
onDialogAccept: function YaAuth_onDialogAccept() {
if (this.usernameText && this.passwordText)
{
try {
if (! this.auth.initLoginProcess(this.usernameText,this.passwordText,! document.getElementById("strangeComputer").checked))
this.close();
}
catch (ex) {
this.api.logger.error(ex.message);
}

}

}
,
sizeToContent: function YaAuth_sizeToContent() {
try {
setTimeout(function () {
var contentHolderBO = document.getElementById("contentHolder").boxObject;
platform.resizeWindowTo(contentHolderBO.width,contentHolderBO.height);
}
,0);
}
catch (e) {

}

}
,
observe: function YaAuth_observe(subject, topic, data) {
switch (topic) {
case "login-state-changed":
this._handleLoginStateChanged(data);
break;
}

}
,
handleEvent: function YaAuth_handleEvent(event) {
if (! event.isTrusted)
return;
var rc = null;
switch (event.type) {
case "mouseup":
rc = this.utils.getHoverCell(event,document);
if (rc)
{
let scrollState = document.getElementById("username").popup.tree.getAttribute("hidescrollbar");
let currentColumnId = scrollState == "false" ? "treecolAutoCompleteComment" : "treecolAutoCompleteImage";
if (rc.column && rc.column.id == currentColumnId)
{
event.stopPropagation();
let pwdmng = this.auth.pwdmng;
let login2remove = document.getElementById("username").controller.getValueAt(rc.row);
let title = this._stringBundle.get("LogginRemoveUserTitle");
let msg = this.branding.expandBrandTemplates(this._stringBundle.get("LogginRemoveUserMessage",[login2remove]));
let result = this.utils.showPrompt(window,title,msg);
if (result)
{
let password2remove = pwdmng.getStoredPassword(login2remove);
pwdmng.removeUserData(login2remove);
try {
if (this.usernameText == login2remove)
{
document.getElementById("username").value = "";
if (this.passwordText == password2remove)
{
document.getElementById("password").value = "";
}

}

this._refreshHasSavedLoginsMode();
this.checkAcceptButton();
}
catch (e) {

}

}

}

}

break;
case "mousemove":
try {
rc = this.utils.getHoverCell(event,document);
}
catch (e) {

}

if (! rc)
return;
let scrollState = document.getElementById("username").popup.tree.getAttribute("hidescrollbar");
let currentColumnId = scrollState == "false" ? "treecolAutoCompleteComment" : "treecolAutoCompleteImage";
let onColumn = rc.column && rc.column.id == currentColumnId ? true : false;
if (this.auth.pwdmng.onHoverTreeUglyHack != onColumn)
{
this.auth.pwdmng.onHoverTreeUglyHack = onColumn;
document.getElementById("username").popup.invalidate();
}

break;
case "mouseout":
this.auth.pwdmng.onHoverTreeUglyHack = false;
document.getElementById("username").popup.invalidate();
break;
}

}
,
checkAcceptButton: function YaAuth_checkAcceptButton(aEvent) {
var disabled = this.usernameText.length < 2 || this.passwordText.length < 2;
var acceptButton = document.getElementById("doLogin");
if (acceptButton.disabled !== disabled)
acceptButton.disabled = disabled;
document.getElementById("doLogin").disabled = disabled;
var usernamePopup = document.getElementById("username").popup;
if (usernamePopup)
usernamePopup.invalidate();
if (! disabled && aEvent && aEvent.type == "keyup" && aEvent.keyCode == aEvent.DOM_VK_RETURN)
{
let loginButton = document.getElementById("doLogin");
loginButton.focus();
loginButton.doCommand();
}

}
,
handleLoginEntered: function YaAuth_handleLoginEntered() {
var savedUser = this.auth.pwdmng.getSavedLoginInfo(this.usernameText);
if (savedUser)
{
document.getElementById("password").value = savedUser.password;
this.checkAcceptButton();
}

}
,
handleSocProviderClick: function YaAuth_handleSocProviderClick(aEvent) {
if (aEvent.button !== 0)
return;
var url = aEvent.target.parentNode.getAttribute("ybar_prov_url");
if (! url)
return;
window.open(url,"YBarSocialAuthWnd","resizable=yes,scrollbars=yes,status=yes,location=yes,centerscreen=yes,width=400,height=400");
this.close();
}
,
handleLinkClick: function YaAuth_handleLinkClick(aEvent) {
if (aEvent.button !== 0)
return;
var target = aEvent.target;
if (target.hasAttribute("yaLinkAction"))
{
this.api.Statistics.logShortAction(target.getAttribute("yaLinkAction"));
}

var url = target.getAttribute("yahref");
url = url.replace("https://passport.yandex.ru",this.authdefs.LINKS.AUTH_PASSPORT_URL);
this.api.Controls.navigateBrowser({
url: url,
eventInfo: aEvent});
this.close();
}
,
_handleLoginStateChanged: function YaAuth__handleLoginStateChanged(data) {
if (! document)
return;
var connectionStatus = 0;
var lastStateIsRequest = document.getElementById("connectionStatus").selectedIndex == 1;
this.api.logger.debug("Login state changed to " + data.state);
switch (data.state) {
case this.authdefs.LOGIN_STATES.REQUEST:
connectionStatus = 1;
break;
case this.authdefs.LOGIN_STATES.NET_ERROR:
connectionStatus = lastStateIsRequest ? 3 : 0;
break;
case this.authdefs.LOGIN_STATES.CAPTCHA_ERROR:
if (lastStateIsRequest)
{
let title = this.branding.expandBrandTemplates(this._stringBundle.get("CaptchaDialogTitle"));
let msg = this._stringBundle.get("CaptchaDialogMsg");
let resultCode = this.utils.showPromptEx(window,title,msg,this._stringBundle.get("CaptchaDialogButtonOK"),this._stringBundle.get("CaptchaDialogButtonCancel"),null,null,{
});
if (resultCode !== 1)
{
this.api.Controls.navigateBrowser({
url: this.authdefs.LINKS.AUTH_PASSPORT_URL,
target: "new tab"});
this.close();
return;
}

connectionStatus = 4;
}

break;
case this.authdefs.LOGIN_STATES.LOGIN_FAIL:
if (lastStateIsRequest)
{
if (this._nLoginTry >= 3)
{
connectionStatus = 4;
}
 else
{
connectionStatus = 2;
this._nLoginTry++;
}

}

break;
case this.authdefs.LOGIN_STATES.AUTH:
this.close();
return;
default:
if (lastStateIsRequest)
{
connectionStatus = 2;
}

break;
}

this._setConnectionStatus(connectionStatus);
var controlsDisabled = data.state >= this.authdefs.LOGIN_STATES.REQUEST;
["username", "password", "strangeComputer", "doLogin"].forEach(function (strControlId) {
document.getElementById(strControlId).disabled = controlsDisabled;
}
);
if (! controlsDisabled)
{
let passTextbox = document.getElementById("password");
if (document.commandDispatcher.focusedElement == passTextbox.inputField)
{
passTextbox.blur();
passTextbox.focus();
}

}

}
,
_setConnectionStatus: function YaAuth__setConnectionStatus(aStatusIndex) {
document.getElementById("connectionStatus").selectedIndex = aStatusIndex;
this.sizeToContent();
}
,
_refreshHasSavedLoginsMode: function YaAuth__refreshHasSavedLoginsMode() {
document.getElementById("username").setAttribute("yaHasSavedLogins",this.auth.pwdmng.hasSavedLogins);
}
,
_showDefaultCredentials: function YaAuth__showDefaultCredentials() {
try {
this._refreshHasSavedLoginsMode();
}
catch (e) {
return false;
}

if (this.usernameText)
return;
var username = this.auth.pwdmng.defaultUsername;
if (! username)
return;
var password = this.auth.pwdmng.getStoredPassword(username);
if (! password)
return;
document.getElementById("username").value = username;
document.getElementById("password").value = password;
}
,
switchSocialAuthList: function YaAuth_switchSocialAuthList() {
var authBlock = document.getElementById("socialAuthBlock");
authBlock.setAttribute("full",authBlock.getAttribute("full") == "false");
this.sizeToContent();
}
,
_setupSocialAuthBlock: function YaAuth__setupSocialAuthBlock() {
var providersFrag = this.api.XMLUtils.transformXMLToFragment(this.services.socialAuthProvidersDoc,this._socialProvsTemplate,document);
var providersShortList = document.getElementById("socialAuthShortList");
while (providersShortList.firstChild) providersShortList.remove(providersShortList.firstChild);
var childNodes = providersFrag.childNodes;
for (let i = 0, len = childNodes.length;i < len;i++) {
if (childNodes[i].getAttribute("ybar_prov_primary") == "1")
providersShortList.appendChild(childNodes[i].cloneNode(true));
}

var providersFullList = document.getElementById("socialAuthFullList");
while (providersFullList.firstChild) providersFullList.remove(providersFullList.firstChild);
var child;
while (child = providersFrag.firstChild) providersFullList.appendChild(child);
document.getElementById("socialAuthShowMore").hidden = providersShortList.childNodes.length == providersFullList.childNodes.length;
}
,
get _socialProvsTemplate() {
return this.api.XMLUtils.xmlDocFromStream(this.api.Package.getFileInputChannel("/native/fx/templates/socauth.xsl").contentStream,null,null,true);
}
};
