/* Handle window resizing and moving */

var screenManager = Components.classes["@mozilla.org/gfx/screenmanager;1"].getService(Components.interfaces.nsIScreenManager);

var ynWindowHandlers = {};

ynWindowHandlers._mode = "simple";// simple or expand
ynWindowHandlers._tab = "";// simple or expand
ynWindowHandlers._maximized = false;

ynWindowHandlers.expand = function (tab) {
  this.changeMode("expand",tab);
  
  if (tab=="browser") {
//    document.getElementById("tab-browser").hidden=false;
    document.getElementById("tab-browser").setAttribute("selected","true");
    document.getElementById("tab-columns").removeAttribute("selected");
    document.getElementById("website-panel").hidden=false;
    document.getElementById("columns-panel").hidden=true;
  } else {
//    document.getElementById("tab-columns").hidden=false;
    document.getElementById("tab-columns").setAttribute("selected","true");
    document.getElementById("tab-browser").removeAttribute("selected");
    document.getElementById("website-panel").hidden=true;
    document.getElementById("columns-panel").hidden=false;
    try {
      function onYServicesReady() {
        var YServices = YOONO_CMPT.getYServices()
        if (!YServices || !YServices.core || !YServices.accountsManager || !YServices.yoodgetInstances)
          return window.setTimeout(onYServicesReady,500);
        var iframe = document.getElementById("columns-iframe");
        YServices.core.require("accountsManager",function () {
          YServices.accountsManager.initAccountsManager(       
          { observe : function(topic, param) {
            switch (topic) {
            case YServices.accountsManager.STATUS_INIT_OK :     
              friends = YServices.yoodgetInstances.getRegisteredYoodgetWrapper("{friends@yoono.com}",-1);
              var w = iframe.contentWindow;
              if (w.wrappedJSObject)
                w = w.wrappedJSObject;
              friends.yoodget.initMultiColumnDoc(w.document);
              break;
            }      
          } } );    
        });
        iframe.style.overflowX = "auto";
      }
      onYServicesReady();
    } catch(e) {
      Components.utils.reportError(e);
    }
  }
  
  this.restoreWidth();
}

ynWindowHandlers.getTab = function () {
  return this._tab;
}

ynWindowHandlers.changeMode = function (mode, tab) {
  this._mode = mode;
  this._tab = tab;
  var win = document.getElementById("yoono-window");
  win.setAttribute("mode",this._mode);
  if (this._tab)
  win.setAttribute("tab",this._tab);
  document.getElementById("tab-buttons").hidden=this._mode!="expand";
  document.getElementById("tabs").hidden=this._mode!="expand";
  document.getElementById("expand-button").className=this._mode;
}

ynWindowHandlers.collapse = function () {
  this.changeMode("simple","");
  this.restoreWidth();
}

ynWindowHandlers.toggle = function (tab) {
  if (this._mode=="simple") {
    this.expand(tab)
  } else if (this._tab!=tab) {
    this.expand(tab)
  } else {
    this.collapse()
  }
}
ynWindowHandlers.toggleExpand = function (aButton) {
  var win = document.getElementById("yoono-window");

  var tab = win.getAttribute("tab");
  if (!tab) tab= "columns"
  
  if(aButton) {
    var class = aButton.className;
    if('simple' == class) {
      tab = 'columns';
    }
  }
  if (this._mode=="simple") {
    this.expand(tab);
  } else {
    this.collapse()
  }
}

