var sled={
  show:function(){ $('sled').fade('in'); },
  hide:function(){ $('sled').fade('out'); }
};
//~

var uiButton = new Class({
  Implements: [Events,Options],

  options: {
    'name':'button', // надпись на кнопке
    'action':null    // действие происходящее при её нажатии
  },

  container:null, // DOM объект окна

  initialize:function(options){
    this.setOptions(options);
    return this;
  },

  // создание DOM элемента
  create: function(){
    this.fireEvent('createRun',this);
    this.fireEvent('create',this);

    this.container = new Element('input',{
      'type':'button',
      'value':this.options.name
    });
    this.container.addEvent('click',this.options.action);

    this.fireEvent('createEnd',this);
  },

  getEl:function(){
    if(!$chk(this.container))
      this.create();
    return this.container;
  }

});
//~

var uiWindow_activeCount=0; // количество активных окон
var uiWindow_list=[];
var uiWindow = new Class({
  Implements: [Events,Options],

  options: {
    'id':null,        // id слоя рабочей обласни(содержания)
    'title':'&nbsp;',       // заголосок
    'width':null,     // ширина рабочей обласни
    'height':null,    // высота рабочей обласни
    'content':null,   // либо строка HTML-кода, либо ссылка на DOM-узел
    'button':[{'name':msg.w('CLOSE'),'action':'close'}],   // массив настроек для создания кнопок
    'close':false     // показывать ли кнопку "Закрыть" в титульной строке
  },

  // набор стандартных действий для кнопок
  actionList:{
    'close':function(){ this.close(); }
  },

  container:null, // DOM объект окна
  active:false, // флаг активности окна

  initialize:function(options){
    this.setOptions(options);
    uiWindow_list.push(this); // регистрация в общем списке
    return this;
  },

  // создание окна в DOM
  create: function(){
    // construct
    this.fireEvent('createRun',this);
    this.fireEvent('create',this);

    this.container = new Element('div',{ 'class':'uiWindow' });
    this.container.setStyles({
      opacity:0,
      display:'block'
    });
    var windowContentEl = new Element('div',{ 'class':'uiWindowContent' });

    var frameEl = new Element('div',{ 'class':'uiWindowFrame' });
    var frameContentEl = new Element('div',{ 'class':'uiWindowFrameContent' });

    var titleEl=new Element('div', {
      'html':this.options.title,
      'class':'uiTopBar'
    });

    if(this.options.close){
      var closeButtonEl = new Element('div',{ 'class':'uiCloseButton' });
      closeButtonEl.addEvent('click',this.actionList['close'].bind(this));
    }

    var bottomSpaceEl = new Element('div',{ 'class':'iBottomSpace' });

    var contentEl = new Element('div',{ 'class':'uiContent' });
    if($chk(this.options.width)) contentEl.setStyle('width',this.options.width);
    if($chk(this.options.height)) contentEl.setStyle('height',this.options.height);

    if($chk(this.options.id))
      contentEl.set('id',this.options.id);

    if($chk(this.options.button)){
      var buttonsBarEl = new Element('div',{ 'class':'uiBottomButton' });
      var buttons=[];
      var i=0;
      for(var i=0,l=this.options.button.length;i<l;i++)
      {
        if($type(this.options.button[i]['action'])=='string')
          this.options.button[i]['action']=this.actionList[this.options.button[i]['action']].bind(this);
        buttons[i]=new uiButton(this.options.button[i]).getEl();
      }
    }

    // assembly
    if(this.options.close)
      closeButtonEl.inject(titleEl,'top');
    titleEl.inject(frameContentEl);

    if($chk(this.options.content)){
      if($type(this.options.content)=='string')
        contentEl.set('html',this.options.content);
      else
        contentEl.grab(this.options.content);
    }
    contentEl.inject(bottomSpaceEl);

    if($chk(this.options.button)){
      for(var i=0,l=buttons.length;i<l;i++)
        buttons[i].inject(buttonsBarEl);
      buttonsBarEl.inject(bottomSpaceEl);
    }

    bottomSpaceEl.inject(frameContentEl);
    frameContentEl.inject(frameEl);
    frameEl.inject(windowContentEl);
    windowContentEl.inject(this.container);

    this.fireEvent('createEnd',this);
  },

  // удаление окна из DOM
  remove: function() {
    this.fireEvent('removeRun',this);
    this.fireEvent('remove',this);

    this.container.destroy();

    this.fireEvent('removeEnd',this);
  },

  // показать окно
  open: function(){
    if(this.active) return;
    this.fireEvent('openRun',this);
    this.fireEvent('open',this);

    if(!$chk(this.container))
      this.create();

    this.container.inject($(document.body));
    var fx=new Fx.Morph(this.container, {
      transition:Fx.Transitions.Expo.easeIn,
      duration:300,
      link:'chain'
    });
    fx.start({'opacity':1});
    fx.addEvent('complete',function(){
      this.active=true;
      uiWindow_activeCount++;
      this.fireEvent('openEnd',this);
    }.bind(this));
  },

  // закрытие окна
  close: function() {
    if(!this.active) return;
    this.fireEvent('closeRun',this);
    this.fireEvent('close',this);

    var fx=new Fx.Morph(this.container, {
      transition:Fx.Transitions.Expo.easeOut,
      duration:300,
      link:'chain'
    });
    fx.start({'opacity':0});
    fx.addEvent('complete',function(){
      this.remove();
      this.active=false;
      uiWindow_activeCount--;
      this.fireEvent('closeEnd',this);
    }.bind(this));
  }
});
// закрывает все открытые окна
function uiWindow_closeAll()
{
  if(uiWindow_activeCount>0){
    for(var i=0,l=uiWindow_list.length;i<l;i++)
      if(uiWindow_list[i].active)
        uiWindow_list[i].close();
  }
}
//~

