var mServerName="";
var mNewsServerName="";
var mSecGUID=0;
var mIsPremium=false;
var mNewsSplitChar="";
var mPricesSplitChar="#";
var mRowSep=String.fromCharCode(13);
var cSecCheck=15121969;
var cDefaultTimestamp="3-Dec-1970 12:50:38";
var cPrices=1,cNews=2,cReports=3
var mPricesTimer,mReportsTimer,mNewsTimer;
var mFlashTime=500;
var mReports;
var mNews;
var mPrices;

var mDataRunning=false;
function Setup()
{
	mPricesTimer=parseInt(document.getElementById('pricestimer').innerHTML);	
	mReportsTimer=parseInt(document.getElementById('reportstimer').innerHTML);
	mNewsTimer=parseInt(document.getElementById('newstimer').innerHTML);
	mFlashTime=parseInt(document.getElementById('flashtime').innerHTML);
	mServerName=document.getElementById('serverName').innerHTML;
	mNewsServerName=document.getElementById('NewsServerName').innerHTML;
	mSecGUID=parseInt(document.getElementById('SecGUID').innerHTML)+cSecCheck;
	mIsPremium=(document.getElementById('prxxm').innerHTML=='true'?true:false);
	mNewsSplitChar=document.getElementById('NewsSplitChar').innerHTML;
	var dataTimeout=parseInt(document.getElementById('DataTimeout').innerHTML);
	SetXMLHTTPObject();
	mPrices=new Data(cPrices,mPricesSplitChar,mPricesTimer,dataTimeout);
	mReports=new Data(cReports,mNewsSplitChar,mReportsTimer,dataTimeout);
	mNews=new Data(cNews,mNewsSplitChar,mNewsTimer,dataTimeout);	
	mDataRunning=true;
	if(mPricesTimer>0)setTimeout("mPrices.Refresh(false)",mPricesTimer);	
	if(mReportsTimer>0)setTimeout("mReports.Refresh(false)",mReportsTimer);
	if(mNewsTimer>0)setTimeout("mNews.Refresh(false)",mNewsTimer);		
	DataStatus(3);		
}

function StopData()
{
	mDataRunning=false;
}

function PriceData()
{
	this.Symbol="";
	this.Fields=new Array();
}

function Page(ID,_symbols,_fields,_updateTypes)
{
	try{
	this.PageID=ID;
	this.symbols=_symbols.replace(' ','');
	this.fields=_fields.replace(' ','');
	this.updateTypes=_updateTypes.replace(' ','');
	var localSymbols=this.symbols.split('!');	
	this.symbolList=new Array();
	for(var i=0;i<localSymbols.length;i++)
	{
		var d=localSymbols[i].indexOf(':');
		if(d>=0)localSymbols[i]=localSymbols[i].substr(0,d);				
		this.symbolList.length++;
		this.symbolList[this.symbolList.length-1]=localSymbols[i];	
	}
	this.fieldList=this.fields.split('!');
	this.updateTypesList=this.updateTypes.split('!');
	}catch(e){		
	}
}

