/*--------------------------------------*/
/* common.js                            */
/* (c) 2007 Lipka.ru                    */
/*--------------------------------------*/

//-- Common ------------------------------

if (!('$' in window)) {
  $ = function(el) {
    return (typeof(el) == 'string' ? document.getElementById(el) : el);
  }
}

function $_(el, container) {
  return (typeof(el) == 'string' ? 
          (container == null ? document.getElementById(el) : 
           getSubElementById(el, container)) : 
          el);
}

function getSubElementById(id, container) {
  var el = container.firstChild;
  while (el) {
    if (el.id && el.id == id) return el;
    var res = getSubElementById(id, el);
    if (res) return res;
    el = el.nextSibling;
  }
  return null;
}

function applyIntf(el) {
  var a = null, i, j, n, arg, len = arguments.length;
  if (el instanceof Array) {
    a = el;
    el = a[0];
    i = 0;
  }
  do {
    if (typeof(el) == 'string') el = document.getElementById(el);
    for (j = 1; j < len; j++) {
      arg = arguments[j];
      for (n in arg) el[n] = arg[n];
    }
    if (a == null || a.length == (++i)) return;
    el = a[i];
  } while (true);
}

function findSubChild(element, tag, className) {
  var list = element.getElementsByTagName(tag.toUpperCase());
  if (className == null) return (list.length > 0 ? list[0] : null);
  for (var i = 0, l = list.length; i < l; i++) {
    var el = list[i];
    if (el.className == className) return el;
  }
  return null;
}

function isChildOf(el, parent) {
  while (el != null) {
    if (el == parent) return true;
    el = el.parentNode;
  } 
  return false;
}

function findParentNode(el, tag, className) {
  if (el == null) return null;
  tag = tag.toUpperCase();
  do {
    el = el.parentNode;
  } while (el != null && (el.tagName != tag || (className != null && el.className != className)));
  return el;
}

function getAbsPos(el) {
  var pos = {left:0, top:0};
  while (el && el.tagName != 'BODY') {
    pos.left += el.offsetLeft;
    pos.top += el.offsetTop;
    el = el.offsetParent;
  }
  return pos;
}


function trim(s) {
  return (s ? s.toString().replace(/^\s+/, '').replace(/\s+$/, '') : '');
}

function trimHTML(s) {
  s = s.replace(/<.*?>/g, '');
  s = s.replace(/&nbsp;/g, ' ');
  s = s.replace(/&quot;/g, '"');
  s = s.replace(/&gt;/g, '>');
  s = s.replace(/&lt;/g, '<');
  return s;
}

function extractPath(s) {
  return s.substr(0, s.lastIndexOf('/')+1);
}

function extractNameNoExt(s) {
  var p = s.lastIndexOf('/');
  if (p >= 0) s = s.substr(p+1);
  p = s.lastIndexOf('.');
  return (p >= 0 ? s.substr(0, p) : s);
}

function extractExt(s) {
  var p = s.lastIndexOf('.');
  return (p >= 0 ? s.substr(p) : '');
}

function delSlash(s) {
  var last = s.length-1;
  if (last > 0 && s.charAt(last) == '/') s = s.substr(0, last);
  return s;
}

function addSlash(s) {
  var last = s.length-1;
  if (last >= 0 && s.charAt(last) != '/') s += '/';
  return s;
}


if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, first) {
    for (var i = first || 0; i < this.length; i++) {
      if (this[i] === item) return i;
    }
    return -1;
  }
}

Array.prototype.addItem = function(item) {
  var i = this.indexOf(item);
  if (i < 0) {
    i = this.length;
    this.push(item);
  }
  return i;
}

Array.prototype.removeItem = function(item) {
  var i = this.indexOf(item);
  if (i >= 0) this.removeItemByIndex(i, true);
  return i;
}

Array.prototype.removeItemByIndex = function(i, shrink) {
  if (shrink) {
    if (this.splice) this.splice(i, 1)
    else {
      for (var j = i+1; j < this.length; j++) this[j-1] = this[j];
      this.length = this.length-1;
    }
  } else {
    if (i < this.length-1) this[i] = null
    else {
      do { this.length = (i--) } while (i >= 0 && this[i] == null);
    }
  }
  return true;
}


//Function.prototype.funcName = function() {
//  return (/function\s*(\S*)\s*\(/.test(this.toString()) ? RegExp.$1 : '');
//}

//function isTypeOf(prm, type) {
//  return (prm && prm.constructor && prm.constructor.funcName() == type);
//}

function isNumber(prm) {
  return (typeof(prm.valueOf()) == 'number');
}

function isString(prm) {
  return (typeof(prm.valueOf()) == 'string');
}

function isFunction(prm) {
  return (typeof(prm.valueOf()) == 'function');
}

function isArray(prm) {
  return (typeof(prm.valueOf()) == 'array' || (typeof(prm) == 'object' && 'join' in prm));
}


function setupEvent(el, eventType, handler, capture) {
  if (el.attachEvent) el.attachEvent('on'+eventType, handler)
  else if (el.addEventListener) el.addEventListener(eventType, handler, capture)
}

function removeEvent(el, eventType, handler, capture) {
  if (el.detachEvent) el.detachEvent('on'+eventType, handler)
  else if (el.removeEventListener) el.removeEventListener(eventType, handler, capture)
}

var
  mouseMoveListeners = [],
  mouseAbsPosX = 0,
  mouseAbsPosY = 0;

function addMouseMoveListener(handler, object) {
  var i, o;
  for (i = 0; i < mouseMoveListeners.length; i++) {
    o = mouseMoveListeners[i];
    if (o.method == handler && o.instance == object) return false;
  }
  if (mouseMoveListeners.length == 0)
    setupEvent(document, 'mousemove', mouseMoveEventHandler);
  mouseMoveListeners.push({method: handler, instance: object});
  return true;
}

function removeMouseMoveListener(handler, object) {
  var i, o;
  for (i = 0; i < mouseMoveListeners.length; i++) {
    o = mouseMoveListeners[i];
    if (o.method == handler && o.instance == object) {
      mouseMoveListeners.splice(i, 1);
      if (mouseMoveListeners.length == 0)
        removeEvent(document, 'mousemove', mouseMoveEventHandler);
      return;
    }
  }
}

var
  activeMouseOverElement;

function mouseOverElement(event, el, func) {
  var el = $(el);
  var target = (event.target || event.toElement);
  while (target && target != el) target = target.parentNode;
  if (target && target != activeMouseOverElement) {
    activeMouseOverElement = target;
    if (func) func(target);
  }
}

function mouseOutElement(event, el, func) {
  var el = $(el);
  var target = (event.relatedTarget || event.toElement);
  while (target && target != el) target = target.parentNode;
  if (target != activeMouseOverElement && activeMouseOverElement != null) {
    if (func) func(activeMouseOverElement);
    activeMouseOverElement = null;
  }
}

function mouseMoveEventHandler(event) {
  if (document.body == null) return;
  mouseAbsPosX = event.clientX + document.body.scrollLeft;
  mouseAbsPosY = event.clientY + document.body.scrollTop;
  var i, o;
  for (i = 0; i < mouseMoveListeners.length; i++) {
    o = mouseMoveListeners[i];
    if (o.method) o.method.call(o.instance || window, event);
  }
}


function getElementBorders(el) {
  if (document && document.defaultView && document.defaultView.getComputedStyle) {
    var s = document.defaultView.getComputedStyle(el, null);
    var l = parseInt(s.borderLeftWidth);
    var r = parseInt(s.borderRightWidth);
    var t = parseInt(s.borderTopWidth);
    var b = parseInt(s.borderBottomWidth);
    return {left: l, right: r, top: t, bottom: b, vert: l+r, horiz: t+b};
  } else {
    return null;
  }
}


var
  preloadedImgs = [];

function preloadImg(src, path) {
  if (path == null) path = '';
  if (isArray(src)) {
    var res = [];
    for (var i = 0, l = src.length; i < l; i++) {
      var img = new Image();
      img.src = path + src[i];
      preloadedImgs.push(img);
      res.push(img.src);
    }
    return res;
  }
  var img = new Image();
  img.src = path + src;
  preloadedImgs.push(img);
  return img.src;
}


function sqr(x) { return x*x }

function warn(s) {
  if (window.flexumHost && flexumHost != 'flexum.ru') alert(s);
}


var
  userAgent = navigator.userAgent,
  isKHTML = (userAgent.indexOf('KHTML') >= 0),
  isOpera = (userAgent.indexOf('Opera') >= 0),
  isIE = (!isOpera && userAgent.indexOf('MSIE') >= 0),
  isIE50 = (isIE && /MSIE 5\.0/.test(userAgent) && navigator.platform == 'Win32'),
  isMozilla = (!isKHTML && !isOpera &&  userAgent.indexOf('Gecko') >= 0),
  isChrome = (userAgent.indexOf("Chrome") >= 0),
  isSafari = ((isKHTML || (navigator.vendor && (navigator.vendor.indexOf('Apple') >= 0)))&&!isChrome),
  ieVersion = 5;

  if(isIE){
     ua=userAgent.toLowerCase()
     var ieVersionString = ua.substring(ua.indexOf("msie ") + 5);
     ieVersionString = ieVersionString.substring(0, ieVersionString.indexOf(";"));
     ieVersion = 1*ieVersionString;
  }

if (isKHTML) {
  var html = document.getElementsByTagName('html')[0];
  if (html) html.style.overflowY = 'visible';
}


function callEventHandler(method, object) {
  if (method == null)     return false;
  if (!object) object = window;
  if (isFunction(method)) return method.call(object);
  if (isArray(method))    return method[0].apply(object, method.slice(1));
  if (isString(method))   return eval(method.valueOf());
  warn('callEventHandler('+method+'): unsupported method type: '+method.constructor);
  return false;
}


//-- Zoom -----------------------------------------

function zoomRight(el, grow, delta, delay) {
  if (grow != '+' && grow != '-' && grow != '') grow = '+';
  zoom(el, 'R'+grow, delta, delay);
}


var
  zoomingElements = [];