ynWindowHandlers.toggleMaximize = function () {
  if (ynWindowHandlers._maximized) {
    ynWindowHandlers._maximized = false;
    ynWindowHandlers.move(ynWindowHandlers.beforeMaximizeX, ynWindowHandlers.beforeMaximizeY);
    ynWindowHandlers.resize(ynWindowHandlers.beforeMaximizeWidth, ynWindowHandlers.beforeMaximizeHeight);
  } else {
    var sc = screenManager.screenForRect(window.screenX, window.screenY, window.outerWidth, window.outerHeight);
    var screenLeft={}, screenTop={}, screenWidth={}, screenHeight={};
    sc.GetAvailRect(screenLeft, screenTop, screenWidth, screenHeight);
    ynWindowHandlers.beforeMaximizeX = window.screenX;
    ynWindowHandlers.beforeMaximizeY = window.screenY;
    ynWindowHandlers.move(screenLeft.value, screenTop.value);
    ynWindowHandlers.beforeMaximizeWidth = window.outerWidth;
    ynWindowHandlers.beforeMaximizeHeight = window.outerHeight;
    ynWindowHandlers.resize(screenWidth.value, screenHeight.value);
    ynWindowHandlers._maximized = true;
  }
  document.getElementById("maximize-button").className=ynWindowHandlers._maximized?"maximized":"normal";
}
ynWindowHandlers.close = function () {
  if (navigator.platform.indexOf("Linux")!=-1)
    trayIcon.quit();
  else
    trayIcon.close();
}

ynWindowHandlers.restoreWidth = function () {
  var win = document.getElementById("yoono-window");
  var width = parseInt(win.getAttribute(this._mode+"width"));
  var height = parseInt(win.getAttribute("height"));
  this.resize(width,height);
}

// Disable effect on window dragging on Linux
// (conflict with windows manager)
ynWindowHandlers._enableEffect = navigator.platform.toLowerCase().indexOf("linux")==-1;
ynWindowHandlers._screenBorder = 2;
ynWindowHandlers._magneticBorder = 15;
ynWindowHandlers._updateTimeout = null;
ynWindowHandlers.move = function (x, y) {
  if (x==null) x=window.screenX;
  if (y==null) y=window.screenY;
 
  if (!ynWindowHandlers._enableEffect) {
    window.moveTo(x,y);
    return;
  }
  
  // Do a magnetic effect on main screen sides
  var sc = screenManager.screenForRect(window.screenX, window.screenY, window.outerWidth, window.outerHeight);
  var left={}, top={}, width={}, height={};
  sc.GetAvailRect(left, top, width, height);
  var screenBorder = ynWindowHandlers._screenBorder;
  // Grip left
  if (x-left.value<=ynWindowHandlers._magneticBorder && x-left.value>=0)
    x = left.value+screenBorder;
  // Grip top
  if (y-top.value<=ynWindowHandlers._magneticBorder && y-top.value>=0)
    y = top.value+screenBorder;
  // Grip right
  var xMaxLimit = width.value-window.outerWidth;
  if (x-left.value>=xMaxLimit-ynWindowHandlers._magneticBorder && x-left.value<=xMaxLimit)
    x = left.value+xMaxLimit-screenBorder;
  // Grip bottom
  var yMaxLimit = height.value-window.outerHeight;
  if (y-top.value>=yMaxLimit-ynWindowHandlers._magneticBorder && y-top.value<=yMaxLimit)
    y = top.value+yMaxLimit-screenBorder;
  
  window.moveTo(x,y);
}

ynWindowHandlers.resize = function (w, h, middleResize) {
  var sc = screenManager.screenForRect(window.screenX, window.screenY, window.outerWidth, window.outerHeight);
  var screenLeft={}, screenTop={}, screenWidth={}, screenHeight={};
  sc.GetAvailRect(screenLeft, screenTop, screenWidth, screenHeight);
  
  if (!w) w=window.outerWidth;
  if (!h) h=window.outerHeight;
  
  var iframe = document.getElementById("main-iframe");
  
  if (this._mode=="simple" || middleResize) {
    w = Math.min(w, 700);
    if (middleResize && this._mode=="expand")
      w = Math.min(w, window.outerWidth-220);
  } else {
    w = Math.max(w, iframe.boxObject.width+470);
  }
  w = Math.min(w, screenWidth.value-10);
  w = Math.max(w, 250);
  h = Math.max(h, 450);
  h = Math.min(h, screenHeight.value-10);
  
  if (this._mode=="simple" || middleResize) {
    iframe.style.minWidth = (w-18)+"px";
    iframe.style.maxWidth = (w-18)+"px";
  } else if (middleResize) {
    iframe.style.minWidth = w+"px";
    iframe.style.maxWidth = w+"px";
  }
  
  if (!middleResize)
    window.resizeTo(w,h);
  
  var sidebarBox = document.getElementById("sidebar-box");
  var flyingLogo = document.getElementById("flying-logo");
  var headerSpacer = document.getElementById("header-spacer");
  if (this._mode=="expand")
    headerSpacer.style.width=(sidebarBox.boxObject.width-flyingLogo.boxObject.width-20+21)+"px";
  else
    headerSpacer.style.width="";
  
  var win = document.getElementById("yoono-window");
  if (middleResize)
    win.setAttribute("simplewidth",w);
  else
    win.setAttribute(this._mode+"width",w);
  
  win.setAttribute("height",h);
}