var feedback = {
  _window:null,
  show:function(){
    if($chk(this._window) && this._window.active) return;
    this._window=new uiWindow({
      'title':msg.v('FEEDBACK'),
      'content':$('feedback_form'),
      'button':null,
      'close':true,
      'width':500
    });
    this._window.addEvent('openEnd',function(){
      $('feedback_form').data.focus();
    });
    this._window.addEvent('removeRun',function(){
      $('feedback_form').reset();
      $('hidden').grab($('feedback_form'));
    });
    this._window.open();
  },
  hide:function(){
    if($chk(this._window))
      this._window.close();
  }
}
//~

/**
 * InfoDot - метки информационных сообщений
 * формат метки: <span class="infodot"><span class="iInfo iTop/iRight/iBottom/iLeft" style="display:none;">текст, любой HTML</span></span>
 */
var infodot = new Class({
  Implements: [Events],

  container:null, // DOM объект окна
  target:null,    // DOM объект метки
  active:false,   // флаг активности

  orientationList:{
    'top':{
      _position:function(obj){
        obj.container.style.marginTop='-'+(Number(obj.container.clientHeight)-1)+'px';
        obj.container.style.marginLeft=Math.round(-Number(obj.container.clientWidth)/2+Number(obj.target.clientWidth)/2)+'px';
      },
      create:function(obj){
        obj.container = new Element('div',{'class':'infodotFrame'});

        var infoEl=obj.target.getChildren('.iInfo');
        if($chk(infoEl))
        {
          var contentEl=new Element('div',{ 'class':'iContentTop' });
          var infoCopyEl=infoEl.clone();
          infoCopyEl.setStyle('display','block');

          var angleEl=new Element('div',{ 'class':'iAngleTop' });

          // assembly
          infoCopyEl.inject(contentEl);
          contentEl.inject(obj.container);

          angleEl.inject(obj.container);

          obj.container.inject(obj.target);
        }
      }
    },
    'right':{
      _position:function(obj){
        obj.container.style.marginTop=Math.round(-Number(obj.container.clientHeight)/2+Number(obj.target.clientHeight)/2)+'px';
        obj.container.style.marginLeft=(Number(obj.target.clientWidth)-1)+'px';
      },
      create:function(obj){
        obj.container = new Element('div',{'class':'infodotFrame'});

        var infoEl=obj.target.getChildren('.iInfo');
        if($chk(infoEl))
        {
          var contentEl=new Element('div',{ 'class':'iContentRight' });
          var infoCopyEl=infoEl.clone();
          infoCopyEl.setStyle('display','block');

          var angleEl=new Element('div',{ 'class':'iAngleRight' });

          // assembly
          angleEl.inject(obj.container);

          infoCopyEl.inject(contentEl);
          contentEl.inject(obj.container);

          obj.container.inject(obj.target);
          angleEl.setStyle('height',obj.container.clientHeight);
        }
      }
    },
    'bottom':{
      _position:function(obj){
        obj.container.style.marginTop=(Number(obj.target.clientHeight)-1)+'px';
        obj.container.style.marginLeft=Math.round(-Number(obj.container.clientWidth)/2+Number(obj.target.clientWidth)/2)+'px';
      },
      create:function(obj){
        obj.container = new Element('div',{'class':'infodotFrame'});

        var infoEl=obj.target.getChildren('.iInfo');
        if($chk(infoEl))
        {
          var contentEl=new Element('div',{ 'class':'iContentBottom' });
          var infoCopyEl=infoEl.clone();
          infoCopyEl.setStyle('display','block');

          var angleEl=new Element('div',{ 'class':'iAngleBottom' });

          // assembly
          angleEl.inject(obj.container);

          infoCopyEl.inject(contentEl);
          contentEl.inject(obj.container);

          obj.container.inject(obj.target);
        }
      }
    },
    'left':{
      _position:function(obj){
        obj.container.style.marginTop=Math.round(-Number(obj.container.clientHeight)/2+Number(obj.target.clientHeight)/2)+'px';
        obj.container.style.marginLeft='-'+(Number(obj.container.clientWidth)-1)+'px';
      },
      create:function(obj){
        obj.container = new Element('div',{'class':'infodotFrame'});

        var infoEl=obj.target.getChildren('.iInfo');
        if($chk(infoEl))
        {
          var contentEl=new Element('div',{ 'class':'iContentLeft' });
          var infoCopyEl=infoEl.clone();
          infoCopyEl.setStyle('display','block');

          var angleEl=new Element('div',{ 'class':'iAngleLeft' });

          // assembly
          infoCopyEl.inject(contentEl);
          contentEl.inject(obj.container);

          angleEl.inject(obj.container);

          obj.container.inject(obj.target);
          angleEl.setStyle('height',obj.container.clientHeight);
        }
      }
    }
  },
  orientation:'top', // направление появляющейся метки

  initialize:function(target){
    // target
    this.target=target;
    this.target.addEvents({
      'mouseenter':function(){ this.open(); }.bind(this),
      'mouseleave':function(){ this.close(); }.bind(this)
    });

    // orientation
    var infoEl=this.target.getChildren('.iInfo');
    if(infoEl.hasClass('iRight')[0])
      this.orientation='right';
    else if(infoEl.hasClass('iBottom')[0])
      this.orientation='bottom';
    else if(infoEl.hasClass('iLeft')[0])
      this.orientation='left';

    return this;
  },

  // создание окна в DOM
  create: function(){
    // construct
    this.fireEvent('createRun',this);
    this.fireEvent('create',this);

    this.orientationList[this.orientation].create(this);

    this.fireEvent('createEnd',this);
  },

  // удаление из DOM
  remove: function() {
    this.fireEvent('removeRun',this);
    this.fireEvent('remove',this);

    this.container.destroy();
    this.container=null;

    this.fireEvent('removeEnd',this);
  },

  // установить позицию
  _position:function(){
    this.orientationList[this.orientation]._position(this);
  },

  // показать окно
  open: function(){
    this.fireEvent('openRun',this);
    this.fireEvent('open',this);

    if(!$chk(this.container))
      this.create();

    this._position();
    this.active=true;

    this.fireEvent('openEnd',this);
  },

  // закрытие окна
  close: function() {
    this.fireEvent('closeRun',this);
    this.fireEvent('close',this);

    this.remove();
    this.active=false;

    this.fireEvent('closeEnd',this);
  }
});
//~

window.addEvent('domready',function(){

  /* hiders */
  window.addEvent('keypress',function(e){
    if(e.key=='esc') uiWindow_closeAll();
  });
  $(document.body).addEvent('click',function(event){
    var e = event || window.event;
    var t = $($chk(e.target)?e.target:e.srcElement);
    if(uiWindow_activeCount>0 && !t.getParent('.uiWindow'))
      uiWindow_closeAll();
  });

  $$('.infodot').each(function(item){
    new infodot(item);
  });

  // sled
  $('sled').setStyles({
    opacity:0,
    display:'block'
  });

  /* FEEDBACK */
  $('feedback_form').addEvent('submit',function(e){
    e.stop();

    if(!( this.data.value!='' && (is_user() || this.email.value!='') ))
      return false;

    this.set('send',{onComplete:function(response){
      sled.hide();
    }});

    //Send the form.
    this.send();
    sled.show();
    feedback.hide();
    return true;
  });
  /* click to show */
  $('fb-trigger').addEvent('click',function(){
    feedback.show();
  });

});