function zoom(el, grow, delta, delay) {
  el = $(el);
  if (el.zoomIntervalId) {
    clearInterval(el.zoomIntervalId);
    if(el.getAttribute('saveOverflow')){
      el.style.overflow = el.getAttribute('saveOverflow');
      el.removeAttribute('saveOverflow');
    }
    el.removeAttribute('zoomIntervalId');
    el.removeAttribute('zooming');
  }
  var direction = '', action = '';
  if (grow) {
    var s = grow.charAt(0).toUpperCase();
    if (s == 'D' || s == 'R') {
      direction = s;
      grow = grow.substr(1);
    }
  }
  if (grow) {
    var s = grow.charAt(0);
    if (s == '+' || s == '-') {
      action = s;
      grow = grow.substr(1);
    }
  }
  if (direction == '') direction = (el.zoomDirection || 'D');  // down
  el.zoomDirection = direction;
  var offsetProp = (direction == 'D' ? 'offsetHeight' : 'offsetWidth');
  var styleProp = (direction == 'D' ? 'height' : 'width');
  if (action == '') {
    if (el.zoomAction) action = (el.zoomAction == '+' ? '-' : '+')
    else action = (el[offsetProp] > 0 ? '-' : '+');
  }
  el.zoomAction = action;
  if (delta == 'quick') {
    if (action == '+') {
      el.style.display = 'block';
      el.style.visibility = 'visible';
      if (el.zoomMaxSize) el.style[styleProp] = el.zoomMaxSize+'px';
    } else {
      el.style.display = 'none';
    }
    el.style[styleProp] = (el.zoomMaxSize ? el.zoomMaxSize+'px' : '');
    el.zoomCurSize = el[offsetProp];
    if (el.afterZoom) {
      var i = zoomingElements.addItem(el);
      setTimeout('callAfterZoom('+i+')', 0);
    }
    if (action == '+') el.zoomed = true; else el.removeAttribute('zoomed');
    return;
  }
  el.zoomAlpha = 1.4;
//  el.setAttribute('saveOverflow',el.style.overflow);
  el.saveOverflow = el.style.overflow;
  el.style.overflow = 'hidden';
  if (action == '+') {
    if (!el.zoomCurSize) el.zoomCurSize = 1;
    el.style.display = 'block';
    if (el.zoomMaxSize) el.zoomNewSize = el.zoomMaxSize
    else {
      el.style[styleProp] = '';
      el.zoomNewSize = el[offsetProp];
    }
//  el.zoomDelta = Math.ceil(el.zoomNewSize/5);
  } else {
    if (!('zoomCurSize' in el)) el.zoomCurSize = el[offsetProp]/el.zoomAlpha;
    el.zoomNewSize = 0;
//  el.zoomDelta = -Math.ceil(el.zoomCurSize/5);
  }
  el.zoomDelta = delta;
//el.zoomCurSize += el.zoomDelta;
  el.style.visibility = 'visible';
  el.style[styleProp] = el.zoomCurSize+'px';
  var h = el[offsetProp];  // to prevent show full block in Fx
  el.removeAttribute('zoomed');
  el.zooming = true;
  var i = zoomingElements.addItem(el);
  el.zoomIntervalId = setInterval('stepZooming('+i+')', delay || 50);
}

function stepZooming(i) {
  var el = zoomingElements[i];
  if (el == null) return;
  var styleProp = (el.zoomDirection == 'D' ? 'height' : 'width');
  if (el.zoomDelta) {
    if (el.zoomAction == '+') el.zoomCurSize += el.zoomDelta; else el.zoomCurSize -= el.zoomDelta;
    if (el.zoomAction == '+' && el.zoomCurSize > el.zoomNewSize) el.zoomCurSize = el.zoomNewSize
    else if (el.zoomAction != '+' && el.zoomCurSize < 1) el.zoomCurSize = 0;
  } else {
    if (el.zoomAction == '+')
      el.zoomCurSize = (el.zoomCurSize > 0 ? Math.min(el.zoomCurSize*el.zoomAlpha, el.zoomNewSize) : 1);
    else
      el.zoomCurSize = (el.zoomCurSize > 1 ? Math.round(el.zoomCurSize/el.zoomAlpha) : 0);
  }
  el.style[styleProp] = el.zoomCurSize+'px';
  if (el.zoomCurSize == 0 || el.zoomCurSize == el.zoomNewSize) {
    clearInterval(el.zoomIntervalId);
    el.removeAttribute('zoomIntervalId');
    el.removeAttribute('zooming');
    el.zoomed = (el.zoomCurSize > 0);
    if (el.zoomCurSize == 0) el.style.display = 'none';
    el.style[styleProp] = (el.zoomMaxSize ? el.zoomMaxSize+'px' : '');
    el.style.overflow = el.getAttribute('saveOverflow');
    el.removeAttribute('saveOverflow');
    if (el.afterZoom) setTimeout('callAfterZoom('+i+')', 0)
    else zoomingElements.removeItemByIndex(i);
  }
}

function callAfterZoom(i) {
  var el = zoomingElements[i];
  zoomingElements.removeItemByIndex(i);
  callEventHandler(el.afterZoom, el);
}


var
  movingElements = [];

function moveAbsBlock(el, dx, dy, delay) {
  var el = $(el);
  if (el.moveIntervalId) {
    clearInterval(el.moveIntervalId);
    el.moveIntervalId = null;
  }
  if ('movePosX' in el) {
    el.moveNewX = (dx != null ? el.movePosX + dx : 0);
  } else if (dx != null) {
    el.movePosX = 0;
    el.moveNewX = dx;
  }
  if ('movePosY' in el) {
    el.moveNewY = (dy != null ? el.movePosY + dy : 0);
  } else if (dy != null) {
    el.movePosY = 0;
    el.moveNewY = dy;
  }
  if (!('movePosX' in el) && !('movePosY' in el)) return;
  if (delay == 'quick') {
    if ('moveNewX' in el) el.style.marginLeft = el.movePosX = el.moveNewX;
    if ('moveNewY' in el) el.style.marginTop  = el.movePosY = el.moveNewY;
    if (el.afterMove) callEventHandler(el.afterMove, el);
    return;
  }
  el.style.width  = el.parentNode.offsetWidth;
  el.style.height = el.parentNode.offsetHeight;
  el.parentNode.style.overflow = 'hidden';
  el.style.position = 'absolute';
  var i = movingElements.addItem(el);
  el.moveIntervalId = setInterval('stepMovingBlock('+i+')', delay || 50);
  stepMovingBlock(i);
}

function stepMovingBlock(i) {
  var el = movingElements[i];
  if (el == null) return;
  if ('moveNewX' in el) {
    el.movePosX = Math.round((el.movePosX + el.moveNewX)/2);
    if (Math.abs(el.movePosX - el.moveNewX) <= 1) el.movePosX = el.moveNewX;
    el.style.marginLeft = el.movePosX;
  }
  if ('moveNewY' in el) {
    el.movePosY = Math.round((el.movePosY + el.moveNewY)/2);
    if (Math.abs(el.movePosY - el.moveNewY) <= 1) el.movePosY = el.moveNewY;
    el.style.marginTop = el.movePosY;
  }
  if ((!('moveNewX' in el) || el.movePosX == el.moveNewX)
   && (!('moveNewY' in el) || el.movePosY == el.moveNewY)) {
    if (!el.movePosX) el.style.marginLeft = '';
    if (!el.movePosY) el.style.marginTop = '';
    if (!el.movePosX && !el.movePosY) {
      el.parentNode.style.overflow = '';
      el.style.position = '';
      el.style.width = '';
      el.style.height = '';
      log3('stepMovingBlock: el.style.position = ""');
    } else {
      log3('stepMovingBlock: el.movePosX: '+el.movePosX);
    }
    clearInterval(el.moveIntervalId);
    el.moveIntervalId = null;
    if (el.afterMove) callAfterMove(i)
    else movingElements.removeItemByIndex(i);
  }
}

function callAfterMove(i) {
  var el = movingElements[i];
  movingElements.removeItemByIndex(i);
  callEventHandler(el.afterMove, el);
}

//-- Fade -----------------------------------------------

var DEF_FADE_TIME    = 200;

var DEF_FADE_STEPS   = 4;

var DEF_DISPLAY_MODE = 'blank';   // 'visible' / 'block' / 'blank' / false
// 'visible': visibility = 'visible' / 'hidden'
// 'block': display = 'block' / 'none'
// 'blank': display = '' / 'none'
// false: никаких действий

function fadeIn(el, time, steps, displayMode) {
  fade(el, 'in', time, steps, displayMode);
}

function fadeOut(el, time, steps, displayMode) {
  fade(el, 'out', time, steps, displayMode);
}

// fade() v. 1.0
//  [how]: 'in' / 'out' (default)
//  [time]: мсек.
//  [steps]: кол-во шагов
//  [displayMode]: режим работы с блоками
//
var
  fadingElements = [];

function fade(el, how, time, steps, displayMode) {
  el = $(el);
  if (time == undefined) time = DEF_FADE_TIME;
  if (steps == undefined) steps = DEF_FADE_STEPS; else if (steps <= 0) steps = 1;
  if (el.fadeIntervalId) {
    clearTimeout(el.fadeIntervalId);
    el.fadeIntervalId = null;
  }
  el.fadeStep = ((how == 'in' ? 1 : -1)/steps);
  if (!('fadeValue' in el)) el.fadeValue = (how == 'in' ? 0 : 1);
  el.fadeValue += el.fadeStep;
  el.fadeDisplayMode = displayMode; 
  if (hasAlpha(el)) setAlpha(el, el.fadeValue);
  if (!el.alphaMode || steps == 1) {
    setVisible(el, how == 'in', displayMode);
    if (el.afterFade) callEventHandler(el.afterFade, el);
    if (el.afterFadeEnd) {
      var i = fadingElements.addItem(el);
      setTimeout('callAfterFadeEnd('+i+')', 0);
    }
    return;
  }
  if (how == 'in') setVisible(el, true, displayMode);
  var i = fadingElements.addItem(el);
  el.fadeIntervalId = setInterval('stepFading('+i+')', time/(steps-1));
}

function stepFading(i) {
  var el = fadingElements[i];
  if (el == null) return;
  el.fadeValue += el.fadeStep;
  if (el.fadeValue > 1) el.fadeValue = 1; else if (el.fadeValue < 0) el.fadeValue = 0;
  setAlpha(el, el.fadeValue);
  if (el.fadeValue <= 0 || el.fadeValue >= 1) {
    clearInterval(el.fadeIntervalId);
    el.fadeIntervalId = null;
    if (el.fadeValue <= 0) setVisible(el, false, el.fadeDisplayMode);
    if (el.afterFade) callEventHandler(el.afterFade, el);
    if (el.afterFadeEnd) setTimeout('callAfterFadeEnd('+i+')', 0);
    else fadingElements.removeItemByIndex(i);
  }
}

