/******************************************************************************
$Workfile: GraphicCommon.js $
$Revision: 36 $
$Author: Dmcginnis $

common functions used by the RtGraphic webpart.

Copyright © 2004 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
*******************************************************************************/

function OpenProcessBook(webPartProperties,timeRange) 
{
	var filename = "";
	
	try
	{
	    
		var wpp = webPartProperties.XMLDocument;
		if (wpp.selectSingleNode("WebPartProperties/SelectedFile/AdhocValue") != null) 
			if (wpp.selectSingleNode("WebPartProperties/SelectedFile/AdhocValue").text != "")
				filename = webPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedFile/AdhocValue").text;		
			else if (wpp.selectSingleNode("WebPartProperties/SelectedFile/AdhocValue").text != "")
				filename = webPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedFile/CurrentValue").text;
			else
				filename = webPartProperties.XMLDocument.selectSingleNode("WebPartProperties/FullFilename").text;
		else
			filename = webPartProperties.XMLDocument.selectSingleNode("WebPartProperties/FullFilename").text;
						
	}
	catch (e) {}
	
	if ((filename.length > 0) && (filename.substring((filename.length - 18)).toLowerCase() != "pigraphicerror.svg"))
	{
		var sTimeStamp;
		nd = timeRange.XMLDocument.selectSingleNode("RtWPTimeRange/StartTime");
		sTimeStamp = nd.selectSingleNode("CurrentValue").text + ";";
		nd = timeRange.XMLDocument.selectSingleNode("RtWPTimeRange/EndTime");
		sTimeStamp += nd.selectSingleNode("CurrentValue").text;

		try	{
			var pb = new ActiveXObject("PbLaunchApp.Ctrl.2");
			pb.EditDocument2(window,filename,sTimeStamp);
			}
		catch(e) 
			{
				alert(errProcessbook);
			}
	}
	else
		alert(errNoFile);
}


function InverseColor(hexcolor)
{
        if(hexcolor.length<7||hexcolor.length>7){
			return "#ff0000";	//red
        }
        
        r=hexcolor.slice(1,3);
        g=hexcolor.slice(3,5);
        b=hexcolor.slice(5,7);
        
        r1=16*giveHex(r.slice(0,1));
        r2=giveHex(r.slice(1,2));
        r=r1+r2;

        g1=16*giveHex(g.slice(0,1));
        g2=giveHex(g.slice(1,2));
        g=g1+g2;

        b1=16*giveHex(b.slice(0,1));
        b2=giveHex(b.slice(1,2));
        b=b1+b2;
        
		//extreme inverse
		if (r>127)
			r=0;
		else
			r=255;
			
		if (g>127)
			g=0;
		else
			g=255;
			
		if (b>127)
			b=0;
		else
			b=255;

        newColor="#"+DecToHex(r)+""+DecToHex(g)+""+DecToHex(b)

		return(newColor);

}
var hexbase="0123456789ABCDEF";
function DecToHex(number) 
{
	return hexbase.charAt((number>> 4)& 0xf)+ hexbase.charAt(number& 0xf);
}
function giveHex(s)
{
	s=s.toUpperCase();
	return parseInt(s,16);
}

function XMLDecode(str)
{
	var tempStr = "";
	tempStr = str;
	while (tempStr.indexOf("&23")>-1)
		tempStr = tempStr.replace("&23","#");
	while (tempStr.indexOf("&3d")>-1)
		tempStr = tempStr.replace("&3d","=");
	return tempStr;
}



/*********************************************************************************************/
//                      
/*********************************************************************************************/

