var windows = new WindowsClass;

function WindowsClass()
{

  this.windowsList = new Array();

  this.newWindow = function(winId)
  {
    if (winId==undefined)
    winId = 'window'+ Math.round(Math.random()*1000);

    this.windowsList[winId] = new Window(winId);
    return this.windowsList[winId];
  }

  this.getWindow = function(winId)
  {
    return this.windowsList[winId];
  }

  this.resizeOverlay = function(id){
    var h = Math.max($('html').attr('scrollHeight'),$('body').height());
    $(id).height(h);
  }
}

function Button(btnId)
{
  this.id          = btnId;
  this.classString = '';
  this.caption     = '';
  this.action	 	 = '';

  this.draw = function($div)
  {
    if ($('#'+this.id)[0]==undefined)
    $div.append('<input type="button" id="'+this.id+'" class="'+this.classString+' btn" onclick="'+this.action+'" value="'+this.caption+'" />');
  }
}

function Window(winId)
{
  this.id   		 = winId;
  this.text 		 = '';
  this.title		 = '';
  this.draggable	 = true;
  this.modal		 = winId;
  this.refresh		 = true;
  this.closeAction   = '';
  this.actionOnBeforeClose = null;
  this.actionOnBeforeClose = null;

  //флаг, отвечающий за то, надо ли весить хук на ескейп
  this.setHook = false;

  this.closeButtonText = ' ';

  this.width 		 = 0;
  this.height		 = 0;
  this.left   		 = 0;
  this.top    		 = 0;
  this.titleClass    = ''
  this.winClass    = '';
  this.div    		 = '';
  this.classString	 = '';
  this.level		 = 0;

  this.ajax   		 = '';
  this.afterResponse = '';
  this.bottomHeight = 32;

  this.buttons = new Array();

  this.getId = function()
  {
    return this.id;
  }

  this.addButton = function(btnId, classString, caption, action)
  {
    this.buttons[btnId] = new Button(this.id+'-'+btnId);
    this.buttons[btnId].classString = classString;
    this.buttons[btnId].caption = caption;
    this.buttons[btnId].action  = action;
  }

  if (!this.closeAction)
  {
    this.closeAction = "windows.windowsList['"+this.id+"'].close();";
  }



  this.show = function()
  {
    this.btnClose		 = this.addButton(this.id+'close' ,'btnClose btn', this.closeButtonText, this.closeAction);
    this.div = $('#'+this.id);

    if (this.modal==false) this.modal = '';

    hidemyselects(this.div);

    if (!this.winClass)
    this.winClass='window';


    if (this.div[0]!=undefined)
    {
      this.div.show();
      $('#'+this.modal+'overlay').show();
      refresh = this.refresh;
    }else
    {
   	  FE.level +=1000;
      this.style = 'width:'+(!this.width?'auto':this.width)+
      ';height:'+(!this.height?'auto':this.height)+
      ';top:'+(!this.top?'50%':this.top)+
      ';left:'+(!this.left?'50%':this.left)+
      (this.level?(';z-index:'+(FE.level+1)+';'):'');

      content = '<div class="content" id="content-'+this.id+'">'+this.text+'</div>';

      var roundTable = '<table class="roundTable"><tr class="t"><td class="l">&nbsp;</td><td class="c">&nbsp;</td><td class="r">&nbsp;</td></tr>';
      roundTable+= '<tr class="m"><td class="l">&nbsp;</td><td class="c">'+content+'</td><td class="r">&nbsp;</td>';
      roundTable+= '<tr class="b"><td class="l">&nbsp;</td><td class="c">&nbsp;</td><td class="r">&nbsp;</td></table>';

      var divHTML = '<div id="'+this.id+'" class="'+ this.winClass +' '+this.classString+'" style="'+this.style+'">'+roundTable+'</div>';

      $(divHTML).appendTo('body');

      this.div = $('#'+this.id);

      refresh = true;

      if (this.div[0]!=undefined )
      {
        for (curButton in this.buttons)
        {
          this.buttons[curButton].draw(this.div);
          //если есть кнопка Закрыть(крестик), то окно закрывается по Esc
          //доработать, если у нас несколько открытых окон, закрывание по Esc только верхнее
          if (this.buttons[curButton].classString=='btnClose btn'){
            if (this.setHook){
//              $(document).bind('keydown', 'esc',function (evt){
//                //$('#'+winId+winId+'close').click();
//                level_win = 1;
//                winZId = winId;
//                $('.btnClose').each(function(){
//                  if ($('#'+winId).css('z-index')>level_win){
//                    level_win = $('#'+winId).css('z-index');
//                    winZId = winId;
//                  }
//                })
//                //$('.btnClose').unbind('click');
//                $(document).unbind('keydown', 'esc',function (evt){})
//                $('#'+winZId+' .btnClose' ).click();
//                return false; });
            }
          }
        }

        if ($('#'+this.modal+'overlay')[0]!=undefined)
        {
          $('#'+this.modal+'overlay').remove();
        }
        var h = Math.max($('html').attr('scrollHeight'),$('body').height());
        FE.manageEvent('onresize','window.windows.resizeOverlay("'+this.modal+'overlay")');
        //$('<div id="'+this.modal+'overlay" class="overlay" style="height:'+h+'px;display: block;'+(this.level?('z-index:'+(this.level)+';'):'')+'"></div>').appendTo('body');
        $('<div id="'+this.modal+'overlay" class="overlay" style="height:100%;display: block;'+(this.level?('z-index:'+(this.level)+';'):'')+'"></div>').appendTo('body');

        if (!this.left)
        this.div.css({'margin-left':'-'+(this.div[0].offsetWidth/2)+'px'});


        if (!this.top)
        this.div.css({'margin-top':'-'+(this.div[0].offsetHeight/2)+'px'});

        if (!this.titleClass)
        this.titleClass='title';

        if (this.title)
        {
          this.div.find('.roundTable .m .c').prepend('<div class="' + this.titleClass + '"><div>'+this.title+'</div></div>');

          if (this.draggable)
          {
            this.div.draggable({'handle':'.' + this.titleClass});
          }
        }
      }
    }


    if (this.div[0]!=undefined && refresh)
    {

      if ($('#'+this.id+' .m .c').children('.title')[0]!= undefined)
      {

        heightOfTop = $('#'+this.id+' .m .c').children('.title')[0].offsetHeight;
        // эта строка падает в ишаке!!!!!!
        //heightOfTop+= $('#'+this.id+' .m .c').children('.title').css('padding').replace('px','')*2;

      }
      else{ heightOfTop = 0; }

      contentHeight = $('#'+this.id).height() - heightOfTop - ($('#'+this.id).css('padding').replace('px','')*2) - this.bottomHeight;

      $('#content-'+this.id).css('height', contentHeight + 'px');

      if (this.text)
      {
        $('#content-'+this.id).html(this.text);
      }

      if (this.ajax)
      {

        downloadPage('index.php', this.ajax, 'content-'+this.id, null, this.afterResponse);
      }

      refresh = false;
    }

  }

  this.hide = function()
  {
    showmyselects();
    this.div.hide();
    $('#'+this.modal+'overlay').hide();
  }

  this.close = function()
  {
	if (this.actionOnBeforeClose) {
		eval(this.actionOnBeforeClose);
	}
    showmyselects();
    $('#'+this.id).remove();
    delete this.buttons;
    delete windows.windowsList[this.id];
    showmyselects();
    $('#'+this.modal+'overlay').remove();
    FE.clearEvent('onresize','window.windows.resizeOverlay("'+this.modal+'overlay")');
	if (this.actionOnAfterClose) {
		eval(this.actionOnAfterClose);
	}
  }
}