ynWindowHandlers.moveLeft = function () {
  var sc = screenManager.screenForRect(window.screenX, window.screenY, window.outerWidth, window.outerHeight);
  var left = {},top = {},width = {},height = {};
  sc.GetAvailRect(left, top, width, height);
  window.moveTo(left.value+ynWindowHandlers._screenBorder, window.screenY);
}

ynWindowHandlers.moveRight = function () {
  var sc = screenManager.screenForRect(window.screenX, window.screenY, window.outerWidth, window.outerHeight);
  var left = {},top = {},width = {},height = {};
  sc.GetAvailRect(left, top, width, height);
  window.moveTo(left.value+width.value-window.outerWidth-ynWindowHandlers._screenBorder, window.screenY);
}

ynWindowHandlers.addWindowDragElement = function(element) {
  element.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onMoveElementClick(element,event);
  },true);
}

ynWindowHandlers._onMoveElementClick = function(elementToDrag, event) {
  if (ynWindowHandlers._maximized) return;
  
  var origWindowX = window.screenX;
  var origWindowY = window.screenY;
  
  var origEventX = event.screenX;
  var origEventY = event.screenY;
  
  var doc = elementToDrag.ownerDocument;
  
  function moveHandler(e) {
    
    var newX = origWindowX + (e.screenX-origEventX);
    var newY = origWindowY + (e.screenY-origEventY);
    
    ynWindowHandlers.move(newX, newY);
    
    e.stopPropagation();
    e.preventDefault();
  }

  function upHandler(e) {
    doc.removeEventListener("mousemove", moveHandler, true);
    doc.removeEventListener("mouseup", upHandler, true);
    ynWebPanel.endMoving();
    if (event.screenX!=e.screenX || event.screenY!=e.screenY) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
  
  doc.addEventListener("mousemove", moveHandler, true);
  doc.addEventListener("mouseup", upHandler, true);

  ynWebPanel.startMoving();

  event.stopPropagation();
  event.preventDefault();
}


ynWindowHandlers._onVerticalResizeElementClick = function(event, side) {
  if (ynWindowHandlers._maximized) return;
  
  var iframe = document.getElementById("main-iframe");
  var win = iframe.contentWindow;
  if (win.wrappedJSObject)
    win = win.wrappedJSObject;
  
  var initialWidth = document.documentElement.boxObject.width; // -10 for transparent resizers
  if (side=="middle")
    initialWidth = iframe.boxObject.width;
  var initialX = event.screenX;
  var previousX = event.clientX;
  
  function mouseUp(evt) {
    document.removeEventListener('mouseup', mouseUp, true);
    document.removeEventListener('mousemove', mouseMove, true);
    evt.stopPropagation();
  }
  
  function mouseMove(evt) {
    var direction = (evt.clientX > previousX)?'right':'left';
    previousX = evt.clientX;
    
    var diffX=evt.screenX - initialX;
    if (side=="left") 
      diffX*=-1;
    var proposedWidth = initialWidth+diffX;
    
    var width = win.ynSidebar.getResizeWidth(proposedWidth, direction);
    //dump("mouse move -- resize --> "+proposedWidth+"=>"+width+" - "+direction+"\n");
    
    ynWindowHandlers.resize(width,null,side=="middle");
    //dump("v-resize : "+(width+10)+"x"+window.outerHeight+"\n");
    if (side=="left") {
      ynWindowHandlers.move(evt.screenX,null);
    }
    
  }
  
  document.addEventListener('mouseup', mouseUp, true);
  document.addEventListener('mousemove', mouseMove, true);
}

ynWindowHandlers._onHorizontalResizeElementClick = function(event) {
  if (ynWindowHandlers._maximized) return;
  
  var initialHeight = window.outerHeight;
  var initialY = event.screenY;
  
  function mouseUp(evt) {
    document.removeEventListener('mouseup', mouseUp, true);
    document.removeEventListener('mousemove', mouseMove, true);
    evt.stopPropagation();
  }
  
  function mouseMove(evt) {
    var height = initialHeight+(evt.screenY-initialY);
    //dump("h-resize : "+window.outerWidth+"x"+height+"\n");
    ynWindowHandlers.resize(null, height);
  }
  
  document.addEventListener('mouseup', mouseUp, true);
  document.addEventListener('mousemove', mouseMove, true);
}

ynWindowHandlers.restore = function () {
  try {
    ynWindowHandlers.restoreWidth();
    window.setTimeout(function () {
      ynWindowHandlers.restoreWidth();
    },100);
    
    var win = document.getElementById("yoono-window");
    var mode = win.getAttribute("mode");
    var tab = win.getAttribute("tab");
    if (!mode || mode=="simple") {
      ynWindowHandlers.collapse();
    } else {
      ynWindowHandlers.expand(tab);
    }
  } catch(e) {
    Components.utils.reportError(e);
  }
}

window.addEventListener("load",function () {
  window.removeEventListener("load",arguments.callee,true);
  var win = document.getElementById("yoono-window");
  
  if (win.getAttribute("screenX")=="2" && win.getAttribute("screenY")=="2") {
    var sc = screenManager.screenForRect(window.screenX, window.screenY, 1, 1);
    var left={}, top={}, width={}, height={};
    sc.GetAvailRect(left, top, width, height);
    ynWindowHandlers.move(left.value, top.value);
    win.setAttribute("screenX",window.screenX);
    win.setAttribute("screenY",window.screenY);
  }
  
  // Set default size
  var win = document.getElementById("yoono-window");
  var h = parseInt(win.getAttribute("height"));
  if (!h || h<=300) {
    var h = Math.floor(window.screen.availHeight*3/4);
    if (h<600)
      h=window.screen.availHeight-10;
    ynWindowHandlers.resize(250, h);
    win.setAttribute("height",h);
    window.setTimeout(function () {
      ynWindowHandlers.resize(250, h);
    },100);
  }
  
  ynWindowHandlers.addWindowDragElement(document.getElementById("flying-logo"));
  
  ynWindowHandlers.addWindowDragElement(document.getElementById("move-handler"));
  
  var leftResizeHandler = document.getElementById("left-resizer");
  leftResizeHandler.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onVerticalResizeElementClick(event,"left")
  },false);
  
  var rightResizeHandler = document.getElementById("right-resizer");
  rightResizeHandler.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onVerticalResizeElementClick(event,"right")
  },false);
  
  var bottomResizeHandler = document.getElementById("bottom-resizer");
  bottomResizeHandler.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onHorizontalResizeElementClick(event)
  },false);
  
  var cornerResizeHandlerBottom = document.getElementById("bottom-right-bottom-resizer");
  cornerResizeHandlerBottom.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onHorizontalResizeElementClick(event);
    ynWindowHandlers._onVerticalResizeElementClick(event,"right");
  },false);
  
  var cornerResizeHandlerRight = document.getElementById("bottom-right-right-resizer");
  cornerResizeHandlerRight.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onHorizontalResizeElementClick(event);
    ynWindowHandlers._onVerticalResizeElementClick(event,"right");
  },false);
  
  var cornerResizeHandlerRight = document.getElementById("middle-resizer");
  cornerResizeHandlerRight.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onVerticalResizeElementClick(event,"middle");
  },false);
  
  ynWindowHandlers.restore();
  
},true);

window.addEventListener("unload",function () {
  
}, false);