function callAfterFadeEnd(i) {
  var el = fadingElements[i];
  fadingElements.removeItemByIndex(i);
  callEventHandler(el.afterFadeEnd, el);
}


// hasAlpha() v. 1.0
//  возвращает: 'opacity' / 'filter' / false
//  запоминает состояние в свойстве alphaMode
//
function hasAlpha(el) {
  if (!('alphaMode' in el))
    el.alphaMode = ('opacity' in el.style ? 'opacity' : 
                     ('filter' in el.style ? 'filter' : false));
  return el.alphaMode;
}

function getAlpha(el) {
  return ('alphaValue' in el ? el.alphaValue : 1);
}

function setAlpha(el, value) {
  if (!el) return;
  if (el.alphaValue != value) {
    if (value < 0.01) value = 0;
    else if (value > 0.99) value = 1;
    el.alphaValue = value;
    if (!('alphaMode' in el)) hasAlpha(el);
    if (el.alphaMode == 'opacity')
      el.style.opacity = el.alphaValue
    else if (el.alphaMode == 'filter') 
      el.style.filter = 'alpha(opacity='+Math.round(el.alphaValue*100)+')';
  }
}


// setVisible() v. 1.0
//  value: true (show) / false (hide)
//  [displayMode] - режим показа элемента (запоминается для последующих вызовов)
//
function setVisible(el, value, displayMode) {
  if (displayMode != undefined) el.displayMode = displayMode;
  else if ('displayMode' in el) displayMode = el.displayMode;
  else displayMode = DEF_DISPLAY_MODE;
  if (displayMode != false) {
    if (displayMode == 'visible') el.style.visibility = (value ? 'visible' : 'hidden');
    else el.style.display = (value ? (displayMode == 'blank' ? '' : displayMode) : 'none');
  }
}


//-- Hint --------------------------------------
// v. 2.1, 02.03.2007

function Hint(type, defContent, w, h) {
  this.hintContainer = document.createElement('DIV');
//if (id) this.hintContainer.id = id;
  this.hintContainer.className = 'hint';
  this.type = type || 'text';
  this.defContent = defContent;
  this.width = w;
  this.height = h;
  this.inBody = false;
  this.visible = false;
  this.show = Hint_show;
  this.hide = Hint_hide;
  this.updatePos = Hint_updatePos;
  if (mouseMoveListeners.length == 0) addMouseMoveListener(null);  // add null handler to know mouse pos
}

function Hint_show(content) {
  if (content == null) content = this.defContent;
  var hintCont = this.hintContainer;
//hintCont.style.display = 'block';
//hintCont.style.visibility = 'hidden';

  hintCont.innerHTML = 
   '<table border="0" cellspacing="0" cellpadding="0"><tr><td>'+
     (this.type == 'image' ?
       '<img src="'+content+'"'+(this.w ? ' width="'+this.w+'"' : '')+(this.height ? ' height="'+this.height+'"' : '')+'>' :
       '<b></b><div>'+content+'</div><b></b>') +
   '</td></tr></table>';

  if (this.visible) return;
  hintCont.hintObject = this;
  if (!this.mouseHandlerAdded) {
    addMouseMoveListener(Hint_updatePos, this);
    this.mouseHandlerAdded = true;
  }

  if (!this.inBody) {
    document.body.appendChild(hintCont);
    this.inBody = true;
  }
  if (this.zIndex) hintCont.style.zIndex = this.zIndex;
  if (this.width) hintCont.style.width = this.width;
  if (this.fastShow) 
    setVisible(hintCont, true)
  else
    fade(hintCont, 'in');
  this.visible = true;
  var t = hintCont.getElementsByTagName('TABLE')[0];
  this.hintWidth = t.offsetWidth;
  this.hintHeight = t.offsetHeight;
  this.updatePos();
}

function Hint_hide(how) {
  if (!this.visible) return;
  this.visible = false;
  var hintCont = this.hintContainer;
  if (how == 'fast' || this.fastShow) {
    setVisible(hintCont, false);
    if (this.mouseHandlerAdded) {
      removeMouseMoveListener(Hint_updatePos, this);
      this.mouseHandlerAdded = false;
    }
    hintCont.hintObject = null;
  } else {
    if (this.mouseHandlerAdded) hintCont.afterFade = Hint_afterFadeOut;
    fade(hintCont, 'out');
  }
}

function Hint_afterFadeOut() {
  this.afterFade = null;
  var obj = this.hintObject;
  this.hintObject = null;
  obj.mouseHandlerAdded = false;
  removeMouseMoveListener(Hint_updatePos, obj);
}

function Hint_updatePos(event) {
  var body = document.body;
  if (event) {
    mouseAbsPosX = event.clientX + body.scrollLeft;
    mouseAbsPosY = event.clientY + body.scrollTop;
  }
  var d = (body.clientWidth + body.scrollLeft) - this.hintWidth;
  var x = Math.min(mouseAbsPosX, d);
  var y = mouseAbsPosY + 20;
  var h = this.hintHeight;
  var ch = body.clientHeight + body.scrollTop;
  if (y + h >= ch) y = Math.min(mouseAbsPosY, ch) - h;
  with (this.hintContainer.style) {
    left = x;
    top  = y;
  }
}

var
  hint = new Hint('text');

function hintHide() {
  hint.hide();
}


var
  requestIndicator = new Hint('image', '/i/loader_sm.gif', 14, 14);
  requestIndicator.zIndex = 1001; // WindowDefModalZIndex + 1
  requestIndicator.fastShow = true;

function requestStarted(loader, id, uri) {
  if (loader && loader.showRequestIndicator) {
    if (!('requestCount' in requestIndicator)) requestIndicator.requestCount = 1
    else requestIndicator.requestCount++;
    if (requestIndicator.requestCount == 1) requestIndicator.show();
  }
}

function requestFinished(loader, id, uri) {
  if (loader && loader.showRequestIndicator && requestIndicator.requestCount > 0) {
    requestIndicator.requestCount--;
    if (requestIndicator.requestCount == 0) requestIndicator.hide();
  }
}

window.HtmlHttpRequestStartEvent  = requestStarted;
window.HtmlHttpRequestFinishEvent = requestFinished;


//-- Window ------------------------------------
// 22.05.2008

var 
  WindowClassName   = 'window',
  WindowBGClassName = 'modal_window_background',
  WindowDefWidth    = 300,
  WindowDefHeight   = 200,
  WindowCloseBtnImg = '/i/window_close.gif',
  WindowDefZIndex   = 1,
  WindowDefModalZIndex = 1000,
  WindowDefModalGBColor = '#F5F5E2',
  WindowDefModalGBOpacity = 0.6,
  WindowDragOpacity = 0.85,
  WindowUseIFrame   = false;

function showWindow(id, title, content, w, h) {
  var wnd = document.getElementById(id);
  if (!wnd) wnd = newWindow(id, w, h);
  wnd.show(title, content);
  return wnd;
}

function showModalWindow(id, title, content, w, h) {
  var wnd = document.getElementById(id);
  if (!wnd) wnd = newWindow(id, w, h);
  wnd.showModal(title, content);
  return wnd;
}

function newWindow(id, w, h) {
  var wnd = document.createElement('DIV');
  wnd.id = id;
  wnd.className = WindowClassName;
  wnd.style.position = 'absolute';
  wnd.style.display = 'none';
  wnd.wndWidth = w || WindowDefWidth;
  wnd.wndHeight = h || WindowDefHeight;
  if (WindowUseIFrame) {
    var iframe = wnd.iframe = document.createElement('IFRAME');
//  iframe.id = id+'_iframe';
    iframe.style.position = 'absolute';
//  iframe.width = wnd.wndWidth;
//  iframe.height = wnd.wndHeight;
    iframe.frameBorder = '0';
    if (iframe.style.filter) iframe.style.filter = 'alpha(opacity=0)';
    if (location.protocol == 'https:') iframe.src = '/empty.html';
  }
  wnd.innerHTML = '<div class="sys"><b class="top"><b class="c4">&nbsp;</b><b class="c3">&nbsp;</b><b class="c2">&nbsp;</b><b class="c1">&nbsp;</b></b><table border="0" cellspacing="0" cellpadding="0"><tr><td class="title"></td><td class="buttons"><img src="'+WindowCloseBtnImg+'" width="14" height="13" alt="Закрыть" title="Закрыть"></td></tr></table></div><table class="container" border="0" cellspacing="0" cellpadding="0"><tr><td class="container"></td></tr></table><b class="bot"><b class="c1">&nbsp;</b><b class="c2">&nbsp;</b><b class="c3">&nbsp;</b><b class="c4">&nbsp;</b></b>';
  wnd.winContent = findSubChild(wnd, 'TD', 'container');
  wnd.winTitle = findSubChild(wnd, 'TD', 'title');
  wnd.contentTable = findSubChild(wnd, 'TABLE', 'container');
  wnd.buttons = findSubChild(wnd, 'TD', 'buttons');
  wnd.closeBtn = findSubChild(wnd.buttons, 'IMG', '');
  wnd.closeBtn.style.cursor = 'pointer';
  setupEvent(wnd.closeBtn, 'click', Window_closeBtnClick);
  wnd.visible = false;
  wnd.put = Window_put;
  wnd.show = Window_show;
  wnd.showModal = Window_showModal;
  wnd.afterShowHandler = Window_afterShowHandler;
  wnd.close = Window_close;
  wnd.hide = Window_close;
  wnd.bringToFront = Window_bringToFront;
  wnd.updatePos = Window_updatePos;
  return wnd;
}

function Window_closeBtnClick(event) {
  closeWindow(event.target || event.srcElement);
}

function Window_put(title, content) {
  if (title != null) this.winTitle.innerHTML = title;
  if (content != null) {
    this.winContent.innerHTML = content;
/*  this.mainForm = this.getElementsByTagName('FORM')[0];
    var inps = this.getElementsByTagName('INPUT');
    for (var i = 0; i < inps.length; i++) {
      var inp = inps[i];
      if (inp.type == 'submit') {
        this.okBtn = inp;
        break;
      }
    } */
  }
//this.updatePos();
}

