/*--------------------------------------*/
/* common.js                            */
/* (c) 2007 Lipka.ru                    */
/*--------------------------------------*/

//-- Common ------------------------------

if (!('$' in window)) {
  $ = function(el) {
    return (typeof(el) == 'string' ? document.getElementById(el) : el);
  }
}

function getStyle(el, styleProp) {
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

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) {
  tag = tag.toUpperCase();
  var list = element.getElementsByTagName(tag);
  if (className == undefined) return (list.length > 0 ? list[0] : null);
  var i, el;
  for (i = 0; i < list.length; i++) {
    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, tagName) {
  while (el) {
    el = el.parentNode;
    if (el.tagName == tagName) return el;
  }
  return null;
}

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.replace(/^\s+/, '').replace(/\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 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;
    }
  }
}

function mouseMoveEventHandler(event) {
  mouseAbsPosX = event.clientX + scLeft();
  mouseAbsPosY = event.clientY + scTop();
  var i, o;
  for (i = 0; i < mouseMoveListeners.length; i++) {
    o = mouseMoveListeners[i];
    if (o.method) o.method.call(o.instance || window, event);
  }
}

function scTop()
{
	if (document.documentElement) return document.documentElement.scrollTop;
	return document.body.scrollTop;
}

function scLeft()
{
	if (document.documentElement) return document.documentElement.scrollLeft;
	return document.body.scrollLeft;
}

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;
  }
}


function sqr(x) { return x*x }

function warn(s) {
//alert(s);
}


var
  userAgent = navigator.userAgent,
  isOpera = (userAgent.indexOf('Opera') >= 0),
  isIE = (!isOpera && userAgent.indexOf('MSIE') >= 0),
  isIE50 = (isIE && /MSIE 5\.0/.test(userAgent) && navigator.platform == 'Win32'),
  isMozilla = (!isOpera && userAgent.indexOf('Gecko') >= 0);


//-- Zoom -----------------------------------------

function callEventHandler(method, object) {
  if (!object) object = window;
  if (method.constructor == Function) 
    method.call(object);
  else if (method.constructor == Array)
    method[0].apply(object, method.slice(1));
  else
    alert('callEventHandler('+method+'): unknown method type: '+method.constructor);
}

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);
    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 == '') {
    if (el.zoomDirection) direction = el.zoomDirection;
    else direction = 'D';  // down
  }
  el.zoomDirection = direction;
  var offsetProp = (el.zoomDirection == 'D' ? 'offsetHeight' : 'offsetWidth');
  var styleProp = (el.zoomDirection == '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';
    } else {
      el.style.display = 'none';
    }
    el.style[styleProp] = '';
    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.style.overflow = 'hidden';
  if (action == '+') {
    if (!('zoomCurSize' in el) || el.zoomCurSize == 0) el.zoomCurSize = 1;
    el.style.display = 'block';
//  if (el == snippetBlock) log3('offsetHeight before: '+el.offsetHeight);
    el.style[styleProp] = '';
//  if (el == snippetBlock) log3('offsetHeight after: '+el.offsetHeight);
    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
//if (el == snippetBlock) log3('curSize: '+el.zoomCurSize+', offsetHeight: '+el.offsetHeight);
  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];
  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.style.overflow = '';
    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 ('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 = '';
    }
    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    = 1;  // 200 :BUG: При больших значениях под IE 6 перестаёт работать функциональность прочитать следующее сообщение. Возможно, создаётся "гонка" timer'ов fading'а и перекрываются процессы назначения прозрачности.

var DEF_FADE_STEPS   = 1; // 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];
  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
//  возвращает: 'filter' / 'opacity' / false
//  запоминает состояние в свойстве alphaMode
//
function hasAlpha(el) {
  if (!('alphaMode' in el))
    el.alphaMode = ('filter' in el.style ? 'filter' :
                     ('opacity' in el.style ? 'opacity' : false));
  return el.alphaMode;
}

