//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2000 by Mike Hall.
// See http://www.brainjar.com for terms of use.

// Modified by Xavier Lawrence, 2005 Copyright Jahia Solutions
//*****************************************************************************

//----------------------------------------------------------------------------
// Code to determine the browser and version.
//----------------------------------------------------------------------------

function Browser() {

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isNS    = false;  // Netscape
  this.isOpera = false;  
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    if (ua.indexOf("Opera") >= 0)
      this.isOpera = true;        // detecting Opera impersonating MSIE    
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Opera/";
  i = ua.indexOf(s);
  if (i < 0)                 // the '/' is missing when Opera tries to impersonate another
    i = ua.indexOf("Opera"); // browser but 'Opera' is still part of the user agent string

  if (i >= 0) {
    this.isOpera = true; // Note: If you want to detect Opera always check isOpera first, because
    this.isNS = true;    // isNS (or isIE if it tries to impersonate MSIE) will also be set to true!
                         // We did this for safety: Some scripts might not yet be aware of Opera and also
                         // have no suitable default in their case distinction; Opera is sufficiently
                         // NS compatible and such scripts should treat it as NS rather than "unknown" (or,
                         // when impersonating MSIE, as MSIE - except for MSIE-only features like iFrames).
                         // E.g. menuItemMouseover() had: if (browser.isIE) {...} if (browser.isNS) {...}
                         // with no else-branch for other browsers :-(that function seems to be obsolete but
                         // would crash with undefined variables if ever called). Of course, although
                         // maybe never called, we fixed that function but other scripts in other files might
                         // have (or develop) similar cross-browser defects (and with this precaution they'd
                         // at least stand a good chance to work with Opera)
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

//----------------------------------------------------------------------------
// Code for handling the menu bar and active button.
//----------------------------------------------------------------------------

var activeButton = null;

// AJAX variables
var req;

// Capture mouse clicks on the page so any active button can be
// deactivated.

if (browser.isIE)
  document.onmousedown = pageMousedown;
else
  document.addEventListener("mousedown", pageMousedown, true);

function pageMousedown(event) {

  var el;

  // If there is no active button, exit.

  if (activeButton == null)
    return;

  // Find the element that was clicked on.

  if (browser.isIE)
    el = window.event.srcElement;
  else
    el = (event.target.tagName ? event.target : event.target.parentNode);

  // If the active button was clicked on, exit.

  if (el == activeButton)
    return;

  // If the element is not part of a menu, reset and clear the active
  // button.

  if (getContainerWith(el, "DIV", "menu") == null) {
    resetButton(activeButton);
    activeButton = null;
  }
}

// Opens up the menu of the given id
function buttonClick (event, menuId) {
  var button = getObjectById ("button_" + menuId);
  var positioner;

  // Get the target button element.

  if (browser.isIE) { 
    event = window.event;
  }
  
  if (event && event.target)  // With w3c conforming browsers, positioner should be event.target, i.e. the
    positioner = event.target; // event originator; this is a child (usually an img) of event.currentTarget
  else                       // (in our case the link element that processes the event). Due to wordwrap,
    positioner = button;     // the link could extend over 2 lines and give us bad coordinates for placing
                             // the menu, so if we have a better positioner we use it
                             // (IE knows only event.srcElement but that seems ok anyway).

  // Blur focus from the link to remove that annoying outline.
  button.blur();

  // Associate the named menu to this button if not already done.
  // Additionally, initialize menu display.
  if (button.menu == null) {
	button.menu = getObjectById (menuId);
    if (button.menu.isInitialized == null) {
      menuInit(button.menu);
	}
  }

  // Reset the currently active button, if any.

  if (activeButton != null) {
    resetButton(activeButton);
  }

  // Activate this button, unless it was the currently active one.

  if (button != activeButton) {
    depressButton(button, positioner);
    activeButton = button;
  } else {
    activeButton = null;
  }
}

// Switches menu if the user's mouse goes on another menu
function buttonMouseover(event, menuId) {
  	var button;
// this functionality has been removed, as with AJAX menues 
// need to be initialized first
}

// This function handles the menu button appearance on pressing it
// and sets the menu element's size, positon style and visibility
// to make the menu associated with the pop up on screen.

function depressButton(button, positioner) {

  if (!positioner)       // if no better element for positioning is given
    positioner = button; // we position the menu relative to the button

  var x, y;

  // Update the button's style class to make it look like it's
  // depressed.

  button.className += " menuButtonActive";

  applyCommonlyWantedMenuStyles(button.menu); // enforce those styles that should be common to all menus
  
  // Position the associated drop down menu near the button
  
  var xMenuParent = getPageOffsetLeft(button.menu.offsetParent); // menu is positioned relative to
  var yMenuParent = getPageOffsetTop(button.menu.offsetParent); // this "offsetParent"
  x = getPageOffsetLeft(positioner) - xMenuParent;             // so we must subtract offsetParent's position
  y = getPageOffsetTop(positioner) - yMenuParent;             // if positioner has a different offsetParent
  // x += positioner.offsetWidth;      // place menu at the positioner's right side
  y += positioner.offsetHeight;  // originally was below but that would cover
                                    // vertically stacked (= quite common!) buttons below our button

  // For IE, adjust position.

  if (browser.isIE) {
    x += positioner.offsetParent.clientLeft;
    y += positioner.offsetParent.clientTop;
  }
  ensureMenuSize(button);  // maybe must enlarge menu to avoid cut-off; when we finally know size:
                           // maybe must flip menu position to avoid menu going partially off screen:
  var delta = x + xMenuParent + button.menu.offsetWidth - getRightWindowBoundary();
  if (delta > 0)
    x -= button.menu.offsetWidth - positioner.offsetWidth;
  delta = y + yMenuParent + button.menu.offsetHeight - getBottomWindowBoundary();
  if (delta > 0)
    y -= button.menu.offsetHeight + positioner.offsetHeight;
  
  button.menu.style.left = x + "px";        // set position and visibility
  button.menu.style.top  = y + "px";        // to finally make this menu
  activateZorderShield(button.menu);        // if needed: shield from elements that ignore zIndex (MSIE 5.5+)
  button.menu.style.visibility = "visible"; // pop up on screen
}

function resetButton(button) {

  deactivateZorderShield(button.menu); // hide the shield if any was placed between menu and background (MSIE 5.5+)
  
  // Restore the button's style class.

  removeClassName(button, "menuButtonActive");

  // Hide the button's menu, first closing any sub menus.

  if (button.menu != null) {
    closeSubMenu(button.menu);
    button.menu.style.visibility = "hidden";
  }
}

//----------------------------------------------------------------------------
// Code to handle the menus and sub menus.
//----------------------------------------------------------------------------

function menuMouseover(event) {

  var menu;

  // Find the target menu element.

  if (browser.isIE)
    menu = getContainerWith(window.event.srcElement, "DIV", "menu");
  else
    menu = event.currentTarget;

  // Close any active sub menu.

  if (menu.activeItem != null)
    closeSubMenu(menu);
}

function menuItemMouseover(event, menuId) {

  var item, menu, x, y;

  // Find the target item element and its parent menu element.

  if (browser.isIE)
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
  menu = getContainerWith(item, "DIV", "menu");

  // Close any active sub menu and mark this one as active.

  if (menu.activeItem != null)
    closeSubMenu(menu);
  menu.activeItem = item;

  // Highlight the item element.

  item.className += " menuItemHighlight";

  // Initialize the sub menu, if not already done.

  if (item.subMenu == null) {
    item.subMenu = document.getElementById(menuId);
    if (item.subMenu.isInitialized == null)
      menuInit(item.subMenu);
  }

  // Get position for submenu based on the menu item.

  x = getPageOffsetLeft(item) + item.offsetWidth;
  y = getPageOffsetTop(item);

  // Adjust position to fit in view.

  var maxX, maxY;

  if (browser.isIE) {
    maxX = (document.documentElement.scrollLeft   != 0 ? document.documentElement.scrollLeft    : document.body.scrollLeft)
         + (document.documentElement.clientWidth  != 0 ? document.documentElement.clientWidth   : document.body.clientWidth);
    maxY = (document.documentElement.scrollTop    != 0 ? document.documentElement.scrollTop    : document.body.scrollTop)
         + (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
  } else {
    maxX = window.scrollX + window.innerWidth;
    maxY = window.scrollY + window.innerHeight;
  }
  
  maxX -= item.subMenu.offsetWidth;
  maxY -= item.subMenu.offsetHeight;

  if (x > maxX)
    x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
      + (menu.offsetWidth - item.offsetWidth));
  y = Math.max(0, Math.min(y, maxY));

  // Position and show it.

  item.subMenu.style.left = x + "px";
  item.subMenu.style.top  = y + "px";
  item.subMenu.style.visibility = "visible";

  // Stop the event from bubbling.

  if (browser.isIE)
    window.event.cancelBubble = true;
  else
    event.stopPropagation();
}

function closeSubMenu(menu) {

  if (menu == null || menu.activeItem == null)
    return;

  // Recursively close any sub menus.

  if (menu.activeItem.subMenu != null) {
    closeSubMenu(menu.activeItem.subMenu);
    menu.activeItem.subMenu.style.visibility = "hidden";
    menu.activeItem.subMenu = null;
  }
  removeClassName(menu.activeItem, "menuItemHighlight");
  menu.activeItem = null;
}

//----------------------------------------------------------------------------
// Code to initialize menus.
//----------------------------------------------------------------------------

function menuInit(menu) {

  var itemList, spanList;
  var textEl, arrowEl;
  var itemWidth;
  var w, dw;
  var i, j;

  // For IE, replace arrow characters.

  if (browser.isIE) {
    menu.style.lineHeight = "2.5ex";
    spanList = menu.getElementsByTagName("SPAN");
    for (i = 0; i < spanList.length; i++)
      if (hasClassName(spanList[i], "menuItemArrow")) {
        spanList[i].style.fontFamily = "Webdings";
        spanList[i].firstChild.nodeValue = "4";
      }
  }

  // Find the width of a menu item.

  itemList = menu.getElementsByTagName("A");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;

  // For items with arrows, add padding to item text to make the
  // arrows flush right.

  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j], "menuItemArrow"))
        arrowEl = spanList[j];
    }
    if (textEl != null && arrowEl != null)
      textEl.style.paddingRight = (itemWidth
        - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";
  }

  // Fix IE hover problem by setting an explicit width on first item of
  // the menu.

  if (browser.isIE) {
    w = itemList[0].offsetWidth;
    itemList[0].style.width = w + "px";
    dw = itemList[0].offsetWidth - w;
    w -= dw;
    itemList[0].style.width = w + "px";
  }

  // Mark menu as initialized.

  menu.isInitialized = true;
}

