Limb.namespace('Limb.window');

Limb.require('Limb.events');
Limb.require('Limb.browser');
Limb.require('Limb.http');
Limb.require('Limb.md5');
Limb.require('Limb.Coordinates');
Limb.require('Limb.Window.Params');
Limb.require('Function.bind');

Limb.window = Class.create();

Limb.window.prototype = {
  initialize: function()
  {
    this.parentWindow = null;
    this.windowName = this._generateName();
    this.onLoadEvents = [];
    this.onUnloadEvents = [];

    if(arguments.length == 0)
      this.window = window;

    // arguments[0] instanceof Window does not work in IE
    if(typeof(arguments[0]) == 'object')
      this.window = win;

    if(arguments.length == 2 || arguments.length == 3)
      this.window = this._createWindow(arguments[0], arguments[1], arguments[2]);

    Limb.events.add_event(this.window, 'load', this.onOpen.bind(this), false);
    Limb.events.add_event(this.window, 'close', this.onClose.bind(this), false);
  },

  centreWindow: function(width, height)
  {
    var newWindowRect = this._getRectInParentCenter(width, height);
    this.setRect(newWindowRect);
  },

  _getRectInParentCenter: function(width, height)
  {
    var windowRect = this.parentWindow.getRect();

    var result = new Limb.Coordinates.Rect();
    result.createWithCenter(windowRect.getCenter(), width, height);

    return result;
  },

  _getDefaultParams: function()
  {
    var width = 150;
    var height = 100;

    var newWindowRect = this._getRectInParentCenter(width, height);

    var params = new Limb.Window.Params();
    params.addParameter('left', newWindowRect.getX());
    params.addParameter('top', newWindowRect.getY());
    params.addParameter('width', width);
    params.addParameter('height', height);

    params.addParameter('scrollbars', 'yes');
    params.addParameter('resizable', 'yes');
    params.addParameter('help', 'no');
    params.addParameter('status', 'yes');

    return params;
  },

  _generateName: function()
  {
    return Math.round(Math.random() * 1000) + '_generate';
  },

  _createWindow: function(href, windowName, createParams)
  {
    this.parentWindow = new Limb.window();

    if(windowName)
      this.windowName = windowName;

    if(!isset(createParams))
      createParams = this._getDefaultParams();

    var win = window.open(href, this.windowName, createParams.toString());
    return win;
  },

  getRect: function()
  {
    if(Limb.browser.is_ie)
      return new Limb.Coordinates.Rect(this.window.screenLeft,
                                       this.window.screenTop,
                                       this.window.document.body.clientWidth,
                                       this.window.document.body.clientHeight);
    else
      return new Limb.Coordinates.Rect(this.window.screenX + this.window.outerWidth - this.window.innerWidth,
                                       this.window.screenY + this.window.outerHeight - this.window.innerHeight,
                                       this.window.innerWidth,
                                       this.window.innerHeight);
  },

  setRect: function(rect)
  {
    if(!rect)
      return false;

    this.window.moveTo(rect.getX(), rect.getY());
    this.window.resizeTo(rect.getWidth(), rect.getHeight());

    return true;
  },

  close: function()
  {
    this.window.close();
  },

  getDocument: function()
  {
    return this.window.document;
  },

  setTitle: function(title)
  {
    var titleNode = this.window.document.getElementsByTagName('title')[0];
    titleNode.text = title;
  },

  onOpen: function()
  {
    Limb.window.register(this.windowName, this);
        
    if(!this.window.limbWindowWidth)
      this.window.limbWindowWidth = this.parentWindow.getRect().getWidth() * 0.85;

    if(!this.window.limbWindowHeight)
      this.window.limbWindowHeight = this.parentWindow.getRect().getHeight() * 0.9;

    this.centreWindow(this.window.limbWindowWidth, this.window.limbWindowHeight);    
    
    this.openHandler();
  },

  onClose: function()
  {
    Limb.window.remove(this.windowName);

    this.closeHandler();
  },

  openHandler: function() {},
  closeHandler: function() {}
}

Limb.window.register = function(windowName, win)
{
  if(!isset(Limb.window.createdWindows))
    Limb.window.createdWindows = [];

  Limb.window.createdWindows[windowName] = win;
}

Limb.window.remove = function(windowName)
{
  if(!isset(Limb.window.createdWindows)||
     !isset(Limb.window.createdWindows[windowName]))
    return;

  Limb.window.createdWindows[windowName] = null;
  delete Limb.window.createdWindows[windowName];
}

Limb.window.current = function()
{
 if(!isset(Limb.window.createdWindows))
    return null;

  for(var i in Limb.window.createdWindows)
    if(Limb.window.createdWindows[i].getWindowObject() == window)
      return Limb.window.createdWindows[i];

  return null;
}

Limb.window.get_close_popup_handler = function ()
{
  return window.opener.popups[window.name]['close_popup_handler'];
}

Limb.window.get_init_popup_handler = function ()
{
  return window.opener.popups[window.name]['init_popup_handler'];
}

