var text='<div class="in"><div class="top"><span class="close" title="Закрыть" onMouseDown="eaAddCommand(\'{{chatid}}\', \'close\',1);">x</span><span class="show" title="Свернуть">O</span>{{name}} </div><div class="bottom" id="bottom_{{chatid}}">  <div class="content"><form action="" onSubmit="return false;"><textarea name="t" id="textarea_{{chatid}}"></textarea><input type="text" name="i" id="input_{{chatid}}"><input id="send" type="button" value="Send" onClick="eaAddCommand(\'{{chatid}}\', \'send\', document.getElementById(\'input_{{chatid}}\').value)"></form></div></div>&nbsp;&nbsp;E-mail: <a href="mailto:ilina@utrade.ru">ilina@utrade.ru</a> <span class="resize"></span></div>';

addHandler(window,'load',chatRoot,false);

function chatRoot(){
  chatWindow.initiate();
// chatWindow.createWindow(300,300);
}

var chatWindow={
  slideTime:500,
  defaultLeft:100,
  defaultTop:100,
  chatCollection:[],
  initiate:function(left,top){
//    this.createWindow(left||this.defaultLeft,top||this.defaultTop);
    addHandler(document,'mousedown',this.mousedown,false);
    addHandler(window,'scroll',this.scroll,false);
//  addHandler(window,'resize',this.resize,false);
    
  },
  createWindow:function(chatid, eaArrSupport, left,top){
	this.chatid = chatid;
    this.window=document.createElement('div');
    this.window.parent=this;
    this.window.counter=this.chatCollection.length;
    addClass(this.window,'chat');
    if(this.active){
      this.window.style.zIndex=this.active.style.zIndex*1+1;
      removeClass(this.active,'active');
    }
    addClass(this.window,'active');
    this.active=this.window;
	var tmptext = text.replace(/{{chatid}}/g, this.chatid);
	tmptext = tmptext.replace(/{{name}}/g, unescape(eaArrSupport.name));
    this.window.innerHTML=tmptext;
//    this.window.innerHTML=text;

    this.window.id='chat'+this.chatCollection.length;//потом заменить на аргумент
    this.chatCollection.push(this.window);

	var quant = this.chatCollection.length;
//	moveTo(this.window,left,top);
	moveTo(this.window,left + quant * 60,top + quant * 40);
    this.window.bodyLeft=left-bodyScrollLeft();
    this.window.bodyTop=top-bodyScrollTop();
    document.body.appendChild(this.window);

// HACK
	objBottom = document.getElementById('bottom_' + this.chatid);
	objBottom.style.background = '#fafafa url(http://education.zerich.ru/e-aid/i/'+this.chatid+'.jpg) no-repeat';

// focus	
	objInput = document.getElementById('input_' + this.chatid);
	addHandler(objInput,'keydown',this.keydown,false);
//	addHandler(objInput,'keypress',this.keydown,false);
	objInput.focus();

// get textarea
	objTextarea = document.getElementById('textarea_' + this.chatid);
	addHandler(objTextarea,'keydown',this.textareakeydown,false);
//	addHandler(objInput,'keypress',this.keydown,false);


    findPosition(this.window);


    this.highlight(this.window);
	return this.window;
  },
  mousedown:function(e){
    e=e||event;
    var target=e.target||e.srcElement;
    var element=chatWindow.findWindow(target);
    if(element&&element.parent&&element.parent==chatWindow){
      if(element.parent.active){
        element.style.zIndex=element.parent.active.style.zIndex*1+1;
        removeClass(element.parent.active,'active');
      }
      element.parent.active=element;
      addClass(element,'active');
      if(target.tagName=='SPAN'){
        if(target.className=='close'){
          var collection=chatWindow.chatCollection;
          if(collection.length>element.counter+1)collection.splice(element.counter,1,collection[collection.length-1]);
          collection[element.counter].counter=element.counter;
          collection.pop();
          removeElement(element);
        }
        else if(target.className=='show'){
          if(testClass(element,'short')){
            removeClass(element,'short');
            target.innerHTML='O';
          }
          else{
            addClass(element,'short');
            target.innerHTML='&ndash;';
          }
        }
        else if(target.className=='resize'){
          element.resizeX=e.clientX;
          element.resizeY=e.clientY;
          element.width=element.offsetWidth;
          element.height=element.offsetHeight;
          element.textarea=element.getElementsByTagName('textarea')[0];
          element.textarea.height=element.textarea.offsetHeight;
          addHandler(document,'mousemove',element.parent.resizemove,false);
          addHandler(document,'mouseup',element.parent.resizeup,false);
          addHandler(document,'selectstart',returnFalse,false);
        }
      }
      else if(target.tagName!='TEXTAREA'&&target.tagName!='INPUT'){
        cancelEvent(e);
        findPosition(element,e);
        addClass(element,'move');
        addHandler(document,'mousemove',element.parent.mousemove,false);
        addHandler(document,'mouseup',element.parent.mouseup,false);
        addHandler(document,'selectstart',returnFalse,false);
      }
    }
    else{
      if(chatWindow.active){
        removeClass(chatWindow.active,'active');
      }
    }
  },
  mouseup:function(e){
    e=e||event;
    cancelEvent(e);
    var element=chatWindow.active;

	//return focus to input
	objInput = document.getElementById('input_' + element.parent.chatid);
	objInput.focus();


    findPosition(element,e);
    removeClass(element,'move');
    removeHandler(document,'mousemove',element.parent.mousemove,false);
    removeHandler(document,'mouseup',element.parent.mouseup,false);
    removeHandler(document,'selectstart',returnFalse,false);
  },
  mousemove:function(e){
    e=e||event;
    var element=chatWindow.active;
    var left=e.clientX-element.deltaX;
    var top=e.clientY-element.deltaY;
    if(left<bodyScrollLeft())left=bodyScrollLeft();
    if(top<bodyScrollTop())top=bodyScrollTop();
    if(bodyWidth()+bodyScrollLeft()<e.clientX+element.offsetWidth-element.deltaX)left=bodyWidth()+bodyScrollLeft()-element.offsetWidth;
    if(bodyHeight()+bodyScrollTop()<e.clientY+element.offsetHeight-element.deltaY)top=bodyHeight()+bodyScrollTop()-element.offsetHeight;
    moveTo(element,left,top);
  },
  resizemove:function(e){
    e=e||event;
    cancelEvent(e);
    var element=chatWindow.active;
    setDimension(element,e,element.textarea);
  },
  resizeup:function(e){
    e=e||event;
    var element=chatWindow.active;
    findPosition(element);
    removeHandler(document,'mousemove',element.parent.resizemove,false);
    removeHandler(document,'mouseup',element.parent.resizeup,false);
    removeHandler(document,'selectstart',returnFalse,false);
  },
  resize:function(e){
    
  },
  findWindow:function(element){
    while(element.parentNode&&element.parent!=this)element=element.parentNode;
    return element;
  },
  scroll:function(){
    for(var i=0;chatWindow.chatCollection[i];i++){
      if(chatWindow.chatCollection[i]){
        findPosition(chatWindow.chatCollection[i]);
        slideTo(chatWindow.chatCollection[i],chatWindow.slideTime);
      }
    }
  },
  keydown:function(e){
	e=e||event;
//    cancelEvent(e);
    var winchatid=chatWindow.active.parent.chatid;
	if (e.keyCode == 13) {
		eaAddCommand(winchatid, 'send', document.getElementById('input_' + winchatid).value);
		return false;
	}
  },

  textareakeydown:function(e){
	e=e||event;
    cancelEvent(e);
	var objInput = document.getElementById('input_' + chatWindow.active.parent.chatid);
	objInput.focus();
  },


  highlight:function(element,index){
    if(!index)index=0;
    index++;
    if(index%2)addClass(element,'highlight');
    else removeClass(element,'highlight');
    if(index<6){
      var parent=this;
      setTimeout(function(){parent.highlight(element,index)},150);
    }
  }
}

