_WGT = true;

//  цвета
_CL_ACTIVE_BORDER = 'gray';
_CL_INACTIVE_BORDER = 'gray';
_CL_BUTTON = 'rgb(220,220,220)';
_CL_PANEL = 'silver';
_CL_STATUS = 'silver';
_CL_WINDOW = 'white';
_CL_SELECTED = 'rgb(220,220,250)';

// стили
_S_HEADER = 'color:white;font-weight: bold;';
_S_STATUS = 'color:white;';
_S_CONTROL = 'color:black;';

//окна
_WND_INDEX = 0;
_WND_A = null;

_DEBUG_WND = null;


function dbg(s) {
  if (_DEBUG_WND == null) {
    _DEBUG_WND = new WGT_Window(0,100,100,200,200,'Отладчик',true);
    var body =  new WGT_Container(_DEBUG_WND);
  }

  _DEBUG_WND.SetBody(s);
  _DEBUG_WND.SetFocus();
}



function win_list() {
  var w = new WGT_Window(0,100,100,200,200,'Список окон',true);
  var body =  new WGT_Container(w);

  var s='',i;
  for (i in _WND_A) {
    if (_WND_A[i] != null)
      s=s+i+' <a onclick="win_set_visible(\''+i+'\')">'+_WND_A[i].GetWindowName()+'</a><br>';
  }

  w.SetBody(s);
  w.SetFocus();
}

function win_set_visible(_id){
  if (_WND_A[_id] != null)
    if (_WND_A[_id].SetVisible != null)
      _WND_A[_id].SetVisible(true);
}


//события
function _evt(e){
  return (e) ? e : window.event;
}

var _MOUSE_MOVE_A = null;

function _add_onmousemove(o) {
  if (_MOUSE_MOVE_A == null)
    _MOUSE_MOVE_A = new Array();
  var l=_MOUSE_MOVE_A.length;
  _MOUSE_MOVE_A[l]=o;
}

function _del_onmousemove(o) {
  if (_MOUSE_MOVE_A == null) return 0;
  for(i=0;i<_MOUSE_MOVE_A.length;i++) {
    if (_MOUSE_MOVE_A[i] == o) {
      _MOUSE_MOVE_A[i]=null;
      return 0;
    }
  }
}

function _document_onmousemove(e) {
  var evt = _evt(e);

  if (_MOUSE_MOVE_A)
    for(i=0;i<_MOUSE_MOVE_A.length;i++){
      if (_MOUSE_MOVE_A[i]) {
        if (_MOUSE_MOVE_A[i]._onmousemove) {
          _MOUSE_MOVE_A[i]._onmousemove(evt);
        }
      }
    }
}


function _document_onkeyup (e) {
  var evt = _evt(e);
  if (evt.altKey &&
      (evt.keyCode == 87 || evt.keyCode == 76)) {
    win_list();
  }
}

document.onmousemove=_document_onmousemove;
document.onkeyup=_document_onkeyup;


function wgt_make_table(a) {
  var i,j;
  if (a == null) return '';
  var res='<table border=1>';
  for(i=0;i<a.length;i++){
    res+='<tr>';
    for(j=0;j<a[i].length;j++){
     res+='<td>'+a[i][j]+'</td>';
    }
    res+='</tr>';
  }
  res+='</table>';

  return res;
}

function wgt_make_table1(a) {
  var i,j,s1='',s2='',res='';
  if (a == null) return '';
  s1=a.split('<');
  res='<table border=1>';
  for(i=0;i<s1.length;i++){
    res+='<tr>';
    s2=s1[i].split('>');
    for(j=0;j<s2.length;j++){
     res+='<td>'+s2[j]+'</td>';
    }
    res+='</tr>';
  }
  res+='</table>';

  return res;
}



//-------------------------------------------------------------------------
//            конструктор элемента управления
//-------------------------------------------------------------------------

