"use strict";
const EXPORTED_SYMBOLS = ["utils"];
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
const utils = {
sendRequest: function yUtils_sendRequest(aUrl, aDetails) {
var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
if (aDetails.background)
request.mozBackgroundRequest = true;
request.open(aDetails.data ? "POST" : "GET",aUrl,true);
if (aDetails.bypassCache)
request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
if (aDetails.data)
{
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
request.setRequestHeader("Connection","close");
}

if (aDetails.referrer)
{
request.setRequestHeader("Referrer",aDetails.referrer);
}

if (aDetails.timeout)
{
request.timeout = aDetails.timeout;
}

if (aDetails.callbackFunc)
{
let target = request.QueryInterface(Ci.nsIDOMEventTarget);
target.addEventListener("load",aDetails.callbackFunc,false);
target.addEventListener("error",aDetails.callbackFunc,false);
target.addEventListener("timeout",aDetails.callbackFunc,false);
}

request.send(aDetails.data || null);
return request;
}
,
tryCreateFixupURI: function yUtils_tryCreateFixupURI(aString) {
const URIFixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
try {
return URIFixup.createFixupURI(aString,URIFixup.FIXUP_FLAG_NONE);
}
catch (e) {

}

return null;
}
,
_VALID_URL_RE: /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+=_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/,
isValidByRegExpURL: function yUtils_isValidByRegExpURL(strURL) {
return this._VALID_URL_RE.test(strURL);
}
,
isValidURL: function yUtils_isValidURL(strURL) {
try {
this.newURI(strURL,null,null);
return true;
}
catch (ex) {

}

return false;
}
,
getSelectionString: function yUtils_getSelectionString(browserWindow, imgHintTpl) {
var focusedWindow = browserWindow.document.commandDispatcher.focusedWindow;
if (focusedWindow == browserWindow)
focusedWindow = browserWindow.content;
if (! focusedWindow)
return undefined;
var selection = focusedWindow.getSelection();
if (selection.isCollapsed || ! selection.rangeCount)
return undefined;
var selRange = selection.getRangeAt(0);
var selContainer = selRange && selRange.commonAncestorContainer ? selRange.commonAncestorContainer : null;
var imageElements = selContainer && selContainer.getElementsByTagNameNS ? Array.slice(selContainer.getElementsByTagNameNS(selContainer.namespaceURI,"img")) : [];
const TMP_ALT_ATTR_NAME = "__yandexBarTmpAlt";
for each(let [, imgElem] in Iterator(imageElements)) {
imgElem.setAttribute(TMP_ALT_ATTR_NAME,imgElem.getAttribute("alt"));
imgElem.setAttribute("alt",imgHintTpl.replace("%url",imgElem.src,"g"));
}

var selectedText = selection.toString();
for each(let [, imgElem] in Iterator(imageElements)) {
imgElem.setAttribute("alt",imgElem.getAttribute(TMP_ALT_ATTR_NAME));
imgElem.removeAttribute(TMP_ALT_ATTR_NAME);
}

return selectedText || undefined;
}
,
getDocumentDescription: function yUtils_getDocumentDescription(aDocument) {
var description = "";
var metaNodes = aDocument.getElementsByTagName("meta");
for (let i = 0, len = metaNodes.length;i < len;i++) {
let metaName = (metaNodes[i].name || "").toLowerCase();
if (metaName == "description" && metaNodes[i].content)
{
description = metaNodes[i].content + "\n\n";
break;
}

}

return description;
}
,
newURI: function yUtils_newURI(spec, origCharset, baseURI) {
return this.ioService.newURI(spec,origCharset,baseURI);
}
,
_ESCAPE_RE: /([.*+?^=!:${}()|[\]\/\\])/g,
escapeRE: function yUtils_escapeRE(aString) {
return String(aString).replace(this._ESCAPE_RE,"\\$1");
}
,
get _UConverter() {
var UConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
UConverter.charset = "UTF-8";
delete this._UConverter;
this.__defineGetter__("_UConverter",function _UConverter() UConverter);
return this._UConverter;
}
,
utf8Tounicode: function yUtils_utf8Tounicode(utf8String) {
return this._UConverter.ConvertToUnicode(utf8String);
}
,
stringEndsWith: function yUtils_stringEndsWith(string, ending) {
return string.substr(- ending.length) === ending;
}
,
getCurrentWindow: function yUtils_getCurrentWindow() {
var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
return wm.getMostRecentWindow("navigator:browser");
}
,
getBrowserHostCookies: function yUtils_getBrowserHostCookies() {
var cookies = {
};
const nsICookie = Ci.nsICookie;
var cookEnum = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager).enumerator;
while (cookEnum.hasMoreElements()) {
let cookie = cookEnum.getNext();
if (! (cookie && cookie instanceof nsICookie))
continue;
let strHost = cookie.host;
if (! cookies[strHost])
cookies[strHost] = [];
let newCookie = Object.create(null);
["name", "host", "path", "expires"].forEach(function (prop) {
newCookie[prop] = cookie[prop];
}
);
try {
newCookie.value = decodeURIComponent(cookie.value);
}
catch (e) {
newCookie.value = cookie.value;
}

cookies[strHost].push(newCookie);
}

return cookies;
}
,
_getHostURIFromURL: function yUtils__getHostURIFromURL(strURL) {
var host = strURL.replace(/^\s*([-\w]*:\/+)?/,"");
return this.newURI("http://" + host);
}
,
showPromptExWithYesNo: function yUtils_showPromptExWithYesNo(parent, strTitle, strText) {
var prompter = this.prompterService;
return this._showPromptEx(parent,strTitle,strText,null,null,null,null,{
value: false},prompter.STD_YES_NO_BUTTONS);
}
,
showPromptEx: function yUtils_showPromptEx(parent, strTitle, strText, strBtnTitle0, strBtnTitle1, strBtnTitle2, strCheckMsg, bCheckState) {
return this._showPromptEx(parent,strTitle,strText,strBtnTitle0,strBtnTitle1,strBtnTitle2,strCheckMsg,bCheckState);
}
,
_showPromptEx: function yUtils__showPromptEx(parent, strTitle, strText, strBtnTitle0, strBtnTitle1, strBtnTitle2, strCheckMsg, bCheckState, initFlags) {
var prompter = this.prompterService;
var flags = (initFlags || 0) + prompter.BUTTON_POS_0_DEFAULT;
if (strBtnTitle0)
{
flags += prompter.BUTTON_POS_0 * prompter.BUTTON_TITLE_IS_STRING;
}

if (strBtnTitle1)
{
flags += prompter.BUTTON_POS_1 * prompter.BUTTON_TITLE_IS_STRING;
}

if (strBtnTitle2)
{
flags += prompter.BUTTON_POS_2 * prompter.BUTTON_TITLE_IS_STRING;
}

var resultCode = prompter.confirmEx(parent,strTitle,strText,flags,strBtnTitle0,strBtnTitle1,strBtnTitle2,strCheckMsg,bCheckState);
return resultCode;
}
,
showPrompt: function yUtils_showPrompt(parent, strTitle, strText) {
return this.prompterService.confirm(parent,strTitle,strText);
}
,
showAlert: function yUtils_showPrompt(parent, strTitle, strText) {
return this.prompterService.alert(parent,strTitle,strText);
}
,
playSound: function yUtils_playSound(strURI) {
try {
let tempLocalFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
tempLocalFile.initWithPath(strURI);
let uri = this.ioService.newFileURI(tempLocalFile);
this.soundService.play(uri);
}
catch (e) {
Cu.reportError("Could not play sound. " + e);
}

}
,
notifyObservers: function yUtils_notifyObservers(strEvent, strState) {
Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService).notifyObservers(null,strEvent,strState);
}
,
getHoverCell: function yUtils_getHoverCell(event, document) {
var docBoxObject = document.documentElement.boxObject;
var x = event.screenX - docBoxObject.screenX;
var y = event.screenY - docBoxObject.screenY;
var row = {
};
var col = {
};
var obj = {
};
var parent = event.originalTarget.parentNode;
parent && parent.treeBoxObject && parent.treeBoxObject.getCellAt(x,y,row,col,obj);
return row.value >= 0 ? {
row: row.value,
column: col.value} : null;
}
,
isReqError: function yUtils_isReqError(req) {
return ! ! (! req || req.type == "error" || ! req.target || req.target.status != 200);
}
,
getNCRndStr: function yUtils_getNCRndStr() {
return "ncrnd=" + (100000 + Math.floor(Math.random() * 899999));
}
,
createXMLString: function yUtils_createXMLString(strXML) {
var str = strXML.replace(/[^\r\n\x9\xA\xD\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]/g,"").replace(/<\?xml .+\?>[\r\n]*/,"").replace(/<!DOCTYPE[^\]]*]>[\r\n]*/,"").replace(/<!DOCTYPE[^>]*>[\r\n]*/,"");
return str;
}
,
cookieService: Cc["@mozilla.org/cookieService;1"].getService().QueryInterface(Ci.nsICookieService),
ioService: Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService),
soundService: Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound),
prompterService: Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService)};
utils.NotificationSource = function NotificationSource() {
this._listeners = {
};
}
;
utils.NotificationSource.prototype = {
constructor: utils.NotificationSource,
addListener: function NotificationSource_addListener(topic, listener) {
if (typeof listener != "object")
throw new TypeError("The listener must be an object");
var topicListeners = this._listeners[topic] || (this._listeners[topic] = []);
if (topicListeners.indexOf(listener) >= 0)
return;
topicListeners.push(listener);
this._listenerAdded(topic,listener);
}
,
removeListener: function NotificationSource_removeListener(topic, listener) {
var topicListeners = this._listeners[topic] || (this._listeners[topic] = []);
if (! topicListeners)
return;
var listenerIdx = topicListeners.indexOf(listener);
if (listenerIdx < 0)
return;
topicListeners.splice(listenerIdx,1);
if (topicListeners.length < 1)
delete this._listeners[topic];
this._listenerRemoved(topic,listener);
}
,
removeAllListeners: function NotificationSource_removeAllListeners() {
if (this._hasListeners)
{
this._listeners = {
};
this._listenerRemoved();
}

}
,
_listeners: null,
get _hasListeners() {
for each(let [topic, list] in Iterator(this._listeners)) {
if (list && list.length)
return true;
}

return false;
}
,
_notifyListeners: function NotificationSource__notifyListeners(topic, data) {
var topicListeners = this._listeners[topic];
if (! topicListeners)
return;
topicListeners.forEach(function NotificationSource__notifyListenersFunc(listener) {
try {
if (this._listeners[topic].indexOf(listener) != - 1)
listener.observe(this,topic,data);
}
catch (e) {
Cu.reportError("Could not notify event listener.\n" + e);
}

}
,this);
}
,
_listenerAdded: function NotificationSource__listenerAdded(topic, listener) {

}
,
_listenerRemoved: function NotificationSource__listenerRemoved(topic, listener) {

}
};
