// This creates a XMLRequest (ActiveXObject) to be sent to the server
var XmlReq;
var symbolHttp;
var newsymbolHttp;
var tdToEdit;
var updateXML;
var rowtoreplace;
var refreshtimer,refreshindextimer;
var symbolexecuter, indexexecuter;


// This page returns the XML Response for the selected choice
var AjaxServerPageName = "./GetData.aspx";

function addRow(event)
{

	eventkey=event.keyCode;

	if(eventkey==13)
	{
    document.getElementById("symbolspan").style.visibility="hidden";
    symboltoget= document.getElementById("symbol").value;
    //    alert(symboltoget);
    //getSymbolDetails(symboltoget);
    addblank(symboltoget);
    document.getElementById("symbol").value="";
           
	}


}

function  addblank(symbol)
{
var symbolGrid = document.getElementById('SymbolsGrid').getElementsByTagName("tbody")[0];

	// Create a HTML Row
		var row = document.createElement("TR"); 
		
		// Set the style
		row.setAttribute("className","text2");
		row.setAttribute("id", String(symbol).toUpperCase());
	    //row.onmouseover= function (evt) { window.status="Row id: "+this.id; };
				
		// Iterate thorugh the columns of each row
		for(var j=0;j<11;j++)
		{
			// Create a HTML DataColumn
			var cell = document.createElement("TD"); 
	        
			// Store the cotents we got from Response XML into the column
			if(j==0)
			{
			cell.innerHTML = String(symbol).toUpperCase();
			
			//set the id of this first column from rows count.
			cell.setAttribute("id", "symbol"+document.getElementById('symbolRows').value);
			//cell.onmouseover= function (evt) { window.status="Column id:"+this.id+" | Row ID:"+this.parentNode.id; };
		    cell.ondblclick = function (evt) { editSymbol(this);};
			}
			
            else{
            if(j==10){
                cell.innerHTML = format(toDecimal(parseFloat("0.00").toFixed(2)));			
                	cell.setAttribute('align', 'right'); 
                	}
                
            else
                {
                cell.innerHTML = format(toDecimal(parseFloat("0.00").toFixed(2)));
                cell.setAttribute('align', 'right'); 
                }
            }
            
			// Append the new column into the current row
			row.appendChild(cell); 
		}
		
        
		    //if this is the first row then clear the table
				
		    if(document.getElementById('symbolRows').value=='0')
		    {
		    ClearTable("SymbolsGrid");		
		    symbolGrid.appendChild(row);
		    document.getElementById('symbolRows').value=1;
		    }
		
		    //Otherwise Append the current row into the HTML Table(i.e DataGrid)
		
    		else{
	    	symbolGrid.appendChild(row);
		
		    //increament symbol row count by 1
		    var count= parseInt(document.getElementById('symbolRows').value);
		    count= count+1;
		    document.getElementById('symbolRows').value=String(count);
		    }
      

}


function getSymbolDetails(symbols)
{
	
	try
	{
		symbolHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			symbolHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			symbolHttp = null;
		}
	}
	if(!symbolHttp && typeof XMLHttpRequest != "undefined") 
	{
		symbolHttp = new XMLHttpRequest();
	}
	

var requestUrl = "getSymbolDetails.aspx?symbols=" + encodeURIComponent(symbols);
	
//alert(requestUrl);
	
	if(symbolHttp)
	{
		symbolHttp.onreadystatechange = HandleSymbolsResponse;
		symbolHttp.open("GET", requestUrl,  true);
		symbolHttp.send(null);		
	}
}


function HandleSymbolsResponse()
{
	if(symbolHttp.readyState == 4)
	{
	
		if(symbolHttp.status == 200)
		{			
			// Before filling new contents into the DataGrid, clear the cotents by calling this function
			
			// Fill the cleared Datagrid with new XML Reponse
			FillSymbolTable(symbolHttp.responseXML.documentElement);
			// Hides the Process Image Table after displaying the contents
			//imgtbl.style.visibility = 'hidden';
			alert('index agaya' );
		}
		else
		{
			alert("There was a problem retrieving data from the server." );
		}
	}
}