//----------------------------------------------------------------------------
// General utility functions.
//----------------------------------------------------------------------------

function getContainerWith(node, tagName, className) {

  // Starting with the given node, find the nearest containing element
  // with the specified tag name and style class.

  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        hasClassName(node, className))
      return node;
    node = node.parentNode;
  }

  return node;
}

function hasClassName(el, name) {

  var i, list;

  // Return true if the given element currently has the given class
  // name.

  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;

  return false;
}

function removeClassName(el, name) {

  var i, curList, newClassName;

  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.

  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name) {
        if (newClassName == null)
          newClassName = curList[i];
        else  
          newClassName += " " + curList[i];
    }
  el.className = newClassName;
}

function getPageOffsetLeft(el) {

  // Return the x coordinate of an element relative to the page.
  
  if (el.offsetParent != null)
    return el.offsetLeft + getPageOffsetLeft(el.offsetParent);
  else
    return el.offsetLeft;
}

function getPageOffsetTop(el) {

  // Return the y coordinate of an element relative to the page.

  if (el.offsetParent != null)
    return el.offsetTop + getPageOffsetTop(el.offsetParent);
  else
    return el.offsetTop;
}

// Returns the substring starting 1 after the first occurrence of the given regex

function skipAfter(text, regex)
{
  var pos = text.search(regex);
  if (pos < 0)
    return "";
  return text.substring(pos+1, text.length);
}
// Returns the length of what appears to be the longest menu text
// assuming the menu's innerHTML has some recognizable and
// not too complex structure (actually looking for some start- and
// end-tags and the usual call to some OpenJahia... macro and
// excluding superfluous whitespace and counting entities like &nbsp;
// &auml; etc. as single char)
// Note: We keep a minimum length to avoid "tiny" menus and assume
// a "safe maximum" if the innerHTML's structure does not meet our
// expectations, i.e. if someone changes the typical menu construction:
// In such case our parsing expectations should be changed too.
// Currently we expect menu text enclosed by an anchor tag and within
// the anchor possibly preceded by an img tag. If the img is present
// we assume a length increase equivalent to 2 extra characters.

