// Keys
var KEY_TAB=0x09;
var KEY_CTRL_ENTER=0x0A;
var KEY_ENTER=0x0D;
var KEY_END = 0x23;
var KEY_HOME = 0x24;
var KEY_LEFT = 0x25;
var KEY_UP = 0x26;
var KEY_RIGHT = 0x27;
var KEY_DOWN = 0x28;
var KEY_ESC = 0x1B;
var KEY_INSERT = 0x2D;
var KEY_DELETE = 0x2E;

var windowScrollbarSize = -1;
var allSelects = new Array();

//Preload the image.  Needed for IE
function preloadOpenedImg()
{
	var openedImg = new Image;
	openedImg.src = glogUrlPrefix+'/images/opened.gif';
	openedImg = null;
}

function writeAlphaPngImage(name, blank, width, height) {
	var imgStr = '<img style="width: ' + width + '; height: ' + height + '; ';
			if (document.all) {
				imgStr = imgStr + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + name + "', sizingMethod='scale';)\" src=\"" + blank + "\" ";
			} else {
			  	imgStr = imgStr + '" src="' + name + '" ';
			}
			imgStr = imgStr + '/>';
			document.write(imgStr);
		}

function intersects(obj1, obj2) {
  return !((parseInt(obj1.style.left) + parseInt(obj1.showWidth) <= findPosX(obj2)) ||
		 (parseInt(obj1.style.top) + parseInt(obj1.showHeight) <= findPosY(obj2)) ||
		 (parseInt(obj1.style.left) >= findPosX(obj2) + obj2.offsetWidth) ||
		 (parseInt(obj1.style.top) >= findPosY(obj2) + obj2.offsetHeight));
    }

/* Returns the browser version # */
function getBrowserVersion (str)
{
	var index = navigator.appVersion.indexOf(str);
	if (index == -1) return;
	return parseFloat(navigator.appVersion.substr(index+str.length+1));
}

/* Tests to see if we're using IE in general */
function isIE ()
{
    return (isIE6() || isIE7());
}

/* Tests to see if we're using IE 6 */
function isIE6 ()
{
	return (navigator.appName == 'Microsoft Internet Explorer' && getBrowserVersion("MSIE") == 6);
}

/* Tests to see if we're using IE 7 */
function isIE7 ()
{
	return (navigator.appName == 'Microsoft Internet Explorer' && getBrowserVersion("MSIE")  == 7);
}

/* Tests to see if we're using Firefox */
function isFirefox ()
{
	return (navigator.product == "Gecko");
}

/* 
 * Function: scrollElementIntoView
 *
 *   Function to scroll a DOM element into view
 *
 *      elId: element id
 */
function scrollElementIntoView (el, alignWithTop)
{
    if (el)
        el.scrollIntoView(alignWithTop);
}

/* Since IE6 creates <select>s as windows, they do not adhere to the z-index property.  The iframe shim works
   in most cases, but does not work when the <select>s are inside a scrollable div.  It'll initially work, but when
   you scroll the div the <select>s once again bleed through.  This disables the scrollbar on the scrollable div.  This
   only needs to be done for IE6 since in Firefox and IE7 <select>s are windowless */ 
function createIEShimFix (menu, d, func)
{
	if (isIE6())
	{	
		var d = menu.doc;
		if (!d || d == undefined)
			d = document;
        var b = d.getElementById('bodyDataContDiv');
        if (func == undefined)
            func = null;
		if (b && func)
        {    
            b.onscroll = func;
        } else if (b) {
            b.style.overflow="hidden";
		}
	}
}

/* This ends the IE6 fix by changing the scrollable div's overflow back to 'auto'. */
function endIEShimFix (menu)
{	
	if (isIE6())
	{	
		var d = menu.doc;
		if (!d)
			d = document;
		var b = d.getElementById('bodyDataContDiv');
		if (b && b.onscroll)
		{
		    b.onscroll = null;
        } else if (b) {
            b.style.overflow="auto";
		}
	}

}

function createMenuShim(menu, d) {
	if (menu == null) {
		return null;
	}
	var doc;
	if (d)
	{
		doc = d;
	} else {
		doc = document;
	}
	var shim = doc.createElement("iframe");
	shim.name = getShimId(menu);
	shim.id = getShimId(menu);
	shim.scrolling = 'no';
	shim.frameBorder = '0';
	shim.style.position = 'absolute';
	shim.style.display = 'none';
    shim.src = "javascript:false;";
	    
    if ((menu.offsetParent == null) || (menu.offsetParent.id == "")) {
		doc.body.appendChild(shim);
	} else {
		menu.offsetParent.appendChild(shim);
	}
	return shim;
}

function getShimId(menu) {
	if (menu.id == null) {
		return "_shim";
	}
	return "_shim"+menu.id;
}

function getShim(menu, d) {
	if (d != null)
		return d.getElementById(getShimId(menu));
	else
		return document.getElementById(getShimId(menu));
}

