






        
var NLDate_short_months = new Array("Jan","Feb","Mar",
	                                "Apr","May","Jun","Jul",
	                                "Aug","Sep","Oct","Nov","Dec");
if ( 13 > 12 )
	NLDate_short_months.push();

<!-- version 2014.2 -->

// Begin Prototype.js (http://prototype.conio.net)----------------------------
var Prototype = {
  Version: '1.3.1',
  emptyFunction: function() {}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}

function $$(inputName)
{
    var element = document.getElementById(inputName);

    if (element == null)
    {
        var elements = document.getElementsByName(inputName);
        element = elements != null ? elements[0] : null;
    }
    return element;
}

if (!Function.prototype.apply) {
  // Based on code from http://www.youngpup.net/
  Function.prototype.apply = function(object, parameters) {
    var parameterStrings = new Array();
    if (!object)     object = window;
    if (!parameters) parameters = new Array();

    for (var i = 0; i < parameters.length; i++)
      parameterStrings[i] = 'parameters[' + i + ']';

    object.__apply__ = this;
    var result = eval('object.__apply__(' +
      parameterStrings.join(', ') + ')');
    object.__apply__ = null;

    return result;
  }
}

Object.extend(String.prototype, {
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0].nodeValue;
  }
});

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  }
}

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = Object.extend({
      method:       'post',
      asynchronous: true,
      parameters:   ''
    }, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
	if (url != null)
	{
		this.setOptions(options);
		this.request(url);
	}
  },

  request: function(url, options) {
	if (options != null)
		this.setOptions(options);
	var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      if (this.options.method == 'get')
        url += '?' + parameters;

      this.transport.open(this.options.method, url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
    }
  },

  abort: function() {
    this.transport.abort();
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest','X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type',
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];

    if (event == 'Complete')
      (this.options['on' + this.transport.status]
       || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
       || Prototype.emptyFunction)(this.transport);

    (this.options['on' + event] || Prototype.emptyFunction)(this.transport);

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  }
});

// End Prototype.js-------------------------------------------------------------


NLSimpleAjax = Class.create();
NLSimpleAjax.prototype =
{
    initialize: function()
    {
        this.bIgnoreReponse = false;
    },

    
    sendRequest: function(sUrl, oParameters, onComplete, bIgnoreResponse)
    {
        this.onComplete = onComplete;
	    this.bIgnoreReponse = bIgnoreResponse;
        var sParams = '';
        for (property in oParameters)
		{
            if (sParams.length > 0)
                sParams += '&';
            sParams += property + '=' + oParameters[property];
        }
        this.oAjaxRequest = new Ajax.Request( sUrl,
            {
                method: 'get',
                parameters: sParams,
                onSuccess: function(oXmlHttpRequest) { this.processSuccess(oXmlHttpRequest); }.bind(this)
            });
    },

    processSuccess: function(oXmlHttpRequest)
    {
	    if(this.bIgnoreReponse)
	        return;

        var xndNlResponse = oXmlHttpRequest.responseXML.getElementsByTagName("nlresponse")[0];
        var aAttributes = xndNlResponse.attributes;
        var oResponse = new Object();

        for (var i=0; i < aAttributes.length; i++)
        {
            oResponse[aAttributes[i].name] = aAttributes[i].value;
        }
        if (this.onComplete != null)
            this.onComplete(oResponse["status"], oResponse)
    }
}

/*--------------- NLXSLTransformer class definition ------------*/
function NLXSLTransformer( xsl )
{
	if ( window.XSLTProcessor )
	{
		this.xslprocessor = new XSLTProcessor();
		this.xslprocessor.importStylesheet( xsl );
	}
	else
	{
		var stylesheet = null;
		try	{ stylesheet = new ActiveXObject("Msxml2.XSLTemplate.4.0");	}
		catch( e )	{/* OLC requires at least MSXML v4.0 */	stylesheet = isOffline() ? null : new ActiveXObject("Msxml2.XSLTemplate"); }
		if ( stylesheet != null )
		{
			stylesheet.stylesheet = xsl;
			this.xslprocessor = stylesheet.createProcessor();
		}
	}
}
NLXSLTransformer.prototype.transform =  function( xml, parameters, streamToText, startMode /* only supported in IE. */ )
{
	for ( var i in parameters )
		if ( parameters[ i ] != null )
			eval( this.xslprocessor.setParameter != null ? 'this.xslprocessor.setParameter( null, i, parameters[ i ] )' : 'this.xslprocessor.addParameter( null, i, parameters[ i ] )' );

	var transformed = null;
	if ( window.XSLTProcessor )	/* StartMode not supported in Mozilla. Workaround is to re-design XSL template to use parameters for calling named-templates */
	{
		transformed = this.xslprocessor.transformToDocument( xml );
		if ( streamToText )
			transformed = nlapiSerializeToString( transformed );
	}
	else
	{
		if ( startMode != null )
			this.xslprocessor.setStartMode( startMode );
		this.xslprocessor.input = xml;
		this.xslprocessor.transform( );

		transformed = this.xslprocessor.output;
		if ( isOffline() && transformed != null )	/* Hack to handle encoded machine data in OLC */
		{
	        transformed = transformed.replace(/_COLUMN_DELIMITER_/g,String.fromCharCode(1)).replace(/_ROW_DELIMITER_/g,String.fromCharCode(2));
			transformed = transformed.replace(/_LESSTHAN_SIGN_/g,"&lt;").replace(/_GREATERTHAN_SIGN_/g,"&gt;")
			transformed = transformed.replace(/_LESSTHAN_BRACKET_TAG_/g, "<xsl:text disable-output-escaping='yes'>&lt;");
			transformed = transformed.replace(/_GREATERTHAN_BRACKET_TAG_/g, "&gt;</xsl:text>");
		}
		if ( !streamToText )
			transformed = nlapiSerializeToXML( transformed );
	}
	return transformed;
}
/*--------------- Generic XML processing functions ------------*/

function nsCreateDocument( )
{
	var doc = null;
	if ( document.implementation && document.implementation.createDocument && !(window.ActiveXObject !== undefined))
		doc = document.implementation.createDocument("","", null);
	else
	{
		try	{ doc = new ActiveXObject(isOffline() ? "Msxml2.FreeThreadedDOMDocument.4.0" : "Msxml2.DOMDocument.6.0"); }
		catch ( e )
        {
            try
            {
                /* OLC requires at least Msxml2.FreeThreadedDOMDocument.4.0 for caching and XSLT processing */
                doc = isOffline() ? null : new ActiveXObject("Msxml2.DOMDocument.3.0");
            }
            catch ( e )
            {
                doc = isOffline() ? null : new ActiveXObject("Msxml2.DOMDocument.4.0");
            }
        }
        if ( doc != null )
        {
			doc.async = false;
			doc.resolveExternals = false;
        }
    }
	return doc;
}
function nsInstanceofDocument( object )
{
    var doc = null;
    if ( document.implementation && document.implementation.createDocument)
    {
        if (typeof Document != "undefined")
            return object instanceof Document;
        else 
            return object.implementation && object.implementation.createDocument;
    }
    else
		return object instanceof ActiveXObject && object.resolveExternals != null && object.async != null;
}
function nsSetChildValue( node, field, value, update )
{
	var xmldoc = nsCreateDocument( );
	var textNode = xmldoc.createElement( field );
	if ( !isValEmpty( value ) )
	{   /*-- handle CHR(5) encoded multi-select values --*/
		value = String(value);
		value = value.split( String.fromCharCode( 5 ) ).join( '\n' );
		textNode.appendChild( xmldoc.createTextNode( value ) );
	}

	if ( update )
	{
		var oldNode = nsSelectNode( node, field );
		eval( prior == null ? 'node.appendChild( textNode )' : 'node.replaceChild( textNode, oldNode )' );
	}
	else
		node.appendChild( textNode );
	return textNode;
}
function nsSetChildValues( node, field, values )
{
	if ( values == null )
		return;
	if ( field != null )
		for ( var i = 0; i < values.length; i++ )
			nsSetChildValue( node, field, values[i] );
	else
		for ( var i in values )
			nsSetChildValue( node, i, values[i] );
}
function nsXmlToString( xml )
{
	if ( xml.nodeType == 2 )	/* Special Handling for Attribute Node. XMLSerializer supports Nodes only */
		return xml.nodeName + '=' + xml.nodeValue;
	else if ( window.XMLSerializer && !(window.ActiveXObject !== undefined) )
		return new XMLSerializer().serializeToString( xml );
	else
		return xml.xml
}
function nsStringToXML( text )
{
	var nsDocument = null;
	if ( window.DOMParser && !(window.ActiveXObject !== undefined))
		nsDocument = new DOMParser().parseFromString( text, 'text/xml' )
	else
	{
		nsDocument = nsCreateDocument();
		nsDocument.loadXML( text );
	}
	return nsDocument;
}
function nsGetXMLValue( node )
{
	if ( node.nodeType == 3 || node.nodeType == 4 )	/* Text or CDATA Nodes */
		return node.nodeValue;
    if (node.nodeType == 2 && node.childNodes.length ==0)
        return node.nodeValue;    /*issue 226824, FF 14 nodes.childNodes.length return 0.*/
	if ( node.nodeType == 9 )	/* Document Node (Use root Element instead) */
		node = node.documentElement;

	var value = null;
	var elems = node.childNodes;
	for ( var i = 0; i < elems.length; i++ )
	{
		var elem = elems[ i ];
		if ( elem.nodeType == 3 || elem.nodeType == 4 )	/* Text or CDATA Nodes */
        {
            if (value == null)
                value = elem.nodeValue;
            else
                value += elem.nodeValue;
        }
	}
	return value;
}
function nsGetXMLBoolean( node )
{
    var value = nsGetXMLValue( node );
	return !isValEmpty( value ) && (value.toLowerCase() == 'true' || value == 'T');
}
function nsSelectNodes( node, expr )
{
	var nodes = null;
	var owner = node.ownerDocument != null ? node.ownerDocument : node;
    if ( window.XPathEvaluator )
	{
        var xpe = new XPathEvaluator();
        /* manually resolve default namespace URI in Firefox/Safari (if needed) */
		var resolver = function (prefix) {
            return this.namespaces[prefix];
        }
		resolver.namespaces = new Object();
		if ( nsXmlToString(node).indexOf( 'xmlns' ) != -1 )
		{
			var nodelist = owner.getElementsByTagName("*")
			for ( var j = 0; j < nodelist.length; j++ )
			{
				var attributes = nodelist[j].attributes;
				for ( var i = 0; attributes != null && i < attributes.length; i++ )
				{
					if ( attributes[i].name == 'xmlns' )
						resolver.namespaces["nlapi"] = attributes[i].nodeValue;
					else if ( attributes[i].name.indexOf('xmlns:') == 0 )
						resolver.namespaces[attributes[i].name.substring(6)] = attributes[i].nodeValue;
				}
			}
		}
		var results = xpe.evaluate( expr, node, resolver, XPathResult.ANY_TYPE, null )
        if ( results != null )
		{
			nodes = new Array();
			while ( result = results.iterateNext() )
				nodes[nodes.length]=result;
		}
	}
	else
	{
		/* manually resolve name spaces in IE (if needed) */
		if ( nsXmlToString(node).indexOf( 'xmlns' ) != -1 )
		{
			var namespaces = null;
			owner.setProperty("SelectionLanguage", "XPath");
			var nodelist = owner.getElementsByTagName("*")
			for ( var j = 0; j < nodelist.length; j++ )
			{
				var attributes = nodelist[j].attributes;
				for ( var i = 0; attributes != null && i < attributes.length; i++ )
				{
					if ( attributes[i].name.indexOf('xmlns:') == 0 )
						namespaces = (namespaces != null ? namespaces + " " : "") + attributes[i].xml;
					else if ( attributes[i].name == 'xmlns' )
						namespaces = (namespaces != null ? namespaces + " " : "") + "xmlns:nlapi=\""+ attributes[i].nodeValue+"\"";
				}
			}
			if ( namespaces != null )
				owner.setProperty("SelectionNamespaces", namespaces)
		}
		nodes = node.selectNodes( expr );
	}
	return nodes;
}
function nsSelectNode( node, expr )
{
	var selections = nsSelectNodes( node, expr );
	var selection = selections != null ? selections[0] : null;
	return selection;
}
function nsSelectValues( node, expr )
{
	var selectedValues = new Array();
	var selections = nsSelectNodes( node, expr );
	if ( selections != null )
	{
		selectedValues = new Array();
		for ( var i = 0; i < selections.length; i++ )
			selectedValues[ i ] = nsGetXMLValue( selections[i] );
	}
	return selectedValues;
}
function nsSelectValue( node, expr )
{
	var selections = nsSelectValues( node, expr );
	var selection = selections != null ? selections[0] : null;
	return selection;
}
function nsSelectBoolean( node, expr )
{
    var val = nsSelectValue( node, expr );
    return val == 'T' || val == 'true';
}

/*--------------- End of Generic XML processing functions ------------*/


function switchState( owner )
{
 var plusSign = document.getElementById( owner + "_p");
 var minusSign = document.getElementById( owner + "_m");
 var detailBody = document.getElementById( owner + "_detail");

 var switchState = plusSign.style.display;
 if ( 'none' == switchState )
 {
 	display( plusSign, true );
 	display( minusSign, false );
    display( detailBody, false );
 }
 else
 {
 	display( plusSign, false );
 	display( minusSign, true );
    display( detailBody, true );
 }
 resetDivSizes();
}

function displayNav( bOn )
{
    var divNavPane = document.getElementById('div__nav');
    var divNavTree = document.getElementById('div__nav_tree');

    
    divNavTree.style.display = bOn ? "" : "none";

    
    divNavPane.style.display = "block";
    divNavPane.style.width   = bOn ? "200px" : "22px";

    resetDivSizes();
}

function hideNavigation( doc )
{
   var divTabs = doc.getElementById('div__nav_tree');
   var divTD = doc.getElementById('div__nav');
   display( divTabs, false);

   display( divTD, false );

   resetDivSizes();
}


function NLAppUtil_pinFirstColumnOfTable(sTableToPinId, bPinNoPrintRows)
{
    var ndTable = document.getElementById(sTableToPinId);
    var ndScrolledArea = ndTable.parentNode;

    var ndHeaderHover = document.createElement("div");
    ndHeaderHover.style.margin = "0 0 0 0";
    ndHeaderHover.style.padding = "0 0 0 0";
    ndHeaderHover.style.overflow = "hidden";
    ndHeaderHover.style.height = ndScrolledArea.clientHeight + "px";
    ndHeaderHover.style.width = "auto";
    ndHeaderHover.style.position = "absolute";
    ndHeaderHover.style.top = findPosY(ndTable);
    ndHeaderHover.style.left = 0;

    var ndRowHeader = document.createElement("table");
    ndRowHeader.id = sTableToPinId + "_pin";
    ndRowHeader.cellSpacing = ndRowHeader.cellPadding = 0;

    ndRowHeader.className         = "noprint";
    ndRowHeader.style.border      = "0px solid red";
    ndRowHeader.style.position    = "relative";
    ndRowHeader.style.borderRight = "1px solid #e0f0e0";

    var ndBody = document.createElement("tbody");
    ndRowHeader.appendChild(ndBody);

	var lstRows = ndTable.getElementsByTagName("tr");

    for(var i=0; i<lstRows.length; i++)
    {
        var tr = lstRows[i];
        if((tr.className != "printonly") && (bPinNoPrintRows || (tr.className != "noprint")))
        {
            var ndFirstColumn = tr.getElementsByTagName("td")[0];
            if(ndFirstColumn)
            {
                var trNew = document.createElement("tr");
                var tdNew = document.createElement("td");
                tdNew.className = ndFirstColumn.className;
                tdNew.innerHTML = ndFirstColumn.innerHTML;
                tdNew.style.width = ndFirstColumn.offsetWidth - 5 + "px";
                tdNew.style.height = ndFirstColumn.offsetHeight + "px";
                trNew.appendChild(tdNew);
                ndBody.appendChild(trNew);
            }
        }
    }

    ndHeaderHover.appendChild(ndRowHeader);
    document.body.appendChild(ndHeaderHover);

	
    var fnScroll = (ndScrolledArea.onscroll ? ndScrolledArea.onscroll: function(){});

    ndScrolledArea.onscroll = function()
    {
        fnScroll();
        ndRowHeader.style.top = -ndScrolledArea.scrollTop + "px";
    };

    var fnOnResize = (window.onresize ? window.onresize: function(){});

    window.onresize = function()
    {
        fnOnResize();
        ndHeaderHover.style.top = findPosY(ndTable) + "px";
        ndHeaderHover.style.height = ndScrolledArea.clientHeight + "px";
    };
}