function FillSymbolTable(symbolsRoot)
{

// Gets the response XML
var rootXml = symbolsRoot.getElementsByTagName('SymbolsData'); 
	// Gets the table type content present in the Response XML and gets the data into a variable tbl
var symbolGrid = document.getElementById('SymbolsGrid').getElementsByTagName("tbody")[0];

if(rootXml.context.childNodes.length!=0)
{			
	// Iterate through the table and add HTML Rows & contents into it.
	for(var i=0;i<rootXml.context.childNodes(0).parentNode.childNodes.length;i++)
	{
		// Create a HTML Row
		var row = document.createElement("TR"); 
		
		// Set the style
		row.setAttribute("className","text2");
		row.setAttribute("id", rootXml.context.childNodes(i).childNodes(0).text);
	    //row.onmouseover= function (evt) { window.status="Row id: "+this.id; };
				
		// Iterate thorugh the columns of each row
		for(var j=0;j<rootXml.context.childNodes(0).childNodes.length;j++)
		{
			// Create a HTML DataColumn
			var cell = document.createElement("TD"); 
	        
			// Store the cotents we got from Response XML into the column
			if(j==0)
			{
			cell.innerHTML = rootXml.context.childNodes(i).childNodes(j).text;
			
			//set the id of this first column from rows count.
			cell.setAttribute("id", "symbol"+document.getElementById('symbolRows').value);
			//cell.onmouseover= function (evt) { window.status="Column id:"+this.id+" | Row ID:"+this.parentNode.id; };
		    cell.ondblclick = function (evt) { editSymbol(this);};
			}
			
            else{
            if(j==rootXml.context.childNodes(0).childNodes.length-1){
                cell.innerHTML = format(toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2)));			
                	cell.setAttribute('align', 'right'); 
                	}
                
            else
                {
                cell.innerHTML = toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2));			
                cell.setAttribute('align', 'right'); 
                }
            }
            
			// Append the new column into the current row
			row.appendChild(cell); 
		}
		
        
		    //if this is the first row then clear the table
				
		    if(document.getElementById('symbolRows').value=='0')
		    {
		    ClearTable("SymbolsGrid");		
		    symbolGrid.appendChild(row);
		    document.getElementById('symbolRows').value=1;
		    }
		
		    //Otherwise Append the current row into the HTML Table(i.e DataGrid)
		
    		else{
	    	symbolGrid.appendChild(row);
		
		    //increament symbol row count by 1
		    var count= parseInt(document.getElementById('symbolRows').value);
		    count= count+1;
		    document.getElementById('symbolRows').value=String(count);
		    }
      
            
	}
	
    }

}



function showSymbol()
{
document.getElementById("symbolspan").style.visibility="visible";
document.getElementById("symbol").focus();
}

function toDecimal(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
	
}

function CreateXmlReq()
{
	try
	{
		XmlReq = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlReq = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlReq = null;
		}
	}
	if(!XmlReq && typeof XMLHttpRequest != "undefined") 
	{
		XmlReq = new XMLHttpRequest();
	}
}

//This fucntion is to send the choice into the AJAX Server page for processing
function FetchContents()
{

	var selecteditem = document.Form1.indexlist.value;
	//Starts displaying the Process Image table
	//document.getElementById('imgtbl').style.visibility = 'visible';
	var requestUrl = AjaxServerPageName + "?indexcode=" + encodeURIComponent(selecteditem);
	
	CreateXmlReq();
	
	if(XmlReq)
	{
		XmlReq.onreadystatechange = HandleResponse;
		XmlReq.open("GET", requestUrl,  true);
		XmlReq.send(null);		
	}
}

function HandleResponse()
{

	if(XmlReq.readyState == 4)
	{
	
		if(XmlReq.status == 200)
		{			
			// Before filling new contents into the DataGrid, clear the cotents by calling this function
			ClearTable("MarketData");
			// Fill the cleared Datagrid with new XML Reponse
			FillTable(XmlReq.responseXML.documentElement);
			// Hides the Process Image Table after displaying the contents
			//imgtbl.style.visibility = 'hidden';       
			
			
		}
		else
		{
			//alert("There was a problem retrieving data from the server." );
		}
	}

 //clearInterval(refreshindextimer);	
//refreshindextimer=setTimeout(FetchContents,2000);

}

//Fills the datagrid contents with the newly recieved Response content
function FillTable(scity)
{
	// Gets the response XML
	var auth = scity.getElementsByTagName('MarketDataSet'); 
	// Gets the table type content present in the Response XML and gets the data into a variable tbl
	var tbl = document.getElementById('MarketData').getElementsByTagName("tbody")[0];
			
	// Iterate through the table and add HTML Rows & contents into it.
	for(var i=0;i<auth.context.childNodes(0).parentNode.childNodes.length;i++)
	{
		// Create a HTML Row
		var row = document.createElement("TR"); 
		
		// Set the style
		row.setAttribute("className","text");
		row.setAttribute("bgColor","#E3EAEB");
	    
				
		// Iterate thorugh the columns of each row
		for(var j=6;j<auth.context.childNodes(0).childNodes.length;j++)
		{
			// Create a HTML DataColumn
			var cell = document.createElement("TD"); 
	        // Store the cotents we got from Response XML into the column
			
			if(j==auth.context.childNodes(0).childNodes.length-1)
			{
			cell.innerHTML = format(toDecimal(parseFloat(auth.context.childNodes(i).childNodes(j).text).toFixed(2)));
			cell.setAttribute('align', 'right'); 
			}
			
			else{
			  cell.innerHTML = toDecimal(parseFloat(auth.context.childNodes(i).childNodes(j).text).toFixed(2));
			cell.setAttribute('align', 'right'); 
			}
			// Append the new column into the current row
			row.appendChild(cell); 
		}
		// Append the current row into the HTML Table(i.e DataGrid)
		tbl.appendChild(row);
		
	}
	
}

