







var CONTEXT_PATH = '';
var CONFIG_MODE = 'Configure';
var PERSONAL_MODE_HELP = 'You are editing your personal layout. Move or re-size your portlets by dragging and dropping.';
var ADMIN_MODE_HELP = 'You are editing the default layout. Changes you make here will be seen by all users.';
var ADD_PORTLET = 'Add Portlet';
var SET_HOMEPAGE = 'Set As Homepage';
var EDITING_PORTLET = 'Editing Portlet';
var DISPLAY_PROPERTIES = 'Portlet Display Properties';
var DELETE_CONFIRM = 'Are you sure you wish to delete this portlet?';
var EDIT_FORM_INTRO = 'Use the form below to edit the selected portlet';
var EDIT_FORM_CONTENT = 'Portlet Content';
var EDIT_FORM_BORDER = 'Portlet border';
var EDIT_FORM_SHOW_TITLEBAR = 'Show portlet title bar';
var EDIT_FORM_SHOW_CONTROLS = 'Show portlet controls';
var EDIT_FORM_ALLOW_MOVE = 'Allow moving/resizing';
var EDIT_FORM_ALLOW_SCROLL = 'Show scroll bar';
var EDIT_FORM_TITLE = 'Portlet title';
var EDIT_FORM_TITLE_IMAGE = 'Portlet title (image)';
var EDIT_FORM_TITLE_BGIMAGE = 'Portlet header background image';
var EDIT_FORM_TITLE_BGCOLOUR = 'Portlet header background color';
var EDIT_FORM_BGCOLOUR = 'Portlet background color';
var EDIT_FORM_SAVE = 'Save';
var EDIT_FORM_CANCEL = 'Cancel';
var EDIT_ADDFORM_INTRO = 'Select the type of portlet to add to the page';
var EDIT_ADDFORM_ADD = 'Add';
var SAVING = 'Saving';
var DEFAULT_LAYOUT = 'Requesting default layout from the server';
var PERSONAL_LAYOUT = 'Requesting your personal layout from the server';
var ADDING = 'Adding portlet';
var DELETING = 'Deleting portlet';
var LOADING = 'Loading portlet display properties';
var SETTING_AS_HOMEPAGE = 'Setting as community homepage';
var SAVEFAIL_POS = 'Failed to save position/dimensions for portlet';
var SAVED_DEFAULT_POS = 'Saved portlet layout and removed any customised layouts';
var SAVED_POS = 'Saved portlet layout';
var SAVEFAIL_ADD = 'Failed to add portlet';
var SAVED_ADD = 'Added new portlet';
var SAVEFAIL_DELETE = 'Failed to delete';
var SAVED_DELETE = 'Deleted portlet';
var FAIL_LAYOUT_DEFAULT = 'Failed to load master layout';
var FAIL_LAYOUT_PERSONAL = 'Failed to load your personal layout';
var SAVEFAIL_CONFIG = 'Failed to update portlet';
var SAVED_CONFIG = 'Saved portlet properties';
var SAVEFAIL_HOMEPAGE = 'Failed to set as community homepage';
var SAVED_HOMEPAGE = 'This page is now the community homepage';
var NO_PORTLETS_MESSAGE = 'This is an empty portlet page. To add portlets, configure the default layout';


var PAGE_ID = 0;
var DEFAULT_GRID_WIDTH = "780";
var CONTAINER_WIDTH_FACTOR = 1;
var FIT_TO_PAGE = true;

addOnLoad(function()
{
  portletsWindowResize();
  window.onresize = portletsWindowResize;
  showAllPortlets();
});



var AJAX_UPDATE_POS     = "update.pos";
var AJAX_RESET_LAYOUT   = "reset.layout";


var SNAPPING_GAP = 13;

var SNAPPING_MARGIN = 6;
var SNAPPING_MARGIN_X = 6;
var MIN_PORTLET_WIDTH  = 100;
var MIN_PORTLET_HEIGHT = 18;


var RESIZE_BORDER = 5;


var TOP          = 2;
var RIGHT        = 4;
var BOTTOM_RIGHT = 5;
var BOTTOM       = 6;
var LEFT         = 8;

var resize_mode = 0;


var PAGE_MODE_OFF    = 'Off';
var PAGE_MODE_CONFIG = 'On';
var PAGE_MODE_ADMIN  = 'Default';

var pageMode = PAGE_MODE_OFF;


var ajax = new sack();
var editing_portlet = null;

var portlet_names = new Array();
var portlet_displayNames = new Array();
var portlet_configurable = new Object();

var containerBoundaryLeft   = 0;
var containerBoundaryTop    = 0;
var containerBoundaryRight  = 5;
var containerBoundaryBottom = 5;
var containerBoundaryWidth  = 0;

var tracking_portlet = null;
var tracking = false;
var moving_portlet = true;


var portlets = new Array();


var gridLinesX;
var gridLinesY;

var toolbar = null;
var infoBar = null;
var modeButtons = null;