function getMenuTextLength(text)
{
  var pos, newLen, len = 0, imgLen = 0;
  var entry;
  while (text.length > 0)
  {
    text = skipAfter(text, /\<a/i);    // find start of anchor tag
    text = skipAfter(text, /\>/);      // and its closing bracket
    entry = skipAfter(text, /\<span/i); // maybe span tag
    if (entry != "")                    // if found:
    {
      text = entry;
      text = skipAfter(text, /\/span>/);    // find its closing bracket
    }
    entry = skipAfter(text, /\<img/i); // maybe img tag
    if (entry != "")                   // if found:
    { imgLen = 2;
      text = entry;
      text = skipAfter(text, /\>/);    // find its closing bracket
    }
    pos = text.search(/\<\/a/i);       // find end-anchor tag
    if (pos < 0)
      break;
    entry = text.substring(0, pos);
    entry = semiNormalizeHtmlText(entry);
    newLen = entry.length;
    len = len < newLen ? newLen : len;
    text = text.substring(pos, text.length);
  }
  if (len == 0)    // no parsing result: menu entries did not have expected structure
    len = 32;      // return 0
  len += imgLen;
  return len > 5 ? len : 5;  // keep minimum length of 5 to avoid "tiny" menus
}

// Returns a text where character sequences which are displayed
// as single character have been replaced with a single character.
// This method was named "semi"-normalize because it does not always
// use the appropriate replacement character (e.g. the &...uml; sequences
// are replaced with ? while one of the umlauts äöüÄÖÜ would be more
// appropriate; Also ß, &, < and > are all mapped to ?. But for our purpose
// we only care for the number of characters since we just want to determine
// the actual text length.

