var windowManager=new windowManagerInit();

function windowManagerInit() {
  this.dims=Position.GetWindowSize();
  this.currentWidth=this.dims.width;
  this.currentHeight=this.dims.height;
  //alert(currentWidth);
  //alert(currentHeight);
  this.masterWidth=1024;
  this.masterHeight=606;
  this.saveWindowSettings=0;
  this.windowHandles=new Array(0);

  window.alert=function(txt) {
    createNewWindow("window_alert","services/alert.cfm?txt="+txt);
  }

  return this;
}

function applyStyle(stylesheet) {
  var css=document.createElement("link");
  css.setAttribute("href",stylesheet);
  css.setAttribute("rel","stylesheet");
  css.setAttribute("type","text/css");
  document.getElementsByTagName("head")[0].appendChild(css);
}

function applyScript(jscript) {
  var js=document.createElement("script");
  js.setAttribute("type","text/javascript");
  js.setAttribute("src",jscript);
  document.getElementsByTagName("head")[0].appendChild(js);
}

function rssRefresh(id) {
  var sURL, sVars, fnWhenDone, xhr;
  try {
    $('rss_icon').src="images/misc/indicator.gif";
    sURL="services/rss_links.cfm";
    sVars="";
    fnWhenDone=function (XHR) { 
      var result=XHR.responseText.replace(/^\s*|\s*$/g,""); 
      $(id).innerHTML=result;
      $('rss_icon').src="images/misc/feed.png";
    };
    xhr=new XHR();
    xhr.sendRequest("get", sURL, sVars, fnWhenDone);
  } catch(e) {}
}

function saveSettings(id,top,left,width,height,minwidth,minheight) {
  if (!windowManager.saveWindowSettings) return;
  var sURL, sVars, fnWhenDone, xhr;
  try {
    //
    // maintain the left margin across different resolutions:
    //
    left = left-((windowManager.currentWidth-windowManager.masterWidth)/2);

    if (width < minwidth) width=minwidth;
    if (height < minheight) height=minheight;

    var settings = top + "," + left + "," + width + "," + height + "," + minwidth + "," + minheight;
    sURL="services/settings.cfm?id="+id+"&settings="+settings;
    sVars="";
    fnWhenDone=function (XHR) { var result=XHR.responseText.replace(/^\s*|\s*$/g,""); };
    xhr=new XHR();
    xhr.sendRequest("get", sURL, sVars, fnWhenDone);
  } catch(e) {}
}

function initNewWindow(attr) {
  var sURL, sVars, fnWhenDone, xhr;
  try {
    sURL="services/settings.cfm?attr="+attr;
    sVars="";
    fnWhenDone=function (XHR) { 
      var result=XHR.responseText.replace(/^\s*|\s*$/g,""); 
      result=result.split(",");
      //
      // maintain the left margin across different resolutions:
      //
      result[1] = parseInt(result[1])+((windowManager.currentWidth-windowManager.masterWidth)/2);

      var win=new Window( {
      "name":attr,
      "z_index":-1,
      "min_width":result[4] || 100,
      "min_height":result[5] || 100,
      "action":"debug",
      "id":attr,
      "scrollbars":1,
      "is_minimized":0,
      "stayontop":0,
      "posy":result[0] || 100,
      "posx":result[1] || 100,
      "width":result[2] || 100,
      "height":result[3] || 100 } )

      windowManager.windowHandles[attr]=win;
    };

    xhr=new XHR();
    xhr.sendRequest("get", sURL, sVars, fnWhenDone);
  } catch(e) {}
}

