//-- 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;
}





//-- 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', 300, 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;
}