function semiNormalizeHtmlText(text)
{
  text = text.replace(/\s+/g, " ");            // replace sequences of whitespaces with one space
                                               // must do this before(!) dealing with non-breaking spaces!
  text = text.replace(/&nbsp;/g, " ");         // non-breaking space
  text = text.replace(/&szlig;/g, "?");        // ß (replacing with ? rather than ß because ß in a String literal causes a syntax error in IE 5.5
  text = text.replace(/&[AaOoUu]uml;/g, "?");  // ÄÖÜäöü (but replacing with ? because abovementioned bug of IE's JScript engine strikes for these characters same as for ß)
  text = text.replace(/&#x?[^;]{4};/g, "?");   // hex or decimal unicodes (&#x20AC; &#8364; etc.)
  text = text.replace(/&[lg]t;/g, "?");        // <>
  text = text.replace(/&quot;/g, "\"");        // double quotes
  text = text.replace(/&amp;/g, "?");          // & (inserting ? rather than &: not necessary if this is the
                                               // last call but if someday someone adds more calls to replace()
  return text;                                 // he might be fooled by & characters that we insert here)
}

// Returns the horizontal extent beyond which dynamically positioned elements
// like popup menus should not extend in order to not go off-screen
// and maybe cause the document width to be increased unnecessarily

function getRightWindowBoundary()
{
  if (browser.isIE)
    return document.body.clientWidth + document.body.scrollLeft;
  else
  { var areaWidth;
    if (document.body.clientWidth)            // if possible (it's not standard but Firefox knows clientWidth):
      areaWidth = document.body.clientWidth; // get width without vertical scrollbar
    else                                    // else must subtract 16px for vert scrollbar (if any) from innerWidth
    { areaWidth = window.innerWidth -                              // we don't know if that scrollbar was really vertical
        (window.scrollbars && window.scrollbars.visible ? 16 : 0); // but assume it: better stay on the safe side
    }
    return areaWidth + window.pageXOffset;
  }
}

// Returns the vertical extent below which dynamically positioned elements
// like popup menus should not extend in order to not go off-screen
// and maybe cause the document height to be increased unnecessarily

function getBottomWindowBoundary()
{
  if (browser.isIE)
  {
    return document.body.clientHeight + document.body.scrollTop;
  }
  else
  { var areaHeight;
    areaHeight = window.innerHeight -
        (window.scrollbars && window.scrollbars.visible ? 16 : 0); // 16 = scrollbarheight (but we don't know if really a horiz scrollbar is shown)

    return areaHeight + window.pageYOffset;
  }
}

// Set some styles that should be common to all menus
// but might have been influenced inadvertently by CSS entries:
// It's hard enough for designers to get a complex page right
// so the menus should be isolated somewhat from CSS side effects.
// This function would normally be called before we resize, position
// and show a popup menu.
// Note that e.g. for id=menubar there are stylesheet settings which
// (for CSS 2.0 at least; maybe not 2.1) take precedence even over local
// settings because the reference to an id is considered "more specific".
// Hence we get e.g. a bold font where our popup menu is enclosed by an
// element with id=menubar although the popup menu has nothing to do with
// the menubar. This can only be sorted out by applying an even more specific
// style in our stylesheet (actions.css) unless menubar styling is redesigned
// to key off a style class rather than a specific id.

function applyCommonlyWantedMenuStyles(menu)
{
  menu.style.zIndex = 32000;        // make sure it pops up above other page elements
                                    // (remember: the menu, too, is just a div on the page!)
  menu.style.textAlign = "left";    // enforce left-alignment for menu entries (else it looks
                                    // funny when a menu div gets included in a document section
                                    // with right-aligned or centered text)
  menu.style.whiteSpace = "nowrap"; // nowrap seems reasonable for menus
}

// Sets width of menu element as a style since some browsers (Firefox) seem to
// cut off the element (and hence its background) if there's not enough room
// for all content - menu icon and text; for this we assume a standard content
// structure, see also getMenuTextLength() - but lets the content run outside the
// element so that text is hard to read without the proper background behind it.
// The div element that constitutes the menu must have the same font-size as the
// anchor element that contains the menu text since we express the required size
// in em-units of the div's font-size (plus some safety margin).
// The icon, if detected, is assumed to have a width of roughly 2 characters.
// Height is currently not changed since that seems always ok... so far.
// Note: This function sets styled width to actual value for situations that need
// no width correction at all since, without this trick, at least IE will sometimes
// show menu icon and text "not on the same line".

function ensureMenuSize(button)
{ return ; }

function bypassThisUselessFunction(button) {
  var safeMenuHeight = button.menu.offsetHeight; // no FF-corrections in this version: just assuming height is ok (which seems to be always the case for whatever reason)
  var oldWidth = button.menu.offsetWidth;
  var safeMenuWidth = oldWidth; // which is true for IE but not necessarily for other browsers, so we must correct:
                      // menu element (actually a div) is enclosed in some parent but often positioned halfway outside parent;
                      // Firefox still shows all text then (default style of overflow:visible) but cuts off the div with its
                      // background (image or color), so the text is hardly readable while IE keeps text and background visible by just enlarging the div:

  if (!browser.isIE                // IE (and newer Opera) provides automatically increased oldWidth here but Firefox cuts off the div at parent boundaries;
      && !browser.isOpera          // for unknown browsers we believe they behave like FF or might even style the div
                                   // as overflow:hidden by default (who knows) so, to be on the safe side, we treat them just like FF
      && !button.menu.style.width) // but only if no width has been explicitly set to this menu already (either
                                   // by our mechanism here on an earlier invocation for this menu or by the human page designer):
  {
    var safeEm = 3 + getMenuTextLength(button.menu.innerHTML); // get charcount of longest entry and add 3 for safety
    safeEm = safeEm * 0.5;                                    // assume: chars average to 0.5em or less in width
    safeEm += "em";
    
//    button.menu.style.height = safeMenuHeight; // does not seem necessary so far: height was always ok on our tests
    button.menu.style.width = safeEm;            // try and set safe width in em-units
    safeMenuWidth = button.menu.offsetWidth;     // check result in px
    if (oldWidth > safeMenuWidth)                // for safety:
      button.menu.style.width = oldWidth;        // reset to old px-value if that was greater
  }
  else                                       // in IE, where no width correction is necessary we explicitly set the width therdiv already has: this seems
    button.menu.style.width = safeMenuWidth; // to avoid "linebreaks" between icon and menu text in popup menus embedded in certain places (e.g. in our newsbox)
}

// Returns an iFrame (as supported by MSIE 5.5 and higher)
// that can cover a windowed control (like a combobox, applet,
// flash player component etc.) such that a non windowed control
// (such as a div) which should hover on top of that (typically a
// popup menu) is not hidden by the windowed control.
// Note: This has effect only on MSIE 5.5 or higher, where iFrames
// respect zIndex while all other windowed controls do not.
// Other browsers don't seem to have the problem and older MSIE
// versions offer no good solution, so we do nothing for these cases.
// Also note: The iFrame is stored in elem as property zorderShield,
// so on element types that need shielding this property name should
// remain reserved for this purpose!

function getZorderShield(elem)
{
  if (!needsZorderShield())
    return null;
  
  var shield = elem.zorderShield;
  if (shield)
    return shield;
  
  shield = document.createElement("<iframe scrolling='no' frameborder='0'"+
                                      "style='position:absolute; top:0px;"+
                                      "left:0px; display:none'></iframe>"); 
  // shield.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"; // untested (try that in case we need transparent elements)

  if (elem.offsetParent == null)   // || elem.offsetParent.id=="") 
    window.document.body.appendChild(shield);
  else 
    elem.offsetParent.appendChild(shield); 

  elem.zorderShield = shield;
  return shield;
}

// Activates the z-order shield if applicable so elem
// (which should be a non-windowed control) is not hidden
// by windowed controls.

function activateZorderShield(elem)
{
  if (!needsZorderShield())
    return;
    
  var shield = getZorderShield(elem);
        
  shield.style.width = elem.offsetWidth;
  shield.style.height = elem.offsetHeight;
  shield.style.top = elem.offsetTop;      // elem.style.top;
  shield.style.left = elem.offsetLeft;    // elem.style.left;
  shield.style.zIndex = elem.style.zIndex - 1;
  shield.style.position = "absolute";
  shield.style.display = "block";
}

// Deactivates the z-order shield if applicable for this browser.

function deactivateZorderShield(elem)
{
  if (!needsZorderShield())
    return;
  
  var shield = elem.zorderShield;
  if (shield)
    shield.style.display = "none";
}

function needsZorderShield()
{
  return (!browser.isOpera && browser.isIE && browser.version > 5.4);
}

// Check the browser for DOM manipulation
function checkBrowser(){
	this.ver=navigator.appVersion;
	this.dom=document.getElementById?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
	this.ie55=((this.ver.indexOf("MSIE 5.5")>-1 || this.ie6) && this.dom)?1:0;
	this.ie5=((this.ver.indexOf("MSIE 5")>-1 || this.ie5 || this.ie6) && this.dom)?1:0;
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.ie4plus=(this.ie6 || this.ie5 || this.ie4);
	this.ie5plus=(this.ie6 || this.ie5)
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns5);
	return this;
}