/**
 * This function will apply javascript validation to an oracle password
 **/
function checkoraclepassword(fld1)
{
	var val = fld1.value;
	msg = "";

	if (val.length < 6)
	{
		msg += "Passwords must be at least 6 characters long.\n";
	}
	if (!/[A-Za-z]/.test(val))
	{
		msg += "Passwords must contain at least one letter (A-Z).\n";
	}
	if (!/^[A-Za-z]/.test(val))
	{
		msg += "Passwords must begin with a letter (A-Z).\n";
	}
	if (!/[0-9$#_= \<\>\/\\\+\?\-\(\)\[\]\{\}]/.test(val))
	{
		msg += "Passwords must contain at least one number or special character including the underscore (_), dollar sign ($), and pound sign (#).\n";
	}
	if (!/^[A-Za-z0-9#$_= \<\>\/\\\+\?\-\(\)\[\]\{\}]+$/.test(val))
	{
		msg += "Passwords can only contain alphanumeric characters and the underscore (_), dollar sign ($), and pound sign (#).\n";
	}

	if (msg.length > 0) {
		alert(msg);
		return false;
	} else {
		return true;
	}
}


function checkacctname(fld1)
{
    var val = fld1.value;
    if (!onlydigitsandchars(val))
    {
        alert("Company login names must contain only letters and digits.");
        return false;
    }
    if (val.length < 4)
    {
        alert("Company login names must be at least 4 characters long.");
        return false;
    }
    if (!alphafirst(val))
    {
        alert("Company login names must begin with a letter.");
        return false;
    }
    return true;
}

function checkusername(fld1)
{
    var val = fld1.value;
    if (!onlydigitsandchars(val))
    {
        alert("User names must contain only letters and digits.");
        return false;
    }
    if (val.length < 4)
    {
        alert("User names must be at least 4 characters long.");
        return false;
    }
    if (!alphafirst(val))
    {
        alert("Usernames must begin with a letter.");
        return false;
    }
    return true;
}

function getMachineByName(machineName)
{
    return getMachine(machineName);
}

function getMachine(machineName)
{
    if (window.machines)
        return window.machines[machineName];
    return null;
}


function getFieldSetDisplayText( mach, fldset, linenum, nohtml, sHideLabels )
{
	var sOutput = "";
	if ( nohtml == null )
		nohtml = false;

	var nCount = 0;
	for ( var i = 0; i < mach.countFormElements(); i++)
	{
		if ( mach.getFormElementFieldSet(i) != fldset )
			continue;
		nCount++;

		var curName = mach.getFormElementName(i);
		var curElement = mach.getFormElement(i);
		var curLabel = mach.getFormElementLabel(i);

		var dataCell = linenum == null ? getFormValue(curElement) : getEncodedValue(mach.name, linenum, curName);
		
		if (linenum == null && curElement != null)
		{
			var spanName = mach.name + "_" + (curName.indexOf( '_display' ) == -1 ? curName : mach.getFormElementName( i+1 )) + '_fs';
			var spanObj = document.getElementById( spanName );
			if (spanObj != null && spanObj.style.display == 'none')
			{
				dataCell = "";
			}
		}

		if ( dataCell != null && dataCell.length > 0 )
		{
			var curType = mach.getFormElementType(i);
			var bCheckBox = curType == 'checkbox';
			var bWriteLabel = curLabel.length > 0 && (!bCheckBox || dataCell == 'T');
			var bWriteLineBreak = false;
			if ( bWriteLabel && (sHideLabels == null || sHideLabels.indexOf(curLabel) == -1))
			{
				sOutput += curLabel;
				if ( !bCheckBox )
					sOutput += ": ";
				bWriteLineBreak = true;
			}
			if ( !bCheckBox )
			{
				if ( mach.isElementPopupDisplayField(i) )
				{
					var pos = curName.indexOf("_display");
					var actualDataCell = linenum == null ? getFormValue(mach.getFormElement(i+1)) : getEncodedValue(mach.name, linenum, mach.getFormElementName(i+1));
					if ( pos != -1 && !isValEmpty(actualDataCell) )
					{
						sOutput += dataCell.replace(/\u0005/g, ', ').replace(/\r/g,'').replace(/\n/g, ', ');
						bWriteLineBreak = true;
					}
				}
				else
				{
					bWriteLineBreak = true;
					if ( curType == "select" )
					{
						if ( isMultiSelect( curElement ) )
							sOutput += getmultiselectlisttext( curElement, dataCell );
						else
							sOutput += getlisttext( curElement, dataCell )  ;
					}
					else if (curType == "currency")
						sOutput += format_currency( parseFloat( dataCell ) );
					else if (curType == "radio")
						sOutput += getradiotext( curElement, dataCell );
					else if (curType == "namevaluelist")
						sOutput += getnamevaluelisttext( dataCell , ", " );
                    else if (curType == "timeselector")
                        sOutput += curElement.parentNode.controller.getTextForValue(dataCell);
					// handle all other field types (text, etc) - but never print out the popup multi-select label data
					else if (curType != "slaveselect" && curName.indexOf("_labels") == -1)
						sOutput += dataCell.replace(/\r/g,'').replace(/\r/g,'').replace(/\n/g, ", ");
					else
						bWriteLineBreak = false;
				}
			}
//			debugAlert(curName+','+curType+','+curLabel+','+dataCell+','+bWriteLabel+','+bWriteLineBreak)
			if ( bWriteLineBreak )
				sOutput +=  nohtml ? " " : "<br>";
		}
	}
	return sOutput;
}



window.fieldnamesArray = new Object();



window.haslineitemgroupArray = new Object();

function hasLineItemGroup(machine_name)
{

 if( window.haslineitemgroupArray[machine_name] == null )
  window.haslineitemgroupArray[machine_name] = document.forms['main_form'].elements[machine_name+'data'] != null;
 return window.haslineitemgroupArray[machine_name]

}


function allowAddLines(machine_name)
{
	return hasMachine(machine_name);
}

function hasMachine(machine_name)
{
    return hasLineItemGroup(machine_name) && eval('typeof('+machine_name+'_machine)') != "undefined";
}

function isEditMachine(machine_name)
{
	return getMachine(machine_name) && (getMachine(machine_name).type == EDIT_MACHINE);
}


window.lineitemFieldTypeArray = new Object();

function getEncodedFieldType(machine_name, fieldname)
{
	if ( hasEncodedField(machine_name, fieldname) )
	{
		if ( window.lineitemFieldTypeArray[machine_name] == null || window.lineitemFieldTypeArray[machine_name][fieldname] == null )
		{
			window.lineitemFieldTypeArray[machine_name] = new Object();
			var aFields = splitIntoCells( document.forms['main_form'].elements[machine_name+'fields'].value );
			var aTypes = splitIntoCells( document.forms['main_form'].elements[machine_name+'types'].value )
			for ( var i = 0; i < aFields.length; i++ )
			{
				var type = aTypes[i];
				if (i > 0 && ( type == "slaveselect" || type == "integer" ) && aFields[i-1] == aFields[i]+"_display")
					type = (aTypes[i-1] == "textarea") ? "multiselect" : "select";
				window.lineitemFieldTypeArray[machine_name][aFields[i]] = type;
			}
		}
		return window.lineitemFieldTypeArray[machine_name][fieldname]
	}
	return null;
}


window.lineitemFieldlabelArray = new Object();

function getEncodedFieldLabel(machine_name, fieldname)
{
	if ( hasEncodedField(machine_name, fieldname) )
	{
		if ( window.lineitemFieldlabelArray[machine_name] == null || window.lineitemFieldlabelArray[machine_name][fieldname] == null )
		{
			window.lineitemFieldlabelArray[machine_name] = new Object();
			var aFields = splitIntoCells( document.forms['main_form'].elements[machine_name+'fields'].value );
			var aLabels = splitIntoCells( document.forms['main_form'].elements[machine_name+'labels'].value )
			for ( var i = 0; i < aFields.length; i++ )
			{
				var label = aLabels[i];
				if (i > 0 && aFields[i-1] == aFields[i]+"_display")
					label = aLabels[i-1];
				window.lineitemFieldlabelArray[machine_name][aFields[i]] = label;
			}
		}
		return window.lineitemFieldlabelArray[machine_name][fieldname]
	}
	return null;
}


window.lineitemFieldParentArray = new Object();

function getEncodedFieldParent(machine_name, fieldname)
{
	if ( hasEncodedField(machine_name, fieldname) )
	{
		if ( window.lineitemFieldParentArray[machine_name] == null || window.lineitemFieldParentArray[machine_name][fieldname] == null )
		{
			window.lineitemFieldParentArray[machine_name] = new Object();
			var aFields = splitIntoCells( document.forms['main_form'].elements[machine_name+'fields'].value );
			var aParents = splitIntoCells( document.forms['main_form'].elements[machine_name+'parents'].value )
			for ( var i = 0; i < aFields.length; i++ )
			{
				window.lineitemFieldParentArray[machine_name][aFields[i]] = aParents[i];
			}
		}
		return window.lineitemFieldParentArray[machine_name][fieldname]
	}
	return null;
}



function getFieldLineNum(machine_name, fld)
{
	var fieldnames = getFieldNamesArray(machine_name);
    var fieldname = fld.name;
    var linenum = -1;

	for ( var i = 0; i < fieldnames.length; i++ )
    {
        var re = new RegExp("^"+fieldnames[i]+"([0-9]+)$");
   	    if ( re.test(fieldname) )
        {
            linenum = parseInt(RegExp.$1, 10);
            break;
        }
    }
	return linenum;
}
function getLineItemField(machine_name, fldname, linenum)
{
	var fld = null;
	var formname = machine_name + '_form';
	if ( getEncodedFieldType( machine_name, fldname ) == "radio" )
	{
		var radio = getFormElementViaFormName( formname, fldname );
		fld = radio[linenum-1]
	}
	else
		fld = getFormElementViaFormName( formname, fldname + ( linenum != null ? linenum : '' ) );
	return fld;
}



function getLineCount(machine_name)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.getNumRows();

    
    return doGetLineCount(machine_name);
}

function getLineArray(machine_name)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.getLineArray();

    
    return doGetLineArray(machine_name);
}

function getLineArrayLine(machine_name, linenum)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.getLineArrayLine(linenum);

    
    return doGetLineArrayLine(machine_name, linenum);
}

function setLineArray(machine_name, linearray)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setLineArray(linearray);
    else
        
        doSetLineArray(machine_name, linearray);
}

function setLineArrayLine(machine_name, linenum, linearray)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setLineArrayLine(linenum, linearray);
    else
        
        doSetLineArrayLine(machine_name, linenum, linearray);
}

function hasLineArray(machine_name)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.hasLineArray();

    
    return doHasLineArray(machine_name);
}

function setMachineContentUpdated(machine_name, bUpdated)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setContentUpdated(bUpdated);
}

function clearLineArray(machine_name)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.clearLineArray();
    else
        
        doClearLineArray(machine_name);
}


function Machine_deleteLineItems(name, start, end)
{
    var machine = getMachine(name);
    if (machine)
        return machine.deletelines(start, end);
    else
        return doDeleteLineItems(name, start, end);
}



 function Machine_clearLineItems(name, bNoFocus)
{
    var machine = getMachine(name);
    if (machine)
        return machine.removeAllLines(bNoFocus);
}

function writeLineArray(machine_name)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.writeLineArray();
    else
        
        doWriteLineArray(machine_name);
}

function getEncodedValue(machine_name, linenum, fieldname)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.getFieldValue(fieldname, linenum, true);

    
    return doGetEncodedValue(machine_name, linenum, fieldname);
}

function findEncodedValue(machine_name, fieldname, value)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.findEncodedValue(fieldname, value, true);

    
    return doFindEncodedValue(machine_name, fieldname, value);
}

function setEncodedValue(machine_name, linenum, fieldname, value)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setFieldValue(linenum, fieldname, value);
    else
        
        doSetEncodedValue(machine_name, linenum, fieldname, value);
}

function setEncodedValues(machine_name, linenum, form)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setEncodedValues(linenum, form);
    else
        
        doSetEncodedValues(machine_name, linenum, form);
}

function setFormValues(machine_name, linenum, form, fld_name, firefieldchanged)
{
    var machine = getMachine(machine_name);
    if (machine)
        machine.setFormValues(linenum, form, fld_name, firefieldchanged);
    else
        
        doSetFormValues(machine_name, linenum, form, fld_name, firefieldchanged);
}


function getEncodedFieldPosition(machine_name, fieldname)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.getFieldPosition(fieldname);

    return doGetEncodedFieldPosition(machine_name, fieldname);
}

function hasEncodedField(machine_name, fieldname)
{
    var machine = getMachine(machine_name);
    if (machine)
        return machine.hasEncodedField(fieldname);

	return doHasEncodedField(machine_name, fieldname);
}

function getFieldNamesArray(machine_name)
{
    return doGetFieldNamesArray(machine_name);
}

function syncMachineSegment(mach, frm, fromline, toline)
{
    var machine = getMachine(mach);
    if (machine)
        machine.updateFormElements(fromline, toline);

	if (fromline == -1) fromline = 1;
	if (toline == -1 || toline > document.forms[0].elements['next'+mach+'idx'].value-1) toline = document.forms[0].elements['next'+mach+'idx'].value-1;
	for (var i=fromline;i<=toline;i++)
		setFormValues(mach,i,frm);
}





function doGetLineCount(machine_name)
{
    return doGetLineArray(machine_name) != null ? doGetLineArray(machine_name).length : 0;
}


var MACHINE_NAME_PREPEND = "mch_";

window.linearrayArray = new Array();


function doGetLineArray(machine_name)
{

	var lineArrayIndex = MACHINE_NAME_PREPEND + machine_name;
	if( window.linearrayArray[lineArrayIndex] == null)
	{
		if ( hasLineItemGroup(machine_name) )
			window.linearrayArray[lineArrayIndex] = splitIntoRows( document.forms['main_form'].elements[machine_name+'data'].value );
	}
	return window.linearrayArray[lineArrayIndex];

}

function doGetLineArrayLine(machine_name, linenum)
{

	var linearray = doGetLineArray(machine_name);
	if (linearray[linenum] != null && typeof linearray[linenum] == 'string')
		linearray[linenum] = splitIntoCells(linearray[linenum]);
	return linearray[linenum];

}

function doSetLineArray(machine_name, linearray)
{

	var lineArrayIndex = MACHINE_NAME_PREPEND + machine_name;
	window.linearrayArray[lineArrayIndex] = linearray;

}

function doSetLineArrayLine(machine_name, linenum, line)
{
	var linearray = doGetLineArray(machine_name);

	linearray[linenum] = line;

}