function hideSelects(menu, d, func) {
    if (!isIE6()) return;
	if (menu == null) {
		return;
	}
	var shim = getShim(menu, d);
	if (shim == null) {
		shim = createMenuShim(menu, d);
    }
	menu.style.zIndex = 100;
	shim.style.width = menu.offsetWidth;
	shim.style.height = menu.offsetHeight;
	shim.style.top = menu.style.top;
	shim.style.left = menu.style.left;
	shim.style.zIndex = menu.style.zIndex - 1;
	shim.style.position = "absolute";
	shim.style.display = "block";
    shim.style.background="red";
    shim.style.filter = 'alpha(opacity=0)';
    shim.setAttribute('removeShim', d != document); 
    createIEShimFix(menu, d, func);
	
}

function showSelects(menu, removeShim) {
    if (!isIE6()) return;
	if (menu == null) {
		return;
	}
    var doc = menu.document;
    if (!doc)
        doc = menu.doc;
    if (!doc)
        doc = document;
        
    var shim = getShim(menu, doc);
	if (shim != null) {
		// Result row tree, related links, IE: for some reason, opening and closing the related
		// link window twice the screen doesn't redraw correctly.  I believe this has to do with adding
		// the rl window to a different document  Not entirely sure.
		if (shim.getAttribute('removeShim') == true || removeShim)
		{
			shim.parentNode.removeChild(shim);
			endIEShimFix(menu);
        } else {
			shim.style.display = "none";
			endIEShimFix(menu);
		}
	}
}

function getDocumentFragment() {
  if (document.createDocumentFragment) {
    return document.createDocumentFragment();
  }
  return document.createElement();
}

function getEvent(e) {
  return (e) ? e : ((window.event) ? window.event : "")
}

function getEventTarget(e) {
    return (e.target) ? e.target : e.srcElement
}

function getViewportWidth(d) {
	var doc = document;
	if (d) {
		doc = d;
	}
  	var width = 0;
  	//ie quirks mode & firefox
  	width = doc.body.clientWidth;
  	return width;
}

function getViewportHeight(d) {
	var doc = document;
	if (d) {
		doc = d;
	}
  	var height = 0;
  	//ie quirks mode & firefox
  	height = doc.body.clientHeight;
  	return height;
}

function getViewportScrollX(d) {
	var doc = document;
	if (d) {
		doc = d;
	}
  	var scrollX = 0;
	// ie & firefox quirks mode
  	scrollX = doc.body.scrollLeft;
  	return scrollX;
}

function getViewportScrollY(d) {
	var doc = document;
	if (d) {
		doc = d;
	}
  	var scrollY = 0;
	// ie & firefox quirks mode
  	scrollY = doc.body.scrollTop;
  	return scrollY;
}

/**
  * Function: cancelBubbling
  *     Stops the event from bubbling
  *
  *     e:              Event
  *     preventDefault: Cancels the default action for the event
  */
function cancelBubbling(e, preventDefault) 
{
    if (!e) var e = window.event;
    if (e)
    {
    	e.cancelBubble = true;
    	if (e.stopPropagation) 
    	{
    	    e.stopPropagation();
        }
    
        if (preventDefault)
        {
            preventEventDefault(e);
        }
    }
}

function preventEventDefault(e)
{
    var ev = getEvent(e);
    if (ev)
    {
        if (isIE())
            ev.returnValue = false;
        else
            ev.preventDefault();
    }
}

function findPosX(obj, stopAtId) {
  var curleft = 0;
  if (obj.offsetParent)
  {
          while (obj.offsetParent && obj.style.position != 'relative' && obj.id != null && obj.id != stopAtId)
          {
                  curleft += obj.offsetLeft;
                  obj = obj.offsetParent;
          }
  }
  else if (obj.x)
          curleft += obj.x;
  return curleft;
}

function findPosY(obj, stopAtId) {
  var curtop = 0;
  if (obj.offsetParent)
  {
          while (obj.offsetParent && obj.style.position != 'relative' && obj.id != null && obj.id != stopAtId)
          {
          	//alert(obj.id+":"+obj.style.position+":"+obj.offsetTop);
	          curtop += obj.offsetTop;
                  obj = obj.offsetParent;
                  
          }
  }
  else if (obj.y)
          curtop += obj.y;
  return curtop;
}

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

/**
  * Function: getElementPosition
  *    Gets an elements x/y coordinates on a page.  This is really a huge hack that probably doesn't always work.         *
  *    The problem is that IE and Firefox do not add in the border widths into the calculations for offsetLeft and        *
  *    offsetTop.  These are important since we do have border widths on grids.  Therefore, there's a lot of if's to      *
  *    help determine the correct position of the element.  I've probably missed certain cases.  This was tested on the   *
  *    Actions Manager (new) and the Quote Manager (edit) for the auto complete functionality.  These had picklists in    *
  *    grids and not in grids                                                                                             */