bw = new checkBrowser();

// Get an Object contained in a DOM document by its ID attribute
function getObjectById (ID) {
	var obj;
	if (bw.dom)
		return document.getElementById (ID);
	else if (bw.ie4)
		return document.all (ID);
	else
		alert ("Error: Your browser version is not supported. Please upgrade...");
    return null;
}

// Returns an array of values. The delimiter is the ',' character
function getNodeValues (content, nodeName) {
	var tag = "<" + nodeName + ">";
	var start = content.indexOf (tag);
	var end   = content.indexOf ("</" + nodeName + ">");

	if (start < end) {
	    var values = content.substring (start + tag.length, end);
		return values.split (";;");
	} else {
		return new Array (0);
	}
}

// Returns the value of an XML tag
function getNodeValue (content, nodeName) {
	var tag = "<" + nodeName + ">";
	var start = content.indexOf (tag);
	var end   = content.indexOf ("</" + nodeName + ">");

	if (start < end) {
		return content.substring (start + tag.length, end);
	} else {
		return null;
	}
}

// AJAX based function to get all Actions to fill up the Action menu
function getActionMenu(context, objectType, objectKey, definitionID, parentID, pageID, domID, lang, contextualContainerListId) {
    document.body.style.cursor = "wait";
    try {
        // correct values are "POST" or "GET" (HTTP methods).
        var method = "POST" ;
        var data = "key=" + objectKey + "&type=" + objectType +
                   "&def=" + definitionID + "&parent=" + parentID + "&domid=" + domID + "&contextualContainerListId="
                    + contextualContainerListId + "&params=/op/edit/lang/" + lang + "/pid/" + pageID;

        var url = context + "/ajaxaction/GetMenuItems";

		if (method == "GET") {
			url += "?" + data;
			data = null;
		}

		// Create new XMLHttpRequest request
    	if (window.XMLHttpRequest) {
        	req = new XMLHttpRequest ();

    	} else if (window.ActiveXObject) {
        	req = new ActiveXObject ("Microsoft.XMLHTTP");

    	} else {
			alert ("Error: Your Browser does not support XMLHTTPRequests, please upgrade...");
			return;
		}

		req.open (method, url, true);

		req.onreadystatechange = function () {
			buildActionMenu();
		}

		if (method == "POST") {
			req.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
		}
		req.send (data);

	} catch (e) {
		alert ("Exception sending the Request: " + e);
	}
}