function Data(mode,_splitChar,_refreshRate,_timeout)
{
	this.SetupXMLHTTPconnection=function()
	{
		switch (mode)
		{
		case cPrices:
		{
			mPricesHTTPRequest=new XMLHttpRequest();
			return mPricesHTTPRequest;
		}
		case cNews:
		{
			mNewsHTTPRequest=new XMLHttpRequest();
			return mNewsHTTPRequest;
		}
		case cReports:
		{
			mReportsHTTPRequest=new XMLHttpRequest();
			return mReportsHTTPRequest;
		}			
		}		
	}

	this.Mode=mode;
	this.Pages=new Array;
	this.symbols="";
	this.fields="";
	this.updateTypes="";
	this.symbolList=new Array;
	this.fieldList=new Array;
	this.updateTypesList=new Array;
	this.LastTimeStamp=cDefaultTimestamp;
	this.UpdateMutex=false;
	this.SplitChar=_splitChar;
	this.Request=this.SetupXMLHTTPconnection();
	this.RefreshRate=_refreshRate;
	this.Timeout=_timeout;
	this.LastRequestCheck=null;

	this.Refresh=function(timedOut)
	{
		try
		{
			if (this.GetUpdateMutex)
			{	
				var u=this.GetURL();							
				if(u!="")
				{
					if(this.Mode==cPrices)
						this.RequestData(mServerName+u,this.ProcessResponseCallBack,this,timedOut);
					else
						this.RequestData(mNewsServerName+u,this.ProcessResponseCallBack,this,timedOut);						
				}
				else
					StartRefresh(timedOut,this.RefreshRate,this);
			}
			else StartRefresh(timedOut,50,this);
		}catch(e){StartRefresh(true,this.RefreshRate,this);}
	}
	
	this.RequestData=function(url,callbackFunction,_Data,timedOut)
	{
		try
		{
			if (mDataRunning)
			{		
				if (this.Request)
				{
					if(this.Mode==cPrices && !timedOut)DataStatus(1);
					var req=this.Request;
					req.open("GET", url, true);		
					req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
					req.setRequestHeader("Cache-Control","no-cache");
					req.setRequestHeader("Connection","keep-alive");
				  req.onreadystatechange = function()
					{
						try{
						if (req.readyState == 4 && req.status == 200 && req.responseText)
						{
							callbackFunction(req.responseText,_Data);
						}
						}catch(e){}
					};
				  req.send(null);
					switch (this.Mode)
					{
						case cPrices:
						{
							this.LastRequestCheck=setTimeout("mPrices.Retry();",this.Timeout);
							break;
						}
						case cNews:
						{
							this.LastRequestCheck=setTimeout("mNews.Retry();",this.Timeout);
							break;
						}
						case cReports:
						{
							this.LastRequestCheck=setTimeout("mReports.Retry();",this.Timeout);
							break;
						}										
					}
				}
				else alert('No XMLHTTP object');
			}
		}catch(e){
			StartRefresh(true,_Data.RefreshRate,_Data);
		}
	}

	this.Retry=function()
	{
		try
		{
			if (this.Mode==cPrices)DataStatus(3);
			this.Refresh(true);
		}
		catch(e){}	
	}

	this.ProcessResponseCallBack=function(responseText,_Data)
	{
		try
		{
			if (_Data.LastRequestCheck)clearTimeout(_Data.LastRequestCheck);
			if (mDataRunning)
			{
				if (_Data.Mode==cPrices)DataStatus(2);
				_Data.ProcessResponse(responseText);
			}
		}
		catch(e){}
		finally
		{
			_Data.ReleaseUpdateMutex();
			if (_Data.Mode==cPrices)setTimeout("DataStatus(0);",100);
			StartRefresh(false,_Data.RefreshRate,_Data);
		}
	}

	this.GetUpdateMutex=function()
	{
		var res=false;
		if (!this.UpdateMutex)
		{
			this.UpdateMutex=true;
			res=true;
		}
		return res;
	}

	this.ReleaseUpdateMutex=function()
	{
		this.UpdateMutex=false;
	}

	this.AddDataRequest=function(ID,_symbols,_fields,_updateTypes)
	{
		try
		{
			if (this.Mode!=cPrices)this.LastTimeStamp=cDefaultTimestamp;
			var newPage=new Page(ID,_symbols,_fields,_updateTypes);
			var fld,sym;
			this.Pages.length++;
			this.Pages[this.Pages.length-1]=newPage;
			var localSymbols=_symbols.split('!');
			for(var i=0;i<localSymbols.length;i++)
			{
				sym=localSymbols[i].replace(' ','')
				if (!ItemExists(this.symbolList,sym))
				{
					if (this.symbols!="")this.symbols+='!';
					this.symbols+=sym;
					var d=sym.indexOf(':');
					if(d>=0)sym=sym.substr(0,d);				
					this.symbolList.length++;
					this.symbolList[this.symbolList.length-1]=sym;
				}
			}
			var localFields=_fields.split('!');
			for(var i=0;i<localFields.length;i++)
			{
				fld=localFields[i].replace(' ','');
				if(!ItemExists(this.fieldList,fld))
				{
					if(this.fields!="")this.fields+='!';
					this.fields+=fld;
					this.fieldList.length++;
					this.fieldList[this.fieldList.length-1]=fld;
				}
			}		
		}
		catch(e){}
	}
	this.RemovePage=function(ID)
	{
		try
		{
			for (var p=0;p<this.Pages.length;p++)
			{
				if (this.Pages[p].PageID==ID)
				{
					for (var ps=0;ps<this.Pages[p].symbolList.length;ps++)
					{
						var idx=-1;
						var sym=this.Pages[p].symbolList[ps];
						for (var pp=0;pp<this.Pages.length;pp++)
						{
							if (pp!=p)
							{
								idx=ItemExistsIndex(this.Pages[pp].symbolList,sym);
								if (idx>=0)break;
							}
						}						
						if (idx<0)
						{
							this.symbolList=RemoveItem(this.symbolList,sym);
							this.symbols=StringRemove(this.symbols,sym);
							if (EndsWith(this.symbols,'!'))this.symbols=this.symbols.substr(0,this.symbols.length-1);
						}	
					}
					for (var ps=0;ps<this.Pages[p].fieldList.length;ps++)
					{
						var idx=-1;
						var fld=this.Pages[p].fieldList[ps];
						for (var pp=0;pp<this.Pages.length;pp++)
						{
							if (pp!=p)
							{
								idx=ItemExistsIndex(this.Pages[pp].fieldList,fld);
								if (idx>=0)break;
							}
						}					
						if (idx<0)
						{
							this.fieldList=RemoveItem(this.fieldList,fld);						
							this.fields=StringRemove(this.fields,fld);
							if (EndsWith(this.fields,'!'))this.fields=this.fields.substr(0,this.fields.length-1);
						}	
					}					
					this.Pages=RemoveItemIndex(this.Pages,p);					
					break;
				}			
			}
		}
		catch(e){}
	}
	this.GetURL=function()
	{
		var res="";
		if(this.symbols!="" && this.fields!="")
		{
			res='?sym='+this.symbols+'&fld='+this.fields;		
			res+='&zz='+mSecGUID;
			res+='&nr='+(this.Mode==3 || this.Mode==2?'true':'false');
			res+='&prxxm='+(mIsPremium?'true':'false');
			res+='&__='+encodeURIComponent((new Date()).getTime());
			res+='&ts='+this.LastTimeStamp.replace(' ','+').replace(':','%3A');
		}
		return res;
	}
	this.ProcessResponse=function(response)
	{
		var thisData;
		var previousPageID="";
		var dom=null;
		var ignoreRequest=false;
		var row=response.split(mRowSep);		
		try{
		if (row.length>0)
		{
			var ts=row[row.length-1];
			if(ts=="@@LOGOFF@@")
			{
				StopData();
				LogOff();			
			}
			else if ((ts>=this.LastTimeStamp && ts.length>=19 && ts.length<=20) || this.LastTimeStamp==cDefaultTimestamp)
			{
				this.LastTimeStamp=ts;
				if (this.Mode==cPrices)
				{
					var lbld=document.getElementById("lblDate");
					if(lbld && this.LastTimeStamp.length>3)lbld.innerHTML=this.LastTimeStamp.substr(0,this.LastTimeStamp.length-3);
				}
			}
			else ignoreRequest=true;
		}
		if (!ignoreRequest)
		{
			for(var r=0;r<row.length-1;r++)
			{
				if(row[r]=="@@LOGOFF@@")
			  {
					LogOff();
					break;
			  }
				var cells=row[r].split(this.SplitChar);
				thisData=new PriceData;
				for (var c=0;c<cells.length ;c++ )
				{
					switch(c)
					{
						case 0:thisData.Symbol=cells[c];break;
						default:thisData.Fields.length++;thisData.Fields[thisData.Fields.length-1]=cells[c];
					}
				}			
				for (var p=0;p<this.Pages.length;p++)
				{
					if (this.Pages[p].PageID!=previousPageID)
					{					
						dom=GetDOM(this.Pages[p].PageID);
						previousPageID=this.Pages[p].PageID;
					}
					if (dom)
					{
						for (var s=0;s<this.Pages[p].symbolList.length;s++ )
						{
							if (this.Pages[p].symbolList[s]==thisData.Symbol)
							{
								for (var f=0;f<thisData.Fields.length ;f++ )
								{
									for(var ff=0;ff<this.Pages[p].fieldList.length;ff++)
									{
										if(this.Pages[p].fieldList[ff]==this.fieldList[f])
										{
											priceUpdate(thisData.Symbol+"_"+this.fieldList[f],thisData.Fields[f],this.Pages[p].updateTypesList[ff],dom,this.Pages[p].PageID);										
											break;
										}
									}									
								}
								break;
							}
						}
					}
				}
				thisData=null;
			}
		}
		}catch(e){}
	}
}

