/**
 * 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 TimesAndSales (tsConfig)
{	

	try{validateTSConfig(tsConfig);}
	catch(e){throw('Initialization of tsConfig went wrong: ' + e);}
		
	//flashing colors //for customer buy is sell and the other way around
	var colorSell = '0FC512';
	var colorBuy= 'FF0000';
	

	//buffers all former trades
	var oldStore=new Array (tsConfig.numTrades);
	var url='!GetTimesAndSales';
	var autoHeight = false;
	var height =100;
	
	if(typeof(tsConfig.autoHeight) != 'undefined')
	{
		autoHeight = tsConfig.autoHeight;
	}
	if(typeof(tsConfig.height) != 'undefined')
	{
		height = tsConfig.height;
	}
	
	
	
	if(typeof(tsConfig.isin) != 'undefined')
	{
		url = url + '?isin=' + tsConfig.isin;
	}
	
	// create the Data Store
	var store = new Ext.data.Store(
	{   	
    	url: url,
    	
    	reader: new Ext.data.XmlReader(
    			{
           			record: 'trade',
           			id: 'tradeno',
           			totalRecords: '@totalTrades'
       			},
    			['tradeno','time','isin', 'wkn', 'buysell', 'quantity' ,'price','currency','timestamp','underlyingconsortialname','productcategoryname']),
    	sortInfo: { field: "time", direction: "DESC" }
	});
	    
	//task for polling data
	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();

	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);
		//these params are getting posted on every call to server
		
		//store.load( {params:{start: 0 , limit:tsConfig.pageSize , iNumTrades:tsConfig.numTrades, isin:isin }});
		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)
	{
	  //alert(error);
	}
	
	function handleLoadEvent()
	{
		
		//when no data was received
		if(store.getCount() < 1)
		{
			var sTextSnipet='';
			
			//when an isin is given 
			if(typeof(tsConfig.isin) != 'undefined')
			{
				//add this snipet
				sTextSnipet=' in diesem Produkt';
			}
			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)
	{
		
		var found=false;
		//only when data is polled the highlightning on new datasets should work
		if(tsConfig.updateInterval > 0 )
		{
			for(var i=0;i<store.getCount();i++)
			{
				found=false;
				//oldStore does buffer the former trades...
				for(var n=0; n<oldStore.length;n++)
				{
					//check if this tradeno was within store before
					if(oldStore[n]==store.getAt(i).get('tradeno'))
					{
						found=true;
						break;
					}	
				}
				//when the tradeno wasnt found within the former store...
				if(found==false) 
				{
					var buysell=store.getAt(i).get('buysell');
					//var color='BAD1E1';
					
					/*if(buysell == 'buy')
					{
						color=colorBuy;
					}
					else
					{
						color=colorSell;
					}*/
					
						Ext.fly(view.getRow(i)).highlight(colorSell,{duration: 0.9});	
				}
			}
		}
		
	
	}
	/**
	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 buysell.
 * @param value The cell content (value)
 * @return The short version K / V (turned the logic)
*/ 
function renderBuySellShort(value)
{
  var newValue='';
  if(value == 'buy') 
  {
     newValue = 'V'
  }
  else
  {
  	newValue = 'K'
  } 
  return newValue;
}
/** 
 * This render function is used to render the cell buysell.
 * @param value The cell content (value)
 * @return The long version K / V (turned the logic)
*/ 
function renderBuySell(value)
{
  var newValue='';
  if(value == 'buy') 
  {
     newValue = 'Kauf'
  }
  else
  {
  	newValue = 'Verkauf'
  } 
  return newValue;
}

/** 
 * 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.numberThousand = function(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);
	}
	else return v;
};

Ext.util.Format.currency = function(value) {

	numberFormat= {
		decimalSeparator: ',',
		decimalPrecision: 3,
		groupingSeparator: '',
		groupingSize: 3,
		currencySymbol: ''
	};
	
	
		var format = Ext.apply(Ext.apply({}, this.numberFormat), numberFormat);
		if (typeof value !== 'number') {
			value = String(value);
			if (format.currencySymbol) {
				value = value.replace(format.currencySymbol, '');
			}
			if (format.groupingSeparator) {
				value = value.replace(new RegExp(format.groupingSeparator, 'g'), '');
			}
			if (format.decimalSeparator !== '.') {
				value = value.replace(format.decimalSeparator, '.');
			}
			value = parseFloat(value);
		}
		var neg = value < 0;
		value = Math.abs(value).toFixed(format.decimalPrecision);
		var i = value.indexOf('.');
		if (i >= 0) {
			if (format.decimalSeparator !== '.') {
				value = value.slice(0, i) + format.decimalSeparator + value.slice(i + 1);
			}
		} else {
			i = value.length;
		}
		if (format.groupingSeparator) {
			while (i > format.groupingSize) {
				i -= format.groupingSize;
				value = value.slice(0, i) + format.groupingSeparator + value.slice(i);
			}
		}
		if (format.currencySymbol) {
			value = format.currencySymbol + value;
		}
		if (neg) {
			value = '-' + value;
		}
		return value;
};