function getAlpha(el) {
  return ('alphaValue' in el ? el.alphaValue : 1);
}

function setAlpha(el, value) {
    
  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 == 'filter') 
      el.style.filter = 'alpha(opacity='+Math.round(el.alphaValue*100)+')';
    else if (el.alphaMode == 'opacity')
      el.style.opacity = el.alphaValue;
      
  }
}


// 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.0, 16.01.2007

function Hint() {
  var elem = document.createElement('DIV');
  elem.id = 'hint';
  this.hintContainer = elem;
  this.inBody = false;
  this.visible = false;

  this.show = function(message) {
    var hintCont = this.hintContainer;
//  hintCont.style.display = 'block';
//  hintCont.style.visibility = 'hidden';
    hintCont.innerHTML='<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td><b></b><div>'+message+'</div><b></b></td></tr></table>';

    if (!this.mouseHandlerAdded) {
      addMouseMoveListener(Hint_updatePos, this);
      this.mouseHandlerAdded = true;
    }

//  hintCont.style.display='block';
    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;
    fade(hintCont, 'in');
    this.visible = true;
    var t = hintCont.getElementsByTagName('TABLE')[0];
    this.hintWidth = t.offsetWidth;
    this.hintHeight = t.offsetHeight;

    this.updatePos();
  }

  this.hide = function(how) {
//  obj.hintContainer.innerHTML='';
    this.visible = false;
    if (how == 'fast') {
      setVisible(this.hintContainer, false);
      if (this.mouseHandlerAdded) {
        removeMouseMoveListener(Hint_updatePos, this);
        this.mouseHandlerAdded = false;
      }
    } else {
      if (this.mouseHandlerAdded) {
        this.hintContainer.afterFade = function() {
          this.afterFade = null;
          removeMouseMoveListener(Hint_updatePos, this);
          this.mouseHandlerAdded = false;
        }
      }
      fade(this.hintContainer, 'out');
    }
//  obj.hintContainer.style.display='none';
  }
  this.updatePos = Hint_updatePos;
  if (mouseMoveListeners.length == 0) addMouseMoveListener(null);  // add null handler to know mouse pos
};

function Hint_updatePos() {
  var body = document.body;
  var d = (body.clientWidth + scLeft()) - this.hintWidth;
  var x = Math.min(mouseAbsPosX, d);
  var y = mouseAbsPosY + 20;
  var h = this.hintHeight;
  var ch = body.clientHeight + scTop();
  if (y + h >= ch) y = Math.min(mouseAbsPosY, ch) - h;
  var s = this.hintContainer.style;
  s.left = x + "px";
  s.top  = y + "px";
}

var hintobject = null;

function hint()
{
	if (hintobject==null)
		hintobject = new Hint();
	return hintobject;
}

//-- Window ------------------------------------
// v. 2.2, 05.02.2007

var 
  WindowClassName   = 'window',
  WindowBGClassName = 'modal_window_background',
  WindowDefWidth    = 300,
  WindowDefHeight   = 200,
  WindowCloseBtnImg = '/i/window_close.gif',
  WindowDefZIndex   = 1,
  WindowDefModalZIndex = 1000,
  WindowDefModalGBColor = '#FFFFFF',
  WindowDefModalGBOpacity = 0.6,
  WindowDragOpacity = 0.85,
  WindowUseIFrame   = true;

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) + "px";
    wnd.wndHeight = (h || WindowDefHeight) + "px";
    
    if (WindowUseIFrame) {
        wnd.iframe = document.createElement('IFRAME');
        //wnd.iframe.id = id+'_iframe';
        wnd.iframe.style.position = 'absolute';
        //wnd.iframe.width = wnd.wndWidth;
        //wnd.iframe.height = wnd.wndHeight;
        wnd.iframe.frameBorder = '0';
        wnd.iframe.style.filter = 'alpha(opacity=0)';
        if (location.protocol == 'https:') wnd.iframe.src = '/empty.htm';
    }
    
    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.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) this.winTitle.innerHTML = title;
  if (content) this.winContent.innerHTML = content;