var
  WindowSaveOnResize = null,
  WindowsZList = [],
  WindowsModalList = [],
  WindowModalEscHotkeyId = null;

var WinBusy = '';

function Window_show(title, content, isModal) {
  if (WinBusy) {
    alert('on show: busy = '+WinBusy);
    return;
  }
  WinBusy = 'show';
  if (title || content) this.put(title, content);
  if (this.visible) {
    this.bringToFront();
    WinBusy = '';
    return;
  }
  this.visible = true;
  this.isModal = isModal;
  var l = WindowsZList.length;
  this.zIndex = Math.max((l > 0 ? WindowsZList[l-1].zIndex+1 : 0),
                         (isModal ? WindowDefModalZIndex : WindowDefZIndex));
  WindowsZList.push(this);

  if (isModal) {
    if (!this.bg) {
      this.bg = document.createElement('DIV');
      if (WindowBGClassName) this.bg.className = WindowBGClassName;
      this.bg.style.zIndex = this.zIndex;
      this.bg.style.position = 'absolute';
      this.bg.style.width = '100%';
      this.bg.style.height = Math.max(document.body.scrollHeight, document.body.clientHeight)+'px';
      this.bg.style.top = '0px';
      this.bg.style.left = '0px';
      var c = this.bgColor || WindowDefModalGBColor;
      var o = this.bgOpacity || WindowDefModalGBOpacity;
      if (o != null) {
        if (window.hasAlpha) {
          if (hasAlpha(this.bg)) {
            setAlpha(this.bg, o);
            if (c) this.bg.style.backgroundColor = c;
          }
        } else {
          if ('opacity' in this.style) {
            if (c) this.bg.style.backgroundColor = c;
            this.bg.style.opacity = o;
          } else if ('filter' in this.style) {
            if (c) this.bg.style.backgroundColor = c;
            this.bg.style.filter = 'alpha(opacity = '+Math.round(o*100)+')';
          }
        }
      }
//    this.bg.style.cursor = 'wait';
    }
    document.body.appendChild(this.bg);
    if (WindowsModalList.length == 0) {
      WindowSaveOnResize = document.body.getAttribute('onresize');
      document.body.setAttribute('onresize',
        (typeof(WindowSaveOnResize) == 'string' || isMozilla ? 'Window_bgResize(event)' : Window_bgResize));
      if (window.setupHotKey) {
        WindowModalEscHotkeyId = setupHotKey('Esc', closeTopModalWindow);
      }
    }
    WindowsModalList.push(this);
  }
  if (this.iframe) {
    this.iframe.style.display = 'none';
    document.body.appendChild(this.iframe);
  }
  document.body.appendChild(this);
  if (!this.mouseListenerActive) {
    setupEvent(this, 'mousedown', Window_mouseDownListener);
    this.mouseListenerActive = true;
  }
  this.style.width = this.wndWidth;
//this.style.height = this.wndHeight;
//this.contentTable.style.width = this.wndWidth;
//this.contentTable.style.height = this.wndHeight;
  this.style.zIndex = this.zIndex;
  this.style.visibility = 'hidden';
  this.style.display = 'block';
  if (this.contentTable.offsetHeight < this.wndHeight) {
    this.contentTable.style.height = this.wndHeight;
  }
  if (this.iframe) {
    this.iframe.style.zIndex = this.zIndex;
    this.iframe.style.width = this.offsetWidth+'px';
    this.iframe.style.height = this.offsetHeight+'px';
  }
  this.updatePos();
  if (this.iframe) this.iframe.style.display = 'block';
  if (this.beforeShow) this.beforeShow();
  if (window.fadeIn) {
    this.afterFade = this.afterShowHandler;
    fadeIn(this, null, 2, 'visible');
    this.afterShowHandler('fade');
  } else {
    this.style.display = 'block';
    this.style.visibility = 'visible';
    this.afterShowHandler();
  }
  WinBusy = '';
}

function Window_showModal(title, content) {
  this.show(title, content, true);
}

function focusElement(el, container) {
  el = $_(el, container);
  if (el && el.focus) el.focus();
}

function Window_afterShowHandler(prm) {
  if (prm != 'fade') this.afterFade = null;
  if (this.afterShow) this.afterShow(prm);
  if (this.focusElementId) focusElement(this.focusElementId, this);
}

function closeTopModalWindow() {
  var i = WindowsModalList.length;
  if (i > 0) WindowsModalList[i-1].close();
}

function getWindowByElement(el) {
  while (el && el.tagName != 'BODY') {
    if (el.tagName == 'DIV' && el.className == WindowClassName) return el;
    el = el.parentNode;
  }
  return null;
}

function closeWindow(el) {
  var wnd = getWindowByElement(el);
  if (wnd) wnd.close();
}

function Window_close() {
  if (WinBusy) {
    alert('on close: busy = '+WinBusy);
    return;
  }
  WinBusy = 'close';
  if (this.canClose) 
    if(!this.canClose()){
      WinBusy = '';
      return;
    }
  if (!this.visible) return;
  this.visible = false;
  if (this.dlgRequestActive) {
    this.dlgRequestActive = false;
    if (window.cancelDlgRequest) cancelDlgRequest(this.id);
  } else if (this.requestActive) {
    this.requestActive = false;
    requestFinished();
  }
  Window_removeMouseUpListener();
  if (!window.fadeOut) {
    this.style.display = 'none';
    this.style.visibility = 'hidden';
    if (this.parentNode) this.parentNode.removeChild(this);
  } else {
    this.afterFade = Window_afterFadeOut; // parentNode.removeChild(this)
    fadeOut(this, null, 2);
  }
  if (this.iframe) this.iframe.parentNode.removeChild(this.iframe);
  if (this.isModal) {
    this.bg.parentNode.removeChild(this.bg);
    WindowsModalList.pop();
    if (WindowsModalList.length == 0) {
      document.body.setAttribute('onresize', WindowSaveOnResize);
      if (WindowSaveOnResize == null)
        document.body.removeAttribute('onresize')
      else
        WindowSaveOnResize = null;
      if (WindowModalEscHotkeyId != null) {
        removeHotKey(WindowModalEscHotkeyId);
        WindowModalEscHotkeyId = null;
      }
    }
  }
  WindowsZList.removeItem(this);
  if (this.onClose) this.onClose();
  this.mainForm = null;
  this.okBtn = null;
  if (this.reloadOnClose) location.reload(false);
  WinBusy = '';
}

function Window_afterFadeOut() {
  this.afterFade = null;
  if (this.parentNode) this.parentNode.removeChild(this);
}

function Window_bringToFront() {
  var k = WindowsZList.removeItem(this);
  if (k >= 0) {
    WindowsZList.push(this);
    var ind = (k > 0 ? WindowsZList[k-1].zIndex+1 : this.zIndex);
    for (var i = k; i < WindowsZList.length; i++) {
      var w = WindowsZList[i];
      w.zIndex = ind;
      w.style.zIndex = ind;
      if (w.iframe) w.iframe.style.zIndex = ind;
      ind++;
    }
  }
}

function Window_updatePos() {
  var x = (Math.max(Math.round((document.body.clientWidth-this.offsetWidth)/2), 0) + document.body.scrollLeft)+'px';
  var y = (Math.max(Math.round((document.body.clientHeight-this.offsetHeight)/2), 0) + document.body.scrollTop)+'px';
  this.style.left = x;
  this.style.top = y;
  if (this.iframe) {
    this.iframe.style.left = x;
    this.iframe.style.top = y;
  }
}

function Window_bgResize(event) {
  for (var i = 0; i < WindowsModalList.length; i++) {
    var w = WindowsModalList[i];
    var x = Math.round((document.body.offsetWidth-w.offsetWidth)/2)+'px';
    w.style.left = x;
    if (w.iframe) w.iframe.style.left = x;
    w.bg.style.height = Math.max(document.body.scrollHeight, document.body.clientHeight);
  }
  if (WindowSaveOnResize) {
    if (typeof(WindowSaveOnResize) == 'function') WindowSaveOnResize(event);
    else eval(WindowSaveOnResize);
  }
}

var
  WindowMouseUpListenerCount = 0;

function Window_addMouseUpListener() {
  WindowMouseUpListenerCount++;
  if (WindowMouseUpListenerCount == 1) {
    setupEvent(document.body, 'mouseup', Window_mouseUpListener);
  }
}

function Window_removeMouseUpListener() {
  if (WindowMouseUpListenerCount > 0) {
    WindowMouseUpListenerCount--;
    if (WindowMouseUpListenerCount == 0) {
      removeEvent(document.body, 'mouseup', Window_mouseUpListener);
    }
  }
}

function isLeftButtonEvent(event) {
  if (isIE) {
    if (event.button == 1) return true;
  } else 
    if (event.button == 0) return true;
  return false;
}

var
  curDragWindow = null;

function Window_mouseDownListener(event) {
  if (!isLeftButtonEvent(event) || curDragWindow != null) return;
  var src = event.target || event.srcElement;
  var el = src, inTitle = false;
  do {
    if (el.tagName == 'DIV') {
      if (el.className == WindowClassName) break;
      if (el.className == 'sys') inTitle = true;
    }
    el = el.parentNode;
    if (!el || el.tagName == 'BODY') return;
  } while (true);
  if (!el.isModal) el.bringToFront();
  if (!inTitle || src.tagName == 'IMG') return;  // window body or [X] button
  if (WindowDragOpacity < 1) setAlpha(el, WindowDragOpacity);
  el.draggingWindow = true;
  curDragWindow = el;
  var pos = getAbsPos(el);
  el.dragDeltaX = pos.left - (event.clientX + document.body.scrollLeft);
  el.dragDeltaY = pos.top  - (event.clientY + document.body.scrollTop);
  addMouseMoveListener(Window_mouseMoveListener, el);
  Window_addMouseUpListener();
}

function Window_mouseMoveListener(event) {
  var el = curDragWindow;
  var x = (mouseAbsPosX + el.dragDeltaX)+'px';
  var y = (mouseAbsPosY + el.dragDeltaY)+'px';
  el.style.left = x;
  el.style.top  = y;
  if (el.iframe) {
    el.iframe.style.left = x;
    el.iframe.style.top  = y;
  }
}