function StartRefresh(timedOut,delay,_Data)
{
	switch (_Data.Mode)
	{
		case cPrices:
		{
			setTimeout("mPrices.Refresh("+ timedOut + ");",delay);
			break;
		}
		case cNews:
		{
			setTimeout("mNews.Refresh("+ timedOut + ");",delay);
			break;
		}
		case cReports:
		{
			setTimeout("mReports.Refresh("+ timedOut + ");",delay);
			break;
		}		
	}
}


function GetDOM(pageName)
{
	var d; 
	if (top.frames.length > 0) 
	{
		d=document.getElementById("pagename");
		if (d && d.innerHTML==pageName)
			return document;
		else
		{
			for ( var i = 0 ; i < top.frames.length; i++) 
			{	
				if ( top.frames[i].name == pageName ) 
				{
					d=top.frames[i].document;
					if(d)return d;
				}
				if(top.frames[i].frames.length > 0 ) 
				{ 
					for(var j = 0; j <  top.frames[i].frames.length; j++) 
					{ 
						if ( top.frames[i].frames[j].name == pageName ) 
						{
							d=top.frames[i].frames[j].document;
							if(d)return d;
						}
						if(top.frames[i].frames[j].frames.length > 0 ) 
						{
							for(var l = 0; l <  top.frames[i].frames[j].frames.length; l++) 
							{ 
								if ( top.frames[i].frames[j].frames[l].name == pageName ) 
								{
									d=top.frames[i].frames[j].frames[l].document;
									if(d)return d;
								}
							}
						}
					}
				}
			}
		}		
	}
	else 
	{
		d=document.getElementById("pagename");
		if (d && d.innerHTML==pageName)return document;
	}
}

