(function ($) {
var hasIntrospection = (function () {
_;
}
).toString().indexOf("_") > - 1, emptyBase = function () {

}
, objCreate = Object.create || function (ptp) {
var inheritance = function () {

}
;
inheritance.prototype = ptp;
return new inheritance();
}
, needCheckProps = true, testPropObj = {
toString: ""};
for(var i in testPropObj) {
testPropObj.hasOwnProperty(i) && (needCheckProps = false);
}

var specProps = needCheckProps ? ["toString", "valueOf"] : null;
function override(base, result, add) {
var hasSpecProps = false;
if (needCheckProps)
{
var addList = [];
$.each(specProps,function () {
add.hasOwnProperty(this) && (hasSpecProps = true) && addList.push({
name: this,
val: add[this]});
}
);
if (hasSpecProps)
{
$.each(add,function (name) {
addList.push({
name: name,
val: this});
}
);
add = addList;
}

}

$.each(add,function (name, prop) {
if (hasSpecProps)
{
name = prop.name;
prop = prop.val;
}

if ($.isFunction(prop) && (! hasIntrospection || prop.toString().indexOf(".__base") > - 1))
{
var baseMethod = base[name] || function () {

}
;
result[name] = function () {
var baseSaved = this.__base;
this.__base = baseMethod;
var result = prop.apply(this,arguments);
this.__base = baseSaved;
return result;
}
;
}
 else
{
result[name] = prop;
}

}
);
}

$.inherit = function () {
var args = arguments, hasBase = $.isFunction(args[0]), base = hasBase ? args[0] : emptyBase, props = args[hasBase ? 1 : 0] || {
}, staticProps = args[hasBase ? 2 : 1], result = props.__constructor || hasBase && base.prototype.__constructor ? function () {
return this.__constructor.apply(this,arguments);
}
 : function () {

}
;
if (! hasBase)
{
result.prototype = props;
result.prototype.__self = result.prototype.constructor = result;
return $.extend(result,staticProps);
}

$.extend(result,base);
var basePtp = base.prototype, resultPtp = result.prototype = objCreate(basePtp);
resultPtp.__self = resultPtp.constructor = result;
override(basePtp,resultPtp,props);
staticProps && override(base,result,staticProps);
return result;
}
;
$.inheritSelf = function (base, props, staticProps) {
var basePtp = base.prototype;
override(basePtp,basePtp,props);
staticProps && override(base,base,staticProps);
return base;
}
;
}
)(jQuery);
;
(function ($) {
var counter = 0, expando = "__" + + new Date(), get = function () {
return "uniq" + ++counter;
}
;
$.identify = function (obj, onlyGet) {
if (! obj)
return get();
var key = "uniqueID" in obj ? "uniqueID" : expando;
return onlyGet || key in obj ? obj[key] : (obj[key] = get());
}
;
}
)(jQuery);
;
(function ($) {
$.isEmptyObject || ($.isEmptyObject = function (obj) {
for(var i in obj) return false;
return true;
}
);
}
)(jQuery);
;
(function ($) {
$.extend({
debounce: function (fn, timeout, invokeAsap, ctx) {
if (arguments.length == 3 && typeof invokeAsap != "boolean")
{
ctx = invokeAsap;
invokeAsap = false;
}

var timer;
return function () {
var args = arguments;
ctx = ctx || this;
invokeAsap && ! timer && fn.apply(ctx,args);
clearTimeout(timer);
timer = setTimeout(function () {
invokeAsap || fn.apply(ctx,args);
timer = null;
}
,timeout);
}
;
}
,
throttle: function (fn, timeout, ctx) {
var timer, args, needInvoke;
return function () {
args = arguments;
needInvoke = true;
ctx = ctx || this;
timer || (function () {
if (needInvoke)
{
fn.apply(ctx,args);
needInvoke = false;
timer = setTimeout(arguments.callee,timeout);
}
 else
{
timer = null;
}

}
)();
}
;
}
});
}
)(jQuery);
;
(function ($) {
var storageExpando = "__" + + new Date() + "storage", getFnId = function (fn, ctx) {
return $.identify(fn) + (ctx ? $.identify(ctx) : "");
}
, Observable = {
buildEventName: function (e) {
return e;
}
,
on: function (e, data, fn, ctx, _special) {
if (typeof e == "string")
{
if ($.isFunction(data))
{
ctx = fn;
fn = data;
data = undefined;
}

var id = getFnId(fn,ctx), storage = this[storageExpando] || (this[storageExpando] = {
}), eList = e.split(" "), i = 0, eStorage;
while (e = eList[i++]) {
e = this.buildEventName(e);
eStorage = storage[e] || (storage[e] = {
ids: {
},
list: {
}});
if (! (id in eStorage.ids))
{
var list = eStorage.list, item = {
fn: fn,
data: data,
ctx: ctx,
special: _special};
if (list.last)
{
list.last.next = item;
item.prev = list.last;
}
 else
{
list.first = item;
}

eStorage.ids[id] = list.last = item;
}

}

}
 else
{
var _this = this;
$.each(e,function (e, fn) {
_this.on(e,fn,data,_special);
}
);
}

return this;
}
,
onFirst: function (e, data, fn, ctx) {
return this.on(e,data,fn,ctx,{
one: true});
}
,
un: function (e, fn, ctx) {
if (typeof e == "string" || typeof e == "undefined")
{
var storage = this[storageExpando];
if (storage)
{
if (e)
{
var eList = e.split(" "), i = 0, eStorage;
while (e = eList[i++]) {
e = this.buildEventName(e);
if (eStorage = storage[e])
{
if (fn)
{
var id = getFnId(fn,ctx), ids = eStorage.ids;
if (id in ids)
{
var list = eStorage.list, item = ids[id], prev = item.prev, next = item.next;
if (prev)
{
prev.next = next;
}
 else
if (item === list.first)
{
list.first = next;
}

if (next)
{
next.prev = prev;
}
 else
if (item === list.last)
{
list.last = prev;
}

delete ids[id];
}

}
 else
{
delete this[storageExpando][e];
}

}

}

}
 else
{
delete this[storageExpando];
}

}

}
 else
{
var _this = this;
$.each(e,function (e, fn) {
_this.un(e,fn,ctx);
}
);
}

return this;
}
,
trigger: function (e, data) {
var _this = this, storage = _this[storageExpando], rawType;
typeof e === "string" ? (e = $.Event(_this.buildEventName(rawType = e))) : (e.type = _this.buildEventName(rawType = e.type));
e.target || (e.target = _this);
if (storage && (storage = storage[e.type]))
{
var item = storage.list.first, ret;
while (item) {
e.data = item.data;
ret = item.fn.call(item.ctx || _this,e,data);
if (typeof ret !== "undefined")
{
e.result = ret;
if (ret === false)
{
e.preventDefault();
e.stopPropagation();
}

}

item.special && item.special.one && _this.un(rawType,item.fn,item.ctx);
item = item.next;
}

}

return this;
}
};
$.observable = $.inherit(Observable,Observable);
}
)(jQuery);
;
(function ($, undefined) {
var afterCurrentEventFns = [], blocks = {
}, channels = {
};
function buildModFnName(elemName, modName, modVal) {
return (elemName ? "__elem_" + elemName : "") + "__mod" + (modName ? "_" + modName : "") + (modVal ? "_" + modVal : "");
}

function modFnsToProps(modFns, props, elemName) {
$.isFunction(modFns) ? (props[buildModFnName(elemName,"*","*")] = modFns) : $.each(modFns,function (modName, modFn) {
$.isFunction(modFn) ? (props[buildModFnName(elemName,modName,"*")] = modFn) : $.each(modFn,function (modVal, modFn) {
props[buildModFnName(elemName,modName,modVal)] = modFn;
}
);
}
);
}

function buildCheckMod(modName, modVal) {
return modVal ? Array.isArray(modVal) ? function (block) {
var i = 0, len = modVal.length;
while (i < len) if (block.hasMod(modName,modVal[i++]))
return true;
return false;
}
 : function (block) {
return block.hasMod(modName,modVal);
}
 : function (block) {
return block.hasMod(modName);
}
;
}

this.BEM = $.inherit($.observable,{
__constructor: function (mods, params, initImmediately) {
var _this = this;
_this._modCache = mods || {
};
_this._processingMods = {
};
_this._params = params;
_this.params = null;
initImmediately !== false ? _this._init() : _this.afterCurrentEvent(function () {
_this._init();
}
);
}
,
_init: function () {
if (! this._initing && ! this.hasMod("js","inited"))
{
this._initing = true;
if (! this.params)
{
this.params = $.extend(this.getDefaultParams(),this._params);
delete this._params;
}

this.setMod("js","inited");
delete this._initing;
this.hasMod("js","inited") && this.trigger("init");
}

return this;
}
,
changeThis: function (fn, ctx) {
return fn.bind(ctx || this);
}
,
afterCurrentEvent: function (fn, ctx) {
this.__self.afterCurrentEvent(this.changeThis(fn,ctx));
}
,
trigger: function (e, data) {
this.__base(e = this.buildEvent(e),data).__self.trigger(e,data);
return this;
}
,
buildEvent: function (e) {
typeof e == "string" && (e = $.Event(e));
e.block = this;
return e;
}
,
hasMod: function (elem, modName, modVal) {
var len = arguments.length, invert = false;
if (len == 1)
{
modVal = "";
modName = elem;
elem = undefined;
invert = true;
}
 else
if (len == 2)
{
if (typeof elem == "string")
{
modVal = modName;
modName = elem;
elem = undefined;
}
 else
{
modVal = "";
invert = true;
}

}

var res = this.getMod(elem,modName) === modVal;
return invert ? ! res : res;
}
,
getMod: function (elem, modName) {
var type = typeof elem;
if (type === "string" || type === "undefined")
{
modName = elem || modName;
var modCache = this._modCache;
return modName in modCache ? modCache[modName] : (modCache[modName] = this._extractModVal(modName));
}

return this._getElemMod(modName,elem);
}
,
_getElemMod: function (modName, elem, elemName) {
return this._extractModVal(modName,elem,elemName);
}
,
getMods: function (elem) {
var hasElem = elem && typeof elem != "string", _this = this, modNames = [].slice.call(arguments,hasElem ? 1 : 0), res = _this._extractMods(modNames,hasElem ? elem : undefined);
if (! hasElem)
{
modNames.length ? modNames.forEach(function (name) {
_this._modCache[name] = res[name];
}
) : (_this._modCache = res);
}

return res;
}
,
setMod: function (elem, modName, modVal) {
if (typeof modVal == "undefined")
{
modVal = modName;
modName = elem;
elem = undefined;
}

var _this = this;
if (! elem || elem[0])
{
var modId = (elem && elem[0] ? $.identify(elem[0]) : "") + "_" + modName;
if (this._processingMods[modId])
return _this;
var elemName, curModVal = elem ? _this._getElemMod(modName,elem,elemName = _this.__self._extractElemNameFrom(elem)) : _this.getMod(modName);
if (curModVal === modVal)
return _this;
this._processingMods[modId] = true;
var needSetMod = true, modFnParams = [modName, modVal, curModVal];
elem && modFnParams.unshift(elem);
[["*", "*"], [modName, "*"], [modName, modVal]].forEach(function (mod) {
needSetMod = _this._callModFn(elemName,mod[0],mod[1],modFnParams) !== false && needSetMod;
}
);
! elem && needSetMod && (_this._modCache[modName] = modVal);
needSetMod && _this._afterSetMod(modName,modVal,curModVal,elem,elemName);
delete this._processingMods[modId];
}

return _this;
}
,
_afterSetMod: function (modName, modVal, oldModVal, elem, elemName) {

}
,
toggleMod: function (elem, modName, modVal1, modVal2, condition) {
if (typeof elem == "string")
{
condition = modVal2;
modVal2 = modVal1;
modVal1 = modName;
modName = elem;
elem = undefined;
}

if (typeof modVal2 == "undefined")
{
modVal2 = "";
}
 else
if (typeof modVal2 == "boolean")
{
condition = modVal2;
modVal2 = "";
}

var modVal = this.getMod(elem,modName);
(modVal == modVal1 || modVal == modVal2) && this.setMod(elem,modName,typeof condition === "boolean" ? condition ? modVal1 : modVal2 : this.hasMod(elem,modName,modVal1) ? modVal2 : modVal1);
return this;
}
,
delMod: function (elem, modName) {
if (! modName)
{
modName = elem;
elem = undefined;
}

return this.setMod(elem,modName,"");
}
,
_callModFn: function (elemName, modName, modVal, modFnParams) {
var modFnName = buildModFnName(elemName,modName,modVal);
return this[modFnName] ? this[modFnName].apply(this,modFnParams) : undefined;
}
,
_extractModVal: function (modName, elem) {
return "";
}
,
_extractMods: function (modNames, elem) {
return {
};
}
,
channel: function (id, drop) {
return this.__self.channel(id,drop);
}
,
getDefaultParams: function () {
return {
};
}
,
del: function (obj) {
var args = [].slice.call(arguments);
typeof obj == "string" && args.unshift(this);
this.__self.del.apply(this.__self,args);
return this;
}
,
destruct: function () {

}
},{
_name: "i-bem",
blocks: blocks,
decl: function (decl, props, staticProps) {
if (typeof decl == "string")
decl = {
block: decl}; else
if (decl.name)
{
decl.block = decl.name;
}

if (decl.baseBlock && ! blocks[decl.baseBlock])
throw "baseBlock \"" + decl.baseBlock + "\" for \"" + decl.block + "\" is undefined";
props || (props = {
});
if (props.onSetMod)
{
modFnsToProps(props.onSetMod,props);
delete props.onSetMod;
}

if (props.onElemSetMod)
{
$.each(props.onElemSetMod,function (elemName, modFns) {
modFnsToProps(modFns,props,elemName);
}
);
delete props.onElemSetMod;
}

var baseBlock = blocks[decl.baseBlock || decl.block] || this;
if (decl.modName)
{
var checkMod = buildCheckMod(decl.modName,decl.modVal);
$.each(props,function (name, prop) {
$.isFunction(prop) && (props[name] = function () {
var method;
if (checkMod(this))
{
method = prop;
}
 else
{
var baseMethod = baseBlock.prototype[name];
baseMethod && baseMethod !== props[name] && (method = this.__base);
}

return method ? method.apply(this,arguments) : undefined;
}
);
}
);
}

if (staticProps && typeof staticProps.live === "boolean")
{
var live = staticProps.live;
staticProps.live = function () {
return live;
}
;
}

var block;
decl.block == baseBlock._name ? (block = $.inheritSelf(baseBlock,props,staticProps))._processLive(true) : ((block = blocks[decl.block] = $.inherit(baseBlock,props,staticProps))._name = decl.block);
return block;
}
,
_processLive: function (heedLive) {
return false;
}
,
create: function (block, params) {
typeof block == "string" && (block = {
block: block});
return new blocks[block.block](block.mods, params);
}
,
getName: function () {
return this._name;
}
,
_extractElemNameFrom: function (elem) {

}
,
afterCurrentEvent: function (fn, ctx) {
afterCurrentEventFns.push({
fn: fn,
ctx: ctx}) == 1 && setTimeout(this._runAfterCurrentEventFns,0);
}
,
_runAfterCurrentEventFns: function () {
var fnsLen = afterCurrentEventFns.length;
if (fnsLen)
{
var fnObj, fnsCopy = afterCurrentEventFns.splice(0,fnsLen);
while (fnObj = fnsCopy.shift()) fnObj.fn.call(fnObj.ctx || this);
}

}
,
changeThis: function (fn, ctx) {
return fn.bind(ctx || this);
}
,
del: function (obj) {
var delInThis = typeof obj == "string", i = delInThis ? 0 : 1, len = arguments.length;
delInThis && (obj = this);
while (i < len) delete obj[arguments[i++]];
return this;
}
,
channel: function (id, drop) {
if (typeof id == "boolean")
{
drop = id;
id = undefined;
}

id || (id = "default");
if (drop)
{
if (channels[id])
{
channels[id].un();
delete channels[id];
}

return;
}

return channels[id] || (channels[id] = new $.observable());
}
});
}
)(jQuery);
;
(function () {
Object.keys || (Object.keys = function (obj) {
var res = [];
for(var i in obj) obj.hasOwnProperty(i) && res.push(i);
return res;
}
);
}
)();
;
(function () {
var ptp = Array.prototype, toStr = Object.prototype.toString, methods = {
indexOf: function (item, fromIdx) {
fromIdx = + (fromIdx || 0);
var t = this, len = t.length;
if (len > 0 && fromIdx < len)
{
fromIdx = fromIdx < 0 ? Math.ceil(fromIdx) : Math.floor(fromIdx);
fromIdx < - len && (fromIdx = 0);
fromIdx < 0 && (fromIdx = fromIdx + len);
while (fromIdx < len) {
if (fromIdx in t && t[fromIdx] === item)
return fromIdx;
++fromIdx;
}

}

return - 1;
}
,
forEach: function (callback, ctx) {
var i = - 1, t = this, len = t.length;
while (++i < len) i in t && (ctx ? callback.call(ctx,t[i],i,t) : callback(t[i],i,t));
}
,
map: function (callback, ctx) {
var i = - 1, t = this, len = t.length, res = new Array(len);
while (++i < len) i in t && (res[i] = ctx ? callback.call(ctx,t[i],i,t) : callback(t[i],i,t));
return res;
}
,
filter: function (callback, ctx) {
var i = - 1, t = this, len = t.length, res = [];
while (++i < len) i in t && (ctx ? callback.call(ctx,t[i],i,t) : callback(t[i],i,t)) && res.push(t[i]);
return res;
}
,
reduce: function (callback, initialVal) {
var i = - 1, t = this, len = t.length, res;
if (arguments.length < 2)
{
while (++i < len) {
if (i in t)
{
res = t[i];
break;
}

}

}
 else
{
res = initialVal;
}

while (++i < len) i in t && (res = callback(res,t[i],i,t));
return res;
}
,
some: function (callback, ctx) {
var i = - 1, t = this, len = t.length;
while (++i < len) if (i in t && (ctx ? callback.call(ctx,t[i],i,t) : callback(t[i],i,t)))
return true;
return false;
}
,
every: function (callback, ctx) {
var i = - 1, t = this, len = t.length;
while (++i < len) if (i in t && ! (ctx ? callback.call(ctx,t[i],i,t) : callback(t[i],i,t)))
return false;
return true;
}
};
for(var name in methods) ptp[name] || (ptp[name] = methods[name]);
Array.isArray || (Array.isArray = function (obj) {
return toStr.call(obj) === "[object Array]";
}
);
}
)();
;
(function () {
var slice = Array.prototype.slice;
Function.prototype.bind || (Function.prototype.bind = function (ctx) {
var fn = this, args = slice.call(arguments,1);
return function () {
return fn.apply(ctx,args.concat(slice.call(arguments)));
}
;
}
);
}
)();
;
(function (BEM, $, undefined) {
var MOD_DELIM = "_", ELEM_DELIM = "__", NAME_PATTERN = "[a-zA-Z0-9-]+";
function buildModPostfix(modName, modVal, buffer) {
buffer.push(MOD_DELIM,modName,MOD_DELIM,modVal);
}

function buildBlockClass(name, modName, modVal, buffer) {
buffer.push(name);
modVal && buildModPostfix(modName,modVal,buffer);
}

function buildElemClass(block, name, modName, modVal, buffer) {
buildBlockClass(block,undefined,undefined,buffer);
buffer.push(ELEM_DELIM,name);
modVal && buildModPostfix(modName,modVal,buffer);
}

BEM.INTERNAL = {
NAME_PATTERN: NAME_PATTERN,
MOD_DELIM: MOD_DELIM,
ELEM_DELIM: ELEM_DELIM,
buildModPostfix: function (modName, modVal, buffer) {
var res = buffer || [];
buildModPostfix(modName,modVal,res);
return buffer ? res : res.join("");
}
,
buildClass: function (block, elem, modName, modVal, buffer) {
var typeOf = typeof modName;
if (typeOf == "string")
{
if (typeof modVal != "string" && typeof modVal != "number")
{
buffer = modVal;
modVal = modName;
modName = elem;
elem = undefined;
}

}
 else
if (typeOf != "undefined")
{
buffer = modName;
modName = undefined;
}
 else
if (elem && typeof elem != "string")
{
buffer = elem;
elem = undefined;
}

if (! (elem || modName || buffer))
{
return block;
}

var res = buffer || [];
elem ? buildElemClass(block,elem,modName,modVal,res) : buildBlockClass(block,modName,modVal,res);
return buffer ? res : res.join("");
}
,
buildClasses: function (block, elem, mods, buffer) {
if (elem && typeof elem != "string")
{
buffer = mods;
mods = elem;
elem = undefined;
}

var res = buffer || [];
elem ? buildElemClass(block,elem,undefined,undefined,res) : buildBlockClass(block,undefined,undefined,res);
mods && $.each(mods,function (modName, modVal) {
if (modVal)
{
res.push(" ");
elem ? buildElemClass(block,elem,modName,modVal,res) : buildBlockClass(block,modName,modVal,res);
}

}
);
return buffer ? res : res.join("");
}
};
}
)(BEM,jQuery);
;
jQuery.cookie = function (name, value, options) {
if (typeof value != "undefined")
{
options = options || {
};
if (value === null)
{
value = "";
options.expires = - 1;
}

var expires = "";
if (options.expires && (typeof options.expires == "number" || options.expires.toUTCString))
{
var date;
if (typeof options.expires == "number")
{
date = new Date();
date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
}
 else
{
date = options.expires;
}

expires = "; expires=" + date.toUTCString();
}

var path = options.path ? "; path=" + options.path : "";
var domain = options.domain ? "; domain=" + options.domain : "";
var secure = options.secure ? "; secure" : "";
document.cookie = [name, "=", encodeURIComponent(value), expires, path, domain, secure].join("");
}
 else
{
var cookieValue = null;
if (document.cookie && document.cookie != "")
{
var cookies = document.cookie.split(";");
for (var i = 0;i < cookies.length;i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0,name.length + 1) == name + "=")
{
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}

}

}