function Window_mouseUpListener(event) {
  if (!isLeftButtonEvent(event) || curDragWindow == null) return;
  removeMouseMoveListener(Window_mouseMoveListener, curDragWindow);
  Window_removeMouseUpListener();
  if (WindowDragOpacity < 1) setAlpha(curDragWindow, 1);
  curDragWindow.draggingWindow = false;
  curDragWindow = null;
}

//-- Hotkeys ---------------------------------------------
// v. 1.0  27.02.2007

var
  shiftKeyPressed = false,
  ctrlKeyPressed = false,
  altKeyPressed = false;

var
  hotKeyLastId = 0,
  hotKeyDownListenerAcrive = false,
  hotKeyUpListenerAcrive = false,
  hotKeysList = [],
  shiftHotKeysList = [];

function setupHotKey(hotKey, handler) {
  var key = parseHotKey(hotKey);
  if (!key) return false;
  key.id = (++hotKeyLastId);
  key.handler = handler;
  hotKeysList.push(key);
  if (!hotKeyDownListenerAcrive) {
    setupEvent(document, 'keydown', hotKeyDownListener);
    hotKeyDownListenerAcrive = true;
  }
  return hotKeyLastId;
}

function removeHotKey(id) {
  for (var i = 0; i < hotKeysList.length; i++) {
    if (hotKeysList[i].id == id) {
      hotKeysList.splice(i, 1);
      return;
    }
  }
}

// setupShiftHotKey('Ctrl', 'down', 'alert("Ctrl key is down")');
// setupShiftHotKey('Ctrl', true, myHandler);  // true - down, false - up
function setupShiftHotKey(hotKey, down, handler) {
  var key = parseShiftHotKey(hotKey);
  if (!key) return false;
  key.id = (++hotKeyLastId);
  if (typeof(down) == 'string') {
    down = down.toLowerCase();
    if (down == 'down') down = true
    else if (down == 'up') down = false
  }
  key.down = Boolean(down);
  key.handler = handler;
  shiftHotKeysList.push(key);
  if (!hotKeyDownListenerAcrive) {
    setupEvent(document, 'keydown', hotKeyDownListener);
    hotKeyDownListenerAcrive = true;
  }
  if (!hotKeyUpListenerAcrive) {
    setupEvent(document, 'keyup', hotKeyUpListener);
    hotKeyUpListenerAcrive = true;
  }
  return hotKeyLastId;
}

function removeShiftHotKey(id) {
  for (var i = 0; i < shiftHotKeysList.length; i++) {
    if (shiftHotKeysList[i].id == id) {
      shiftHotKeysList.splice(i, 1);
      return;
    }
  }
}


function parseHotKey(hotKey) {
  if (typeof(hotKey) != 'string') return false;
  var s = hotKey.toLowerCase();
  var shifts = 0;
  if (s.match(/^(shift|ctrl|alt)(\+|-)(.+)/i)) {
    var sh = RegExp.$1.toLowerCase();
    shifts = (sh == 'shift' ? 1 : (sh == 'ctrl' ? 2 : 4));
    s = RegExp.$3;
  }
  s = s.toUpperCase();
  var codes = null;
  if (s.length == 1 && ((s >= 'A' && s <= 'Z') || (s >= '0' && s <= '9')))
    codes = s.charCodeAt(0);
  else {
    for (var i = 0; i < keyCodes.length; i++) {
      if (keyCodes[i][1].toUpperCase() == s) {
        if (codes == null) codes = keyCodes[i][0]
        else {
          if (typeof(codes) == 'number') codes = [codes];
          codes.push(keyCodes[i][0]);
        }
      }
    }
  }
  return (codes ? {shift: shifts, key: codes} : false);
}

function parseShiftHotKey(hotKey) {
  if (typeof(hotKey) != 'string') return false;
  var key;
  hotKey = hotKey.toLowerCase();
  if (hotKey == 'shift') key = 16
  else if (hotKey == 'ctrl') key = 17
  else if (hotKey == 'alt') key = 18
  else return false;
  return {shiftKey: key};
}

var
  keyCodes = [
    [27,  'Esc'],

    [112, 'F1'],
    [113, 'F2'],
    [114, 'F3'],
    [115, 'F4'],
    [116, 'F5'],
    [117, 'F6'],
    [118, 'F7'],
    [119, 'F8'],
    [120, 'F9'],
    [121, 'F10'],
    [122, 'F11'],
    [123, 'F12'],
    
    [192, '`'],
    [109, '-'], // ff
    [189, '-'], // IE
    [61,  '='], // ff  // =
    [187, '='], // IE
//  [92,  '\\'] // Opera
    [220, '\\'], // ff, IE
    [226, '\\'], // ff, IE
    [8,   'BackSpace'],

    [9,   'Tab'],
    [13,  'Enter'],
    
    [20,  'CapsLock'],
    [219, '['],
    [221, ']'],
    [59,  ';'],  // ff // =
    [186, ';'],  // IE
    [222, '\''],
    [188, ','],
    [190, '.'],
    [191, '/'],

    [32,  'Space'],

//  [16,  'Shift'],
//  [17,  'Ctrl'],
//  [18,  'Alt'],
//  [91,  'LWin'],
//  [92,  'RWin'],
    [93,  'Menu'],

    [37,  'Left'],
    [38,  'Up'],
    [39,  'Right'],
    [40,  'Down'],

//  [45,  '-'],   // Opera
    [45,  'Ins'],
    [46,  'Del'],
    [36,  'Home'],
    [35,  'End'],
    [33,  'PageUp'],
    [34,  'PageDown'],
    [19,  'Pause'],

    [145, 'ScrollLock'],
    [144, 'NumLock'],
    
    [111, 'Gray/'],
    [106, 'Gray*'],
    [109, 'Gray-'],
    [107, 'Gray+'],
    
    [96,  'Num0'],
    [97,  'Num1'],
    [98,  'Num2'],
    [99,  'Num3'],
    [100, 'Num4'],
    [101, 'Num5'],
    [102, 'Num6'],
    [103, 'Num7'],
    [104, 'Num8'],
    [105, 'Num9'],

    [12,  'Num_'], // Num 5

    [110, '.']     // Num.
  ];

function hotKeyDownListener(event) {
  var keyCode = event.keyCode;
  if (keyCode >= 16 && keyCode <= 18) {
    var pressed = false;
    switch (keyCode) {
      case 16:
        if (!shiftKeyPressed) {
          shiftKeyPressed = true;
          pressed = true;
        }
        break;

      case 17:
        if (!ctrlKeyPressed) {
          ctrlKeyPressed = true;
          pressed = true;
        }
        break;

      case 18:
        if (!altKeyPressed) {
          altKeyPressed = true;
          pressed = true;
        }
    } 
    if (pressed) {
      for (var i = 0; i < shiftHotKeysList.length; i++) {
        var h = shiftHotKeysList[i];
        if (h.shiftKey == keyCode && (h.down == true || h.down == null) && h.handler) {
          callEventHandler(h.handler, h);
        }
      }
    }
  } else {
    var shift = 0;
    if (event.shiftKey) shift |= 1;
    if (event.ctrlKey)  shift |= 2;
    if (event.altKey)   shift |= 4;
    var cancel = false;
    for (var i = 0; i < hotKeysList.length; i++) {
      var h = hotKeysList[i];
      var found = false;
      if (h.shift == shift) {
        if (typeof(h.key) == 'number') {
          if (h.key == keyCode) found = true;
        } else if (h.key.length) {
          for (var j = 0; j < h.key.length; j++) {
            if (h.key[j] == keyCode) {
              found = true;
              break;
            }
          }
        }// else alert('typeof(h.key) == '+typeof(h.key));
        if (found && h.handler) {
          if (callEventHandler(h.handler, h)) cancel = true;
        }
      }
    }
    if (cancel) cancelEvent(event);
  }
}

function hotKeyUpListener(event) {
  var keyCode = event.keyCode;
  if (keyCode == 16) shiftKeyPressed = false
  else if (keyCode == 17) ctrlKeyPressed = false
  else if (keyCode == 18) altKeyPressed = false
  else return;
  var cancel = false;
  for (var i = 0; i < shiftHotKeysList.length; i++) {
    var h = shiftHotKeysList[i];
    if (h.shiftKey == keyCode && !h.down && h.handler) {
      if (callEventHandler(h.handler, h)) cancel = true;
    }
  }
  if (cancel) cancelEvent(event);
}


//-- Dialogs --------------------------------------

function loadDlg(url, id, onCopyContent) {
  sendDlgRequest(id, onCopyContent, url);
}

function sendDlgData(form, id, evnt, onCopyContent) {
  sendDlgRequest(id, onCopyContent, form, evnt);
}

var
  dlgRequest = null;

function sendDlgRequest(id, onCopyContent, url_form, evnt) {
  if (!dlgRequest) {
    dlgRequest = new RemoteFileLoader('dlgRequest');
    dlgRequest.onCopyContent = dlgRequest_onCopyContent;
    dlgRequest.onCopyContentEvents = {};
    dlgRequest.requestDlgs = {};
    dlgRequest.showRequestIndicator = true;
  }
  if (id in dlgRequest.onCopyContentEvents) dlgRequest.cancel(id);
  dlgRequest.onCopyContentEvents[id] = onCopyContent;
  if (evnt) {
//  alert('submitInto('+url_form.getAttribute('action')+')');
    var dlg = dlgRequest.requestDlgs[id] = getWindowByElement(url_form);
    if (dlg) dlg.dlgRequestActive = true;
    dlgRequest.submitInto(url_form, id, evnt);
  } else {
//  alert('loadInto('+url_form+')');
    dlgRequest.loadInto(url_form, id);
  }
}

function dlgRequest_onCopyContent(doc, text, id) {
  if (!(id in dlgRequest.onCopyContentEvents)) return false;
  var callback = dlgRequest.onCopyContentEvents[id];
  delete dlgRequest.onCopyContentEvents[id];
  if (id in dlgRequest.requestDlgs) {
    var dlg = dlgRequest.requestDlgs[id];
    delete dlgRequest.requestDlgs[id];
    if (dlg) dlg.dlgRequestActive = false;
  }
  return (callback ? callback(doc, text, id) : false);
}

function cancelDlgRequest(id) {
  if (dlgRequest && (id in dlgRequest.onCopyContentEvents)) dlgRequest.cancel(id);
}

//-- Function autologin on mirror -----------------------