function hidemyselects($me){
  $("select").not($me).each(function(i){
    //if ($(this).css('z-index')<=$me.css('z-index'))
      this.style.visibility='hidden';
  });
}

function showmyselects(){
  $("select").each(function(i){
    this.style.visibility='visible';
  });
}

//@todo: перенести отсюда
FE.addHandler('alertMessageClose');
function showAlertMessage (message, title, width, height) {
  if (title==undefined) title='Внимание';
  if (width==undefined) width='400px';
  if (height==undefined) height='200px';
  var windowId = Math.round(Math.random()*1000);
  var alertWindow;
  alertWindow = windows.newWindow('alertWindow'+windowId);
  alertWindow.width  = width;
  alertWindow.height = height;
  alertWindow.level  = 149;
  alertWindow.title  = title;
  //alertWindow.id;
  alertWindow.closeAction = 'windows.windowsList[\'alertWindow'+windowId+'\'].close(); FE.handleEvent(\'alertMessageClose\');';
  //alertWindow.addButton('close', 'button_release', 'Закрыть', 'windows.windowsList[\'alertWindow'+windowId+'\'].close(); FE.handleEvent(\'alertMessageClose\');');
  //alertWindow.draggable = false;
  alertWindow.bottomHeight = 52;
  alertWindow.ajax = '';
  alertWindow.text = '<div style="overflow:auto;">'+message+'</div>';
  alertWindow.show();
}