return cookieValue;
}

}
;
;
(function (BEM, $, undefined) {
var INTERNAL = BEM.INTERNAL, ELEM_DELIM = INTERNAL.ELEM_DELIM, SHORT_TAGS = {
area: 1,
base: 1,
br: 1,
col: 1,
command: 1,
embed: 1,
hr: 1,
img: 1,
input: 1,
keygen: 1,
link: 1,
meta: 1,
param: 1,
source: 1,
wbr: 1}, buildClass = INTERNAL.buildClass, buildClasses = INTERNAL.buildClasses, decls = {
};
function addPropToDecl(decl, name, fn) {
(decl[name] || (decl[name] = [])).unshift(fn);
}

function buildDeclFn(fn, desc) {
return desc.modName ? function (ctx) {
(ctx._curBlock.mods || {
})[desc.modName] === desc.modVal && fn(ctx);
}
 : fn;
}

function join(a, b) {
var isArrayB = $.isArray(b), res;
$.isArray(a) ? isArrayB ? (res = a.concat(b)) : (res = a).push(b) : isArrayB ? (res = b).unshift(a) : (res = [a, b]);
return res;
}

var attrEscapes = {
"\"": "&quot;",
"&": "&amp;",
"<": "&lt;",
">": "&gt;"}, attrEscapesRE = /["&<>]/g;
function escapeAttr(attrVal) {
return attrVal.replace(attrEscapesRE,function (needToEscape) {
return attrEscapes[needToEscape];
}
);
}

BEM.HTML = {
decl: function (desc, props) {
typeof desc == "string" && (desc = {
block: desc});
desc.name && (desc.block = desc.name);
var decl = decls[desc.block] || (decls[desc.block] = {
});
props.onBlock && addPropToDecl(decl,"_block",buildDeclFn(props.onBlock,desc));
if (props.onElem)
{
$.isFunction(props.onElem) ? addPropToDecl(decl,"_elem",buildDeclFn(props.onElem,desc)) : $.each(props.onElem,function (elem, fn) {
addPropToDecl(decl,"_elem" + (elem === "*" ? "" : ELEM_DELIM + elem),buildDeclFn(fn,desc));
}
);
}

}
,
build: function (params) {
var builder = new this.Ctx(params);
builder._buildAll();
return builder._flush();
}
,
Ctx: $.inherit({
__constructor: function (params) {
this._buffer = [];
this._params = params;
this._tParams = null;
this._tParamsChanges = null;
this._curBlock = undefined;
}
,
pos: function () {
return this._params._pos;
}
,
isFirst: function () {
return this._params._pos === 1;
}
,
isLast: function () {
var params = this._params;
return params._pos === params._siblingsCount;
}
,
params: function (params) {
var _this = this;
if (typeof params == "undefined")
return _this._params;
_this._params = params;
return _this;
}
,
param: function (name, val, force, needExtend) {
var _this = this, params = _this._params;
if (typeof val == "undefined")
return params[name];
if (force || ! (name in params))
{
params[name] = val;
}
 else
if (needExtend)
{
params[name] = $.extend(val,params[name]);
}

return _this;
}
,
attrs: function (val, force) {
return this.param("attrs",val,force,true);
}
,
attr: function (name, val, force) {
var _this = this;
if (typeof val == "undefined")
return (_this._params.attrs || {
})[name];
var attrs = _this._params.attrs;
attrs ? (force || ! (name in attrs)) && (attrs[name] = val) : ((_this._params.attrs = {
})[name] = val);
return _this;
}
,
tag: function (val, force) {
return this.param("tag",val,force);
}
,
cls: function (val, force) {
return this.param("cls",val,force);
}
,
mods: function (val, force) {
return this.param("mods",val,force,true);
}
,
mod: function (name, val, force) {
var _this = this;
if (typeof val == "undefined")
return (_this._params.mods || {
})[name];
var mods = _this._params.mods;
mods ? (force || ! (name in mods)) && (mods[name] = val) : ((_this._params.mods = {
})[name] = val);
return _this;
}
,
mix: function (val, force) {
var _this = this, params = _this._params;
if (typeof val == "undefined")
return params.mix;
if (force || ! ("mix" in params))
{
params.mix = val;
}
 else
{
params.mix = params.mix.concat(val);
}

return _this;
}
,
js: function (val) {
return this.param("js",val);
}
,
content: function (val, force) {
return this.param("content",val,force);
}
,
wrapContent: function (obj) {
var _this = this, params = _this._params;
obj.content = params.content;
params.content = obj;
return _this;
}
,
beforeContent: function (obj) {
var _this = this, params = _this._params;
params.content = join(obj,params.content);
return _this;
}
,
afterContent: function (obj) {
var _this = this, params = _this._params;
params.content = join(params.content,obj);
return _this;
}
,
wrap: function (obj) {
var _this = this, params = _this._params;
obj.block || (obj._curBlock = _this._curBlock);
obj.content = params._wrapper ? params._wrapper : params;
params._wrapper = obj;
return _this;
}
,
tParam: function (name, val) {
var _this = this, tParams = _this._tParams || (_this._tParams = {
});
if (typeof val == "undefined")
return tParams[name];
var tParamsChanges = _this._tParamsChanges || (_this._tParamsChanges = {
});
name in tParamsChanges || (tParamsChanges[name] = tParams[name]);
tParams[name] = val;
return _this;
}
,
generateId: function () {
return $.identify();
}
,
stop: function () {
this._params._isStopped = true;
}
,
_buildAll: function () {
var _this = this, buffer = _this._buffer, params = _this._params, paramsType = typeof params;
if (paramsType == "string" || paramsType == "number")
{
buffer.push(params);
}
 else
if ($.isArray(params))
{
var i = 0, len = params.length, currParams, currParamsType;
while (i < len) {
_this._params = currParams = params[i++];
currParamsType = typeof currParams;
if (currParamsType == "string" || currParamsType == "number")
{
buffer.push(currParams);
}
 else
if (currParams)
{
currParams._pos = i;
currParams._siblingsCount = len;
_this._buildByDecl();
}

}

}
 else
if (params)
{
_this._params._pos = _this._params._siblingsCount = 1;
_this._buildByDecl();
}

}
,
_build: function () {
var _this = this, buffer = _this._buffer, params = _this._params, tag = params.tag || "div", jsParams, isBEM = params.block || params.elem, curBlock = isBEM && (params.block || _this._curBlock.block), addInitingCls = false;
if (params.js)
{
(jsParams = {
})[buildClass(curBlock,params.elem)] = params.js === true ? {
} : params.js;
addInitingCls = ! params.elem;
}

buffer.push("<",tag);
if (isBEM || params.cls)
{
buffer.push(" class=\"");
if (isBEM)
{
buildClasses(curBlock,params.elem,params.mods,buffer);
params.mix && $.each(params.mix,function (i, mix) {
if (mix)
{
buffer.push(" ");
buildClasses(mix.block,mix.elem,mix.mods,buffer);
if (mix.js)
{
(jsParams || (jsParams = {
}))[buildClass(mix.block,mix.elem)] = mix.js === true ? {
} : mix.js;
addInitingCls || (addInitingCls = ! mix.elem);
}

}

}
);
}

params.cls && buffer.push(isBEM ? " " : "",params.cls);
addInitingCls && buffer.push(" i-bem");
buffer.push("\"");
}

jsParams && buffer.push(" onclick=\"return ",escapeAttr(JSON.stringify(jsParams)),"\"");
params.attrs && $.each(params.attrs,function (name, val) {
typeof val != "undefined" && val !== null && val !== false && buffer.push(" ",name,"=\"",val.toString().replace(/"/g,"&quot;"),"\"");
}
);
if (SHORT_TAGS[tag])
{
buffer.push("/>");
}
 else
{
buffer.push(">");
if (typeof params.content != "undefined")
{
_this._params = params.content;
_this._buildAll();
}

buffer.push("</",tag,">");
}

}
,
_flush: function () {
var res = this._buffer.join("");
delete this._buffer;
return res;
}
,
_buildByDecl: function () {
var _this = this, currBlock = _this._curBlock, params = _this._params;
params._curBlock && (_this._curBlock = params._curBlock);
params.block && (_this._curBlock = params);
if (! params._wrapper)
{
if (params.block || params.elem)
{
var decl = decls[_this._curBlock.block];
if (decl)
{
var fns;
if (params.elem)
{
fns = decl["_elem" + ELEM_DELIM + params.elem];
decl._elem && (fns = fns ? fns.concat(decl._elem) : decl._elem);
}
 else
{
fns = decl._block;
}

if (fns)
{
var i = 0, fn;
while (fn = fns[i++]) {
fn(_this);
if (params._isStopped)
break;
}

}

}

}

if (params._wrapper)
{
params._curBlock = _this._curBlock;
_this._params = params._wrapper;
return _this._buildAll();
}

}

var tParamsChanges = _this._tParamsChanges;
_this._tParamsChanges = null;
_this._build();
_this._curBlock = currBlock;
if (tParamsChanges)
{
var tParams = _this._tParams;
$.each(tParamsChanges,function (name, val) {
typeof val == "undefined" ? delete tParams[name] : (tParams[name] = val);
}
);
}

}
})};
}
)(BEM,jQuery);
;
(function (undefined) {
if (window.JSON)
return;
var _toString = Object.prototype.toString, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, meta = {
"\b": "\\b",
"\t": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
"\"": "\\\"",
"\\": "\\\\"}, stringify;
window.JSON = {
stringify: stringify = function (val) {
if (val === null)
{
return "null";
}

if (typeof val === "undefined")
{
return undefined;
}

switch (_toString.call(val)) {
case "[object String]":
escapable.lastIndex = 0;
return "\"" + (escapable.test(val) ? val.replace(escapable,function (a) {
var c = meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(- 4);
}
) : val) + "\"";
case "[object Number]":

case "[object Boolean]":
return "" + val;
case "[object Array]":
var res = "[", i = 0, len = val.length, strVal;
while (i < len) {
strVal = stringify(val[i]);
res += (i++ ? "," : "") + (typeof strVal === "undefined" ? "null" : strVal);
}

return res + "]";
case "[object Object]":
if (_toString.call(val.toJSON) === "[object Function]")
{
return stringify(val.toJSON());
}

var res = "{", i = 0, strVal;
for(var key in val) {
if (val.hasOwnProperty(key))
{
strVal = stringify(val[key]);
typeof strVal !== "undefined" && (res += (i++ ? "," : "") + "\"" + key + "\":" + strVal);
}

}

return res + "}";
default:
return undefined;
}

}
};
}
)();
;
(function (BEM, $, undefined) {
var win = $(window), doc = $(document), uniqIdToDomElems = {
}, uniqIdToBlock = {
}, domElemToParams = {
}, liveEventCtxStorage = {
}, liveClassEventStorage = {
}, blocks = BEM.blocks, INTERNAL = BEM.INTERNAL, NAME_PATTERN = INTERNAL.NAME_PATTERN, MOD_DELIM = INTERNAL.MOD_DELIM, ELEM_DELIM = INTERNAL.ELEM_DELIM, buildModPostfix = INTERNAL.buildModPostfix, buildClass = INTERNAL.buildClass;
function init(domElem, uniqInitId) {
var domNode = domElem[0];
$.each(getParams(domNode),function (blockName, params) {
processParams(params,domNode,blockName,uniqInitId);
var block = uniqIdToBlock[params.uniqId];
if (block)
{
if (block.domElem.index(domNode) < 0)
{
block.domElem = block.domElem.add(domElem);
$.extend(block._params,params);
}

}
 else
{
initBlock(blockName,domElem,params);
}

}
);
}

function initBlock(blockName, domElem, params, forceLive, callback) {
if (typeof params == "boolean")
{
callback = forceLive;
forceLive = params;
params = undefined;
}

var domNode = domElem[0];
params = processParams(params || getParams(domNode)[blockName],domNode,blockName);
var uniqId = params.uniqId;
if (uniqIdToBlock[uniqId])
{
return uniqIdToBlock[uniqId]._init();
}

uniqIdToDomElems[uniqId] = uniqIdToDomElems[uniqId] ? uniqIdToDomElems[uniqId].add(domElem) : domElem;
var parentDomNode = domNode.parentNode;
if (! parentDomNode || parentDomNode.nodeType === 11)
{
$.unique(uniqIdToDomElems[uniqId]);
}

var blockClass = blocks[blockName] || DOM.decl(blockName,{
},{
live: true});
if (! (blockClass._liveInitable = ! ! blockClass._processLive()) || forceLive || params.live === false)
{
var block = new blockClass(uniqIdToDomElems[uniqId], params, ! ! forceLive);
delete uniqIdToDomElems[uniqId];
callback && callback.apply(block,Array.prototype.slice.call(arguments,4));
return block;
}

}

function processParams(params, domNode, blockName, uniqInitId) {
(params || (params = {
})).uniqId || (params.uniqId = (params.id ? blockName + "-id-" + params.id : $.identify()) + (uniqInitId || $.identify()));
var domUniqId = $.identify(domNode), domParams = domElemToParams[domUniqId] || (domElemToParams[domUniqId] = {
});
domParams[blockName] || (domParams[blockName] = params);
return params;
}

function findDomElem(ctx, selector, excludeSelf) {
var res = ctx.find(selector);
return excludeSelf ? res : res.add(ctx.filter(selector));
}

function getParams(domNode) {
var uniqId = $.identify(domNode);
return domElemToParams[uniqId] || (domElemToParams[uniqId] = extractParams(domNode));
}

function extractParams(domNode) {
var fn = domNode.onclick || domNode.ondblclick;
if (! fn && domNode.tagName.toLowerCase() == "body")
{
var elem = $(domNode), attr = elem.attr("onclick") || elem.attr("ondblclick");
attr && (fn = Function(attr));
}

return fn ? fn() : {
};
}

function cleanupDomNode(domNode) {
delete domElemToParams[$.identify(domNode)];
}

function removeDomNodeFromBlock(block, domNode) {
block.domElem.length === 1 ? block.destruct(true) : (block.domElem = block.domElem.not(domNode));
}

function getClientNode() {
return doc[0][$.support.boxModel ? "documentElement" : "body"];
}

$.fn.bem = function (blockName, params) {
return initBlock(blockName,this,params,true);
}
;
var DOM = BEM.DOM = BEM.decl("i-bem__dom",{
__constructor: function (domElem, params, initImmediately) {
var _this = this;
_this.domElem = domElem;
_this._eventNameCache = {
};
_this._elemCache = {
};
uniqIdToBlock[_this._uniqId = params.uniqId || $.identify(_this)] = _this;
_this._needSpecialUnbind = false;
_this.__base(null,params,initImmediately);
}
,
findBlocksInside: function (elem, block) {
return this._findBlocks("find",elem,block);
}
,
findBlockInside: function (elem, block) {
return this._findBlocks("find",elem,block,true);
}
,
findBlocksOutside: function (elem, block) {
return this._findBlocks("parents",elem,block);
}
,
findBlockOutside: function (elem, block) {
return this._findBlocks("closest",elem,block)[0] || null;
}
,
findBlocksOn: function (elem, block) {
return this._findBlocks("",elem,block);
}
,
findBlockOn: function (elem, block) {
return this._findBlocks("",elem,block,true);
}
,
_findBlocks: function (select, elem, block, onlyFirst) {
if (! block)
{
block = elem;
elem = undefined;
}

var ctxElem = elem ? typeof elem == "string" ? this.findElem(elem) : elem : this.domElem, isSimpleBlock = typeof block == "string", blockName = isSimpleBlock ? block : block.block || block.blockName, selector = "." + (isSimpleBlock ? buildClass(blockName) : buildClass(blockName,block.modName,block.modVal)) + (onlyFirst ? ":first" : ""), domElems = ctxElem.filter(selector);
select && (domElems = domElems.add(ctxElem[select](selector)));
if (onlyFirst)
{
return domElems[0] ? initBlock(blockName,domElems.eq(0),true) : null;
}

var res = [], uniqIds = {
};
$.each(domElems,function (i, domElem) {
var block = initBlock(blockName,$(domElem),true);
if (! uniqIds[block._uniqId])
{
uniqIds[block._uniqId] = true;
res.push(block);
}

}
);
return res;
}
,
bindToDomElem: function (domElem, event, fn) {
var _this = this;
fn ? domElem.bind(_this._buildEventName(event),function (e) {
(e.data || (e.data = {
})).domElem = $(this);
return fn.apply(_this,arguments);
}
) : $.each(event,function (event, fn) {
_this.bindToDomElem(domElem,event,fn);
}
);
return _this;
}
,
bindToDoc: function (event, fn) {
this._needSpecialUnbind = true;
return this.bindToDomElem(doc,event,fn);
}
,
bindToWin: function (event, fn) {
var _fn = fn, currentHeight, currentWidth;
if (event === "resize")
{
fn = function () {
var height = win.height(), width = win.width();
if (currentHeight !== height || currentWidth !== width)
{
currentHeight = height;
currentWidth = width;
_fn.apply(this,arguments);
}

}
;
}

this._needSpecialUnbind = true;
return this.bindToDomElem(win,event,fn);
}
,
bindTo: function (elem, event, fn) {
if (! event || $.isFunction(event))
{
fn = event;
event = elem;
elem = this.domElem;
}
 else
if (typeof elem == "string")
{
elem = this.elem(elem);
}

return this.bindToDomElem(elem,event,fn);
}
,
unbindFromDomElem: function (domElem, event) {
domElem.unbind(this._buildEventName(event));
return this;
}
,
unbindFromDoc: function (event) {
return this.unbindFromDomElem(doc,event);
}
,
unbindFromWin: function (event) {
return this.unbindFromDomElem(win,event);
}
,
unbindFrom: function (elem, event) {
if (! event)
{
event = elem;
elem = this.domElem;
}
 else
if (typeof elem == "string")
{
elem = this.elem(elem);
}

return this.unbindFromDomElem(elem,event);
}
,
_buildEventName: function (event) {
var _this = this;
return event.indexOf(" ") > 1 ? event.split(" ").map(function (e) {
return _this._buildOneEventName(e);
}
).join(" ") : _this._buildOneEventName(event);
}
,
_buildOneEventName: function (event) {
var _this = this, eventNameCache = _this._eventNameCache;
if (event in eventNameCache)
return eventNameCache[event];
var uniq = "." + _this._uniqId;
if (event.indexOf(".") < 0)
return eventNameCache[event] = event + uniq;
var lego = ".bem_" + _this.__self._name;
return eventNameCache[event] = event.split(".").map(function (e, i) {
return i == 0 ? e + lego : lego + "_" + e;
}
).join("") + uniq;
}
,
trigger: function (e, data) {
this.__base(e = this.buildEvent(e),data).domElem && this._ctxTrigger(e,data);
return this;
}
,
_ctxTrigger: function (e, data) {
var _this = this, storage = liveEventCtxStorage[_this.__self._buildCtxEventName(e.type)], ctxIds = {
};
storage && _this.domElem.each(function () {
var ctx = this, counter = storage.counter;
while (ctx && counter) {
var ctxId = $.identify(ctx,true);
if (ctxId)
{
if (ctxIds[ctxId])
break;
var storageCtx = storage.ctxs[ctxId];
if (storageCtx)
{
$.each(storageCtx,function (uniqId, handler) {
handler.fn.call(handler.ctx || _this,e,data);
}
);
counter--;
}

ctxIds[ctxId] = true;
}

ctx = ctx.parentNode;
}

}
);
}
,
setMod: function (elem, modName, modVal) {
if (elem && typeof modVal != "undefined" && elem.length > 1)
{
var _this = this;
elem.each(function () {
var item = $(this);
item.__bemElemName = elem.__bemElemName;
_this.setMod(item,modName,modVal);
}
);
return _this;
}

return this.__base(elem,modName,modVal);
}
,
_extractModVal: function (modName, elem, elemName) {
var domNode = (elem || this.domElem)[0], matches;
domNode && (matches = domNode.className.match(this.__self._buildModValRE(modName,elemName || elem)));
return matches ? matches[2] : "";
}
,
_extractMods: function (modNames, elem) {
var res = {
}, extractAll = ! modNames.length, countMatched = 0;
((elem || this.domElem)[0].className.match(this.__self._buildModValRE("(" + (extractAll ? NAME_PATTERN : modNames.join("|")) + ")",elem,"g")) || []).forEach(function (className) {
var iModVal = (className = className.trim()).lastIndexOf(MOD_DELIM), iModName = className.substr(0,iModVal - 1).lastIndexOf(MOD_DELIM);
res[className.substr(iModName + 1,iModVal - iModName - 1)] = className.substr(iModVal + 1);
++countMatched;
}
);
countMatched < modNames.length && modNames.forEach(function (modName) {
modName in res || (res[modName] = "");
}
);
return res;
}
,
_afterSetMod: function (modName, modVal, oldModVal, elem, elemName) {
var _self = this.__self, classPrefix = _self._buildModClassPrefix(modName,elemName), classRE = _self._buildModValRE(modName,elemName), needDel = modVal === "";
(elem || this.domElem).each(function () {
var className = this.className;
className.indexOf(classPrefix) > - 1 ? (this.className = className.replace(classRE,needDel ? "" : "$1" + classPrefix + modVal)) : needDel || $(this).addClass(classPrefix + modVal);
}
);
elemName && this.dropElemCache(elemName,modName,oldModVal).dropElemCache(elemName,modName,modVal);
}
,
findElem: function (ctx, names, modName, modVal) {
if (arguments.length % 2)
{
modVal = modName;
modName = names;
names = ctx;
ctx = this.domElem;
}
 else
if (typeof ctx == "string")
{
ctx = this.findElem(ctx);
}

var _self = this.__self, selector = "." + names.split(" ").map(function (name) {
return buildClass(_self._name,name,modName,modVal);
}
).join(",.");
return findDomElem(ctx,selector);
}
,
_elem: function (name, modName, modVal) {
var key = name + buildModPostfix(modName,modVal), res;
if (! (res = this._elemCache[key]))
{
res = this._elemCache[key] = this.findElem(name,modName,modVal);
res.__bemElemName = name;
}

return res;
}
,
elem: function (names, modName, modVal) {
if (modName && typeof modName != "string")
{
modName.__bemElemName = names;
return modName;
}

if (names.indexOf(" ") < 0)
{
return this._elem(names,modName,modVal);
}

var res = $([]), _this = this;
names.split(" ").forEach(function (name) {
res = res.add(_this._elem(name,modName,modVal));
}
);
return res;
}
,
dropElemCache: function (names, modName, modVal) {
if (names)
{
var _this = this, modPostfix = buildModPostfix(modName,modVal);
names.indexOf(" ") < 0 ? delete _this._elemCache[names + modPostfix] : names.split(" ").forEach(function (name) {
delete _this._elemCache[name + modPostfix];
}
);
}
 else
{
this._elemCache = {
};
}

return this;
}
,
elemParams: function (elem) {
var elemName;
if (typeof elem == "string")
{
elemName = elem;
elem = this.elem(elem);
}
 else
{
elemName = this.__self._extractElemNameFrom(elem);
}

return extractParams(elem[0])[buildClass(this.__self.getName(),elemName)] || {
};
}
,
elemify: function (elem, elemName) {
(elem = $(elem)).__bemElemName = elemName;
return elem;
}
,
containsDomElem: function (domElem) {
var res = false;
this.domElem.each(function () {
return ! (res = domElem.parents().andSelf().index(this) > - 1);
}
);
return res;
}
,
buildSelector: function (elem, modName, modVal) {
return this.__self.buildSelector(elem,modName,modVal);
}
,
destruct: function (keepDOM) {
var _this = this, _self = _this.__self;
_this._isDestructing = true;
_this._needSpecialUnbind && _self.doc.add(_self.win).unbind("." + _this._uniqId);
_this.dropElemCache().domElem.each(function (i, domNode) {
var params = getParams(domNode);
$.each(params,function (blockName, blockParams) {
var block = uniqIdToBlock[blockParams.uniqId];
if (block)
{
if (! block._isDestructing)
{
removeDomNodeFromBlock(block,domNode);
delete params[blockName];
}

}
 else
{
delete uniqIdToDomElems[blockParams.uniqId];
}

}
);
$.isEmptyObject(params) && cleanupDomNode(domNode);
}
);
keepDOM || _this.domElem.remove();
delete uniqIdToBlock[_this.un()._uniqId];
delete _this.domElem;
delete _this._elemCache;
_this.__base();
}
},{
scope: null,
doc: doc,
win: win,
_processLive: function (heedLive) {
var _this = this, res = _this._liveInitable;
if ("live" in _this)
{
var noLive = typeof res == "undefined";
if (noLive ^ heedLive)
{
res = _this.live() !== false;
_this.live = function () {

}
;
}

}

return res;
}
,
init: function (ctx, callback, callbackCtx) {
if (! ctx || $.isFunction(ctx))
{
callbackCtx = callback;
callback = ctx;
ctx = doc;
}

var uniqInitId = $.identify();
findDomElem(ctx,".i-bem").each(function () {
init($(this),uniqInitId);
}
);
callback && this.afterCurrentEvent(function () {
callback.call(callbackCtx || this,ctx);
}
);
this._runAfterCurrentEventFns();
return ctx;
}
,
destruct: function (keepDOM, ctx, excludeSelf) {
if (typeof keepDOM != "boolean")
{
excludeSelf = ctx;
ctx = keepDOM;
keepDOM = undefined;
}

findDomElem(ctx,".i-bem",excludeSelf).each(function (i, domNode) {
var params = getParams(this);
$.each(params,function (blockName, blockParams) {
if (blockParams.uniqId)
{
var block = uniqIdToBlock[blockParams.uniqId];
if (block)
{
removeDomNodeFromBlock(block,domNode);
delete params[blockName];
}
 else
{
delete uniqIdToDomElems[blockParams.uniqId];
}

}

}
);
$.isEmptyObject(params) && cleanupDomNode(this);
}
);
keepDOM || (excludeSelf ? ctx.empty() : ctx.remove());
}
,
update: function (ctx, content, callback, callbackCtx) {
this.destruct(ctx,true);
this.init(ctx.html(content),callback,callbackCtx);
}
,
replace: function (ctx, content) {
this.destruct(true,ctx);
this.init($(content).replaceAll(ctx));
}
,
append: function (ctx, content) {
this.init($(content).appendTo(ctx));
}
,
prepend: function (ctx, content) {
this.init($(content).prependTo(ctx));
}
,
before: function (ctx, content) {
this.init($(content).insertBefore(ctx));
}
,
after: function (ctx, content) {
this.init($(content).insertAfter(ctx));
}
,
_buildCtxEventName: function (e) {
return this._name + ":" + e;
}
,
_liveClassBind: function (className, e, callback, invokeOnInit) {
var _this = this;
if (e.indexOf(" ") > - 1)
{
e.split(" ").forEach(function (e) {
_this._liveClassBind(className,e,callback,invokeOnInit);
}
);
}
 else
{
var storage = liveClassEventStorage[e], uniqId = $.identify(callback);
if (! storage)
{
storage = liveClassEventStorage[e] = {
};
doc.bind(e,_this.changeThis(_this._liveClassTrigger,_this));
}

storage = storage[className] || (storage[className] = {
uniqIds: {
},
fns: []});
if (! (uniqId in storage.uniqIds))
{
storage.fns.push({
uniqId: uniqId,
fn: _this._buildLiveEventFn(callback,invokeOnInit)});
storage.uniqIds[uniqId] = storage.fns.length - 1;
}

}

return this;
}
,
_liveClassUnbind: function (className, e, callback) {
var storage = liveClassEventStorage[e];
if (storage)
{
if (callback)
{
if (storage = storage[className])
{
var uniqId = $.identify(callback);
if (uniqId in storage.uniqIds)
{
var i = storage.uniqIds[uniqId], len = storage.fns.length - 1;
storage.fns.splice(i,1);
while (i < len) storage.uniqIds[storage.fns[i++].uniqId] = i - 1;
delete storage.uniqIds[uniqId];
}

}

}
 else
{
delete storage[className];
}

}

return this;
}
,
_liveClassTrigger: function (e) {
var storage = liveClassEventStorage[e.type];
if (storage)
{
var node = e.target, classNames = [];
for(var className in storage) storage.hasOwnProperty(className) && classNames.push(className);
do {
var nodeClassName = " " + node.className + " ", i = 0;
while (className = classNames[i++]) {
if (nodeClassName.indexOf(" " + className + " ") > - 1)
{
var j = 0, fns = storage[className].fns, fn, stopPropagationAndPreventDefault = false;
while (fn = fns[j++]) if (fn.fn.call($(node),e) === false)
stopPropagationAndPreventDefault = true;
stopPropagationAndPreventDefault && e.preventDefault();
if (stopPropagationAndPreventDefault || e.isPropagationStopped())
return;
classNames.splice(--i,1);
}

}

}
 while (classNames.length && (node = node.parentNode));
}

}
,
_buildLiveEventFn: function (callback, invokeOnInit) {
var _this = this;
return function (e) {
var args = [_this._name, ((e.data || (e.data = {
})).domElem = $(this)).closest(_this.buildSelector()), true], block = initBlock.apply(null,invokeOnInit ? args.concat([callback, e]) : args);
if (block && ! invokeOnInit && callback)
return callback.apply(block,arguments);
}
;
}
,
liveInitOnEvent: function (elemName, event, callback) {
return this.liveBindTo(elemName,event,callback,true);
}
,
liveBindTo: function (to, event, callback, invokeOnInit) {
if (! event || $.isFunction(event))
{
callback = event;
event = to;
to = undefined;
}

if (! to || typeof to == "string")
{
to = {
elem: to};
}

to.elemName && (to.elem = to.elemName);
var _this = this;
if (to.elem && to.elem.indexOf(" ") > 0)
{
to.elem.split(" ").forEach(function (elem) {
_this._liveClassBind(buildClass(_this._name,elem,to.modName,to.modVal),event,callback,invokeOnInit);
}
);
return _this;
}

return _this._liveClassBind(buildClass(_this._name,to.elem,to.modName,to.modVal),event,callback,invokeOnInit);
}
,
liveUnbindFrom: function (elem, event, callback) {
var _this = this;
if (elem.indexOf(" ") > 1)
{
elem.split(" ").forEach(function (elem) {
_this._liveClassUnbind(buildClass(_this._name,elem),event,callback);
}
);
return _this;
}

return _this._liveClassUnbind(buildClass(_this._name,elem),event,callback);
}
,
_liveInitOnBlockEvent: function (event, blockName, callback, findFnName) {
var name = this._name;
blocks[blockName].on(event,function (e) {
var args = arguments, blocks = e.block[findFnName](name);
callback && blocks.forEach(function (block) {
callback.apply(block,args);
}
);
}
);
return this;
}
,
liveInitOnBlockEvent: function (event, blockName, callback) {
return this._liveInitOnBlockEvent(event,blockName,callback,"findBlocksOn");
}
,
liveInitOnBlockInsideEvent: function (event, blockName, callback) {
return this._liveInitOnBlockEvent(event,blockName,callback,"findBlocksOutside");
}
,
liveInitOnBlockInit: function (blockName, callback) {
return this.liveInitOnBlockEvent("init",blockName,callback);
}
,
liveInitOnBlockInsideInit: function (blockName, callback) {
return this.liveInitOnBlockInsideEvent("init",blockName,callback);
}
,
on: function (ctx, e, data, fn, fnCtx) {
return ctx.jquery ? this._liveCtxBind(ctx,e,data,fn,fnCtx) : this.__base(ctx,e,data,fn);
}
,
un: function (ctx, e, fn, fnCtx) {
return ctx.jquery ? this._liveCtxUnbind(ctx,e,fn,fnCtx) : this.__base(ctx,e,fn);
}
,
liveCtxBind: function (ctx, e, data, fn, fnCtx) {
return this._liveCtxBind(ctx,e,data,fn,fnCtx);
}
,
_liveCtxBind: function (ctx, e, data, fn, fnCtx) {
var _this = this;
if (typeof e == "string")
{
if ($.isFunction(data))
{
fnCtx = fn;
fn = data;
data = undefined;
}

if (e.indexOf(" ") > - 1)
{
e.split(" ").forEach(function (e) {
_this._liveCtxBind(ctx,e,data,fn,fnCtx);
}
);
}
 else
{
var ctxE = _this._buildCtxEventName(e), storage = liveEventCtxStorage[ctxE] || (liveEventCtxStorage[ctxE] = {
counter: 0,
ctxs: {
}});
ctx.each(function () {
var ctxId = $.identify(this), ctxStorage = storage.ctxs[ctxId];
if (! ctxStorage)
{
ctxStorage = storage.ctxs[ctxId] = {
};
++storage.counter;
}

ctxStorage[$.identify(fn) + (fnCtx ? $.identify(fnCtx) : "")] = {
fn: fn,
data: data,
ctx: fnCtx};
}
);
}

}
 else
{
$.each(e,function (e, fn) {
_this._liveCtxBind(ctx,e,fn,data);
}
);
}

return _this;
}
,
liveCtxUnbind: function (ctx, e, fn, fnCtx) {
return this._liveCtxUnbind(ctx,e,fn,fnCtx);
}
,
_liveCtxUnbind: function (ctx, e, fn, fnCtx) {
var _this = this, storage = liveEventCtxStorage[e = _this._buildCtxEventName(e)];
if (storage)
{
ctx.each(function () {
var ctxId = $.identify(this,true), ctxStorage;
if (ctxId && (ctxStorage = storage.ctxs[ctxId]))
{
fn && delete ctxStorage[$.identify(fn) + (fnCtx ? $.identify(fnCtx) : "")];
if (! fn || $.isEmptyObject(ctxStorage))
{
storage.counter--;
delete storage.ctxs[ctxId];
}

}

}
);
storage.counter || delete liveEventCtxStorage[e];
}

return _this;
}
,
_extractElemNameFrom: function (elem) {
if (elem.__bemElemName)
return elem.__bemElemName;
var matches = elem[0].className.match(this._buildElemNameRE());
return matches ? matches[1] : undefined;
}
,
extractParams: extractParams,
_buildModClassPrefix: function (modName, elem) {
return buildClass(this._name) + (elem ? ELEM_DELIM + (typeof elem === "string" ? elem : this._extractElemNameFrom(elem)) : "") + MOD_DELIM + modName + MOD_DELIM;
}
,
_buildModValRE: function (modName, elem, quantifiers) {
return new RegExp("(\\s|^)" + this._buildModClassPrefix(modName,elem) + "(" + NAME_PATTERN + ")(?=\\s|$)", quantifiers);
}
,
_buildElemNameRE: function () {
return new RegExp(this._name + ELEM_DELIM + "(" + NAME_PATTERN + ")(?:\\s|$)");
}
,
buildSelector: function (elem, modName, modVal) {
return "." + buildClass(this._name,elem,modName,modVal);
}
,
getBlockByUniqId: function (uniqId) {
return uniqIdToBlock[uniqId];
}
,
getWindowSize: function () {
return {
width: win.width(),
height: win.height()};
}
});
$(function () {
BEM.DOM.scope = $("body");
}
);
}
)(BEM,jQuery);
;
(function () {
String.prototype.trim || (String.prototype.trim = function () {
var str = this.replace(/^\s\s*/,""), ws = /\s/, i = str.length;
while (ws.test(str.charAt(--i))) ;
return str.slice(0,i + 1);
}
);
}
)();
;
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.isSessionValid = function () {
return ! ! Lego.getCookie("yandex_login");
}
;
}
)(window.Lego);
;
BEM.DOM.decl("i-global",{
onSetMod: {
"js": function () {
this.del(this.__self._params = $.extend({
},this.params),"uniqId","name");
var params = this.__self._params;
params["passport-msg"] || (params["passport-msg"] = params.id);
if (params["show-counters"] === undefined)
{
params["show-counters"] = Math.round(Math.random() * 100) <= params["show-counters-percent"];
}

params.locale = params.lang;
$(function () {
params.oframebust && Lego.oframebust(params.oframebust);
}
);
}
},
getDefaultParams: function () {
return {
id: "",
login: Lego.isSessionValid() ? $.cookie("yandex_login") || "" : "",
yandexuid: $.cookie("yandexuid"),
lang: "ru",
retpath: window.location.toString(),
"passport-host": "https://passport.yandex.ru",
"pass-host": "//pass.yandex.ru",
"social-host": "//social.yandex.ru",
"lego-path": "/lego",
"show-counters-percent": 100};
}
},{
param: function (name) {
return (this._params || {
})[name];
}
});
;
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
! Lego.params && (Lego.params = {
});
function preparseHost(h) {
return h.replace(/^(?:https?:)?\/\//,"");
}

Lego.c = function (w, a, opts) {
var host = preparseHost(opts && opts.host || BEM.blocks["i-global"].param("click-host") || "clck.yandex.ru"), url = function (w, h, t, a) {
h = h.replace("'","%27");
return h.indexOf("/dtype=") > - 1 ? h : location.protocol + "//" + host + "/" + t + "/dtype=" + w + "/rnd=" + ((new Date()).getTime() + Math.round(Math.random() * 100)) + (a ? "/*" + (h.match(/^http/) ? h : location.protocol + "//" + location.host + (h.match("^/") ? h : "/" + h)) : "/*data=" + encodeURIComponent("url=" + encodeURIComponent(h.match(/^http/) ? h : location.protocol + "//" + location.host + (h.match("^/") ? h : "/" + h))));
}
, click = function () {
var head = document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0];
var script = document.createElement("script");
script.setAttribute("src",url(w,location.href,"jclck"));
head.insertBefore(script,head.firstChild);
}
;
if (a)
{
if (a.className.match(/b-link_pseudo_yes/) || a.href && a.href.match(/^mailto:/) || opts && opts.noRedirect === true)
{
click();
}
 else
if (a.href)
{
var h = a.href;
a.href = url(w,h,"redir");
setTimeout(function () {
a.href = h;
}
,500);
}
 else
if (a.form)
{
if (a.type.match(/submit|button|image/))
{
var h = a.form.action;
a.form.action = url(w,h,"redir",true);
setTimeout(function () {
a.form.action = h;
}
,500);
}
 else
{
click();
}

}
 else
if (a.action)
{
a.action = url(w,a.action,"redir",true);
}
 else
{
throw "counter.js: not link and not form!";
}

}
 else
{
click();
}

}
;
}
)(window.Lego);
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.cp = function (pi, ci, p, a, opts) {
Lego.c("stred/pid=" + pi + "/cid=" + ci + (p ? "/path=" + p : ""),a,opts);
}
;
}
)(window.Lego);
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.ch = function (p, a) {
BEM.blocks["i-global"].param("show-counters") && Lego.cp(0,2219,p,a);
}
;
}
)(window.Lego);
;
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.getCookie = function (n) {
var c = document.cookie;
if (c.length < 1)
return false;
var b = c.indexOf(n + "=");
if (b == - 1)
return false;
b += n.length + 1;
var e = c.indexOf(";",b);
return decodeURIComponent(e == - 1 ? c.substring(b) : c.substring(b,e));
}
;
}
)(window.Lego);
;
(function ($, Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.init || (Lego.init = function (params) {
(params = Lego.params = $.extend({
id: "",
login: Lego.isSessionValid() ? Lego.getCookie("yandex_login") || "" : "",
yandexuid: Lego.getCookie("yandexuid"),
locale: "ru",
retpath: window.location.toString(),
"passport-host": "//passport.yandex.ru",
"pass-host": "//pass.yandex.ru",
"passport-msg": params.id,
"social-host": "//social.yandex.ru",
"lego-path": "/lego",
"show-counters-percent": 100},params,Lego.params))["show-counters"] = Math.round(Math.random() * 100) <= params["show-counters-percent"];
BEM.blocks["i-global"]._params || $.extend(BEM.blocks["i-global"]._params = {
},params);
$(function () {
params.oframebust && Lego.oframebust(params.oframebust);
}
);
return params;
}
);
Lego.block || (Lego.block = {
});
Lego.blockInit || (Lego.blockInit = function (context, blockSelector) {
context = context || document;
blockSelector = blockSelector || ".g-js";
$(context).find(blockSelector).each(function () {
var block = $(this), params = this.onclick ? this.onclick() : {
}, name = params.name || "", init = Lego.block[name];
if (init && ! block.data(name))
{
init.call(block,params);
block.data(name,true).addClass(name + "_js_inited");
}

}
);
}
);
Lego.blockInitBinded || (Lego.blockInitBinded = ! ! $(document).ready(function () {
Lego.blockInit();
}
));
}
)(jQuery,window.Lego);
;
(function (Lego) {
if (! Lego)
Lego = window.Lego = {
};
Lego.messages = Lego.messages || {
};
Lego.message = function (id, text) {
return Lego.params.locale == "ru" ? text : Lego.messages[id] || text;
}
;
}
)(window.Lego);
;
$(function () {
BEM.DOM.init();
}
);
;
(function () {
window.console = window.console;
(function () {
var map = {
"&": "&amp;",
"  ": "&nbsp; ",
"<": "&lt;",
">": "&gt;",
"\n": "<br />",
"\r\n": "<br />",
"\"": "&quot;"};
var map2 = {
"&amp;": "&",
"&nbsp;": " ",
"&lt;": "<",
"&gt;": ">",
"<br />": "\n",
"<br/>": "\n",
"<br>": "\n",
"&quot;": "\""};
var funcReplace = function (str) {
return map[str];
}
;
var funcReplace2 = function (str) {
return map2[str.toLowerCase()];
}
;
String.prototype.toHTML = function () {
return this.replace(/&|  |<|>|\r\n|\n|"|"/g,funcReplace);
}
;
String.prototype.fromHTML = function () {
return this.replace(/&amp;|&nbsp;|&lt;|&gt;|<(br|BR)\s*\/?>|&quot;/g,funcReplace2);
}
;
}
)();
Function.empty = function () {

}
;
Function.prototype.callbackDelay = function (minTimeout) {
if (! minTimeout || minTimeout < 1)
{
return this;
}

var endTime = (new Date()).valueOf() + minTimeout;
var func = this;
return function () {
var interval = endTime - (new Date()).valueOf();
var args = arguments, self = this;
if (interval > 0)
{
setTimeout(function () {
func.apply(self,args);
}
,interval);
}
 else
{
func.apply(self,args);
}

}
;
}
;
BEM.decl("i-widget-helper",{
},{
_localStringPrefix: "",
_initialized: false,
init: function (platform, localStringPrefix) {
if (this._initialized)
{
return this;
}

this._initialized = true;
this._platform = platform;
this._localStringPrefix = localStringPrefix || "";
BEM.I18N.lang(platform.language);
var self = this;
this._helperPlatformListener = function (message) {
if (! message)
{
return;
}

var topic, data;
try {
topic = message.message || message;
data = message.data || null;
self._platform.logger.debug("getMessage::",topic,data);
}
catch (exc) {
self._platform.logger.error("[slice] onMessage: parameter error");
return;
}

self.fireEvent(topic,data);
}
;
this._platform.onMessage.addListener(this._helperPlatformListener);
var notunloaded = true;
function unload() {
if (notunloaded)
{
try {
self.clearInterval();
self._removePlatformListener();
notunloaded = false;
}
catch (exc) {

}

}

}

window.onunload = unload;
window.onbeforeunload = unload;
jQuery.ajaxSetup({
crossDomain: false,
xhr: function () {
return new platform.XMLHttpRequest();
}
});
if (! this._enableContextMenu)
{
document.oncontextmenu = function (e) {
e = e || window.event;
var tag = (e.target || e.srcElement).tagName;
return tag === "INPUT" || tag === "TEXTAREA";
}
;
window.onerror = function (e, ur, ln) {
return false;
}
;
}

;
return this;
}
,
browser: {
isIE: function () {
return /msie/i.test(navigator.userAgent);
}
,
isFF: function () {
return /Firefox/i.test(navigator.userAgent);
}
},
setInterval: function (ms) {
this.clearInterval();
var curtime = (new Date()).valueOf();
var self = this;
this._workTimer = setInterval(function () {
var time = (new Date()).valueOf();
self.fireEvent(":timer",time - curtime);
curtime = time;
}
,ms || 10);
}
,
clearInterval: function () {
if (this._workTimer)
{
clearInterval(this._workTimer);
this._workTimer = null;
}

}
,
logDebug: function (str) {
this._platform.logger.debug(str);
}
,
logError: function (str) {
this._platform.logger.error(str);
}
,
branding: function (conf) {
if (! conf.current)
{
conf.current = {
};
var bran = (conf.branding || {
})[this._platform.brandID];
$.extend(conf.current,conf.common || {
},bran || {
});
}

return conf.current;
}
,
getScript: function (url, callback) {
this.ajax({
type: "GET",
url: url,
success: callback,
dataType: "script"});
}
,
ajax: function (config, attemptsCount) {
attemptsCount = attemptsCount || 1;
if (config.dataType == "script" || config.dataType == "jsonp")
{
config.crossDomain = true;
}

function request() {
attemptsCount--;
return $.ajax(config);
}

if (attemptsCount > 1)
{
var oldError = config.error || Function.empty;
config.error = function () {
if (attemptsCount)
{
request();
}
 else
{
oldError.apply(this,arguments);
}

}
;
}

request();
}
,
getCookie: function (url, name, http) {
if (! /^https?:/.test(url))
{
url = "http://" + url;
}

return this._platform.getCookie(url,name,! ! http);
}
,
openSettings: function () {
if (! window.closed)
{
window.close();
}

this._platform.showSettings();
}
,
parseDate: function (str) {
if (typeof str !== "string" || ! str)
{
return str;
}

var i, part = str.match(/\d+/g);
for (i = 0;i < part.length;++i) {
part[i] = parseInt(part[i],10);
}

return new Date(part[0], part[1] - 1, part[2], part[3], part[4], part[5]);
}
,
openNewTab: function (url) {
this._platform.navigate(url,"new tab");
window.close();
}
,
localStr: function (key) {
var str = this._platform.getLocalizedString(this._localStringPrefix + key) || "";
if (! str)
{
this._platform.logger.error("[slice] getLocalizedString: (" + this.lang() + ") empty string \"" + this._localStringPrefix + key + "\"");
}

return str;
}
,
lang: function () {
return this._platform.language;
}
,
getParam: function (param, url) {
return (RegExp("[?&]" + param + "=([^&#]*)","i").exec(url || document.location.href) || "")[1] || "";
}
,
platformLocalization: function (mainBlock) {
if (mainBlock.platform_i18n)
{
mainBlock.platform_i18n(this);
}

for(var bl in BEM.blocks) {
if (/^b-/.test(bl))
{
var blocks = mainBlock.findBlocksInside(bl);
if (blocks)
{
for (var i = 0;i < blocks.length;++i) {
if (blocks[i].platform_i18n)
{
blocks[i].platform_i18n(this,i);
}

}

}

}

}

}
,
logAction: function (actionCode) {
this._platform.logCustomAction(actionCode);
}
,
_helperPlatformListener: null,
_pltfListeners: {
},
_removePlatformListener: function () {
if (this._helperPlatformListener)
{
this._platform.onMessage.removeListener(this._helperPlatformListener);
this._helperPlatformListener = null;
}

}
,
reloadSlice: function () {
this._removePlatformListener();
window.location.reload(true);
}
,
removeListener: function (topic, callback) {
if (! this._pltfListeners[topic])
{
return;
}

if (! callback)
{
this._pltfListeners[topic] = null;
}
 else
{
var listeners = this._pltfListeners[topic];
for (var i = 0;i < listeners.length;++i) {
if (listeners[i].func == callback)
{
listeners.splice(i,1);
--i;
}

}

}

}
,
addListener: function (topic, callback, scope) {
this._pltfListeners[topic] = this._pltfListeners[topic] || [];
this._pltfListeners[topic].push({
func: callback,
scope: scope});
return this;
}
,
addBlockListeners: function (block) {
var handlers = block.handlers;
if (handlers && ! block.__addBlockListeners_called)
{
for(var i in handlers) {
if (handlers.hasOwnProperty(i))
{
var val = handlers[i];
if (typeof val == "string" && handlers.hasOwnProperty(val))
{
val = handlers[val];
}

if (typeof val == "function")
{
this.addListener(i,val,block);
}

}

}

block.__addBlockListeners_called = true;
}

return this;
}
,
initAllHandlers: function (mainBlock) {
this.addBlockListeners(mainBlock);
for(var bl in BEM.blocks) {
if (/^b-/.test(bl))
{
var blocks = mainBlock.findBlocksInside(bl);
if (blocks)
{
for (var i = 0;i < blocks.length;++i) {
this.addBlockListeners(blocks[i]);
}

}

}
 else
{
if (/^i-/.test(bl))
{
this.addBlockListeners(BEM.blocks[bl]);
}

}

}

}
,
sendMessage: function (msg, data) {
var obj = {
message: msg};
if (data !== undefined)
{
obj.data = data;
}

this._platform.sendMessage(obj);
}
,
fireEvent: function (topic, data) {
var listeners = this._pltfListeners[topic];
if (listeners)
{
for (var i = 0;i < listeners.length;++i) {
var ret = listeners[i].func.call(listeners[i].scope || window,topic,data);
if (ret === false)
{
break;
}

}

}

}
,
md5: function (str, callback, scope) {
this.addListener("md5",function md5Callback(topic, data) {
if (typeof callback === "function")
scope ? callback.call(scope,data) : callback(data);
this.removeListener("md5",md5Callback);
}
,this);
window.platform.sendMessage({
message: "md5",
data: str});
}
,
shuffle: function (inArray) {
var outArray = Array.prototype.slice.call(inArray);
for (var j, x, i = outArray.length;i;(j = parseInt(Math.random() * i), x = outArray[--i], outArray[i] = outArray[j], outArray[j] = x)) ;
return outArray;
}
});
}
)();
;
(function ($) {
BEM.decl("i-widget-mail",{
},{
Error: {
GENERIC: 1,
NETWORK_IS_NOT_AVAILABLE: 2},
Action: {
CLICK_LOGO: 2,
CLICK_COMPOSE_NEW: 3,
CLICK_REFRESH: 4,
CLICK_GO_TO_WEB: 5,
OPEN_MESSAGE: 6,
MESSAGE_ACTION: 7,
CLICK_COLLECTOR_LINK: 9,
CLICK_FOLDER: 8,
HIDE_COLLECTOR_LINK_IN_FOOTER: 10},
_currentUser: null,
init: function (platform) {
"use strict";
this._platform = platform;
this._helper = BEM.blocks["i-widget-helper"];
this._config = BEM.blocks["i-widget-mail__config"].current;
this._platform.resizeWindowTo(this._config.windowSize[0],this._config.windowSize[1]);
this._auth = BEM.blocks["i-yandex-auth"];
this._helper.setInterval(7000);
$(document).on("selectstart",function () {
return false;
}
);
}
,
handlers: {
":timer": function (topic, delta) {
var users = this._auth.getUsers();
for (var i = 0;i < users.length;++i) {
if (users[i].authorized)
{
this._helper.fireEvent("u:timer",users[i]);
}

}

}
},
getLastMessageDate: function (email) {

}
,
setLastMessageDate: function (email, date) {

}
,
prepareURL: function (url, opt_user, opt_noKUBR) {
opt_user = opt_user || this._auth.getUser();
return this.mailDomain(this._addParamToURL(url,{
name: "elmt",
value: "mail"}).replace(/^http:/,"https:"),opt_user,opt_noKUBR);
}
,
mailDomain: function (url, opt_user, opt_noKUBR) {
opt_user = opt_user || this._auth.getUser();
var domain = opt_user.passport;
if (this._config.passportLocaleReplace && ! opt_noKUBR && (this._config.pddKUBR || opt_user.type != "pdd"))
{
var repl = this._config.passportLocaleReplace[this._helper.lang()] || this._config.passportLocaleReplace.all;
if (repl)
{
domain = domain.replace(repl[0],repl[1]);
}

}

if (opt_user.type == "pdd")
{
domain += "/for/" + opt_user.domain;
}

return url.replace(/__maildomain__/g,domain);
}
,
openURL: function (url) {
"use strict";
url = this.prepareURL(url);
this._helper.openNewTab(url);
}
,
_addParamToURL: function (urlString, param) {
"use strict";
var NUMBER_SIGN = "#", QUESTION_MARK = "?", url = urlString, base, queryString, fragment;
var numberSignPosition = url.indexOf(NUMBER_SIGN);
if (- 1 != numberSignPosition)
{
fragment = url.substring(numberSignPosition + 1);
url = url.substring(0,numberSignPosition);
}

var questionMarkPosition = url.indexOf(QUESTION_MARK);
if (- 1 != questionMarkPosition)
{
queryString = url.substring(questionMarkPosition + 1);
url = url.substring(0,questionMarkPosition);
}

base = url;
var params;
if ("undefined" != typeof queryString)
{
params = this._getParamsFromQueryString(queryString);
}
 else
{
params = {
};
}

params[param.name] = param.value;
var newURL = base + QUESTION_MARK + $.param(params);
if ("undefined" != typeof fragment)
{
newURL += NUMBER_SIGN;
newURL += fragment;
}

return newURL;
}
,
_getParamsFromQueryString: function (queryString) {
"use strict";
var params = {
};
var pairs = queryString.split("&");
for (var i = 0, len = pairs.length;i < len;++i) {
var split = pairs[i].split("=");
params[split[0]] = split[1] || "";
}

return params;
}
,
getHumanFriendlyDate: function (dateString) {
"use strict";
var MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
function lpad(str) {
return str < 10 ? "0" + str : str;
}

var date = this._helper.parseDate(dateString);
var now = new Date();
var messageAgeInMilliseconds = Math.abs(now.getTime() - date.getTime());
var prettyDate = "";
if (messageAgeInMilliseconds < MILLISECONDS_IN_DAY && date.getDate() == now.getDate())
{
prettyDate = lpad(date.getHours()) + ":" + lpad(date.getMinutes());
}
 else
if (date.getFullYear() == now.getFullYear())
{
prettyDate = date.getDate() + " " + this._getMonthName(date.getMonth());
}
 else
{
prettyDate = date.getDate() + " " + this._getMonthName(date.getMonth()) + " " + date.getFullYear();
}

return prettyDate;
}
,
_getMonthName: function (monthNumber) {
"use strict";
return BEM.I18N("b-mail-widget","month.g" + (monthNumber + 1)).toLowerCase();
}
});
}
)(jQuery);
;
(function () {
BEM.decl("i-widget-mail__config",{
},{
current: null,
common: {
URL_WEB: "https://mail.__maildomain__/",
URL_COUNTER: "http://export.__maildomain__/for/counters.xml",
URL_USER: "http://export.__maildomain__/for/login.xml",
API_URL_ROOT: "https://mail.__maildomain__/api/",
XIVA_CREDENTIALS_URL: "https://mail.__maildomain__/neo2/handlers/xiva_sub.jsx",
XIVA_CONNECT_URL: "https://xiva-daria.mail.yandex.net/events/iframe",
maxVisibleMsgCount: 20,
pddKUBR: false,
passportLocaleReplace: {
uk: ["yandex.ru", "yandex.ua"],
be: ["yandex.ru", "yandex.by"],
kk: ["yandex.ru", "yandex.kz"]},
windowSize: [740, 390]},
branding: {
tb: {
},
ua: {
passportLocaleReplace: {
all: [/yandex\.(ru|by|kz)/, "yandex.ua"]}}}});
}
)();
;
(function () {
BEM.decl("i-yandex-auth",{
},{
_KnownMessages: {
USER_GET_ALL: "user.get_all",
USER_GET_ACTIVE: "user.get_active",
USER_LOGOUT: "user.logout",
USER_LOGIN: "user.login",
USER_LOGOUT_ALL: "user.logout_all",
AUTH_GET_ALL_NOTIFY: "auth:get_all_notify",
AUTH_USERS: "auth:users",
AUTH_REMOVE_USERS: "auth:remove_users",
AUTH_CURRENT: "auth:current",
AUTH_RENAME: "auth:rename",
AUTH_LOGIN: "auth:login",
AUTH_LOGIN_LOST: "auth:login_lost",
AUTH_LOGOUT: "auth:logout"},
_maxUsersCount: 10000,
init: function () {
this._helper = BEM.blocks["i-widget-helper"];
this._sequence = 0;
this._users = [];
this._currentUser = null;
}
,
_ensureMaxUsersCount: function (users) {
users = users || this._users;
var deleted = [];
if (! users || users.length <= this._maxUsersCount)
{
return deleted;
}

for (var i = users.length - 1;i >= 0;--i) {
if (! users[i].authorized)
{
deleted.push(users[i]);
users.splice(i,1);
if (users.length <= this._maxUsersCount)
{
break;
}

}

}

return deleted;
}
,
_createUser: function (user) {
var soc = user.social;
return {
login: user.login,
type: user.type,
domain: user.domain,
passport: user.passport,
social: soc && soc != "" ? soc : false,
data: {
},
email: this.normalizeEMail(user.login + "@" + (user.domain || user.passport)),
id: (++this._sequence).toString(10),
displayLogin: user.login,
displayEmail: user.login + "@" + (user.domain || user.passport),
displayChanged: false};
}
,
handlers: {
"user.get_all": function (topic, users) {
if (! users.length)
{
return;
}

var jsusers = [], eMails = {
};
var i, newCurrent = null;
for (i = 0;i < users.length;++i) {
var email = users[i].login + "@" + users[i].domain;
eMails[this.normalizeEMail(email)] = true;
var user = this.getUserByEmail(email,false);
if (! user)
{
user = this._createUser(users[i]);
user.authorized = users[i].authorized;
user.isCurrent = false;
if (user.authorized)
{
if (user.type == "yandex" || ! newCurrent)
{
newCurrent = user;
}

}

jsusers.push(user);
this._users.push(user);
}

}

if (! this._currentUser)
{
newCurrent.isCurrent = true;
this._currentUser = newCurrent;
}

var deleted = [];
for (var i = this._users.length - 1;i >= 0;--i) {
if (! this._users[i].authorized && ! eMails[this._users[i].email])
{
deleted.push(this._users[i]);
this._users.splice(i,1);
}

}

if (jsusers.length)
{
this._helper.fireEvent(this._KnownMessages.AUTH_USERS,jsusers);
}

if (deleted.length)
{
this._helper.fireEvent(this._KnownMessages.AUTH_REMOVE_USERS,deleted);
}

for (i = 0;i < jsusers.length;++i) {
if (jsusers[i].authorized)
{
this._helper.fireEvent(this._KnownMessages.AUTH_LOGIN,jsusers[i]);
}

}

}
,
"user.login": function (topic, users) {
var newUsers = [];
var i, auth = [];
for (i = 0;i < users.length;++i) {
var email = users[i].login + "@" + users[i].domain;
var user = this.getUserByEmail(email,false);
if (user)
{
if (! user.authorized)
{
auth.push(user);
user.authorized = true;
}

}
 else
{
user = this._createUser(users[i]);
user.isCurrent = false;
user.authorized = true;
this._users.push(user);
newUsers.push(user);
auth.push(user);
}

}

var deleted = this._ensureMaxUsersCount();
if (deleted.length)
{
this._helper.fireEvent(this._KnownMessages.AUTH_REMOVE_USERS,deleted);
}

if (newUsers.length)
{
this._helper.fireEvent(this._KnownMessages.AUTH_USERS,newUsers);
}

if (auth.length)
{
var newCurrent = auth[0];
newCurrent.isCurrent = true;
newCurrent.oldCurrent = this._currentUser;
if (this._currentUser)
{
this._currentUser.isCurrent = false;
}

this._currentUser = newCurrent;
for (i = 0;i < auth.length;++i) {
this._helper.fireEvent(this._KnownMessages.AUTH_LOGIN,auth[i]);
}

newCurrent.oldCurrent = null;
}

}
,
"user.logout": function (topic, users) {
var i, lu = [];
var deleted = [];
for (i = 0;i < users.length;++i) {
var email = users[i].login + "@" + users[i].domain;
var user = this.getUserByEmail(email,false,true);
if (user.user && user.user.authorized)
{
lu.push(user.user);
if (user.user.social)
{
deleted.push(user.user);
this._users.splice(user.idx,1);
}

user.user.authorized = false;
user.user.isCurrent = false;
}
 else
{

}

}

if (this._currentUser && ! this._currentUser.isCurrent)
{
var newCurrent = null;
for (i = 0;i < this._users.length;++i) {
if (this._users[i].authorized)
{
if (this._users[i].type == "yandex" || ! newCurrent)
{
newCurrent = this._users[i];
}

}

}

this.setCurrentUser(newCurrent,true);
}

for (i = 0;i < lu.length;++i) {
this._helper.fireEvent(this._KnownMessages.AUTH_LOGOUT,lu[i]);
}

if (deleted.length)
{
this._helper.fireEvent(this._KnownMessages.AUTH_REMOVE_USERS,deleted);
}

}
},
setCurrentUser: function (user, allowNull) {
if (typeof user == "string")
{
user = this.getUser(user);
}

if (! user && ! allowNull)
{
return;
}

if (user != this._currentUser)
{
if (user && ! user.authorized)
{
this.login(user);
return;
}

var oldUser = this._currentUser;
if (oldUser)
{
oldUser.isCurrent = false;
}

this._currentUser = user;
if (user)
{
user.isCurrent = true;
}

this._helper.fireEvent(this._KnownMessages.AUTH_CURRENT,{
current: user,
oldCurrent: oldUser});
}

}
,
loginLost: function (user) {
if (! user.authorized)
{
return;
}

this._helper.fireEvent(this._KnownMessages.AUTH_LOGIN_LOST,user);
}
,
setDisplayLogin: function (user, newLogin) {
if (typeof user == "string")
{
user = this.getUser(user);
}

if (user)
{
user.displayEmail = newLogin;
user.displayChanged = true;
this._helper.fireEvent(this._KnownMessages.AUTH_RENAME,user);
}

}
,
_yandexMailDomains: {
"yandex.ru": true,
"yandex.by": true,
"yandex.ua": true,
"yandex.kz": true,
"yandex.com": true,
"yandex.com.tr": true,
"ya.ru": true,
"narod.ru": true},
normalizeEMail: function (email) {
if (! email)
{
return "";
}

var arr = email.split("@");
return this._yandexMailDomains[arr[1]] ? arr[0].replace(/-/g,".") + "@yandex.ru" : email;
}
,
getUserByEmail: function (email, isDisplay, getIdx) {
if (! email || ! this._users)
{
return getIdx ? {
user: this._currentUser,
idx: - 1} : this._currentUser;
}

var f = isDisplay ? "displayEmail" : "email";
if (! isDisplay)
{
email = this.normalizeEMail(email);
}

for (var i = 0;i < this._users.length;++i) {
if (this._users[i][f] == email)
{
return getIdx ? {
user: this._users[i],
idx: i} : this._users[i];
}

}

return getIdx ? {
user: null,
idx: - 1} : null;
}
,
updateUserData: function (actives) {
this._helper.sendMessage(this._KnownMessages[actives ? "USER_GET_ACTIVE" : "USER_GET_ALL"]);
}
,
login: function (opt_user) {
if (typeof opt_user == "string")
{
opt_user = this.getUser(opt_user);
}

this._helper.sendMessage(this._KnownMessages.USER_LOGIN,{
login: opt_user ? opt_user.login : "",
type: opt_user ? opt_user.type : "",
domain: opt_user ? opt_user.domain : ""});
}
,
logout: function (user) {
if (typeof user == "string")
{
user = this.getUser(user);
}

if (user)
{
this._helper.sendMessage(this._KnownMessages.USER_LOGOUT,{
login: user.login,
type: user.type,
domain: user.domain});
}

}
,
logoutAll: function () {
this._helper.sendMessage(this._KnownMessages.USER_LOGOUT_ALL);
}
,
getMailAddress: function () {
var user = this.getUser();
return null !== user ? user.email : "";
}
,
getYandexDomain: function () {
var user = this.getUser();
return null !== user ? user.domain : "";
}
,
getUser: function (id) {
if (! id || ! this._users)
{
return this._currentUser;
}

for (var i = 0;i < this._users.length;++i) {
if (this._users[i].id == id)
{
return this._users[i];
}

}

return null;
}
,
getUsers: function () {
return this._users;
}
});
}
)();
;
(function ($) {
BEM.decl("i-yandex-mail-api",{
},{
_REQUEST_TIMEOUT_IN_SECONDS: 10,
init: function () {
this._config = BEM.blocks["i-widget-mail__config"].current;
this._helper = BEM.blocks["i-widget-helper"];
this._widget = BEM.blocks["i-widget-mail"];
}
,
getMessagesInFolder: function (user, count, successCallback, opt_errorCallback, opt_tryCount) {
var self = this;
var params = {
first: 0,
last: count,
extra_cond: "only_new",
"goto": "all"};
this.request("GET","mailbox_list",user,params,function (xml) {
self._handleMessagesListResponse(user,xml,successCallback,opt_errorCallback);
}
,opt_errorCallback,opt_tryCount || 3);
}
,
_isLogout: function (xml) {
return $("authProcedure>error[code=\"2001\"]",xml).length > 0;
}
,
_handleMessagesListResponse: function (user, xml, successCallback, errorCallback) {
var data;
try {
data = this._extractMessagesDataFromXML(user,xml);
}
catch (e) {

}

if (! data)
{
errorCallback();
}
 else
{
successCallback(data.folder,data.messages);
}

}
,
_extractMessagesDataFromXML: function (user, xml) {
"use strict";
var doc = $(xml);
var messagesNodes = $("mailbox_list>message",doc);
var messages = [];
user.data.apiFolderList = this._extractFoldersListFromXML(xml);
var folderList = user.data.apiFolderList;
var self = this;
$.each(messagesNodes,function (index, messageNode) {
messageNode = $(messageNode);
var fold = folderList.map[messageNode.attr("fid")];
if (fold && fold.ignoreMsgList)
{
return;
}

var message = {
};
message.id = messageNode.attr("mid");
var fromNode = $("from",messageNode);
message.sender = {
name: $("name",fromNode).text(),
email: $("email",fromNode).text()};
message.subject = $("subject text",messageNode).text();
message.firstline = $("firstline",messageNode).text();
message.date = messageNode.attr("date");
message.isUnread = messageNode.attr("status") === "New";
message.hasAttach = messageNode.attr("att_count") > 0;
message.url = self._widget.mailDomain(self._config.URL_WEB + "message?ids=",user) + messageNode.attr("mid");
messages.push(message);
}
);
var foldersDetailsNode = $("details",doc);
var folder = {
name: foldersDetailsNode.attr("name"),
page: foldersDetailsNode.attr("page_number"),
messagesCount: parseInt(foldersDetailsNode.attr("msg_count"),10),
unreadCount: folderList.unreadCount};
return {
folder: folder,
messages: messages};
}
,
getFoldersList: function (user, successCallback, errorCallback, opt_fromCache) {
"use strict";
var self = this;
if (opt_fromCache && user.data.apiFolderList)
{
successCallback(user.data.apiFolderList);
return;
}

this.request("GET","folder_list",user,function (xml) {
if ($("authProcedure>error",xml).length > 0)
{
successCallback({
user: user,
loginLost: true});
return;
}

user.data.apiFolderList = self._extractFoldersListFromXML(xml);
successCallback(user.data.apiFolderList);
}
,errorCallback);
}
,
_extractFoldersListFromXML: function (xml) {
"use strict";
var doc = $(xml);
var folderNodes = $("folder_list>folder",doc);
var folders = [];
var map = {
};
var ignoreUnreadCountFids = {
outbox: true,
sent: true,
spam: true,
trash: true,
draft: true};
var unreadCount = 0;
$.each(folderNodes,function (index, folderNode) {
folderNode = $(folderNode);
var folder = {
};
folder.id = $("fid",folderNode).text();
folder.special = $("special",folderNode).text();
folder.symbol = $("symbol",folderNode).text();
folder.name = $("name",folderNode).text();
folder.messages = {
total: $("count",folderNode).text(),
"new": $("new",folderNode).text() || "0"};
folder.ignoreXivaInsert = ignoreUnreadCountFids[folder.symbol] || false;
folder.ignoreMsgList = ignoreUnreadCountFids[folder.symbol] || false;
folder.unreadCount = folder.ignoreMsgList ? 0 : parseInt(folder.messages.new,10);
folders.push(folder);
map[folder.id] = folder;
unreadCount += folder.unreadCount;
}
);
return {
list: folders,
map: map,
unreadCount: unreadCount};
}
,
markMessageAsRead: function (user, messageId, callback) {
this.request("POST","mailbox_oper",user,{
ids: messageId,
oper: "mark_read"},callback);
}
,
markMessageAsSpam: function (user, messageId, callback) {
"use strict";
this.request("POST","mailbox_oper",user,{
ids: messageId,
oper: "tospam"},callback);
}
,
deleteMessage: function (user, messageId, callback) {
"use strict";
this.request("POST","mailbox_oper",user,{
ids: messageId,
oper: "delete"},callback);
}
,
getCounterInfo: function (user, callback, errback) {
errback = errback || Function.empty;
this._helper.ajax({
cache: false,
data: {
services: 43},
dataType: "xml",
error: errback,
success: function (data) {
var mail = $("mail",data);
if (mail.attr("e"))
{
callback({
user: user,
loginLost: true});
return;
}

var count = mail.attr("v");
if (/^\d+$/.test(count))
{
var c = mail.parent();
callback({
user: user,
count: parseInt(count,10),
login: c.attr("l") || "",
name: c.attr("d") || "",
type: c.attr("p") || ""});
}
 else
{
var s = $("s",data);
count = s.attr("v");
var l = s.attr("l");
if (count && l)
{
callback({
user: user,
count: parseInt(count,10),
login: l,
name: "",
type: ""});
}
 else
{
callback({
user: user,
loginLost: true});
}

}

}
,
timeout: this._REQUEST_TIMEOUT_IN_SECONDS * 1000,
type: "GET",
url: this._widget.mailDomain(this._config.URL_COUNTER,user,true)},1);
}
,
getUserSettings: function (user, callback, errback) {
this.request("GET","settings_setup",user,{
},function (xml) {
if ($("yamail>authProcedure>error",xml).length > 0)
{
callback({
user: user,
loginLost: true});
return;
}

var email = $("body>default_email",xml).text();
var name = $("body>from_name",xml).text();
callback({
user: user,
email: email,
name: name});
}
,errback);
}
,
resetYandexUID: function (user, callback) {
this._helper.ajax({
url: this._widget.mailDomain(this._config.URL_USER,user,true),
data: {
_rand: (new Date()).valueOf()},
success: function () {
callback(true);
}
,
error: function () {
callback(false);
}
},2);
}
,
request: function (httpMethod, apiMethod, user, opt_params, opt_successCallback, opt_errorCallback, opt_tryCount) {
var params;
if ("object" == typeof opt_params)
{
params = opt_params;
}
 else
if ("function" == typeof opt_params)
{
opt_errorCallback = opt_successCallback;
opt_successCallback = opt_params;
}

if ("undefined" === typeof params || null === params)
{
params = {
elmt: "mail"};
}
 else
{
params.elmt = "mail";
}

params._rand = (new Date()).valueOf();
params.uid = this._helper.getCookie(user.passport,"yandexuid") || "";
var successCallback = null, errorCallback = null;
if ("function" == typeof opt_successCallback)
{
successCallback = opt_successCallback;
}

if ("function" == typeof opt_errorCallback)
{
errorCallback = opt_errorCallback;
}

var requestURL = this._getRequestURL(apiMethod);
this._helper.ajax({
data: params,
dataType: "xml",
error: errorCallback,
success: successCallback,
timeout: this._REQUEST_TIMEOUT_IN_SECONDS * 1000,
type: httpMethod,
url: this._widget.mailDomain(requestURL,user,true)},opt_tryCount || 1);
}
,
_getRequestURL: function (methodName) {
"use strict";
return this._config.API_URL_ROOT + methodName;
}
});
}
)(jQuery);
;
(function ($) {
BEM.decl("i-yandex-mail-notifications",{
},{
_KnownMessages: {
MSG: "xiva:msg",
TIMEOUT: "xiva:timeout",
ERROR: "xiva:error"},
_offline: {
_interval: 20000,
_onlineInterval: 2000,
init: function (helper) {
this._helper = helper;
}
,
start: function (user) {
user.data.xivaStartOffline = (new Date()).valueOf();
}
,
connect: function (user) {
var date = (new Date()).valueOf();
var dateStartOffline = user.data.xivaStartOffline;
if (date - dateStartOffline > this._interval)
{
this.start(user);
this._helper.fireEvent("xiva:timeout",user);
}

user.data.xivaStartOnline = date;
}
,
error: function (user) {
var date = (new Date()).valueOf();
var dateStartOffline = user.data.xivaStartOffline;
if (date - user.data.xivaStartOnline > this._onlineInterval)
{
this.start(user);
}

}
},
init: function () {
this._helper = BEM.blocks["i-widget-helper"];
this._widget = BEM.blocks["i-widget-mail"];
this._auth = BEM.blocks["i-yandex-auth"];
this._config = BEM.blocks["i-widget-mail__config"].current;
this._api = BEM.blocks["i-yandex-mail-api"];
this._offline.init(this._helper);
}
,
handlers: {
"u:timer": function (t, user) {
this._ensureWork(user);
}
,
"auth:login_lost": function (t, user) {
this._abortConnection(user);
user.data.xivaLoginLost = true;
}
,
"mail-before-popup": function () {
var users = this._auth.getUsers();
var curtime = (new Date()).valueOf();
for (var i = 0;i < users.length;++i) {
if (users[i].authorized)
{
users[i].data.xivaRefreshInterval = 0;
users[i].data.xivaXEInterval = 0;
if (users[i].data.xivaRefreshTime && users[i].data.xivaRefreshTime - curtime > 15000 || users[i].data.xivaLoginLost)
{
users[i].data.xivaRefreshTime = 7000;
}

users[i].data.xivaLoginLost = false;
}

}

}
,
"auth:login": function (topic, user) {
user.data.xivaUpdatingYAUID = false;
user.data.xivaLoginLost = false;
user.data.xivaXEInterval = 0;
this._setRefreshTime(user,0);
this._connect(user);
}
,
"auth:logout": function (topic, user) {
this._abortConnection(user);
this._setXivaCredentials(user,null);
}
},
_ensureWork: function (user) {
if (! user.authorized)
{
return;
}

var curtime = (new Date()).valueOf();
if (user.data.xivaRefreshTime && curtime >= user.data.xivaRefreshTime)
{
this._connect(user);
}

}
,
_setRefreshTime: function (user, delay, test, type) {
if (test && user.data.xivaRefreshTime)
{
return;
}

type = "xiva" + (type || "Refresh");
var pInt = type + "Interval";
if (! delay)
{
user.data[pInt] = 0;
user.data.xivaRefreshTime = 0;
return;
}

if (delay < 0)
{
delay = user.data[pInt] || 6000;
var maxDelay = type == "XE" ? 300000 : 700000;
if (delay < maxDelay)
{
user.data[pInt] = Math.min(Math.round(delay * 1.5),maxDelay);
}

}
 else
{
user.data[pInt] = 0;
}

user.data.xivaRefreshTime = (new Date()).valueOf() + delay;
}
,
_connect: function (user, opt_delay) {
user.data.xivaRefreshTime = 0;
if (user.data.xivaConnection)
{
return;
}

var delay = "number" === typeof opt_delay ? Math.max(1,opt_delay) : 0;
var attemptsCount = 0;
var self = this;
var connect = function () {
if (! user.authorized || user.data.xivaLoginLost)
{
return;
}

var credentials = self._getXivaCredentials(user);
if (credentials)
{
self._offline.connect(user);
user.data.xivaConnection = $.ajax({
url: self._widget.mailDomain(self._config.XIVA_CONNECT_URL),
dataType: "json",
data: {
_rand: Math.random(),
single: "1",
client_id: "bar",
service: "mail",
uid: credentials.uid,
sign: credentials.sign,
ts: credentials.ts},
timeout: 180000,
success: function (data) {
var jqXHR = user.data.xivaConnection;
user.data.xivaConnection = null;
if (data && data.lcn)
{
self._offline.start(user);
self._handleXivaConnectionResponse(user,data);
}
 else
{
self._offline.error(user);
self._handleXivaConnectionError(user,0,"",jqXHR);
}

}
,
error: function (jqXHR, textStatus) {
user.data.xivaConnection = null;
self._offline.error(user);
var status = jqXHR.status;
self._handleXivaConnectionError(user,status > 600 ? 0 : status,textStatus,jqXHR);
}
});
}
 else
{
if (attemptsCount < 3)
{
attemptsCount++;
self._requestXivaCredentials(user,connect);
}
 else
{
self._setRefreshTime(user,- 1);
}

}

}
;
if (delay)
{
self._setRefreshTime(user,delay);
}
 else
{
connect();
}

}
,
_abortConnection: function (user) {
if (user.data.xivaConnection && user.data.xivaConnection.readyState !== 4)
{
user.data.xivaConnection.abort();
}

user.data.xivaConnection = null;
}
,
_requestXivaCredentials: function (user, callback) {
if (! user.authorized)
{
callback();
return;
}

user.data.xivaLCN = null;
var self = this;
var yandexuid = self._helper.getCookie(user.passport,"yandexuid");
this._helper.ajax({
url: self._widget.mailDomain(self._config.XIVA_CREDENTIALS_URL,user,true),
dataType: "json",
data: {
_rand: (new Date()).valueOf(),
req: yandexuid},
success: function (credentials) {
if (credentials && credentials.code == "AUTH_NO_AUTH")
{
self._updateYAUID(user);
return;
}

self._setXivaCredentials(user,credentials);
callback();
}
,
error: function (jqXHR) {
var status = jqXHR.status;
if (status == 0 || status >= 600)
{
self._helper.fireEvent(self._KnownMessages.ERROR,user);
}

self._setRefreshTime(user,- 1,true);
}
},1);
}
,
_updateYAUID: function (user) {
user.data.xivaUpdatingYAUID = true;
if (! this._updatingYAUID)
{
this._updatingYAUID = true;
var self = this;
this._api.getCounterInfo(user,function (ret) {
self._updatingYAUID = false;
if (ret.loginLost)
{
self._auth.loginLost(user);
}

var users = self._auth.getUsers();
for (var i = 0;i < users.length;++i) {
if (users[i].authorized && users[i].data.xivaUpdatingYAUID)
{
users[i].data.xivaUpdatingYAUID = false;
self._setRefreshTime(users[i],- 1,true);
}

}

}
,function () {
self._updatingYAUID = false;
var users = self._auth.getUsers();
for (var i = 0;i < users.length;++i) {
if (users[i].authorized && users[i].data.xivaUpdatingYAUID)
{
users[i].data.xivaUpdatingYAUID = false;
self._setRefreshTime(users[i],- 1,true);
}

}

}
);
}

}
,
_handleXivaConnectionResponse: function (user, response) {
var resp;
var isNewData = user.data.xivaLCN !== response.lcn;
user.data.xivaNotWork = 0;
if (isNewData)
{
user.data.xivaLCN = response.lcn || user.data.xivaLCN;
resp = {
operation: response.operation};
if (response.operation == "insert")
{
resp.msg = this._parseMsgXML(response.data);
}

}

this._connect(user);
if (isNewData)
{
this._helper.fireEvent(this._KnownMessages.MSG,{
user: user,
resp: resp});
}

}
,
_handleXivaConnectionError: function (user, status, textStatus, xhr) {
if (textStatus == "abort")
{
return;
}

var timeout = - 1;
if (status == 0)
{
if (textStatus !== "timeout")
{
this._helper.fireEvent(this._KnownMessages.ERROR,user);
}

}

if (textStatus === "timeout")
{
timeout = 0;
}

if (status == 503)
{
var retryAfter = xhr.getResponseHeader("Retry-After");
if (retryAfter)
{
var responseDate = xhr.getResponseHeader("Date");
responseDate = new Date(responseDate);
retryAfter = new Date(retryAfter);
timeout = Math.max(retryAfter.valueOf() - responseDate.valueOf(),30000);
if (isNaN(timeout))
{
timeout = 600000;
}

}
 else
{
timeout = 600000;
}

}

if (status == 403)
{
this._setXivaCredentials(user,null);
timeout = 100;
}

if (timeout == 0 && ! user.data.xivaRefreshTime)
{
this._connect(user);
}
 else
{
this._setRefreshTime(user,timeout,true,"XE");
}

}
,
_setXivaCredentials: function (user, credentials) {
if (credentials && credentials.timestamp && credentials.ts)
{
user.data.xivaCredentials = credentials;
user.data.xivaCredentials.expire = (new Date()).valueOf() + (parseInt(credentials.ts,10) - parseInt(credentials.timestamp,10)) * 1000 - 2000;
}
 else
{
user.data.xivaCredentials = null;
}

}
,
_getXivaCredentials: function (user) {
if (! this._isValidXivaCredentials(user.data.xivaCredentials))
{
user.data.xivaCredentials = null;
}

return user.data.xivaCredentials;
}
,
_isValidXivaCredentials: function (credentials) {
return credentials != null && credentials.sign && credentials.uid && credentials.expire > (new Date()).valueOf();
}
,
_parseMsgXML: function (xml) {
if (! xml)
{
return null;
}

xml = $.parseXML(xml);
var mess = $("message",xml);
var msgObj = {
id: mess.attr("id"),
folderId: $("folder",mess).attr("id"),
date: this._helper.parseDate($("date iso",mess).text()),
from: $("from name",mess).text(),
to: $("to name",mess).text(),
from_email: $("from email",mess).text(),
to_email: $("to email",mess).text(),
subject: $("subject",mess).text(),
firstline: $("firstline",mess).text(),
isUnread: mess.children("new").length > 0,
hasAttach: $("flags attachment",mess).length > 0};
msgObj.url = this._config.URL_WEB + "message?ids=" + msgObj.id;
msgObj.sender = {
name: msgObj.from,
email: msgObj.from_email};
return msgObj;
}
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-mail-actions",{
_handleAction: function (e) {
"use strict";
var item = $(e.target);
var action = this._getItemAction(item);
action && this._getParentMessage().handleAction(action);
}
,
_getItemAction: function (itemElem) {
"use strict";
var action;
var KNOWN_ACTIONS_LIST = this.__self._KNOWN_ACTIONS_LIST;
for (var i = 0, len = KNOWN_ACTIONS_LIST.length;i < len;++i) {
action = KNOWN_ACTIONS_LIST[i];
var itemClass = this.__self._getItemClass(action);
if (itemElem.hasClass(itemClass))
{
return action;
}

}

}
,
_getParentMessage: function () {
"use strict";
return this._message || (this._message = this.findBlockOutside("b-mail-message"));
}
},{
_KNOWN_ACTIONS_LIST: ["readed", "remove", "spam"],
live: function () {
"use strict";
this.liveBindTo("leftclick",function (e) {
e.preventDefault();
this._handleAction(e);
}
);
}
,
_getItemClass: function (type) {
"use strict";
var cacheEntryName = "__cache_" + type;
return this._getItemClass[cacheEntryName] || (this._getItemClass[cacheEntryName] = this.buildSelector("item","type",type).slice(1));
}
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-mail-message",{
onSetMod: {
js: function () {
"use strict";
this._mailAPI = BEM.blocks["i-yandex-mail-api"];
this._helper = BEM.blocks["i-widget-helper"];
this._widget = BEM.blocks["i-widget-mail"];
this._auth = BEM.blocks["i-yandex-auth"];
this._notifications = BEM.blocks["i-yandex-mail-notifications"];
this._widgetBlock = this.findBlockOutside("b-mail-widget");
this._id = this.domElem.attr("data-id");
}
},
_getLink: function () {
"use strict";
return this._link || (this._link = this.findElem("link"));
}
,
_handleLinkClick: function () {
"use strict";
this._widgetBlock.lastAction("readed");
this._helper.logAction(this._widget.Action.OPEN_MESSAGE);
this._widget.openURL(this._getMessageURL());
this._widgetBlock.removeMessage(this._id);
}
,
_getMessageURL: function () {
"use strict";
return this._getLink().attr("href");
}
,
_endAction: function () {
if (this._waitingActionItem)
{
this._waitingActionItem = null;
}

}
,
handleAction: function (actionName) {
var curDate = (new Date()).valueOf();
if (this._waitingActionItem && this._waitingActionItem.endTime > curDate)
{
var msgDate = this.elem("date").text();
return;
}

this._waitingActionItem = {
endTime: curDate + 10000,
action: actionName};
this._helper.logAction(this._widget.Action.MESSAGE_ACTION);
this._widgetBlock.lastAction(actionName);
var self = this;
var user = this._auth.getUser();
var method = this._actions[actionName];
var msgDate = this.elem("date").text();
if (method && user)
{
this._mailAPI[method](user,this._id,function () {
self._endAction();
self._widgetBlock.removeMessage(self._id);
}
,function () {
self._endAction();
}
);
}

}
,
_actions: {
readed: "markMessageAsRead",
spam: "markMessageAsSpam",
remove: "deleteMessage"}},{
live: function () {
"use strict";
this.liveBindTo("link","leftclick",function (e) {
e.preventDefault();
this._handleLinkClick(e);
}
);
}
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-mail-widget",{
onSetMod: {
js: function () {
"use strict";
var self = this;
var loadListener = function () {
$(window).unbind("load",loadListener);
self.__init();
}
;
$(window).bind("load",loadListener);
}
},
_Alert: {
SPINNER: 0,
GENERIC_ERROR: 1,
NETWORK_IS_NOT_AVAILABLE: 2,
NO_NEW_MESSAGES: 3},
_lastActionInterval: 3000,
__init: function () {
"use strict";
if (this._initialized)
{
return;
}

this._sliceVisible = false;
this._deferredListRefresh = false;
this._helper = BEM.blocks["i-widget-helper"];
this._widget = BEM.blocks["i-widget-mail"];
this._mailAPI = BEM.blocks["i-yandex-mail-api"];
this._auth = BEM.blocks["i-yandex-auth"];
this._mailNotifications = BEM.blocks["i-yandex-mail-notifications"];
this._messagesBox = this.findBlockInside("b-mail-messages");
this._configs = BEM.blocks["i-widget-mail__config"];
if (window.parent && window.parent.__debug_Tools_)
{
window.parent.__debug_Tools_(this,window);
}

if (! window.platform)
{
window.platform = window.external;
}

var platform = window.platform;
this._helper.init(platform);
this.config = this._helper.branding(this._configs);
this._helper.platformLocalization(this);
this._helper.initAllHandlers(this);
this._widget.init(platform);
this._mailAPI.init();
this._auth.init();
this._mailNotifications.init();
this._messagesBox.init();
this._initialized = true;
this._auth.updateUserData(this._helper.browser.isFF());
}
,
handlers: {
"mail-before-popup": function () {
var users = this._auth.getUsers();
var curtime = (new Date()).valueOf();
for (var i = 0;i < users.length;++i) {
if (users[i].authorized)
{
users[i].data.mwRefreshInterval = 0;
users[i].data.mwOfflineInterval = 0;
if (users[i].data.mwRefreshTime && users[i].data.mwRefreshTime - curtime > 10000 || users[i].data.mwLoginLost)
{
this._setRefreshTime(users[i],5000);
}

if (users[i].data.mwLoginLost)
{
this.requestUserName(users[i]);
}

users[i].data.mwLoginLost = false;
}

}

this.ensureVisible(true);
}
,
"mail-before-hide": function () {
this._sliceVisible = false;
}
,
"u:timer": function (topic, user) {
if (! user.data.mwLoginLost && user.data.mwRefreshTime && (new Date()).valueOf() >= user.data.mwRefreshTime)
{
this.refresh(user);
}

}
,
"auth:login_lost": function (t, user) {
user.data.mwLoginLost = true;
}
,
"auth:login": function (topic, user) {
user.data.mwLastActionTime = 0;
user.data.mwLoginLost = false;
this._setRefreshTime(user,0);
this._setRefreshTime(user,0,false,"Offline");
this.requestUserName(user);
this.refresh(user);
}
,
"auth:logout": function (topic, user) {
this.setUserCount(0,user);
}
,
"auth:current": function (topic, data) {
if (this._sliceVisible)
{
this.refresh();
}
 else
{
this._deferredListRefresh = true;
this._notifyCounters();
}

}
,
"xiva:timeout": function (t, user) {
this._setRefreshTime(user,- 1,true,"Offline");
}
,
"xiva:error": function (t, user) {
var curtime = (new Date()).valueOf();
if (! user.data.mwRefreshTime || user.data.mwRefreshTime - curtime > 300000 && user.data.mwRefreshInterval < 180000)
{
this._setRefreshTime(user,- 1);
}

}
,
"xiva:msg": function (t, data) {
var resp = data.resp;
var user = data.user;
user.data.mwOfflineInterval = 0;
if (! user.authorized)
{
return;
}

if (resp.operation == "insert")
{
if (! resp.msg.isUnread)
{
return;
}

var email = this._auth.normalizeEMail(resp.msg.from_email);
if (user.email == email)
{
return;
}

var self = this;
function insert() {
if (self._sliceVisible && user.isCurrent)
{
self._insertMessages([resp.msg],true);
self.addUserCount(1,user);
}
 else
{
self._setRefreshTime(user,1500);
}

resp.msg.url = self._widget.prepareURL(resp.msg.url,user);
resp.msg.from = (resp.msg.from || "").fromHTML();
resp.msg.sender.name = (resp.msg.sender.name || "").fromHTML();
self._helper.sendMessage("messages.new",{
inbox_url: self._widget.prepareURL(self.config.URL_WEB,user),
messages: [resp.msg]});
}

this._mailAPI.getFoldersList(user,function (folders) {
var folder = folders.map[resp.msg.folderId];
if (folder && folder.ignoreXivaInsert)
{
return;
}

insert();
}
,insert,true);
}
 else
{
var currtime = (new Date()).valueOf();
if (currtime - user.data.mwLastActionTime > this._lastActionInterval)
{
this._setRefreshTime(user,8000);
}
 else
{

}

}

}
},
requestUserName: function (user) {
if (! user.data.mwUpdatingDisplayName && user.type != "pdd")
{
user.data.mwUpdatingDisplayName = true;
var auth = this._auth;
this._mailAPI.getUserSettings(user,function (data) {
user.data.mwUpdatingDisplayName = false;
if (data.loginLost)
{
auth.loginLost(user);
}

if (data.email)
{
auth.setDisplayLogin(user,data.email);
}

}
,function () {
user.data.mwUpdatingDisplayName = false;
}
);
}

}
,
lastAction: function (type, opt_user) {
opt_user = opt_user || this._auth.getUser();
if (opt_user)
{
opt_user.data.mwLastActionTime = (new Date()).valueOf();
}

}
,
ensureVisible: function (doRefresh) {
this._sliceVisible = true;
if (doRefresh && this._deferredListRefresh)
{
this._deferredListRefresh = false;
this.refresh();
}

}
,
_setRefreshTime: function (user, delay, test, type) {
type = "mw" + (type || "Refresh");
var pTime = "mwRefreshTime";
var pInt = type + "Interval";
if (test && user.data[pTime])
{
return;
}

if (! delay)
{
user.data[pInt] = 0;
user.data[pTime] = 0;
return;
}

if (delay < 0)
{
var maxDelay = 710000;
delay = user.data[pInt] || 6000;
if (delay < maxDelay)
{
user.data[pInt] = Math.min(Math.round(delay * 1.5),maxDelay);
}

}
 else
{
user.data[pInt] = 0;
}

user.data[pTime] = (new Date()).valueOf() + delay;
}
,
refresh: function (user, opt_minSpinnerTime) {
user = user || this._auth.getUser();
if (! user || ! user.authorized || user.data.mwUpdating)
{
return;
}

user.data.mwUpdating = true;
user.data.mwRefreshTime = 0;
if (user.isCurrent)
{
this._showAlert(this._Alert.SPINNER);
}
 else
{
opt_minSpinnerTime = 0;
}

var self = this;
this.getMessagesList(user,(function (folderInfo, messages) {
user.data.mwUpdating = false;
if (folderInfo.apiError)
{
self._setRefreshTime(user,- 1,true);
}
 else
{
user.data.mwRefreshInterval = 0;
}

self._handleMessageList(user,folderInfo,messages);
}
).callbackDelay(opt_minSpinnerTime),(function (error) {
user.data.mwUpdating = false;
self._setRefreshTime(user,- 1,true);
if (user.isCurrent)
{
self._showError(error);
}

}
).callbackDelay(opt_minSpinnerTime));
}
,
getMessagesList: function (user, successCallback, errorCallback) {
var helper = this._helper;
var widget = this._widget;
var mailAPI = this._mailAPI;
var maxMsgCount = this._messagesBox.getMaxVisibleCount() * 2;
var unreadCount = 0;
function getListCallback(folder, messages) {
folder.unreadCount = unreadCount;
if (! messages || messages.length < unreadCount && messages.length < 2)
{
helper.logError("messages.length < unreadCount!!! messages.length=" + (messages ? messages.length : 0));
folder.apiError = true;
}

successCallback(folder,messages);
}

function handleError(jqXHR, textStatus, errorThrown) {
var errorType = jqXHR && (0 === jqXHR.status || 600 < jqXHR.status) ? "NETWORK_IS_NOT_AVAILABLE" : "GENERIC";
errorCallback(widget.Error[errorType]);
}

function getList() {
self._deferredListRefresh = false;
var tryCount = 3;
if (unreadCount > 20000)
{
tryCount = 4;
}

if (unreadCount > 30000)
{
tryCount = 6;
}

if (unreadCount > 40000)
{
tryCount = 9;
}

mailAPI.getMessagesInFolder(user,maxMsgCount,getListCallback,function () {
helper.logError("get msg list error!!!");
successCallback({
unreadCount: unreadCount,
apiError: true},[]);
}
,tryCount);
}

;
var self = this;
mailAPI.getCounterInfo(user,function (data) {
if (data.loginLost)
{
self._auth.loginLost(user);
successCallback({
unreadCount: 0},[]);
return;
}

unreadCount = data.count || 0;
if (self._sliceVisible)
{
if (unreadCount && user.isCurrent)
{
getList();
}
 else
{
successCallback({
unreadCount: unreadCount},[]);
}

}
 else
{
if (user.isCurrent)
{
self._deferredListRefresh = true;
}

successCallback({
unreadCount: unreadCount},[]);
}

}
,handleError);
}
,
_handleMessageList: function (user, folderInfo, messages) {
this.setUserCount(folderInfo.unreadCount,user);
if (user.isCurrent)
{
this._messagesBox.clear();
this._showMessagesList(messages,folderInfo.apiError);
}

}
,
addUserCount: function (delta, user) {
if (! delta)
{
return;
}

user = user || this._auth.getUser();
this.setUserCount((user.data.count || 0) + delta,user);
}
,
setUserCount: function (count, user) {
user = user || this._auth.getUser();
user.data.count = count;
this._helper.fireEvent("w:user_counter",user);
this._notifyCounters();
}
,
_notifyCounters: function () {
var cc = 0, oc = 0, users = this._auth.getUsers(true);
for (var i = 0;i < users.length;++i) {
if (users[i].isCurrent)
{
cc = users[i].data.count || 0;
}
 else
{
oc += users[i].data.count || 0;
}

}

this._helper.fireEvent("w:user_counters",{
current: cc,
other: oc});
this._helper.sendMessage("messages.unread_count",cc + oc);
}
,
_showMessagesList: function (messages, apiError) {
"use strict";
if (this._deferredListRefresh)
{
this._hideAllAlerts();
return;
}

if (0 == messages.length && ! apiError)
{
this._showAlert(this._Alert.NO_NEW_MESSAGES);
}
 else
{
this._insertMessages(messages);
}

}
,
removeMessage: function (messageId) {
var result = this._messagesBox.removeMessage(messageId);
if (result)
{
this.addUserCount(- 1);
var len = this._messagesBox.getCount();
if (0 === len)
{
this._showAlert(this._Alert.NO_NEW_MESSAGES);
}
 else
{
if (len < this._messagesBox.getMaxVisibleCount() && this._auth.getUser().data.count > len)
{
this.refresh();
}

}

}

return result;
}
,
_insertMessages: function (messages, bFirst) {
this._hideAllAlerts();
this._messagesBox.insertMessages(messages,bFirst);
}
,
_showError: function (error) {
"use strict";
this._hideAlert(this._Alert.SPINNER);
this.setUserCount(0);
switch (error) {
case this._widget.Error.GENERIC:
this._showAlert(this._Alert.GENERIC_ERROR);
break;
case this._widget.Error.NETWORK_IS_NOT_AVAILABLE:
this._showAlert(this._Alert.NETWORK_IS_NOT_AVAILABLE);
break;
}

}
,
_getAlertsList: function () {
"use strict";
return this._alerts || (this._alerts = this.findBlocksInside("b-mail-alerts"));
}
,
_getAlert: function (alertIndex) {
"use strict";
return this._getAlertsList()[alertIndex];
}
,
_showAlert: function (alertType) {
"use strict";
this._hideAllAlerts();
this._getAlert(alertType).domElem.show();
this._alertType = alertType;
}
,
_hideAlert: function (alertType) {
"use strict";
this._getAlert(alertType).domElem.hide();
this._alertType = null;
}
,
_hideAllAlerts: function () {
"use strict";
for(var i in this._Alert) {
if (this._Alert.hasOwnProperty(i))
{
this._hideAlert(this._Alert[i]);
}

}

this._alertType = null;
}
,
_showUserName: function (login) {
"use strict";
var userBlock = this.findBlockInside("b-mail-user");
userBlock.setUser(login);
}
},{
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-mail-head-l",{
platform_i18n: function (helper, i) {
this._btnLogo = this.elem("item","btn","logo");
this._btnRefresh = this.elem("item","btn","refresh");
this._btnCreate = this.elem("item","btn","create");
this._btnLogo.css("backgroundImage","url(\"/mail/logo.png\")").attr("alt",BEM.I18N("b-mail-widget","logo"));
this._btnRefresh.attr("title",BEM.I18N("b-mail-widget","tt.refresh")).attr("alt",BEM.I18N("b-mail-widget","refresh"));
this._btnCreate.attr("title",BEM.I18N("b-mail-widget","tt.create")).attr("alt",BEM.I18N("b-mail-widget","create"));
}
},{
live: function () {
this.liveBindTo("item","leftclick",function (e) {
e.preventDefault();
var helper = BEM.blocks["i-widget-helper"];
var widget = BEM.blocks["i-widget-mail"];
var conf = BEM.blocks["i-widget-mail__config"].current;
var user = BEM.blocks["i-yandex-auth"].getUser();
if (! user)
{
return;
}

if (e.target == this._btnLogo[0])
{
helper.logAction(widget.Action.CLICK_LOGO);
widget.openURL(conf.URL_WEB);
return;
}

if (e.target == this._btnRefresh[0])
{
helper.logAction(widget.Action.CLICK_REFRESH);
var mainBlock = this.findBlockOutside("b-mail-widget");
mainBlock.ensureVisible();
mainBlock.refresh("",800);
return;
}

if (e.target == this._btnCreate[0])
{
helper.logAction(widget.Action.CLICK_COMPOSE_NEW);
widget.openURL(conf.URL_WEB + "compose");
}

}
);
}
});
}
)(jQuery);
;
(function () {
BEM.DOM.decl("b-mail-user",{
_setUser: function (name) {
var firstLetter = name.slice(0,1);
this._userBlock.elem("first-letter").text(firstLetter);
var tail = name.slice(1);
var elem = this._userBlock.domElem[0];
while (elem.lastChild != elem.firstChild) {
elem.removeChild(elem.lastChild);
}

elem.appendChild(document.createTextNode(tail));
}
,
handlers: {
"w:user_counters": function (topic, counts) {
this._counter.domElem.text(counts.current);
}
,
"auth:login": function (topic, user) {
if (user.isCurrent)
{
this._setUser(user.displayEmail);
}

}
,
"auth:current": function (topic, data) {
var user = data.current;
if (user)
{
this._setUser(user.displayEmail);
}
 else
{
this._setUser("  ");
}

}
,
"auth:rename": function (topic, user) {
if (user.isCurrent)
{
this._setUser(user.displayEmail);
}

}
},
platform_i18n: function (helper) {
this._helper = helper;
this._auth = BEM.blocks["i-yandex-auth"];
this._widget = BEM.blocks["i-widget-mail"];
this._userBlock = this.findBlockInside("b-user");
this._counter = this.findBlockInside("b-mail-counter");
this._config = BEM.blocks["i-widget-mail__config"].current;
this._counter.domElem.attr("title",BEM.I18N("b-mail-widget","ft.unread"));
}
},{
live: function () {
"use strict";
this.liveBindTo("leftclick",function (e) {
if (! this._auth.getUser())
{
return;
}

var user = this._userBlock.domElem[0];
if (e.target == user || e.target.parentNode == user || e.target.parentNode.parentNode == user)
{
this._widget.openURL(this._config.URL_WEB);
}

}
);
}
});
}
)();
;
BEM.decl("i-common__string",{
},{
cleverSubstring: (function () {
var ellipsisChar = "\u2026";
return function (str, maxLength, maxLengthRelative) {
return str.length > maxLength + maxLengthRelative ? str.substring(0,maxLength - 1) + ellipsisChar : str;
}
;
}
)(),
escapeHTML: (function () {
var map = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&#39;"}, f = function (t) {
return map[t] || t;
}
;
return function (string) {
return String(string).replace(/&(?!\w+;)|[<>"']/g,function (s) {
return map[s] || s;
}
);
}
;
}
)(),
escapeRegExp: function (string) {
return string.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1");
}
,
highlight: function (text, ranges) {
if (! $.isArray(ranges))
return text;
var emphasized = [], cursor = 0, index, _ranges = ranges.sort(function (a, b) {
return a[0] - b[0];
}
);
_ranges.forEach(function (range) {
index = cursor > range[0] ? cursor : range[0];
emphasized.push({
tag: "span",
elem: "span",
content: this.escapeHTML(text.slice(cursor,index))});
emphasized.push({
tag: "em",
elem: "em",
content: this.escapeHTML(text.slice(index,cursor = range[1]))});
}
,this);
emphasized.push({
tag: "span",
elem: "span",
content: this.escapeHTML(text.slice(cursor))});
return emphasized;
}
});
;
BEM.DOM.decl("b-mail-switch",{
handlers: {
"options:show": function (topic, visible) {
this.setMod("opened",visible ? "yes" : "no");
}
,
"w:user_counters": function (topic, counts) {
var counter = this.findBlockInside("b-mail-counter").domElem;
var helper = BEM.blocks["i-widget-helper"];
var countAll = counts.current + counts.other;
this.setMod("counter",countAll ? "yes" : "no");
counter.text(BEM.I18N("b-mail-widget","total",{
count: countAll}));
}
}},{
live: function () {
this.liveBindTo("leftclick",function (e) {
var helper = BEM.blocks["i-widget-helper"];
if (helper.browser.isFF() && this.getMod("opened") != "yes")
{
BEM.blocks["i-yandex-auth"].updateUserData();
}

helper.fireEvent("switch:click");
}
);
}
});
;
(function ($) {
BEM.DOM.decl("b-mail-alerts",{
onSetMod: {
js: function () {
"use strict";
var link = this._getLink();
if (null === link)
{
return;
}

var self = this;
link.domElem.click(function (e) {
self._handleClick(e);
}
);
}
},
_handleClick: function (e) {
"use strict";
e.preventDefault();
var link = this._getLink();
var isRefreshButton = "refresh" === link.getMod("type");
if (isRefreshButton)
{
this._getWidgetBlock().refresh();
return;
}

var url = link.domElem.attr("href");
if (! url)
{
return;
}

var helper = this._getHelper();
var widget = this._getWidget();
helper.logAction(widget.Action.CLICK_GO_TO_WEB);
widget.openURL(url);
}
,
_getLink: function () {
"use strict";
return this._link || (this._link = this.findBlockInside("b-link"));
}
,
_getHelper: function () {
"use strict";
return this._helper || (this._helper = BEM.blocks["i-widget-helper"]);
}
,
_getWidget: function () {
"use strict";
return this._widget || (this._widget = BEM.blocks["i-widget-mail"]);
}
,
_getWidgetBlock: function () {
"use strict";
return this._widgetBlock || (this._widgetBlock = this.findBlockOutside("b-mail-widget"));
}
,
platform_i18n: function (helper, i) {
var types = this._getWidgetBlock()._Alert;
var msg = this.elem("message");
if (i === types.SPINNER)
{
msg.text(BEM.I18N("b-mail-widget","wait"));
}

if (i === types.GENERIC_ERROR)
{
this.findBlockInside("b-icon").domElem.attr("alt",BEM.I18N("b-mail-widget","error.refresh"));
msg.text(BEM.I18N("b-mail-widget","error.refresh"));
this._getLink().elem("inner").text(BEM.I18N("b-mail-widget","retry"));
}

if (i === types.NETWORK_IS_NOT_AVAILABLE)
{
this.findBlockInside("b-icon").domElem.attr("alt",BEM.I18N("b-mail-widget","error.net"));
msg.text(BEM.I18N("b-mail-widget","error.net"));
}

if (i === types.NO_NEW_MESSAGES)
{
this.findBlockInside("b-icon").domElem.attr("alt",BEM.I18N("b-mail-widget","nounread"));
msg.text(BEM.I18N("b-mail-widget","nounread"));
this._getLink().elem("inner").text(BEM.I18N("b-mail-widget","continuewm"));
}

}
},{
});
}
)(jQuery);
;
BEM.HTML.decl("b-icon",{
onBlock: function (ctx) {
var a = {
src: "//yandex.st/lego/_/La6qi18Z8LwgnZdsAr1qy1GwCwo.gif",
alt: ""}, params = ctx.params(), props = ["alt", "width", "height"], p;
params.url && (a.src = params.url);
while (p = props.shift()) params[p] && (a[p] = params[p]);
ctx.tag("img").attrs(a);
}
});
;
BEM.HTML.decl("b-link",{
onBlock: function (ctx) {
ctx.tag("a").attr("href",ctx.param("url"));
var props = ["title", "target"], p;
while (p = props.pop()) ctx.param(p) && ctx.attr(p,ctx.param(p));
}
});
;
(function ($) {
var leftClick = $.event.special.leftclick = {
setup: function () {
$(this).bind("click",leftClick.handler);
}
,
teardown: function () {
$(this).unbind("click",leftClick.handler);
}
,
handler: function (e) {
if (! e.button)
{
e.type = "leftclick";
$.event.handle.apply(this,arguments);
e.type = "click";
}

}
};
}
)(jQuery);
;
BEM.DOM.decl({
"name": "b-link",
"modName": "pseudo",
"modVal": "yes"},{
_onClick: function (e) {
e.preventDefault();
this.hasMod("disabled","yes") || this.afterCurrentEvent(function () {
this.trigger("click");
}
);
}
},{
live: function () {
this.__base.apply(this,arguments);
this.liveBindTo({
modName: "pseudo",
modVal: "yes"},"leftclick",function (e) {
this._onClick(e);
}
);
}
});
;
BEM.HTML.decl({
name: "b-link",
modName: "pseudo",
modVal: "yes"},{
onBlock: function (ctx) {
ctx.tag(ctx.param("url") ? "a" : "span");
ctx.wrapContent({
elem: "inner"});
ctx.js(true);
}
,
onElem: {
"inner": function (ctx) {
ctx.tag("span");
}
}});
;
(function ($) {
BEM.DOM.decl({
name: "b-mail-options",
modName: "type",
modVal: "settings"},{
onSetMod: {
hidden: function () {
var self = this;
setTimeout(function () {
var hidden = self.getMod("hidden") == "yes";
self._updateScrollBar();
self._helper.fireEvent("options:show",! hidden);
}
,1);
}
},
platform_i18n: function (helper) {
this.domElem.find("a[href=\"action:login\"] .b-link__inner").text(BEM.I18N("b-mail-widget","login_other"));
this.domElem.find("a[href=\"action:settings\"] .b-link__inner").text(BEM.I18N("b-mail-widget","settings"));
this.domElem.find("a[href=\"action:exit\"] .b-link__inner").text(BEM.I18N("b-mail-widget","logout_all"));
this._auth = BEM.blocks["i-yandex-auth"];
this._helper = helper;
this._widget = BEM.blocks["i-widget-mail"];
this._separator = this.elem("item","type","separate");
this._map = {
};
this._scrollBox = this.findBlockInside("b-scroll-y-box");
this._updateScrollBar();
}
,
_updateScrollBar: function () {
var hidden = this.getMod("hidden") == "yes";
if (! hidden && this._scrollBox)
{
this._scrollBox.updateScrollBar();
}

}
,
handlers: {
"auth:users": function (topic, users) {
for (var i = 0;i < users.length;++i) {
var elem = {
block: "b-mail-options",
elem: "item",
mods: {
userid: users[i].id,
login: "off",
type: "user"},
content: [{
block: "b-link",
mods: {
pseudo: "yes",
inner: "yes"},
content: [{
block: "b-mail-counter",
tag: "span",
content: "0"}, {
elem: "email",
tag: "span",
content: users[i].email}, {
block: "b-icon",
mods: {
action: "yes"},
mix: [{
block: "b-link",
elem: "icon"}],
url: "img/b-icon-empty.gif"}]}]};
var html = BEM.HTML.build(elem);
BEM.DOM.before(this._separator,html);
var elem = this.elem("item","userid",users[i].id);
$(".b-link__email",elem)[0].__optionCmd = {
type: "select",
id: users[i].id};
$(".b-icon",elem)[0].__optionCmd = {
type: "logout",
id: users[i].id};
this._map[users[i].id] = {
elem: elem,
wait: false};
this._updateScrollBar();
}

}
,
"auth:remove_users": function (topic, users) {
var count = 0;
for (var i = 0;i < users.length;++i) {
var item = this._getUserItem(users[i],true);
if (item)
{
item.css("display","none");
delete this._map[users[i].id];
count = 1;
}

}

if (count)
{
this._updateScrollBar();
}

}
,
"auth:current": function (topic, data) {
var itemCurr = this._getUserItem(data.current,true);
var itemOld = this._getUserItem(data.oldCurrent,true);
if (itemOld)
{
this._setUserItemState(itemOld,data.oldCurrent.authorized,false);
}

if (itemCurr)
{
this._setUserItemState(itemCurr,true,true);
}

}
,
"auth:login": function (topic, user) {
this._setUserItemState(this._getUserItem(user,true),true,user.isCurrent);
if (user.isCurrent && user.oldCurrent)
{
this._setUserItemState(this._getUserItem(user.oldCurrent,true),user.oldCurrent.authorized,false);
}

}
,
"auth:logout": function (topic, user) {
this._setUserItemState(this._getUserItem(user,true),false,false);
}
,
"auth:rename": function (topic, user) {
var item = this._getUserItem(user);
if (item)
{
this.findBlockInside(item,"b-link").elem("email").text(user.displayEmail);
}

}
,
"switch:click": function () {
this.toggleMod("hidden","yes","no");
}
,
"w:user_counter": function (topic, user) {
var item = this._getUserItem(user);
if (item)
{
this.findBlockInside(item,"b-mail-counter").domElem.html(user.data.count);
}

}
,
"mail-before-hide": function () {
this.setMod("hidden","yes");
}
},
_getUserItem: function (user, unwait) {
var el = user ? this._map[user.id] : null;
if (el && unwait && el.wait)
{
this._unwait(el);
}

return el ? el.elem : null;
}
,
_setUserItemState: function (item, isActive, isCurrent) {
if (! item)
{
return;
}

this.setMod(item,"login",isCurrent ? "current" : isActive ? "on" : "off");
var ctr = this.findBlockInside(item,"b-mail-counter");
ctr.setMod("gray",isCurrent ? "no" : "yes");
}
,
_unwait: function (elem, timer) {
var self = this;
var f = function () {
elem.wait = false;
self.delMod(elem.elem,"wait");
if (elem.timer)
{
var tmr = elem.timer;
elem.timer = null;
clearTimeout(tmr);
}

}
;
if (timer)
{
elem.timer = setTimeout(f,7000);
}
 else
{
f();
}

}
,
_handleItemClick: function (e) {
"use strict";
var cmd = e.target.__optionCmd;
if (cmd)
{
if (cmd.type == "select" && cmd.id == this._auth.getUser().id)
{
this.setMod("hidden","yes");
return;
}

var elem = this._map[cmd.id];
if (elem && ! elem.wait)
{
elem.wait = true;
if (cmd.type == "select")
{
this.setMod("hidden","yes");
this._auth.setCurrentUser(cmd.id);
}
 else
{
this.setMod(elem.elem,"wait","yes");
this._auth.logout(cmd.id);
}

this._unwait(elem,true);
}

return true;
}

var a = e.target.tagName == "A" ? e.target : e.target.parentNode;
if (/action:([a-z]+)/.test(a.href))
{
cmd = RegExp.$1;
if (this._urlActions[cmd])
{
window.close();
this._urlActions[cmd].call(this);
}

return true;
}

return false;
}
,
_urlActions: {
"login": function () {
this._auth.login();
}
,
"settings": function () {
this._helper.openSettings();
}
,
"exit": function () {
this._auth.logoutAll();
}
}},{
live: function () {
this.liveBindTo("item","leftclick",function (e) {
e.preventDefault();
this._handleItemClick(e);
return false;
}
);
}
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-scroll-y-box",{
_sbarWidth: 11,
updateScrollBar: function () {
if (! this._box)
{
this._createDOM();
return;
}

var contentHeight = this._content.height();
var height = this.domElem.height();
var parentWidth = this.domElem.width();
var show = this.getMod("show");
this._scrollBarVisible = contentHeight > height;
if (this._scrollBarVisible)
{
var scrollTop = this._box.scrollTop();
var hDrag = height * height / contentHeight;
var tDrag = scrollTop * (height - hDrag) / (contentHeight - height);
this._content.css("width",parentWidth - this._sbarWidth + "px");
this._bardrag.css({
height: Math.round(hDrag) + "px",
top: Math.round(tDrag) + "px",
display: ""});
this._bar.css({
display: "block"});
this.delMod("hiddenbar");
}
 else
{
if (show == "all")
{
this._bar.css("display","block");
this._bardrag.css("display","none");
this._content.css("width",parentWidth - this._sbarWidth + "px");
}
 else
{
this._bar.css("display","none");
this._content.css("width",parentWidth + "px");
if (show == "hidden")
{
this.setMod("hiddenbar","yes");
}

}

}

}
,
_createDOM: function () {
var elemBox = {
block: "b-scroll-y-box",
elem: "box",
content: [{
elem: "content",
block: "b-scroll-y-box",
content: ""}]};
var elemBar = {
elem: "bar",
block: "b-scroll-y-box",
content: [{
elem: "bardrag",
block: "b-scroll-y-box",
content: [{
elem: "bardragtop",
block: "b-scroll-y-box",
content: ""}, {
elem: "bardragbottom",
block: "b-scroll-y-box",
content: ""}]}]};
var i, content = [];
this.domElem.children().each(function () {
content.push(this);
}
);
var htmlBox = BEM.HTML.build(elemBox);
var htmlBar = BEM.HTML.build(elemBar);
BEM.DOM.append(this.domElem,htmlBox);
BEM.DOM.append(this.domElem,htmlBar);
this._box = this.elem("box");
this._content = this.elem("content");
for (i = content.length - 1;i >= 0;--i) {
BEM.DOM.prepend(this._content,content[i]);
}

this._bar = this.elem("bar");
this._bardrag = this.elem("bardrag");
this._sbarWidth = this._bar.outerWidth();
this._initScrollBarEvents();
this.updateScrollBar();
}
,
_initScrollBarEvents: function () {
var self = this;
this._box.bind("scroll",function () {
self.updateScrollBar();
}
);
var yd, scrolld, contentHeight, height, hDrag;
var doc = $(document);
function mouseMove(e) {
if (e.which != 1)
{
return mouseUp(e);
}

var delta = e.pageY - yd;
self._box.scrollTop(scrolld + Math.round(delta * (contentHeight - height) / (height - hDrag)));
e.preventDefault();
return false;
}

function mouseUp(e) {
doc.unbind("mousemove",mouseMove).unbind("mouseup",mouseUp);
e.preventDefault();
return false;
}

this._box.bind("mousedown",function (e) {
if (! self._scrollBarVisible)
{
return;
}

yd = e.pageY;
scrolld = self._box.scrollTop();
contentHeight = self._content.height();
height = self.domElem.height();
hDrag = height * height / contentHeight;
var dragTop = self._bardrag.offset().top;
if (yd < dragTop)
{
self._box.scrollTop(scrolld - 300);
return false;
}

if (yd > dragTop + hDrag)
{
self._box.scrollTop(scrolld + 300);
return false;
}

doc.bind("mousemove",mouseMove).bind("mouseup",mouseUp);
return false;
}
);
this._content.bind("mousedown",function (e) {
e.stopPropagation();
return false;
}
);
}
},{
});
}
)(jQuery);
;
(function ($) {
BEM.DOM.decl("b-mail-messages",{
init: function () {
this._helper = BEM.blocks["i-widget-helper"];
this._widget = BEM.blocks["i-widget-mail"];
this._config = BEM.blocks["i-widget-mail__config"].current;
this._count = 0;
this._scrollBox = this.findBlockInside("b-scroll-y-box");
this._list = this.elem("list");
this._list.css("maxHeight",this._config.maxVisibleMsgCount * 52 - 1 + "px");
this._updateScrollBar();
}
,
_updateScrollBar: function () {
if (this._scrollBox)
{
this._scrollBox.updateScrollBar();
}

}
,
getCount: function () {
return this._count;
}
,
getMaxVisibleCount: function () {
return this._config.maxVisibleMsgCount;
}
,
clear: function () {
var messages = this.findBlocksInside("b-mail-message");
for (var i = 0, len = messages.length;i < len;++i) {
var message = messages[i];
message.destruct();
}

this._count = 0;
this._updateScrollBar();
}
,
removeMessage: function (messageId) {
var messages = this.findBlocksInside("b-mail-message");
for (var i = 0, len = messages.length;i < len;++i) {
var currentMessage = messages[i];
var currentMessageId = currentMessage.domElem.attr("data-id");
if (currentMessageId === messageId)
{
currentMessage.destruct();
this._count--;
this._updateScrollBar();
return true;
}

}

return false;
}
,
insertMessages: function (messages, bFirst) {
if (! messages.length)
{
return;
}

var list = this.elem("list");
for (var i = 0, len = messages.length;i < len;++i) {
var data = messages[i];
BEM.DOM[bFirst ? "prepend" : "append"](list,this._createMessage(data));
this._count++;
}

this._updateScrollBar();
}
,
_createMessage: function (messageData) {
var blockContent = [];
var blockConfig = {
block: "b-mail-message",
js: true,
attrs: {
"data-id": messageData.id},
content: blockContent};
if (! messageData.isUnread)
{
blockConfig.mods = {
type: "readed"};
}

var linkContent = [];
var link = {
elem: "link",
tag: "a",
attrs: {
href: messageData.url},
content: linkContent};
var date = this._widget.getHumanFriendlyDate(messageData.date);
var leftPart = {
elem: "left",
content: [{
elem: "from",
attrs: {
title: messageData.sender.email},
content: (messageData.sender.name || messageData.sender.email || "").toHTML()}, {
elem: "date",
title: date,
content: date}]};
linkContent.push(leftPart);
var rightPartContent = [{
elem: "subject",
content: messageData.subject.toHTML() || "&#160;"}, {
elem: "firstline",
content: messageData.firstline.toHTML() || "&#160;"}];
if (messageData.hasAttach)
{
rightPartContent.splice(0,0,{
elem: "attach",
attrs: {
title: BEM.I18N("b-mail-widget","attach")},
content: [{
block: "b-icon",
url: "img/b-icon-empty.gif",
alt: BEM.I18N("b-mail-widget","attach")}]});
}

var rightPart = {
elem: "right",
content: rightPartContent};
linkContent.push(rightPart);
blockContent.push(link);
var actions = {
block: "b-mail-actions",
js: true,
content: [{
elem: "item",
tag: "span",
mods: {
type: "readed"},
attrs: {
title: BEM.I18N("b-mail-widget","setreaded")},
content: [{
block: "b-icon",
url: "img/b-icon-empty.gif",
alt: BEM.I18N("b-mail-widget","setreaded")}]}, {
elem: "item",
tag: "span",
mods: {
type: "remove"},
attrs: {
title: BEM.I18N("b-mail-widget","delete")},
content: [{
block: "b-icon",
url: "img/b-icon-empty.gif",
alt: BEM.I18N("b-mail-widget","delete")}]}, {
elem: "item",
tag: "span",
mods: {
type: "spam"},
attrs: {
title: BEM.I18N("b-mail-widget","spam")},
content: [{
block: "b-icon",
url: "img/b-icon-empty.gif",
alt: BEM.I18N("b-mail-widget","spam")}]}]};
blockContent.push(actions);
return BEM.HTML.build(blockConfig);
}
},{
});
}
)(jQuery);
;
BEM.DOM.decl("b-mail-over30",{
_handleLinkClick: function (e) {
this._helper.logAction(this._widget.Action.CLICK_GO_TO_WEB);
this._widget.openURL(this._link.domElem.attr("href"));
}
,
platform_i18n: function (helper) {
this._helper = helper;
this._widget = BEM.blocks["i-widget-mail"];
this._link = this.findBlockInside("b-link");
this._link.elem("inner").text(BEM.I18N("b-mail-widget","continuewm"));
}
,
handlers: {
"auth:current": function (topic, data) {
this._setLinkUrl(data.current);
}
,
"auth:login": function (topic, user) {
this._setLinkUrl(user);
}
},
_setLinkUrl: function (user) {
if (user && user.isCurrent)
{
var url = BEM.blocks["i-widget-mail__config"].current.URL_WEB;
this._link.domElem.attr("href",this._widget.mailDomain(url,user));
}

}
},{
live: function () {
this.liveBindTo("inner","leftclick",function (e) {
e.preventDefault();
this._handleLinkClick(e);
return false;
}
);
}
});
;
(function ($) {
BEM.DOM.decl("b-mail-foot",{
platform_i18n: function (helper) {
this._helper = helper;
this._widget = BEM.blocks["i-widget-mail"];
var config = BEM.blocks["i-widget-mail__config"].current;
var widget = this._widget;
var link = this.findBlockInside("b-link");
if (! link)
{
return;
}

link.elem("inner").text(BEM.I18N("b-mail-widget","addmail"));
this.domElem[0].appendChild(document.createTextNode(" " + BEM.I18N("b-mail-widget","addmail.desc")));
link.domElem.on("leftclick",function (e) {
window.close();
helper.logAction(widget.Action.CLICK_COLLECTOR_LINK);
widget.openURL(config.URL_WEB + "neo2/#setup/collectors");
}
);
}
},{
});
}
)(jQuery);
;
(function (global_, bem_, undefined) {
if (typeof bem_.I18N === "function" && bem_.I18N._proto)
{
return bem_.I18N;
}

if (typeof i18n === "undefined")
{
i18n = {
};
}

BEM = bem_;
var MOD_DELIM = "_", ELEM_DELIM = "__", DEFAULT_LANG = "ru", cache = {
}, stack = [], log = typeof console !== "undefined" && typeof console.log === "function" ? console.log.bind(console) : function () {

}
;
function bemName(decl) {
typeof decl === "string" && (decl = {
block: decl});
return decl.block + (decl.elem ? ELEM_DELIM + decl.elem : "") + (decl.modName ? MOD_DELIM + decl.modName + MOD_DELIM + decl.modVal : "");
}

function bemParse(name) {
var bemitem = {
};
name.split(ELEM_DELIM).forEach(function (item, i) {
var keys = [i ? "elem" : "block", "mod", "val"];
item.split(MOD_DELIM).forEach(function (part, j) {
bemitem[keys[j]] = part;
}
);
}
);
return bemitem;
}

function _pushStack(name) {
if (! name)
return false;
return stack.push(name);
}

function _popStack() {
return stack.length && stack.pop();
}

function _i18n() {
this._lang = "";
this._prj = "lego";
this._keyset = "";
this._key = "";
}

_i18n.prototype = {
lang: function (name) {
this._lang = name;
return this;
}
,
project: function (name) {
this._prj = name;
return this;
}
,
keyset: function (name, saveCtx) {
saveCtx && _pushStack(this._keyset);
this._keyset = bemName(name);
return this;
}
,
key: function (name) {
this._key = name;
return this;
}
,
decl: function (v) {
var bemitem = bemParse(this._keyset), prj = bemitem.block === "i-tanker" ? "tanker" : this._prj, keyset = bemitem.elem || this._keyset, key = this._key;
prj = i18n[prj] || (i18n[prj] = {
});
keyset = prj[keyset] || (prj[keyset] = {
});
keyset[key] = typeof v === "function" ? v : function (p) {
return v;
}
;
var l = cache[this._lang] || (cache[this._lang] = {
}), k = l[this._keyset] || (l[this._keyset] = {
});
k[key] = v;
}
,
val: function (params, ctx) {
var value = cache[this._lang] && cache[this._lang][this._keyset], debugString = "keyset: " + this._keyset + " key: " + this._key + " (lang: " + this._lang + ")";
if (! value)
{
log("[I18N_NO_KEYSET] %s",debugString);
return "";
}

value = value[this._key];
var valtype = typeof value;
if (valtype === "undefined")
{
log("[I18N_NO_VALUE] %s",debugString);
return "";
}

if (valtype === "string")
{
return value;
}

ctx || (ctx = this);
return value.call(ctx,params);
}
,
_cache: function () {
return cache;
}
};
bem_.I18N = (function (base) {
var klass = function (keyset, key, params) {
return klass.keyset(keyset).key(key,params);
}
;
klass._proto = base;
klass.project = function (name) {
this._proto.project(name);
return this;
}
;
klass.keyset = function (name) {
this._proto.keyset(name,true);
return this;
}
;
klass.key = function (name, params) {
var proto = this._proto, result, ksetRestored;
proto.lang(this._lang).key(name);
result = proto.val.call(proto,params,klass);
ksetRestored = _popStack();
ksetRestored && proto.keyset(ksetRestored,false);
return result;
}
;
klass.decl = function (bemitem, keysets, params) {
var proto = this._proto, k;
params || (params = {
});
params.lang && proto.lang(params.lang);
proto.keyset(bemitem);
for(k in keysets) {
if (keysets.hasOwnProperty(k))
{
proto.key(k).decl(keysets[k]);
}

}

return this;
}
;
klass.lang = function (lang) {
typeof lang !== "undefined" && (this._lang = lang);
return this._lang;
}
;
klass.lang(DEFAULT_LANG);
return klass;
}
)(new _i18n());
}
)(this,typeof BEM === "undefined" ? {
} : BEM);
(function (bem_, undefined) {
var DEFAULT_BRAND = null;
var base = bem_.I18N._i18n;
bem_.I18N.brand = (function () {
var _brand = DEFAULT_BRAND;
var klass = function (brand) {
base.setDeclProp("brand",brand);
}
;
return klass;
}
)();
}
)(typeof BEM === "undefined" ? {
} : BEM);
BEM.I18N.decl("b-mail-widget",{
"addmail": "Подключить другой ящик",
"addmail.desc": "вы всегда сможете в настройках почты",
"attach": "С вложением",
"continuewm": "Продолжить работу с почтой",
"create": "Написать",
"delete": "Удалить",
"error.net": "Нет подключения к интернету",
"error.refresh": "При обновлении произошла ошибка",
"ft.unread": "Непрочитанные",
"login_other": "Войти в другой почтовый ящик",
"logo": "Яндекс Почта",
"logout": "Выход",
"logout_all": "Выйти из всех ящиков",
"mail.wait": "Секундочку...",
"mails": "Подключенные почтовые ящики",
"month.g1": "Января",
"month.g10": "Октября",
"month.g11": "Ноября",
"month.g12": "Декабря",
"month.g2": "Февраля",
"month.g3": "Марта",
"month.g4": "Апреля",
"month.g5": "Мая",
"month.g6": "Июня",
"month.g7": "Июля",
"month.g8": "Августа",
"month.g9": "Сентября",
"nounread": "У вас нет непрочитанных писем",
"refresh": "Обновить",
"retry": "Попробуйте еще раз",
"setreaded": "Отметить как прочитанное",
"settings": "Настройки виджета",
"spam": "Отметить как спам",
"total": function (params) {
return "всего " + params.count;
}
,
"tt.create": "Написать новое письмо",
"tt.logo": "Перейти в Я.Почту",
"tt.refresh": "Обновить список писем",
"wait": "Секундочку..."},{
"lang": "ru"});
BEM.I18N.decl("i-tanker__months",{
"g1": "Января",
"g10": "Октября",
"g11": "Ноября",
"g12": "Декабря",
"g2": "Февраля",
"g3": "Марта",
"g4": "Апреля",
"g5": "Мая",
"g6": "Июня",
"g7": "Июля",
"g8": "Августа",
"g9": "Сентября",
"n1": "Январь",
"n10": "Октябрь",
"n11": "Ноябрь",
"n12": "Декабрь",
"n2": "Февраль",
"n3": "Март",
"n4": "Апрель",
"n5": "Май",
"n6": "Июнь",
"n7": "Июль",
"n8": "Август",
"n9": "Сентябрь",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "янв",
"short10": "окт",
"short11": "ноя",
"short12": "дек",
"short2": "фев",
"short3": "мрт",
"short4": "апр",
"short5": "май",
"short6": "июн",
"short7": "июл",
"short8": "авг",
"short9": "сен"},{
"lang": "ru"});
BEM.I18N.decl("b-mail-widget",{
"addmail": "You can always add another mailbox",
"addmail.desc": "in the mail settings menu",
"attach": "With attachment",
"continuewm": "Continue managing your mail",
"create": "Compose",
"delete": "Remove",
"error.net": "No internet connection",
"error.refresh": "An error occurred while updating",
"ft.unread": "Unread",
"login_other": "Log in to another account",
"logo": "Yandex Mail",
"logout": "Log\u00a0out",
"logout_all": "Log out of all mail accounts",
"mail.wait": "Just a sec...",
"mails": "Mailboxes",
"month.g1": "January",
"month.g10": "October",
"month.g11": "November",
"month.g12": "December",
"month.g2": "February",
"month.g3": "March",
"month.g4": "April",
"month.g5": "May",
"month.g6": "June",
"month.g7": "July",
"month.g8": "August",
"month.g9": "September",
"nounread": "You have no unread mail",
"refresh": "Update",
"retry": "Try again",
"setreaded": "Mark as read",
"settings": "Widget settings",
"spam": "Mark as spam",
"total": function (params) {
return params.count + " in total";
}
,
"tt.create": "Compose message",
"tt.logo": "Go to Yandex.Mail",
"tt.refresh": "Refresh message list",
"wait": "Please wait..."},{
"lang": "en"});
BEM.I18N.decl("i-tanker__months",{
"g1": "January",
"g10": "October",
"g11": "November",
"g12": "December",
"g2": "February",
"g3": "March",
"g4": "April",
"g5": "May",
"g6": "June",
"g7": "July",
"g8": "August",
"g9": "September",
"n1": "January",
"n10": "October",
"n11": "November",
"n12": "December",
"n2": "February",
"n3": "March",
"n4": "April",
"n5": "May",
"n6": "June",
"n7": "July",
"n8": "August",
"n9": "September",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "Jan",
"short10": "Oct",
"short11": "Nov",
"short12": "Dec",
"short2": "Feb",
"short3": "Mar",
"short4": "Apr",
"short5": "May",
"short6": "Jun",
"short7": "Jul",
"short8": "Aug",
"short9": "Sep"},{
"lang": "en"});
BEM.I18N.decl("b-mail-widget",{
"addmail": "Başka e-posta hesabı bağla",
"addmail.desc": "mail ayarlarından her zaman yapılabilir",
"attach": "Ekli",
"continuewm": "Mail'i kullanmaya devam et",
"create": "E-posta yaz",
"delete": "Sil",
"error.net": "İnternet bağlantısı yok",
"error.refresh": "Güncelleme sırasında hata oluştu",
"ft.unread": "Okunmamış",
"login_other": "Diğer hesaba giriş yap",
"logo": "Yandex Mail",
"logout": "Çıkış",
"logout_all": "Tüm hesaplardan çıkış yap",
"mail.wait": "Bekleyin...",
"mails": "Bağlı e-posta hesapları",
"month.g1": "Ocak",
"month.g10": "Ekim",
"month.g11": "Kasım",
"month.g12": "Aralık",
"month.g2": "Şubat",
"month.g3": "Mart",
"month.g4": "Nisan",
"month.g5": "Mayıs",
"month.g6": "Haziran",
"month.g7": "Temmuz",
"month.g8": "Ağustos",
"month.g9": "Eylül",
"nounread": "Okunmamış e-postanız yok",
"refresh": "Güncelle",
"retry": "Tekrar deneyin",
"setreaded": "Okundu olarak işaretle",
"settings": "Widget ayarları",
"spam": "Spam olarak işaretle",
"total": function (params) {
return "toplam " + params.count;
}
,
"tt.create": "E-posta yaz",
"tt.logo": "Yandex.Mail'e git",
"tt.refresh": "Mesaj listesini güncelle",
"wait": "Lütfen bekleyin..."},{
"lang": "tr"});
BEM.I18N.decl("i-tanker__months",{
"g1": "Ocak",
"g10": "Ekim",
"g11": "Kasım",
"g12": "Aralık",
"g2": "Şubat",
"g3": "Mart",
"g4": "Nisan",
"g5": "Mayıs",
"g6": "Haziran",
"g7": "Temmuz",
"g8": "Ağustos",
"g9": "Eylül",
"n1": "Ocak",
"n10": "Ekim",
"n11": "Kasım",
"n12": "Aralık",
"n2": "Şubat",
"n3": "Mart",
"n4": "Nisan",
"n5": "Mayıs",
"n6": "Haziran",
"n7": "Temmuz",
"n8": "Ağustos",
"n9": "Eylül",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "Oca",
"short10": "Eki",
"short11": "Kas",
"short12": "Ara",
"short2": "Şub",
"short3": "Mar",
"short4": "Nis",
"short5": "May",
"short6": "Haz",
"short7": "Tem",
"short8": "Ağu",
"short9": "Eyl"},{
"lang": "tr"});
BEM.I18N.decl("b-mail-widget",{
"addmail": "Басқа жәшікті қосу",
"addmail.desc": "сіз әрдайым пошта баптауларынан таба аласыз",
"attach": "Тіркемелері бар",
"continuewm": "Поштамен жұмысты жалғастыру",
"create": "Жазу",
"delete": "Жою",
"error.net": "Интернетке қосылыс жоқ",
"error.refresh": "Жаңарту барысында қате кетті",
"ft.unread": "Оқылмағандар",
"login_other": "Басқа пошта жәшігіне кіру",
"logo": "Яндекс Пошта",
"logout": "Шығу",
"logout_all": "Барлық жәшіктен шығу",
"mail.wait": "Бір сәт күтіңіз...",
"mails": "Кірістірілген пошта жәшіктері",
"month.g1": "Қаңтар",
"month.g10": "Қазан",
"month.g11": "Қараша",
"month.g12": "Желтоқсан",
"month.g2": "Ақпан",
"month.g3": "Наурыз",
"month.g4": "Сәуір",
"month.g5": "Мамыр",
"month.g6": "Маусым",
"month.g7": "Шілде",
"month.g8": "Тамыз",
"month.g9": "Қыркүйек",
"nounread": "Сізде оқылмаған хат жоқ",
"refresh": "Жаңарту",
"retry": "Тағы сынап көріңіз",
"setreaded": "Оқылған деп белгілеу",
"settings": "Виджеттің баптаулары",
"spam": "Спам деп белгілеу",
"total": function (params) {
return "барлығы " + params.count;
}
,
"tt.create": "Жаңа хат жазу",
"tt.logo": "Я.Поштаға өту",
"tt.refresh": "Хаттар тізімін жаңарту",
"wait": "Бір сәт күтіңіз..."},{
"lang": "kk"});
BEM.I18N.decl("i-tanker__months",{
"g1": "Қаңтардың",
"g10": "Қазанның",
"g11": "Қарашаның",
"g12": "Желтоқсанның",
"g2": "Ақпанның",
"g3": "Науырыздың",
"g4": "Сәуірдің",
"g5": "Мамырдың",
"g6": "Маусымның",
"g7": "Шілденің",
"g8": "Тамыздың",
"g9": "Қыркүйектің",
"n1": "Қаңтар",
"n10": "Қазан",
"n11": "Қараша",
"n12": "Желтоқсан",
"n2": "Ақпан",
"n3": "Науырыз",
"n4": "Сәуір",
"n5": "Мамыр",
"n6": "Маусым",
"n7": "Шілде",
"n8": "Тамыз",
"n9": "Қыркүйек",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "қаң",
"short10": "қаз",
"short11": "қар",
"short12": "жел",
"short2": "ақп",
"short3": "наур",
"short4": "сәуір",
"short5": "мам",
"short6": "маус",
"short7": "шіл",
"short8": "там",
"short9": "қыр"},{
"lang": "kk"});
BEM.I18N.decl("b-mail-widget",{
"addmail": "Підключити іншу скриньку",
"addmail.desc": "ви завжди зможете в налаштуваннях пошти",
"attach": "Із вкладенням",
"continuewm": "Продовжити роботу з поштою",
"create": "Написати",
"delete": "Видалити",
"error.net": "Немає підключення до інтернету",
"error.refresh": "Під час оновлення сталася помилка",
"ft.unread": "Непрочитані",
"login_other": "Увійти в іншу поштову скриньку",
"logo": "Яндекс Пошта",
"logout": "Вихід",
"logout_all": "Вийти з усіх скриньок",
"mail.wait": "Секундочку...",
"mails": "Підключені поштові скриньки",
"month.g1": "Cічня",
"month.g10": "Жовтня",
"month.g11": "Листопада",
"month.g12": "Грудня",
"month.g2": "Лютого",
"month.g3": "Березня",
"month.g4": "Квітня",
"month.g5": "Травня",
"month.g6": "Червня",
"month.g7": "Липня",
"month.g8": "Серпня",
"month.g9": "Вересня",
"nounread": "У вас немає непрочитаних листів",
"refresh": "Оновити",
"retry": "Спробуйте ще раз",
"setreaded": "Позначити як прочитане",
"settings": "Налаштування віджета",
"spam": "Позначити як спам",
"total": function (params) {
return "всього " + params.count;
}
,
"tt.create": "Написати новий лист",
"tt.logo": "Перейти у Я.Пошту",
"tt.refresh": "Оновити список листів",
"wait": "Секундочку..."},{
"lang": "uk"});
BEM.I18N.decl("i-tanker__months",{
"g1": "Cічня",
"g10": "Жовтня",
"g11": "Листопада",
"g12": "Грудня",
"g2": "Лютого",
"g3": "Березня",
"g4": "Квітня",
"g5": "Травня",
"g6": "Червня",
"g7": "Липня",
"g8": "Серпня",
"g9": "Вересня",
"n1": "Січень",
"n10": "Жовтень",
"n11": "Листопад",
"n12": "Грудень",
"n2": "Лютий",
"n3": "Березень",
"n4": "Квітень",
"n5": "Травень",
"n6": "Червень",
"n7": "Липень",
"n8": "Серпень",
"n9": "Вересень",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "січ",
"short10": "жовт",
"short11": "лист",
"short12": "груд",
"short2": "лют",
"short3": "бер",
"short4": "квіт",
"short5": "трав",
"short6": "черв",
"short7": "лип",
"short8": "серп",
"short9": "вер"},{
"lang": "uk"});
BEM.I18N.decl("b-mail-widget",{
"addmail": "Далучыць іншую скрыню",
"addmail.desc": "вы заўсёды зможаце ў наладах пошты",
"attach": "З укладаннем",
"continuewm": "Працягваць работу з поштай",
"create": "Напісаць",
"delete": "Выдаліць",
"error.net": "Няма далучэння да інтэрнета",
"error.refresh": "Падчас абнаўлення адбылася памылка",
"ft.unread": "Непрачытаныя",
"login_other": "Увайсці ў іншую паштовую скрыню",
"logo": "Яндекс Пошта",
"logout": "Выхад",
"logout_all": "Выйсці з усіх скрыняў",
"mail.wait": "Секундачку...",
"mails": "Далучаныя паштовыя скрыні",
"month.g1": "Студзеня",
"month.g10": "Кастрычніка",
"month.g11": "Лістапада",
"month.g12": "Снежня",
"month.g2": "Лютага",
"month.g3": "Сакавіка",
"month.g4": "Красавіка",
"month.g5": "Траўня",
"month.g6": "Чэрвеня",
"month.g7": "Ліпеня",
"month.g8": "Жніўня",
"month.g9": "Верасня",
"nounread": "У вас няма непрачытаных лістоў",
"refresh": "Абнавіць",
"retry": "Паспрабуйце яшчэ раз",
"setreaded": "Пазначыць як прачытанае",
"settings": "Наладкі віджэта",
"spam": "Пазначыць як спам",
"total": function (params) {
return "усяго " + params.count;
}
,
"tt.create": "Напісаць новы ліст",
"tt.logo": "Перайсці ў Я.Пошту",
"tt.refresh": "Абнавіць спіс лістоў",
"wait": "Секундачку..."},{
"lang": "be"});
BEM.I18N.decl("i-tanker__months",{
"g1": "Студзеня",
"g10": "Кастрычніка",
"g11": "Лістапада",
"g12": "Снежня",
"g2": "Лютага",
"g3": "Сакавіка",
"g4": "Красавіка",
"g5": "Траўня",
"g6": "Чэрвеня",
"g7": "Ліпеня",
"g8": "Жніўня",
"g9": "Верасня",
"n1": "Студзень",
"n10": "Кастрычнік",
"n11": "Лістапад",
"n12": "Снежань",
"n2": "Люты",
"n3": "Сакавік",
"n4": "Красавік",
"n5": "Травень",
"n6": "Чэрвень",
"n7": "Ліпень",
"n8": "Жнівень",
"n9": "Верасень",
"name": function (params) {
return (function (params) {
var month = i18n.tanker.months[(params.case || "n") + params.month]();
return Boolean(params.lowercase) ? month.toLowerCase() : month;
}
).call(this,params);
}
,
"short1": "сту",
"short10": "кас",
"short11": "ліс",
"short12": "сне",
"short2": "лют",
"short3": "сак",
"short4": "кра",
"short5": "май",
"short6": "чэр",
"short7": "ліп",
"short8": "жні",
"short9": "вер"},{
"lang": "be"});