// Clearing the existing contents of the Datagrid
function ClearTable(tname)
{
//    var tbl= document.getElementsByName("MarketData")[0].getElementsByTagName("tbody")[0];;
var tbl = document.getElementById(tname).getElementsByTagName("tbody")[0];
		var row = tbl.rows.length
	    for (var i=1,j=1;j<row;i++,j++)
	{
		if (tbl.rows.length == 2){i = 1;}
		tbl.deleteRow(i);
		if (tbl.rows.length == i) {i = 0;}
	}
}

function editSymbol(symboltd)
{
value=symboltd.innerHTML;
rowtoreplace= symboltd.parentNode.id;

if (document.all) {
    symboltd.innerHTML =
      '<INPUT ' +
      ' ID="editCell"' +
      ' ONKEYPRESS=" changeRow(event,this.value,\''+symboltd.id+'\'); "  ' + 
      ' ONBLUR="restoreRow(\''+value+ '\',\''+ symboltd.id + '\')" ' +
      ' VALUE="' + symboltd.innerText + '"' + 
      ' Class="Text"' +
      ' SIZE="' + symboltd.innerText.length + '"' +
      '>';
    document.all.editCell.focus();
    document.all.editCell.select();

}
}

function restoreRow(oldValue, td)
{
document.getElementById(td).innerHTML=oldValue;
}

function changeRow(event, newsymbol,tdID)
{
tdToEdit= tdID;

    if(event.keyCode==13)
    {
    //alert(newsymbol+','+tdID);
        
    	
	try
	{
		newsymbolHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			newsymbolHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			newsymbolHttp = null;
		}
	}
	if(!symbolHttp && typeof XMLHttpRequest != "undefined") 
	{
		newsymbolHttp = new XMLHttpRequest();
	}
	

var requestUrl = "getSymbolDetails.aspx?symbols=" + encodeURIComponent(newsymbol);
		
	if(newsymbolHttp)
	{
		newsymbolHttp.onreadystatechange = addNewRow;
		newsymbolHttp.open("GET", requestUrl,  true);
		newsymbolHttp.send(null);		
	}
    
    }
    

}

function addNewRow()
{
//alert("In add new row "+tdToEdit);


if(newsymbolHttp.readyState == 4)
	{
	
		if(newsymbolHttp.status == 200)
		{			
		
		replaceRow(newsymbolHttp.responseXML.documentElement,tdToEdit);
		newsymbolHttp=null;	
		}
		else
		{
			alert("There was a problem retrieving data from the server." );
		}
	}
	
}

function replaceRow(root,tdid)
{

//alert("replace row ="+tdid);
var rootXml = root.getElementsByTagName('SymbolsData'); 
if(rootXml.context.childNodes.length!=0)
{
	// Gets the table type content present in the Response XML and gets the data into a variable tbl
    var symbolGrid = document.getElementById('SymbolsGrid').getElementsByTagName("tbody")[0];
			
	// Iterate through the table and add HTML Rows & contents into it.
	for(var i=0;i<rootXml.context.childNodes(0).parentNode.childNodes.length;i++)
	{
		// Create a HTML Row
		var row = document.createElement("TR"); 
		
		// Set the style
		row.setAttribute("className","text2");
		row.setAttribute("id", rootXml.context.childNodes(i).childNodes(0).text);
	
				
		// Iterate thorugh the columns of each row
		for(var j=0;j<rootXml.context.childNodes(0).childNodes.length;j++)
		{
			// Create a HTML DataColumn
			var cell = document.createElement("TD"); 
	        
			// Store the cotents we got from Response XML into the column
			if(j==0)
			{
			cell.innerHTML = rootXml.context.childNodes(i).childNodes(j).text;
			//set the id of this first column from rows count.
			cell.setAttribute("id", tdid);
			//cell.onmouseover= function (evt) { window.status='Column:'+this.id+' | Row ID:'+this.parentNode.id; };
	        cell.ondblclick = function (evt) { editSymbol(this);};

	        
			}
			
           /* else{
            
            cell.innerHTML = toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2));			
            }*/
            
            else{
            
            if(j==rootXml.context.childNodes(0).childNodes.length-1){
                cell.innerHTML = format(toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2)));			
                	cell.setAttribute('align', 'right'); 
                	}
            else{
                cell.innerHTML = toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2));			
                cell.setAttribute('align', 'right'); 
                }
            }
            
            
			// Append the new column into the current row
			row.appendChild(cell); 
		}
		
        //alert(row.innerHTML);
       
        oldRow=document.getElementById(rowtoreplace);
        //alert(oldRow.innerHTML);
        oldRow.parentNode.replaceChild(row, oldRow);
        
        row=null;
        rowtoreplace=null;
        tdid=null;
        oldRow=null;
        newsymbolHttp=null;
        
          
        }       
   }
}
function startUpdate()
{
symbolexecuter= new PeriodicalExecuter(updateSymbols, 2);
indexexecuter= new PeriodicalExecuter(FetchContents, 2);
//refreshtimer= setTimeout(updateSymbols,3000);
//refreshindextimer=setTimeout(FetchContents,2000);
}


