/*--------------------------------------*/
/* common.js                            */
/* (c) 2007 zapominalka.ru              */
/*--------------------------------------*/

//-- Common ------------------------------

if (!('$' in window)) {
  $ = function(el) {
    return (typeof(el) == 'string' ? document.getElementById(el) : el);
  }
}

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 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 + 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;
  }
}


function sqr(x) { return x*x }

function warn(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';
    el.style[styleProp] = '';
    el.zoomNewSize = el[offsetProp];
  } else {
    if (!('zoomCurSize' in el)) el.zoomCurSize = el[offsetProp]/el.zoomAlpha;
    el.zoomNewSize = 0;
  }
  el.zoomDelta = delta;
  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];
  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    = 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];
  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.innerHTML='<table wi_dth="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;
    }

    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) {
    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');
    }
  }
  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 + 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;
  var s = this.hintContainer.style;
  s.left = x;
  s.top  = y;
}

var hint = new Hint();


//-- 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;
  wnd.wndHeight = h || WindowDefHeight;
  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 = '/frameblank.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.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);
      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;
          }
        }
      }
    }
    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.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;
    this.iframe.style.height = this.offsetHeight;
  }
  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';
  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 x = Math.max(Math.round((document.body.clientWidth-this.offsetWidth)/2), 0) + document.body.scrollLeft;
  var y = Math.max(Math.round((document.body.clientHeight-this.offsetHeight)/2), 0) + document.body.scrollTop;
  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) {
  if (WindowCurModalWindow) {
    WindowCurModalWindow.style.left = Math.round((document.body.offsetWidth-WindowCurModalWindow.offsetWidth)/2);
    WindowCurModalWindow.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);
  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 + document.body.scrollLeft;
  el.startMouseY = event.clientY + document.body.scrollTop;
  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;
  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;
}



//---------------------------------------------------
// Форма (де-)авторизации
//---------------------------------------------------

function submitLogin(formLogin, event){
 if(!window.loader_login) {
    loader_login = new RemoteFileLoader('loader_login'); 
    loader_login.onload = analyseLoginResult;
 }
 loader_login.submitInto(formLogin, 'login_result', event);
}

function analyseLoginResult(){
 switch (trim($('login_result').innerHTML)){
  case '-1': 
   $('errorLogin').innerHTML = 'Неверный&nbsp;логин&nbsp;или&nbsp;пароль';
   var pass = $('pass');
   pass.value = ''; 
   pass.focus();
   break;

  default:
   self.parent.location.reload(); 
 }
}


function loginResult(flag){
 switch (parseInt(flag)){
  case -1: { 
   $('errorLogin').innerHTML = 'Неверный&nbsp;логин&nbsp;или&nbsp;пароль';
   var pass = $('pass');
   pass.value = ''; 
   pass.focus();
   break;
   }
  default: {$('login_frame').src = 'about:blank';
           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){  
var ie5=false;
var ie=true;
	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='image')"
		}
	}
	return 1;
}




//----------------------------------------------------
// Zooming
//----------------------------------------------------

function toggleSign(){this._sign.innerHTML='['+(this.zoomAction == '+' ? '&#8211;' : '+')+']'}

function initZoom(toogleEl, zoomEl){
 if (!zoomEl) return; 
 zoomEl._sign = toogleEl; 
 zoomEl.afterZoom = toggleSign; 
 zoom(zoomEl);
 return false
}



/*paging*/
function getNewPage(current, cmd)
{
    var iframe = $('ifGet');
    var url = $("ctl00_cphBody_txtUrlContains");
    var host = $("ctl00_cphBody_txtHostContains");
    var text = $("ctl00_cphBody_txtPageContains");
    var wdcFrom = igdrp_getComboById("ctl00_cphBody_wdcFrom");
    var wdcTo = igdrp_getComboById("ctl00_cphBody_wdcTo");
    
    var from = getSqlDate(wdcFrom.getValue());
    var to = getSqlDate(wdcTo.getValue());
    
    iframe.src = "/get.ashx?current=" + current + "&dtFrom=" + from + "&dtTo=" + to + "&cmd=" + cmd + "&urlt=" + url.value + "&host=" + host.value + "&text=" + text.value;
}

function getSqlDate(d)
{
    var strYear     = d.getFullYear() + "";
    var iMonth      = d.getMonth() + 1; // +1, we do NOT want zero-based month index
    var iDay        = d.getDate();
    var strDateOut  = "";

    iMonth = (iMonth < 10)? "0" + iMonth : iMonth + "";
    iDay = (iDay < 10)? "0" + iDay : iDay + "";

    strDateOut = strYear + "-" + iMonth + "-" + iDay;
    
return strDateOut;
}


/*getting search results*/
 function searchUrls()
 {
 try
 {
     var rbDate = $("ctl00_cphBody_rbSortByDate");
        
        /*we have urls*/
        if(rbDate.checked == true)
        {
            getNewPage(1, 'url');
            host.innerHTML = "";
        }
        else
        {
            getNewPage(1, 'host');
            url.innerHTML = "";   
        }
  }
  catch(ex)
  {
  
  }
}

function loadBranch(host, current)
{
     var wdcFrom = igdrp_getComboById("ctl00_cphBody_wdcFrom");
     var wdcTo = igdrp_getComboById("ctl00_cphBody_wdcTo");

    /*setting dates values*/
    var from = getSqlDate(wdcFrom.getValue());
    var to  = getSqlDate(wdcTo.getValue());
        
        
    var iframe = $('ifGet');
    var url = $("ctl00_cphBody_txtUrlContains");
    var text = $("ctl00_cphBody_txtPageContains");
    var divhost = $(host);
    var img_tree = $("img_" + host);
    
    if(divhost.loaded == "true")
    {
        if(divhost.style.display == "block")
        {
            divhost.style.display = "none";
            img_tree.src = "/images/img_plus.gif";
        }
        else
        {
            divhost.style.display = "block";
            img_tree.src = "/images/img_minus.gif";
        }
        
    }
    else
    {
        img_tree.src = "/images/img_minus.gif";
        iframe.src = "/get.ashx?current=" + current + "&dtFrom=" + from + "&dtTo=" + to + "&cmd=" + host + "&urlt=" + url.value + "&host=" + host + "&text=" + text.value;
    }
}