function createNewWindow(id,url) {
  /*
  what we are generating (via http://muffinresearch.co.uk/code/javascript/DOMTool/):

  <div id="window_id" class="window_container">
    <div id="window_id_resize_handle" class="window_resize_handle"></div>
    <div id="window_id_topslice" class="window_topslice" >
      <div id="window_id_drag_handle" class="window_dragger"></div>
      <div class="window_button_holder">
        <a href="#" onClick="windowManager.windowHandles[id].minimize();"><img border="0" src="images/misc/window_min.png" /></a>
        <a href="#" onClick="windowManager.windowHandles[id].maximize();"><img border="0" src="images/misc/window_max.png" /></a>
        <a href="#" onClick="windowManager.windowHandles[id].close();"><img border="0" src="images/misc/window_close.png" /></a>
      </div>
      <div class="window_handle_left"></div>
      <div class="window_handle_center"></div>
      <div class="window_handle_right"></div>
    </div>
    <div id="window_id_middleslice" class="window_middleslice">
      <div class="window_border_left"></div>
      <div class="window_content" id="window_id_content">
        content
      </div>
      <div class="window_border_right"></div>
    </div>
    <div id="window_id_bottomslice" class="window_bottomslice">
      <div class="window_bottom_left"></div>
      <div class="window_bottom_center"></div>
      <div class="window_bottom_right"></div>
    </div>
  </div>
  */

  var div1=document.createElement('div');
  div1.className='window_container';
  div1.setAttribute('id',id);
  var div2=document.createElement('div');
  div2.className='window_resize_handle';
  div2.setAttribute('id',id+'_resize_handle');
  div1.appendChild(div2);
  var div3=document.createElement('div');
  div3.className='window_topslice';
  div3.setAttribute('id',id+'_topslice');
  div1.appendChild(div3);
  var div4=document.createElement('div');
  div4.className='window_dragger';
  div4.setAttribute('id',id+'_drag_handle');
  div3.appendChild(div4);
  var div5=document.createElement('div');
  div5.className='window_button_holder';
  div3.appendChild(div5);
  /*
  var a1=document.createElement('a');
  a1.onclick=function(){windowManager.windowHandles[id].minimize(); return false;};
  a1.setAttribute('href','#');
  div5.appendChild(a1);
  var img1=document.createElement('img');
  img1.setAttribute('border','0');
  img1.setAttribute('src','images/misc/window_min.png');
  a1.appendChild(img1);

  var a2=document.createElement('a');
  a2.onclick=function(){windowManager.windowHandles[id].maximize(); return false;};
  a2.setAttribute('href','#');
  div5.appendChild(a2);
  var img2=document.createElement('img');
  img2.setAttribute('border','0');
  img2.setAttribute('src','images/misc/window_max.png');
  a2.appendChild(img2);
  */
  var a3=document.createElement('a');
  a3.onclick=function(){windowManager.windowHandles[id].close(); return false;};
  a3.setAttribute('href','#');
  div5.appendChild(a3);
  var img3=document.createElement('img');
  img3.setAttribute('border','0');
  img3.setAttribute('src','images/misc/window_close.png');
  a3.appendChild(img3);

  var div6=document.createElement('div');
  div6.className='window_handle_left';
  div3.appendChild(div6);
  var div7=document.createElement('div');
  div7.className='window_handle_center';
  div3.appendChild(div7);
  var div8=document.createElement('div');
  div8.className='window_handle_right';
  div3.appendChild(div8);
  var div9=document.createElement('div');
  div9.className='window_middleslice';
  div9.setAttribute('id',id+'_middleslice');
  div1.appendChild(div9);
  var div10=document.createElement('div');
  div10.className='window_border_left';
  div9.appendChild(div10);
  var div11=document.createElement('div');
  div11.setAttribute('id',id+'_content');
  div11.className='window_content';
  div9.appendChild(div11);
  var txt18=document.createTextNode('content');
  div11.appendChild(txt18);
  var div12=document.createElement('div');
  div12.className='window_border_right';
  div9.appendChild(div12);
  var div13=document.createElement('div');
  div13.className='window_bottomslice';
  div13.setAttribute('id',id+'_bottomslice');
  div1.appendChild(div13);
  var div14=document.createElement('div');
  div14.className='window_bottom_left';
  div13.appendChild(div14);
  var div15=document.createElement('div');
  div15.className='window_bottom_center';
  div13.appendChild(div15);
  var div16=document.createElement('div');
  div16.className='window_bottom_right';
  div13.appendChild(div16);

  if (url) {    
    var sURL=url;
    var sVars="";
    var fnWhenDone=function (XHR) { 
      var result=XHR.responseText.replace(/^\s*|\s*$/g,""); 
      result=result.split("|");
      if (result[0]=='Alert')
        div4.innerHTML="<div style='padding:4px 0 0 8px;'><b>Alert</b></div>";
      else
        div4.innerHTML=result[0]; 
      div11.innerHTML=result[1]; 
      MM_preloadImages(); 
    };
    var xhr=new XHR();
    xhr.sendRequest("get", sURL, sVars, fnWhenDone);
  }

  div1.style.visibility='hidden';
  div1.style.display='none';
  document.body.appendChild(div1);

  try {
    new Effect.Appear(div1,{duration:0.5, afterFinish:function(){ initNewWindow(id); }});
  } catch(e) {
    div.style.display='';
    dump(e);
  }
}