function toggleConfigure(newMode)
{
  
  if (pageMode == newMode)
    return;

  if (newMode == PAGE_MODE_CONFIG || newMode == PAGE_MODE_ADMIN)
  {
    if (document.getElementById("outer") == null)
    {
      var outerDivEl = document.createElement("div");
      outerDivEl.id = "outer";
      document.getElementById("barcontainer").appendChild(outerDivEl);
      var barOuterwrap = document.createElement("div");
      barOuterwrap.id = "barOuterwrap";
      outerDivEl.appendChild(barOuterwrap);
      var infocontent = document.createElement("div");
      infocontent.id = "infocontent";
      infocontent.style.marginLeft = "0px";
      infocontent.style.marginRight = "0px";
      barOuterwrap.appendChild(infocontent);
      var rightbar = document.createElement("div");
      rightbar.id = "right";
      outerDivEl.appendChild(rightbar);
    }

    document.getElementById("outer").className = "barOuter";
    document.getElementById("barOuterwrap").className = "outerwrap";
    document.getElementById("infocontent").className = "infocontent";
    document.getElementById("right").className = "rightBar";

    if (infoBar == null)
      infoBar = new InfoBar(document.getElementById("infocontent"), true);
    if (toolbar == null)
      toolbar = new Toolbar(document.getElementById("right"), "right");
    infoBar.showBar();

    var rightBox = document.getElementById("right");
    if (newMode == PAGE_MODE_CONFIG)
    {
      if (pageMode == PAGE_MODE_ADMIN)
      {
        hideTitleEditIcons();
        postAjax(AJAX_ADMIN_OFF);
        unregisterConfigHandlers();
      }
      else
      {
        registerConfigHandlers();
      }

      setPageMode(PAGE_MODE_CONFIG);
      toolbar.hideToolbar();

      rightBox.style.width = "0px";                 
      rightBox.style.marginRight = "0px";
      rightBox.style.visibility = "hidden";
      document.getElementById("outer").style.marginRight = "0px";
      infoBar.setDefaultMessage(PERSONAL_MODE_HELP);
    }
    else      
    {
      rightBox.style.width = "190px";
      rightBox.style.marginRight = "-189px";
      rightBox.style.visibility = "visible";
      document.getElementById("outer").style.marginRight = "190px";
      toolbar.showToolbar();
      toolbar.removeAllButtons();
      if (toolbar.buttonCount() == 0)
      {
        var button1 = toolbar.addButton(ADD_PORTLET);
        toolbar.setAction(button1, addPortletClick);
        var button2 = toolbar.addButton(SET_HOMEPAGE);
        toolbar.setAction(button2, setAsHomepageClick);
      }

      unregisterConfigHandlers();
      postAjax(AJAX_ADMIN);
    }
    
    calculateContainerOffsets();

    if (containerBoundaryWidth == 0)
      containerBoundaryWidth = document.body.offsetWidth - containerBoundaryLeft - 25;

    if (SNAPPING_MARGIN_X != -1)
      SNAPPING_MARGIN_X = Math.round(SNAPPING_MARGIN * CONTAINER_WIDTH_FACTOR);
    else
      SNAPPING_MARGIN_X = SNAPPING_MARGIN;

    getAllGridLines();

    
  }

  else if (newMode == PAGE_MODE_OFF)
  {
    if (pageMode == PAGE_MODE_ADMIN)
    {
      hideTitleEditIcons();
      postAjax(AJAX_ADMIN_OFF);
    }
    infoBar.hideBar();
    toolbar.hideToolbar();

    unregisterConfigHandlers();

    infoBar = null;
    toolbar = null;
    document.getElementById("barcontainer").removeChild(document.getElementById("outer"));

    
    setPageMode(PAGE_MODE_OFF);
  }
}

function setPageMode(newMode)
{
  pageMode = newMode;
  modeButtons.set(pageMode);
}


function ModeButtons(el, isAdmin)
{
  this.isAdmin = isAdmin;

  var modeButtonsDiv = document.createElement("div");
  modeButtonsDiv.className = "confButtonsContainer";
  el.appendChild(modeButtonsDiv);

  var modeButtonsP = document.createElement("p");
  modeButtonsP.className = "confButtons";
  modeButtonsDiv.appendChild(modeButtonsP);

  this.extraMsg = document.createElement("span");
  modeButtonsP.appendChild(this.extraMsg);

  var configSpan = document.createElement("span");
  configSpan.innerHTML = CONFIG_MODE + ":";
  modeButtonsP.appendChild(configSpan);
  configSpan.className = "confButton2";

  var pageModeConfig = document.createElement("span");
  pageModeConfig.id = "pageModeConfig";
  pageModeConfig.innerHTML = PAGE_MODE_CONFIG;
  modeButtonsP.appendChild(pageModeConfig);
  pageModeConfig.className = "confButton";

  if (isAdmin)
  {
    var pageModeAdmin = document.createElement("span");
    pageModeAdmin.id = "pageModeAdmin";
    pageModeAdmin.innerHTML = PAGE_MODE_ADMIN;
    modeButtonsP.appendChild(pageModeAdmin);
    pageModeAdmin.className = "confButton";
  }

  var pageModeOff = document.createElement("span");
  pageModeOff.id = "pageModeOff";
  pageModeOff.innerHTML = PAGE_MODE_OFF;
  modeButtonsP.appendChild(pageModeOff);
  pageModeOff.className = "confButton2";

  this.set(PAGE_MODE_OFF);
}

