Ext.namespace('SilverMapper');

SilverMapper.ClusterGrid = function( config ) {

	var store = new Ext.data.Store({
			sortInfo: {field: "Family", direction: "ASC"}
		,	reader: new Ext.data.JsonReader({
					totalProperty: 'totalCount'
				,	root: 'markers'
				,	id: 'id'
			}, [
					{name: 'layer_id'}
				,	{name: 'dp'}
				,	{name: 'Family'}
				,	{name: 'Genus'}
				,	{name: 'SpecificEpithet'}
				,	{name: 'sz'}
				,	{name: 'DecimalLatitude'}
				,	{name: 'DecimalLongitude'}
				,	{name: 'DecimalLatitudeEst'}
				,	{name: 'DecimalLongitudeEst'}
				,	{name: 'html_summary'}
				,	{name: 'html_details'}
			])
	});

	// Template used when a marker represents 1 record.
	var recordTplMarkup = [
			'<div class="recordDetail">'
		,	'{html_details}'
		,	'</div>'
	];

	var recordTpl = new Ext.Template(recordTplMarkup);

	// Template shown when a marker is considered a cluster.
	var multipleTplMarkup = [
			'<div class="recordDetail">'
		,	'This marker contains {sz} records.  To view the records enclosed in this marker double click icon or the record on the right hand side.'
		,	'</div>'
	];

	var multipleTpl = new Ext.Template(multipleTplMarkup);

	// Default construction for ClusterGrid
	Ext.apply(this, config, {
			store: store
		,	id: 'sm-clustergrid'
		,	border: false
//		,	enableColumnHide: false
		,	enableHdMenu: false
		,	enableColumnMove: false
		,	columns: [
					{header: "&nbsp;", width: 20, dataIndex: 'layer_id', renderer: this.renderLayer, sortable: true}
				,	{header: "&nbsp;", width: 50, dataIndex: 'sz', sortable: true}
				,	{header: "Family", width: 115, dataIndex: 'Family', renderer: this.renderCluster, sortable: true}
				,	{header: "Genus", width: 100, dataIndex: 'Genus', renderer: this.renderCluster, sortable: true}
				,	{header: "Species", width: 100, dataIndex: 'SpecificEpithet', renderer: this.renderCluster, sortable: true}
			]
		,	sm: new Ext.grid.RowSelectionModel({singleSelect: true})
		,	viewConfig: {
					forceFit: true
				,	enableRowBody: true
				,	showPreview: true
				,	getRowClass : function(record, rowIndex, p, store){
						if ( this.showPreview ) {
							if (record.data.sz == 1) {				
								p.body = record.data.html_summary;
								return 'x-grid3-row-expanded';
							} else {
								return 'x-grid3-row-collapsed';
							}
						}
						return 'x-grid3-row-collapsed';
					}
			}
		,	listeners: {
					'rowdblclick': function( grid, rowIndex, e ) {

						var r = this.getStore().getAt( rowIndex );

						if ( r.data.sz > 1 ) {
							Ext.getCmp('sm-recordsCard').getLayout().setActiveItem( 'sm-specimengrid' );
							
							var detailPanel = Ext.getCmp('detailPanel');
							detailPanel.body.update('');

							// Disable Google Map
							var mask = Ext.getCmp('sm-map').mask;
							mask.msg = Lang.Get('Core','general','cluster_deactivated');
							mask.msgCls = 'deactivated';
							mask.show();

							// Disable Timeline
							var mask = Ext.getCmp('sm-timeline').mask;
							mask.msg = Lang.Get('Core','general','cluster_deactivated');
							mask.msgCls = 'deactivated';
							mask.show();

							var tmpStore = Ext.getCmp('sm-specimengrid').getStore();
							var bounds = Ext.getCmp('sm-map').gmap.getBounds();

							tmpStore.baseParams.DecimalLatitude = r.data.DecimalLatitudeEst;
							tmpStore.baseParams.DecimalLongitude = r.data.DecimalLongitudeEst;
							tmpStore.baseParams.layer = r.data.layer_id;
							tmpStore.baseParams.DecimalPercision = r.data.dp;
							tmpStore.baseParams.sw_lat = bounds.getSouthWest().lat()
							tmpStore.baseParams.sw_lng = bounds.getSouthWest().lng()
							tmpStore.baseParams.ne_lat = bounds.getNorthEast().lat()
							tmpStore.baseParams.ne_lng = bounds.getNorthEast().lng()
							
							tmpStore.baseParams.filters = Ext.encode( Ext.getCmp('sm-filter').getForm().getValues() );
							tmpStore.load({params:{start: 0, limit: 25 }});							

							Ext.getCmp('sm-layers').disable();
							Ext.getCmp('sm-filter').disable();

						}
						
					}

				,	'render': function() {

						this.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {

							// Set Grid tab to be visible
							var tabs = Ext.getCmp('sm-tabs');
							tabs.setActiveTab( 'sm-recordsCard' );

							// Highlight marker on map with images/icons/{layer_id}-selected.png
							var detailPanel = Ext.getCmp('detailPanel');
							r.marker.setImage( r.marker.img_select );
							
							if ( r.data.sz > 1 ) {
								multipleTpl.overwrite( detailPanel.body, r.data );
							} else {
								recordTpl.overwrite( detailPanel.body, r.data );
							}
						});

						this.getSelectionModel().on('rowdeselect', function(sm, rowIdx, r) {

							Ext.getCmp('detailPanel').body.update('');
							if ( r.data.sz > 1 ) {
								r.marker.setImage( r.marker.img_cluster );
							} else {
								r.marker.setImage( r.marker.img_single );
							}

						});
 
					}
			}
	});

	SilverMapper.ClusterGrid.superclass.constructor.apply(this, arguments);

};

Ext.extend( SilverMapper.ClusterGrid, Ext.grid.GridPanel, {

		// Function used to render single or cluster icon
		renderLayer: function( layer_id ) {
			return '<img src="images/icons/' + layer_id + '-icon.png" style="margin-left: -3px">';
		}

		// Function used to draw line in record when it is a cluster
	,	renderCluster: function( value, cell, r ) {
			if (r.data.sz > 1) {
				return('<hr>');
			}
			return( value );
		}

});