//  this class is based on the original work rtwindows by martin scheffler and markus hartleb

Window = Class.create();
Window.prototype = {
  initialize:function() {
      
  var options = Object.extend({
    id:-1,
    name:"noname",
    min_width:100,
    min_height:100,
    screen_safety_border:20,
    width:100,
    height:100,
    posx:100,
    posy:100,
    z_index:-1,
    is_minimized:false }, arguments[0] || {});

    this.options = options;
    this.start();
  },

  start: function() {
    this.closing=false;
    this.event("startinit");
    this.element = $(this.options.id+""); 
 
    this.draghandle = $(this.options.id + "_drag_handle");
    this.resizehandle = $(this.options.id + "_resize_handle");
    this.fader = $(this.options.id + "_middleslice");
    
    this.topslice = $(this.options.id + "_topslice");
    Element.cleanWhitespace(this.topslice);
    this.middleslice = $(this.options.id + "_middleslice");
    Element.cleanWhitespace(this.middleslice);
    this.bottomslice = $(this.options.id + "_bottomslice");
    Element.cleanWhitespace(this.bottomslice);

    // set contents and border divs to window height:
    this.border_l = this.middleslice.childNodes[0];
    this.content = this.middleslice.childNodes[1];
    this.border_r = this.middleslice.childNodes[2];

    if(!parseInt(this.options.posx))
      this.options.posx=-1;
    if(!parseInt(this.options.posy))
      this.options.posy=-1;
    this.setHeight(this.options.height);
    this.setWidth(this.options.width);
    this.setPosX(this.options.posx);
    this.setPosY(this.options.posy);

    this.event("starteffects");
    this.positiondragger=new Draggable(this.element, {
      snap:5,
      handle:this.options.id+'_drag_handle',
      starteffect:this.startdrag.bind(this),
      zindex:500,
      endeffect: (this.stopdrag).bind(this)
    });

    this.resizedragger=new Draggable(this.options.id+"_resize_handle", {
      snap:5,
      starteffect:(function() {this.event("resizestart");}).bind(this),
      change:(function(){this.event("resizing");}).bind(this),
      endeffect:(this.stopresize).bind(this) 
    });
    
    this.options.resizestartInternal=(function(){
      this.bringToTop();
    }).bind(this);

    this.options.resizingInternal=(function() {
      handleOffsets = Position.offsetParent(this.resizehandle);

      width = this.getResizeWidth();
      height = this.getResizeHeight();

      if (width < this.options.min_width) {
        width = this.options.min_width;
        // touch the bottom div, required for FF and KHTML:
        this.fore=(!this.fore || this.fore==1)?-1:1;
        this.bottomslice.style.height=(this.bottomslice.offsetHeight+this.fore)+"px";
      }
      else {
        this.bottomslice.style.height=this.bottomslice.childNodes[0].style.height;
      } 
      if (height < this.options.min_height) height = this.options.min_height;
    
      this.setHeight(height);
      this.setWidth(width);
    }).bind(this);
    
    // touch the bottom div, required for FF and KHTML:
    this.options.correctBottomSlice=function(target) {
      target.fore=(!target.fore || target.fore==1)?-1:1;
      target.bottomslice.style.height=(target.bottomslice.offsetHeight+target.fore)+"px";
    }

    this.options.resetResizeDraggerInternal = function(target) {
      this.maximized=false;
      //
      //check if resize_handler position is not where it should be.
      //this happens when win was made smaller than the minimums.
      //
      h= target.bottomslice.childNodes[0].offsetHeight
        +target.middleslice.childNodes[0].offsetHeight
        +target.topslice.childNodes[0].offsetHeight
        -target.getResizeHeight();

      w= target.bottomslice.offsetWidth-target.getResizeWidth();
    
      new Effect.MoveBy(target.resizehandle, h,w, {duration:0.0});
    }

    if(!window.max_zIndex ||window.max_zIndex<this.options.z_index) {
      window.max_zIndex=(this.options.z_index>0)?this.options.z_index:0; 
    }

    if(this.options.z_index==-1){
      this.bringToTop();
    }
    
    this.element.style.zIndex=this.options.z_index;

    new Effect.Appear(this.element, {
      duration:0.2,
      afterUpdate:(function(event) {
        this.element.style.visibility="visible";
        this.event("stopinit");
      }).bind(this)
    });

    if(this.options.is_minimized==true) {
      this.options.is_minimized=false;
      this.minimize();
    }

    if(this.options.stayontop==true) {
      this.options.stayontop=false;
      this.toggleStayOnTop();
    }

     if(this.options.scrollbars==true) {
       this.content.style.overflow="auto";
    }
                                                                 else this.content.style.overflow="hidden";
    this.event("resetResizeDragger");
  },

  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },

  setWidth:function(val) {
    this.options.width=val;
    // touch the value, required for FF:
    this.element.style.width="0px";
    this.element.style.width=val+"px";
  },

  setHeight:function(val) {
    if(this.options.minimized)
      return;
    this.options.height=val;

    h= val - this.topslice.childNodes[0].offsetHeight 
        - this.bottomslice.childNodes[0].offsetHeight;

    this.content.style.height=h+"px";
    this.border_l.style.height=h+"px";
    this.border_r.style.height=h+"px";
  },

  setPosX:function(val) {
    this.element.style.left=val+"px";
  },

  setPosY:function(val) {
    this.element.style.top=val+"px";
  },

  getResizeWidth: function() {
    return this.resizehandle.offsetLeft+this.resizehandle.offsetWidth;
  },

  getResizeHeight: function() {
     return this.resizehandle.offsetTop+this.resizehandle.offsetHeight;
  },

  stopdrag:function(element)  {
    if(document.all) {
      windowWidth=document.body.offsetWidth-this.options.screen_safety_border;
      windowHeight=document.body.offsetHeight-this.options.screen_safety_border;
    }
    else {
      windowWidth=window.innerWidth-this.options.screen_safety_border;
      windowHeight=window.innerHeight-this.options.screen_safety_border;
    }

    var currentX=this.element.offsetLeft;
    var currentY=this.element.offsetTop;
    var width=this.getResizeWidth();
    var height=this.getResizeHeight();

    saveposev=function(){
      this.options.posx=currentX;
      this.options.posy=currentY;
      this.event("stopdrag");
    }.bind(this);
    
    saveposev();

    saveSettings(element.id,currentY,currentX,width,height,this.options.min_width,this.options.min_height);
  },

  stopresize:function(){
    this.event("resetResizeDragger");
    this.event("stopresize");
    
    var currentX=this.element.offsetLeft;
    var currentY=this.element.offsetTop;
    var width=this.getResizeWidth();
    var height=this.getResizeHeight();

    saveSettings(this.element.id,currentY,currentX,width,height,this.options.min_width,this.options.min_height);
  },
 
  close:function() {
    if(this.closing)
      return;
    this.event("close");
    this.closing=true;
    new Effect.Fade( this.element, { 
      duration:0.2, 
      afterFinish:(function(event) { Element.remove(this.element); }).bind(this) }
    );
  },

  bringToTop:function() {
    if(this.options.stayontop==false && this.options.z_index<window.max_zIndex) {
      this.element.style.zIndex=++window.max_zIndex;
      this.options.z_index=this.element.style.zIndex;
    }
  },

  toggleStayOnTop:function() {
    if(this.options.stayontop==false) {
      this.options.stayontop=true;
      this.element.style.zIndex=990;
    }
    else {
      this.options.stayontop=false;
      this.bringToTop();
    }
  },

  minimize:function() {
    this.bringToTop();
    if(!this.fader.currentlyFading) {
      this.currentlyFading=true;
      if(this.options.is_minimized==true) {
        this.options.is_minimized=false;
        new Effect.BlindDown(
          this.fader,
          { afterFinish:(function(event){
              this.currentlyFading=false;
				      this.event("resetResizeDragger");
              this.event("unminimized");            
            }).bind(this),
            afterUpdate:(function(event){
              this.event("correctBottomSlice");
            }).bind(this)
          }
        );
      }
      else {
        this.options.is_minimized=true;
        new Effect.BlindUp(
          this.fader,
          { afterFinish:(function(event){
              this.currentlyFading=false;
              this.event("resetResizeDragger");
              this.event("minimized");
            }).bind(this),
            afterUpdate:(function(event){
              this.event("correctBottomSlice")
            }).bind(this)
          }
        );
      }
    }
    this.event("minimize");
  },

  maximize:function() {
    this.bringToTop();
    if(this.fader.currentlyFading)
      return;

    if(this.options.is_minimized==true) {      
      this.options.is_minimized=false;
      new Effect.BlindDown(this.fader,{afterFinish:(function() {this.maximize();}).bind(this)});
      return;
    }

    if(this.maximized) {
      this.fader.currentlyFading=true;
      this.event("maximize");
      new Effect.MoveBy( 
        this.element, 
        this.preMaxDims[1],
        this.preMaxDims[0],
        { duration:0.2  }
      );
     
     midh=(this.preMaxDims[3]-this.topslice.childNodes[0].offsetHeight-this.bottomslice.childNodes[0].offsetHeight);
     contenth=midh/this.middleslice.childNodes[0].offsetHeight*100;
     s_opts={scaleX:false, scaleContent:false, duration:0.2};
     new Effect.Scale( this.border_l,contenth, s_opts);
     new Effect.Scale( this.content, contenth, s_opts);
     new Effect.Scale( this.border_r,contenth, s_opts);
     
     new Effect.Scale( this.element,
       this.preMaxDims[2]*100/this.element.offsetWidth, 
        { scaleY:false, 
          afterFinish:(function() {
            this.event("resetResizeDragger");
            this.event("maximized");
            this.fader.currentlyFading=false;
            this.maximized=false;
            this.event("correctBottomSlice"); }).bind(this),  
          scaleContent:false,
          duration:0.2 }
     );
     
    }
    else {
      this.fader.currentlyFading=true;
      if(document.all) {
        windowWidth=document.body.offsetWidth-20;
        windowHeight=document.body.offsetHeight-20;
      }
      else {
        windowWidth=window.innerWidth;
        windowHeight=window.innerHeight;
      }
      
      new Effect.MoveBy( 
        this.element, 
        -this.element.offsetTop,
        -this.element.offsetLeft,
        { duration:0.2  }
      );

      endh=windowHeight-this.topslice.childNodes[0].offsetHeight-this.bottomslice.childNodes[0].offsetHeight;

      contenth=endh*100/this.middleslice.childNodes[0].offsetHeight;

      this.preMaxDims=[
        this.element.offsetLeft,
        this.element.offsetTop,
        this.element.offsetWidth,
        this.element.offsetHeight
      ];

      this.event("maximize");
     
      s_opts={scaleX:false, scaleContent:false, duration:0.2};
      new Effect.Scale( this.border_l,contenth, s_opts);
      new Effect.Scale( this.content, contenth, s_opts);
      new Effect.Scale( this.border_r,contenth, s_opts);

      new Effect.Scale( this.element, windowWidth*100/this.element.offsetWidth, { 
        scaleY:false, 
        afterFinish:(function() {
          this.event("resetResizeDragger");
          this.event("maximized");
          this.fader.currentlyFading=false;
          this.maximized=true;
          this.event("correctBottomSlice"); }).bind(this),  
        scaleContent:false,
        duration:0.2 }
      );
    }
  },

  startdrag:function(event) {
    this.bringToTop();
    if(this.options.stayontop==true)
      this.positiondragger.originalZ=990;
    else
      this.positiondragger.originalZ=this.options.z_index;
    this.event("startdrag");
  }
}