ModeButtons.prototype.set = function(mode)
{
  var config = document.getElementById("pageModeConfig");
  var admin = document.getElementById("pageModeAdmin");
  var off = document.getElementById("pageModeOff");

  switch (mode)
  {
    case PAGE_MODE_CONFIG:
      config.innerHTML = "<strong>" + PAGE_MODE_CONFIG + "</strong>";
      this.extraMsg.innerHTML =  "(<a href='javascript:postAjax(\"" + AJAX_RESET_LAYOUT + "\")'>Reset layout</a>)&nbsp;&nbsp; ";
      if (this.isAdmin)
        admin.innerHTML = "<a href='#a' onclick='toggleConfigure(PAGE_MODE_ADMIN)'>" + PAGE_MODE_ADMIN + "</a>";
      off.innerHTML = "<a href='#a' onclick='toggleConfigure(PAGE_MODE_OFF)'>" + PAGE_MODE_OFF + "</a>";
      break;
    case PAGE_MODE_ADMIN:
      config.innerHTML = "<a href='#' onclick='toggleConfigure(PAGE_MODE_CONFIG)'>" + PAGE_MODE_CONFIG + "</a>";
      this.extraMsg.innerHTML = "";
      if (this.isAdmin)
        admin.innerHTML = "<strong>" + PAGE_MODE_ADMIN + "</strong>";
      off.innerHTML = "<a href='#' onclick='toggleConfigure(PAGE_MODE_OFF)'>" + PAGE_MODE_OFF + "</a>";
      break;
    case PAGE_MODE_OFF:
      config.innerHTML = "<a href='#' onclick='toggleConfigure(PAGE_MODE_CONFIG)'>" + PAGE_MODE_CONFIG + "</a>";
      this.extraMsg.innerHTML = "";
      if (this.isAdmin)
        admin.innerHTML = "<a href='#' onclick='toggleConfigure(PAGE_MODE_ADMIN)'>" + PAGE_MODE_ADMIN + "</a>";
      off.innerHTML = "<strong>" + PAGE_MODE_OFF + "</strong>";
      break;
  }
}


function InfoBar(el, isInAdminMode)
{
  this.isInAdminMode = isInAdminMode;
  this.pageTopDiv = el;

  this.infoBarDiv = document.createElement("div");
  this.infoBarDiv.className = "info";
  this.infoBarDiv.style.margin = "0px";
  this.infoBarDiv.style.padding = "0px";
  this.infoMessage = document.createElement("p");
  this.infoMessage.style.margin = "0px";
  this.infoMessage.style.padding = "5px";
  this.infoBarDiv.appendChild(this.infoMessage);
  this.defaultMessage = "";
  this.countdown = false;        
  this.countdownSecs = 6;        
}

InfoBar.prototype.showBar = function()
{
  document.getElementById("infocontent").style.height = "auto";
  if (this.infoBarDiv.parentNode == null || this.infoBarDiv.parentNode.id == null)    
    this.pageTopDiv.appendChild(this.infoBarDiv);
}

InfoBar.prototype.hideBar = function()
{
  this.pageTopDiv.removeChild(this.infoBarDiv);
  document.getElementById("infocontent").style.height = "0px";    
}

InfoBar.prototype.setMessage = function(message, timeout)
{
  this.infoMessage.innerHTML = message;
  this.infoBarDiv.className = "info";
  if (timeout)
  {
    this.countdown = true;
    this.countdownSecs = 5;
    setTimeout(function() {if (infoBar) infoBar.countdownCallback(5)}, 1000);
  }
  else
    this.countdown = false;
}

InfoBar.prototype.setDefaultMessage = function(message)
{
  this.setMessage(message);
  this.defaultMessage = message;
}

InfoBar.prototype.setErrorMessage = function(message)
{
  this.setMessage(message, false);
  this.infoBarDiv.className = "error";
}

InfoBar.prototype.setWaitMessage = function(message)
{
  this.setMessage(message, false);
  this.infoBarDiv.className = "wait";
}

InfoBar.prototype.setSuccessMessage = function(message)
{
  this.setMessage(message, true);
  this.infoBarDiv.className = "success";
}

InfoBar.prototype.countdownCallback = function(seconds)
{
 if (!this.countdown || this.countdownSecs != seconds)          
   return;

 if (--this.countdownSecs <= 0)
   this.clearMessage();
 else
 {
   setTimeout(function() {if (infoBar) infoBar.countdownCallback(--seconds)}, 1000);
 }
}

InfoBar.prototype.clearMessage = function()
{
  this.setMessage(this.defaultMessage, true);
}



function Toolbar(el, align)
{
  this.container = el;
  this.toolbarDiv = document.createElement("div");
  this.toolbarDiv.className = "folder-toolbar";
  this.toolbarDiv.style.margin = "0px";
  this.list = document.createElement("ul");
  this.toolbarDiv.appendChild(this.list);
  if (align == "left")
    this.list.className = "left-toolbar";
  else
    this.list.className = "right-toolbar";

  this.buttons = new Array();
}


Toolbar.prototype.addButton = function(displayName)
{
  var index = this.buttons.length;
  this.buttons[index] = document.createElement("li");
  var elA = document.createElement("a");
  elA.innerHTML = displayName;
  elA.href = "#";
  this.buttons[index].appendChild(elA);
  this.list.appendChild(this.buttons[index]);
  return index;
}

Toolbar.prototype.setAction = function(buttonNum, fn)
{
 this.buttons[buttonNum].childNodes[0].onmousedown = fn;
}

Toolbar.prototype.removeButton = function(num)
{
  this.list.removeChild(this.buttons[num]);        
  this.buttons[num] = null;
}

Toolbar.prototype.removeAllButtons = function()
{
  for (var i = 0; i < this.buttons.length; i++)
  {
    this.removeButton(i);
  }
  this.buttons = new Array();
}

Toolbar.prototype.buttonCount = function()
{
  return this.buttons.length;
}

Toolbar.prototype.showToolbar = function()
{
  if (this.container.childNodes.length == 0)
    this.container.appendChild(this.toolbarDiv);
}

Toolbar.prototype.hideToolbar = function()
{
  if (this.container.childNodes.length != 0)
   this.container.removeChild(this.toolbarDiv);
}