function WGT_Control(obj,  //объект на котором размещаем элемент
                     tp,   //тип элемента - 'button','separator','input'
                     nm,   //имя элемента
                     img,  //картинка
                     _w,   //длина элемента
                     _a    //выравнивание
                    ) {
  var i=0;
  var offs=3;

  if(obj == null) return null;
  if(obj.controls == null) obj.controls=new Array();
  else {
    i=obj.controls.length;
    for(j=0;j<obj.controls.length;j++)
      offs=offs+3+obj.controls[j].obj.offsetWidth;
  }
  if(obj.controls_a == null) obj.controls_a=_a; //controls_a - выравнивание

  var ctrl = null;
  var label = null;

  if (tp == 'button' || tp == 'separator') ctrl = document.createElement("DIV");
  if (tp == 'input') ctrl = document.createElement("INPUT");

  if (ctrl == null) return null;

  obj.controls[i] = this;
  obj.controls[i].obj=ctrl;
  ctrl.id=obj.id+'_ctrl'+i;
  ctrl.style.position='absolute';
  ctrl.style.top='3px';
  ctrl.style.width=_w;
  ctrl.style.height=(obj.offsetHeight-6)+'px';
  if (tp == 'button' || tp == 'separator') {
    if (img != '')
      ctrl.innerHTML='<table height="100%"><tr><td><img src="'+img+'"></td></tr></table>';  //'<img src="'+img+'">';
    else
      ctrl.innerHTML='<table height="100%"><tr><td><font style="'+_S_CONTROL+'">'+nm+'</font></td></tr></table>';
  }
  if (tp == 'button') {
    ctrl.style.backgroundColor=_CL_BUTTON;
    ctrl.style.borderStyle='solid';
    ctrl.style.borderWidth='1px';
    ctrl.style.borderColor=_CL_ACTIVE_BORDER;
  }
  ctrl.style.overflow='hidden';
  obj.appendChild(ctrl);

  if (obj.controls_a == 'left') ctrl.style.left=offs+'px';
  if (obj.controls_a == 'right') ctrl.style.right=offs+'px';

  this.Set_onmouseup = function(fn) {
    ctrl.onmouseup = fn;
  }
  this.GetValue = function(){
    return ctrl.value;
  }

  this.Close = function() {
  }

  this.SetWidth = function(_w) {
    ctrl.style.width=_w;
  }

  this.GetWidth = function(_w) {
    return ctrl.offsetWidth;
  }

  this.SetVisible = function(_m){
    if (_m) ctrl.style.visibility='inherit';
    else ctrl.style.visibility='hidden';
  }
}


//-------------------------------------------------------------------------
//            конструктор панели
//-------------------------------------------------------------------------

function WGT_Panel(_w,  //окно в котором размещаем панель
                  _h) {
  var i = 0;
  if(_w == null) return null;
  var obj=_w.GetWnd();
  if(obj == null) return null;
  if(obj.panels == null) obj.panels=new Array();
  else {
    i = obj.panels.length;
  }

  var panel = document.createElement("DIV");
  obj.panels[i]=this;
  obj.panels[i].obj=panel;
  panel.id=obj.id+'_panel'+i;
  panel.style.position='relative';
  panel.style.width='100%';
  panel.style.height=_h;
  panel.style.backgroundColor=_CL_PANEL;
  panel.style.overflow='hidden';

  this.GetHeight = function() {
    return panel.offsetHeight;
  }

  this.Close = function() {
    obj.removeChild(panel);
  }

  obj.appendChild(panel);

  if (_w.ResizeControls != null) _w.ResizeControls();
}

//-------------------------------------------------------------------------
//            конструктор контейнера
//-------------------------------------------------------------------------

function WGT_Container(_w  //окно в котором размещаем контейнер
                      ) {
  if(_w == null) return null;
  var obj=_w.GetWnd();
  if(obj == null) return null;

  this.id='qqqq';
  var container = document.createElement("DIV");
  obj.container=this;
  obj.container.obj=container;

  container.id=obj.id+'_container';
  container.style.position='relative';
  container.style.width='100%';
  container.style.height='10px';
  container.style.backgroundColor=_CL_WINDOW;
  container.style.overflow='auto';

  this.SetHeight = function(_h1) {
    container.style.height=_h1;
  }

  this.SetBody = function(_s) {
    container.innerHTML=_s;
  }

  this.GetBody = function() {
    return container.innerHTML;
  }

  this.SetScroll = function (_n){
    container.scrollTop=_n;
  }

  this.Close = function() {
    obj.removeChild(container);
  }

  obj.appendChild(container);

  if (_w.ResizeControls != null) _w.ResizeControls();
}


//-------------------------------------------------------------------------
//            конструктор статусной строки
//-------------------------------------------------------------------------

function WGT_Status(_w,  //окно в котором размещаем строку
                    _h  ) {
  if(_w == null) return null;
  var obj=_w.GetWnd();
  if(obj == null) return null;

  this.id='qqqq';
  var status = document.createElement("DIV");
  obj.status=this;
  obj.status.obj=status;

  status.id=obj.id+'_status';
  status.style.position='relative';
  status.style.width='100%';
  //status.style.height='25px';
  status.style.height=_h;
  status.style.backgroundColor=_CL_STATUS;
  status.style.borderTopStyle='solid';
  status.style.borderWidth='2px';
  status.style.borderColor=_CL_ACTIVE_BORDER;
  status.style.overflow='hidden';


  this.SetHeight = function(_h) {
    status.style.height=_h;
  }

  this.GetHeight = function() {
    return status.offsetHeight;
  }

  this.SetText = function(_s) {
    status.innerHTML=_s;
  }

  this.Close = function() {
    obj.removeChild(status);
  }

  obj.appendChild(status);

  if (_w.ResizeControls != null) _w.ResizeControls();
}

