/* 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._currentHeight = 0;
ynWindowHandlers._currentWidth = 0;
ynWindowHandlers._heightInitialOffset = 0;


ynWindowHandlers.expand = function (tab) {
  this.changeMode("expand", tab);
  var tabs = document.getElementById("tabs");

  document.getElementById("tab-browser").removeAttribute("selected");
  document.getElementById("tab-columns").removeAttribute("selected");
  document.getElementById("tab-socialzine").removeAttribute("selected");

  document.getElementById("tab-" + tab).setAttribute("selected", "true");

  switch(tab) {
    case "browser":
      tabs.setAttribute("selectedIndex", 0);
    break;
    case "socialzine" :
      tabs.setAttribute("selectedIndex", 2);
      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("socialzine-iframe");
          YServices.core.require("accountsManager",function () {
            YServices.accountsManager.initAccountsManager(
            { observe : function(topic, param) {
              switch (topic) {
              case YServices.accountsManager.STATUS_INIT_OK :
                ynWindowHandlers.initSocialzineDoc();
                break;
              }
            } } );
          });
          iframe.style.overflowX = "auto";
        }
        onYServicesReady();
      } catch(e) {
        Components.utils.reportError(e);
      }
    break;
    case "columns" :
      tabs.setAttribute("selectedIndex", 1);
      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);
      }
    break;
  }
  
  this.restoreWidth();
}

ynWindowHandlers.fixPosition = function () {
  window.moveTo(100,100);
}

ynWindowHandlers.initSocialzineDoc = function () {
  var iframe = document.getElementById("socialzine-iframe");
  var YServices = YOONO_CMPT.getYServices()

  var friends = YServices.yoodgetInstances.getRegisteredYoodgetWrapper("{friends@yoono.com}",-1);
  var w = iframe.contentWindow;
  if (w.wrappedJSObject)
    w = w.wrappedJSObject;
  friends.yoodget.initSocialzineDoc(w.document);
}

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("middle-resizer").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= "browser"
  
//  if(aButton) {
//    var className = aButton.className;
//    if('simple' == className) {
//      tab = 'columns';
//    }
//  }
  if (this._mode=="simple") {
    this.expand(tab);
  } else {
    this.collapse();
  }
  ynWindowHandlers.resize(ynWindowHandlers.restoreWidth());
}

ynWindowHandlers.urlTextEntered = function(aString) {
  var url = aString.trim();
  if((-1 != url.indexOf(' ')) || (-1 == url.indexOf('.'))) {
    url = "http://www.google.com/search?q=" + encodeURIComponent(url);
  }

  ynWindowHandlers.openPage(url);  
}

ynWindowHandlers.expandBrowser = function() {
  if (this._mode=="simple") {
    this.expand('browser');
    ynWindowHandlers.resize(ynWindowHandlers.restoreWidth());
  }
}

ynWindowHandlers.openPage = function (aUrl) {
  YOONO_YEXTIF.methods.openUrl([aUrl]);
}

ynWindowHandlers.cancelUrlInput = function (aInputElement) {
  var iframeWin = ynWebPanel._iframe.contentWindow;
  if (iframeWin.wrappedJSObject)
    iframeWin = iframeWin.wrappedJSObject;
  var previous = iframeWin.document.location.href;
  setTimeout(function() {
    aInputElement.value = previous;
  }, 200);
}

ynWindowHandlers.toggleMaximize = function () {
  if (ynWindowHandlers._maximized) {
    window.moveTo(ynWindowHandlers.beforeMaximizeX, ynWindowHandlers.beforeMaximizeY);
    window.resizeTo(ynWindowHandlers.beforeMaximizeWidth,ynWindowHandlers.beforeMaximizeHeight);
    ynWindowHandlers._maximized = false;
  } else {
    ynWindowHandlers.beforeMaximizeX = window.screenX;
    ynWindowHandlers.beforeMaximizeY = window.screenY;
    ynWindowHandlers.beforeMaximizeWidth = window.outerWidth;
    ynWindowHandlers.beforeMaximizeHeight = window.outerHeight;
    var origin = 0;
    if (navigator.platform.indexOf("Mac") != -1) {
      origin = 20;
    }
    window.moveTo(0,origin);
    window.resizeTo(screen.availWidth,screen.availHeight);
    ynWindowHandlers.expand(this._tab);
    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();
//  trayIcon.minimize();
  trayIcon.quit();
}

ynWindowHandlers.restoreWidth = function () {
  var win = document.getElementById("yoono-window");
  var width = parseInt(win.getAttribute(this._mode+"width"));
//  width = Math.min(width, 700);
  width = Math.max(width, 250);
  if(this._mode=="simple") {
    var iframe = document.getElementById("main-iframe");
    iframe.style.minWidth = (width-18)+"px";
    iframe.style.maxWidth = (width-18)+"px";
  }
  ynWindowHandlers._updateTabPosition();
  return(width);
}

// Disable effect on window dragging on Linux
// (conflict with windows manager)
// - "Sarah Connor" ?
// - "Next door".
ynWindowHandlers._enableEffect = navigator.platform.toLowerCase().indexOf("linux")==-1;
ynWindowHandlers._screenBorder = 0;
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(Math.max(0,x),Math.max(0,y));
    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(Math.max(0,x),Math.max(0,y));
  window.moveTo(x, y);
}

/**
 *
 * @param w optionnal new width
 * @param h optional new heigth
 */