var
  loginDlg = null,
  loginResult = null;  // callback, вызывающийся из login_frame
  please = null;
  remainCountTest = 0;
  thisMirror = null;
  inMirrorTest = null;

function AbortTimer(){
  try{
    var el=window.frames['flexum_login_frame'];
    if(el){
      var x=el.location.href;
      document.getElementById('remain_tima').innerHTML=x;
      if(inMirrorTest)
        if(inMirrorTest.test(x))
          remainCountTest=2;
    }else{
      el=document.getElementById('flexum_login_frame');
      if(el){
        var x=el.contentDocument.location.href;
        if(inMirrorTest)
          if(inMirrorTest.test(x))
            remainCountTest=2;
      }
    }
  }finally{

  }
}

function testLoginInFlexum(){
  document.getElementById('remain_time').innerHTML=''+Math.floor(remainCountTest/60)+':'+Math.floor((remainCountTest%60)/10)+(remainCountTest%10);
  if(remainCountTest>3){
    window.setTimeout(function(){AbortTimer()},100);
  }
  if(remainCountTest<=1){
    please.canClose=null;
    please.close();
  }
}

function setMirror(Mirror){
  thisMirror=Mirror;
  inMirrorTest=new RegExp("http:\/\/"+Mirror+"\/.*","i");
}

//-- Login dialog ---------------------------------------


function loginUser() {
  if (!loginDlg) {
    loginDlg = newWindow('login_dlg', 320, 180);
  }
  loginDlg.focusElementId = 'user_login';
  loginDlg.showModal('Авторизация', loginDlg_getHTML('login_frame'));
  if(thisMirror){
    if (!please){
      please = newWindow('pause_form', 320, 80);
    }
    please.canClose=function(){return false;};
    var r=Math.floor(Math.random()*100000); //Убиваем кеширование браузера
    please.showModal('Секундочку...', 'Пожалуйста, подождите...<br /><span id="remain_time"></span><span id="remain_tima" style="display:none"></span><br /><iframe style="display:none" id="flexum_login_frame" width="100" height="100" src="http://flexum.ru/cookie.html?randp='+r+'&amp;GET='+thisMirror+'"></iframe>');
    remainCountTest=30; // Ждём 30 секунд, если flexum за это время не ответил, то разрешаем войти. Если ответил, то время будет уменьшено.
    window.setTimeout(function(){testLoginInFlexum();if(--remainCountTest>0)window.setTimeout(arguments.callee,1000);},1000);
  }
}


var
  NO_CLOSE_BTN = 1;

function loginDlg_getHTML(target, flags) {
  var showCloseBtn = (!flags || ((flags & NO_CLOSE_BTN) == 0));/*http://www.'+flexumHost+'*/
  return '\n\
    <form action="/auth.html" method="post"'+(target ? ' target="'+target+'"' : '')+' onSubmit="loginDlg_submitForm(this, event)">\n\
     <table width="100%" border="0">\n\
      <tr>\n\
       <td>\n\
        Логин\n\
       </td>\n\
       <td>\n\
        <input type="text" id="user_login" name="login" value="" style="width: 100%" />\n\
       </td>\n\
       <td>\n\
       </td>\n\
      </tr>\n\
      <tr>\n\
       <td>\n\
        <span style="position:relative;top: +7px">Пароль&nbsp;&nbsp;&nbsp;</span><br/>\n\
    <small onClick="document.getElementById(\'spass\').checked=!document.getElementById(\'spass\').checked;LoginShowPasswd();if(document.getElementById(\'spass\').checked)this.innerHTML=\'(скрыть)\';else this.innerHTML=\'(показать)\';" class="js" style="position:relative;top: +2px;left: +1px">(показать)</small>\n\
       </td>\n\
       <td width="70%" id="passI">\n\
        <input type="password" id="user_password" name="password" value="" style="width: 100%" />\n\
       </td>\n\
       <td>\n\
        <small onClick="requestPassword()" class="js"><nobr>Забыли?</nobr></small>\n\
        <input style="display:none" type="checkbox" id="spass" />\n\
       </td>\n\
      </tr>\n\
      <tr>\n\
       <td>&nbsp;</td>\
       <td colspan=2>\n\
        <nobr><input type="checkbox" id="user_remember" name="remember" /><label for="user_remember">&nbsp;Запомнить меня</label></nobr>\n\
       </td>\n\
      </tr>\n\
      <tr>\n\
       <td>&nbsp;</td>\n\
       <td colspan="2">\n\
        <div class="login_dlg_error">\n\
         <div id="login_error" class="error" style="display: none; background-color: #EE0000; color: #FFFFFF; padding: 0 0.5em"></div>\n\
        </div>\n\
       </td>\n\
      </tr>\n\
      <tr>\n\
       <td>\n'+/*http://www.'+flexumHost+'*/
       (flexumHost != 'flexum.ru' ? '\
        <a href="/help_hint_authorize.html" onClick="showHelpHint(\'authorize\'); return false"><img src="/i/help_big.gif" width="23" height="23" border="0" alt="Помощь"/><br /></a>' : '\
        &nbsp;') + '\n\
       </td>\n\
       <td colspan="2" align="right">\n\
        <input id="login_ok_btn" type="submit" value="  Войти  " />&nbsp;&nbsp;\n'+
      (showCloseBtn ? '\
        <input id="login_cancel_btn" type="submit" value="Закрыть" onClick="closeWindow(this); return false" />\n' 
        : '') + '\
        <input id="login_redirect_path" type="hidden" name="path" value="" />\n\
       </td>\n\
      </tr>\n\
     </table>\n\
    </form>';
}

var
  loginSubmited = null;

function loginDlg_submitForm(form, evnt) {
  if(remainCountTest) return false;
  if (!loginDlg || !loginDlg.visible) {
    if (loginDlg && loginDlg.isBrowserWindow) {  // отдельное окно (addurl) 
      with ($('login_ok_btn')) {
        focus();
        disabled = true;
      }
      loginSubmited = true;
      return true;
    } else {  // логин через newWindow после закрытия окна
      cancelEvent(evnt);
      return false;
    }
  }
//отправляем запрос из окошка
  with ($('login_ok_btn')) {
    focus();
    disabled = true;
  }
  $('login_redirect_path').value = 'http://'+location.host+'/auth.html';
  loginDlg.requestActive = true;
  requestStarted();
  loginResult = loginDlg_loginResult;
  loginSubmited = true;
}


// вызывается из iframe
function loginDlg_loginResult(loggedIn, errorMsg, cf) {
  if (!loginDlg || !(loginDlg.visible || loginDlg.isBrowserWindow)) return;
  loginDlg.requestActive = false;
  requestFinished();
  if (loggedIn) {
//  loginDlg.close();
//  document.cookie = '';
    if(cf){
      location.href="http://"+thisMirror+"/cookie.html?GETFS="+cf+"&path="+escape(location.href);
    }else{
      location.reload(false);
    }
  } else {
    $('login_ok_btn').disabled = false;
    with ($('user_password')) {
      value = '';
      focus();
    }
    var errorFld = $('login_error');
    errorFld.innerHTML = errorMsg;
    zoom(errorFld, '+');
    setTimeout('loginDlg_hideError()', 5000);
  }
}

function loginDlg_hideError() {
  if (!loginDlg || !(loginDlg.visible || loginDlg.isBrowserWindow)) return;
  var errorFld = $('login_error');
  if (errorFld) zoom(errorFld, '-');
}


//-- Login / Signup dialog ------------------

var
  loginSignupDlg = null;

function loginSignupUser() {
  if (!loginSignupDlg) {
    loginSignupDlg = newWindow('login_signup_dlg', 350, 180);
  }
  loginSignupDlg.focusElementId = 'user_signup_name';
  loginSignupDlg.showModal('Необходима авторизация', loginSignupDlg_getHTML('login_frame'));
}