//-------------------------------------------------------------------------
//            конструктор окна
//-------------------------------------------------------------------------


function WGT_Window(_p,_l,_t,_w,_h,_nm,_visible){

  if (!_p || !_p.appendChild) _p=document.body;
  this.id='window'+(++_WND_INDEX);

  var _this = this;

  this.ww='w'+this.id;

//-------------------------------------------------------------------
//                         окно
//----_--------------------------------------------------------------
  var wnd = document.createElement("DIV");
  //свойства DIV
  wnd.id=this.id+'_wnd';
  wnd.style.position='absolute';
  wnd.style.left=_l+'px';
  wnd.style.top=_t+'px';
  wnd.style.width=_w+'px';
  wnd.style.height=_h+'px';
  wnd.style.borderStyle='solid';
  wnd.style.borderWidth='2px';
  wnd.style.borderColor=_CL_ACTIVE_BORDER;
  wnd.style.backgroundColor='white';
  wnd.style.overflow='hidden';
  wnd.style.zIndex=0;
  wnd.onmousedown = function (e) {
    var evt = _evt(e);
    //_set_active_wnd(wnd);

    //dbg('');


    var scl=document.documentElement.scrollLeft > 0 ? document.documentElement.scrollLeft : document.body.scrollLeft;
    var sct=document.documentElement.scrollTop > 0 ? document.documentElement.scrollTop : document.body.scrollTop;

    _this.SetFocus();
    if ((evt.clientX+scl-wnd.offsetLeft) > (wnd.offsetWidth-20) &&
        (evt.clientY+sct-wnd.offsetTop) > (wnd.offsetHeight-20)) {
      wnd.doResize=true;
      wnd.style.cursor='nw-resize';
    }
  };
  wnd.onmouseup = function (e) {
    var evt = _evt(e);
    wnd.doResize=false;
    wnd.style.cursor='default';
  };

  //свойства wnd
  wnd.p=_p;
  wnd.nm='';
  wnd.x1=0;
  wnd.y1=0;
  wnd.doResize=false;
  wnd._onmousemove = function (e) {
      if (wnd.doResize) {
        var scl=document.documentElement.scrollLeft > 0 ? document.documentElement.scrollLeft : document.body.scrollLeft;
        var sct=document.documentElement.scrollTop > 0 ? document.documentElement.scrollTop : document.body.scrollTop;

        var dx=e.clientX+scl-wnd.offsetLeft+2;
        var dy=e.clientY+sct-wnd.offsetTop+2;

        if (dx > 50 && dy > 50) {
          wnd.style.width=dx+'px';
          wnd.style.height=dy+'px';
          wnd.SetBodyHeight();
          _this.OnResize();
        }
      }
    };
  _add_onmousemove(wnd);

//-------------------------------------------------------------------
//                         заголовок окна
//-------------------------------------------------------------------
  //свойства DIV
  var head1 = document.createElement("DIV");
  head1.id=this.id+'_head1';
  head1.style.position='relative';
  head1.style.left='0px';
  head1.style.top='0px';
  head1.style.width='100%';
  head1.style.height='22px';
  head1.onmousemove = function () {
    head1.style.cursor='default';
  };
  //свойства wnd
  head1.buttons=null;
  head1.button_a='right';

//-------------------------------------------------------------------
//                         заголовок окна
//-------------------------------------------------------------------

  var head = document.createElement("DIV");
  //свойства DIV
  head.id=this.id+'_head';
  head.style.position='absolute';
  head.style.left='0px';
  head.style.top='0px';
  head.style.width='100%';
  head.style.height='22px';
  head.style.backgroundColor=_CL_ACTIVE_BORDER;
  head.style.borderBottomStyle='solid';
  head.style.borderWidth='2px';
  head.style.borderColor=_CL_ACTIVE_BORDER;
  head.style.overflow='hidden';
  head.onmousedown = function (e) {
    var evt = _evt(e);
    head.x1 = evt.clientX;
    head.y1 = evt.clientY;
    head.pos_x = wnd.offsetLeft;
    head.pos_y = wnd.offsetTop;
    head.doMove=true;
  };
  head.onmouseup = function (e) {
    var evt = _evt(e);
    head.doMove=false;
    head.x1 = 0;
    head.y1 = 0;
    head.pos_x = 0;
    head.pos_y = 0;
  };
  //свойства head
  head.pos_x=0;
  head.pos_y=0;
  head.x1=0;
  head.y1=0;
  head.doMove=false;
  head._onmousemove = function (e) {
    if (head.doMove) {
      //var dx=e.clientX+document.body.scrollLeft-head.x1;
      //var dy=e.clientY+document.body.scrollTop-head.y1;
      var dx=e.clientX-head.x1;
      var dy=e.clientY-head.y1;
      if (head.pos_x+dx < 0) dx=-head.pos_x;
      wnd.style.left=(head.pos_x+dx)+'px';
      if (head.pos_y+dy < 0) dy=-head.pos_y;
      wnd.style.top=(head.pos_y+dy)+'px';
    }
  };
  _add_onmousemove(head);


//-------------------------------------------------------------------
//                 внутренние функции
//-------------------------------------------------------------------

  wnd._SetVisible = function (e,v) {
    if (e.visible)
      if (e.visible != v)
        if (v) {
          wnd.appendChild(e);
          e.visible=false;
        }
        else {
          wnd.removeChild(e);
          e.visible=false;
        };

  }

  wnd.SetBodyHeight = function () {
    if (wnd.container == null) return 0;
    var i=0;
    var h=wnd.offsetHeight;
    h-=head1.offsetHeight;
    if (wnd.panels != null) {
      for(i=0;i<wnd.panels.length;i++)
        if (wnd.panels[i] != null) {
          h-=wnd.panels[i].GetHeight();
        }
    }
    if (wnd.status != null)
      h-=wnd.status.GetHeight();
    h-=4;
    wnd.container.SetHeight(h+'px');
  }



//-------------------------------------------------------------------
  this.OnDynData = function (_data){
    //надо определить в потомке
  }


  this.OnResize = function (){
    //надо определить в потомке
  }
//-------------------------------------------------------------------


//-------------------------------------------------------------------
//                 функции, доступные пользователю
//-------------------------------------------------------------------

  this.Close = function () {
    //освобождаем обработчики событий
    _del_onmousemove(wnd);
    _del_onmousemove(head);
    //удаляем из списка окон
    _WND_A[_this.id]=null;

    wnd.p.removeChild(wnd);

    head1=null;
    head=null;
    btnClose=null;

    if (wnd.container != null) {
      wnd.container.Close();
      wnd.container = null;
    }

    if (wnd.status != null) {
      wnd.status.Close();
      wnd.status = null;
    }

    var i;
    if (wnd.panels != null)
      for (i in wnd.panels)
        if (wnd.panels[i] != null) {
          wnd.panels[i].Close();
          wnd.panels[i]=null;
        }
  };


  this.SetBody = function (s) {
    if (wnd.container != null)
      wnd.container.SetBody(s);
  };

  this.SetStatus = function(n) {
    wnd.status.SetText('<table height="100%"><tr><td><font style="'+_S_STATUS+'">&nbsp;'+n+'</font></td></tr></table>');
  };

  this.SetWindowName = function(n) {
    if (n == null || n == '') return 0;
    head.innerHTML='<table height="100%"><tr><td><font style="'+_S_HEADER+'">&nbsp;'+n+'</font></td></tr></table>';
    wnd.nm=n;
  };

  this.GetWindowName = function() {
    return wnd.nm;
  };



  this.AddBtnToBottom = function (nm,fn){
    _this.AddBtn(bot_tb,nm,fn);
  }

  this.SetZ = function (ind) {
    wnd.style.zIndex=ind;
  }

  this.SetVisible = function (m) {
    if (m) wnd.style.visibility='visible';
    else wnd.style.visibility='hidden';
  }

  this.SetFocus = function () {
    var i;
    for (i in _WND_A)
      if (_WND_A[i] != null)
        if (_WND_A[i] == this)
          _WND_A[i].SetZ(1);
        else
          _WND_A[i].SetZ(0);
  }

  this.Dump = function() {
    var s='',i;
    for (i in head)
      s+=i+' : '+head[i]+'\n';
    return s;
  }


  this.GetWnd = function() {
    return wnd;
  }

  this.ResizeControls = function(){
    wnd.SetBodyHeight();
  }

  this.SetBtnCloseOnMouseUp = function (fn){
    btnClose.Set_onmouseup(fn);
  }

//-------------------------------------------------------------------
//                      инициализация
//-------------------------------------------------------------------
  this.SetVisible(_visible);

  wnd.appendChild(head1);
  head1.appendChild(head);
  wnd.p.appendChild(wnd);

  var btnClose = new WGT_Control(head1,'button','','images/close.png','auto','right');
  btnClose.Set_onmouseup(this.Close);

  this.SetWindowName(_nm);

  if (_WND_A == null) _WND_A=new Array();
  _WND_A[this.id]=this;
}


//эту функцию надо вызывать для передачи данных окну (_id - код окна)
function window_callback(_id,_data,_reccount,_f,_e){
  if (_WND_A[_id] != null)
    if (_WND_A[_id].OnDynData != null)
      _WND_A[_id].OnDynData(_data,_reccount,_f,_e);
}

