/******************************************************************************
$Workfile: RtWPv2_0.js $
$Revision: 119 $
$Author: Cnorton $

Common RtWebPart page javascript objects and methods. 

Copyright © 2006 OSIsoft, Inc. All rights reserved.
Unpublished - rights reserved under the copyright law of the United States.
USE OF A COPYRIGHT NOTICE IS PRECAUTIONARY ONLY AND DOES NOT
IMPLY PUBLICATION OR DISCLOSURE.
THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF OSIsoft, Inc. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, Inc.
RESTRICTED RIGHTS LEGEND
Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227.7013

OSIsoft, Inc.
777 Davis St., San Leandro CA 94577
*******************************************************************************/

// Object used in most web service calls
// This is defined as a C# struct in the OSISoft.PI.WebServices.PIDataServices namespace
function TimeZoneInfo() {
	this.Bias;
	this.DisplayName;
	this.StandardDate = new Object();
	this.StandardDate.Month;
	this.StandardDate.Day;
	this.StandardDate.Hour;
	this.StandardBias;
	this.DaylightDate = new Object();
	this.DaylightDate.Month;
	this.DaylightDate.Day;
	this.DaylightDate.Hour;
	this.DaylightBias;
}

// Return object from GetTimeRange() web method
// This is defined as a C# struct in the OSIsoft.RtWebParts.RtTimeRange namespace
function TimeRangeData() {
	this.TimeRange = "";
	this.TimeRangeLocalized = "";
	this.TimeRangeUTF = "";
	this.StartTime = "";
	this.StartTimeLocalized = "";
	this.StartTimeUTF = "";
	this.EndTime = "";
	this.EndTimeLocalized = "";
	this.EndTimeUTF = "";
	this.CurrentTimeLocalized = "";
	this.IsUpdating = false;	// true if end time is "*" or "*+" but not if "*-"
	this.ErrorMessage = "";
}

// Returns a TimeZoneInfo object. If an XML data island with id="RegionalSettings"
// is found, then the object is initialized using values found there.
// boolean reload_xml directs the function to either return any existing TimeZoneInfo
// object or to forcibly reload the XML data island (IE: in case a script changed it)
var rt_TimeZoneInfo = null;
function RtGetTimeZoneInfo(reload_xml) {
	try {
		if( rt_TimeZoneInfo != null && (typeof(reload_xml) == "boolean" && reload_xml != true))
			return rt_TimeZoneInfo;
		rt_TimeZoneInfo = new TimeZoneInfo();
		var timeZoneXmlDoc;
		timeZoneXmlDoc = RtWP_LoadXML(timeZoneXmlDoc, "RegionalSettings"); // RegionalSettings.XMLDocument.xml
		rt_TimeZoneInfo.Bias = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/Bias").text;
		rt_TimeZoneInfo.DisplayName = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/DisplayName").text;
		rt_TimeZoneInfo.StandardDate.Month = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/StandardDate/Month").text;
		rt_TimeZoneInfo.StandardDate.Day = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/StandardDate/Day").text;
		rt_TimeZoneInfo.StandardDate.Hour = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/StandardDate/Hour").text;
		rt_TimeZoneInfo.StandardBias = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/StandardBias").text;
		rt_TimeZoneInfo.DaylightDate.Month = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/DaylightDate/Month").text;
		rt_TimeZoneInfo.DaylightDate.Day = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/DaylightDate/Day").text;
		rt_TimeZoneInfo.DaylightDate.Hour = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/DaylightDate/Hour").text;
		rt_TimeZoneInfo.DaylightBias = timeZoneXmlDoc.selectSingleNode("TimeZoneInfo/DaylightBias").text;
	}
	catch(ex) {
		alert(ex.message);
	}
	return rt_TimeZoneInfo;
}