function loginSignupDlg_getHTML(target) {/*http://www.'+flexumHost+'*/
  return '\n\
   <div id="login_signup_block">\n\
    <table width="100%" border="0" cellspacing="0" cellpadding="8"><tr><td>\n\
\n\
     <div id="login_signup_container">\n\
      <table class="switch" border="0" cellspacing="0" cellpadding="0" style="margin-bottom: 0.5em;">\n\
       <tr>\n\
        <td><b>Регистрировались раньше?</b>&#160;</td>\n\
        <td id="user_login_switch" onClick="switchLoginSignup(\'login\')">\n\
         <i></i>\n\
         <div><span>Да</span></div>\n\
         <i></i>\n\
        </td>\n\
        <td id="user_signup_switch" class="selected" onClick="switchLoginSignup(\'signup\')">\n\
         <i></i>\n\
         <div><span>Нет</span></div>\n\
         <i></i>\n\
        </td>\n\
       </tr>\n\
      </table>\n\
\n\
      <form id="user_login_form" action="/auth.html" method="post"'+(target ? ' target="'+target+'"' : '')+' onSubmit="loginSignupDlg_submitLoginForm(this, event)">\n\
       <table id="user_login_block" style="display: none" width="100%" border="0">\n\
        <tr>\n\
         <td>Логин</td>\n\
         <td><input type="text" id="user_login" name="login" value="" style="width:100%"/>\n\
     </td><td>&#160;&#160;</td>\n\
        </tr>\n\
        <tr>\n\
         <td><span style="position:relative;top: +7px">Пароль&#160;&#160;&#160;</span><br/>\n\
     <small onClick="document.getElementById(\'spass\').checked=!document.getElementById(\'spass\').checked;LoginShowPasswd();if(document.getElementById(\'spass\').checked)this.innerHTML=\'(скрыть)\';else this.innerHTML=\'(показать)\';" class="js" style="position:relative;top: +2px;left: +1px">(показать)</small>\n\
     </td>\n\
         <td width="70%" id="passI">\n\
          <input type="password" id="user_password" name="password" value="" style="width: 100%" />\n\
         </td>\n\
         <td>\n\
      <input style="display:none" type="checkbox" id="spass" />\n\
      <small onClick="requestPassword()" class="js">Забыли?</small>\n\
         </td>\n\
        </tr>\n\
        <tr>\n\
         <td>&#160;</td>\n\
         <td colspan="2">\n\
          <input type="checkbox" id="user_remember" name="remember" />\n\
          <label for="user_remember">Запомнить&#160;меня</label>\n\
          <input type="hidden" id="user_login_redirect_path" name="path" value="" />\n\
         </td>\n\
        </tr>\n\
        <tr>\n\
         <td>&#160;</td>\n\
         <td colspan="2">\n\
          <div class="login_dlg_error">\n\
           <div id="user_login_error" class="error" style="display: none; background-color: #EE0000; color: #FFFFFF; padding: 0 0.5em"></div>\n\
          </div>\n\
         </td>\n\
        </tr>\n\
        <tr>\n\
         <td>&#160;</td><td colspan="2" align="right">\n\
          <input id="user_login_ok_btn" type="submit" value="  Войти  " />&#160;&#160;\n\
          <input id="user_login_cancel_btn" type="button" value="Закрыть" onClick="closeWindow(this)" />\n\
         </td>\n\
        </tr>\n\
       </table>\n\
      </form>\n\
\n\
      <div id="signup_container">\n\
       <form id="user_signup_form" action="/user_reg.html" method="get" onSubmit="loginSignupDlg_submitSignupForm(this, event)">\n\
        <table id="user_signup_block" width="100%" border="0" cellspacing="0" cellpadding="0">\n\
         <tr>\n\
          <td colspan="3" style="padding-bottom: 0.3em;">Просто укажите</td>\n\
         </tr>\n\
         <tr>\n\
          <td nowrap="nowrap">желаемый логин&#160;</td>\n\
          <td width="50%">\n\
           <input type="text" id="user_signup_name" name="username" value="" style="width: 100%" />\n\
          </td>\n\
          <td class="pl05"><small class="pale">латинские <nobr>буквы, цифры</nobr></small></td>\n\
         </tr>\n\
         <tr>\n\
          <td nowrap="nowrap">и свой e-mail&#160;</td>\n\
          <td>\n\
           <input type="text" id="user_signup_email" name="email" value="" style="width: 100%" />\n\
          </td>\n\
         </tr>\n\
         <tr>\n\
          <td colspan="3" align="right">\n\
           <br /><br />\n\
           <input id="user_signup_ok_btn" type="submit" value="Отправить" />&#160;&#160;\n\
           <input id="user_signup_cancel_btn" type="button" value="Закрыть" onClick="closeWindow(this)" />\n\
          </td>\n\
         </tr>\n\
        </table>\n\
       </form>\n\
      </div>\n\
\n\
     </div>\n\
\n\
     <div id="signup_result_msg" style="display: none">\n\
      <b>Вы успешно зарегистрированы.</b><br /><br />\n\
      Проверьте ваш почтовый ящик и <span class="js" onClick="switchLoginSignup(\'login\')">введите высланный вам пароль</span>.\n\
     </div>\n\
\n\
    </td></tr></table>\n\
   </div>';
}

function loginSignupDlg_submitLoginForm(form, event) {
  if (!loginSignupDlg || !loginSignupDlg.visible) {
    cancelEvent(event);
    return false;
  }
//отправляем запрос из окошка
  with ($('user_login_ok_btn')) {
    focus();
    disabled = true;
  }
  $('user_login_redirect_path').value = 'http://'+location.host+'/auth.html';
  loginSignupDlg.requestActive = true;
  requestStarted();
  loginResult = loginSignupDlg_loginResult;
}

// вызывается из iframe
function loginSignupDlg_loginResult(loggedIn, errorMsg) {
//alert('loginResult('+loggedIn+(errorMsg ? ', "'+errorMsg+'"' : '')+')');
  if (!loginSignupDlg || !loginSignupDlg.visible) return;
  loginSignupDlg.requestActive = false;
  requestFinished();
  if (loggedIn) {
//  loginDlg.close();
//  document.cookie = '';
    location.reload(false);
  } else {
    $('user_login_ok_btn').disabled = false;
    with ($('user_password')) {
      value = '';
      focus();
    }
    var errorFld = $('user_login_error');
    errorFld.innerHTML = errorMsg;
    zoom(errorFld, '+');
    setTimeout('loginSignupDlg_hideError()', 5000);
  }
}

function loginSignupDlg_hideError() {
  if (!loginSignupDlg || !loginSignupDlg.visible) return;
  var errorFld = $('user_login_error');
  if (errorFld) zoom(errorFld, '-');
}

function loginSignupDlg_submitSignupForm(form, event) {
  if (!loginSignupDlg || !loginSignupDlg.visible) {
    cancelEvent(event);
    return false;
  }
  with ($('user_signup_ok_btn')) {
    focus();
    disabled = true;
  }
  var err = $('user_signup_name_error');
  if (err) err.style.display = 'none';
  var err = $('user_signup_email_error');
  if (err) err.style.display = 'none';
  loginSignupDlg.userNameToReg = trim($('user_signup_name').value);
  sendDlgData(form, loginSignupDlg.id, event, loginSignupDlg_signupRequestSent);
}

function loginSignupDlg_signupRequestSent(doc, text, id) {
  if (text == null || !loginSignupDlg || !loginSignupDlg.visible) return true;
  if (text.match(/ id="user_signup_status">Ok</i)) {
//  alert('Вы успешно зарегистрированы.\n\nПроверьте ваш почтовый ящик\nи введите высланный вам пароль.\n');
//  switchLoginSignup('login');
    $('user_signup_ok_btn').blur();
    $('user_login').value = loginSignupDlg.userNameToReg;
    $('user_password').value = '';
    $('login_signup_container').style.display = 'none';
    $('signup_result_msg').style.display = 'block';
  } else {
    $('signup_container').innerHTML = text;
    $('user_signup_buttons').style.display = '';
    if ($('user_signup_name_error')) $('user_signup_name').focus()
    else $('user_signup_email').focus();
    $('user_signup_ok_btn').disabled = false;
  }
  return true;
}

//-- Login / Signup dialog block ------------------

var
  userWasRegistered = false,
  lastUserLoginName = '',
  signInDlg = null;

function loginSignupInit() {
  switchLoginSignup((userWasRegistered ? 'login' : 'signup'), 'nofocus');
//this.focusElementId = (userWasRegistered ? 
//    (lastUserLoginName == '' ? 'user_login' : 'user_password') :
//      'user_signup_name');
  if (userWasRegistered) $('user_login').value = lastUserLoginName;
}

function loginSignupDlg_onClose() {
  if (signInDlg) {
    signInDlg.mainForm = null;
    signInDlg.okBtn = null;
    signInDlg = null;
  }
}

function switchLoginSignup(what, nofocus) {
  if ($('signup_result_msg').offsetHeight > 0) { // переключаемся с signup сообщеия
    $('signup_result_msg').style.display = 'none';
    $('login_signup_container').style.display = 'block';
    if (signInDlg) signInDlg.okBtn.disabled = false;
  } else if (signInDlg && signInDlg.okBtn.disabled) return;  // пока отсылаем, переключаться нельзя
  if (what == 'login') {
    $('user_login_switch').className = 'selected';
    $('user_signup_switch').className = '';
    $('user_login_block').style.display = '';
    $('user_signup_block').style.display = 'none';
    if (!nofocus) {
      var loginEl = $('user_login');
      if (trim(loginEl.value) == '')
        loginEl.focus()
      else
        $('user_password').focus();
    }
  } else {
    $('user_login_switch').className = '';
    $('user_signup_switch').className = 'selected';
    $('user_login_block').style.display = 'none';
    $('user_signup_block').style.display = '';
    if (!nofocus) {
      var nameEl = $('user_signup_name');
      if (trim(nameEl.value) == '')
        nameEl.focus()
      else
        $('user_signup_email').focus();
    }
  }
}

function chkSignInAndSubmit(okBtn, form) {
  var wnd = getWindowByElement(okBtn);
  if (!wnd || !wnd.visible) return false;  // окно закрывается -> отмена
  form = (form ? $(form) : findSubChild(wnd, 'FORM'));  // находим первую форму в окне
  if (userLogin != '') { // юзер залогинен -> сабмитим форму
    form.onsubmit();
    return;
  }
  signInDlg = wnd;
  signInDlg.mainForm = form;
  signInDlg.okBtn = okBtn;
  if ($('user_login_switch').className == 'selected')
    signInDlg_submitLogin(okBtn)
  else
    signInDlg_submitSignup(okBtn);
}

function signInDlg_submitSignup(okBtn) {
  okBtn.focus();
  okBtn.disabled = true;
  var err = $('user_signup_name_error');
  if (err) err.style.display = 'none';
  var err = $('user_signup_email_error');
  if (err) err.style.display = 'none';
  signInDlg.userNameToReg = trim($('user_signup_name').value);
  var evnt = window.event || {};
  sendDlgData($('user_signup_form'), signInDlg.id, evnt, signInDlg_signupResult);
}

function signInDlg_signupResult(doc, text, id) {
  if (text == null || !signInDlg) return true;
  if (!signInDlg.visible) {
    signInDlg.mainForm = null;
    signInDlg.okBtn = null;
    signInDlg = null;
    return;
  }
  if (text.match(/ id="user_signup_status">Ok</i)) {
//  alert('Вы успешно зарегистрированы.\n\nПроверьте ваш почтовый ящик\nи введите высланный вам пароль.\n');
//  switchLoginSignup('login');
    signInDlg.okBtn.blur(); // сбиваем фокус с кнопки Ok
    $('user_login').value = signInDlg.userNameToReg;
    $('user_password').value = '';
    $('login_signup_container').style.display = 'none';
    $('signup_result_msg').style.display = 'block';
//  signInDlg.okBtn.disabled = false;
  } else {
    $('signup_container').innerHTML = text;
    if ($('user_signup_name_error')) $('user_signup_name').focus()
    else $('user_signup_email').focus();
    signInDlg.okBtn.disabled = false;
  }
  return true;
}

function signInDlg_submitLogin(okBtn) {
  var inp = $('login_redirect_path');
  if (inp) inp.value = 'http://'+location.host+'/auth.html';
  $('user_login_error').style.display = 'none';
  okBtn.focus();
  okBtn.disabled = true;
  loginResult = signInDlg_loginResult;
  $('user_login_form').submit();
  signInDlg.requestActive = true;
  requestStarted();
}

