/**
 * This class is used to display a TimesAndSales Grid  
 * @param tsConfig A times and sales config object. It may have the following params.... 
 * @param renderTo The id of the HTML element to render the grid to
 * @param updateInterval The interval to poll the data in msec. When 0 no polling.
 * @param colModel Ext.grid.ColumnModel for defining the columns 
 * @param numTrades The number of trades to display. (set to 0 when using pageSize!)
 * @param gridWidth
 * @param gridHeight
 * @param pageSize The number of records per page (when 0 no paging)
 * @param isin (opt) When set only trades for that isin are polled 
 * @param autoHeight true/false when true the browser cares for setting the height. 
*/
function MostlyTraded( hebel, volume, tsConfig)
{	
	try{
		validateTSConfig( tsConfig );
	} catch(e) {
		throw('Initialization of tsConfig went wrong: ' + e);
	}
		
	var oldStore   = new Array( tsConfig.numTrades );
	var url        = '!MostlyTradedXml?hebel='+hebel+'&volumeSort='+volume;
	var autoHeight = false;
	var height     = 100;
	
	if(typeof(tsConfig.autoHeight) != 'undefined') {
		autoHeight = tsConfig.autoHeight;
	}
	if(typeof(tsConfig.height) != 'undefined') {
		height = tsConfig.height;
	}	
	
	if( volume=='1' ) {
		sortField = 'volume';
	} else {
		sortField = 'trades';
	}
	
	// create the Data Store
	var store = new Ext.data.Store( {   	
    	url: url,
    	reader: new Ext.data.XmlReader( {
           	record: 'instrument',
           	id: 'isin',
           	totalRecords: '@totalInstruments'
       	    },
			['trades','volume','isin', 'wkn','underlyingconsortialname','productcategoryname']
		)
		//,sortInfo: { field: sortField, direction: "DESC" }
	});
	    
	var taskUpdateStore = {
	    run: function(){
	    	try {
		   		//for checking if the renderTo is available 
		   		Ext.fly(tsConfig.renderTo).isVisible();
		   		store.reload();
			} catch (e) {		
				//when the element where to render is no longer there
				//then stop the task to poll data
				Ext.TaskMgr.stop(taskUpdateStore); 
			}		        
	    },
	    interval: tsConfig.updateInterval 
	}
	 
	var gridView = new Ext.grid.GridView ( {
	 	forceFit: 	true,
	 	scrollOffset: 0
	})
	
	//creating the toolbar when wanted
	
//	var  bbar = createPageBar(); blättern laut Markus vorläufig nicht erwünscht.

	var grid = new Ext.grid.GridPanel({
	        store: store,
	    	cm: tsConfig.colModel,
	        viewConfig: gridView,   		
	        renderTo:tsConfig.renderTo,
	        stripeRows: true,
	        width:tsConfig.width,
	        height:height,
	        autoHeight:autoHeight
//			,bbar:bbar
    });    
	
	//Startingpoint to initialize the grid
	function initGrid() {    
		grid.getSelectionModel().on('rowselect', handleRowSelect);
		gridView.addListener('refresh', handleRefreshGridView);
		  
		store.addListener('beforeload', handleBeforeLoadEvent);
		store.addListener('load', handleLoadEvent);
		store.addListener('loadexception', handleLoadException);

		store.load( {params:{start: 0 , limit: tsConfig.pageSize , iNumTrades:tsConfig.numTrades}});
			
		//when 0 no polling
		if(tsConfig.updateInterval != 0){
			Ext.TaskMgr.start(taskUpdateStore);
		}	
	}
	
	function handleLoadException(proxy, options, response, error) {
	}
	
	function handleLoadEvent() {
		
		//when no data was received
		if(store.getCount() < 1) {
			var sTextSnipet='';
			Ext.fly(tsConfig.renderTo).update("<b class='colorRed'>Heute wurden noch keine Umsätze" + sTextSnipet +" getätigt.</b>");	
		}
		
	}
	
	/* This function creates the page tool bar (when needed)
	   @return toolBar
	*/
	function createPageBar()
	{
	 	var toolBar=null;
	 	if(tsConfig.pageSize > 0) 
	 	{
	 	 	toolBar =  new Ext.PagingToolbar ({
				pageSize: tsConfig.pageSize,
				store:store
	        });
	    }
	    return toolBar;
	}
	/** 
	This function cares for highlighting the new records (rows) that were added to the view.
	@param view The view that triggerd the event
	*/
	function handleRefreshGridView( view) {}
	/**
	Buffers all tradeno within var oldStore.
	*/		
	function handleBeforeLoadEvent() {
		for(var i=0;i<store.getCount();i++) {
			//gl.log(store.getAt(i).get('tradeno'));
			oldStore[i]=store.getAt(i).get('tradeno');		
		}
	}
	/**
	Handling user click on row 
	@param selectionModel 
	@rowIndex 
	@record
	*/
	function handleRowSelect(selectionModel, rowIndex, record) 
	{    
	    //leaving the page so I stop the taskmgr
	    Ext.TaskMgr.stop(taskUpdateStore);  
	    //when in snapshots (isin is given) the row select should be ignored
	    if(typeof(tsConfig.isin)=='undefined')
	    {  
	    	ShowSnapshot(record.get('isin'),'snapshotTab2');
	    }    
	}
	
	/**
	 * @param tsConfig
	 * @throws An Exception when the input is invalid.
	*/ 
	function validateTSConfig(tsConfig) {
		//checking required fields	
		if(typeof(tsConfig.renderTo) == 'undefined') 
		{throw('renderTo is not defined');}
		
		if(typeof(tsConfig.colModel) == 'undefined') 
		{throw('colModel is not defined');}
		
		if(typeof(tsConfig.width) == 'undefined') 
		{throw('width is not defined');}
		
		if(tsConfig.updateInterval < 2000 && tsConfig.updateInterval > 0)
		{throw('The updateinterval is lower than 2000 msec. This will generate to much traffic!');}	
		
		if((typeof(tsConfig.height) == 'undefined') &&  (typeof(tsConfig.autoHeight) == 'undefined')) 
		{throw('height or autoHeight need to be defined.');}
		
		
		if((typeof(tsConfig.autoHeight) != 'undefined') && (typeof(tsConfig.height) != 'undefined') ) 
		{throw('autoHeight and height are defined. This makes no sense.');}	
	}
	
	initGrid();
}