function getElementPosition (el, relationToEl)
{
    var x=0;
    var y=0;

    while (el != null && el != relationToEl)
    {
       var blw = parseInt(getStyle(el, 'border-left-width'));
       var brw = parseInt(getStyle(el, 'border-right-width'));
       var xa = 0;
   //   alert(blw+":"+brw+":"+el.nodeName+":"+el.id);
       if (!isNaN(blw) && el.nodeName != 'INPUT')
       {
         if (el.nodeName == 'TD') 
         {
            if (!el.previousSibling)
            {
            //   alert(blw+":"+brw);
               if (blw > 0 && brw > 0)
                 xa += isFirefox() ? 0  : -1;
               else
                  xa += 0;  
            } else {
               xa += isFirefox() ? 0  : ((blw+brw) / 2)-1;
            }
         } else if (isFirefox() && el.nodeName == 'TABLE') {
            xa = 0;
         } else {
               xa += isFirefox() ? blw : blw;       
         }
       }
     //  alert(xa);
       var btw = parseInt(getStyle(el, 'border-top-width'));
       var bbw = parseInt(getStyle(el, 'border-bottom-width'));
       var ya = 0;
       if (!isNaN(btw) && el.nodeName != 'INPUT')
       {
         if (el.nodeName == 'TD') 
         {
            if (!el.previousSibling)
            {
               if (btw > 0 && bbw > 0)
                 ya += isFirefox() ? 0 : (btw+bbw)/2;
               else
                  ya += 0;  
            } else {
               ya += isFirefox() ? 0  : (btw+bbw)/2;  //firefox was -1; mass update
            }
         } else {
               ya += isFirefox() ? 0 : btw;       
         }
       }       
        x += el.offsetLeft - el.scrollLeft + xa;
        y += el.offsetTop - el.scrollTop + ya;
        if (isFirefox() && el.nodeName == 'BODY')
        {
          //  x += 1;
          //  y += 1;
        }
      // alert(x+":"+xa+":"+y+":"+ya+":"+el.nodeName);
        el = el.offsetParent;
    }
  //  alert('done');
  

    return { x:x, y:y };
}

function getInput(type, name, value, size, maxlength, style) {
    var input = document.createElement("input");
    input.type = type;
    if(name) input.name = name;
    if(name) input.id = name;
    if(value) input.value = value;
    if(size) input.size = size;
    if(maxlength) input.maxlength = maxlength;
    if(style) {
      var str = "input.style."+style;
      eval(str);
    }
    return input;
}

function getSection(table, name, required, hidelabel) {
    if(hidelabel != false) {
        var row = getRow(table=table);
        var cell = getCell(row=row);

        var table2 = cell.appendChild(getTable(border="0", pad="0", space="0", height="", width="", className="mtlabel"));
        var row2 = getRow(table=table2, border="", bordercolor="", height="", width="", className="mtlabel");
        if(required == true) {
            var cell = getCell(row=row2, align="center");
            var div = cell.appendChild(document.createElement("div"));
            div.className = "required";
            div.innerHTML = "*";
        }

        var cell2 = getCell(row=row2, align="", nowrap="", colspan="", width="", className="mtlabel");
        cell2.innerHTML = name;
    }

    var row = getRow(table=table);
    var cell = getCell(row=row);
    cell.valign = "top";

    return cell;
}

function getContentTable() {
    var table = document.createElement("table");
    table.border = "0";
    table.cellPadding = "4";
    table.cellSpacing = "0";
    table.className = "mtcolor2";

    return table;
}

function getTable(border, pad, space, height, width, className, valign, bordercolor, doc) {

    var d = doc;
    if (!d) d = document;
    var out = d.createElement("table");
    if(height) out.height = height;
    if(width) out.width = width;
    if(className) out.className = className;
    if(border) out.border = border;
    if(pad) out.cellPadding = pad;
    if(space) out.cellSpacing = space;
    if(valign) out.valign = valign;
    if(bordercolor) out.bordercolor = bordercolor;
    return out;
}

function getRow(table, border, bordercolor, height, width, className, valign) {
    var out = table.insertRow(table.rows.length);
    if(className) out.className = className;
    if(border) out.border = border;
    if(height) out.height = height;
    if(width) out.width = width;
    if(valign) out.valign = valign;
    if(bordercolor) out.bordercolor = bordercolor;
    return out;
}

function getCell(row, align, nowrap, colspan, width, className, height) {
    var cell = row.insertCell(row.cells.length);
    if(align) cell.align = align;
    if(nowrap) cell.noWrap = nowrap;
    if(colspan) cell.colSpan=colspan;
    if(width) cell.width = width;
    if(height) cell.height = height;
    if(className) cell.className = className;
    return cell;
}

function getImage(src, border, width, height, vspace, hspace, align, alt, name, d) {
    var doc;
    if (d)
        doc = d;
    else
        doc = document;
        
    var image = doc.createElement("img");
    if (src && src != undefined) image.setAttribute("src", src);
    if (border && border != undefined) image.setAttribute("border", border);
    if (width && width != undefined) image.setAttribute("width", width);
    if (height && height != undefined) image.setAttribute("height", height);
    if (vspace && vspace != undefined) image.setAttribute("vspace", vspace);
    if (hspace && hspace != undefined) image.setAttribute("hspace", hspace);
    if (align && align != undefined) image.setAttribute("align", align);
    if (alt && alt != undefined) image.setAttribute("alt", alt);
    if (name && name != undefined) image.setAttribute("name", name);
    return image;
}