function doHasLineArray(machine_name, linearray)
{
	return window.linearrayArray != null && window.linearrayArray[MACHINE_NAME_PREPEND + machine_name] != null;
}

function doClearLineArray(machine_name)
{
	if( window.linearrayArray != null )
	    window.linearrayArray[MACHINE_NAME_PREPEND + machine_name] = null;
}

function doWriteLineArray(machine_name)
{

	if( doHasLineArray(machine_name) )
	{
		var linearray = doGetLineArray(machine_name);
		doWriteLineArrayData(machine_name, linearray);
	}

}

function doWriteLineArrayData(machine_name, linearray)
{
    if( linearray && linearray.length > 0)
    {
        for (var i=0; i<linearray.length; i++)
            if (linearray[i] != null && typeof(linearray[i]) != 'string')
                linearray[i] = linearray[i].join(String.fromCharCode(1));
        document.forms['main_form'].elements[machine_name+'data'].value = doGetLineArray(machine_name).join(String.fromCharCode(2));
	}
    else
        document.forms['main_form'].elements[machine_name+'data'].value = "";
}

function doGetEncodedValue(machine_name, linenum, fieldname)
{
    var linedata = doGetLineArrayLine(machine_name, linenum-1);
    if( linedata == null )
         return null;
    var i = doGetEncodedFieldPosition(machine_name, fieldname);
     if (i != -1)
       return linedata[i];
    return '';
}

function doFindEncodedValue(machine_name, fieldname, value)
{
    var i = doGetEncodedFieldPosition(machine_name, fieldname);
    if (i == -1)
        return -1;
    for (var linenum=0;linenum < doGetLineCount(machine_name);linenum++)
    {
        var linedata = doGetLineArrayLine(machine_name,linenum);
        if (value == linedata[i])
            return linenum+1;
    }
    return -1;
}

function doSetEncodedValue(machine_name, linenum, fieldname, value)
{
    if ( !hasLineItemGroup(machine_name) )
		return;
    var linedata = doGetLineArrayLine(machine_name,linenum-1 );
    if ( linedata == null ) linedata = new Array();
    var i = doGetEncodedFieldPosition(machine_name, fieldname);
	if (i == -1)
		return;
	linedata[i] = value != null ? String(value) : "";
	doSetLineArrayLine(machine_name,linenum-1,linedata);
}


function doSetEncodedValues(machine_name, linenum, form)
{
    
	if ( !hasLineItemGroup(machine_name) )
		return;
	if ( form == null )
		form = document.forms[machine_name+'_form']

    var fieldnames = doGetFieldNamesArray(machine_name);
    var fieldflags = splitIntoCells( document.forms['main_form'].elements[machine_name+'flags'].value );
    var linedata = new Array(fieldnames.length);
    var olddata = getLineArrayLine(machine_name,linenum-1);

    for (var i=0; i < fieldnames.length; i++)
    {
        if ( isValEmpty( fieldnames[i] ) )
            continue;
        if ((fieldflags[i] & 4) == 0)
            linedata[i] = olddata[i];
        else
        {
            var fld;
			if (form.elements[fieldnames[i]] != null && form.elements[fieldnames[i]][0] != null && form.elements[fieldnames[i]][0].type == "radio")
			{
				for ( var j = 0; j < form.elements[fieldnames[i]].length; j++ )
					if ( form.elements[fieldnames[i]][j].value == linenum )
						fld = form.elements[fieldnames[i]][j]
			}
			else if ((fieldflags[i] & 8) != 0)
                fld = form.elements[fieldnames[i+1]+linenum.toString()+"_display"];
            else
                fld = form.elements[fieldnames[i]+linenum.toString()];
            if (fld != null)
			{
				if (fld.type == "checkbox" || fld.type == "radio")
					linedata[i] = fld.checked ? 'T' : 'F';
				else if (fld.type == "select-one")
					linedata[i] = fld.options[fld.selectedIndex].value;
				else if (fld.type == "textarea")
					linedata[i] = fld.value.replace(/\r/g,'').replace(/\n/g,String.fromCharCode(5));
				else
					linedata[i] = fld.value;
			}
            else
                linedata[i] = olddata[i];
 		}
    }
	setLineArrayLine(machine_name,linenum-1,linedata);
}


function doSetFormValues(machine_name, linenum, form, fld_name, firefieldchanged)
{
    
	if ( !hasLineItemGroup(machine_name) || isEditMachine(machine_name) )
		return;

    var fieldnames = doGetFieldNamesArray(machine_name);
    var fieldflags = splitIntoCells( document.forms['main_form'].elements[machine_name+'flags'].value );
    var linedata = getLineArrayLine(machine_name, linenum-1);;

    for (var i=0; i < fieldnames.length; i++)
    {
        if ( isValEmpty( fieldnames[i] ) || ( fld_name != null && fieldnames[i] != fld_name ) )
            continue;
        if ((fieldflags[i] & 4) != 0)
        {
            var fld;
            if (form.elements[fieldnames[i]] != null && form.elements[fieldnames[i]][0] != null && form.elements[fieldnames[i]][0].type == "radio")
                fld = form.elements[fieldnames[i]][linenum-1];
            else if ((fieldflags[i] & 8) != 0)
                fld = form.elements[fieldnames[i+1]+linenum.toString()+"_display"];
            else
                fld = form.elements[fieldnames[i]+linenum.toString()];
			if ( fld.type == "radio")
 				fld.checked = linedata[i] == 'T';
            else if (fld.type == "checkbox")
                setFormValue(fld, linedata[i] == 'T');
            else if (fld.type == "textarea")
                fld.value = linedata[i].replace(/\u0005/g,'\n');
            else
                setFormValue(fld,linedata[i],null,firefieldchanged);
        }
    }
}


function doDeleteLineItems(name, start, end)
{
    var machine = eval(name+'_machine');
    var linearray = getLineArray(machine.name);
    setLineArray(machine.name,linearray.slice(0,start).concat(linearray.slice(end)));
    machine.setIndex( machine.getNextIndex() - (end - start) );
    return true;
}

function doGetEncodedFieldPosition(machine_name, fieldname)
{
    var fieldnames = doGetFieldNamesArray(machine_name);
	if ( fieldnames != null )
	{

 return fieldnames[fieldname] != null ? fieldnames[fieldname] : -1;

}
	return -1;
}

function doHasEncodedField(machine_name, fieldname)
{
    if (doGetEncodedFieldPosition(machine_name, fieldname) < 0)
		return false;
	return true;
}

function doGetFieldNamesArray(machine_name)
{

    if( window.fieldnamesArray[machine_name] == null )
    {
        if ( document.forms['main_form'].elements[machine_name+'fields'] != null )
        {
            window.fieldnamesArray[machine_name] = splitIntoCells( document.forms['main_form'].elements[machine_name+'fields'].value );
            for (var i=0; i < window.fieldnamesArray[machine_name].length; i++)
                window.fieldnamesArray[machine_name][window.fieldnamesArray[machine_name][i]] = i
        }
    }
 return window.fieldnamesArray[machine_name];

}






function hasEncodedMatrixField(type, fldnam, bucket)
{
    if (hasEncodedField(type, getMatrixFieldName(type, fldnam, bucket)) && getFormElement(document.forms['main_form'], type+"matrixfields" ) != null)
    {
        var matrixfields = getFormValue( document.forms['main_form'].elements[type+"matrixfields"] )
        return matrixfields != null && arrayContains( matrixfields.split( String.fromCharCode(1) ), fldnam )
    }
    return false;
}
function getMatrixHeaderField(type, fldnam, bucket)
{
    if (hasEncodedMatrixField(type, fldnam, bucket))
    {
        return getFormElement( document.forms[type+'_form'], getFormValue( document.forms['main_form'].elements[type+"header"] )+bucket );
    }
    return null;
}
function getMatrixField(type, fldnam, linenum, column)
{
    if (hasEncodedMatrixField(type, fldnam, column) && linenum <= getLineCount(type))
    {
        return getFormElement( document.forms[type+'_form'], getMatrixFieldName(type, fldnam, column)+linenum );
    }
    return null;
}
function getMatrixFieldName(type, fldnam, column)
{
    if (hasLineItemGroup(type))
    {
        return fldnam+"_"+column+"_"
    }
    return null;
}



function chooseAorAn(sField, capsflag)
{
    
    var sReturn = (capsflag ? "A":"a");
    var cVowels = ['a','e','i','o','u'];
    var iLength = cVowels.length;
    sField = sField.toLowerCase();

    for (var i = 0; i < iLength; i++)
    {
      if (sField.charAt(0) == cVowels[i])
      {
        sReturn = sReturn + "n";
        break;
      }
    }

    return sReturn;
}