function slideTo(e,slideTime){
  e.timeout=e.timeout||10;
  e.xTarget=bodyScrollLeft()+e.bodyLeft||0;
  e.yTarget=bodyScrollTop()+e.bodyTop||0;
  e.slideTime=slideTime;
  e.stop=false;
  e.yA=e.yTarget-e.top;
  e.xA=e.xTarget-e.left;
  if(e.slideLinear)e.period=1/e.slideTime;
  else e.param=Math.PI/(2*e.slideTime);
  e.yD=e.top;
  e.xD=e.left;
  var start=new Date();
  e.start=start.getTime();
  if(!e.moving)_slideTo(e);
}
function _slideTo(e){
  var current=new Date(),param,left,top;
  var delta=current.getTime()-e.start;
  if(e.stop){e.moving=false;}
  else if(delta<e.slideTime){
    var parent=this;
    setTimeout(function(){parent._slideTo(e)},e.timeout);
    if(e.slideLinear)param=e.param*delta;
    else param=Math.sin(e.param*delta);
    left=Math.round(e.xA*param+e.xD);
    top=Math.round(e.yA*param+e.yD);
    moveTo(e,left,top);
    e.moving=true;
  }
  else{
    moveTo(e,e.xTarget,e.yTarget);
    e.moving=false;
  }
}