function GetWindow(pageName)
{
	var d; 
	if (top.frames.length > 0) 
	{
		d=document.getElementById("pagename");
		if (d && d.innerHTML==pageName)
			return top;
		else
		{
			for ( var i = 0 ; i < top.frames.length; i++) 
			{	
				if ( top.frames[i].name==pageName)
					return top.frames[i];
				if(top.frames[i].frames.length > 0 ) 
				{ 
					for(var j = 0; j <  top.frames[i].frames.length; j++) 
					{ 
						if (top.frames[i].frames[j].name == pageName )
							return top.frames[i].frames[j];
						if(top.frames[i].frames[j].frames.length > 0 ) 
						{
							for(var l = 0; l <  top.frames[i].frames[j].frames.length; l++) 
							{ 
								if (top.frames[i].frames[j].frames[l].name==pageName)
									return top.frames[i].frames[j].frames[l];
							}
						}
					}
				}
			}
		}		
	}
	else 
	{
		return top;
	}
}

function EndsWith(str,chr)
{
	return (str.length>0 && str.substr(str.length-1,1)==chr)
}

function ItemExists(arr,itm)
{
	var res=false;	
	for (var i=0;i<arr.length ;i++ )
	{
		if (arr[i]==itm)
		{
			res=true;
			break;
		}
	}
	return res;
}

