package ibase.client;




import ibase.e12ria.e12table.client.AbstractDataGrid;
import ibase.e12ria.e12table.client.ColumnInfoBean;
import ibase.e12ria.e12table.client.DataGridTableRowModel;
import ibase.e12ria.e12table.client.E12CustomColumn;
import ibase.e12ria.e12table.client.E12CustomTextCell;
import ibase.e12ria.e12table.client.ResizableHeader;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeMap;

import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
/**
 * This class is used to show the data in paged format.
 * 
 * @author base
 */

public class CustomGrid extends AbstractDataGrid<DataGridTableRowModel>
{
	private String rangeText = "50";
	ListDataProvider<DataGridTableRowModel> dataProvider = new ListDataProvider<DataGridTableRowModel>();	
	ArrayList<DataGridTableRowModel> dataGridTableRowList = new ArrayList<DataGridTableRowModel>();
	PopupPanel contextMenuPanel = new PopupPanel(true);
	private ScrollPanel scrollPanel = new ScrollPanel(); 
	private DataGridTableRowModel selDataGridTRModel = null;
	HashMap<String,   ArrayList<String>>  gridPropertyeMap=new HashMap<String,   ArrayList<String>>();
	public CustomGrid(int pageSize) {
		super(pageSize);
	}

	@Override
	public void refresh() {
	}
  
	@Override
	public void performDoubleClick() {
	}