function getAnchor(node, tabIndex, href, onclick, name, text, image) {
  var a = node.appendChild(document.createElement("a"));
  if (tabIndex) a.tabIndex = tabIndex;
  if (href) a.href = href;
  if (onclick) a.onclick = onclick;
  if (name) {
    a.name = name;
    a.id = name;
  }
  if (text) a.appendChild(document.createTextNode(text));
  if (image) a.appendChild(image);
  return a;
}

function getDiv(node, className, text) {
  var div = node.appendChild(document.createElement("div"));
  if (className) div.className = className;
  if (text) div.appendChild(document.createTextNode(text));
  return div;
}


function hasParent(el, id) {
  if (el.id == id) {
    return true;
  }
  var p = el.parentNode;
  if (p != null) {
    return hasParent(p, id);
  }
  return false;
}



/* Function: changeSectionLabel
        This changes a section's label text
            elId:       Element id (same as the value for tableId when defining the section)
            newLabel:   The new label text
 */
function changeSectionLabel (elId, newLabel)
{
    var el = document.getElementById('label_'+elId);
    if (el)
        el.innerHTML = newLabel;
    
}

/* Function: showHideElementWithImage
        This is a toggle of showing/hiding an element based upon the element's current visibility style.  It also changes
        an associated image element to the correct show/hide image.
            elId:           Element id
            imgId:          The show/hide image element id
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view (only works on show)
*/ 
function showHideElementWithImage (elId, imgId, visibilityOnly, ignoreResize, scrollIntoView)
{
    var style = document.getElementById(elId).style.visibility;
    if (style == 'visible' || style == '') 
    {
        hideElement(elId, visibilityOnly, ignoreResize);
	    if (imgId)
        {
            var imgEl = document.images[imgId];
            imgEl.src=show_img;
            imgEl.alt=show_img_alt;
        }
    } else {
        showElement(elId, visibilityOnly, ignoreResize, scrollIntoView); 
	    if (imgId)
        {
            var imgEl = document.images[imgId];
            imgEl.src=hide_img;
            imgEl.alt=hide_img_alt;
        }
   }
}

/* Function: showSection
        This function makes a section visible.
            elId:           The tableId value of a section.
            imgId:          The id of the section +/- image
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view
*/ 
function showSection (elId, imgId, visibilityOnly, ignoreResize, scrollIntoView)
{
    showElement(elId, visibilityOnly, scrollIntoView); 
    var imgId2 = imgId;
    if (!imgId2)
        imgId2 = 'image_'+elId;
    if (imgId2)
    {
        var imgEl = document.images[imgId2];
        imgEl.src=hide_img;
        imgEl.alt=hide_img_alt;        
    }
    
}

/* Function: hideSection
        This function makes a section hidden.
            elId:           The tableId value of a section.
            imgId:          The id of the section +/- image
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view
*/ 
function hideSection (elId, imgId,  visibilityOnly, ignoreResize)
{
    hideElement(elId, visibilityOnly); 
    var imgId2 = imgId;
    if (!imgId2)
        imgId2 = 'image_'+elId;
    if (imgId2)
    {
        var imgEl = document.images[imgId2];
        imgEl.src=show_img;
        imgEl.alt=show_img_alt;        
    }
    
}


function showHideTableTreeRowChildren (gridName, elId, imgId, tabName, scrollIntoView)
{
    var i = 1;
    var childEl = document.getElementById(elId+'_1');
    var show = true;
    while (childEl)
    {
        var style = childEl.style.visibility;
        if (style == 'visible' || style == '') 
        {
            hideElement(childEl.id, false, true);
            show = true;
        } else {
            showElement(childEl.id, false, true, scrollIntoView); 
            show = false;
        }
        i++;
        childEl = document.getElementById(elId+'_'+i);
   }
   if (show && imgId)
   {
        var imgEl = document.images[imgId];
        imgEl.src=show_img;
        imgEl.alt=show_img_alt;
   }
   if (!show && imgId)
   {
        var imgEl = document.images[imgId];
        imgEl.src=hide_img;
        imgEl.alt=hide_img_alt;
   }
   setGridBodyRowClasses(gridName);
   if (typeof(resizeBodyContainer)=='function') 
        resizeBodyContainer(null, 'tabSwitch', tabName)
}


function showHideSection (elId, imgId, tabName, scrollIntoView)
{
    showHideElementWithImage(elId, imgId, false, true, scrollIntoView);
    if (typeof(resizeBodyContainer)=='function') 
        resizeBodyContainer(null, 'tabSwitch', tabName)
    
}