// Build the Action Menu
function buildActionMenu () {
	var readyState = req.readyState;
	if (req.readyState == 4) {
		// alert ("resp: " + req.responseText);
    	if (req.status == 200) {
			try {
				var response = req.responseText;
                var uniqueID = getNodeValue(response, "domid");

				var methods = getNodeValues (response, "method");
				var launchers = getNodeValues (response, "launcher");
				var images = getNodeValues (response, "image");
				var styleClasses = getNodeValues (response, "styleClass");				

				var fieldset = getNodeValue (response, "fieldset");
				updateFieldSet (uniqueID, fieldset);

				addActions (uniqueID, methods, launchers, images, styleClasses);

                // changeURL(uniqueID);

				buttonClick (null, uniqueID);

			} catch (e) {
				alert ("Exception building Action Menu: " + e);
			}

		} else {
			alert ("There was a problem processing the request. Status: " +
						   req.status + ", msg: " + req.statusText);
		}
		document.body.style.cursor = "default";
	}
}

// Changes the default grey border. Use in case the object is locked for example
function updateFieldSet (id, param) {
	// alert ("Updating fieldSet for " + id + ", param = " + param);
    if (param == null) {
        return;
    }

	var setID = "fieldset_" + id;
	var setElem = getObjectById (setID);

	var content;
	if (param == "complete") {
		content = "completeLocked";

	} else if (param == "partial") {
		content = "partialLocked";

	} else {
		content = "unlocked";
	}

	setElem.className = content;
}