function dollars_string(amount)
{
    var temp = amount;
    DigitStrings = new Array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
    TeenStrings = new Array('ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eightteen', 'nineteen');
    DecadeStrings = new Array('zero', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety');
    result = '';
    if (temp >= 1000)
    {
        result = result + dollars_string(Math.floor(temp/1000)) + 'thousand ';
        temp = temp % 1000;
    }
    if (temp >= 100)
    {
        result = result + DigitStrings[Math.floor(temp/100)] + ' hundred ';
        temp = temp % 100;
    }
    if (temp >= 20)
    {
        result = result + DecadeStrings[Math.floor(temp/10)] + ' ';
        temp = temp % 10;
    }
    if (temp >= 10)
    {
        result = result + TeenStrings[Math.floor(temp-10)] + ' ';
        temp = temp - Math.floor(temp);
    }
    else if ((amount == 0) || (temp > 0))
    {
        result = result + DigitStrings[Math.floor(temp)] + ' ';
        temp = temp - Math.floor(temp);
    }
    return result;
}

function isUpperCase(ch)
{
    for (var i=65;i<=90;i++)
	{
        if (unescape('%' + i.toString(16)) == ch)
            return true;
    }
    return false;
}

/**
 * Given some text and a zero-based offest into it, this returns the human-readable character position as an array
 * of [line,column], both as 1-based values.
 */
function char_pos_to_line_col(text, pos)
{
	var i = 0;
	var iLfs = 0;
	var iLfPos = 0;
	while (i < pos)
	{
		var c = text.charAt(i);
		if (c == '\r')
		{
			iLfs++;
			iLfPos = i;
			if (i+1 < pos && text.charAt(i+1) == '\n')
				i++;
		}
		i++;
	}
	return new Array(iLfs+1, pos-iLfPos);
}


function validate_html(field, val_type)
{
	var doalert = true;
	if (field.value == null || field.value.length == 0 || val_type == null)
    {
        NS.form.setValid(true);
        return true;
    }

    html = field.value.toLowerCase().replace(/\n/g,"").replace(/\t/g," ");
    var validflag = true;
    var err = '';

	
    if (val_type == 'html')
    {
		if (html.indexOf('<html') == -1)
			err = "HTML document must begin with an <HTML> tag.";
		else if (html.indexOf('</html') == -1)
			err = "HTML document must end with a </HTML> tag.";
		else if (html.indexOf('</html') < html.indexOf('<html') || html.indexOf('</html') < html.lastIndexOf('<'))
			err = "</HTML> tag is in the wrong place.";
		else if (html.indexOf('<body') == -1)
			err = "HTML document is missing </BODY> tag.";
		else if (html.indexOf('<body') < html.indexOf('<html'))
			err = "<BODY> tag is in the wrong place.";
		else if (html.indexOf('</body') == -1)
			err = "HTML document is missing </BODY> tag.";
		else if (html.indexOf('</body') < html.indexOf('<body') || html.indexOf('</body') > html.indexOf('</html'))
			err = "<BODY> tag is in the wrong place.";
		else
			val_type = "table";
    }
    else
    {
		if (html.indexOf('<html') != -1 || html.indexOf('</html') != -1 || html.indexOf('<body') != -1 || html.indexOf('</body') != -1)
		{
			err = "Only an HTML fragment is expected here, not a whole HTML document.  There should be no <HTML> or <BODY> tags.";
		}
    }

	var index = 0;
	var len = 0;
    if (err == '')
    {
		var expectedtaglist = val_type.split(",");
		var expectedtags = "";
		for (var i = 0; i < expectedtaglist.length; i++) { expectedtags += "<"+expectedtaglist[i]+">" };
		var newindex;
		var bFirst = true;
		var iNestLevel = 0;
		var scriptSave;
		var attributeIdx;
		
		while ((newindex = html.indexOf("<", index)) != -1)
		{
			if (newindex < attributeIdx) newindex = attributeIdx;
			index = newindex+1;
			var tag = html.substring(newindex);
			if (tag.indexOf(">") != -1)
				tag = tag.substring(0, tag.indexOf(">"));
			if (tag.indexOf(" ") != -1)
				tag = tag.substring(0, tag.indexOf(" "));

			
			if (tag == "<!--")
			{
				index = html.indexOf("-->", index);
				if (index == -1) index = html.length;
				continue;
			}

			
			if (tag.substring(0,2) == "<"+"%")
			{
				var endindex = html.indexOf("%"+">", index);
				var errpos = char_pos_to_line_col(html,index-1);
				if (endindex == -1)
				{
					err="Missing substitution closing tag sequence %> for open tag at line "+errpos[0]+" column "+errpos[1]+"";
					break;
				}
				index = endindex;
				continue;
			}

			tag += ">"
			len = tag.length;

			
			attributeIdx = newindex+len-1;
			var openQuoteIdx;
			var bInSingQuot = false;
			var bInDoubQuot = false;
			while (attributeIdx < html.length)
			{
				var c = html.charAt(attributeIdx);
				if (c == '\\') { attributeIdx+=2; continue; }
				else if (c == '\'') { if (!bInDoubQuot) {bInSingQuot=!bInSingQuot; if (bInSingQuot)openQuoteIdx=attributeIdx;} }
				else if (c == '\"') { if (!bInSingQuot) {bInDoubQuot=!bInDoubQuot; if (bInDoubQuot)openQuoteIdx=attributeIdx;} }
				else if (c == '>' && !(bInSingQuot || bInDoubQuot)) { break; }
				attributeIdx++;
			}
			if (bInSingQuot || bInDoubQuot)
			{
				index = openQuoteIdx+1;
				len = 1;
				err = "Missing closing quote on tag attribute at character "+(index-newindex)+" for:\n"+html.substring(newindex, attributeIdx+1);
				break;
			}

			
			if (tag != "<td>" && tag != "</td>"
			 && tag != "<tr>" && tag != "</tr>"
			 && tag != "<table>" && tag != "</table>"
			 && tag != "<script>" && tag != "</script>")
				continue;

			
			if (tag.substring(0,2) == "</")
				iNestLevel--;
			else
			    iNestLevel++;

			if (iNestLevel < 0)
			{
				var errpos = char_pos_to_line_col(html,newindex);
				err = "There are too many closing table tags due to tag "+tag.toUpperCase()+" at line "+errpos[0]+" column "+errpos[1]+"";
				break;
			}

			
			if (bFirst)
			{
				if (tag != '<script>' && tag != '</script>')
				{
					bFirst = false;
					if (expectedtags.indexOf(tag) == -1)
					{
						if (expectedtags.indexOf('><') != -1)
						{
							var list = expectedtags.replace(/></g,'> or <');
							err = "The first table tag in your HTML must be one of "+list+", not "+tag.toUpperCase()+"";
						}
						else
							err = "The first table tag in your HTML must be a "+expectedtags.toUpperCase()+" tag, not "+tag.toUpperCase()+".";
						break;
					}
				}
			}
			else
			{
				if (expectedtags.indexOf(tag) == -1)
				{
					var list = expectedtags.toUpperCase().replace(/></g,'> or <');
					var errpos = char_pos_to_line_col(html,newindex);
					err = "Expected "+list+" at line "+errpos[0]+" column "+errpos[1]+", but found a "+tag.toUpperCase()+" tag";
					break;
				}
			}

			
			if (tag == "<table>" || tag == "</tr>")
			{
				expectedtags = "</table><tr><script>";
			}
			else if (tag == "<td>" || tag =="</table>")
			{
				expectedtags = "</td><table><script>";
			}
			else if (tag == "<tr>" || tag == "</td>")
			{
				expectedtags = "</tr><td><script>";
			}
			else if (tag == "<script>")
			{
				scriptSave = expectedtags; expectedtags = "</script>";
			}
			else if (tag == "</script>")
			{
				expectedtags = scriptSave; scriptSave = "";
			}
		}

		if (err == '' && iNestLevel > 0)
		{
			err = "Not all table tags were closed ("+iNestLevel+").  Your HTML is missing a closing "+expectedtags.substring(0, expectedtags.indexOf('>'))+"> tag at the end";
		}
    }

    if (err != '')
    {
        if (doalert)
			alert(err);
		validflag = false;
		setSelectionRange(field, index-1, index+len-1);
    }

    return validflag;
}

function validate_tag(str)
{
	if (str == null || str=='') return true;
	if (str.length>=2 && str.substring(0,2)=="__") return false;
    var re = new RegExp("([A-Za-z_][A-Za-z0-9_]*)");
    return (re.exec(str)!=null && RegExp.$1==str);
}

function modifydate(d, val, mmyyyy)
{
    
    if (typeof window.weekstart == "string")
        window.weekstart = parseInt(window.weekstart);

    timenow = d;
    
    var v = val.split(",");
    var num = 0;
    for (var i=0; i<3; i++)
    {
        if (v[i] == "-")
        {
            continue;
        }
        else if (v[i].charAt(0) == "-" || v[i].charAt(0) == "+")
        {
            num = parseInt(v[i],10);
            if (i==0) 
                adddays(timenow, num);
            else if (i==1)
                addmonths(timenow, num);
            else if (i==2)
                nlSetFullYear(timenow,nlGetFullYear(timenow)+num);
        }
        else
        {
            num = parseInt(v[i],10);
            if (i==0)
                timenow.setDate(num);
            else if (i==1)
                timenow.setMonth(num);
            else if (i==2)
                nlSetFullYear(timenow,num);
        }
    }
    if (v[3] == "0"||v[3] == "1"||v[3] == "2")
    {
        var qstart = parseInt(v[3],10);
        num = timenow.getMonth();
        addmonths(timenow, 0-((num-qstart+3)%3));
    }
    if (v[4] == "Y")
    {
        adddays(timenow,-1);
    }
    if (v[5] == "E")
    {
        
        num = timenow.getDay(); 
        adddays(timenow, ((5+window.weekstart-num)%7));
    }
    else if (v[5] == "B")
    {
        
        num = timenow.getDay(); 
        adddays(timenow, -((num+8-window.weekstart) % 7));
    }
    else if (v[5] == "Z")
    {
        
        num = timenow.getDay(); 
        adddays(timenow, ((7-num)%7));
    }
    else if (v[5] == "A")
    {
        
        num = timenow.getDay(); 
        adddays(timenow, -((6+num) % 7));
    }
    else if (v[5] == "C")
    {
        

    }
    return (mmyyyy ? getmmyydatestring(timenow,NLDate_short_months) : getdatestring(timenow));
}

function delta(iDelta)
{
    return iDelta > 0 ? "+"+iDelta : iDelta == 0 ? "-" : iDelta;
}



function nlutil_getmodifieddate(type,which,fm,mmyyyy,datetoday)
{
    var curdate = new Date();
    if ( datetoday != null ) {


        curdate = new Date(datetoday);
    }

    if (type=="ALL")
        return "";
    if (type.substr(0,2) == 'SO')
    {
        type = type.substr(2);
        which = 1;
    }

    var timenow = new Date();
    if (type.substr(1,3) == 'AGO' || type.substr(1,2) == 'FN')
    {
        var unit = type.substr(0,1);
        var past = type.substr(1,3) == 'AGO';
        var count = parseInt(type.substr(past ? 4 : 3));
        var sign = past ? "-" : "+";
        if (unit == "D")
            modifier = sign+count+",-,-,N,N,-";
        else if (unit == "W")
            modifier = sign+count*7+",-,-,N,N,-";
        else if (unit == "M")
            modifier = "-,"+sign+count+",-,N,N,-";
        else if (unit == "Q")
            modifier = "-,"+sign+count*3+",-,N,N,-";
        else if (unit == "Y")
            modifier = "-,-,"+sign+count+",N,N,-";
    }
    else if (type=="TODAY")
        modifier =  (which==1 ? "-,-,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="OD")
        modifier =  (which==1 ? "-1,-,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="TMTD")
        modifier =  (which==1 ? "1,-,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="OY")
        modifier =  (which==1 ? "+1,-,-1,N,N,-" : "-,-,-,N,N,-");
	else if (type=="OYBL")
		modifier =  (which==1 ? "+1,-,-2,N,N,-" : "-,-,-1,N,N,-");
    else if (type=="OQ")
        modifier =  (which==1 ? "+1,-3,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="OH")
        modifier =  (which==1 ? "+1,-6,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="YESTERDAY")
        modifier =  (which==1 ? "-1,-,-,N,N,-" : "-1,-,-,N,N,-");
    else if (type=="TOMORROW")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "+1,-,-,N,N,-");
    else if (type=="OW")
        modifier =  (which==1 ? "-6,-,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="TW")
        modifier =  (which==1 ? "-,-,-,N,N,B" : "-,-,-,N,N,E");
    else if (type=="LW")
        modifier =  (which==1 ? "-7,-,-,N,N,B" : "-7,-,-,N,N,E");
    else if (type=="LWTD")
        modifier =  (which==1 ? "-7,-,-,N,N,B" : "-7,-,-,N,N,-");
    else if (type=="TWTD")
        modifier =  (which==1 ? "-,-,-,N,N,B" : "-,-,-,N,N,-");
    else if (type=="TY")
        modifier =  (which==1 ? "1,0,-,N,N,-" : "31,11,-,N,N,-");
    else if (type=="TM")
        modifier =  (which==1 ? "1,-,-,N,N,-" : "1,+1,-,N,Y,-");
    else if (type=="OM")
        modifier =  (which==1 ? "+1,-1,-,N,N,-" : "-,-,-,N,N,-");
    else if (type=="LM")
        modifier =  (which==1 ? "1,-1,-,N,N,-" : "1,-,-,N,Y,-");
    else if (type=="LMTD")
        modifier =  (which==1 ? "1,-1,-,N,N,-" : "-,-1,-,N,N,-");
    else if (type=="NW")
        modifier =  (which==1 ? "+7,-,-,N,N,B" : "+7,-,-,N,N,E");
    else if (type=="N4W")
        modifier =  (which==1 ? "+7,-,-,N,N,B" : "+29,-,-,N,N,E");
    else if (type=="NM")
        modifier =  (which==1 ? "1,+1,-,N,N,-" : "1,+2,-,N,Y,-");
    else if (type=="NOW")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "+7,-,-,N,N,-");
    else if (type=="NOM")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "-,+1,-,N,N,-");
    else if (type=="NOQ")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "-,+3,-,N,N,-");
    else if (type=="NOH")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "-,+6,-,N,N,-");
    else if (type=="NOY")
        modifier =  (which==1 ? "+1,-,-,N,N,-" : "-,-,+1,N,N,-");
    else if (type=="SMLFQ")
        modifier =  (which==1 ? "1,-3,-,N,N,-" : "1,-2,-,N,Y,-");
    else if (type=="SMFQBL")
        modifier =  (which==1 ? "1,-6,-,N,N,-" : "1,-5,-,N,Y,-");
    else if (type=="SMLFY")
        modifier =  (which==1 ? "1,-,-1,N,N,-" : "1,+1,-1,N,Y,-");
    else if (type=="SWLFY")
        modifier =  (which==1 ? "-,-,-1,N,N,B" : "-,-,-1,N,N,E");
    else if (type=="SDLFY")
        modifier =  (which==1 ? "-,-,-1,N,N,-" : "-,-,-1,N,N,-");
	else if (type=="SDLW")
		modifier =  (which==1 ? "-7,-,-,N,N,-" : "-7,-,-,N,N,-");
	else if (type=="SDLM")
		modifier =  (which==1 ? "-,-1,-,N,N,-" : "-,-1,-,N,N,-");
	else if (type=="SDLFQ")
		modifier =  (which==1 ? "-,-3,-,N,N,-" : "-,-3,-,N,N,-");
	else if (type=="SDWBL")
		modifier =  (which==1 ? "-14,-,-,N,N,-" : "-14,-,-,N,N,-");
	else if (type=="SDMBL")
		modifier =  (which==1 ? "-,-2,-,N,N,-" : "-,-2,-,N,N,-");
	else if (type=="SDFQBL")
		modifier =  (which==1 ? "-,-6,-,N,N,-" : "-,-6,-,N,N,-");
    else if (type=="SMFYBL")
        modifier =  (which==1 ? "1,-,-2,N,N,-" : "1,+1,-2,N,Y,-");
    else if (type=="SWFYBL")
        modifier =  (which==1 ? "-,-,-2,N,N,B" : "-,-,-2,N,N,E");
    else if (type=="SDFYBL")
        modifier =  (which==1 ? "-,-,-2,N,N,-" : "-,-,-2,N,N,-");
    else if (type=="SMLFQTD")
        modifier =  (which==1 ? "1,-3,-,N,N,-" : "-,-3,-,N,N,-");
    else if (type=="SMLFYTD")
        modifier =  (which==1 ? "1,-,-1,N,N,-" : "-,-,-1,N,N,-");
    else if (type=="TRQ")
        modifier =  (which==1 ? "1,-,-,N,N,-" : "1,+3,-,N,Y,-");
    else if (type=="PRQ")
        modifier =  (which==1 ? "1,-2,-,N,N,-" : "1,+1,-,N,Y,-");
    else if (type=="LRQ")
        modifier =  (which==1 ? "1,-3,-,N,N,-" : "1,-,-,N,Y,-");
    else if (type=="TRH")
        modifier =  (which==1 ? "1,-,-,N,N,-" : "1,+6,-,N,Y,-");
    else if (type=="PRH")
        modifier =  (which==1 ? "1,-5,-,N,N,-" : "1,+1,-,N,Y,-");
    else if (type=="LRH")
        modifier =  (which==1 ? "1,-6,-,N,N,-" : "1,-,-,N,Y,-");
    else if (type=="TRY")
        modifier =  (which==1 ? "1,-,-,N,N,-" : "1,+12,-,N,Y,-");
    else if (type=="PRY")
        modifier =  (which==1 ? "1,-11,-,N,N,-" : "1,+1,-,N,Y,-");
    else if (type=="LRY")
        modifier =  (which==1 ? "1,-12,-,N,N,-" : "1,-,-,N,Y,-");
    else if (type=="TBW")
        modifier =  (which==1 ? "-,-,-,N,N,A" : "-,-,-,N,N,Z");
    else if (type=="LBW")
        modifier =  (which==1 ? "-7,-,-,N,N,A" : "-7,-,-,N,N,Z");
    else if (type=="NBW")
        modifier =  (which==1 ? "+7,-,-,N,N,A" : "+7,-,-,N,N,Z");
    else if (type=="WBL")
        modifier =  (which==1 ? "-14,-,-,N,N,B" : "-14,-,-,N,N,E");
    else if (type=="WAN")
        modifier =  (which==1 ? "+14,-,-,N,N,B" : "+14,-,-,N,N,E");
    else if (type=="MBL")
        modifier =  (which==1 ? "1,-2,-,N,N,-" : "1,-1,-,N,Y,-");
    else if (type=="MAN")
        modifier =  (which==1 ? "1,+2,-,N,N,-" : "1,+3,-,N,Y,-");
    else if (type=="MB")
		modifier =  (which==1 ? "1,-3,-,N,N,-" : "1,-2,-,N,Y,-");
	else if (type=="MBTD")
		modifier =  (which==1 ? "1,-3,-,N,N,-" : "-,-3,-,N,N,-");
    else if (type=="WBLTD")
        modifier =  (which==1 ? "-14,-,-,N,N,B" : "-14,-,-,N,N,-");
    else if (type=="WANTD")
        modifier =  (which==1 ? "+14,-,-,N,N,B" : "+14,-,-,N,N,-");
    else if (type=="MBLTD")
        modifier =  (which==1 ? "1,-2,-,N,N,-" : "-,-2,-,N,N,-");
    else if (type=="MANTD")
        modifier =  (which==1 ? "1,+2,-,N,N,-" : "-,+2,-,N,N,-");
    else if (type=="LMLFQ")
        modifier =  (which==1 ? "1,-4,-,N,N,-" : "1,-3,-,N,Y,-");
	else if (type=="LMFQBL")
		modifier =  (which==1 ? "1,-7,-,N,N,-" : "1,-6,-,N,Y,-");
    else if (type=="LMLFY")
        modifier =  (which==1 ? "1,-1,-1,N,N,-" : "1,-,-1,N,Y,-");
    else if (type=="CUSTOM")
        modifier =  (which==1 ? "-,-,-,-,N,-" : "-,-,-,-,N,-");
    else if (type=="")
        modifier =  (which==1 ? "" : "");
    else if (type.search("FQ")!=-1)
    {
        var curmonth = curdate.getMonth();
        var monthmod=0;
        var yearmod;
        var endmodifier;
        if (which==1)
        {
            modifier = "1,";
            yearmod = (type == "SFQLFY" || type == "SFQLFYTD" || type == "PMSFQLFY" || type == "LFQLFY") ? "-1" : "-";
            endmodifier = yearmod+","+(fm%3)+",N,-";
            if (type=="LFQTD" || type=="LFQ" || type=="LFQLFY" || type=="PMLFQ")
                monthmod +=  -3;
            else if (type=="TFQTD" || type=="SFQLFYTD" || type =="PMTFQ")
                monthmod += 0;
            else if (type=="TFQ" || type == "SFQLFY")
                monthmod += 0;
            else if (type=="NFQ")
                monthmod += 3;
            else if (type=="FQBL" || type=="FQBLTD")
                monthmod += -6;
            else if (type=="FQB" || type=="FQBTD")
                monthmod += -9;
        }
        else
        {
            if (type=="LFQTD" || type=="TFQTD" || type=="SFQLFYTD" || type=="FQBLTD" || type=="FQBTD")
            {
                modifier = "-,";
                yearmod = type=="SFQLFYTD" ? "-1" : "-"
                endmodifier = yearmod+",N,N,-";
            }
            else if (type=="PMTFQ" || type=="PMLFQ" || type=="PMSFQLFY")
            {
                modifier = "1,";
                yearmod = type=="PMSFQLFY" ? "-1" : "-";
                endmodifier = yearmod+",N,Y,-";
            }
            else
            {
                modifier = "1,";
                yearmod = type=="SFQLFY" || type=="LFQLFY" ? "-1" : "-"
                endmodifier = yearmod+","+(fm%3)+",Y,-";
            }
            if (type=="TFQTD" || type=="LFQ" || type=="SFQLFYTD" || type =="LFQLFY"||type=="PMTFQ"||type=="PMSFQLFY")
                monthmod =  0; 
            else if (type=="LFQTD" || type == "FQBL" || type=="PMLFQ")
                monthmod += -3;
            else if (type=="TFQ" || type=="SFQLFY")
                monthmod += 3;
            else if (type=="FQBLTD")
                monthmod += -6;
            else if (type=="NFQ")
                monthmod +=  6;
            else if (type=="FQB")
                monthmod += -6;
            else if (type=="FQBTD")
                monthmod += -9;
        }

        modifier += delta(monthmod)+",";

        modifier += endmodifier;
    }
    else if (type.search("FH")!=-1)
    {
        var curmonth = curdate.getMonth();
        var monthmod = curmonth%6 > fm%6 ? fm%6-curmonth%6 : curmonth%6-fm%6;
        var yearmod;
        var endmodifier;
        if (which==1)
        {
            modifier = "1,";
            yearmod = (type == "SFHLFY" || type == "SFHLFYTD" || type == "PMSFHLFY" || type == "LFHLFY") ? "-1" : "-";
            endmodifier = yearmod+",N,N,-";
            if (type=="LFHTD" || type=="LFH" || type=="LFHLFY" || type=="PMLFH")
                monthmod +=  -6;
            else if (type=="TFHTD" || type=="SFHLFYTD" || type =="PMTFH")
                monthmod += 0;
            else if (type=="TFH" || type == "SFHLFY")
                monthmod += 0;
            else if (type=="NFH")
                monthmod += 6;
            else if (type=="FHBL" || type=="FHBLTD")
                monthmod += -12;
        }
        else
        {
            if (type=="LFHTD" || type=="TFHTD" || type=="SFHLFYTD" || type=="FHBLTD")
            {
                modifier = "-,";
                yearmod = type=="SFHLFYTD" ? "-1" : "-"
                endmodifier = yearmod+",N,N,-";
            }
            else if (type=="PMTFH" || type=="PMLFH" || type=="PMSFHLFY")
            {
                modifier = "1,";
                yearmod = type=="PMSFHLFY" ? "-1" : "-";
                endmodifier = yearmod+",N,Y,-";
            }
            else
            {
                modifier = "1,";
                yearmod = type=="SFHLFY" || type=="LFHLFY" ? "-1" : "-"
                endmodifier = yearmod+",N,Y,-";
            }
            if (type=="TFHTD" ||  type=="SFHLFYTD" || type=="PMTFH"||type=="PMSFHLFY")
                monthmod =  0; 
            else if (type=="LFH" || type =="LFHLFY")
                monthmod += 0;
            else if (type=="LFHTD" || type=="PMLFH")
                monthmod = -6;
            else if (type == "FHBL")
                monthmod += -6;
            else if (type=="TFH" || type=="SFHLFY")
                monthmod += 6;
            else if (type=="FHBLTD")
                monthmod = -12;
            else if (type=="NFH")
                monthmod +=  12;
        }

        modifier += delta(monthmod)+",";

        modifier += endmodifier;
    }
    else if (type.search("FY")!=-1)
    {
        var curmonth = curdate.getMonth();
        var yearmod = (curmonth< fm) ? -1 : 0;
        var endmodifier;
        if (which==1)
        {
            modifier = "1,"+fm+",";
            endmodifier = "N,N,-";
            if (type=="LFYTD" || type=="LFY" || type=="PMLFY" || type=="PQLFY")
                yearmod +=  -1;
            else if (type=="TFYTD" || type=="TFY" || type=="PMTFY" || type=="PQTFY")
                yearmod += 0;
            else if (type=="NFY")
                yearmod +=  1;
            else if (type=="FYBL" || type=="FYBLTD")
                yearmod +=  -2;
			else if (type=="FYB" || type=="FYBTD")
 				yearmod +=  -3;
        }
        else
        {
            if (type=="LFYTD" || type=="TFYTD" || type=="FYBLTD" || type=="FYBTD")
            {
                modifier = "-,-,";
                endmodifier = "N,N,-";
            }
            else if (type=="PMTFY"  || type=="PMLFY")
            {
                modifier = "1,-,";
                endmodifier = "N,Y,-";
            }
            else if (type == "PQTFY" || type=="PQLFY")
            {
                modifier = "1,-,";
                endmodifier = (fm %3) +",Y,-";
            }
            else
            {
                modifier = "1,"+fm+",";
                endmodifier = "N,Y,-";
            }
            if (type=="TFYTD" || type=="PMTFY" || type=="PQTFY")
                yearmod =  0; 
            else if (type=="LFY")
                yearmod +=  0;
            else if (type=="FYBL")
                yearmod += -1;
            else if (type=="LFYTD" || type=="PMLFY" || type=="PQLFY")
                yearmod = -1;
            else if (type=="FYBLTD")
                yearmod = -2;
			else if (type=="FYBTD")
				yearmod = -3;
            else if (type=="TFY")
                yearmod += 1;
            else if (type=="NFY")
                yearmod +=  2;
			else if (type=="FYB")
				yearmod +=  -2;
        }

        modifier += delta(yearmod)+",";

        modifier += endmodifier;
    }
    else
        return "";
    return modifydate(curdate, modifier,mmyyyy);
}

// ================================================== TIME SELECTORS ==================================================


function getTimeSelectorRange(timeSelectorID, fiscalCalendarID, timeSelectors)
{
    if (!fiscalCalendarID)
        fiscalCalendarID = document.currentFCId;
    if (!timeSelectors)
        timeSelectors = document.timeSelectors;

    var timeSelData = timeSelectors[timeSelectorID];
    if (timeSelData)
    {
        var range = ('start' in timeSelData) ? timeSelData : timeSelData[fiscalCalendarID];
        if (range)
            return range;
    }
    return {start: null, end: null};
}

function setDatePeriodField(field, value)
{
    if (!field)
        return;
    if (isNLDropDown(field))
    {
        if (value)
            setSelectValue(field, value);
        else
            getDropdown(field).setText('', true);
    }
    else
        field.value = value;
}

// =============================================== End of TIME SELECTORS ==============================================

function createTDWindow(dest)
{
  var wide = screen.width*(0.35);
  var high = screen.height*(0.3);
  if(wide<150 || high<150)
  {
    wide = 150;
    high = 150;
  }
  var leftpos = screen.width-(wide+20);
  var toppos =  screen.height-(high+60);
  window.open(dest,'test','scrollbars=yes,width='+wide+',height='+high+',left='+leftpos+',top='+toppos);
}

function nlFieldHelpEdit(p,f,fld)
{
    nlOpenWindow('/core/help/admin/helpfieldeditform.nl?perm='+p+'&field='+f,'fieldhelpedit',1024,450,fld);
    return false;
}

function displayHelpSearch(sSearchString)
{
    var searchwindow = window.open('/core/help/helpindex.nl?searchstring='+sSearchString,'helpSearch','');
    searchwindow.focus();
    return false;
}

function nlCustomHelp(id)
{
    var customwindow = window.open('/core/help/customhelp.nl?htext='+id,'customhelp','scrollbars=no,width=350,height=150');
    customwindow.focus();
    return false;
}

function popupMainPageHelp()
{
    try
    {
        var helpAnchor = document.getElementById('main_help_anchor');
        if(helpAnchor != null)
        {
            helpAnchor.onclick();
        }
    }
    catch(e)
    {
        
    }
}


window.helpBaseUrl='/help/en_US/Output';
var ERR_HELP_SESSION_TIMEOUT_MSG = 'Help is unavailable because your connection has timed out.\n This help window will be closed. Please log into the application and open the help window again.';


function nlPopupHelp(taskId)
{
	
    var url;
    if(taskId.indexOf("uber_")==0)
        url = '/app/help/helpcenter.nl?uber_='+taskId.substring(5);
    else
        url = '/app/help/helpcenter.nl?topic='+taskId;
    var newWin = window.open(url,'popuphelp','location=yes,toolbar=yes,menubar=yes,scrollbars=yes,resizable=yes,height='+getDocumentHeight()+',width='+getDocumentWidth());
    newWin.focus();
}

function nlPopupHelpEdit(taskId)
{
    var dest = '/core/help/helpadmin.nl?taskid='+taskId;
    var newWin = window.open(dest,'helpedit','toolbar=yes,menubar=yes,scrollbars=yes,location=yes,resizable=yes');
    newWin.focus();
}

function nlPopupGuides(role_name)
{
    var parms= 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0';
    var dest='/images/guide/quicklooks.html?'+role_name;

    screenx = top.screenLeft;
    screeny = top.screenTop;

    var newWin = window.open(dest,'popupguide',parms + ',left='+screenx+',top='+screeny+',height=410,width=800');

    var offsetX = screenx - newWin.screenLeft + 30;
    var offsetY = screeny - newWin.screenTop + 30;
    newWin.moveBy(offsetX, offsetY);

    newWin.focus();
}

function nlPopupGuide(role_name)
{
    minwinh = 768;
    minwinw = 1024;
    minbarw = 300;
    screenh = screen.height;
    screenw = screen.width;
    windowh = outerHt();
    windoww = outerWd();

    screenx = window.screenLeft;
    screeny = window.screenTop;


    neww = windoww;
    if (neww < minwinw )
        neww = minwinw;
    if (neww+minbarw > screenw - screenx)
        newx = screenw - (neww+minbarw);
    else
        newx = screenx;
    if (newx < -4) newx = -4;

    if (minwinh > screenh - screeny)
        newy = screenh - minwinh;
    else
        newy = screeny;

    newy = newy -121;  //adjust

    if (newy < -4) newy = -4;

    if (windowh < minwinh)
        newh = minwinh;
    else
        newh = windowh;

    if (windoww < minwinw)
        neww = minwinw;
    else
        neww = windoww;

     if (screenw - neww < minbarw)
        neww = screenw-minbarw;

    newh = newh ;

    resizeTo(neww,newh);
    moveTo(newx,newy);

    windowh = getDocumentHeight();
    windoww = getDocumentWidth();
    screenx = this.screenLeft;
    screeny = this.screenTop;

    var parms;
    parms= 'toolbar=no';
    parms += ',statusbar=no';
    parms += ',menubar=no';
    h = newh+50;
    x = newx+neww-4;
    dest='/images/guide/quicklooks.html?'+role_name;
    var newWin = window.open(dest,'popupguide',parms + ',resizableresizable=no,left='+x+',top='+newy+',height=700,width='+minbarw);
    newWin.focus();
}


function setTextUnderline(val, bSet)
{
	var n = val.className.indexOf('hover');
	if (n >= 0 && bSet == false)
	{
		val.className = val.className.substring(0,n);
	}
	else if (n < 0 && bSet == true)
	{
		val.className += 'hover';
	}
	return true;
}

function syncSelectSlaveOptions(sel,optionsString,optionText,curValue)
{
    deleteAllSelectOptions(sel,parent);
    if (optionsString != null && optionsString.length > 0)
    {
        var selOptions = optionsString.split(String.fromCharCode(5));
        var hasCur = false;
        for (var i=0;i < selOptions.length;i++)
        {
            addSelectOption(document,sel,selOptions[i].length > 0 ? optionText[selOptions[i]] : "",selOptions[i],selOptions[i]==curValue,parent);
            if (selOptions[i] == curValue) hasCur = true;
        }
        if (curValue.length > 0 && !hasCur && optionText[curValue] != null)
            addSelectOption(document,sel,optionText[curValue],curValue,true,parent);
    }
}


function syncSelectOptions(sel, data, curValue, win)
{
    if (typeof win == "undefined" || win==null )
        win = window;

    deleteAllSelectOptions(sel,win);

    if (isArray(data) && data.length > 0)
    {
        var hasCur = false;
        for (var i=0;i < data.length;i++)
            addSelectOption(document,sel,data[i].text,data[i].value,data[i].value==curValue,win);
    }
}


function handleToggleField(elem)
{
	var thisValue;
	var fieldIsDisabled;
	onChangeField = null;
	if(elem.nodeName == "INPUT")
	{
		thisValue = elem.value;
		fieldIsDisabled = elem.disabled;
	}
	else
	{
		thisValue = elem.getAttribute("childvalue");
		elem.parentNode.firstChild.value = thisValue;
		fieldIsDisabled = elem.parentNode.firstChild.disabled;
		onChangeField = elem.parentNode.firstChild;
	}
	for(var i=1; i<elem.parentNode.childNodes.length; i++)
	{
		var currentSpan = elem.parentNode.childNodes[i];
		var baseimage = currentSpan.getAttribute("baseimage")
		if(currentSpan.getAttribute("childvalue") == thisValue && !fieldIsDisabled)
			baseimage += "_selected";
		else if(fieldIsDisabled)
			baseimage += "_disabled";
		currentSpan.firstChild.src = "/images/buttons/"+baseimage+".gif";
	}

	if(onChangeField != null)
		onChangeField.onchange();
}



function handleOnOffSwitchField(elem)
{
    var thisValue;
    var fieldIsDisabled;
    var imageElem;
    var onChangeField = null;
    var bChanged;

    if(elem.nodeName == "INPUT")
    {
        thisValue = elem.value;
        fieldIsDisabled = elem.disabled;
        imageElem = elem.nextSibling;
        bChanged = true;
    }
    else
    {
        thisValue = elem.getAttribute("childvalue");
        imageElem = getParentElementByTag("table", elem);
        onChangeField = imageElem.previousSibling;
        fieldIsDisabled = onChangeField.disabled;
        if (fieldIsDisabled)
        {   
            thisValue = onChangeField.value;
            bChanged = false;
        }
        else
        {
            bChanged = (onChangeField.value != thisValue);
            onChangeField.value = thisValue;
        }
    }

    var on = (thisValue == "T");
    for(var i=0; i<imageElem.rows[0].cells.length; i++)
    {
        var elem = imageElem.rows[0].cells[i];
        elem.className =  elem.className.replace((on ? "_off" : "_on"), (on ? "_on" : "_off") );
        elem.firstChild.className =  elem.firstChild.className.replace((on ? "_off" : "_on"), (on ? "_on" : "_off") );
        if (elem.firstChild.firstChild)
            elem.firstChild.firstChild.className = elem.firstChild.firstChild.className.replace((on ? "_off" : "_on"), (on ? "_on" : "_off") )
    }

    if(fieldIsDisabled)
        imageElem.style.display = 'none'; <!-- hide switch image when it's disabled (UI spec for disabled state pending) -->
    else if(bChanged && onChangeField != null)
        onChangeField.onchange();
}

function isCheckboxImageField(fld)
{
	return fld.className != null && fld.className.indexOf("imagefield")>=0;
}

function openMapWindow(address, defaultcountry, type)
{
  if (!defaultcountry || defaultcountry.length == 0)
    defaultcountry = 'US';

  address = trim(address);
  if (address.length == 0)
  {
    alert("You must enter an address before you can view a map.");
    return;
  }

  // determine country
  var country;
  var lines = address.split("\n");
  var j = lines.length - 1;
  for (; j >= 0; j--)
  {
    line = trim(lines[j]);
    if (line.length == 0)
      continue;

	country = getCountry(line);
	if (country != null)
		break;
  }
  if (country == null)
	country = defaultcountry;

   callMapFunctionByIndex(countryMap[country], address, type);

  return;
}


function getHexValueFromDecimal(val)
{
	if ( isNaN(val) )
		return null;

	var returnMe = "#";
	for ( var i = 0; i < 3; i++ )
	{
		var myByte = val & 0xFF;
		val >>= 8;
		var lsNybble = myByte & 0x0F;
		var msNybble = (myByte >> 4) & 0x0F;
		returnMe += msNybble.toString(16);
		returnMe += lsNybble.toString(16);
	}
     
    var re = /^#[0-9ABCDEFabcdef]{6,}$/;
    if ( !re.test(returnMe) )
        returnMe = null;
	return returnMe.toUpperCase();
}

function getTwoDigitHexString(val)
{
  var hex = (new Number(val % 256)).toString(16).toUpperCase();
  if (hex.length == 1)
    hex = "0"+hex;
  return hex;
}

function setHexColor(fld)
{
  fld.value = "#" + getTwoDigitHexString(fld.form.elements[fld.name+"Red"].value) + getTwoDigitHexString(fld.form.elements[fld.name+"Green"].value) + getTwoDigitHexString(fld.form.elements[fld.name+"Blue"].value);
}

function setColorComponents(fld)
{
  fld.form.elements[fld.name+"Red"].value=parseInt(fld.value.substr(1,2),16);
  fld.form.elements[fld.name+"Green"].value=parseInt(fld.value.substr(3,2),16);
  fld.form.elements[fld.name+"Blue"].value=parseInt(fld.value.substr(5,2),16);
}

function setColorFromHSL(fld)
{
  var h=parseFloat(fld.form.elements[fld.name+"Hue"].value)/360.0;
  var s=parseFloat(fld.form.elements[fld.name+"Sat"].value)/100.0;
  var l=parseFloat(fld.form.elements[fld.name+"Lum"].value)/100.0;
  var r,g,b;
  if (s==0)
  {
    r = Math.round(l*255.0);
    g = r;
    b = r;
  }
  else
  {
    var v = l < 0.5 ? l*(1.0+s) : (l+s - l*s);
    if (v <= 0)
    {
      r = 0;
      g = 0;
      b = 0;
    }
    else
	{
	  var m = l+l-v;
	  var sv= (v - m) /v
	  h *= 6.0;
	  var sextant = Math.floor(h);
	  var fract = h - sextant;
	  vsf = v * sv * fract;
	  mid1 = m + vsf;
	  mid2 = v - vsf;
	  switch (sextant) {
		case 0: r = v; g = mid1; b = m; break;
		case 1: r = mid2; g = v; b = m; break;
		case 2: r = m; g = v; b = mid1; break;
		case 3: r = m; g = mid2; b = v; break;
		case 4: r = mid1; g = m; b = v; break;
		case 5: r = v; g = m; b = mid2; break;
		case 6: r = v; g = mid1; b = m; break;
	  }
	  r = Math.round(r*255.0);
	  g = Math.round(g*255.0);
	  b = Math.round(b*255.0);
    }
  }
  fld.form.elements[fld.name+"Red"].value=r;
  fld.form.elements[fld.name+"Green"].value=g;
  fld.form.elements[fld.name+"Blue"].value=b;
  fld.value = "#"+getTwoDigitHexString(r)+getTwoDigitHexString(g)+getTwoDigitHexString(b);
}

function setHSLFromColor(fld)
{
  var r=parseFloat(fld.form.elements[fld.name+"Red"].value)/255.0;
  var g=parseFloat(fld.form.elements[fld.name+"Green"].value)/255.0;
  var b=parseFloat(fld.form.elements[fld.name+"Blue"].value)/255.0;

  var v = Math.max(Math.max(r,g),b);
  var m = Math.min(Math.min(r,g),b);
  l = (v + m)/2.0;
  if (v == m)
  {
    s = 0;
    h = 0;
  }
  else
  {
    var vm = v-m;
    s = vm/(l < 0.5 ? v+m : 2.0-v-m);


    var r2 = (v - r) / vm;
    var g2 = (v - g) / vm;
    var b2 = (v - b) / vm;

    if (r == v)
      h = (g == m ? 5.0 + b2 : 1.0 - g2);
    else if (g==v)
      h = (b == m ? 1.0 + r2 : 3.0 - b2);
    else
      h = (r == m ? 3.0 + g2 : 5.0 - r2);
  }
  fld.form.elements[fld.name+"Hue"].value=Math.round(60.0*h);
  fld.form.elements[fld.name+"Sat"].value=Math.round(100.0*s);
  fld.form.elements[fld.name+"Lum"].value=Math.round(100.0*l);
}

function setGraph(file)
{
	document.graph.src = '/app/center/snapshotgraph.nl?g='+file;
}



function htmlToPlain(html)
{
	return html.replace(/[\n\r]/g, ' ').replace(/<p>\s*<\/p>\s*|<p>\s*|<\/p>\s*/gi, '\n\n').replace(/<br>\s*|<\/div>\s*/gi, '\n')
               .replace(/<[^>]*>/g, '').replace(/&nbsp;/gi, ' ').replace(/[ \t\f\v]+/g, ' ');
}


function resetIframeSource(windowName)
{
	// we must use setTimeout here, but I'm not sure why...  without it the browser just hangs
	setTimeout("document.getElementById('"+windowName+"').src='/empty.html';",10);
}

function parseFloatOrZero(f)
{
   var r=parseFloat(f);
   return isNaN(r) ? 0 : r;
}


function nsResizeIframeToContent(iframeId)
{
    var iframe = top.document.getElementById(iframeId);
    var body = iframe.contentWindow.document.body;
    var height = body.scrollHeight;
    if (height > 0)
    {
        var respawn = iframe.height != height;
        iframe.height = height;
        var contentTable = nsDescendantOfType(body, 'TABLE');
        if (contentTable)
            iframe.width = contentTable.scrollWidth;
        if (respawn)
            nsResizeIframeToContent(iframeId);
    }
}




function nsDescendantOfType(elem, nodeName)
{
    var children = elem.childNodes;
    var i, child;
    for (i=0; i<children.length; ++i)
    {
        if (children[i].nodeName.toUpperCase() == nodeName)
            return children[i];
    }
    for (i=0; i<children.length; ++i)
    {
        child = children[i];
        if (child.nodeName[0]=='#') continue;
        var match = nsDescendantOfType(child, nodeName);
        if (match) return match;
    }
    return null;
}


function nsAddBeforeUnloadHandler(fn, windowContext)
{
    windowContext = windowContext || window;
    var oldFn = windowContext.onbeforeunload;
    windowContext.onbeforeunload = oldFn ? function() { var msg = oldFn() || fn(); if (msg) return msg; } : fn;
}

function popupMessageDiv(msgstr,obj,clicktohide)
{
    if (msgstr == null || msgstr.length==0)
        return;
    var messageDiv=document.getElementById('MessageInlineDIV');
    if (messageDiv == null)
    {
        messageDiv = document.createElement('div');
        messageDiv.style.border     = '1px solid black';
        messageDiv.style.position   = 'absolute';
        messageDiv.style.padding    = '2px';
        if (clicktohide == null || clicktohide == true)
			messageDiv.onclick      = new Function("document.getElementById('MessageInlineDIV').style.display='none'; return false;");
		else
			messageDiv.onmousedown  = new Function("event.cancelBubble = true;");
        messageDiv.id               = 'MessageInlineDIV';
        messageDiv.className        = 'bglt';
        messageDiv.style.display='none';
        messageDiv.style.zIndex = 1000;

        document.body.appendChild(messageDiv);
    }
    var elementRectangle = obj.getBoundingClientRect();

    messageDiv.innerHTML = "<span class=smalltext>"+msgstr+"</span>";
    messageDiv.style.left = elementRectangle.left + getWindowPageXOffset() + "px";
    messageDiv.style.top = elementRectangle.top + getWindowPageYOffset() + obj.offsetHeight + "px";
    messageDiv.style.display = '';
    addDivToClose('MessageInlineDIV');
}

function getPagePerfInfo( tagName )
{
    var cbody = GetCookie('base_t');
    if (cbody != null)
    {
        var b=cbody.indexOf(tagName+':');
        if ( b >= 0 )
        {
             var e =cbody.indexOf('|',b);
             if ( e < 0 )
                e = cbody.length;
             return unescape(cbody.substring(b+tagName.length+1, e));
        }
    }
    return null;
}


function uir_getAlertBoxHtml(sTitle, sMessage, iType, width, helpUrl, helpText, imageHostName)
{
    if (iType != NLAlertDialog.TYPE_LOWEST_PRIORITY &&
        iType != NLAlertDialog.TYPE_LOW_PRIORITY &&
        iType != NLAlertDialog.TYPE_MEDIUM_PRIORITY &&
        iType != NLAlertDialog.TYPE_HIGH_PRIORITY)
        iType = NLAlertDialog.TYPE_LOW_PRIORITY;

    if (!sTitle)
    {
        sTitle = NLAlertDialog.defaultTitles[iType]
        if (sTitle == null)
            sTitle = "Error"
    }

    var hasHelpLink = false;
    if (helpUrl && helpUrl.length > 0)
    {
        hasHelpLink = true;
        if (!helpText)
            helpText = "Visit this Help Topic";
    }

    if (!imageHostName)
        imageHostName = "";

    return  "<div class='uir-alert-box " + NLAlertDialog.imageNames[iType] + "'  width='"+width+"'>"+
                    "<div class='icon " + NLAlertDialog.imageNames[iType] + "' >" + "<img src='" + imageHostName + "/images/icons/messagebox/icon_msgbox_"+NLAlertDialog.imageNames[iType]+".png' alt=''>" + "</div>" +
                    "<div class='content'>" +
                        "<div class='title'>" + sTitle + "</div>" +
                        "<div class='descr'>" + sMessage + "</div>"+
                        (hasHelpLink ? "<div class='help'><a href=\"" + helpUrl.replace(/"/g, "&#34") + "\">" + helpText + "</a></div>" : "" ) +
                    "</div>" +
            "</div>";
}

function getAlertBoxHtml(sTitle, sMessage, iType, width, helpUrl, helpText, imageHostName)
{
    if (iType != NLAlertDialog.TYPE_LOWEST_PRIORITY &&
            iType != NLAlertDialog.TYPE_LOW_PRIORITY &&
            iType != NLAlertDialog.TYPE_MEDIUM_PRIORITY &&
            iType != NLAlertDialog.TYPE_HIGH_PRIORITY)
        iType = NLAlertDialog.TYPE_LOW_PRIORITY;
    if(!width)
        width = 500;
    if (!sTitle)
    {
        sTitle = NLAlertDialog.defaultTitles[iType];
        if (sTitle == null)
            sTitle = "Error"
    }

    var bHelpLink = false;
    if (helpUrl && helpUrl.length > 0)
    {
        bHelpLink = true;
        if (!helpText)
            helpText = "Visit this Help Topic";
    }

    if (!imageHostName)
        imageHostName = "";

    return "<table class='uir-report-information' cellpadding='0' cellspacing='0' border='0' style='margin:0px; min-height: 65px; border: 1px solid #417ed9;' width='"+width+"' bgcolor='"+NLAlertDialog.backgroundColors[iType]+"'>"+
           "<tr><td colspan='2' width='100%' height='15'></td></tr>"+
           "<tr>"+
           "<td align='left' valign='top'><div class='icon " + NLAlertDialog.imageNames[iType] + "'></div></td>"+
           "<td width='100%' valign='top'><div class='content'>" +
               "<b>"+sTitle+"</b><br />"+sMessage+
               (bHelpLink ? ("<p align='right'> <img src='" + imageHostName + "/images/icons/messagebox/icon_help_green.png' style='height:12px; width:12px; display:block; vertical-align:middle' /> <a href=\"" + helpUrl.replace(/"/g, "&#34") + "\">" + helpText + "</a></p>") : "") +
           "</div></td></tr>"+
           "<tr><td colspan='4' width='100%' height='15'></td></tr>"+
           "</table>";
}


NLAlertDialog = Class.create();

NLAlertDialog.CONFIRMATION = 0;
NLAlertDialog.INFORMATION  = 1;
NLAlertDialog.WARNING      = 2;
NLAlertDialog.ERROR        = 3;
NLAlertDialog.defaultTitles = ["Confirmation",
                               "Information",
                               "WARNING",
                               "Error"];

NLAlertDialog.TYPE_LOWEST_PRIORITY = 0;
NLAlertDialog.TYPE_LOW_PRIORITY    = 1;
NLAlertDialog.TYPE_MEDIUM_PRIORITY = 2;
NLAlertDialog.TYPE_HIGH_PRIORITY   = 3;

NLAlertDialog.backgroundColors = ["#DAEBD5", "#EAEEF3", "#FFF2CC", "#FCE8E8"];
NLAlertDialog.imageNames = ["confirmation", "info", "warning", "error"];

NLAlertDialog.prototype =
{
    initialize: function(sId)
    {
        this.sId = sId || "NLAlertDialog";
    },

	
	show: function(sTitle, sMessage, iType)
	{
		var posX = document.body.clientWidth / 2;
		var posY = document.body.clientHeight / 2;

		if(!iType)
        {
            iType = NLAlertDialog.TYPE_LOW_PRIORITY;
        }

		if (!this.hndDialogDiv)
		{
			this.hndDialogDiv = document.createElement("div");
			this.hndDialogDiv.innerHTML = getAlertBoxHtml(sTitle, sMessage, iType);
			this.hndDialogDiv.style.display = "none";
			this.hndDialogDiv.style.position = "absolute";
			document.body.appendChild(this.hndDialogDiv);
		}

		if (this.hndDialogDiv.style.display == "block")
            return;

        this.hndDialogDiv.style.display = "block";
        this.hndDialogDiv.style.top = posY - (this.hndDialogDiv.clientHeight / 2) + "px";
        this.hndDialogDiv.style.left = posX - (this.hndDialogDiv.clientWidth / 2) + "px";
    },

    hide: function()
    {
		if (this.hndDialogDiv != null)
            this.hndDialogDiv.style.display = "none";
    }
}

var netsuiteProductDirectory = "netsuite";
function showGettingStarted(t)
{
    var pdfdir = "/pages/support/pdfs/"+netsuiteProductDirectory+"/";
    if (t=='payroll')
        window.open( pdfdir + "GettingStartedPR.pdf");
    else if (t=='store')
        window.open( pdfdir + "GettingStartedWS.pdf");
	else if (t=='yahoo')
        window.open( pdfdir + "GettingStartedYahoo.pdf");
	else if (t=='wsdk')
        window.open("/pages/support/wsdk/"+netsuiteProductDirectory+"/wsdk.jsp");
    else if (t=='billpay')
        window.open( pdfdir + "GettingStartedOBP.pdf");
    else if (t=='crm')
        window.open( pdfdir + "GettingStartedCRM.pdf");
    else if (t=='test')
        window.open( pdfdir + "GettingToKnow.pdf");
    else if (t=='customization')
        window.open( pdfdir + "GettingStartedCustom.pdf");
    else if (t=='crmbasics')
        window.open( pdfdir + "GettingtoKnowCRMBasics.pdf");
    else
        window.open( pdfdir + "GettingStartedGuide.pdf");
}

function showReleaseNotes(release)
{
    parent.document.location = "/pages/releases/"+netsuiteProductDirectory+"/releaseNotes"+release+".jsp";
}
function showCurrentReleaseNotes(release)
{
    parent.document.location = "/pages/releases/"+netsuiteProductDirectory+"/releaseNotes"+release+".jsp";
}
function showCurrentNewFeatures(release)
{
    parent.document.location = "/pages/releases/"+netsuiteProductDirectory+"/release"+release+".jsp";
}
function showNewFeatures(release, sAnchorName)
{
    parent.document.location = "/pages/releases/"+netsuiteProductDirectory+"/release"+release+".jsp" + (sAnchorName != null ? "#"+sAnchorName : "");
}
function showWhatsNewPDF()
{
	window.open("/pages/support/pdfs/"+netsuiteProductDirectory+"/whatsnew.pdf","whatsnew","scrollbars=yes,resizable=yes");
}
function showSneakPeek(type)
{
	window.open("/pages/support/pdfs/"+netsuiteProductDirectory+"/sneakpeek"+type+".pdf","sneakpeak","scrollbars=yes,resizable=yes");
}


function scrollToField(sFieldName)
{
    try
	{
			var fieldAnchor = document.getElementById("scrollfield_" + sFieldName);
			if(fieldAnchor != null)
				document.body.scrollTop = findPosY(fieldAnchor) - 30;
	}
	catch (e)
	{
		
	}
}

function syncChildEventHandlers(win)
{
	win.scExistingOnMouseMove = win.document.onmousemove;
	win.document.onmousemove = new Function("event", "parent.childPanesMouseMove(getMouseX(event)); scExistingOnMouseMove(event)");

	win.scExistingOnMouseUp = win.document.onmouseup;
	win.document.onmouseup = new Function("event", "parent.childPanesMouseUp(); scExistingOnMouseUp(event)");

	win.document.onselectstart = new Function("event", "parent._panesOnSelectStart()")
}


function attachEventHandler(event, elem, handler)
{
    if(!!elem.addEventListener){
        elem.addEventListener(event, handler, false);
    } else {
        elem.attachEvent("on" + event, handler);
    }
}



function detachEventHandler(event, elem, handler)
{
    
        elem.detachEvent("on" + event, handler);
    
}


function setEntryFormTitleStatusLabel(label, bEscape)
{
    var statusElem = document.getElementById("recStatus");
	if (statusElem)
	{
    	if (bEscape != false)
        	statusElem.innerHTML = escapeHTML(label);
    	else
	        statusElem.innerHTML = label;
	}
}

function validate_multitype_fld(fld,fieldtype)
{
	return (fieldtype =='SELECT' || fieldtype == 'MULTISELECT' || fieldtype =='CHECKBOX' || fieldtype =='IMAGE' || fld.disabled || validate_field(fld,fieldtype.toLowerCase(),true));
}

function NLView(sView, sViewSuffix, bLoad)
{
	this.sName = sView;
	this.sSuffix = sViewSuffix;
	this.bInitialized = false;
	this.bDataLoaded = false;
	this.mTable = null;
	this.trNodes = new Array();
	this.sFieldWidth = null;

	this.initialize();

	if (bLoad)
		this.loadTableRows();
}

NLView.prototype.initialize = function()
{
	this.mTable = document.getElementById(this.sName);
	if (this.mTable == null)
	{
		return;
	}

	var className = this.mTable.className
	if (className == null)
		this.bHidden = false;
	else if (className.indexOf('hideElement') == -1)
		this.bHidden = false;
	else
		this.bHidden = true;


    this.sFieldWidth = 'width: '+this.mTable.getAttribute('FieldWidth');
	this.mViewAnchor = document.getElementById(this.sName + '_link');

	this.bInitialized = true;
}

NLView.prototype.hide = function()
{
	var className = this.mTable.className;

	if (className == null || className.length == 0)
		this.mTable.className = 'hideElement';
	else
		this.mTable.className += ' hideElement';

	this.mViewAnchor.className = 'formviewunselected';

   opacity(this.sName, 100, 0, 200);
   this.bHidden = true;
}

NLView.prototype.show = function()
{
	if (this.mTable.className == null)
		return;

	this.mTable.className.replace('hideElement', '');
	this.mTable.className = '';

	this.mViewAnchor.className = 'formviewselected';

    opacity(this.sName, 0, 100, 400);
	this.bHidden = false;
}

// Function will loop and store all the dom elements.
NLView.prototype.loadTableRows = function()
{
	var form = NLEntryForm.getForm(false);
	if (form == null)
    	return;

    var spans = form.mFieldSpans;
    var spanslen = form.mFieldSpans.length;
	    var fields = form.mFields;
    var pageField, layoutId, row, rowInfo, trIndex = 0;

    for(i = 0;i<spanslen; i++)
    {
    	pageField = fields[spans[i]];

        if (pageField.sSumLayoutId == null)
        	continue;

        row = document.getElementById(pageField.sSumLayoutId);

        rowInfo = new Object();
        rowInfo.sId = row.id.substring(0, (row.id.length - this.sSuffix.length));
 		rowInfo.row = row;
		this.trNodes[trIndex++] = rowInfo;
	}

	this.bDataLoaded = true;
}

NLView.prototype.moveFields = function(destination)
{
	var trRows, trLen, rowId, numOfCells;
	var srcRow,  srcRowCells,  srcCell, srcCellWidth;
	var destRow, destRowCells, destCell, destCellWidth;
	var bUseThis, bDestDataLoaded = false;

	if (this.bDataLoaded) // This is the summary table.
	{
		trRows = this.trNodes;
		bUseThis = true;

		if (destination.bDataLoaded)
			bDestDataLoaded = true;
	}
	else if (destination.bDataLoaded)
	{
		trRows = destination.trNodes;
		bUseThis = false;
	}
	else
		return;


	srcCellWidth = this.sFieldWidth;
	destCellWidth = destination.sFieldWidth;
	var srcWidthRegex = new RegExp(srcCellWidth, 'i');
	var doFieldWidthReplace = false;

	if (srcCellWidth != destCellWidth)
	{
		doFieldWidthReplace = true;
	}

	if ((srcCellWidth == null) || (destCellWidth == null))
	{
		srcCellWidth = null;
		destCellWidth = null;
	}

	trLen = trRows.length;
	for (i=0; i< trLen; i++)
	{
		rowId = trRows[i].sId;

		if (bUseThis)
		{
			srcRowCells = trRows[i].row.cells;

			if (bDestDataLoaded)
			{
				destRowCells = destination.trNodes[i].row.cells;
			}
			else
			{
				var rowInfo = new Object();
				destRow = document.getElementById(rowId + destination.sSuffix);
				rowInfo.sId = destRow.id.substring(0, (destRow.id.length - destination.sSuffix.length));
				rowInfo.row = destRow;

				destination.trNodes[i] = rowInfo;
				destRowCells = destRow.cells;
			}
		}
		else
		{
			// Here, the source is not loaded. So let's go and load it.
			var rowInfo = new Object();
			srcRow = document.getElementById(rowId + this.sSuffix);
			rowInfo.sId = srcRow.id.substring(0, (srcRow.id.length - this.sSuffix.length));
			rowInfo.row = srcRow;

			this.trNodes[i] = rowInfo;

			srcRowCells = srcRow.cells;
			destRowCells = destination.trNodes[i].row.cells;
		}

		numOfCells = srcRowCells.length;
		for(c=0; c<numOfCells; c++)
		{
			srcCell  = srcRowCells[c];
			destCell = destRowCells[c];

			var cellHtml = srcCell.innerHTML;
			srcCell.innerHTML = '';

			if (doFieldWidthReplace)
				cellHtml = cellHtml.replace(srcWidthRegex, destCellWidth);


			destCell.innerHTML = cellHtml;
		}
	}

	if (bUseThis)
		destination.bDataLoaded = true;
	else
		this.bDataLoaded = true;
}


NLView.prototype.isHidden = function()
{
	return this.bHidden;
}

function NLViewToggle(sSummary, sDetail)
{
	this.sumTabName = sSummary;
	this.detTabName = sDetail;

	this.initialize();
}

NLViewToggle.prototype.initialize = function()
{
	this.sumView = new NLView(this.sumTabName, '_sum', true);
	this.detView = new NLView(this.detTabName, '_dtl', false);

	this.formdisplayview = document.getElementById('formdisplayview');
}

NLViewToggle.prototype.getView = function(sName)
{
	if (this.sumTabName == sName)
		return this.sumView;
	else if (this.detTabName == sName)
		return this.detView;

    return null;
}

NLViewToggle.prototype.hideView = function(unselected)
{
	var view = this.getView(unselected);
	view.hide();
}

NLViewToggle.prototype.show = function(selected)
{
	var view = this.getView(selected);
	view.show();
}

NLViewToggle.toggle = function(sSumTabName, sDetTabName, sSelected)
{
	// first check to see if the object is created.
	var toggle = window.nlviewtoggle;
	if (toggle == undefined)
	{
		toggle = new NLViewToggle(sSumTabName, sDetTabName);
		window.nlviewtoggle = toggle;
	}

	var sUnselected = (sSelected == sSumTabName? sDetTabName : sSumTabName);
	var selView = toggle.getView(sSelected);
	var unselView = toggle.getView(sUnselected);

	if (selView.isHidden())
	{
		toggle.hideView(sUnselected);

		unselView.moveFields(selView);

		toggle.show(sSelected);

		toggle.formdisplayview.value = 'DETAIL_VIEW';
	}

	return false;
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


function callAddShortcut(link)
{
	if (typeof addShortcut == 'function')
    	addShortcut();
    else if (link)
    	link.disabled = true;
}

function NLCrossLink(sLabel, sLink)
{
    this.sLabel = sLabel;
    this.sLink = sLink;
}

NLCrossLink.getSeparator = function()
{
	var td = document.createElement('td');
    td.style = 'background-color: #CCCCCC';

    var img = document.createElement('img');
    img.width = 1;
    img.src = '/images/nav/ns_x.gif';

    td.appendChild(img);
	return td;
}

NLCrossLink.prototype.getElement = function()
{
	var td = document.createElement('td');
    td.className = 'headbarsub';
    td.align = 'right';
    td.nowrap = true;

    var anchor = document.createElement('a');
    anchor.className = 'crosslinktext';
    anchor.href = this.sLink;
    attachEventHandler('mouseout', anchor, function() {this.className='crosslinktext'});
    attachEventHandler('mouseover', anchor, function() {this.className='crosslinktextul'});

    anchor.appendChild(document.createTextNode(this.sLabel));
    td.appendChild(anchor);

    return td;
}

function NLPageField(sSpanId, sSumLayoutId, sDetLayoutId, sTabName, sFieldGroup, nLabelLen, nCol)
{
	this.sSpanId = sSpanId;
	this.sSumLayoutId = sSumLayoutId;
	this.sDetLayoutId = sDetLayoutId;
    this.sTabName = sTabName;
	this.sFieldGroup = sFieldGroup;
    this.nLabelLen = nLabelLen;
    this.nCol = nCol;
}

function NLPageFieldGroup(sName, sTitleId, nVisibleFlds)
{
	this.sName = sName;
	this.sTitleId = sTitleId;

	this.nVisibleField = nVisibleFlds;
}

NLPageFieldGroup.prototype.trackFieldVisibility = function(bOn)
{
	if (bOn)
	{
		if (this.nVisibleField == 0)
			this.showTitle();

		this.nVisibleField++;
	}
	else
	{
		if (this.nVisibleField == 1)
			this.hideTitle();

		this.nVisibleField--;
	}
}

// Field group needs to have a count of the number elements visible.
// We need to hide or show field groups when all the fields disappear.
NLPageFieldGroup.prototype.hideTitle = function()
{
	var title = document.getElementById(this.sTitleId);
	if (title == null)
		return;

	title.style.display = 'none';
}

NLPageFieldGroup.prototype.showTitle = function()
{
	var title = document.getElementById(this.sTitleId);
	if (title == null)
		return;

	title.style.display = '';
}

function NLPageTab(sTabName, nNumOfCol, sFormName)
{
	this.sTabName = sTabName;

    if (nNumOfCol < 1)
		nNumOfCol = 3;

	this.nNumOfCol = nNumOfCol;
	this.sFormName = sFormName;
	this.nFormWidth = -1;

    this.mLongestColWidth = new Array();
}

NLPageTab.prototype.addField = function(sSpanId, nLabelLen, nCol)
{
	var longestField = this.mLongestColWidth[nCol];
	if (longestField)
	{
		if (longestField.nLabelLen < nLabelLen)
		{
		    longestField.sSpanId = sSpanId;
			longestField.nLabelLen = nLabelLen;
			this.mLongestColWidth[nCol] = longestField;
		}
	}
	else
	{
		longestField = new Object();
		longestField.sSpanId = sSpanId;
		longestField.nLabelLen = nLabelLen;
		this.mLongestColWidth[nCol] = longestField;
	}
}

NLPageTab.prototype.getColumnWidth = function(nCol)
{
	if (this.nFormWidth < 0)
	{
		var tabForm=document.getElementById(this.sFormName);
		if (tabForm)
		    this.nFormWidth=tabForm.offsetWidth;
		else
			this.nFormWidth=0;
	}

    if (this.nFormWidth==0)
	    return '{width: 25%}';

    var longestField = this.mLongestColWidth[nCol];
	if (longestField)
	{
		if (longestField.offsetWidth == null)
		{
			var field = document.getElementById(longestField.sSpanId+'_lbl');
			if (field)
			    longestField.offsetWidth = field.offsetWidth;
		}
	}
	else
	    return '{width: 25%}';

    var nWidth =  (longestField.offsetWidth / (this.nFormWidth / this.nNumOfCol)) * 100;
	nWidth += 2;
	nWidth = nWidth.toFixed();

	if (nWidth < 20)
	    nWidth = 20;
 	else if (nWidth > 50)
	    nWidth = 50;
    else
        nWidth = 25;

    return '{width: '+nWidth+'%}';
}

// Object that contains all the fields on a page.
function NLEntryForm()
{
	this.mFieldSpans = new Array();
	this.mFields = new Object();

	this.mFGNames = new Array();
	this.mFGroups = new Object();

	this.mTabs = new Object();
}

NLEntryForm.prototype.addField = function NLEntryForm_addField(sSpanId, sSumLayoutId, sDetLayoutId, sTabName, sFieldGroup, nLabelLen, nCol)
{
	var pageField = new NLPageField(sSpanId, sSumLayoutId, sDetLayoutId, sTabName, sFieldGroup, nLabelLen, nCol);

	this.mFields[sSpanId] = pageField;
    var index = this.mFieldSpans.length;

	this.mFieldSpans[index] = sSpanId;

	var tab = this.getTab(sTabName);
	if (tab)
	{
		tab.addField(sSpanId, nLabelLen, nCol);
	}
}

NLEntryForm.prototype.addFieldGroup = function NLEntryForm_addFieldGroup(sName, sTitleId, nVisibleFlds)
{
	var fg = new NLPageFieldGroup(sName, sTitleId, nVisibleFlds);

	this.mFGNames[this.mFGNames.length] = sName;
	this.mFGroups[sName] = fg;
}
NLEntryForm.prototype.trackFieldVisibility = function NLEntryForm_trackFieldVisibility(spanId, on)
{
	var form = NLEntryForm.getForm();

	if (this.mFields[spanId] == null)
		return;

    var fld = this.mFields[spanId];
	if(fld == null)
		return;

	if (fld.sFieldGroup == null)
		return;

    this.mFGroups[fld.sFieldGroup].trackFieldVisibility(on)
}
NLEntryForm.prototype.addTab = function NLEntryForm_addTab(sTabName, nNumOfCol, sFormName)
{
	var pageTab = new NLPageTab(sTabName, nNumOfCol, sFormName);

	this.mTabs[sTabName] = pageTab;
}

NLEntryForm.prototype.getTab = function NLEntryForm_getTab(sTabName)
{
	return this.mTabs[sTabName];
}

NLEntryForm.getForm = function NLEntryForm_getForm(bCreate)
{
	var form = window.nlentryform;
	if (form == null && bCreate)
	{
		form = new NLEntryForm();
		window.nlentryform = form;
	}

	return form;
}

NLEntryForm.prototype.expandCollapseTab = function NLEntryForm_expandCollapseTab(tabName, sethidden)
{
    var tabBlock = null
    if ( document.getElementById(tabName+'_wrapper'))
        tabBlock =  document.getElementById(tabName+'_wrapper');
    else
        tabBlock =  document.getElementById(tabName+'_layer');

    if (sethidden == null || typeof sethidden == 'undefined')
        sethidden = tabBlock.style.display !='none';

    tabBlock.style.display =  sethidden ? "none" :  "";
    document.getElementById(tabName+'_h').style.display = sethidden ? "none" :  "";
    var t1 = !sethidden ? "collapse" : "expand";
    var t2 = !sethidden ? "expand" : "collapse";
    document.getElementById(tabName+'_collapse').src = document.getElementById(tabName+'_collapse').src.replace(t2, t1);
    document.getElementById(tabName+'_pane_ul').className = document.getElementById(tabName+'_pane_ul').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_um').className = document.getElementById(tabName+'_pane_um').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_ur').className = document.getElementById(tabName+'_pane_ur').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_ml').className = document.getElementById(tabName+'_pane_ml').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_mr').className = document.getElementById(tabName+'_pane_mr').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_ll').className = document.getElementById(tabName+'_pane_ll').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_lm').className = document.getElementById(tabName+'_pane_lm').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_lr').className = document.getElementById(tabName+'_pane_lr').className.replace(t1, t2);
    document.getElementById(tabName+'_pane_hd').className = document.getElementById(tabName+'_pane_hd').className.replace(t1, t2);

    if (!sethidden && typeof NetSuite != 'undefined' && typeof NetSuite.RTEManager != 'undefined' && !!NetSuite && !!NetSuite.RTEManager){
        NetSuite.RTEManager.resyncSizeAll();
    }
}


NLEntryForm.addCrossLink = function NLEntryForm_addCrossLink(nlcrosslink, targetId)
{
	if (!targetId)
    	targetId = 'header_rs';

    if (!nlcrosslink)
    	return;

    var target = document.getElementById(targetId);
    if (target)
    {
    	target.appendChild(nlcrosslink.getElement());
    }
}


function checkMaxTotalLimit(totalFieldName, machineName, itemAmountFieldName)
{
	var newTotalAmount;
	if(machineName == '')
		newTotalAmount = parseFloat(nlapiGetFieldValue(totalFieldName)) + parseFloat(nlapiGetFieldValue(itemAmountFieldName));
	else
		newTotalAmount = parseFloat(nlapiGetFieldValue(totalFieldName)) + parseFloat(nlapiGetCurrentLineItemValue(machineName,itemAmountFieldName));
    if( newTotalAmount >= getMaxTotalLimit() )
    {
    	alert("The total amount is too large. Please split the transaction into multiple ones.");
        return false;
    }
    else
    	return true;
}

function getMaxTotalLimit()
{
    var cp = nlapiGetField('currencyprecision') ? nlapiGetFieldValue('currencyprecision') : 2;
    return Math.pow(10, 15-cp);
}


function getButton(name)
{
    
    var elements = document.getElementsByName(name);

    for (var i = 0; i < elements.length; i++)
    {
        var element = elements[i];

        
        if ((element.tagName == 'INPUT' && element.type.match(/^(submit|reset|button)$/i) != null) || element.tagName == 'BUTTON')
        {
            return element;
        }
    }

    return null;
}

// disable/enable a button with the given ID
function setButtonDisabled(buttonId, isDisabled)
{
    var topButtonSelector = '#' + buttonId;
    var bottomButtonSelector = '#secondary' + buttonId;

    var button = jQuery(topButtonSelector + ',' + bottomButtonSelector);
    if (isDisabled)
    {
        // disable
        button.attr('disabled', 'disabled');
        button.removeClass('rndbuttoninpt').addClass('rndbuttoninptdis');
    }
    else
    {
        // enable
        button.removeAttr('disabled');
        button.removeClass('rndbuttoninptdis').addClass('rndbuttoninpt');
    }
}

// show/hide a button with the given ID
function setButtonVisibility(buttonId, isVisible)
{
    var topButtonSelector = '#' + buttonId;
    var bottomButtonSelector = '#secondary' + buttonId;

    var button = jQuery(topButtonSelector + ',' + bottomButtonSelector);
    button.closest('table').toggle(isVisible);
}
        
function validate_fromaddress(fld)
{
 if (fld.value.length > 0 && !fld.value.toLowerCase().match(/^\"[^<>"]+\"\s\<(?:(?:[-a-z0-9!#$%&'*+/=?^_`{|}~]+(?:\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*@(?:[a-z0-9]+(?:-+[a-z0-9]+)*\.)+(?:xn--[a-z0-9]+|[a-z]{2,16}))|(?:\{[A-Za-z0-9_\.]+\}))\>$/))
 {
     alert('From address must be of the form \"Name\" <Email Address>');
     selectAndFocusField(fld);
     NS.form.setValid(false);
     return false;
 }
 NS.form.setValid(true);
 return true;
}

/* Access key handler
*   - access key works differently in IE than in other browsers
*   - access key pressing will cause click on the selected element
* */

attachEventHandler("keydown", document, keyDownListenerAccessKey);


function keyDownListenerAccessKey(e)
{
    var key = (e.keyCode ? e.keyCode : e.which);
    if(e.altKey && key != 18)
    {
        NS.jQuery("[accesskey='" + e.key + "']").click();
        if(e.stopPropagation)
        {
            e.stopPropagation();
        }
        else
        {
            window.event.cancelBubble = true;
        }
    }
}
/* END - Access key handler */


    function showAlertBox(elemId, sTitle, sMessage, iType, width, helpUrl, helpText)
{
    jQuery('#' + elemId).html(getAlertBoxHtml(sTitle, sMessage, iType, width, helpUrl, helpText)).show();
}

function hideAlertBox(elemId)
{
    jQuery("#"+elemId).hide();
}



var doPageLogging = (window.parent == null || window.parent == window);
var doPerfdbLogging = window.doPageLogging && true;

var isProdsys = true;
var pageEndToEndTime = null; 
var e2eResultsString = null; 
function logEndOfRequest()
{
    if ( !window.doPageLogging ) return;
    try
    {
        var renderendtime = new Date();
        var endtoendTime = null;
        var base_t = getPagePerfInfo('start');
        var base_t_url = getPagePerfInfo('url');
        var base_t_whence = getPagePerfInfo('whence');
        var base_t_method = getPagePerfInfo('method');
        var base_t_sql = nvl(getPagePerfInfo('sqlcalls'),0);
        var base_t_sqltime = getPagePerfInfo('sqltime');
        var base_t_servertime = getPagePerfInfo('servertime');
        var base_t_ssstime = getPagePerfInfo('ssstime');
        var base_t_user_email = getPagePerfInfo('email');
        var base_t_fcalls = getPagePerfInfo('fcalls');
        var base_t_ftime = getPagePerfInfo('ftime');
        var base_t_nthreadid = getPagePerfInfo('nthreadid');

        if (base_t != null && base_t != 0 && base_t_url != null && unescape(document.location.href).indexOf(base_t_url) != -1)
        {
            document.cookie = 'base_t=; path=/';
            endtoendTime = renderendtime.getTime() - base_t;
            window.pageEndToEndTime = endtoendTime;
        }

        var pageloadTime = window.renderstarttime != null ? renderendtime.getTime() - window.renderstarttime.getTime() : 0;
        var pageinitTime = window.pageinitstart != null ? (renderendtime.getTime() - window.pageinitstart.getTime()) : 0;
        var headerTime = window.headerstarttime != null ? (window.headerendtime.getTime() - window.headerstarttime.getTime()) : 0;
        var staticscriptTime = window.staticscriptstarttime != null ? (window.staticscriptendtime.getTime() - window.staticscriptstarttime.getTime()) : 0;
        var dynamicscriptTime = window.dynamicscriptstarttime != null ? (window.dynamicscriptendtime.getTime() - window.dynamicscriptstarttime.getTime()) : 0;
        var footerscriptTime = window.footerscriptstarttime != null ? (window.footerscriptendtime.getTime() - window.footerscriptstarttime.getTime()) : 0;
        var unmeasuredTime = pageloadTime - pageinitTime - headerTime - staticscriptTime - dynamicscriptTime - footerscriptTime - (window.dropdownCounter > 0 ? window.dropdownloadtime : 0);

        var logoSpan = document.getElementById("devpgloadtime");
        if (logoSpan != null)
        {
            var resultsAsTable = '<table cellspacing=5 cellpadding=0 class="smalltextnolink">';
            if ( endtoendTime != null )
            {
                resultsAsTable = addPetDataRow(resultsAsTable, 'Total', (endtoendTime/1000));

                if ( window.isProdsys )
                {
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Server', ((base_t_servertime)/1000) + ' ('+format_currency(100*(base_t_servertime)/endtoendTime)+'%)');
                    if (base_t_ssstime != null)
                        resultsAsTable = addPetDataRow(resultsAsTable, 'SSS', (base_t_ssstime/1000) + ' ('+format_currency(100*base_t_ssstime/endtoendTime)+'%)');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Network', ((endtoendTime-base_t_servertime-pageloadTime)/1000) + ' ('+format_currency(100*(endtoendTime-base_t_servertime-pageloadTime)/endtoendTime)+'%)');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Client', (pageloadTime/1000) + ' ('+format_currency(100*pageloadTime/endtoendTime)+'%)');
                }
                else
                {
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Java', ((base_t_servertime-base_t_sqltime)/1000) + ' ('+format_currency(100*(base_t_servertime-base_t_sqltime)/endtoendTime)+'%)');
                    if (base_t_ssstime != null)
                        resultsAsTable = addPetDataRow(resultsAsTable, 'SSS', (base_t_ssstime/1000) + ' ('+format_currency(100*base_t_ssstime/endtoendTime)+'%)');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'SQL', (base_t_sqltime/1000) + ' ('+format_currency(100*base_t_sqltime/endtoendTime)+'%) ('+base_t_sql+' call'+(base_t_sql == 1 ? '' : 's')+')');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Fetches', (base_t_ftime/1000) + ' ('+base_t_fcalls+' call'+(base_t_fcalls == 1 ? '' : 's')+')');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Network', ((endtoendTime-base_t_servertime-pageloadTime)/1000) + ' ('+format_currency(100*(endtoendTime-base_t_servertime-pageloadTime)/endtoendTime)+'%)');
                    resultsAsTable = addPetDataRow(resultsAsTable, 'Client', (pageloadTime/1000) + ' ('+format_currency(100*pageloadTime/endtoendTime)+'%)');
                }

            }
            else
                resultsAsTable = addPetDataRow(resultsAsTable, 'Client', (pageloadTime/1000));

            if ( !window.isProdsys )
            {
                resultsAsTable = addPetDataRow(resultsAsTable, 'Header', (headerTime/1000) + ' ('+format_currency(100*headerTime/pageloadTime)+'%)');
                resultsAsTable = addPetDataRow(resultsAsTable, 'Static', (staticscriptTime/1000) + ' ('+format_currency(100*staticscriptTime/pageloadTime)+'%)');
                resultsAsTable = addPetDataRow(resultsAsTable, 'Dynamic', (dynamicscriptTime/1000) + ' ('+format_currency(100*dynamicscriptTime/pageloadTime)+'%)');
                resultsAsTable = addPetDataRow(resultsAsTable, 'Footer', (footerscriptTime/1000) + ' ('+format_currency(100*footerscriptTime/pageloadTime)+'%)');
                resultsAsTable = addPetDataRow(resultsAsTable, 'Selects', (window.dropdownloadtime/1000) + ' ('+format_currency(100*window.dropdownloadtime/pageloadTime)+'%) ('+window.dropdownCounter+' dropdown'+(window.dropdownCounter != 1 ? 's' : '')+')');

                var machinePerfInfo = window.editmachineCounter > 0 ? '('+ window.editmachineCounter+' machine'+(window.editmachineCounter != 1 ? 's' : '')+': '+(window.editmachineConstructorTime/1000) + ')' : '';
                resultsAsTable = addPetDataRow(resultsAsTable, 'PageInit', (pageinitTime/1000) + ' ('+format_currency(100*pageinitTime/pageloadTime)+'%) '+machinePerfInfo);
                resultsAsTable = addPetDataRow(resultsAsTable, 'Other', (unmeasuredTime/1000) + ' ('+format_currency(100*unmeasuredTime/pageloadTime)+'%)');
            }

            resultsAsTable = addPetDataRow(resultsAsTable,'Page', emptyIfNull( base_t_url ));
            resultsAsTable = addPetDataRow(resultsAsTable,'Email', emptyIfNull( base_t_user_email ));
            resultsAsTable = addPetDataRow(resultsAsTable,'Time', getdatestring(renderendtime)+' '+gettimestring(renderendtime)+' GMT '+(renderendtime.getTimezoneOffset() > 0 ? '+' : '')+(renderendtime.getTimezoneOffset()/60));
            resultsAsTable += '</table>';
            logoSpan.ondblclick = new Function("nlShowPet('', 'get_nlPetContent().submitAsCase()','" + resultsAsTable + "');");
        }

        if ( window.doPerfdbLogging && endtoendTime != null && parseInt(endtoendTime) > (parseInt(pageloadTime) + parseInt(base_t_servertime)) )
        {
            var params = new Array();
            params['url'] = base_t_url;
            if ( window.renderstarttime != null )
                params['pageload'] = pageloadTime;
            if ( window.headerstarttime != null )
                params['header'] = headerTime;
            if ( window.pageinitstart != null )
                params['pageinit'] = pageinitTime;
            if ( window.staticscriptstarttime != null )
                params['staticscript'] = staticscriptTime;
            if ( window.dynamicscriptTime != null )
                params['dynamicscript'] = dynamicscriptTime;
            if ( window.footerscriptTime != null )
                params['footerscript'] = footerscriptTime;
            if ( endtoendTime != null )
                params['endtoend'] = endtoendTime;
            if ( base_t_whence != null )
                params['whence'] = base_t_whence;
            if ( base_t_sql != null )
                params['sqlcalls'] = base_t_sql;
            if ( base_t_sqltime != null )
                params['sqltime'] = base_t_sqltime;
            if ( base_t_servertime != null )
                params['servertime'] = base_t_servertime;
            if ( base_t_ssstime != null )
                params['ssstime'] = base_t_ssstime;
            if ( base_t_method != null )
                params['method'] = base_t_method;
            if ( base_t_fcalls != null )
                params['fcalls'] = base_t_fcalls;
            if ( base_t_ftime != null )
                params['ftime'] = base_t_ftime;
            if ( base_t_nthreadid != null )
                params['nthreadid'] = base_t_nthreadid;
            new NLXMLHttpRequest( true ).requestURL( '/app/PerfRenderTime.nl', params, null, true )
        }
    }
    catch ( e ) { }   
}

function addPetDataRow(dataThusFar, colName, colValue)
{
    var newData;

    if(!dataThusFar)
        newData = "";
    else
        newData = dataThusFar;

    newData += '<tr><td class="textbold">' + colName + '</td><td>&nbsp;</td><td>' + colValue + '</td></tr>';

    return newData;
}


var loggedBeforeUnload = false;
function logStartOfRequest( type )
{
    if ( window.doPageLogging )
    {
        if ( type != 'onunload' || !window.loggedBeforeUnload )
        {
            var start = new Date().getTime();
            var whence = document.location.href.substring( document.location.href.indexOf( document.location.pathname ) );
            document.cookie = 'base_t=start:'+start+'|whence:'+whence+'; path=/';
        }
        window.loggedBeforeUnload = (type == 'beforeonunload');
    }
}


function setStartOfRequestLoggers( )
{
    if ( window.doPageLogging )
    {
        var unload = window.onunload;
        var beforeunload = window.onbeforeunload;
        window.onunload = unload != null && unload instanceof Function ? function() { unload(); logStartOfRequest( 'onunload' ) } : new Function("logStartOfRequest('onunload')");
        window.onbeforeunload = beforeunload != null && beforeunload instanceof Function ? function() { var x = beforeunload(); if ( x != null ) return x; logStartOfRequest( 'beforeonunload' ) } : new Function("logStartOfRequest('beforeonunload')") ;
    }
}