/* Function: showHideElement
        This is a toggle of showing/hiding an element based upon the element's current visibility style.
            elId:           Element id
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view (only works on show)
*/ 
function showHideElement(elId, visibilityOnly, ignoreResize, scrollIntoView)
{
    var style = document.getElementById(elId).style.visibility;
    if (style == 'visible' || style == '') 
    {
        hideElement(elId, visibilityOnly, ignoreResize);
    } else {
        showElement(elId, visibilityOnly, ignoreResize, scrollIntoView);
   }
}

/* Function: forceShowHideElement
        This forceable shows or hides an element.
            elId:           Element id
            show:           true -> show element; false -> hide element
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view (only works on show)
*/            
function forceShowHideElement (elId, show, visibilityOnly, ignoreResize, scrollIntoView)
{
    if (show == true)
        showElement(elId, visibilityOnly, ignoreResize, scrollIntoView);
    else
        hideElement(elId, visibilityOnly, ignoreResize);
    
}

/* Function: showElement
        This shows a DOM element
            elId:           Element id
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to show the element.
            ignoreResize:   If you want to ignore the resizing of the scrollable screen body.  Set this to true only
                            if you are doing multiple show/hides at a time.  You only want to do this on the last one.
            scrollIntoView: Scroll the element into view
            doc:            document
 */
function showElement (elId, visibilityOnly, ignoreResize, scrollIntoView, doc)
{
    if (visibilityOnly == undefined)
        visibilityOnly = false;
    if (ignoreResize == undefined)
        ignoreResize = false;
    if (scrollIntoView == undefined)
        scrollIntoView = false; 
    var d = doc;
    if (!d) d = document; 
    var el = d.getElementById(elId);
    if (el)
    {
    	setTimeout("void(1)", 1);
    	if (!visibilityOnly)
    		el.style.display='';
        el.style.visibility='visible';
        if (!ignoreResize && !visibilityOnly && typeof(resizeBodyContainer)=='function')
        	resizeBodyContainer(null, 'element');
        if (scrollIntoView == true)
            scrollElementIntoView(el, true);        
    }
}

/* Note: for both IE and Firefox to work, name and id should be set to the same value */
function showMultiElements (elName)
{
    var list = document.getElementsByName(elName);
     for(var i = 0; i < list.length; i++) {
       var node = list.item(i);
       node.style.display='';
       node.style.visibility='visible';
    }
}

/* Function: hideElement
        This hides a DOM element
            elId:           Element id
            visibilityOnly: Only change the visibility style.  Changing the display causes element collapsing.  Set
                            this to true if you only want to hiding the element.
            ignoreResize:   Ignore resizing the body container
            doc:            document
 */
function hideElement (elId, visibilityOnly, ignoreResize, doc)
{
    if (visibilityOnly == undefined)
        visibilityOnly = false;
    if (ignoreResize == undefined)
        ignoreResize = false;   
        
    var d = doc;
    if (!d) d = document;
    var el = d.getElementById(elId);
    if (el)
    {	
    	setTimeout("void(1)", 1);
    	if (!visibilityOnly)
    		d.getElementById(elId).style.display='none';
        d.getElementById(elId).style.visibility='hidden'; 
        if (!ignoreResize && !visibilityOnly && typeof(resizeBodyContainer)=='function')
            resizeBodyContainer(null, 'element');
    }
}

/* Note: for both IE and Firefox to work, name and id should be set to the same value */
function hideMultiElements (elName)
{
    var list = document.getElementsByName(elName);
   for(var i = 0; i < list.length; i++) {
       var node = list.item(i);
       node.style.display='none';
       node.style.visibility='hidden';
    }
}

/* Sets a table cell's id and name attributes.  Used primarily for setting the name
   and id attributes on a empty row's cell. */
function setTableCellIdAndName(tableId, colNum, id)
{
    	var e = document.getElementById(tableId);
    	if (e)
    	{
    	    cell = e.cells[colNum];
            cell.setAttribute('name',id);
            cell.setAttribute('id',id);
    	}
}

function displayTabAndData(tab) {
    var tabShow = null;
    for (var i = 0; i < tabs.length-1; i++) {
 //       var last = i != tabs.length-1;
        if (tabs[i+1] == tab) {
            forceShowHideElement(tabs[i+1]+'_On', true, false, true);
            forceShowHideElement(datas[i+1], true, false, true);
            tabShow = datas[i+1];
            showHideElement(tabs[i+1]+'_Off', false, false, true);
        } else {
            forceShowHideElement(tabs[i+1]+'_On', false, false, true);
            forceShowHideElement(datas[i+1], false, false, true);
            forceShowHideElement(tabs[i+1]+'_Off', true, false, true);
        }
    }
    if (typeof(resizeBodyContainer)=='function') 
    	resizeBodyContainer(null, 'tabSwitch', tabShow)
}


function showHideHeadDiv (id, show)
{
	var el = document.getElementById(id)
	if (show == true)
	{
		el.style.visibility = 'visible';
		el.style.display = '';
	} else {
		el.style.visibility = 'hidden';
		el.style.display = 'none';	
	}
}