function Portlet(portletNum)
{
  
  portlets[portletNum] = this;

  var portletEl = $('portlet' + portletNum);
  var titleEl = $('portlet-title-' + portletNum);
  this.portletEl = portletEl;
  this.titleEl = titleEl;


  this.originalDims = {width : null, height : null};   
  this.originalPos  = {x : null, y : null};            

  this.mouseOffset  = {x : null, y : null};            
  this.mouseStart   = {x : null, y : null};

  this.position({x: 0, y: 0});
  this.portletName = "";                               
  this.portletBorder = true;
  this.portletTitleBar = true;
  this.portletMoveButtons = true;
  this.portletScroll = false;
  this.portletControls = false;
  this.portletTitle = "";
  this.portletHeaderImage = "";
  this.portletHeaderBackground = "";
  this.portletHeaderBackgroundColour = "";
  this.portletBackgroundColour = "";

  this.isConfigurable = true;
  this.originalControlsHTML = "";
  
}

Portlet.prototype.showPortlet = function(show)
{
  this.portletEl.style.display = (show) ? "block" : "none";
}


Portlet.prototype.position = function(pos, normalised)
{
  if (pos != null)
  {
    this.portletEl.style.position = "absolute";

    if (pos.x != null)                                  
      this.portletEl.style.left = ((normalised) ? Math.round(pos.x * CONTAINER_WIDTH_FACTOR) : pos.x) + "px";
    if (pos.y != null)
    {
      this.portletEl.style.top  = pos.y + "px";
      checkBottom(getIndex(this.portletEl.id));
    }
  }
  else
  {
    return {
      x : getPixels(this.portletEl.style.left),
      y : getPixels(this.portletEl.style.top),
      right : getPixels(this.portletEl.style.left) + this.dimensions().width,
      bottom : getPixels(this.portletEl.style.top) + this.dimensions().height
    };
  }
}


Portlet.prototype.dimensions = function(dims, normalised)
{
  if (dims != null)
  {
    if (dims.width != null && dims.width >= MIN_PORTLET_WIDTH)
      this.portletEl.style.width = ((normalised) ? dims.width * CONTAINER_WIDTH_FACTOR : dims.width) + "px";
    if (dims.height != null && dims.height >= MIN_PORTLET_HEIGHT)
    {
      this.portletEl.style.height = dims.height + "px";
      checkBottom(getIndex(this.portletEl.id));
    }
  }
  else
  {
    return {
      width: getPixels(this.portletEl.style.width),
      height: getPixels(this.portletEl.style.height)
    }
  }
}


Portlet.prototype.move = function(newPos)
{
  var newX, newY;
  if (newPos.x != null)
  {
    newX = newPos.x - this.mouseOffset.x;

    
    if (gridLinesX[newX] != null)
    {
      newX = gridLinesX[newX]
    }
    else if (gridLinesX[newX + this.dimensions().width] != null)
      newX = gridLinesX[newX + this.dimensions().width] - this.dimensions().width - SNAPPING_MARGIN_X;
  }
  if (newPos.y != null)
  {
    newY = newPos.y - this.mouseOffset.y;

    if (gridLinesY[newY] != null)
    {
      newY = gridLinesY[newY]
    }
    else if (gridLinesY[newY + this.dimensions().height] != null)
      newY = gridLinesY[newY + this.dimensions().height] - this.dimensions().height - SNAPPING_MARGIN;
  }
  if (newX != null && newX >= 0)
    if (this.originalPos.x + this.originalDims.width > containerBoundaryWidth || (!moving_portlet || (newX + this.dimensions().width <= containerBoundaryWidth)))
      this.position({x : newX});
  if (newY != null && newY >= 0)
    this.position({y : newY});
}


Portlet.prototype.transMove = function(newPos, normalised)
{
  var index = getIndex(this.portletEl.id);
  var moveEffect = new fx.Styles(this.portletEl, {duration: 400, onComplete: function() {checkBottom(index); finishedEffect();}});
  moveEffect.custom({
    'top': [this.portletEl.offsetTop, newPos.y],
    'left': [this.portletEl.offsetLeft, (normalised) ? Math.round(newPos.x * CONTAINER_WIDTH_FACTOR) : newPos.x]
  }
  );
}


Portlet.prototype.resize = function(mousePos)
{
  var widthDiff = mousePos.x - this.mouseStart.x;
  var heightDiff = mousePos.y - this.mouseStart.y;
  var newWidth, newHeight;
  if (resize_mode == LEFT)
  {
    newWidth = this.originalDims.width + this.mouseStart.x - mousePos.x;
  }
  else
  {
    newWidth = this.originalDims.width + mousePos.x - this.mouseStart.x;
  }
  if (resize_mode == TOP)
  {
    newHeight = this.originalDims.height + Math.abs(mousePos.y - this.mouseStart.y);
  }
  else
  {
    newHeight = this.originalDims.height + mousePos.y - this.mouseStart.y;
  }

  var newRight = this.position().x + newWidth;
  var newBottom = this.position().y + newHeight;

  if (resize_mode == RIGHT || resize_mode == BOTTOM_RIGHT || resize_mode == BOTTOM)
  {
  
    if (gridLinesX[newRight] != null)
      newWidth = gridLinesX[newRight] - this.position().x - SNAPPING_MARGIN_X;

    if (gridLinesY[newBottom] != null)
      newHeight = gridLinesY[newBottom] - this.position().y - SNAPPING_MARGIN;
  }
  if (Math.floor(newWidth / CONTAINER_WIDTH_FACTOR) > MIN_PORTLET_WIDTH && ((this.originalPos.x + this.originalDims.width > containerBoundaryWidth)
      || this.position().x + newWidth <= containerBoundaryWidth))
    this.dimensions({width: newWidth});
  if (newHeight > MIN_PORTLET_HEIGHT)
    this.dimensions({height: newHeight});
}