// Changes the href value of the given element
function changeURL (id) {
	var button = getObjectById ("button_" + id);
	button.href = "javascript:buttonClick(null, '" + id + "');";
}

// Adds the Actions to the action menu
function addActions(id, methods, launchers, images, styleClasses) {
    var menuDiv = getObjectById(id);
    var content = "\n";

    var i;
    for (i = 0; i < methods.length-1; i++) {
       //alert("i="+i+methods[i])

       if(methods[i]=="copies"){

            //specific code to display the list of pickers
                var parts=launchers[i].split(",")
				p=false
				if(parts.length>1) p=parts[1]

                content +="<a class=\"menuItem\" href=\""+parts[3]+"\" title=\"id:"+parts[0]+"\"><i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+parts[2]+"</i></a>"
            } else {
                content += printLauncher(launchers[i]) + printImage(styleClasses[i], images[i]) + printMethod(methods[i]);
             }

    }
    menuDiv.innerHTML = content;
}

// Returns a String for the Action Launcher URI
function printLauncher (launcher) {
	return "   <a class=\"menuItem\" href=\"javascript:" + launcher + "\">\n";
}

// Returns a String for the Action Image
function printImage (styleClass, imageName) {
    var imageTag = "      <span class=\"" + styleClass + "\">";
    if (imageName != null && imageName.length > 0) {
      imageTag += "<img class=\"" + styleClass + "\" src=\"" + imageName + "\" alt=\"\" border=\"0\" />";
    } else {
      imageTag += "&nbsp;";    
    }
    imageTag += "</span>";
	return imageTag;
}