function showHideDiv(divName, label, altLabel, textId) {

    var divTag = document.getElementById(divName);
    var visibleElementName = "showHide"+divName;
    var visibleElement = document.getElementById(visibleElementName);
    if (divTag.style.visibility=='visible') {
        divTag.style.visibility='hidden';
        divTag.style.display='none';
    	if (visibleElement)
        	visibleElement.value = 'false';
    }
    else {
        divTag.style.visibility='visible';
        divTag.style.display='';
    	if (visibleElement)
        	visibleElement.value = 'true';
    }

    var textElement = document.getElementById(textId);
    var text = textElement.getAttribute("value");
    if (text == label) {
        document.getElementById(textId).setAttribute("value", altLabel);
        var oTextNode = document.createTextNode(altLabel);
        var oReplaceNode = document.getElementById(textId).childNodes[0];
        if (document.replaceNode)
        	oReplaceNode.replaceNode(oTextNode);
        else
        	oReplaceNode.parentNode.replaceChild(oTextNode, oReplaceNode);
    }
    else {
        document.getElementById(textId).setAttribute("value", label);
        var oTextNode = document.createTextNode(label);
        var oReplaceNode = document.getElementById(textId).childNodes[0];
        if (document.replaceNode)
        	oReplaceNode.replaceNode(oTextNode);
        else
        	oReplaceNode.parentNode.replaceChild(oTextNode, oReplaceNode);
    }
}

    
function openCloseDiv(divName) {

    var divTag = document.getElementById(divName);
    if (divTag.style.visibility=='visible' || divTag.style.visibility == '') {
        divTag.style.visibility='hidden';
        divTag.style.display='none';
        if (document.getElementById("image_"+divName))
        	document.getElementById("image_"+divName).src=show_img;
    }
    else {
        divTag.style.visibility='visible';
        divTag.style.display='';
        if (document.getElementById("image_"+divName))
        	document.getElementById("image_"+divName).src=hide_img;
    }
}

function formatUrl(url){
  if(url == null){
     return "";
  }   
  var qIndex = url.indexOf("?");
  var servletPath = null;
  var queryString = null;

  if(qIndex < 0){
     servletPath = url;
  }else{ 
     servletPath = url.substring(0,qIndex);
     queryString = url.substring((qIndex+1),url.length);
  }

  var sb = glogUrlPrefix+glogUrlContext+servletPath+"/";
      
  if((glogServlet != null) && (glogServlet.length > 0)){
   	sb += glogServlet;
  }

  if((queryString != null) && (queryString.length > 0)){
    sb+= "?"+queryString;
  }
      
  return sb;
}

function onLoadResize()
{
  var temp = document.getElementById("detail_table_id");
  var temp2 = document.getElementById("divmulti");
  if (temp && temp2 && temp.offsetWidth < temp2.offsetWidth)
  	temp.setAttribute("width", temp2.offsetWidth);
} 

function XidFromGid(gid) {
   var index = gid.indexOf('.');
   if(index == -1) return gid;

   else return(gid.substring(index+1));
}

function DomainFromGid(gid) {
	var index = gid.indexOf('.');
   	if(index == -1) {
   		return "";
   	} else {
   		return(gid.substring(0, index));
   	}
}

function applyPopMask (maskId, doc, hideSelectTags)
{
    var d = null;
    if (doc != null)
        d = doc;
    else
        d = document;
        
    var el = d.getElementById(maskId);
    if (el)
    {
        el.style.width = d.body.clientWidth;
        el.style.height = d.body.clientHeight;
        el.style.visibility = 'visible';
        el.style.top = 0;
        el.style.left = 0;
        el.doc = doc;
        if (hideSelectTags)
        {
           hideSelects(el, d);  
        }
    }
    
}
	
function removePopMask (maskId, doc, showSelectTags)
{
    var d = null;
    if (doc != null)
        d = doc;
    else
        d = document;
        
    var el = d.getElementById(maskId);
    if (el)
    {
        el.style.width = 0;
        el.style.height = 0;
        el.style.visibility = 'hidden';
        if (showSelectTags)
        {
           showSelects(el);  
        }
    }
}


function ImagePreloader(images)
{
   // initialize internal state.
   this.nLoaded = 0;
   this.nProcessed = 0;
   this.aImages = new Array;

   // record the number of images.
   this.nImages = images.length;

   // for each image, call preload()
   for ( var i = 0; i < images.length; i ++ ) 
      this.preload(images[i], images[++i]);

} 

ImagePreloader.prototype.preload = function(image, imageName)
{
   // create new Image object and add to array
   var oImage = new Image;
   this.aImages[imageName] = oImage;
   oImage.border="0";
   oImage.src = image;
}

/*
 * function: addEvent
 *     Adds an event to a specified element
 *
 *     el: element
 *     type: event type (mousedown, mouseup, etc)
 *     func: function to assign to the event
 *     useCapture: for Mozilla.
 */