Portlet.prototype.transResize = function(newDims, saveAfter, normalised)
{
  var index = getIndex(this.portletEl.id);
  var heightEffect = new fx.Style(this.portletEl, 'height', {duration: 400});
  heightEffect.custom(this.dimensions().height, newDims.height);
  var widthEffect = new fx.Style(this.portletEl, 'width', {duration: 400, onComplete:
                                          (saveAfter) ? function(){postAjax(AJAX_UPDATE_POS, index);finishedEffect();}
                                                      : function() {checkBottom(index);finishedEffect();}});
  widthEffect.custom(this.dimensions().width,(normalised) ? Math.round(newDims.width * CONTAINER_WIDTH_FACTOR) : newDims.width);
}


Portlet.prototype.revert = function()
{
  if ( tracking_portlet.position().x != tracking_portlet.originalPos.x
    || tracking_portlet.position().y != tracking_portlet.originalPos.y)
    this.transMove({x : this.originalPos.x, y : this.originalPos.y});
  if ( tracking_portlet.dimensions().width  != tracking_portlet.originalDims.width
    || tracking_portlet.dimensions().height != tracking_portlet.originalDims.height)
    this.transResize({width : this.originalDims.width, height : this.originalDims.height});
}


Portlet.prototype.isChanged = function()
{
  return  (tracking_portlet.position().x != tracking_portlet.originalPos.x
    || tracking_portlet.position().y != tracking_portlet.originalPos.y
    || tracking_portlet.dimensions().width != tracking_portlet.originalDims.width
    || tracking_portlet.dimensions().height != tracking_portlet.originalDims.height)
}



function mouseDownPortlet(ev)
{
  var noOnClick = false;
  if (ev)
  {
    noOnClick = !ev.target.onclick;
  }
  else if (window.event)
  {
    noOnClick = !window.event.srcElement.onclick;
  }
  if (tracking_portlet == null && noOnClick)          
  {
    var mousePos = mouseCoords(ev);
    var portlet = portlets[getIndex(this.id)];
    if ((pageMode == PAGE_MODE_ADMIN) && (portlet.position().right - mousePos.x) <= 60 && (mousePos.y - portlet.position().y) <= 20)
      return;
    if (!(pageMode == PAGE_MODE_ADMIN) && !portlets[getIndex(this.id)].portletMoveButtons)
    {
      
      return;
    }

    tracking_portlet = portlet;
    tracking = true;
    
    tracking_portlet.portletEl.style.zIndex = 100;
    ;
    new fx.Style(this, 'opacity').set(0.5);
    tracking_portlet.mouseStart.x = mousePos.x;
    tracking_portlet.mouseStart.y = mousePos.y;
    tracking_portlet.mouseOffset.x = mousePos.x - tracking_portlet.position().x;
    tracking_portlet.mouseOffset.y = mousePos.y - tracking_portlet.position().y;

    tracking_portlet.originalPos.x = tracking_portlet.position().x;
    tracking_portlet.originalPos.y = tracking_portlet.position().y;

    tracking_portlet.originalDims.width = tracking_portlet.dimensions().width;
    tracking_portlet.originalDims.height = tracking_portlet.dimensions().height;

    
    document.onselectstart = new Function ("return false");   
    if (window.sidebar)        
    {
      document.onmousedown = new Function("return false");
      document.onclick = new Function("true");
    }
  }
}


function mouseUpPortlet()
{
  if (tracking_portlet != null)
  {
    
    tracking = false;

    if (!valid_move(tracking_portlet))
    {
      tracking_portlet.revert();
      
    }
    else
    {
      if (tracking_portlet != null && tracking_portlet.isChanged())
      {

        postAjax(AJAX_UPDATE_POS, getIndex(tracking_portlet.portletEl.id));
      }
      else
      {
        finishedEffect();
      }
      getAllGridLines();       
    }

    
    document.onselectstart = null;
    if (window.sidebar)
    {
      document.onmousedown = null;
      document.onclick = null;
    }
  }
}


function mouseOverPortlet(ev)
{
  if (!(pageMode == PAGE_MODE_ADMIN) && !portlets[getIndex(this.id)].portletMoveButtons)
  {
    this.style.cursor = "not-allowed";
  }
  else if (tracking_portlet == null)
  {
    var portlet = portlets[getIndex(this.id)];
    var mousePos = mouseCoords(ev);
    if ((pageMode == PAGE_MODE_ADMIN) && (portlet.position().right - mousePos.x) <= 60 && (mousePos.y - portlet.position().y) <= 20)
    {
      this.style.cursor = "default";
      return;
    }
    if ((portlet.position().right - mousePos.x) <= RESIZE_BORDER && (portlet.position().bottom - mousePos.y) <= RESIZE_BORDER)
    {
      moving_portlet = false;
      this.style.cursor = "nw-resize";
      resize_mode = BOTTOM_RIGHT;
    }
    else if ((mousePos.x - portlet.position().x) <= RESIZE_BORDER)
    {
      moving_portlet = false;
      this.style.cursor = "w-resize";
      resize_mode = LEFT;
    }
    else if ((portlet.position().bottom - mousePos.y) <= RESIZE_BORDER)
    {
      moving_portlet = false;
      this.style.cursor = "n-resize";
      resize_mode = BOTTOM;
    }
    else if ((portlet.position().right - mousePos.x) <= RESIZE_BORDER)
    {
      moving_portlet = false;
      this.style.cursor = "w-resize";
      resize_mode = RIGHT;
    }
    else if ((mousePos.y - portlet.position().y) <= RESIZE_BORDER)
    {
      moving_portlet = false;
      this.style.cursor = "n-resize";
      resize_mode = TOP;
    }
    else
    {
      moving_portlet = true;
      this.style.cursor = "move";
    }
  }
}


