const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
var Dlg = {
get params() {
return window.yaWinArguments;
}
,
get api() {
return this.params.api;
}
,
onDialogLoad: function () {

}
,
onDialogUnload: function () {

}
,
onDialogAccept: function () {

}
,
getLocalizedString: function (strName) {
return document.documentElement.getLocalizedString(strName);
}
,
getLocalizedFormattedString: function (strName, aStrArray) {
return document.documentElement.getFormattedString(strName,aStrArray,aStrArray.length);
}
,
getPref: function (strPrefName, defaultValue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
return prefsModule.get(prefFullName,defaultValue);
}
,
setPref: function (strPrefName, strPrefValue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
return prefsModule.set(prefFullName,strPrefValue);
}
,
fireEvent: function OpinionsDialog__fireEvent(strType, data) {
var clb = this.params.onEvent;
if (clb)
clb({
type: strType,
data: data});
}
,
get utils() {
var scope = {
};
Cu.import(this.api.Package.resolvePath("/native/fx/modules/utils.jsm"),scope);
delete this.utils;
this.__defineGetter__("utils",function utils() scope.utils);
return scope.utils;
}
};
var BookmarksDlg = {
get params() {
return window.yaWinArguments;
}
,
handleListChange: function (list) {
document.getElementById("bookmarks-newfolder").disabled = list.selectedIndex != 0 && ! list.selectedItem.hasAttribute("folderid");
}
,
validate: function () {
var disabled = ! this._getEnabled() || document.getElementById("bookmarks-row-url").hidden != true && document.getElementById("bookmarks-url").value == "" || document.getElementById("bookmarks-name").value.trim() == "" || document.getElementById("bookmarks-desc").textLength > 65536;
if (! document.getElementById("bookmarks-name").value.trim())
{
document.getElementById("bookmarks-name").className = "invalid";
}
 else
{
document.getElementById("bookmarks-name").className = "";
}

if (document.getElementById("bookmarks-desc").textLength > 65536)
{
document.getElementById("bookmarks-desc").className = "invalid";
}
 else
{
document.getElementById("bookmarks-desc").className = "";
}

document.documentElement.getButton("accept").disabled = disabled;
}
,
onDialogLoad: function () {
var bookmark = this.params.bookmark;
var services = this.params.services;
var documentTitleType = "yaTitleBookmarks";
document.getElementById("bookmarks-url").value = bookmark.url || "";
document.getElementById("bookmarks-name").value = bookmark.name || "";
document.getElementById("bookmarks-desc").value = bookmark.desc || "";
var root = services.selectBookmarksStructure();
var menuListPlaceholder = document.getElementById("bookmarks-folder-placeholder");
menuListPlaceholder.removeChild(menuListPlaceholder.firstChild);
var menuList = this._buildMenuList(root);
menuListPlaceholder.appendChild(menuList);
menuList = menuListPlaceholder.firstChild;
if (bookmark.id)
{
if (bookmark.type == "folder")
{
document.getElementById("bookmarks-row-url").hidden = true;
document.getElementById("bookmarks-row-tags").hidden = true;
documentTitleType = "yaTitleFolderEdit";
let folderForEdit = menuList.querySelector("[folderid='" + bookmark.parentId + "']");
if (! folderForEdit)
this._exitWithError("input",true);
folderForEdit.setAttribute("disabled","true");
}
 else
{
documentTitleType = "yaTitleBookmarkEdit";
}

}
 else
{
if (bookmark.type == "link")
{
let yaRu = document.getElementById("yaru-settings");
yaRu.visible = true;
}

}

document.getElementById("bookmarks-tags").initWithValue(bookmark.tags,this.params.tags);
document.title = document.documentElement.getAttribute(documentTitleType);
var selectedFolder = typeof bookmark.parentId != "undefined" ? menuList.querySelector("[folderid='" + bookmark.parentId + "']") : menuList.querySelector("[folderid='" + this.getPref("lastFolderId","0") + "']");
if (selectedFolder)
{
menuList.selectedItem = selectedFolder;
}
 else
{
if (bookmark.id)
{
this._exitWithError("input",true);
}

}

window.sizeToContent();
this.validate();
}
,
_buildMenuList: function (root) {
var document = window.document;
var menulist = document.createElement("menulist");
menulist.setAttribute("id","bookmarks-folder");
menulist.setAttribute("class","folder-icon");
menulist.setAttribute("oncommand","BookmarksDlg.handleListChange(this)");
var menupopup = document.createElement("menupopup");
menulist.appendChild(menupopup);
var menuitem = document.createElement("menuitem");
menuitem.setAttribute("label",this.getLocalizedString("name"));
menuitem.setAttribute("class","folder-icon");
menuitem.setAttribute("folderid","0");
menuitem.setAttribute("style","padding-left:3px");
menupopup.appendChild(menuitem);
var startIndex = 0;
var folder = root;
var child;
var level = 1;
while (true) {
let children = folder.children;
while (startIndex < children.length) {
child = children[startIndex];
menuitem = document.createElement("menuitem");
menuitem.setAttribute("label",child.name);
menuitem.setAttribute("class","folder-icon");
menuitem.setAttribute("folderid",child.id);
menuitem.setAttribute("style","padding-left:" + (level * 11 + 3) + "px");
menupopup.appendChild(menuitem);
children = child.children;
folder = child;
startIndex = 0;
level++;
}

if (folder.parentNode)
{
startIndex = folder.parentNode.children.indexOf(folder) + 1;
folder = folder.parentNode;
level--;
}
 else
{
break;
}

}

return menulist;
}
,
_exitWithError: function (strErrorType, isEdit) {
this._showError(strErrorType,isEdit);
setTimeout(function () {
window.close();
}
,10);
}
,
__enabled: true,
_getEnabled: function () {
return this.__enabled;
}
,
_setEnabled: function (val) {
this.__enabled = val;
document.documentElement.setAttribute("loading",! val);
var yaru = document.getElementById("yaru-settings");
yaru.enabled = val;
var elements = document.querySelectorAll("textbox,#bookmarks-tags,menulist");
Array.forEach(elements,function (node) {
node.disabled = ! val;
}
);
this.validate();
document.documentElement.getButton("cancel").disabled = ! val;
}
,
_actionCallback: function (data, domXMLResponse) {
var bookmark = this.params.bookmark;
this._setEnabled(true);
var nSaved = parseInt(this.getPref("yaruBookmarksSaved",0),10);
if (nSaved <= 10)
{
nSaved++;
this.setPref("yaruBookmarksSaved",nSaved);
}

this.setPref("lastFolderId",data.parentId);
if (! bookmark.id)
{
data.id = domXMLResponse.querySelector("ok").getAttribute("id");
if (bookmark.type == "link")
{
let yaRu = document.getElementById("yaru-settings");
yaRu.save();
if (this.params.showYaRuWindow && yaRu.exportChecked)
{
document.documentElement.changeMode(data,domXMLResponse);
return;
}

}

}

this.fireEvent("accept",{
bookmarkData: data,
showYaRuWindow: this.params.showYaRuWindow});
setTimeout(function () {
window.close();
}
,10);
}
,
confirmOnYaRuNotAvailable: function () {
var rv = this.utils.showPromptEx(window,this.getLocalizedString("YaRuNotAvailableTitle"),this.getLocalizedString("YaRuNotAvailableMsg"),this.getLocalizedString("YaRuNotAvailableButtonYes"),this.getLocalizedString("YaRuNotAvailableButtonReturn"),null,null,{
});
return ! (rv === 1);
}
,
onDialogAccept: function (isYaRuIncluded) {
var selectedFolder = document.getElementById("bookmarks-folder").selectedItem;
var strNewFolder = document.getElementById("bookmarks-newfolder").value || "", selectedFolderId = selectedFolder.getAttribute("folderid") || 0;
var yaRu = document.getElementById("yaru-settings");
var bookmark = this.params.bookmark;
var services = this.params.services;
var bookmarkUrl = document.getElementById("bookmarks-row-url").hidden != true ? document.getElementById("bookmarks-url").value.trim() : "";
try {
bookmarkUrl = this._URIFixer.createFixupURI(bookmarkUrl,this._URIFixer.FIXUP_FLAG_USE_UTF8).spec;
}
catch (e) {
bookmarkUrl = null;
}

var data = {
id: bookmark.id,
type: bookmark.type,
name: document.getElementById("bookmarks-name").value.trim() || bookmarkUrl,
url: bookmarkUrl,
desc: document.getElementById("bookmarks-desc").value,
tags: document.getElementById("bookmarks-tags").value,
parentId: selectedFolderId};
this._setEnabled(false);
if (strNewFolder)
{
let onSuccess = function (folderId) {
data.parentId = folderId;
if (bookmark.id)
{
this._editBookmark(data,this._actionCallback.bind(this,data));
}
 else
{
data.yaru = isYaRuIncluded ? yaRu.getPostData() : null;
this._addBookmark(data,this._actionCallback.bind(this,data));
}

}
;
services.addBookmarkFolder({
name: strNewFolder,
folder: selectedFolderId},onSuccess.bind(this),this._onError.bind(this));
return false;
}
 else
{
if (bookmark.id)
{
return ! this._editBookmark(data,this._actionCallback.bind(this,data));
}
 else
{
data.yaru = isYaRuIncluded ? yaRu.getPostData() : null;
return ! this._addBookmark(data,this._actionCallback.bind(this,data));
}

}

return true;
}
,
_addBookmark: function (data, callback) {
var services = this.params.services;
if (data.type == "folder")
{
services.addBookmarkFolder(data,callback,this._onError.bind(this));
}
 else
{
services.addBookmark(data,callback,this._onError.bind(this));
}

return true;
}
,
_editBookmark: function (data, callback) {
var bookmark = this.params.bookmark;
var services = this.params.services;
if (bookmark.parentId != data.parentId)
{
let onMoveSuccess = function () {
if (this._isDataChanged(data))
{
services.editBookmark(data,callback,this._onError.bind(this));
}
 else
{
if (callback)
callback(data);
}

}
;
this._moveBookmark(data,onMoveSuccess.bind(this));
return true;
}
 else
{
if (this._isDataChanged(data))
{
services.editBookmark(data,callback,this._onError.bind(this));
return true;
}

}

return false;
}
,
_isDataChanged: function (data) {
var bookmark = this.params.bookmark;
var strStartTags = document.getElementById("bookmarks-tags").startValue;
return bookmark.name != data.name || strStartTags != data.tags || (bookmark.desc || "") != data.desc || (bookmark.url || "") != data.url;
}
,
_moveBookmark: function (data, callback) {
var services = this.params.services;
services.moveBookmark(data,callback,this._onError.bind(this));
}
,
_onError: function (msg) {
if (! msg)
return;
switch (msg.toString()) {
case "wow":
if (this.confirmOnYaRuNotAvailable())
{
this.onDialogAccept(false);
}
 else
{
setTimeout(function () {
window.close();
}
,10);
}

break;
case "reg_required":
let services = this.params.services;
services.subscribe(this.onDialogAccept.bind(this,true),this._onError.bind(this));
break;
default:
let strErrorAlias = "Exception:" + msg;
let bookmark = this.params.bookmark;
this._setEnabled(true);
this._showError(strErrorAlias,! ! bookmark.id);
break;
}

}
,
_showError: function (strError, isEdit) {
if (! strError.indexOf("Exception:"))
{
strError = strError.split(":")[1].trim();
let errorType = "Error_" + strError + "_";
let errorTypeTitle = "Error_" + strError + "_Title";
try {
this.getLocalizedString(errorTypeTitle);
}
catch (ex) {
errorType = "Error_service_";
}

let t1 = [this.getLocalizedString("Action_" + (isEdit ? "edit" : "add") + "_InTitle")];
let t2 = [this.getLocalizedString("Action_" + (isEdit ? "edit" : "add") + "_InMessage")];
if (strError === "input")
{
t2.unshift(t1);
}

this.utils.showAlert(window,this.getLocalizedFormattedString(errorType + "Title",t1),this.getLocalizedFormattedString(errorType + "Message",t2));
return;
}

this.utils.showAlert(window,"Error",strError);
}
,
_URIFixer: Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup)};