function addEvent (el, type, func, useCapture)
{
	if (!el) return;
	if (typeof el.addEventListener != "undefined")
	{		
		el.addEventListener(type, func, useCapture);
	} else if (typeof el.attachEvent != "undefined") {
		el.attachEvent("on"+type, func);
	} else {
	}
}

/*
 * function: removeEvent
 *     Removes an event from a specified element
 *
 *     el: element
 *     type: event type (mousedown, mouseup, etc)
 *     func: function to remove
 */
function removeEvent (el, type, func)
{
    if (typeof el.addEventListener != "undefined")
    {       
        el.removeEventListener(type, func, false);
    } else if (typeof el.attachEvent != "undefined") {
        el.detachEvent("on"+type, func);
    } else {
    }
}


var submittingForm = false;

/* 
 * Function: delaySubmit
 *     Delays the submitting of a form
 *        f:  form name
 *        dt: delay time (in ms)
 */
function delaySubmit (f, dt)
{
  submittingForm = true;
  var formName = f;
  if (!formName)
    formName = 'management_main';
  var delayTime = dt;
  if (!delayTime)
    delayTime = 150;
    
  setTimeout("document.forms['"+formName+"'].submit()", delayTime);
  
}

/*
 *  Function: setCaretPosition
 *      Sets the caret (cursor) position of the specified text field.
 *          oField:    field element
 *          iCaretPos: caret position.  Valid positions are 0-oField.length.
 */
function setCaretPosition (oField, iCaretPos) 
{
    if (isIE()) 
    { 
       // Set focus on the element
       oField.focus ();
  
       // Create empty selection range
       var oSel = document.selection.createRange ();
  
       // Move selection start and end to 0 position
       oSel.moveStart ('character', -oField.value.length);
  
       // Move selection start and end to desired position
       oSel.moveStart ('character', iCaretPos);
       oSel.moveEnd ('character', 0);
       oSel.select ();
     } else {
       oField.selectionStart = iCaretPos;
       oField.selectionEnd = iCaretPos;
       oField.focus ();
     }
}           


function isElementVisible (oField)
{
    return (oField != null && (oField.style.visibility == '' || oField.style.visibility == 'visible'));
}

function createPopMessage (d, parentEl, divId, imgId, imgSrc, msgId, msg, divStyles)
{
    var doc;
    if (d)
        doc = d;
    else
        doc = document;
    
    var divEl = doc.createElement('div');
    if (divId)
        divEl.id = divId;
    divEl.style.position = "absolute";
    divEl.style.zIndex = 999999;    
    
    if (imgSrc)
    {
        var imgEl = getImage(imgSrc, "0", null, null, null, null, null, null, null, doc);
        if (imgId)
            imgEl.id = imgId;
        divEl.appendChild(imgEl);
    
        var brEl = doc.createElement("br");
        divEl.appendChild(brEl);
    }
    
    var spanEl = doc.createElement("span");
    if (msgId)
        spanEl.id = msgId;
    if (msg)
        spanEl.innerHTML = msg;
    divEl.appendChild(spanEl);
    
    if (parentEl)
    {
        parentEl.appendChild(divEl);
    }
    
    var cnt = divStyles ? divStyles.length : 0;
    var posX = true;
    var posY = true;
    for (var i=0; i < cnt; ++i)
    {
        var dStyle = divStyles[i];
        if (dStyle[0] == 'top') posY = false;
        if (dStyle[0] == 'left') posX = false;
        
        divEl.style[dStyle[0]] = dStyle[1];
    }
    centerElement(divEl, posX, posY);
    
    return divEl;
}

function changePopMessageText (msgId, msgText)
{
    var msgDiv = document.getElementById(msgId);
    if (msgDiv)
    {
        msgDiv.innerHTML = msgText;
    }
}

function centerElementById (elId, horizontal, vertical)
{
    centerElement(document.getElementById(elId), horizontal, vertical);
}

function centerElement(el, horizontal, vertical)
{
    if (!el) return;
    var parEl = el.parentNode;
    
    // Sometimes we create the message when the client* is not known yet.  In this case
    // use the offset*.
    // See Result Body messages needs client.  Result Body Tree message needs offset
    if (horizontal)
    {
        var val = 0;
    	if (parEl.clientWidth == 0)
        {
            val = (el.parentNode.offsetWidth - el.offsetWidth) / 2;
        } else {
            val = (el.parentNode.clientWidth - el.clientWidth) / 2;
        }
        if (val < 0)
        {
            val = (el.parentNode.scrollWidth - el.clientWidth) / 2; 
        }
        el.style.left = val+"px";
    }
    if (vertical)
    {       
        var val = 0;
        if (parEl.clientHeight == 0)
        {
            val = (el.parentNode.offsetHeight - el.offsetHeight) / 2;
        } else {
            val = (el.parentNode.clientHeight - el.clientHeight) / 2;
        }
        if (val < 0)
        {
            val = (el.parentNode.scrollHeight - el.clientHeight) / 2; 
        }
        el.style.top = val+"px";
    }
    
}