// вызывается из iframe
function signInDlg_loginResult(loggedIn, prm) {
  if (!signInDlg) return;
  if (signInDlg.requestActive) {
    signInDlg.requestActive = false;
    requestFinished();
  }
  if (!signInDlg.visible) {
    signInDlg.mainForm = null;
    signInDlg.okBtn = null;
    signInDlg = null;
    return;
  }
  if (loggedIn) {
    userLogin = prm;  // userName
    signInDlg.reloadOnClose = true;
    zoom('login_signup_block', '-');
    signInDlg.mainForm.onsubmit();
    signInDlg.mainForm = null;
    signInDlg.okBtn = null;
    signInDlg = null;
  } else {
//  var errorFld = $('login_error');
//  errorFld.innerHTML = 'Ошибка: '+error;
//  zoom(errorFld, '+');
//  setTimeout('loginDlg_hideError()', 5000);
    with ($('user_login_error')) {
      innerHTML = prm;  // errorMsg
      style.display = 'block';
    }
//  alert('Ошибка: '+errorMsg);
    with ($('user_password')) {
      value = '';
      focus();
    }
    signInDlg.okBtn.disabled = false;
  }
}


//-- Send password request ------------------------

var
  passwordRequestDlg = null,
  passwordRequestDlgLoading = false;

function requestPassword() {
  if (passwordRequestDlgLoading) return;
  loadDlg('/pwd_request.html', 'pwd_request_dlg', passwordRequestDlgLoaded);
  passwordRequestDlgLoading = true;
}

function passwordRequestDlgLoaded(doc, text, id) {
  passwordRequestDlgLoading = false;
  if (text == null) return;
  if (!passwordRequestDlg) {
    passwordRequestDlg = newWindow('password_request_dlg');
  }
  passwordRequestDlg.focusElementId = 'pwd_request_email';
  passwordRequestDlg.showModal('Напоминание пароля', text);
  return true;
}

function passwordRequestDlg_submit(form, evnt) {
  if (!passwordRequestDlg || !passwordRequestDlg.visible) {
    cancelEvent(evnt);
    return false;
  }
  var el = $('pwd_request_email_error');
  if (el) el.innerHTML = '';
  $('pwd_request_ok_btn').disabled = true;
  sendDlgData(form, passwordRequestDlg.id, evnt || {}, passwordRequestSent);
}

function passwordRequestSent(doc, text, id) {
  if (text == null || !passwordRequestDlg || !passwordRequestDlg.visible) return true;
  passwordRequestDlg.put(null, text);
  var el = $('pwd_request_email');
  if (el) el.focus()
  else if (el = $('pwd_request_close_btn')) el.focus();
  return true;
}


//-- Search dialog -------------------------------

var
  addSearchDlg = null,
  addSearchDlgLoading = false;

function addSearch() {
  if (addSearchDlgLoading) return;
  loadDlg('/add_search.html', 'add_search_dlg', addSearchDlgLoaded);
  addSearchDlgLoading = true;
}

function addSearchDlgLoaded(doc, text, id) {
  addSearchDlgLoading = false;
  if (text == null) return;
  if (!addSearchDlg) {
    addSearchDlg = newWindow('add_search_dlg', (userLogin ? 350 : 400), (userLogin ? 200 : 400));
    addSearchDlg.onClose = loginSignupDlg_onClose;
  }
  if (userLogin != '') addSearchDlg.focusElementId = 'add_search_title'
  else addSearchDlg.afterShow = loginSignupInit;
  addSearchDlg.showModal('Создание поиска', text);
  return true;
}

function addSearchDlg_submitForm(form, evnt) {
  if (!addSearchDlg || !addSearchDlg.visible) {
    cancelEvent(evnt);
    return false;
  }
  $('add_search_ok_btn').disabled = true;
  sendDlgData(form, addSearchDlg.id, evnt || {}, addSearchSubmited);
}

function addSearchSubmited(doc, text, id) {
  if (text == null || !addSearchDlg || !addSearchDlg.visible) return true;
  if (text.match(/ id="pubsearch_create_result">Ok</i)) {
    if (text.match(/<a href="(.*?)">/i)) {
      location.assign(RegExp.$1);
    } else {
      location.reload(false);
    }
  } else {
    addSearchDlg.put(null, text);
  }
  return true;
}


//-- Join author dialog ---------------------------

var
  joinAuthorDlg = null,
  joinAuthorDlgLoading = false;

function joinAuthor() {
  if (joinAuthorDlgLoading) return;
  loadDlg('/join_author.html', 'join_author_dlg', joinAuthorDlgLoaded);
  joinAuthorDlgLoading = true;
}

function joinAuthorDlgLoaded(doc, text, id) {
  joinAuthorDlgLoading = false;
  if (text == null) return;
  if (!joinAuthorDlg) {
    joinAuthorDlg = newWindow('join_author_dlg', 350, 200);
    joinAuthorDlg.onClose = loginSignupDlg_onClose;
  }
  if (userLogin != '') joinAuthorDlg.focusElementId = 'join_author_descr'
  else joinAuthorDlg.afterShow = loginSignupInit;
  joinAuthorDlg.showModal('Стать соавтором', text);
  return true;
}

function joinAuthorDlg_submitForm(form, event) {
  if (!joinAuthorDlg || !joinAuthorDlg.visible) {
    cancelEvent(evnt);
    return false;
  }
  var error = $('join_author_descr_error');
  if (error) error.innerHTML = '';
  $('join_author_ok_btn').disabled = true;
  sendDlgData(form, joinAuthorDlg.id, event || {}, joinAuthorRequestSent);
}

function joinAuthorRequestSent(doc, text, id) {
  if (text == null || !joinAuthorDlg || !joinAuthorDlg.visible) return true;
  if (text.match(/ id="join_author_result">Ok</i)) {
    joinAuthorDlg.close();
  } else {
    joinAuthorDlg.put(null, text);
    var el = $('join_author_descr');
    if (el) el.focus();
  }
  return true;
}

//-- Submit site dialog ---------------------------

var
  submitSiteDlg = null,
  submitSiteDlgLoading = false;

function submitSite() {
  if (submitSiteDlgLoading) return;
  loadDlg('/submit_site.html', 'submit_site_dlg', submitSiteDlgLoaded);
  submitSiteDlgLoading = true;
}

function submitSiteDlgLoaded(doc, text, id) {
  submitSiteDlgLoading = false;
  if (text == null) return;
  if (!submitSiteDlg) {
    submitSiteDlg = newWindow(id, 350, 200);
  }
  submitSiteDlg.focusElementId = 'submit_site_name';
  submitSiteDlg.showModal('Предложить сайт', text);
  return true;
}

function submitSiteDlg_submitForm(form, event) {
  if (!submitSiteDlg || !submitSiteDlg.visible) {
    cancelEvent(event);
    return false;
  }
  var e;
  if (e = $('submit_site_url_error')) e.innerHTML = '';
  if (e = $('submit_site_descr_error')) e.innerHTML = '';
  $('submit_site_ok_btn').disabled = true;
  sendDlgData(form, submitSiteDlg.id, event || {}, submitSiteRequestSent);
}

function submitSiteRequestSent(doc, text, id) {
  if (text == null || !submitSiteDlg || !submitSiteDlg.visible) return true;
  if (text.match(/ id="submit_site_result">Ok</i)) {
    submitSiteDlg.close();
  } else {
    submitSiteDlg.put(null, text);
    var el = $('submit_site_name');
    if (el) el.focus();
  }
  return true;
}

function addLeadingZero(a) {
  return (a <= 9 ? '0' : '') + a.toString();
}

function yearToYYStr(year) {
  return (year >= 2000 && year <= 2999 ? addLeadingZero(year-2000) : year.toString());
}

function UnixTimeToDateTimeStr(ut, dateOnly, showSec) {
  var d = new Date(ut*1000);
  return (
    addLeadingZero(d.getDate()) + '.' +
    addLeadingZero(d.getMonth()+1) + '.' +
    yearToYYStr(d.getFullYear()) + (dateOnly ? '' : (' ' +
    addLeadingZero(d.getHours()) + ':' +
    addLeadingZero(d.getMinutes()) + (!showSec ? '' : (':' + 
    addLeadingZero(d.getSeconds())))))
  );
}

function write_date(ut, dateOnly) {
  document.write(UnixTimeToDateTimeStr(ut, dateOnly));
}

function write_dt(ut) {
  write_date(ut, false);
}

function write_d(ut) {
  write_date(ut, true);
}

/*function dateTimeStrToUnixTime(txt) {
  var d = new Date(('20'+txt.substring(6, 8))*1,
    txt.substring(3, 5)-1, txt.substring(0, 2)*1,
    txt.substring(9, 11)*1, txt.substring(12, 14)*1);
  return Math.round(Date.parse(d)/1000);
}*/

function setBlockUnixTime(el, ut) {
  el = $(el);
  if (el) el.innerHTML = UnixTimeToDateTimeStr(ut);
}

function updateUnixTimeBlocks(container, tagName, className) {
  var elements = container.getElementsByTagName(tagName);
  for (var i = 0; i < elements.length; i++) {
    var el = elements[i];
    if (el.className == className) el.innerHTML = UnixTimeToDateTimeStr(el.innerHTML);
  }
}

function showHelpHint(name) {
  var x = 200, y = 100, w = 400, h = 300;
  if (name == 'autorize') { w = 400; h = 300 }/* http://www.'+flexumHost+' */
  window.open('/help_hint_'+name+'.html', 'help_hint_'+name, 'resizable=yes,scrollbars=yes,left='+x+',top='+y+',width='+w+',height='+h);
}

window.commonLoaded = true;
function LoginShowPasswd(){
var x;
if(document.getElementById('spass').checked){
  x=Math.round(Math.random()*100000+1);
  document.getElementById('passI').innerHTML='<div style="display:none"><input type="password" id="user_password" name="password" /></div><input type="text" id="user_password'+x+'" style="width: 100%" onchange="document.getElementById('+"'user_password'"+').value=this.value"/>';
  document.getElementById('user_password'+x).focus();
}else{
  x=document.getElementById('user_password').value;
  document.getElementById('passI').innerHTML='<input type="password" id="user_password" name="password" style="width: 100%" />';
  document.getElementById('user_password').value=x;
  x='';
  document.getElementById('user_password').focus();
}
}

function png(id, src_png, src_gif, sizingMethod){  
  var image = document.getElementById(id);
  if (isIE50) image.src = src_gif;
  else if (!isIE) image.src = src_png;
  else image.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src_png + '",sizingMethod="'+(sizingMethod || 'image')+'")';
  return 1;
}