// Returns a String for the Action method name
function printMethod (methodName) {
	return methodName + "\n   </a>\n";
}

function clipboard (context, objectKey, op, pageID) {
    document.body.style.cursor = "wait";
    try {
        // correct values are "POST" or "GET" (HTTP methods).
        var method = "POST" ;
        var data = "key=" + objectKey + "&cop=" + op;
        var url = jahiaMainServletPath + "/op/edit/engineName/clipboard/pid/" + pageID ;

		if (method == "GET") {
			url += "?" + data;
			data = null;
		}

		// Create new XMLHttpRequest request
    	if (window.XMLHttpRequest) {
        	req = new XMLHttpRequest ();

    	} else if (window.ActiveXObject) {
        	req = new ActiveXObject ("Microsoft.XMLHTTP");

    	} else {
			alert ("Error: Your Browser does not support XMLHTTPRequests, please upgrade...");
			return;
		}

		req.open (method, url, true);

		if (op == "paste") {
		    req.onreadystatechange = function () {
                if (req.readyState == 4) {
                    document.body.style.cursor = "default";
                    window.location.reload();
                }
	    	}
	    } else {
		    req.onreadystatechange = function () {
                if (req.readyState == 4) {
                    //copy
                    myurl = "http://" + document.location.host + context + "/jsp/jahia/engines/images/clipboard_next.png";
                    myclip = document.getElementById('clipboard');
                    myclip.src = myurl;
                    myclip.alt = "clipboard:" + objectKey;
                    //window.location.reload();
                    document.body.style.cursor = "default";
                }
            }
	    }

		if (method == "POST") {
			req.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
		}
		req.send (data);
	} catch (e) {
		alert ("Exception sending the Request: " + e);
	}
}

function getWorkflowState(context, key, pid) {
    try {
        // correct values are "POST" or "GET" (HTTP methods).
        var method = "POST" ;
        var data = "key=" + key + "&params=/op/edit/pid/" + pid;

        var url = context + "/ajaxaction/GetWorkflowState";

        if (method == "GET") {
            url += "?" + data;
            data = null;
        }

        // Create new XMLHttpRequest request
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest ();

        } else if (window.ActiveXObject) {
            req = new ActiveXObject ("Microsoft.XMLHTTP");

        } else {
            alert("Error: Your Browser does not support XMLHTTPRequests, please upgrade...");
            return;
        }

        req.open(method, url, true);

        req.onreadystatechange = function () {
            changeIcone();
        }

        if (method == "POST") {
            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        }
        req.send(data);

    } catch (e) {
        alert("Exception sending the Request: " + e);
    }
}

function changeIcone() {
    var readyState = req.readyState;
    if (req.readyState == 4) {
        // alert ("resp: " + req.responseText);
        if (req.status == 200) {
            try {
                var response = req.responseText;
                var objectKey = getNodeValue(response, "key");
                var icone = getNodeValue(response, "stateIcone");

                var elem = getObjectById("img_" + objectKey);
                elem.src = icone;

            } catch (e) {
                alert("Exception changing Icone: " + e);
            }

        } else {
            alert("There was a problem processing the request. Status: " +
                  req.status + ", msg: " + req.statusText);
        }
    }
}

function isIntegerNotNull(valore){
	var ok = false;
	var RegExpInteger = new RegExp("[^0-9]");
	if (valore!='' && !valore.match(RegExpInteger)){
		ok = true;
	}
	return ok;
}