/*
 * Function: importNode
 *
 *      Imports a node from one document to the current document.
 *      Currently, due to a flaw (so they say), this is not needed in Firefox.
 *      Therefore, for Firefox we can just return the current node.
 *
 *          oNode: node to import
 *          bDeep: Deep copy
 */
function importNode(oNode, bDeep) 
{
    if (isIE())
    {
        var nodeHTML = oNode.xml||oNode.outerHTML;
        var tmpNode = document.createElement("div");
        tmpNode.innerHTML = nodeHTML;
        return tmpNode.firstChild.cloneNode(bDeep);
    } else {
        //return oNode.importNode(bDeep);
        return oNode;
    }
}

function createDataSectionContainer  (id, type, background, fitToContents, doc)
{
	var d = doc;
    if (!d) d = document;
	var divEl = d.createElement('div');
    if (id)
        divEl.id = id;
    if (type == 'view')
        divEl.className = 'bodySectCont';
    else if (background) 
        divEl.className = 'bodySectCont bodySectBG';        
    else
        divEl.className = 'bodySectCont';
   
    if (fitToContents)
        divEl.className += ' wa';
    
    return divEl;
}

function createDataInnerSectionContainer (id, hide, doc)
{
    var d = doc;
    if (!d) d = document;
    var tabEl = getTable(null, null, null, null, null, 'bodySectInCont', null, null, d);
    if (id)
        tabEl.id = id;
    if (hide)
        hideElement(tabEl, false, false, d);
    return tabEl;
}

/*
 * Functions to add and remove class names
 */
function addClass(el, cls, forceBefore) {
    if (el.className.indexOf(cls) == -1)
        if(forceBefore != null && el.className.match(new RegExp('(^| )' + forceBefore))) 
        {
            el.className = el.className.replace(new RegExp("( |^)" + forceBefore), '$1' + cls + ' ' + forceBefore);
        } else if(!el.className.match(new RegExp('(^| )' + cls + '($| )'))) {
            el.className += ' ' + cls;
            el.className = el.className.replace(/(^ +)|( +$)/g, '');
        }
}

function removeClass(el, cls) {
    var old = el.className;
    var newCls = ' ' + el.className + ' ';
    newCls = newCls.replace(new RegExp(' (' + cls + ' +)+','g'), ' ');
    el.className = newCls.replace(/(^ +)|( +$)/g, '');
} 


function setFocus(formName)
{
    var focusSet = false;
    if (formName && document.forms[formName] && document.forms[formName].elements[0]!=null) {
        var i;
        var max = document.forms[formName].length;
        for( i = 0; i < max; i++ ) {
            if( document.forms[formName].elements[ i ].type != "hidden" &&
                !document.forms[formName].elements[ i ].disabled &&
                !document.forms[formName].elements[ i ].readOnly ) {
                        try {
                            document.forms[formName].elements[ i ].focus();
                            focusSet = true;
                            break;
                        } catch(ex) { 
                        }
            }
        }
    }
    
    // Make the first focusable link the focus element.
    if (!focusSet)
    {
        var max = document.links.length;
        for (var i = 0; i < max; i++ ) 
        {
            if (document.links && document.links[i] && document.links[i].focus) 
            {
                try {
                    document.links[i].focus();
                    break;
                } catch(ex) { 
                }
            }
        }    
    }
}

function setFocusById (id)
{
    var el = document.getElementById(id);
    if (el)
    {
        el.focus();el.focus();
        }
}

function launchHelp(_finderSetGid) {
    finderSetForHelp = null;
    if(_finderSetGid != null){
        finderSetForHelp = _finderSetGid;
    }else{
        finderSetForHelp = finderSetGid;
    }
    

    URL = formatUrl('glog.webserver.finder.HelpRedirectServlet?finder_set_gid='+finderSetForHelp);
    window.open(URL,"name","toolbar=yes,location=yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=800,height=480");

}

function NameValuePair (name, value)
{
    this.name = name;
    this.value = value;
}

/*
 * Function: getWindowScrollbarSize
 *	Calculates the size of the scrollbar as determined by the user's windows display setting.
 */
function getWindowScrollbarSize() {
	
    if (windowScrollbarSize != -1)
        return windowScrollbarSize;
        
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Add the scrollbar
    scr.style.overflow = 'auto';

    windowScrollbarSize = scr.offsetWidth - inn.offsetWidth;
    
    // If nothing, then make sure it's at least 17.  This is the default as set by Windows.
    if (!windowScrollbarSize)
    	windowScrollbarSize = 17;
    
    // Remove the scrolling div from the doc
    document.body.removeChild(document.body.lastChild);
    
    scr = null;
    inn = null;
    
    return windowScrollbarSize;

}

function getParentWindow (doc)
{
    if (!doc) return null;
    
    if (isIE()) return doc.parentWindow;
    if (isFirefox()) return doc.defaultView;
    
    return null;
        
}