/** 
 * This render function is used to render the cell Produktart
 * X products will be mapped to non X products
 * @param value The cell content (value)
 * @return the new category name
*/ 
function renderProduktart(value)
{
  var newValue=value;
  if(value == 'X-Turbos') 
  {
     newValue = 'Turbo-Optionsscheine';
  }
  if(value =='X-Endlos-Turbos')
  {
  	newValue ='Endlos-Turbo-Optionsscheine';
  }
  
  return newValue;
}

/**
 * Defining a new format number
*/
Ext.util.Format.number = function(v) {
	v = (Math.round((v-0)*100))/100;
	v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
	return ('' + v).replace(/\./, ',');
};

/**
 * Defining a new format number (Tausender-Trennzeichen) 
*/
Ext.util.Format.numberThousandEuro = function(v) {
	v = Math.ceil( v );
	v = '' + v;
	if (v.length > 3) 
	{
		var mod = v.length % 3;
		var output = (mod > 0 ? (v.substring(0,mod)) : '');
		
		for (i=0 ; i < Math.floor(v.length / 3); i++) 
		{
			if ((mod == 0) && (i == 0))
				output += v.substring(mod+ 3 * i, mod + 3 * i + 3);
			else
				// hier wird das Trennzeichen festgelegt mit '.'
				output+= '.' + v.substring(mod + 3 * i, mod + 3 * i + 3);
		}
		return (output+" EUR");
	}
	else return v+" EUR";
};