function ItemExistsIndex(arr,itm)
{
	var res=-1;	
	for (var i=0;i<arr.length ;i++ )
	{
		if (arr[i]==itm)
		{
			res=i;
			break;
		}
	}
	return res;
}

function RemoveItemIndex(arr,idx)
{
	var counter=0;
	var newArray=new Array(arr.length-1);
	for (var i=0;i<idx;i++)newArray[counter++]=arr[i];
	for (var i=idx+1;i<arr.length;i++)newArray[counter++]=arr[i];	
	return newArray;		
}

function RemoveItem(arr,itm)
{
	var idx=0;
	var newArray=new Array(arr.length-1);
	for (var i=0;i<arr.length;i++)
	{
		if (arr[i]!=itm)newArray[idx++]=arr[i];
	}
	return newArray;	
}

function StringRemove(str,itm)
{
	var res=str;
	arr=str.split('!');
	for (var s=0;s<arr.length;s++)
	{
		if (arr[s]==itm)
		{
			res="";
			for (var r=0;r<s;r++ )res+=arr[r]+'!';
			for (var r=s+1;r<arr.length;r++ )
			{
				res+=arr[r];
				if (r<arr.length-1)res+='!';
			}
		}
	}
	return res;
}

function AddPrices(ID,symbols,fields,updateTypes)
{
	if (mPrices.GetUpdateMutex)
	{
		mPrices.AddDataRequest(ID,symbols,fields,updateTypes);
		mPrices.ReleaseUpdateMutex();		
	}
	else	
		setTimeout("AddPrices('"+ID+"','"+symbols+"','"+fields+"','"+updateTypes+"');",500);	
}

function RemovePrices(ID)
{
	if (mPrices.GetUpdateMutex)
	{
		mPrices.RemovePage(ID);	
		mPrices.ReleaseUpdateMutex();
	}
	else
		setTimeout("RemovePrices('"+ID+"');",10);
}

function AddNews(ID,symbols,fields,updateTypes)
{
	if (mNews.GetUpdateMutex)
	{
		mNews.AddDataRequest(ID,symbols,fields,updateTypes);
		mNews.ReleaseUpdateMutex();
	}
	else
		setTimeout("AddNews('"+ID+"','"+symbols+"','"+fields+"','"+updateTypes+"');",50);
}

function RemoveNews(ID)
{	
	if (mNews.GetUpdateMutex)
	{
		mNews.RemovePage(ID);	
		mNews.ReleaseUpdateMutex();
	}
	else
		setTimeout("RemoveNews('"+ID+"');",50);
}

function AddReports(ID,symbols,fields,updateTypes)
{
	if (mReports.GetUpdateMutex)
	{
		mReports.AddDataRequest(ID,symbols,fields,updateTypes);
		mReports.ReleaseUpdateMutex();
		
	}
	else
		setTimeout("AddReports('"+ID+"','"+symbols+"','"+fields+"','"+updateTypes+"');",50);
}

function RemoveReports(ID)
{
	if (mReports.GetUpdateMutex)
	{
		mReports.RemovePage(ID);	
		mReports.ReleaseUpdateMutex();
	}
	else
		setTimeout("RemoveReports('"+ID+"');",50);
}

function SetXMLHTTPObject()
{
	if( !window.XMLHttpRequest ) XMLHttpRequest = function()
	{
		try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e){}
	  try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e){}
		try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
	  try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
		throw new Error("Could not find an XMLHttpRequest alternative.")
	};
}

function DataStatus(i)
{	
	for (var p=0;p<=3;p++)
	{
		var o=document.getElementById('imgData'+p);
		if(o)o.style.display=(p==i?'block':'none');
	}
}