// Adds an error message to an XML data island that stores error
// messages for the user to review via a web part toolbar.
function AddToRtWPErrors(wpq, errorMsg)
{
	var rtErrorsXmlDoc;
	var rtErrorsXmlId = "RtErrors" + wpq;

	try
	{
		rtErrorsXmlDoc = RtWP_LoadXML(rtErrorsXmlDoc, rtErrorsXmlId);
		nodeList = rtErrorsXmlDoc.selectSingleNode("ArrayOfString");

		// Create a new XML element to hold the received errorMsg
		newNode = rtErrorsXmlDoc.createElement("string");

		var dttm = new Date();

		var utcDttm;
		var utcOffset = dttm.getTimezoneOffset();
		if (utcOffset > 0) {
		  utcDttm = dttm.valueOf() - (utcOffset * 60 * 1000);
		}
		else {
		  utcDttm = dttm.valueOf() + (utcOffset * 60 * 1000);
		}
		var dttmStamp = "[" + formatUTCDateTime(utcDttm, dateTimeFormatString) + "] ";


				
		newText = rtErrorsXmlDoc.createTextNode(dttmStamp + errorMsg);
		newNode.appendChild(newText);

		// Now append the new error node to our ArrayOfString
		nodeList.appendChild(newNode);

		// Save our newly created node to the XML data island
		myXMLBlock = document.getElementById(rtErrorsXmlId);
		myXMLBlock.innerHTML = rtErrorsXmlDoc.xml;

		// Add the error count to our toolbar text
		wpErrorCount = document.getElementById("RtWPErrorCount" + wpq);
		if( wpErrorCount != null ) { // Backward compatibility w/1.0
			numErrors = nodeList.childNodes.length;
			var num = new Number(wpErrorCount.innerHTML) + 1;
			wpErrorCount.innerHTML = num.toString();
		}

		// Last step is to unhide the toolbar table by setting its display style attribute to "block"
		myXMLBlock = document.getElementById("RtWPToolBar" + wpq);
		myXMLBlock.style.display = "block";
	}
	catch(ex)
	{
		if( typeof(wpq) != "undefined" && wpq != "" )
			alert(CreateLocalizedString(errAddErrorMsg,errorMsg,wpq,ex.message));
		else
			alert(errorMsg);
	}
}
// Clears all error messages from the XML data island that stores error
// messages for the user to review via a web part toolbar.
function ClearRtWPErrors(wpq)
{
	var rtErrorsXmlDoc;
	var rtErrorsXmlId = "RtErrors" + wpq;

	try
	{
		rtErrorsXmlDoc = RtWP_LoadXML(rtErrorsXmlDoc, rtErrorsXmlId);
		nodeList = rtErrorsXmlDoc.selectSingleNode("ArrayOfString");
		
		// Clear all the error messages
		numNodes = nodeList.childNodes.length;
		for(i=0; i<numNodes; i++)
		{
			nodeList.removeChild(nodeList.firstChild);
		}

		// Save our cleared node list to the XML data island
		myXMLBlock = document.getElementById(rtErrorsXmlId);
		myXMLBlock.innerHTML = rtErrorsXmlDoc.xml;

		// Clear the error count
		document.getElementById("RtWPErrorCount" + wpq).innerHTML = "0";
		
		// Last step is to hide the toolbar table by setting its display style attribute to "none"
		myXMLBlock = document.getElementById("RtWPToolBar" + wpq);
		myXMLBlock.style.display = "none";
	}
	catch(ex)
	{
		alert("[ClearRtWPErrors] " + ex.message);
	}
}
function ParameterInProperty() {
	this.Description = "";
	this.ParameterName = "";
	this.ParameterDisplayName = "";
	this.Required = false;
}
function ParameterOutProperty() {
	this.Description = "";
	this.ParameterName = "";
	this.ParameterDisplayName = "";
	this.Required = false;
}
function ParametersOutReadyEventArgs() {
	this.ParameterValues = null;
}
function ParametersOutProviderInitEventArgs() {
	this.ParameterOutProperties = null;
}
function CellProviderInitEventArgs() {
	this.FieldName = "";
	this.FieldDisplayName = "";
}
function CellReadyEventArgs() {
	this.Cell = "";
}
function ShowRtValuesAdhocTrend( timeRange, dataConfig, dataview, column, pitag, summaries, query ) {
  showAdhocTrend("",timeRange,dataConfig,"","",summaries,query,dataview,column,pitag);
}
function showTrendAdhocTrend( tags, timeRange, dataConfigdoc ) {
  showAdhocTrend("",timeRange,dataConfig,"","","","","","","",doc);
}