//this.updatePos();
}

var
  WindowCurModalWindow = null,
  WindowSaveOnResize = null,
  WindowsZList = [];

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 = 0;
            this.bg.style.left = 0;
            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 ('filter' in this.style) {
                        if (c) this.bg.style.backgroundColor = c;
                        this.bg.style.filter = 'alpha(opacity = '+Math.round(o*100)+')';
                    } else if ('opacity' in this.style) {
                        if (c) this.bg.style.backgroundColor = c;
                        this.bg.style.opacity = o;
                    }
                }
            }
            //this.bg.style.cursor = 'wait';
        }
        document.body.appendChild(this.bg);
        if (WindowCurModalWindow == null) {
            WindowSaveOnResize = document.body.getAttribute('onresize');
            document.body.setAttribute('onresize',
                (typeof(WindowSaveOnResize) == 'string' || isMozilla ? 'Window_bgResize(event)' : Window_bgResize));
            this.resizeHooked = true;
            WindowCurModalWindow = 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 (window.fadeIn) {
        this.afterFade = null;
        fadeIn(this, null, null, 'visible');
    } else 
        this.style.visibility = 'visible';
    
    //this.visible = true;
    //this.isModal = isModal;

    WinBusy = '';
}

function Window_showModal(title, content) {
    this.show(title, content, true);
}

function closeWindow(el) {
    while (el && el.tagName != 'BODY') {
        if (el.close) {
            el.close();
            return true;
        }
        el = el.parentNode;
    }
    return false;
}

function getParentWindow(element) {
    var p = element.parentNode;
    while (p && !(p.tagName == 'DIV' && p.className == WindowClassName)) p = p.parentNode;
    return (p.tagName == 'DIV' && p.className == WindowClassName) ? p : null;
}

function Window_close() { 
    if (WinBusy) {
        alert('on close: busy = '+WinBusy);
        return;
    }
    
    if (!this.visible) return;
    WinBusy = 'close';
    this.visible = false;
    Window_removeMouseUpListener();

    if (!window.fadeOut) {
        this.style.display = 'none';
        if (this.parentNode) this.parentNode.removeChild(this);
    } else {
        this.afterFade = function() {
            this.afterFade = null;
            if (this.parentNode) this.parentNode.removeChild(this);
        }
        fadeOut(this);
    }

    if (this.iframe) this.iframe.parentNode.removeChild(this.iframe);
    
    if (this.isModal) {
        this.bg.parentNode.removeChild(this.bg);
        if (this.resizeHooked) {
            WindowCurModalWindow = null;
            this.resizeHooked = false;
            document.body.setAttribute('onresize', WindowSaveOnResize);
            if (WindowSaveOnResize == null)
                document.body.removeAttribute('onresize')
            else
                WindowSaveOnResize = null;
        }
    }
    WindowsZList.removeItem(this);
    if (this.onClose) this.onClose();
    WinBusy = '';
}

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 wWidth = 0, wHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        wWidth = window.innerWidth;
        wHeight = window.innerHeight;
    } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        wWidth = document.documentElement.clientWidth;
        wHeight = document.documentElement.clientHeight;
    }

    var x = Math.max(Math.round((wWidth-this.offsetWidth)/2), 0) + scLeft();
    var y = Math.max(Math.round((wHeight-this.offsetHeight)/2), 0) + scTop();

    this.style.left = x + "px";
    this.style.top = y + "px";
    
    if (this.iframe) {
        this.iframe.style.left = x + "px";
        this.iframe.style.top = y + "px";
    }
}

function Window_bgResize(event) {
    if (WindowCurModalWindow) {
        WindowCurModalWindow.style.left = Math.round((document.body.offsetWidth-WindowCurModalWindow.offsetWidth)/2) + "px";
        WindowCurModalWindow.bg.style.height = Math.max(document.body.scrollHeight, document.body.clientHeight) + "px";
    }
    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);
    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.startDragX = pos.left;
    el.startDragY = pos.top;
    el.startMouseX = event.clientX + scLeft();
    el.startMouseY = event.clientY + scTop();
    addMouseMoveListener(Window_mouseMoveListener, el);
    Window_addMouseUpListener();
}