function GraphicObject() {
	this.IsAdhoc = false;
	this.wpq;
	this.wpsc;
	this.PiGraphicDoc;
	this.PiGraphicError;
	this.SvgDoc;
	this.SvgObj;
	this.SvgScript;
	this.DocObj;
	this.SvgAnnObj;	
	this.TimerId = 0;
	this.IsUpdating = true;
	this.DefaultIsUpdating = false;
	this.SVGIsUpdating = false;
	this.UpdateInterval;
	this.UpdateStartTime;
	this.UpdateEndTime;
	this.SoapClient;
	this.WebPartProperties;
	this.Document;
	this.WebPartDataConfig;
	this.TimeRange;
	this.WebPartODBCData;
	this.WebPartPICalcData;
	this.UpdateDataConfig;
	this.UpdateODBCData;
	this.UpdatePICalcData;
	this.AdhocQueryDataConfig;
	this.AdhocQueryDatasetConfig;  
	this.AdhocTagList;
	this.AssemblyName;
	this.ClassName;
	this.SelColor;
	this.SelectedSymbols = new Array();

	this.UniqueID;
	this.ServerConns = 0;
	this.ClientConns = 0;
	this.ClearedCtr = 0;
	
	this.Ready = false;

	//Function Definitions
	this.RtGraphicParamsOut;

	this.DoUpdate = _doUpdate;
	this.Update = _update;
	this.SoapCallback = _soapCallback;
	this.FileModified = _fileModified;

	this.InitContextMenu = _initContextMenu;
	this.UpdateContextMenu = _updateContextMenu;
	
	this.OnSymbolClick = _onSymbolClick;
	this.ClearSelectedSymbols = _clearSelectedSymbols;
	this.RemoveSelectedSymbol = _removeSelectedSymbol
	this.AddSelectedSymbol = _addSelectedSymbol
	this.SelectSymbols = _selectSymbols;
	this.SelectSymbol = _selectSymbol;

	this.OpenAdhocTrend = _openAdhocTrend;
	this.OpenAdhocSVG = _openAdhocSVG;

	this.ServerConnectGO = _serverConnectGO;
	this.ClientConnectGO = _clientConnectGO;
	this.ConnectionTags = _connectionTags;
    this.Unload = _unload;
	
    function _unload() {
      this.SoapClient.xml.abort();
    }


	function _doUpdate(updXML) 
	{
		// save updating callback data
		if (updXML == null || updXML[0] == null || updXML[1] == null)
			return;
			
		this.PiGraphicDoc.innerHTML	= updXML[0];
		try{this.PiGraphicError.innerHTML = updXML[1];}
		catch(e){}
			
		if (updXML[1].substring(0,2) != 'OK') // error
		{
			if (updXML[1] != null)
			{
				if (this.IsAdhoc == true)
				{
					adhClearRtWPErrors();
					adhAddToRtWPErrors(updXML[1]);
				}
				else
				{
					ClearRtWPErrors(this.wpq);
					AddToRtWPErrors(this.wpq, updXML[1]);
				}
			}
		}
		else
		{
			if (this.IsAdhoc == true)
				adhClearRtWPErrors();
			else
				ClearRtWPErrors(this.wpq);
		}
		if (updXML[0] == null)
			return;

		try	{

			var docFrag = this.SvgObj.window.parseXML(updXML[0],this.SvgDoc);
			var docFragNodes = docFrag.firstChild.childNodes;
			if ((docFragNodes  == null) || (docFragNodes.length == 0 ))
			return;
			var x = docFragNodes.length;
			for( var n = 0 ; n < x ; n++ ) 
			{
				id = docFragNodes.item(0).getAttribute("id");
				if (id.length > 0) 
				{
					currentNode = this.SvgDoc.getElementById(id);
					if (currentNode != null) 
					{
						prnt = currentNode.parentNode;
						prnt.replaceChild(docFragNodes.item(0),currentNode);
					}
					else 
					{
						this.SvgDoc.appendChild(docFragNodes.item(0));
					}
				}
				else 
				{
					this.SvgDoc.appendChild(docFragNodes.item(0));
				}
			}
		}
		catch(e)
		{}
	}


	function _update() 
	{
		var thisobj = this;
	    
	    if (!this.Ready)
			return;
		
		
		function soapCallback(r) {
			thisobj.SoapCallback(r);
		}

		try 
		{
			var w = this.SvgObj.parentElement.offsetWidth;
			var tNode = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/ClientWPHeight");
			tNode.firstChild.text = this.SvgObj.parentElement.offsetHeight;
			tNode = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/ClientWPWidth");
			tNode.firstChild.text = this.SvgObj.parentElement.offsetWidth;
			this.SvgAnnObj.wp_H = parseInt(eval('GraphicObj'+ this.wpq).SvgObj.parentElement.offsetHeight);
			this.SvgAnnObj.wp_W = parseInt(eval('GraphicObj'+ this.wpq).SvgObj.parentElement.offsetWidth);
			
			if(this.DocObj != null)
			{
				try
				{
					this.DocObj.XMLDocument.loadXML(this.DocObj.innerHTML);
					this.SvgAnnObj.vb_H = parseInt(this.DocObj.XMLDocument.selectSingleNode('Document/viewBoxHeight').childNodes.item(0).nodeValue);
					this.SvgAnnObj.vb_W = parseInt(this.DocObj.XMLDocument.selectSingleNode('Document/viewBoxWidth').childNodes.item(0).nodeValue);
					this.SvgAnnObj.vb_Ratio = Math.min((this.SvgAnnObj.wp_H / this.SvgAnnObj.vb_H),(this.SvgAnnObj.wp_W / this.SvgAnnObj.vb_W));
					this.SvgAnnObj.vb_Orientation = ((this.SvgAnnObj.wp_H / this.SvgAnnObj.wp_W) > (this.SvgAnnObj.vb_H / this.SvgAnnObj.vb_W));
				}
				catch(e) 
				{
				}				
			}
			clearTimeout(this.TimerId);
			this.UpdateStartTime = new Date();
			if (this.SoapClient != null) 
			{
				params = new Array(10);

				params[0] = this.WebPartProperties.xml;
				params[1] = this.Document.innerHTML;
				try{params[2] = this.WebPartDataConfig.innerHTML;	}
				catch(e){params[2] = "";}
				params[3] = this.TimeRange.XMLDocument.xml;
				params[4] = "CELL_CONSUMER_UPDATE";
				try{params[5] = this.WebPartODBCData.innerHTML;}
				catch(e){params[5] = "";}
				try{params[6] = this.WebPartPICalcData.innerHTML;}
				catch(e){params[6] = "";}
				try{params[7] = this.UpdateDataConfig.innerHTML;}
				catch(e){params[7] = "";}
				try{params[8] = this.UpdateODBCData.innerHTML;}
				catch(e){params[8] = "";}
				try{params[9] = this.UpdatePICalcData.innerHTML;}
				catch(e){params[9] = "";}

				if(params[2] == "" && params[5] == "" && params[6] == "" ) 
				{
					// if no data source, stop update
				}
				else
				{			
					this.SoapClient.call
						("getUpdates",
							this.AssemblyName,
							this.ClassName,
							this.wpq,
							RegionalSettings.XMLDocument.xml,
							rtLocale,
							GetSPLangID(),
							params,
							soapCallback);
				}
			}
		}
		catch (e) 
		{			
			var i = 0;
		}
	}	

	function _soapCallback(response)
	{
		if ((response == null) || (response.length == 0))
			AddToRtWPErrors(this.wpq, emptyResponseMessage);
			
		var thisobj = this;
	    
		function doUpdate(r) {
		thisobj.DoUpdate(r);
		}

		if(response[0] == 'CELL_CONSUMER')
		{
		    //this.WebPartProperties.innerHTML = response[1];
			try{this.WebPartProperties.loadXML( response[1]);}
			catch(e){};
			try{this.Document.innerHTML = response[2];}
			catch(e){};
			try{this.WebPartDataConfig.innerHTML = response[3];}
			catch(e){};
			this.TimeRange.innerHTML = response[4];
			try{this.WebPartODBCData.innerHTML = response[5];}
			catch(e){};
			try{this.WebPartPICalcData.innerHTML = response[6];}
			catch(e){};
			try{this.AdhocQueryDataConfig.loadXML( response[9]);}
			catch(e){};
			try{this.AdhocQueryDatasetConfig.loadXML( response[10]);}
			catch(e){};
			
			//update queries
			try{this.UpdateDataConfig.innerHTML = response[12];}
			catch(e){};			
			try{this.UpdateODBCData.innerHTML = response[13];}
			catch(e){};
			try{this.UpdatePICalcData.innerHTML = response[14];}
			catch(e){};
				
			//save defs section that contains the context menu definition
			var nd = this.SvgDoc.getElementById("MenuDefinition");		
			
			//replace entire svg document
			var svgNode = this.SvgObj.window.parseXML(response[8],this.SvgDoc);
			prnt = this.SvgDoc.firstChild.parentNode;
			prnt.replaceChild(svgNode,this.SvgDoc.firstChild);

			//add the context menu back
			if (nd != null)
				this.SvgDoc.documentElement.appendChild(nd);
				

			//DO NOT REMOVE! - to print svg document
			//string = this.SvgObj.window.printNode(this.SvgDoc.documentElement, this.SvgDoc);
			//alert(string);			
			
			resp = new Array(1);
			resp[0] = response[7];
			resp[1] = response[11];	//OK or error message
			
			doUpdate(resp);
									
			this.SVGIsUpdating = true;

			var hasFile = true;			
			var filename = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedFile/CurrentValue").text;
			var ndAhSVG = this.SvgDoc.getElementById("AdhocSVG");

			if ((filename.length > 0) && (filename.substring((filename.length - 18)).toLowerCase() != "pigraphicerror.svg"))
			{
				var nUpdating = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/updating");
				if (nUpdating != null)
				{
					if (nUpdating.text == "false")
						this.SVGIsUpdating = false;
				}	
				
				
				//enable ad hoc svg context menu item
				if (this.IsAdhoc==false)
					ndAhSVG.setAttribute("enabled","yes");
				else
					ndAhSVG.setAttribute("enabled","no");
					
				this.SvgScript.updateMenu();
			
			}
			else
			{
				//update 'unconfigured' message
				var nd = this.SvgDoc.getElementById("RtGraphicMSG");
				nd.firstChild.nodeValue = errNotConfigured;

				ndAhSVG.setAttribute("enabled","no");
			
				hasFile = false;
				this.SVGIsUpdating = false;
			}

			this.SvgScript.updateMenu();
			
			var mnu = document.all["WebPart" + this.wpq + "_Menu"];
			if (mnu != null) {
				var mi = mnu.all["OpenProcessBook"];
				if (mi != null) {
					mi.disabled = !hasFile;
				}
				var mi = mnu.all["OpenAdhocSVG"];
				if (mi != null) {
					mi.disabled = !hasFile;
				}
				var mi = mnu.all["OpenAdhocTrend"];
				if (mi != null) {
					mi.disabled = !this.SVGIsUpdating;
				}
			}
			
			//set selection rectangle color
			var backgroundcolor = this.SvgDoc.rootElement.getAttribute("fill");
			if (backgroundcolor.length == 7)
				this.SelColor = InverseColor(backgroundcolor);
			
			if ((!this.IsAdhoc) && (this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedSymbols") != null))
			{
				var selectedSymbols = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedSymbols").text;
				if (selectedSymbols != "")
					this.SelectSymbols(selectedSymbols);				
			}
			
		}
		else
		{
		
			if (response[2] == 'CELL_CONSUMER_UPDATE')	// && response[1] == 'OK')
			{
				try{this.UpdateDataConfig.innerHTML = response[3];}
				catch(e){};			
				try{this.UpdateODBCData.innerHTML = response[4];}
				catch(e){};
				try{this.UpdatePICalcData.innerHTML = response[5];}
				catch(e){};
			}

			this.DoUpdate(response);
		}
		
		this.Ready = true;		

		// start update timer			
		if (this.SVGIsUpdating) {
			if (this.IsUpdating) {
				if (this.DefaultIsUpdating == true) {
					var delta = (new Date()) - this.UpdateStartTime;
					if (delta < this.UpdateInterval) {
						clearTimeout(this.TimerId);
						this.TimerId = setTimeout("update"+this.wpq+"()",this.UpdateInterval - delta);
					}
					else {
	 					clearTimeout(this.TimerId);
						this.TimerId = setTimeout("update"+this.wpq+"()",this.UpdateInterval);
					}
				}
			}
		}
	}


	//handle client side file changes from buttons and parameter connections
	function _fileModified(fileName)//obj
	{
		var thisobj = this;
	    
		function soapCallback(r) {
		thisobj.SoapCallback(r);
		}


		try
		{
			clearTimeout(this.TimerId);
			if (this.SoapClient != null) 
			{
				var params = new Array(8);
				for(var i = 0;i < 8 ;i++)
				{
					params[i] = "";
				}
				
				//update the WPQ property to indentify the web part
				var nd = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/WPQ")
				if (nd != null)
				{
					nd.text = this.wpq;
				}
				
				nd = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/BaseURL")
				if ((!this.IsAdhoc) && (nd != null))
				{
					nd.text = L_Menu_BaseUrl;
				}
				
				nd = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/ClientWPHeight");
			    nd.text = this.SvgObj.clientHeight;
			    nd = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/ClientWPWidth");
			    nd.text = this.SvgObj.clientWidth;

				
				params[0] = this.WebPartProperties.XMLDocument.xml;			
				params[1] = fileName;
				params[3] = this.TimeRange.XMLDocument.xml;
				params[4] = "CELL_CONSUMER";
				
				this.SoapClient.call
					("getUpdates",
						this.AssemblyName,
						this.ClassName,
						"",
						RegionalSettings.XMLDocument.xml,
						rtLocale,
						GetSPLangID(),
						params,
						soapCallback);
						
			}
			
		}
		catch (e) {}
		
		

	}

	/********************************************************/
	/*             Symbol Selection Functions               */
	/********************************************************/

	function _onSymbolClick(evt) {

		var sym = evt.target;
		//search for the root SVG node
		var b = !(sym.parentNode == sym.ownerDocument.rootElement );
		while(b)
		{
			sym = sym.parentNode;
			b = !(sym.parentNode == sym.ownerDocument.rootElement );
		}

		if (evt.getDetail() == 2)
		{
			if ((this.ServerConns == 0) && !(this.ClientConns > 0 && browserDesignMode == "true"))
				this.OpenAdhocTrend();		
		}
		else
		{
			if (evt.shiftKey == false)
			{
				this.ClearSelectedSymbols(evt,sym.id);
			}
				
			this.SelectSymbol(sym, evt.shiftKey);	
			
			
			if (this.ClientConns > 0)
			{
				try {
					this.ClientConnectGO();
				}
				catch(e)
				{
					AddToRtWPErrors(this.wpq, e.message);
				}
			}
			
			if (this.ServerConns > 0)
			{
				try {
					this.ServerConnectGO();
				}
				catch(e)
				{
					AddToRtWPErrors(this.wpq, e.message);
				}
			}		
					
		}			
		
	}


	function _selectSymbols(symbolnames)
	{
		var sym = null;
		
		var symbols = symbolnames.split(';');
		for (i=0; i<symbols.length; i++)
		{	
			sym = this.SvgDoc.getElementById(symbols[i]);
			if (sym != null)
				this.SelectSymbol(sym,false);
		}
				
	}

	function _selectSymbol(sym,shiftKey)
	{
		var tags = null;
		var rects = null;
		var found = false;
		
		rects = sym.getElementsByTagName("rect");
		tags = sym.getElementsByTagName("DataSource");
		for (var i=0; i < rects.length; i++)
		{
			rect = rects.item(i);
			if (rect.hasAttribute("selected"))
			{	
				if (shiftKey == true)
				{				
					if (rect.getAttribute("selected") == "true")
					{
						rect.setAttribute("stroke","none");
						rect.setAttribute("selected","false");
						this.RemoveSelectedSymbol(sym.id);
					}
					else					
					{
						rect.setAttribute("stroke",this.SelColor);
						rect.setAttribute("selected","true");	
						this.AddSelectedSymbol(sym.id, tags);					
					}
				}
				else
				{
					rect.setAttribute("stroke",this.SelColor);
					rect.setAttribute("selected","true");
					this.AddSelectedSymbol(sym.id, tags);
				}
				found = true;
				break;
			}				
		}
		
		if (found == false && sym.id.length > 0)
		{
			//create a 'select' rectangle to display around the symbol
			var bBox = sym.getBBox();
			var node = sym.ownerDocument.createElement('rect');
			node.setAttribute('id', sym.id+'_select');
			node.setAttribute('selected','true');
			node.setAttribute('x',bBox.x-5);
			node.setAttribute('y',bBox.y-5);
			node.setAttribute('width',bBox.width+10);
			node.setAttribute('height',bBox.height+10);
			node.setAttribute('stroke',this.SelColor);
			node.setAttribute('stroke-width','2');
			node.setAttribute('fill','none');
			
			if (sym.hasChildNodes == true)			
				sym.insertBefore(node,sym.firstChild);
			else
			{
				var gnode = sym.ownerDocument.createElement('g');
				var id = sym.id;				
				gnode.setAttribute('id',id);
				sym.parentNode.insertBefore(gnode,sym);
				
				sym.parentNode.removeChild(sym);
				
				gnode.appendChild(node);
				
				sym.setAttribute('id',id+'_value');
				gnode.appendChild(sym);
				sym = gnode;
			}
			
			this.AddSelectedSymbol(sym.id, tags);
		}
		
		this.UpdateContextMenu();

	}

	function _addSelectedSymbol(id, tags)
	{
		this.SelectedSymbols[id] = tags;		
	}

	function _removeSelectedSymbol(id)
	{
		delete this.SelectedSymbols[id];
	}

	function _clearSelectedSymbols(evt,id)
	{
		this.ClearedCtr = 0;
		
		var rect = null;
		var rects = evt.currentNode.ownerDocument.getElementsByTagName("rect");
		for (var i=0; i < rects.length; i++)
		{
			rect = rects.item(i);
			if (rect.hasAttribute("selected") && rect.hasAttribute("id"))
			{		
				myId = rect.getAttribute("id")			
				if (rect.getAttribute("id") != id+"_select")
				{
					var attr = rect.getAttribute("selected");
					if (attr=="true")
					{	
						rect.setAttribute("selected","false");
						rect.setAttribute("stroke","none");
						this.ClearedCtr++;
					}
				}
			}
		}
		
		for(var symbolKey in this.SelectedSymbols)
			delete this.SelectedSymbols[symbolKey];
	}




	function _openAdhocTrend()
	{
		var tags;
		var pitags = "";
		var dstags = "";
		
		this.AdhocTagList.XMLDocument.loadXML("<tags/>");
		var tagsnode = this.AdhocTagList.XMLDocument.selectSingleNode("tags");
		var tagnode;
		var tagname;
		var tagtype;
		var key;
		
		for(var symbolKey in this.SelectedSymbols)
		{
			tags = this.SelectedSymbols[symbolKey];	
			if (tags != null)
			{			
				var sTags = "";
				for (var i=0; i<tags.length; i++)
				{
					var nd = tags.item(i);
					tagname = XMLDecode(nd.getAttribute("tag"));
					tagtype = nd.getAttribute("type");
					key = nd.getAttribute("key");	//ClientResultKey
					switch (tagtype)
					{
						case "1":
							tagtype = "pitag";
							break;
						case "2":
							tagtype = "dataset";
							break;
						case "3":	//alias
						case "4":	//property
							tagtype = "mrd";
							break;
						case "5":	//currentcontext
							break;
					}
						
					if (tagtype != "5")	//don't trend mrd current context tags
					{
						var nds = tagsnode.childNodes;
						var bNotFound = true;
						for (var k=0;k < nds.length; k++) 
						{
							if ((nds.item(k).getAttribute("name").toLowerCase() == tagname.toLowerCase())
							    && (nds.item(k).getAttribute("key").toLowerCase() == key.toLowerCase()))
							{
								bNotFound = false;
								break;
							}
						}	
						if (bNotFound)
						{				
							tagnode = this.AdhocTagList.XMLDocument.createElement("tag");
							tagnode.setAttribute('name', tagname);
							tagnode.setAttribute('type', tagtype);
							tagnode.setAttribute('key', key);
							tagsnode.appendChild(tagnode);
						}
					}
				}		
			}				
		}
		
		
		if (tagsnode.childNodes.length > 0)
		{
			showAdhocTrendGraphic(this.AdhocTagList.XMLDocument.xml,this.TimeRange,this.AdhocQueryDataConfig,this.AdhocQueryDatasetConfig,this.wpsc);		
		}
		else
			alert(errSelectSymbol);
		
	}



	function _openAdhocSVG()
	{	 
		var filename = this.WebPartProperties.XMLDocument.selectSingleNode("WebPartProperties/SelectedFile/CurrentValue").text;
		
		if ((filename.length > 0) && (filename.substring((filename.length - 18)).toLowerCase() != "pigraphicerror.svg"))
			showAdhocSVG(this.WebPartProperties,this.TimeRange,this.DocObj);		
		else
			alert(errNoFile);		
	}


	/* ****************************************************************************** */
	/*                            Connection Functions                                */
	/* ********************************************************************************/

	function _serverConnectGO()
	{
		var symbols = "";
		var tags = "";		
		
		for(var symbolKey in this.SelectedSymbols)
		{
			if (symbols.length == 0)
				symbols = symbolKey;
			else
				symbols += ";" + symbolKey;
			
			tags = this.ConnectionTags(symbolKey,tags);
		}
		if (tags.length > 2)
			tags = tags.substring(0,tags.length-1);

		var values = "targetguid";
		values += "*SymbolName=" + symbols;
		values += "#DataSource=" + tags;

		if ((this.ClearedCtr > 0) || (symbols.length > 0))
		{
			__doPostBack(this.UniqueID, values);
		}	
	}

	function _clientConnectGO()
	{
		var symbols = "";
		var datasources = "";
		var tags = "";
		
			
		for(var symbolKey in this.SelectedSymbols)
		{
			if (symbols.length == 0)
				symbols = XMLDecode(symbolKey);
			else
				symbols += ";" + XMLDecode(symbolKey); 

			tags = this.ConnectionTags(symbolKey,tags);			
		}
		if (tags.length > 2)
		{
			tags = tags.substring(0,tags.length-1);
			datasources = XMLDecode(tags);
		}


		try
		{
			if ((this.ClearedCtr > 0) || (symbols.length > 0))
			{
				var parametersOutReadyEventArgs = new ParametersOutReadyEventArgs();
				parametersOutReadyEventArgs.ParameterValues = new Array(2);
				//SymbolName
				parametersOutReadyEventArgs.ParameterValues[0] = symbols;
				//DataSource
				parametersOutReadyEventArgs.ParameterValues[1] = datasources;
					
				this.RtGraphicParamsOut.ParametersOutReady(parametersOutReadyEventArgs);
			}
		}
		catch(ex)
		{
			AddToRtWPErrors(this.wpq, "[NodeClick] " + ex.message);
		}
	}
		
	function _connectionTags(symbolKey,tags)
	{
		//var tags = "";
		var seltags = this.SelectedSymbols[symbolKey];
		for (var i=0; i<seltags.length; i++)
		{
			var nd = seltags.item(i);
			var tagname = nd.getAttribute("tag") + ";";
			var tagtype = nd.getAttribute("type");
				
			if (tagtype != "5")	//don't use mrd current context tags
			{
				if (tags.toLowerCase().indexOf(tagname.toLowerCase()) == -1)
				{
					tags += tagname; 			
				}
			}
		}						
		
		return(tags);
	}

	function _initContextMenu()
	{
		try {
			var nd = this.SvgDoc.getElementById("AdhocTrend");		
			nd.setAttribute("onactivate","GraphicObj"+this.wpq+".OpenAdhocTrend()");
			
			nd = this.SvgDoc.getElementById("AdhocSVG");		
			nd.setAttribute("onactivate","GraphicObj"+this.wpq+".OpenAdhocSVG()");
			
			this.SvgScript.updateMenu();		
			
		}catch(e){}
	}
	
	function _updateContextMenu()
	{
		var yesno = "no";		
		for(var symbolKey in this.SelectedSymbols)		
		{
			yesno = "yes";
			break;
		}
		try {
			var nd = this.SvgDoc.getElementById("AdhocTrend");
			nd.setAttribute("enabled",yesno);
			
			this.SvgScript.updateMenu();
			
					
		}catch(e){}
	}


}