function mouseMove(ev)
{
  if (tracking)
  {
    ev = ev || window.event;
    var mousePos = mouseCoords(ev);

    if (tracking_portlet)
    {
      var newX = mousePos.x;
      var newY = mousePos.y;

      if (moving_portlet)
      {
        tracking_portlet.move({x : newX, y : newY});
      }
      else      
      {
        if (resize_mode == BOTTOM_RIGHT)
          tracking_portlet.resize({x : newX, y : newY});
        else if (resize_mode == RIGHT)
          tracking_portlet.resize({x : newX});
        else if (resize_mode == BOTTOM)
          tracking_portlet.resize({y : newY});
        else if (resize_mode == LEFT)
        {
          if (newX < tracking_portlet.originalPos.x + tracking_portlet.originalDims.width - SNAPPING_GAP - MIN_PORTLET_WIDTH)
          {
            tracking_portlet.move({x : newX});

            var xDiff = (tracking_portlet.originalPos.x + tracking_portlet.originalDims.width) - tracking_portlet.position().right;
            tracking_portlet.dimensions({width: tracking_portlet.dimensions().width + xDiff});
          }
        }
        else if (resize_mode == TOP)
        {
          if (newY < tracking_portlet.originalPos.y + tracking_portlet.originalDims.height - SNAPPING_GAP)
          {
            tracking_portlet.move({y : newY});
            var yDiff = (tracking_portlet.originalPos.y + tracking_portlet.originalDims.height) - tracking_portlet.position().bottom;
            tracking_portlet.dimensions({height : tracking_portlet.dimensions().height + yDiff});
          }
        }
      }

      
      var mouseWindowCoord = mousePos.y + document.getElementById("portletsContainer").offsetTop - getScrollXY()[1];
      if (mouseWindowCoord >= getWindowSize()[1] - 60)
      {
        scrollTo(0, getScrollXY()[1] + 20);
      }
      else if (mouseWindowCoord <= 50)
        scrollTo(0, getScrollXY()[1] - 20);

      
      calculateContainerOffsets();
    }
  }
}

function dblClickPortlet(ev)
{
  if (pageMode != PAGE_MODE_CONFIG) return;
  var portlet = portlets[getIndex(this.id)];
  if (portlet.portletMoveButtons && portlet.portletTitleBar)
  {
    if (portlet.dimensions().height != MIN_PORTLET_HEIGHT)
      portlet.transResize({width: portlet.dimensions().width, height: MIN_PORTLET_HEIGHT}, true);
  }
}



function portletsWindowResize()
{
  if (FIT_TO_PAGE)
  {
    var oldWidthFactor = CONTAINER_WIDTH_FACTOR;
    var newWidth = document.getElementById("portletsContainer").offsetWidth;
    if (newWidth > getPageSize().x)
      newWidth -= (getPageSize().x - newWidth);
    CONTAINER_WIDTH_FACTOR = Math.round((((newWidth)) / DEFAULT_GRID_WIDTH)* 1000)/1000;
    if (document.getElementById("portletsContainer").offsetWidth == 0 || CONTAINER_WIDTH_FACTOR == 0
        || CONTAINER_WIDTH_FACTOR == oldWidthFactor)
      return;

    for (var i = 0; i < portlets.length; i++)
    {
      if ((portlets[i] != null) && (typeof portlets[i] == "object") && (portlets[i].constructor == Portlet))
      {
        var originalRight = portlets[i].position().x + portlets[i].dimensions().width;
        var normalisedRight = originalRight / oldWidthFactor;
        portlets[i].position({x : ((portlets[i].position().x / oldWidthFactor) * CONTAINER_WIDTH_FACTOR), y : portlets[i].position().y}, false);
        var width = (normalisedRight * CONTAINER_WIDTH_FACTOR) - portlets[i].position().x;
        portlets[i].dimensions({width : width, height : portlets[i].dimensions().height}, false);
      }
    }
    calculateContainerOffsets();
    getAllGridLines();
    try
    {
      if (resizeHeaderBar) resizeHeaderBar();      // This is from the global skin js
    }
    catch (err) {}
  }
}




function valid_move(portlet)
{
  if (portlet.position().y < 0 || portlet.position().x < 0)
    return false;
  if (portlet.originalPos.x + portlet.originalDims.width <= containerBoundaryWidth && portlet.position().right > containerBoundaryWidth)
    return false;
  if (isOverlappingAny(portlet))
    return false;

  return true;
}

function isOverlappingAny(portlet)
{
  for (var i = 0; i < portlets.length; i++)
  {
    if ((portlets[i] != null) && (typeof portlets[i] == "object") && (portlets[i].constructor == Portlet))
    {
      if (isOverlapping(portlet, portlets[i]))
        return true;
    }
  }
  return false;
}