function updateSymbols()
{
var rowid="";

var totalSymbols= document.getElementById('symbolRows').value;
 
    if(totalSymbols!=0)
    {
        var symbolToGet="";
    
        for(i=0; i<totalSymbols; i++)
        {
        symbol= document.getElementById('symbol'+i).innerHTML;
        symbolToGet+=symbol + "|";
        }
        symbolToGet=symbolToGet.substring(0,symbolToGet.length-1);
        symbol="";
      
	try
	{
		updateXML = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			updateXML = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			updateXML = null;
		}
	}
	if(!updateXML && typeof XMLHttpRequest != "undefined") 
	{
		updateXML = new XMLHttpRequest();
	}
	

var requestUrl = "updater.aspx?symbols=" + encodeURIComponent(symbolToGet)+"&dumm="+new Date();

	if(updateXML)
	{
		updateXML.onreadystatechange =  function() {
        if (updateXML.readyState == 4) {
		
		
        if(updateXML.status == 200)
		{			
		var rootXml = updateXML.responseXML.documentElement.getElementsByTagName('SymbolsUpdate'); 
		   
		    if(rootXml.context.childNodes.length>0 )
		    {
	            // Gets the table type content present in the Response XML and gets the data into a variable tbl
                var symbolGrid = document.getElementById('SymbolsGrid').getElementsByTagName("tbody")[0];
			
	            // Iterate through the table and add HTML Rows & contents into it.
	            for(var i=0;i<rootXml.context.childNodes(0).parentNode.childNodes.length;i++)
	            {
		        // Create a HTML Row
		        var row = document.createElement("TR"); 
		
		        // Set the style
		
		        row.setAttribute("className","text2");
		        row.setAttribute("id", rootXml.context.childNodes(i).childNodes(0).text);
	
				
		        // Iterate thorugh the columns of each row
		            for(var j=0;j<rootXml.context.childNodes(0).childNodes.length;j++)
		            {
			        // Create a HTML DataColumn
			        var cell = document.createElement("TD"); 
	                
			        // Store the cotents we got from Response XML into the column
			            if(j==0)
			            {
			            cell.innerHTML = rootXml.context.childNodes(i).childNodes(j).text;
			            rowid= cell.innerHTML;
			            //set the id of this first column from rows count.
			            
			            colid= document.getElementById(rowid).childNodes[0].getAttribute("id");
			            cell.setAttribute("id", colid); //problem here .. if the rows is only 1 then it always write  0 to it.
			            
			            //cell.onmouseover= function (evt) { window.status="Column id:"+this.id+" | Row id:"+this.parentNode.id; };
			            cell.ondblclick = function (evt) { editSymbol(this);};
			            }
			
                        else
                           {
                            if(j==rootXml.context.childNodes(0).childNodes.length-1){
                            cell.innerHTML = format(toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2)));			
                    	    cell.setAttribute('align', 'right'); 
                            }
                            else
                            {
                            cell.innerHTML = toDecimal(parseFloat(rootXml.context.childNodes(i).childNodes(j).text).toFixed(2));			
                            cell.setAttribute('align', 'right'); 
                            }
                            
                            }
            
			                // Append the new column into the current row
			                row.appendChild(cell); 
			
                           }
				    
		                document.getElementById(rowid).parentNode.replaceChild(row,document.getElementById(rowid));	
	    	          
	                }
            now=new Date();
            document.getElementById('lastupdate').innerText= now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
            }// (rootXml.context.ChildNode.length >0) end here
            
        //clearInterval(refreshtimer);
        //refreshtimer= setTimeout(updateSymbols,3000);
        }
    	else
		{
            //alert("There was a problem retrieving data from the server." );
		}


		 
		
        }
    }
		updateXML.open("GET", requestUrl,  true);
		updateXML.send(null);		
	}
	
	    
    }
}

function format(value)
{
tagline="";

if(value>0)
tagline="<span style='  color:#008E00;'>"+value+"</span>"

else if(value<0)
tagline="<span style='	color:#FF0000;'>"+value+"</span>"

else 
tagline="<span style='	color:#000000;'>"+value+"</span>"

return ""+tagline;

}

