ynWindowHandlers.resize = function (w, h) {
//  YOONO_LOG.backtrace("resize start " + [w, h, window.outerWidth, window.outerHeight]);
  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") {
    w = Math.min(w, 700);
  } 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 only the sidebar is displayed, we need to size its iframe
  if (this._mode=="simple") {
    iframe.style.minWidth = (w-18)+"px";
    iframe.style.maxWidth = (w-18)+"px";
  }
  ynWindowHandlers._updateTabPosition();

  window.resizeTo(w, h);

  var win = document.getElementById("yoono-window");
  win.setAttribute(this._mode+"width", w);

//  win.setAttribute("height", h );
//  win.setAttribute("width", w );
  ynWindowHandlers._currentHeight = h;
  ynWindowHandlers._currentWidth = w;
//  YOONO_LOG.backtrace("resize end " + [w, h, window.outerWidth, window.outerHeight]);
}

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(Math.max(0,left.value+ynWindowHandlers._screenBorder), Math.max(0,window.screenY));
  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(Math.max(0,left.value+width.value-window.outerWidth-ynWindowHandlers._screenBorder), Math.max(0,window.screenY));
  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);
  element.addEventListener("dblclick",function (event) {
    ynWindowHandlers.toggleMaximize();
  },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._onResizeMiddleElementClick  = function(event) {
  var iframe = document.getElementById("main-iframe");
  var win = iframe.contentWindow;
  if (win.wrappedJSObject)
    win = win.wrappedJSObject;
  var winYoono = document.getElementById("yoono-window");

  var 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;
    var proposedWidth = initialWidth+diffX;
    var width = win.ynSidebar.getResizeWidth(proposedWidth, direction);
    width = Math.max(width, 250);
    width = Math.min(width, 700);
    iframe.style.minWidth = width+"px";
    iframe.style.maxWidth = width+"px";
    ynWindowHandlers._updateTabPosition();
    winYoono.setAttribute("simplewidth", width + 18);
    
    // if user keeps going left, give up after a while, otherwise the inner document will disappear (sidebar.js resize handling)
    if(120 >= width) {
      mouseUp(evt);
    }
  }

  document.addEventListener('mouseup', mouseUp, true);
  document.addEventListener('mousemove', mouseMove, true);
}

ynWindowHandlers._updateTabPosition = function() {
  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="";
}

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);
    //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;
//  YOONO_LOG.error("RESIZE INIT HEIGHT: " + initialHeight)
  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);
    }
    ynWindowHandlers.restoreWidth();
//    ynWindowHandlers._updateTabPosition();

  } catch(e) {
    Components.utils.reportError(e);
  }
}

window.addEventListener("load",function (aEvent) {
  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("header-spacer"));  
  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 middleResizeHandler = document.getElementById("middle-resizer");
  middleResizeHandler.addEventListener("mousedown",function (event) {
    ynWindowHandlers._onResizeMiddleElementClick(event);
  },false);
  
  ynWindowHandlers.restore();
  // takes care of document initialization when switching between cover and mag
  var iframe = document.getElementById("socialzine-iframe");
  iframe.addEventListener("DOMContentLoaded", function() {
    ynWindowHandlers.initSocialzineDoc();
  }, true);
},true);

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