Limb.window.optimize_window = function ()
{
  var w = window;
  var top_opener = window;

  var x_ratio = 0.85;
  var y_ratio = 0.85;
  var screen_x = (Limb.browser.is_gecko) ? top_opener.screenX : top_opener.screenLeft;

  while(typeof(top_opener.top.opener) != 'undefined' && top_opener.top.opener != null && screen_x >= 0)
  {
    screen_x = (Limb.browser.is_gecko) ? top_opener.screenX : top_opener.screenLeft;
    top_opener = top_opener.top.opener;
  }

  if (Limb.browser.is_ie)
  {
    openerWidth = top_opener.top.document.body.clientWidth;
    openerHeight = top_opener.top.document.body.clientHeight;
    openerLeft = top_opener.top.screenLeft;
    openerTop = top_opener.top.screenTop;
  }
  else if(Limb.browser.is_gecko || Limb.browser.is_opera)
  {
    openerWidth = top_opener.top.innerWidth;
    openerHeight = top_opener.top.innerHeight;
    openerLeft = top_opener.top.screenX + top_opener.top.outerWidth - top_opener.top.innerWidth;
    openerTop = top_opener.top.screenY + top_opener.top.outerHeight - top_opener.top.innerHeight;
  }
  else
  {
    openerWidth = top_opener.document.body.clientWidth;
    openerHeight = top_opener.document.body.clientHeight;
    openerLeft = top_opener.screenLeft;
    openerTop = top_opener.screenTop;
  }

  if(window.WINDOW_WIDTH)
    newWidth = window.WINDOW_WIDTH;
  else
    newWidth = openerWidth*x_ratio;

  if(window.WINDOW_HEIGHT)
    newHeight = window.WINDOW_HEIGHT;
  else
    newHeight = openerHeight*y_ratio;

  newLeft = openerLeft + (openerWidth - newWidth)/2;
  newTop = openerTop + (openerHeight - newHeight)/2;

  w.moveTo(newLeft, newTop);
  w.resizeTo(newWidth, newHeight);
}

Limb.window.get_popup_params = function ()
{
  var w = window;
  var top_opener = window;

  var screen_x = (Limb.browser.is_gecko) ? top_opener.screenX : top_opener.screenLeft;

  while(typeof(top_opener.top.opener) != 'undefined' && top_opener.top.opener != null && screen_x >= 0)
  {
    screen_x = (Limb.browser.is_gecko) ? top_opener.screenX : top_opener.screenLeft;
    top_opener = top_opener.top.opener;
  }

  if (Limb.browser.is_ie)
  {
    openerWidth = top_opener.top.document.body.clientWidth;
    openerHeight = top_opener.top.document.body.clientHeight;
    openerLeft = top_opener.top.screenLeft;
    openerTop = top_opener.top.screenTop;
  }
  else if(Limb.browser.is_gecko || Limb.browser.is_opera)
  {
    openerWidth = top_opener.top.innerWidth;
    openerHeight = top_opener.top.innerHeight;
    openerLeft = top_opener.top.screenX + top_opener.top.outerWidth - top_opener.top.innerWidth;
    openerTop = top_opener.top.screenY + top_opener.top.outerHeight - top_opener.top.innerHeight;
  }
  else
  {
    openerWidth = document.body.clientWidth;
    openerHeight = document.body.clientHeight;
    openerLeft = screenLeft;
    openerTop = screenTop;
  }

  var x_ratio = 0.85;
  var y_ratio = 0.85;

  newWidth = openerWidth * x_ratio;
  newHeight = openerHeight * y_ratio;

  newLeft = openerLeft + (openerWidth - newWidth)/2;
  newTop = openerTop + (openerHeight - newHeight)/2;

  var params = 'width=' + newWidth + ',height=' + newHeight + ',top=' + newTop + ',left=' + newLeft;
  params += ',scrollbars=yes,resizable=yes,help=no,status=yes';

  return params;
}

//makes popup window at href address
Limb.window.popup = function (href, window_name, window_params, dont_set_focus, on_close_handler, on_init_handler)
{
  href = Limb.http.add_url_query_item(href, 'popup', 1);

  if (typeof(window_name) == 'undefined' || window_name == null)
    window_name = '_generate';

  new_left = window.screen.width / 2 - 100;
  new_top = window.screen.height / 2 - 50;

  if (typeof(window_params) == 'undefined' || window_params == null)
    window_params = Limb.window.get_popup_params();

  if (window_name.toLowerCase() == '_generate')
    window_name = 'w' + Limb.md5.hex_md5(href) + 's';

  if (typeof(window.popups) != 'array')
    window.popups = new Array();

  if (typeof(window.popups[window_name]) != 'array')
    window.popups[window_name] = new Array();

  if (typeof(on_close_handler) != 'undefined')
    window.popups[window_name]['close_popup_handler'] = on_close_handler;

  if (typeof(on_init_handler) != 'undefined')
    window.popups[window_name]['init_popup_handler'] = on_init_handler;

  window.popups[window_name]['status'] = 'popped_up';

  w = window.open(LOADING_STATUS_PAGE, window_name, window_params);
  if (href != LOADING_STATUS_PAGE)
   w.location.href = href;

  if(!dont_set_focus)
    w.focus();

  return w;
}

Limb.window.process_popup = function ()
{
  href = window.location.href;

  if(window.opener)
  {
    if(Limb.http.get_query_item(href, 'reload_parent'))
      window.opener.location.reload();
    else if(window.opener.popups)
      window.opener.popups[window.name]['status'] = 'processed';
  }
}

Limb.window.open_page = function (message, href, window_name, window_params)
{
  if (typeof(window_name) == 'undefined' || window_name == null)
    window_name = '_generate';

  if (typeof(window_params) == 'undefined' || window_params == null)
    window_name = 'height=400,width=600,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes';

  if (confirm(message))
    Limb.window.popup(href, window_name, window_params)
}

Limb.post_load_hooks = [];

Limb.post_load_hooks.push(
function()
{
  if(Limb.http.get_query_item(location.href, 'popup'))
    Limb.window.process_popup();
});