function isOverlapping(portlet1, portlet2)
{
  if (portlet1 === portlet2)
    return false;
  var portlet1Left = portlet1.position().x;
  var portlet1Right = (portlet1.position().x + portlet1.dimensions().width);
  var portlet1Top = portlet1.position().y;
  var portlet1Bottom = (portlet1.position().y + portlet1.dimensions().height);

  var portlet2Left = portlet2.position().x;
  var portlet2Right = (portlet2.position().x + portlet2.dimensions().width);
  var portlet2Top = portlet2.position().y;
  var portlet2Bottom = (portlet2.position().y + portlet2.dimensions().height);


  if (portlet1Left >= portlet2Right)     
    return false;
  if (portlet1Right <= portlet2Left)     
    return false;
  if (portlet1Top >= portlet2Bottom)     
    return false;
  if (portlet1Bottom <= portlet2Top)     
    return false;

  return true;
}


function getAllGridLines()
{
  gridLinesX = new Array();
  gridLinesY = new Array();

  for (var i = 0; i < portlets.length; i++)
  {
    if (portlets[i] != null)
    {
      var left = portlets[i].position().x;
      var right = portlets[i].position().right + SNAPPING_MARGIN_X;
      var top = portlets[i].position().y;
      var bottom = portlets[i].position().bottom + SNAPPING_MARGIN;

      if (gridLinesX[left] == null)
        for (var j = left - SNAPPING_GAP; j < left + SNAPPING_GAP; j++)
          gridLinesX[j] = left;
      if (gridLinesX[right] == null)
        for (var j = right - SNAPPING_GAP; j < right + SNAPPING_GAP; j++)
         gridLinesX[j] = right;
      if (gridLinesY[top] == null)
        for (var j = top - SNAPPING_GAP; j < top + SNAPPING_GAP; j++)
          gridLinesY[j] = top;
      if (gridLinesY[bottom] == null)
        for (var j = bottom - SNAPPING_GAP; j < bottom + SNAPPING_GAP; j++)
          gridLinesY[j] = bottom;
    }
  }
  
  for (var j = 0; j < SNAPPING_GAP; j++)
  {
    gridLinesX[j] = 0;
    gridLinesY[j] = 0;
  }
//  for (j = containerBoundaryRight - SNAPPING_GAP; j <= containerBoundaryRight; j++)
//  {
//    gridLinesX[j] = containerBoundaryRight;
//  }

}

function getPortletSimpleName(portletName)
{
  var split = portletName.split('_');
  return split[1].substring(split[0]);
}
function finishedEffect()
{
  if (tracking_portlet != null)
  {
    tracking_portlet.portletEl.style.zIndex = 0;
    var index = getIndex(tracking_portlet.portletEl.id);
    var fadeEffect = new fx.Style(tracking_portlet.portletEl, 'opacity', {duration: 200, onComplete: function()
    {
      if (pageMode == PAGE_MODE_ADMIN) showIcons(index);
    }});
    fadeEffect.custom(0.5, 1);
    tracking_portlet = null;
  }
  getAllGridLines();
}


function resizeAll(factor)
{
  for (var i = 0; i < portlets.length; i++)
  {
    if (portlets[i] != null)
    {
      if (portlets[i].position().x != 0)
        portlets[i].position({x: (portlets[i].position().x) * factor});
      portlets[i].dimensions({width: (portlets[i].dimensions().width) * factor});
    }
  }
}

function showAllPortlets()
{
  for (var i = 0; i < portlets.length; i++)
  {
    if (portlets[i] != null)
    {
      portlets[i].showPortlet(true);
    }
  }
}





function postAjax(op, portletId)
{
  ajax.URLString = "";
  ajax.method = 'POST';
  ajax.setVar('portletPageId', PAGE_ID);
  ajax.requestFile = CONTEXT_PATH + '/portletmanager/index.jsp';
  ajax.setVar('admin', (pageMode == PAGE_MODE_ADMIN) ? "on" : "off");
  switch (op)
  {

  case AJAX_UPDATE_POS:
    infoBar.setWaitMessage(SAVING + "...");
    
    ajax.setVar('mode', AJAX_UPDATE_POS);
    if (portletId == null) { return;}
    ajax.setVar('portletId', portletId);
    ajax.setVar('widthFactor', CONTAINER_WIDTH_FACTOR);

    ajax.setVar('x', portlets[portletId].position().x);
    ajax.setVar('y', portlets[portletId].position().y);
    ajax.setVar('width', portlets[portletId].dimensions().width);
    ajax.setVar('right', portlets[portletId].position().right);
//    alert(portlets[portletId].position().right)
    ajax.setVar('height', portlets[portletId].dimensions().height);

    ajax.onCompletion = savePositionComplete;
    break;
  case AJAX_RESET_LAYOUT:
    infoBar.setWaitMessage('Resetting layout to default' + "...");
    ajax.setVar('mode', AJAX_RESET_LAYOUT);
    ajax.onCompletion = resetLayoutComplete;
    break;


  default:
    
    break;
  }
  ajax.runAJAX();
}


function savePositionComplete() {
  var response = ajax.response;
  

  if (response.match(/^(false|$)/))
  {
    
    infoBar.setErrorMessage(SAVEFAIL_POS);
    tracking_portlet.revert();
  }
  else
  {
    finishedEffect();
    if (pageMode == PAGE_MODE_ADMIN)
      infoBar.setSuccessMessage(SAVED_DEFAULT_POS);
    else
      infoBar.setSuccessMessage(SAVED_POS);
  }
}