	@Override
	public void createContextMenu() {
	}
	/*Start code for progess bar to data building- Dhanendra 17Nov2014*/
	protected E12LoadingInterface e12LoadImg=new E12LoadingInterface();
	/*End code for progess bar to data building- Dhanendra 17Nov2014*/
	@SuppressWarnings("unchecked")
	public FlexTable jsonToArrayList(HashMap<String, HashMap> gridNGraphMeataDataMap,JSONObject jsonObjGridData ,String dataSrc,String componentId)
	{
		e12LoadImg.setLoadingInfo("Building view...");
		e12LoadImg.setLoading(true);
		DataGridTableRowModel rowDataGrid= null;
		E12CustomTextCell.CellData celldata = null;
		ArrayList<ColumnInfoBean> dataGridTableColList = new ArrayList<ColumnInfoBean>();
		FlexTable flexTable= new FlexTable();
		//for arraylist of DataGridTableRowModel object (rows of data)
		HashMap<Integer, E12CustomTextCell.CellData> rowData =  null;
		gridNGraphMeataDataMap.toString().replace('=', ':');
		HashMap<String, ArrayList<String>> graphDataMap = null;
		HashMap<String,   ArrayList<String>>  graphSizeMap=null;
		HashMap<String,   ArrayList<String>>  graphCaptioneMap=null;
		HashMap<String,   ArrayList<String>>  graphAlignMap = null;
		//Added By Prashant Chavan on 09-Mar-15 [For Link in Grid Control] Start
		HashMap<String,   String>  graphMetaLinkMap = null;
		//Added By Prashant Chavan on 09-Mar-15 [For Link in Grid Control] End
		ArrayList<String> graphDtlList = new ArrayList<String>();
		ArrayList<String> graphAlignList=new ArrayList<String>();	
		ArrayList<String> graphCaptionList=new ArrayList<String>();	
		//Added By Prashant Chavan on 09-Mar-15 [For Link in Grid Control] Start
		ArrayList<String>  graphMetaLinkList = new ArrayList<String>();
		//Added By Prashant Chavan on 09-Mar-15 [For Link in Grid Control] End
		ArrayList<String> temp = new ArrayList<String>();
		ArrayList<String> gridIdList = new ArrayList<String>();
		HashMap<String,   String>  graphLinkFormatMap = null;
		try
		{
			JSONObject jsonEachRow = null;
			int count=0;
			String  graphLinkFormat ="";
			JSONObject jsonObjData =(JSONObject) jsonObjGridData.get(dataSrc);
			graphDataMap=gridNGraphMeataDataMap.get(componentId);	
			//Added By Prashant Chavan on 11-Mar-15 [For Getting the Link name]
			graphMetaLinkMap=gridNGraphMeataDataMap.get("metadataNameLink"+componentId);
			graphLinkFormatMap =gridNGraphMeataDataMap.get("linkFormatType"+componentId);
			for(int jRowCtr=0;jRowCtr<jsonObjData.size();jRowCtr++)
			{
				rowData = new HashMap<Integer, E12CustomTextCell.CellData> ();	
				for (String graphKey : graphDataMap.keySet())
				{
					String  graphMetaLink ="";
					graphDtlList = graphDataMap.get(graphKey);
					if(graphMetaLinkMap.get(graphKey) != null )
					{
					  graphMetaLink = graphMetaLinkMap.get(graphKey);
					}
					if(graphLinkFormatMap.get(graphKey) != null )
					{
						graphLinkFormat = graphLinkFormatMap.get(graphKey);
					}
					jsonEachRow = new JSONObject();
				    jsonEachRow = (JSONObject)jsonObjData.get(""+jRowCtr);
				    count=rowData.size();
				    for(int jDataCtr=0;jDataCtr<graphDtlList.size();jDataCtr++)
					{
							if(jsonEachRow.get(graphDtlList.get(jDataCtr))!=null)
							 {
								//Changed By Prashant Chavan on 11-Mar-15 [For Link Chart]  Start
							    if(graphMetaLink !=null && graphMetaLink !="")
							    {
							    	/*if(graphLinkFormat !=null && graphLinkFormat !="")
							    	{
							    		celldata =  new E12CustomTextCell.CellData(0,(""+jsonEachRow.get(""+graphDtlList.get(jDataCtr))).replace('"', ' '),graphMetaLink+"@"+graphLinkFormat);
							    	}else 
							    	{*/
							    	    celldata =  new E12CustomTextCell.CellData(0,(""+jsonEachRow.get(""+graphDtlList.get(jDataCtr))).replace('"', ' '),graphMetaLink);
							    	//}
							    }
							    else
							    {
							    	celldata =  new E12CustomTextCell.CellData((""+jsonEachRow.get(""+graphDtlList.get(jDataCtr))).replace('"', ' '));
							    }
							    //Changed By Prashant Chavan on 11-Mar-15 [For Link Chart] End
							     celldata.setMandatory(true);
								 celldata.setOriginalText("Cell"+jDataCtr);
								 celldata.setName(""+(graphDtlList.get(jDataCtr)).replace('"', ' '));						
								 rowData.put(count, celldata);
								 count++;
							 }
					}	
				}
				celldata.setMandatory(true);
				celldata.setOriginalText("Cell"+graphDtlList.size());
				celldata.setName("");						
				rowData.put(count, celldata);
				count++;
				rowDataGrid = new DataGridTableRowModel(rowData);	
				dataGridTableRowList.add(rowDataGrid);
			}
			ColumnInfoBean columnInfoBean=null;
			graphDataMap  	 =	gridNGraphMeataDataMap.get("columnName"+componentId);
			graphSizeMap  	 =	gridNGraphMeataDataMap.get("columnSize"+componentId);
			graphAlignMap 	 =	gridNGraphMeataDataMap.get("columnAlign"+componentId);
			graphCaptioneMap =  gridNGraphMeataDataMap.get("componentCaption"+componentId);
			for (String graphKey : graphDataMap.keySet())
			{
				graphDtlList.clear();
				graphDtlList = new ArrayList<String>();
				graphDtlList = graphDataMap.get(graphKey);
				for(int jDataCtr=0;jDataCtr<graphDtlList.size();jDataCtr++)
				{
					columnInfoBean = new ColumnInfoBean(""+(graphDtlList.get(jDataCtr)),"physicalName", "logicalName", ""+graphSizeMap.get(graphKey));
					dataGridTableColList.add(columnInfoBean);
					graphAlignList.add(""+graphAlignMap.get(graphKey));
				}
			}
			graphCaptionList.add(""+graphCaptioneMap.get("componentCaption"+componentId));
			//Window.alert("graphLinkFormat: "+graphLinkFormat);
			//if(graphLinkFormat.contains("@"))
			//{
				String arr[] = graphLinkFormat.split("@");
				if(arr[0].equalsIgnoreCase("F"))
				{
					flexTable=createTableComponent(dataGridTableRowList,dataGridTableColList,flexTable,graphAlignList,graphCaptionList,graphLinkFormat);
				}
				else
				{
				   flexTable.setStyleName("flexCSS");
				   flexTable=createTableComponent(dataGridTableRowList,dataGridTableColList,flexTable,graphAlignList,graphCaptionList);
				}
			/*}
			else
			{
			   flexTable.setStyleName("flexCSS");
			   flexTable=createTableComponent(dataGridTableRowList,dataGridTableColList,flexTable,graphAlignList,graphCaptionList);
			}*/
			
			e12LoadImg.setLoading(false);
		} catch (Exception e)
		{
			Window.alert(" Exception : DataGrid : jsonToArrayList(): [" + e.getMessage() + "]");
		}
		return flexTable;
	}
	
	
	/**
	 * It creates The AdvDataGrid Table .
	 * 
	 * @param dataGridTableRowList
	 * @return 
	 */
	final SimpleDateFormat gridDateFormat = new SimpleDateFormat( "dd-mm-yy");
	public FlexTable createTableComponent( ArrayList< DataGridTableRowModel> dataGridTableRowList, ArrayList<ColumnInfoBean> dataGridTableColList, FlexTable flexTable,ArrayList<String> graphAlignList,ArrayList<String> graphCaptionList) 
	{
		final int noOfRows = dataGridTableRowList.size();
		final int noOfColumns = dataGridTableColList.size();
		dataProvider.setList( dataGridTableRowList );
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] Start
		E12CustomColumn firstColumn = null;
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] End
		String caption ="";
		ResizableHeader<DataGridTableRowModel> header=null;
		try
		{
			E12CustomTextCell.isValidate = false;
			E12CustomTextCell.currentCellElement = null;
			E12CustomTextCell.currentContext = null;
			E12CustomTextCell.incrFactor = 0;
			E12CustomTextCell.editableField = null;
			E12CustomTextCell.prvEditableField = null;
			
			//  handler for table sorting 
			final ListHandler<DataGridTableRowModel> sortHandler = new ListHandler<DataGridTableRowModel>( dataProvider.getList())
					{
						@Override
						public void onColumnSort(ColumnSortEvent event) {
							super.onColumnSort(event);
							dataProvider.refresh();
						}
					};
			this.addColumnSortHandler(sortHandler);
			int width = 0;
			for( int i= 0  ; i < noOfColumns ; i++ )
			{
				final int index = i;
			    ColumnInfoBean colInfo = dataGridTableColList.get( i );
			    final String colName = colInfo.getDisplayNameOfCol();
			    width = colInfo.getWidth();
				E12CustomColumn column = new E12CustomColumn(i, false);
				column.setSortable( true );
				if(graphAlignList.get(i).trim().equalsIgnoreCase("left"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("right"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("center"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
				}
				if ( i == 0 )
				{
					firstColumn = column;
				}
				sortHandler.setComparator( column , new Comparator<DataGridTableRowModel>() 
				{
				 	public int compare( DataGridTableRowModel o1, DataGridTableRowModel  o2 ) 
				 	{
				 		if(isValidDate1(o1.getCellText( index )) && isValidDate1(o2.getCellText( index )))
				 		{
				 			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
				 			Date date1=null,date2=null;
							try 
							{
								 date1 = formatter.parse(o1.getCellText( index ));
								 date2 = formatter.parse(o2.getCellText( index ));
							} catch (Exception e) 
							{
								e.printStackTrace();
							}
							return date1.compareTo(date2);
				 		}
				 		if(isValidDouble(o1.getCellText( index )) && isValidDouble(o2.getCellText( index )))
				 		{
				 		    return Double.compare(Double.parseDouble(o1.getCellText( index )), Double.parseDouble(o2.getCellText( index )));
				 		}
				 		else
				 		{
						    return o1.getCellText(index).compareTo(o2.getCellText( index ));
				 		}
				 	}
				});
				this.setColumnWidth( column, width +"px" );
				header = new ResizableHeader<DataGridTableRowModel>(colName, this, column ) {
					@Override
					public String getValue() {
						return colName;
					}
				};
				Header<String> footer1 = new Header<String>(new TextCell()) {
					
					@Override
					public String getValue() {
						return "";
					}
				};
				
				this.addColumn(column, header, null);
			}
			caption = graphCaptionList.get(0);			
			dataProvider.addDataDisplay( this );
			dataProvider.refresh();
			this.getColumnSortList().clear();
			this.getColumnSortList().push( firstColumn );
			this.getColumnSortList().push( firstColumn );
			ColumnSortEvent.fire(this, this.getColumnSortList());
		}
		catch (Exception e )
		{
			Window.alert("Exception in table "+ e.getMessage()) ;
		}
		GridThemes.applyDatagridThemes();
		//E12SimplePager.Resources pagerResources = GWT.create(E12SimplePager.Resources.class);
		//final E12SimplePager pager =new E12SimplePager(E12SimplePager.TextLocation.CENTER, pagerResources, false, 0 , true);
		
		
		HorizontalPanel excelBtnPnl = new HorizontalPanel();
		Button excelBtn = new Button();
		excelBtn.setTitle("Excel");
		Image excelImg = new Image("FusionChart/images/excel.png");
		excelImg.setHeight("20px");
		excelBtn.getElement().appendChild(excelImg.getElement());
		excelBtnPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(excelBtn).buildExportFormWidget());
		SimplePager.Resources displayPagerResources = GWT.create(SimplePager.Resources.class);
		final SimplePager displayPager = new SimplePager(SimplePager.TextLocation.CENTER, displayPagerResources, false, 0 , true, excelBtnPnl);
		displayPager.setDisplay(this);
		displayPager.setRangeText(rangeText);
		Command setRowCmd = new Command() {
			@Override
			public void execute() 
			{
				try
				{
					int rowNo= (int)Double.parseDouble( displayPager.getRangeText().trim() );
					if( rowNo > 0 && rowNo <= noOfRows)
					{
					    CustomGrid.this.setPageSize( rowNo );
					    displayPager.firstPage();
						dataProvider.refresh();
						rangeText = displayPager.getRangeText();
						displayPager.setRangeText(displayPager.getRangeText());
					}
					else
					{
						displayPager.setRangeText("Error");
					}
				}
				catch (Exception e)
				{
					displayPager.setRangeText("Error");
				}
			}
		};
		displayPager.setRangeCommand( setRowCmd );	
		String cellVal = Window.Location.getParameter("CELL_VAL") == null ? "" : Window.Location.getParameter("CELL_VAL");
		String brandName = Window.Location.getParameter("brand") == null ? "" : Window.Location.getParameter("brand");
		if(caption.trim().length()==0 && cellVal.trim().length()>0)
		{
			if(brandName.trim().length()>0)
			{
				caption = brandName.trim()+" - "+cellVal.trim()+" (Stock Quantity)";
			}
			else
			{
				caption = cellVal.trim();
			}
		}
		if(caption.trim().length()!=0)
		{
			flexTable.setText(0, 0, caption);
			flexTable.setWidget(1, 0, this);
			flexTable.setWidget(2, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "FlexTable-ColumnHeaderCell");
			flexTable.getCellFormatter().setStyleName(1 ,0 , "gwt-ScrollTable");
			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager-forIE");
			}
		}else
		{
			flexTable.setWidget(0, 0, this);
			flexTable.setWidget(1, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "gwt-ScrollTable");
			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager-forIE");
			}
		}
		//flexTable.setHeight( Window.getClientHeight() - 240 + "px" );
		flexTable.setHeight("280px");
		setHeight("280px");
		/*setHeight( Window.getClientHeight() - 207+ "px" );*/
		/*setHeight( ( ( Window.getClientHeight() - 250 ))+ "px" );*/
		addStyleName("e12AdvDataGrid-SideBars");
		
		return flexTable;
	}
	
	@Override
	public FlexTable createTableComponent(
			ArrayList<DataGridTableRowModel> dataGridTableRowList,
			TreeMap<Integer, Object> dataGridTableColList) {
		return null;
	}

	@Override
	public FlexTable createTableComponent(ArrayList<DataGridTableRowModel> dataGridTableRowList,
			ArrayList<ColumnInfoBean> dataGridTableColList, FlexTable flexTable) 
	{
		// TODO Auto-generated method stub
		return null;
	}
  
	
	public void showOptionMenu() 
	{}		
	
	/***For on click action of grid row --- added by swati 24-Feb-2015***/
	int xPosition = 0;
	int yPosition = 0;
	
	public void onBrowserEvent2(Event event) {
		super.onBrowserEvent2(event);
		//event.preventDefault();
		EventTarget eventTarget = event.getEventTarget();
		if (!Element.is(eventTarget)) {
			return;
		}

		final Element target = event.getEventTarget().cast();
		TableCellElement tableCell = findNearestParentCell(target);
		if (tableCell == null) {
			return;
		}

		Element trElem = tableCell.getParentElement();
		if (trElem == null) {
			return;
		}
		TableRowElement tr = TableRowElement.as(trElem);
        
		Element sectionElem = tr.getParentElement();
		if (sectionElem == null) {
			return;
		}
		TableSectionElement section = TableSectionElement.as(sectionElem);
		switch (DOM.eventGetType(event)) {
		       
		case Event.ONCLICK:
			if (section == getTableBodyElement()) {
				selectedRow = tr.getSectionRowIndex();
				xPosition = event.getClientX();
				yPosition = event.getClientY();
				performSingleClick(tr,tableCell);
			}
		default:
			break;
		}
	}
	
	StringBuffer pkFieldNames=null;
	StringBuffer pkFieldValue=null;
	@SuppressWarnings("unused")
	public void performSingleClick(TableRowElement tr,TableCellElement tableCell) 
	{
		if(tableCell.getElementsByTagName("a").getItem(0) !=null   )
		{
			String urlStr="";
			String propertyStr="";
			String comStr="";
			String metadataName="";
			String dispFilterStatus="";
			String linkFormat="";
			int count=0;
			String cellValue="";
			cellValue = tableCell.getInnerText();
			String period =FilterCreator.parameterList.get(1);
			for (FilterInfo filterInfo : GWTDashBoardReport.filterList)
			{
				if(count==0)
				{
					propertyStr = "&"+filterInfo.getColNameId()+"="+FilterCreator.parameterList.get(count+1);
				}
				else
				{
					propertyStr = propertyStr+"&"+filterInfo.getColNameId()+"="+FilterCreator.parameterList.get(count+1);
				}
				count++;
			}
			urlStr = tr.getInnerText();
			metadataName = ""+tableCell.getElementsByTagName("a").getItem(0).getAttribute("linkName");
			String parameterListString = "";
			for (int i = 0 ; i<tr.getChildCount();i++)
			{
				Node tdCell = tr.getChild(i).getFirstChild().getFirstChild();
				Element spanElemt = tdCell.cast();
				String colName= spanElemt.getElementsByTagName("div").getItem(0).getAttribute("colname");
				String colval= spanElemt.getElementsByTagName("div").getItem(0).getAttribute("title");
				parameterListString = parameterListString + "&" + colName.trim() + "=" + colval.trim();
			}
			/*String splitArr[] = comStr.split("@");
			metadataName = splitArr[0];
			linkFormat   = splitArr[1];
			dispFilterStatus = splitArr[2];
			if(linkFormat.trim().length()>0 && linkFormat.trim().equalsIgnoreCase("F"))
			{
				buildGridFrame(metadataName,cellValue, propertyStr,urlStr,parameterListString,dispFilterStatus);
			}
			if(linkFormat.trim().length()>0 && linkFormat.trim().equalsIgnoreCase("P"))
			{
				Window.open("/ibase/dwh/GwtDashboardPage.html?metadataname="+metadataName+"&CELL_VAL="+cellValue.trim()+propertyStr+"&"+parameterListString+"&FLAG="+dispFilterStatus+"&P1="+urlStr, "_blank", "menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=no,height=450,width=900,top=100");
			}
			if(linkFormat.trim().length()>0 && linkFormat.trim().equalsIgnoreCase("N"))
			{
				Window.open("/ibase/dwh/GwtDashboardPage.html?metadataname="+metadataName+"&CELL_VAL="+cellValue.trim()+propertyStr+"&"+parameterListString+"&FLAG="+dispFilterStatus+"&P1="+urlStr,"", "");
			}*/
			buildGridFrame(metadataName,cellValue, propertyStr,urlStr,parameterListString,dispFilterStatus);
		}
	}
	private native void buildGridFrame(String metadataName,String cellValue,String propertyStr,String urlStr,String parameterListString,String dispFilterStatus)
	/*-{
		try {
			
				document.getElementById('frameContainer').innerHTML = "<iframe scrolling='no' id='frame1' width='99%' height='230' frameborder='0' src='/ibase/dwh/GwtDashboardPage.html?metadataname="+metadataName+propertyStr+"&"+parameterListString+"&CELL_VAL="+cellValue.trim()+"&P1="+urlStr+"&FLAG=N'></iframe>";
				//document.getElementById('frameContainer').innerHTML = "<iframe scrolling='no' id='frame1' width='99%' height='230' frameborder='0' src='/ibase/dwh/GwtDashboardPage.html?metadataname="+metadataName+propertyStr+"&"+parameterListString+"&CELL_VAL="+cellValue.trim()+"&P1="+urlStr+"&FLAG="+dispFilterStatus+"'></iframe>";
				
			} catch (e) {
				alert("Excpeiton :: GraphComponent : createChart [" + e.message+ "]");
			}
		}-*/;
	private TableCellElement findNearestParentCell(Element elem) 
	{
		while ((elem != null) && (elem != getElement())) 
		{
			// This would allow us to use TableCellElement.is() -- much cleaner.
			String tagName = elem.getTagName();
			if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) 
			{
				return elem.cast();
			}
			elem = elem.getParentElement();
		}
		return null;
	}
	/***For on click action of grid row --- ended by swati 24-Feb-2015***/

	@Override
	public void showContextMenu(int selectedRow, int xPosition, int yPosition) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void performOnTouch() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void showOptionMenu(int selectedRow) {
		// TODO Auto-generated method stub
		
	}
	
	public FlexTable createTableComponent( ArrayList<DataGridTableRowModel> dataGridTableRowList, ArrayList<ColumnInfoBean> dataGridTableColList, FlexTable flexTable,ArrayList<String> graphAlignList,ArrayList<String> graphCaptionList,String graphLinkFormat) 
	{
		
		final int noOfRows = dataGridTableRowList.size();
		final int noOfColumns = dataGridTableColList.size();
		//Window.alert("dataGridTableColList:  "+dataGridTableColList.get(0));
		dataProvider.setList( dataGridTableRowList );
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] Start
		E12CustomColumn firstColumn = null;
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] End
		String caption ="";
		ResizableHeader<DataGridTableRowModel> header=null;
		try
		{
			E12CustomTextCell.isValidate = false;
			E12CustomTextCell.currentCellElement = null;
			E12CustomTextCell.currentContext = null;
			E12CustomTextCell.incrFactor = 0;
			E12CustomTextCell.editableField = null;
			E12CustomTextCell.prvEditableField = null;
			
			//  handler for table sorting 
			final ListHandler<DataGridTableRowModel> sortHandler = new ListHandler<DataGridTableRowModel>( dataProvider.getList())
					{
						@Override
						public void onColumnSort(ColumnSortEvent event) {
							super.onColumnSort(event);
							dataProvider.refresh();
						}
					};
			this.addColumnSortHandler(sortHandler);
			int width = 0;
			for( int i= 0  ; i < noOfColumns ; i++ )
			{
				final int index = i;
			    ColumnInfoBean colInfo = dataGridTableColList.get( i );
			    final String colName = colInfo.getDisplayNameOfCol();
			    width = colInfo.getWidth();
				E12CustomColumn column = new E12CustomColumn(i, false);
				column.setSortable( true );
				if(graphAlignList.get(i).trim().equalsIgnoreCase("left"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("right"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("center"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
				}
				if ( i == 0 )
				{
					firstColumn = column;
				}
				sortHandler.setComparator( column , new Comparator<DataGridTableRowModel>() {
				 	
				public int compare( DataGridTableRowModel o1, DataGridTableRowModel  o2 ) 
				 	{
				 		if(isValidDate1(o1.getCellText( index )) && isValidDate1(o2.getCellText( index )))
				 		{
				 			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
				 			Date date1=null,date2=null;
							try {
								 date1 = formatter.parse(o1.getCellText( index ));
								 date2 = formatter.parse(o2.getCellText( index ));
							} catch (Exception e) {
								e.printStackTrace();
							}
							return date1.compareTo(date2);
				 		}
				 		if(isValidDouble(o1.getCellText( index )) && isValidDouble(o2.getCellText( index )))
				 		{
				 			 double d1 = Double.parseDouble(o1.getCellText( index ));
				 		     double d2 = Double.parseDouble(o2.getCellText( index ));
				 			 return Double.compare(d1, d2);
				 		}
				 		else
				 		{
				 			//Window.alert("in string comparision");
						  return o1.getCellText(index).compareTo(o2.getCellText( index ));
				 		}
				 	}
				});
				this.setColumnWidth( column, width +"px" );
				header = new ResizableHeader<DataGridTableRowModel>(colName, this, column ) {
					@Override
					public String getValue() {
						return colName;
					}
				};
				Header<String> footer1 = new Header<String>(new TextCell()) {
					
					@Override
					public String getValue() {
						return "";
					}
				};
				
				this.addColumn(column, header, null);
			}
			caption = graphCaptionList.get(0);			
			dataProvider.addDataDisplay( this );
			dataProvider.refresh();
			this.getColumnSortList().clear();
			this.getColumnSortList().push( firstColumn );
			this.getColumnSortList().push( firstColumn );
			ColumnSortEvent.fire(this, this.getColumnSortList());
		}
		catch (Exception e )
		{
			Window.alert("Exception in table "+ e.getMessage()) ;
		}
		GridThemes.applyDatagridThemes();
		HorizontalPanel excelBtnPnl = new HorizontalPanel();
		Button excelBtn = new Button();
		excelBtn.setTitle("Excel");
		Image excelImg = new Image("FusionChart/images/excel.png");
		excelImg.setHeight("20px");
		excelBtn.getElement().appendChild(excelImg.getElement());
		excelBtnPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(excelBtn).buildExportFormWidget());
		SimplePager.Resources displayPagerResources = GWT.create(SimplePager.Resources.class);
		final SimplePager displayPager = new SimplePager(SimplePager.TextLocation.CENTER, displayPagerResources, false, 0 , true, excelBtnPnl);
		displayPager.setDisplay(this);
		displayPager.setRangeText(rangeText);
		Command setRowCmd = new Command() 
		{
			@Override
			public void execute() 
			{
				try
				{
					int rowNo= (int)Double.parseDouble( "24");
					if( rowNo > 0 && rowNo <= noOfRows)
					{
					    CustomGrid.this.setPageSize( rowNo );
					    displayPager.firstPage();
						dataProvider.refresh();
						rangeText = displayPager.getRangeText();
						displayPager.setRangeText(displayPager.getRangeText());
					}
					else
					{
						displayPager.setRangeText("Error");
					}
				}
				catch (Exception e)
				{
					displayPager.setRangeText("Error");
				}
			}
		};
		displayPager.setRangeCommand( setRowCmd );	
		String cellVal = Window.Location.getParameter("CELL_VAL") == null ? "" : Window.Location.getParameter("CELL_VAL");
		String brandName = Window.Location.getParameter("brand") == null ? "" : Window.Location.getParameter("brand");
		if(caption.trim().length()==0 && cellVal.trim().length()>0)
		{
			if(brandName.trim().length()>0)
			{
				caption = brandName.trim()+" - "+cellVal.trim()+" (Stock Quantity) ";
			}
			else
			{
				caption = cellVal.trim();
			}
		}
		if(caption.trim().length()!=0)
		{
			flexTable.setText(0, 0, caption);
			flexTable.setWidget(1, 0, this);
			flexTable.setWidget(2, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "FlexTable-ColumnHeaderCellFrame");
			flexTable.getCellFormatter().setStyleName(1 ,0 , "gwt-ScrollTableForFrame");
			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager-forIE");
			}
		}else
		{
			flexTable.setWidget(0, 0, this);
			flexTable.setWidget(1, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "gwt-ScrollTableForFrame");			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager-forIE");
			}
		}
		flexTable.setHeight( Window.getClientHeight() - 240 + "px" );
		flexTable.setHeight("180px");
		setHeight("160px");
		flexTable.setStyleName("flexCSSFrame");
		addStyleName("e12AdvDataGrid-SideBarsFrame");
		
		return flexTable;
	}
	
	/**
	 * @param date
	 * @return true
	 * It checks Whether the given String is date.
	 */
	public boolean isValidDate( String date ) 
	{
		SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yy");
		Date testDate = null;
			try 
			{
						testDate = sdf.parse(  date  );
			}			
			catch(Exception ex){
				ex.printStackTrace();
			}
			
			return true;
	}
	
	
	public boolean isValidDouble( String Num ) 
	{
		double numToDouble=0.0;
			try 
			{
					numToDouble = Double.parseDouble(Num);
			}			
			catch(Exception NumberFormatException){
				return false;
			}
			
			return true;
	}
	public boolean isValidDate1( String dateString ) 
	{
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
			try 
			{
	    		Date date = formatter.parse(dateString);
			}			
			catch(Exception ParseException){
				return false;
			}
			
			return true;
	}
}