function Window_mouseMoveListener(event) {
    var el = curDragWindow;
    var x = el.startDragX - (el.startMouseX - mouseAbsPosX);
    var y = el.startDragY - (el.startMouseY - mouseAbsPosY);
    el.style.left = x + "px";
    el.style.top  = y + "px";
    if (el.iframe) {
        el.iframe.style.left = x + "px";
        el.iframe.style.top  = y + "px";
    }
}

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;
}



//---------------------------------------------------
// Форма (де-)авторизации
//---------------------------------------------------

function loginResult(flag, err, redirectUrl){

 switch (parseInt(flag)){
  case -1: { 
	if (!err || err=='') err='Неверный&nbsp;логин&nbsp;или&nbsp;пароль';
   $('errorLogin').innerHTML = err;
   var pass = $('pass');
   pass.value = ''; 
   pass.focus();   
   break;
   }
  case 1:
    if (redirectUrl && redirectUrl != '')
    {
		self.location.replace(redirectUrl);	
		break;
	}
  default: {$('login_frame').src = '/empty.htm';
           location.reload()}
 }
}

/*
function formLoginCode() {
 return '\
  <p id="errorLogin" class="error" style="color: red; padding: 1em 0"></p>\
  <form class="m00" action="/Login.aspx" onsubmit="submitLogin(this, event)">\
   <table class="mb08" cellpadding="0" cellspacing="0">\
    <tr>\
     <td class="pr05"><label for="name">Логин</label></td>\
     <td><input name="name" id="name" type="text" class="mb08" /></td>\
    </tr>\
    <tr>\
     <td class="pr05"><label for="pass">Пароль</label></td>\
     <td><input name="pass" id="pass" type="password" /></td>\
    </tr>\
    <tr>\
     <td></td>\
     <td>\
      <input name="autologin" id="autologin" type="checkbox" /><label for="autologin">Запомнить меня</label>\
      <p><input type="submit" value="Войти" /></p>\
     </td>\
    </tr>\
   </table>\
  </form>' 
}
*/
//----------------------------------------------------
// Публикация PNG
//----------------------------------------------------

function png(id, src_png, src_gif){  
	image = document.getElementById(id);
	if (image) image.src = src_gif;
	/*
	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='image')"
		}
	}
	*/
	return 1;
}




//----------------------------------------------------
// Zooming
//----------------------------------------------------

function toggleSign(){
 if (this._sign.tagName == 'IMG') 
  this._sign.src='/i/'+(this.zoomAction == '+' ? 'minus' : 'plus')+'_small.gif'
 else 
  this._sign.innerHTML='['+(this.zoomAction == '+' ? '&#8211;' : '+')+']'
}

function initZoom(zoomEl, toogleEl){
 if (!zoomEl) return; // balabanov
 
 if(toogleEl) {
  zoomEl._sign = toogleEl; 
  zoomEl.afterZoom = toggleSign; 
 }
 zoom(zoomEl);
 return false
}

function go2Login(page)
{
	var temp;
	var wnd = self;
	
	while (wnd.parent && wnd.parent!=wnd && wnd.parent.location!=wnd.location)
		wnd = wnd.parent;
	
	while (wnd.opener && wnd.opener!=wnd)
	{
		temp = wnd;
		wnd = wnd.opener;
		temp.close();
	}
	
	redirectLogin(wnd, page);
}

function redirectLogin(wnd, page)
{
	if (!page) page = "/login/";
	wnd.location.href=page;
}

//**************
// Функции сообщений
//**************
function mes(title, message)
{
  showWindow('mes', title, message, 300, 170);
}


//********************************************************************************
//
// Effects functions
//
//********************************************************************************