function resetLayoutComplete()
{
  var response = ajax.response;
  

  if (response.match(/^(false|$)/))
  {
    
    infoBar.setErrorMessage('Failed to reset your personal layout to the default');
    return;
  }
  switchPortletPositions(response);
  infoBar.setSuccessMessage('Restored layout to default');
}




function switchPortletPositions(positions)
{
  if (portlets.length == 0) return;
  var values = positions.split(/\//);

  var i = 0;
  while (i < values.length)
  {
    var posData = values[i++].split(/, /);
    if (posData != "" && portlets[posData[0]] != null)
    {
      portlets[posData[0]].transMove({x : posData[1], y : posData[2]}, true);
      var portletWidth = Math.round(posData[3] * CONTAINER_WIDTH_FACTOR) - Math.round(posData[1] * CONTAINER_WIDTH_FACTOR);
      portlets[posData[0]].transResize({width : portletWidth, height : posData[4]}, false, false);
    }
  }

  getAllGridLines();
  if (pageMode != PAGE_MODE_OFF)
    registerConfigHandlers();
}




function setInfoMsg(msg) {document.getElementById("infoArea").innerHTML = "<strong>" + msg + "</strong>";}
function clearInfoMsg() {document.getElementById("infoArea").innerHTML = "&nbsp;";}

function registerConfigHandlers()
{
  document.onmousemove = mouseMove;
  for (var i = 0; i < portlets.length; i++)
  {
    if (portlets[i] != null)
    {
      portlets[i].portletEl.onmousedown = mouseDownPortlet;
      document.onmouseup = mouseUpPortlet;
      portlets[i].portletEl.onmousemove = mouseOverPortlet;
      portlets[i].portletEl.ondblclick = dblClickPortlet;

      portlets[i].portletEl.style.borderWidth = "1px";
      portlets[i].portletEl.style.borderStyle = "solid";
    }
  }
}

function unregisterConfigHandlers()
{
  document.onmousemove = null;
  for (var i = 0; i < portlets.length; i++)
  {
    if (portlets[i] != null)
    {
      portlets[i].portletEl.onmousedown = null;
      document.onmouseup = null;
      portlets[i].portletEl.onmousemove = null;
      portlets[i].portletEl.style.cursor = "auto";
      portlets[i].portletEl.ondblclick = null;

      if (!portlets[i].portletBorder)
      {
        portlets[i].portletEl.style.borderWidth = "0px";
      }
    }
  }
}


function getPixels(pixels)
{
  return parseInt(pixels.split("p")[0]);
}


function getIndex(id)
{
  var portletPattern = /portlet\d+/
  var titlePattern = /portlet-title-\d+/
  var editControlsPattern = /portlet-dd-controls-\d+/
  if (portletPattern.test(id))
  {
    return id.substr(7, id.length);
  }
  else if (titlePattern.test(id))
    return id.split("-")[2];
  else if (editControlsPattern.test(id))
  {
    return id.split("-")[3];
  } 
}

function mouseCoords(ev)
{
  if (!ev) ev = window.event;      

  if(ev.pageX || ev.pageY)
  {
    return {x:ev.pageX - containerBoundaryLeft, y:ev.pageY - containerBoundaryTop};
  }
  else if (document.documentElement.scrollLeft || document.documentElement.scrollTop)       
  {
    return {
		  x:ev.clientX + document.documentElement.scrollLeft - containerBoundaryLeft,
	  	y:ev.clientY + document.documentElement.scrollTop - containerBoundaryTop };
  }
  else if (document.body)                  
  {
    return {
      x:ev.clientX + document.body.scrollLeft - containerBoundaryLeft,
  		y:ev.clientY + document.body.scrollTop - containerBoundaryTop };
	}
}

function absMouseCoords(ev)
{
  if (!ev) ev = window.event;      

  if(ev.pageX || ev.pageY)
  {
    return {x:ev.pageX, y:ev.pageY};
  }
  else if (document.documentElement.scrollLeft || document.documentElement.scrollTop)       
  {
    return {
		  x:ev.clientX + document.documentElement.scrollLeft,
	  	y:ev.clientY + document.documentElement.scrollTop};
  }
  else if (document.body)                  
  {
    return {
      x:ev.clientX + document.body.scrollLeft,
  		y:ev.clientY + document.body.scrollTop};
	}
}

function getWindowSize()
//http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight];
}

function getPageSize()
{
  var x,y;
  var test1 = document.body.scrollHeight;
  var test2 = document.body.offsetHeight
  if (test1 > test2) // all but Explorer Mac
  {
    x = document.body.scrollWidth;
    y = document.body.scrollHeight;
  }
  else // Explorer Mac;
       //would also work in Explorer 6 Strict, Mozilla and Safari
  {
    x = document.body.offsetWidth;
    y = document.body.offsetHeight;
  }
  return {width: x, height: y};
}

function getScrollXY()
{
  var scrOfX = 0, scrOfY = 0;
  if (typeof(window.pageYOffset) == 'number') {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  }
  else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  }
  else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [scrOfX, scrOfY];
}

function findPosX(obj)
// http://www.quirksmode.org/js/findpos.html
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function checkBottom(index)
{
  if (document.getElementById("portletsContainer").offsetHeight < portlets[index].position().bottom - 5)
    document.getElementById("portletsContainer").style.height = (portlets[index].position().bottom + 5) + "px";
;}

function calculateContainerOffsets()
{
  containerBoundaryLeft   = findPosX(document.getElementById("portletsContainer"));
  containerBoundaryTop    = findPosY(document.getElementById("portletsContainer"));
  containerBoundaryWidth  = document.getElementById("portletsContainer").offsetWidth;
}