function showAdhocTrend( tags, timeRange, dataConfig, adhocQueryTags, adhocDataConfig, 
                         summaries, updateQuery, dataview, column, pitag, doc, trendObj, rtGraphicsTagDoc,wpsc ) {
                         
    var oWPSC;
    if ((wpsc != undefined) && (wpsc != null))
		oWPSC = wpsc;
	else
		oWPSC = WPSC;
    
	args = new Array();
	args[0] = tags;
	
	if ((dataConfig != undefined) && (dataConfig != "")) {
	  args[1] = dataConfig.XMLDocument.xml;
	}
	else {
	  args[1] = null;
	}
	
	args[2] = timeRange.XMLDocument.xml;
	args[3] = window;

	try {
	if (adhocQueryTags != undefined)
	    args[5] = adhocQueryTags;
	else
	    args[5] = null;
	
	if ((adhocDataConfig != undefined) && (adhocDataConfig != ""))
	    // 21422 - pass in string insteae of object
	    args[6] = adhocDataConfig.XMLDocument.xml;
    else
	    args[6] = null;
	
	if (summaries != undefined)
	    args[7] = summaries;
    else
	    args[7] = null;
	
	if (updateQuery != undefined)
	    args[8] = updateQuery;
    else
	    args[8] = null;
	
	if (dataview != undefined)
	    args[9] = dataview;
    else
	    args[9] = null;
	
	if (column != undefined)
	    args[10] = column;
    else
	    args[10] = null;
	
	if (pitag != undefined)
	    args[11] = pitag;
    else
	    args[11] = null;
	
	if (doc != undefined)
	    args[12] = doc;
    else
	    args[12] = null;

	if (rtGraphicsTagDoc != undefined)
	    args[13] = rtGraphicsTagDoc;
    else
	    args[13] = null;

	if (wpsc != undefined)
	    args[14] = wpsc;
    else
	    args[14] = null;
  }
  catch (e){
	  args[5] = null;
	  args[6] = null;
	  args[7] = null;
	  args[8] = null;
	  args[9] = null;
	  args[10] = null;
	  args[11] = null;
	  args[12] = null;
	  args[13] = null;
	  args[14] = null;
  }

//  wpqpos = dataConfig.outerHTML.indexOf("WPQ");
//  wpq = dataConfig.outerHTML.substring(wpqpos,wpqpos+4);
//  dsd = eval("dataSetDescriptions" + wpq);
//  dsd = "none";
  if (trendObj != undefined) {
    args[4] = trendObj;
  }
  else {
    args[4] = "none";
  }
	// Sanity check, sent to browser by base class from ICEWebPart2.cs
	if( typeof(dateTimeFormatString) == "undefined" )
		dateTimeFormatString = "";
	
	var url = "/" + webServicesVDIR + "/adhoctrend.aspx?lcid=" + rtLocale + "&langID=" + GetSPLangID();
	//22460 - changed encode method so that plus sign is encoded.
	url += "&tz=" + encodeURIComponent(RegionalSettings.XMLDocument.xml);
	url += "&decimalSeparator=" + escape(decimalSeparator);
	url += "&dateFormatString=" + escape(dateFormatString);
	url += "&dateTimeFormatString=" + escape(dateTimeFormatString);
	try
	{
	    var data = window.showModelessDialog(url, args, "dialogHeight:480px;dialogWidth:610px;status:no;help:no;resizable:yes;unadorned:yes;scroll:no", false);
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}


function showAdhocTrendGraphic(tags, timeRange, dataConfig, adhocDataConfig, wpsc) {
  showAdhocTrend("",timeRange,dataConfig,"",adhocDataConfig,"","","","","","","",tags,wpsc);
}

function showAdhocSVG( wpp, timeRange, doc ) {
	args = new Array();
	args[0] = wpp.XMLDocument.xml;
	args[1] = timeRange.XMLDocument.xml;
	args[2] = doc.XMLDocument.xml;	
	args[3] = WPSC;	
	args[4] = window;
	
	// Sanity check, sent to browser by base class from ICEWebPart2.cs
	if( typeof(dateTimeFormatString) == "undefined" )
		dateTimeFormatString = "";
	
	var url = "/" + webServicesVDIR + "/adhocsvg.aspx?lcid=" + rtLocale + "&langID=" + GetSPLangID();
	//22460 - changed encode method so that plus sign is encoded.
	url += "&tz=" + encodeURIComponent(RegionalSettings.XMLDocument.xml);
	url += "&decimalSeparator=" + escape(decimalSeparator);
	url += "&dateFormatString=" + escape(dateFormatString);
	url += "&dateTimeFormatString=" + escape(dateTimeFormatString);
	try
	{
	var data = window.showModelessDialog(url, args, "dialogHeight:"+document.body.offsetHeight+"px;dialogWidth:"+document.body.offsetWidth+"px;status:no;help:no;resizable:yes;center:yes;unadorned:yes;scroll:no", false);
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}

function getDataSet(dataSetNameCtl) {
    try
    {
	    var dataSet = window.showModalDialog('/' + webServicesVDIR + '/datasetsdialog.aspx?lcid=' + rtLocale + '&langID=' + GetSPLangID(),window,
		    "font-size:4;dialogHeight:415px;dialogWidth:308px;status:no;help:no;resizable:yes;unadorned:yes;scroll:no");
	    if ((dataSet != '') && (dataSet != null)) {
    		dataSetNameCtl.value = dataSet;
            dataSetNameCtl.onchange();
	    }
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
function getDataSetOnly(dataSetNameCtl) {
	try
	{
	    var dataSet = window.showModalDialog('/' + webServicesVDIR + '/datasetsonlydialog.aspx?lcid=' + rtLocale + '&langID=' + GetSPLangID(),window,
		    "dialogHeight:254px;dialogWidth:308px;status:no;help:no;resizable:yes;unadorned:yes;scroll:no");
	    if ((dataSet != '') && (dataSet != null)) {
    		dataSetNameCtl.value = dataSet;
            dataSetNameCtl.onchange();
	    }
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
function getProviders() {
    try
    {
	    var dataSet = window.showModelessDialog('/' + rtWebPartsVDIR + '/connectionsdialog.aspx?lcid=' + rtLocale + '&langID=' + GetSPLangID(),window,
		 "dialogTop:0;dialogHeight:702px;dialogWidth:950px;status:no;help:no;resizable:no;unadorned:yes;scroll:no");
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}

var wizard;
function Wizard(trgt, url) {
	this.target = trgt;
	try
	{
	    var data = window.showModalDialog("/" + url,window,"status:no;help:no;resizable:yes;unadorned:yes");
	    trgt.value = data;
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
function showWizard(trgt, url) {
	wizard = new Wizard(trgt,url);
}
function showMore(moreCtl) {
    try
    {
	    var propVal = window.showModalDialog('/' + webServicesVDIR + '/more.aspx?val=' + moreCtl.value,window,
		 "dialogHeight:315px;dialogWidth:319px;status:no;help:no;resizable:no;unadorned:yes");
	    if ((propVal != '') && (propVal != null)) {
    		moreCtl.value = propVal;
    	}
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
var tagsearch;
function TagSearch(target) {
	this.target = target;
	var url = '/' + webServicesVDIR + '/TagSearch.aspx?lcid=' + rtLocale + '&langID=' + GetSPLangID();
	try
	{
	    var retval = window.showModalDialog(url,this,"dialogHeight:575px;dialogWidth:600px;status:0;help:0;resizable:yes;unadorned:1;scroll:0");
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
function showTagSearch(target) {
	tagsearch = new TagSearch(target);
	if (target.value != "")
		target.onchange();
}
// Loads a block of XML data from the given HTML id.
function RtWP_LoadXML(XmlDocActiveXObj, xmlElementId)
{
	try
	{
		myXMLBlock = document.getElementById(xmlElementId);
		XmlDocActiveXObj = new ActiveXObject("MSXML2.DOMDocument");
		XmlDocActiveXObj.loadXML(myXMLBlock.innerHTML);
		return XmlDocActiveXObj;
	}
	catch(ex)
	{
		alert("[RtWP_LoadXML] " + ex.message);
		return null;
	}
}
// Opens a modal dialog window to display error messages for a given web part.
function ShowRtWPErrorDialog(webPartTitle, wpq)
{
	var webPart = new Object();
	
	re = /&27/g;
	webPart.Title = webPartTitle.replace(re, "'");
	re = /&22/g;
	webPart.Title = webPart.Title.replace(re, '"');
	webPart.target = this;
	try
	{
		webPart.cssUrl = document.all.onetidThemeCSS.href;
	}
	catch(e)
	{
		webPart.cssUrl = "";
	}
	try
	{
		var rtErrorsXmlDoc;
		rtErrorsXmlDoc = RtWP_LoadXML(rtErrorsXmlDoc, "RtErrors" + wpq);
		nodeList = rtErrorsXmlDoc.selectSingleNode("ArrayOfString");
		numNodes = nodeList.childNodes.length;

		webPart.ErrorList = new Array(numNodes);
		for(i=0; i<numNodes; i++)
		{
			node = nodeList.childNodes.item(i);
			name = node.nodeName.toString();
			value = node.text.toString();
			webPart.ErrorList[i] = value;
		}
	}
	catch(ex)
	{
		alert("[ShowRtWPErrorDialog] " + ex.message);
	}
	var url = '/' + webServicesVDIR + '/RtWPErrorDialog.aspx?lcid=' + rtLocale + '&langID=' + GetSPLangID();
	try
	{
	    window.showModalDialog(url, webPart, "dialogHeight:300px;dialogWidth:500px;dialogTop:px;dialogLeft:px;center:Yes;help:No;resizable:Yes;status:No");
	}
	catch(ex)
	{
	    // If the IE7 pop-up blocker is enabled, we might get an access denied error
	    alert(ex.message);
	}
}
function ConnectionFoundInProviderParameterMappingNodes(wpq, nodeList)
{
	if( nodeList == null )
		return false;
	try
	{
		num_ProviderParameterMapping_Nodes = nodeList.childNodes.length;
		// Iterate through each "<ProviderParameterMapping>" child node
		for(i=0; i<num_ProviderParameterMapping_Nodes; i++)
		{
			selectedNode = nodeList.childNodes.item(i).selectSingleNode("Selected");
			nodeValue = selectedNode.text.toString().toLowerCase();
			if( eval(nodeValue) )
				return true;
		}
		return false;
	}
	catch(ex)
	{
		AddToRtWPErrors(wpq, ex.message);
		return false;
	}
	return false;
}
// Examines the RtWPTimeRange XML data island and determines if there is
// a connected time range provider for this web part
function ConnectedToTimeRangeProvider(wpq, RtWPTimeRange_XMLDocument)
{
	try
	{
		nodeList = RtWPTimeRange_XMLDocument.selectSingleNode("RtWPTimeRange/StartTime/SelectedProviderParameterNames");
		if( nodeList != null && ConnectionFoundInProviderParameterMappingNodes(wpq, nodeList) )
			return true;
		nodeList = RtWPTimeRange_XMLDocument.selectSingleNode("RtWPTimeRange/EndTime/SelectedProviderParameterNames");
		if( nodeList != null && ConnectionFoundInProviderParameterMappingNodes(wpq, nodeList) )
			return true;
	}
	catch(ex)
	{
		AddToRtWPErrors(wpq, ex.message);
		return false;
	}
	return false;
}

// Enables RtTimeRange web part buttons
function EnableTimeRangeBtns(wpq) {
	try
	{
		if( typeof(wpq) == "undefined" )
			wpq = "";
		document.getElementById("btnApply" + wpq).disabled = false;
		document.getElementById("btnRevert" + wpq).disabled = false;
		document.getElementById("btnBack" + wpq).disabled = false;
		document.getElementById("btnForward" + wpq).disabled = false;
	}
	catch(ex)
	{
		AddToRtWPErrors(wpq, "EnableTimeRangeBtns(): " + ex.message);
	}
}

// Disables RtTimeRange web part buttons
function DisableTimeRangeBtns(wpq) {
	try
	{
		if( typeof(wpq) == "undefined" )
			wpq = "";
		document.getElementById("btnApply" + wpq).disabled = true;
		document.getElementById("btnRevert" + wpq).disabled = true;
		document.getElementById("btnBack" + wpq).disabled = true;
		document.getElementById("btnForward" + wpq).disabled = true;
	}
	catch(ex)
	{
		AddToRtWPErrors(wpq, "DisableTimeRangeBtns(): " + ex.message);
	}
}

function formatDataBase(nbr, n, lessThanOneSwitchToSci, greaterThenOneSwitchToSci) {
  if (parseInt(n) > 0) {
    return parseFloat(nbr).toFixed(n);
  }
  if (parseInt(n) < 0) {
    if ((Math.abs(nbr) > greaterThenOneSwitchToSci) || (Math.abs(nbr) < lessThanOneSwitchToSci)) {
       return parseFloat(nbr).toExponential(Math.abs(n) - 1);
    }
  }  

  return parseFloat(nbr).toPrecision(Math.abs(n));      
}

function formatGeneral(nbr) {
	var intLength = Math.round(parseInt(nbr)).toString().length;
	if (intLength > 5) 
	{
		return Math.round(parseFloat(nbr)).toString();
	}
	else
	{
		return parseFloat(nbr).toFixed(6 - intLength);
	}
}


function RComma(S) { 
  S = String(S)
  var RgX = /^(.*\s)?([-+\u00A3\u20AC]?\d+)(\d{3}\b)/
  return S == (S=S.replace(RgX, "$1$2,$3")) ? S : RComma(S) 
}

function formatNumber(nbr, n, typ, fmt) {
  
  switch (fmt) {
    case "Scientific":
      //21098 - round integers
      if (typ == "INTEGER") {
        str = parseFloat(Math.round(nbr)).toExponential((Math.round(nbr).toString()).length); 
      }
      else {
        str = parseFloat(nbr).toExponential(5); 
      }
      str = str.replace('e','E');
      while (str.indexOf('0E')>-1) str=str.replace('0E','E'); // remove trailing zeros
      str=str.replace('.E','E'); // remove trailing decimal point if necessary
      var idxPlus = str.indexOf('+');
      if ((str.length - (++idxPlus)) < 2) {
        str = str.replace('+','+0');
      }
      var idxMinus = str.indexOf('-');
      if (idxMinus > 0 && (str.length - (++idxMinus)) < 2) {
        str = str.replace('-','-0');
      }
      return str;
    case "0":
      return Math.round(nbr);
      
    case "0.00":
      return (parseFloat(nbr).toFixed(2));
    case "#,##0":
      return RComma(Math.round(nbr));
    case "#,##0.00":
      return RComma(parseFloat(nbr).toFixed(2));
    case "(#,##0)":
      if (nbr < 0) {
        return "(" + RComma(Math.round(Math.abs(nbr))) + ")";
      }
      else {
        return RComma(Math.round(nbr));      
      }
    case "(#,##0.00)":
      if (nbr < 0) {
        return "(" + RComma(parseFloat(Math.abs(nbr)).toFixed(2)) + ")";
      }
      else {
        return RComma(parseFloat(nbr).toFixed(2));      
      }
    case "0%":
      return (Math.round(nbr * 100)) + "%" ;
    case "0.00%":
	  return (parseFloat(nbr * 100).toFixed(2) + "%");
    default:
      break;
  }
  
  
  if (n == "") {
    n = -6;
  }
  
  var lessThanOneSwitchToSci;
  var greaterThenOneSwitchToSci;
  if (typ != "INTEGER") {
    lessThanOneSwitchToSci = .1;
    greaterThenOneSwitchToSci = Math.pow(10,Math.abs(n));
  }
  
  if (nbr == 0) {
    return nbr;
  }
  
  if ((parseInt(n) == 0) || (typ == "INTEGER")) {
    if (nbr > Math.pow(10,8)) {
      x = Math.round(parseFloat(nbr)).toExponential(4);
    }
    else {
      x = Math.round(parseFloat(nbr));      
    }
  }
      
  if ((parseInt(n) != 0) && (typ != "INTEGER")) {
    if (fmt == "General") {
			x = formatGeneral(nbr);
    }
    else {
			x = formatDataBase(nbr,n,lessThanOneSwitchToSci,greaterThenOneSwitchToSci)      
		}
  }
  return x.toString().replace('.',decimalSeparator);
}
//var MNAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
//var DNAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZZ(x) {return(x < 0||x > 9?"":"0")+x}	
// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatUTCDateTime(dt, format) {
	date = new Date(dt);
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getUTCFullYear()+"";
	var M=date.getUTCMonth()+1;
	var d=date.getUTCDate();
	var E=date.getUTCDay();
	var H=date.getUTCHours();
	var m=date.getUTCMinutes();
	var s=date.getUTCSeconds();
	var ms = date.getMilliseconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZZ(M);
	value["MMM"]=MNAMES[M-1];
	value["NNN"]=MNAMES[M+11];
	value["d"]=d;
	value["dd"]=LZZ(d);
	value["E"]=DNAMES[E+7];
	value["EE"]=DNAMES[E];
	value["H"]=H;
	value["HH"]=LZZ(H);
	value["0"]=ms;
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZZ(value["K"]);
	value["kk"]=LZZ(value["k"]);
	if (H > 11) { value["tt"]=pm; }
	else { value["tt"]=am; }
	value["m"]=m;
	value["mm"]=LZZ(m);
	value["s"]=s;
	value["ss"]=LZZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
}

// Cross-browser window onLoad handler function
function HookUpOnLoadEvent(eventHandler) {
	// DOM2
	if ( typeof window.addEventListener != "undefined" )
		window.addEventListener( "load", eventHandler, false );
	// IE
	else if ( typeof window.attachEvent != "undefined" ) {
		window.attachEvent( "onload", eventHandler );
	} else {
		if ( window.onload != null ) {
			var oldOnload = window.onload;
			window.onload = function ( e ) {
				oldOnload( e );
				eventHandler();
			};
		} else {
			window.onload = eventHandler;
		}
	}
}

// Cross browser getElementById function
function RtGetElementById(e) {
	if(typeof(e)!='string') return e;
	if(document.getElementById) e=document.getElementById(e);
	else if(document.all) e=document.all[e];
	else e=null;
	return e;
}

function RtEditDocumentWithProgID2(strDocument, varProgID, varEditor)
{
    var objEditor;
    if (strDocument.charAt(0) == "/" || strDocument.substr(0,3).toLowerCase() == "%2f")
    {
		// Chris 20060307: Add support for extranets with reverse proxies
		var baseUrl = document.URL;
		var pos = baseUrl.indexOf("//") + 2;
		pos += baseUrl.substr(pos).indexOf("/");
		strDocument = baseUrl.substr(0, pos) + strDocument;
	}
    try
    {
        objEditor = new ActiveXObject(varEditor + ".2");
        if (!objEditor.ViewDocument2(window, strDocument, varProgID))
            alert(L_EditDocumentRuntimeError_Text);
        //window.onfocus = RefreshOnNextFocus;
        return;
    }
    catch (e)
    {
    }
    try
    {
        objEditor = new ActiveXObject(varEditor + ".1");
        //window.onfocus = null;
        if (SzExtension(strDocument) == "ppt" && varProgID == "")
            varProgID = "PowerPoint.Slide";
        if (!objEditor.EditDocument(strDocument, varProgID))
            alert(L_EditDocumentRuntimeError_Text);
        //SetWindowRefreshOnFocus();
        return;
    }
    catch (e)
    {
        alert(L_EditDocumentProgIDError_Text);
    }
}

function RtViewXls(strDocument)
{
    var objEditor;
    if (strDocument.charAt(0) == "/" || strDocument.substr(0,3).toLowerCase() == "%2f")
    {
		// Chris 20060307: Add support for extranets with reverse proxies
		var baseUrl = document.URL;
		var pos = baseUrl.indexOf("//") + 2;
		pos += baseUrl.substr(pos).indexOf("/");
		strDocument = baseUrl.substr(0, pos) + strDocument;
	}
    try
    {
		var xlApp = new  ActiveXObject("Excel.Application");
        var xlSheet = new ActiveXObject("Excel.Sheet");
        xlSheet.Application.Visible = true;
        xlSheet.Application.Workbooks.Open(strDocument);
        return;
    }
    catch (e)
    {
		alert(L_EditDocumentRuntimeError_Text);
    }
}

function GetSPBaseURL()
{
	return L_Menu_BaseUrl; 
}

function GetSPLangID()
{
	return L_Menu_LCID;
}

var isAdhoc = false;

function ShowSingleAdhocTrend(tagName, dataQry, updateQry, timeRangeObj)
{
	var tags;
	var pitags = "";
	var dstags = "";
	var tmp,tmp1,tmp2;
	var adhocQuery = null;
	var AdhocTagList = new ActiveXObject("MSXML2.DOMDocument");
	AdhocTagList.loadXML("<tags/>");
	var tagsnode = AdhocTagList.selectSingleNode("tags");
	var sTag = tagName;
	
	
	var oDQuery = dataQry;
	var oQuery;
	var oUQuery = updateQry; 
	var oQryNodes;
	var paraNode;
	var pNodes;
	if(oUQuery != null && oUQuery.length > 0)
		oQuery = oUQuery;
	else
		oQuery = oDQuery;
			
	if (oQuery != null)
	{
		oQryNodes = oQuery.selectNodes("ArrayOfRtWPDataQuery/RtWPDataQuery");
		for (var i = 0 ; i < oQryNodes.length;i++)
		{
			if(tagsnode.childNodes != null && tagsnode.childNodes.length > 0)
				break;
			tmp2 = oQryNodes.item(i).selectSingleNode('ViewName').text;
			switch (tmp2)
			{
				case 'ALIAS':
					paraNode = oQryNodes.item(i).selectNodes('ICEParameters/RtWPDataQueryParameter').item(3);
					tmp = paraNode.selectSingleNode('CurrentValue').text;
					tmp1 = 'alias.' + sTag;
					if(paraNode == null)
						continue;
					if( tmp.toUpperCase() != tmp1.toUpperCase() )
						continue;
					tagnode = AdhocTagList.createElement("tag");
					tagnode.setAttribute('name', sTag);
					tagnode.setAttribute('type', 'mrd');
					tagnode.setAttribute('key', oQryNodes.item(i).selectSingleNode('ClientDataResultKey').text);
					tagsnode.appendChild(tagnode);
					break;
				case 'PI Tags':
					tagnode = AdhocTagList.createElement("tag");
					paraNode = oQryNodes.item(i).selectSingleNode("ColumnNames");
					if(paraNode == null || paraNode.text.indexOf(sTag) == -1)
					{
						if(oQryNodes.item(i).text.indexOf(sTag) == -1)
							continue;
					}
					tagnode.setAttribute('name', sTag);
					tagnode.setAttribute('type', 'pitag');
					tagnode.setAttribute('key', oQryNodes.item(i).selectSingleNode('ClientDataResultKey').text);
					tagsnode.appendChild(tagnode);
				
					break;
				default:
					//case 'Dataset':
						paraNode = oQryNodes.item(i).selectSingleNode("ColumnNames");
						for(var j = 0 ; j < paraNode.childNodes.length ;j++)
						{
							if ((tmp2 + "." +  paraNode.childNodes.item(j).text).toUpperCase() != sTag.toUpperCase())
								continue;
							tagnode = AdhocTagList.createElement("tag");
							tagnode.setAttribute('name', sTag);
							tagnode.setAttribute('type', 'dataset');
							tagnode.setAttribute('key', oQryNodes.item(i).selectSingleNode('ClientDataResultKey').text);
							tagsnode.appendChild(tagnode);
							break;
						}
						break;
			}
			
		}
	}
	if(tagsnode.childNodes != null && tagsnode.childNodes.length > 0)
	{
		showAdhocTrend(AdhocTagList.xml,timeRangeObj, dataQry);
	}
}

function CreateLocalizedString(literalString) {
	var s = literalString;
	for (var i=1; i < arguments.length; i++) {
	  s = s.replace("{" + (i-1) + "}",arguments[i]);
	}
	return s;
}

// writes html into the html stream. used to write <embed> and <object> elements so
// that the ActiveX user interface is automatically activated.
function EmbedObject(src) {
  document.write(src);
}