// Change the opacity for different browsers
function setOpacity (element, value) {
	element = $(element);
	if ( !element ) return false;
	var currentStyle = element.currentStyle;
	if (( currentStyle && !currentStyle.hasLayout ) ||
		(!currentStyle && element.style.zoom == 'normal'))
		element.style.zoom = 1;
	var filter = element.style.filter, style = element.style;
	
	if ( value == 1 || value === '' ) {
		if (currentStyle && filter) style.removeAttribute('filter');
		return element;
	} else if (value < 0.00001) value = 0;
	
	element.style.opacity = (value);
	element.style.MozOpacity = (value);
	element.style.KhtmlOpacity = (value);
	element.style.filter = "alpha(opacity=" + value * 100 + ")";	
	return element;
}

function setOpacityAll(elements, opacity)
{
	var ids = elements.split(",");
	for (var i=0; i<ids.length; i++)
	{
		var elementid = ids[i];
		if (!elementid || elementid=="") continue;
		setOpacity(elementid, opacity);
	}
	
}

function Fade (elements, millisec, func, iterations, curopacity) {

	if ( !millisec ) millisec = 1000;
	if (!iterations) iterations=10;
	if (!curopacity) curopacity=1;
	var speed = Math.round( millisec / iterations );
	var opacity = curopacity - (1/iterations);
	if (opacity<0) opacity=0;
	opacity = opacity.toFixed(2);
	
	setOpacityAll(elements, opacity);

	if (opacity<=0)
	{
		if (func) func();
		return;
	}
	
	setTimeout("Fade('" + elements + "', " + millisec + ", " + func + ", " + iterations + ", " + opacity + ")",speed);
}

function Appear (elements, millisec, func, iterations, curopacity)
{
	if (!millisec) millisec = 1000;
	if (!iterations) iterations=10;
	if (!curopacity) curopacity=0;
	var speed = Math.round( millisec / iterations );
	var opacity = curopacity + (1/iterations);
	if (opacity>1) opacity=1;
	opacity = opacity.toFixed(2);
	
	setOpacityAll(elements, opacity);
	
	if (opacity>=1)
	{
		if (func) func();
		return;
	}
	
	setTimeout("Appear('" + elements + "', " + millisec + ", " + func + ", " + iterations + ", " + opacity + ")",speed);
}

function openIM(id)
{
	var w = 533;
	var h = 520;
	var l = screen.width ? parseInt(screen.width/2 - (w/2)) : 200;
	var t = screen.height ? parseInt(screen.height/2 - (h/2)) : 200;
	var w=window.open('/IM/?userid='+ id,'IM' + USER_ID + "_" + id,"width="+w+",height="+h+",left="+l+",top="+t+",resizable=yes,toolbar=0,location=0,status=no,menubar=0,directories=0,scrollbars=yes");
	if (!w) { 
	  alert('В броузере включена блокировка всплывающих окон.');
	  return
	}
	if (w.focus) w.focus()
}

function openRecommendation(file) 
{
    var w = 760;
    var h = 520;
    var l = screen.width ? parseInt(screen.width / 2 - (w / 2)) : 200;
    var t = screen.height ? parseInt(screen.height / 2 - (h / 2)) : 200;
    var w = window.open(file, "Recommendation", "width=" + w + ",height=" + h + ",left=" + l + ",top=" + t + ",resizable=yes,toolbar=0,location=0,status=no,menubar=0,directories=0,scrollbars=yes");
    if (!w) {
        alert('В броузере включена блокировка всплывающих окон.');
        return
    }
    if (w.focus) w.focus()
}

function openPopup(url)
{
    var w=window.open(url, '_blank',"resizable=yes,toolbar=yes,location=yes,status=yes,menubar=yes,directories=yes,personalbar=yes,scrollbars=yes");
	if (!w) { 
	  alert('В броузере включена блокировка всплывающих окон.');
	  return
	}
	if (w.focus) w.focus();
}