var urlForRefresh=null;
var dashboardNameT="";
var compType="";
var isRefresh = false;
var totalPage = 1;
var totalRecords;
var totalPageNo;
var gridMsg = '';
var pagesizec = 0;
var glUrl;
var key="";
var DirProperty="";
var sortState="";

Ext.Loader.setConfig({
	enabled: true,
	disableCaching: false,
	paths: {
        "Ext.ux": "/final/scripts/ux",
		"utilities": "/final/scripts/utilities"
    }
});
Ext.define('DashboardGeneralMeasuresGridPanel', {
	extend: 'Ext.panel.Panel',
	alias:'widget.dashboardgeneralmeasuresgridpanel',
	url:"",
	border:false,
	frame:false,
	layout:'fit',
	//bodyCls:'general-dashboard-grid-panel',
	screenLabelPath:"",

	loadTab:function(url,tabValue,totalRecords,pageNo,totalPageNo){
		var me = this;
		if(Ext.isEmpty(url))			// Prem
			url = this.url;
		var combovalue = Ext.getCmp('comboValue');
		if(!Ext.isEmpty(combovalue))
			combovalue = combovalue.value;
		isRefresh = false;
		if(!Ext.isEmpty(url) && url.indexOf("Refreshing") > -1)
		{
			isRefresh = true;
		}
		if(!Ext.isEmpty(compSelectedValue) && Ext.isEmpty(combovalue))
		{
			if(!Ext.isEmpty(url) && url.indexOf("appCurrentHost") > -1)
			{
				var updateUrl = url.split("&");
				var newUrl="";
				for(var i=0;i<updateUrl.length;i++)
				{
					var name = updateUrl[i];
					if(name.indexOf("appCurrentHost") > -1)
					{
						var value = name.substring(name.indexOf("=")+1,name.length);
						name = 'appCurrentHost='+compSelectedValue;
					}
					newUrl = newUrl+name+"&";
				}
				url = newUrl;
			}
			else
			{
				url = url+'&appCurrentHost='+compSelectedValue;
			}
		}
		urlForRefresh=url;
		Ext.Ajax.request({
			url : url,
			scope:this,
		    success: function(response){
		        var jsonText = response.responseText;
		        var jsonData = Ext.decode(jsonText);

				if(!Ext.isEmpty(jsonData.aggregateTab))										// Prem
				{
					if(!Ext.isEmpty(me.up('segmentsdashboard')))
						me.up('segmentsdashboard').aggregateTab = jsonData.aggregateTab;
					if(!Ext.isEmpty(me.up('servicesdashboard')))
						me.up('servicesdashboard').aggregateTab = jsonData.aggregateTab;
					if(!Ext.isEmpty(me.up('zonesdashboard')))
						me.up('zonesdashboard').aggregateTab = jsonData.aggregateTab;
				}																			// Prem

				var dockedItems = me.getDockedItems();
				for(var dockedCounter = 0 ; dockedCounter < dockedItems.length ; dockedCounter++){
					me.removeDocked(dockedItems[dockedCounter]);
				}

				if(!Ext.isEmpty(urlForRefresh) && urlForRefresh.indexOf('Refreshing=true') < 0)
					me.removeAll();
				
				try
				{
					if(!Ext.isEmpty(jsonData) && Ext.isEmpty(jsonData.error)){

					totalRecords=jsonData.countJson['recount'];
					totalPageNo=jsonData.countJson['totalPages'];
					pagesizec=jsonData.countJson['pagesizec'];
					this.entireData = jsonData;
					this.entireOrgData = jsonData;
					this.totalRecords = totalRecords;
					this.totalPageNo = totalPageNo;
					this.pagesize = pagesizec;
					var currentPage = 1;
					if(pageNo != null && pageNo != undefined && pageNo != 'undefined' && typeof(pageNo) == 'number')
						currentPage=pageNo;
					startIn = (currentPage -1)*pagesizec;
					endIn = startIn + pagesizec;
					startIn = startIn+1;
					if(endIn > totalRecords )
						endIn = totalRecords;
					
					gridMsg = startIn+ ' - '+endIn+' '+oftxt+' '+totalRecords;
					if(totalRecords <= 0)
						totalRecords = 1;
							this.displayGrid(jsonData,tabValue,url,totalRecords,pageNo,totalPageNo,gridMsg);

						if(!Ext.isEmpty(Ext.getCmp('afterTextColumn')))
						{
							Ext.getCmp('afterTextColumn').setValue('1');
						}

						var val = 1;
						if(pageNo !=null && pageNo != undefined && pageNo != 'undefined' && typeof(pageNo) == 'number')
							val = pageNo;
						
						if(Ext.getCmp('afterTextColumn'))
						{
							Ext.getCmp('afterTextColumn').setValue(val);
							
							if(val == 1 || val == '1')
							{
								Ext.getCmp('firstRec').setDisabled(true);
								Ext.getCmp('prevRec').setDisabled(true);
								if(val == totalRecords){
									Ext.getCmp('nextRec').setDisabled(true);
									Ext.getCmp('lastRec').setDisabled(true);
								}
							}
							else if(val == totalRecords)
							{
								Ext.getCmp('nextRec').setDisabled(true);
								Ext.getCmp('lastRec').setDisabled(true);
							}
						}

					}else{
						//display error message
						var error_msg=jsonData.error;
						var toolbarConfig=this.formToolbar(jsonData,isRefresh);
						var error_panel={
								xtype:'emptypanel',
								//tbar:toolbarConfig,
								style:{'border':'0px solid green !important'},
								border:false,
								margin:0,
								frame:false,
								bodyStyle:{'background-color':'transparent !important','background-image':'none !important'},
								cls:'datapanel',
								items: [{
										xtype: 'container',
										//padding: 50,
										style: {
											'text-align': 'center'
										},
										html: '<div class = "iconInformation" style="margin:15% auto 0px auto"></div><div>'+error_msg+'</div>'
										}
								]
								//height : '100%'
						};
						this.addDocked({
							xtype: 'toolbar',
							dock: 'top',
							cls:'linebottom toolbarBg',
							padding:'1 10 1 2',
							//bodyStyle:{'background-color':'transparent !important','background-image':'none !important'},
							//style:{'background-color':'transparent !important','background-image':'none !important'},
							items: toolbarConfig
						});
						this.add(error_panel);
					}
				}catch(e){
					console.log(e)
				}
		       
		    }
		});
	},

	formToolbar:function(jsonData,isRefresh){
		//create combo if selectfieldData present in data
		var compCombo=null;
		if(!Ext.isEmpty(jsonData.selectFieldData)){
			var comboStore = Ext.create('Ext.data.Store',{
				fields:['value','name'],
				proxy:{
					type: 'memory',
					reader: {
		            	type: 'json',
		            	root:'selectOptions'
		        	}
				},
				data:jsonData.selectFieldData
			});
			var comboValueId = Ext.getCmp('comboValue');
			if(!Ext.isEmpty(comboValueId) && !isRefresh)
				comboValueId.destroy();
			compCombo={
					xtype:'combo',
					id:'comboValue',
					editable : false,
					store:comboStore,
					labelSeparator:'',
					cls : 'dropdown',
					displayField:'name',
					valueField:'value',
					trigerAction:'all',
					fieldLabel:jsonData.selectFieldData.selectFieldLabel,
					labelWidth:40,
				//	margin:1,
					margin:'8 0 8 8',
					value:jsonData.selectFieldData.selectedValue
			};
		}

		var systemGridTitle=jsonData.screenLabels[this.screenLabelPath+'.systemTitle'];
		var toolbarConfig=new Array();
		toolbarConfig.push({
			xtype:'label',
			text:systemGridTitle,
			cls:'toolbar-title',
		//	margin:3,
			margin:8,
			disableSelection : true
		});

		if(!Ext.isEmpty(compCombo)){
			toolbarConfig.push('->');
			toolbarConfig.push(compCombo);
		}

		return toolbarConfig;
	},

	displayGrid:function(jsonData,tabValue,url,totalRecords,pageNo,totalPageNo,gridMsg){
		try
		{
			if(!Ext.isEmpty(urlForRefresh) && urlForRefresh.indexOf('Refreshing=true') < 0)
			{
				Ext.getCmp('firstRec').destroy();
				Ext.getCmp('prevRec').destroy();
				Ext.getCmp('afterTextColumn').destroy();
				Ext.getCmp('nextRec').destroy();
				Ext.getCmp('lastRec').destroy();
				Ext.getCmp('refresAct').destroy();	
			}
		}
		catch (e)
		{
		}
		
		var meComp = this;
		if(tabValue != undefined && tabValue != null)
			dashboardNameT = tabValue;
		else
			dashboardNameT = 'otherDashboard';
		
		glUrl = url;
		var storeFields=new Array();
		var columns=new Array();
		var systemColumn={dataIndex:'system'};
		systemColumn.text='<span style="margin-top:2px;display:inline-block">'+jsonData.columns[0].text+'</span>';
		systemColumn.menuDisabled = true;
		systemColumn.width=250;
		systemColumn.locked=true;
		systemColumn.sortable = true;
		systemColumn.url=url;
		systemColumn.SortForCompName=jsonData.columns[0].SortForCompName;
		systemColumn.SortTypeForCompName=jsonData.columns[0].SortTypeForCompName;
		var endUserText = 'User Details';
		try
		{
			endUserText = jsonData.measures[0].endUserText;
		}
		catch (w)
		{
			endUserText = 'User Details';
		}
	//	endUserText="Comparison";
		endUserText="Resource Usage Analysis";
		//systemColumn.cls = 'textAlignCenter';
		systemColumn.listeners= {
			'headerclick':function(gridheader,eventobj,tml){
				key=eventobj.SortForCompName;
				DirProperty=eventobj.dataIndex;
				sortState=eventobj.SortTypeForCompName;
				url=eventobj.url;
				var fromPageView=jsonData.pageParams.fromPageView;
				Ext.ComponentQuery.query("#"+meComp.itemId)[0].sortByGridColumn(key,sortState,fromPageView,url);
			}
		};
		systemColumn.renderer=function(value,metaData,record,rowIndex,colIndex){
			var endUserUrlLink = record.get("endUserUrl");
			var layerModelLink = record.get("layerModelUrl");
			var MaintenanceTime = record.get("MaintenanceTime");
			var configChange = record.get("configChange");
			var widthComp=100;
			//var widthExtra=45;
			var extraIcons="";
			var isMaintence=false;
			var isConfigChanges=false;
			var isEnduserLink=false;
			if(!Ext.isEmpty(MaintenanceTime) && MaintenanceTime!=null && MaintenanceTime!=undefined)
			{
				widthComp=87;
				//widthExtra=20;
				isMaintence=true;
				extraIcons='<div style="margin-top:2px;margin-right:4px;float:left;"><img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="  class="iconMaintenance" data-qclass="yellowTip" style="margin:auto;text-align:center" data-qtip="'+MaintenanceTime+'"/></div>';
			}

			if(!Ext.isEmpty(configChange) && configChange!=null && configChange!=undefined)
			{
				if(isMaintence)
				{
					widthComp=80;
					//widthExtra=40;
				}
				else
				{
					widthComp=87;
					//widthExtra=20;
				}
				isConfigChanges=true;
				var confighref = '/final/monitor/EgConfigChange.jsp?componentName='+configChange;
				extraIcons=extraIcons+'<div id="configchange" style="margin-top:2px;margin-right:4px;float:left;"><img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" onclick="configPop(\''+confighref+'\')" onmouseover="javascript:void(0)" class="iconConfigUser handSymbol"  data-qclass="yellowTip" style="margin:auto;text-align:center" data-qtip="Configuration"/></div>';
			}
			if(!Ext.isEmpty(endUserUrlLink) && endUserUrlLink!=null && endUserUrlLink!=undefined)
			{
				if(isMaintence)
				{
					widthComp=80;
					//widthExtra=35;
				}
				else
				{
					widthComp=82;
					//widthExtra=20;
				}
				isEnduserLink=true;
				//extraIcons=extraIcons+'<div id="configchange" style="margin-top:2px;margin-right:4px;float:left;"><img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" onclick="configPop(\''+confighref+'\')" onmouseover="javascript:void(0)" class="iconConfigUser handSymbol"  data-qclass="yellowTip" style="margin:auto;text-align:center" data-qtip="Configuration"/></div>';
				extraIcons=extraIcons+'<div style="margin-top:-1px;margin-right:4px;float:left;position:relative;top:3px;"><a href="'+endUserUrlLink+'" ><img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" class="iconResourceUsage handSymbol"  data-qclass="yellowTip" style="margin:auto;text-align:center" data-qtip="'+endUserText+'"/> </a></div>';
			}
			if(isMaintence && isConfigChanges && isEnduserLink)
				widthComp = 70;

			var full_text='<div style="float:left;overflow:hidden;text-overflow:ellipsis;width:'+widthComp+'%;"><img style="vertical-align:middle;display:inline-block;margin-right:10px;margin-top:0px;" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-qclass="yellowTip" class="columnIcon '+record.get("systemIconClass")+'" data-qtip='+record.get("systemIconTitle")+'/><a href='+layerModelLink+'  data-qtip='+record.get("systemTitle")+' style="position:relative;top:1px;">'+value+'</a></div>';

			if(extraIcons!=null && extraIcons!=undefined && extraIcons!="")
			{
				var styleclass="style=\"float:right;\"";
				if(value.length>30)
				{
					styleclass="";
				}
				//full_text=full_text+'<div style="float:right;margin-left:2px;width:'+widthExtra+'px;">'+extraIcons+'</div>';
				//full_text=full_text+'<div style="float:right;width:'+widthExtra+'px;">'+extraIcons+'</div>';
				full_text=full_text+'<div style="float:right;">'+extraIcons+'</div>';
				//-w-//full_text=full_text+'<span '+styleclass+'>'+extraIcons+'</span>';
				//full_text=full_text+extraIcons;
			}

			return full_text;
			// return '<img style="vertical-align:middle;display:inline-block;margin-right:10px;margin-top:-2px;" src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-qclass="yellowTip" class="columnIcon '+record.get("systemIconClass")+'" data-qtip='+record.get("systemIconTitle")+'><a href='+layerModelLink+'  data-qtip='+record.get("systemTitle")+'>'+value+'</a>';

			// <div style="margin-bottom:-2px" data-qclass="yellowTip" class="columnIcon '+record.get("systemIconClass")+'"  data-qtip="'+record.get("systemIconTitle")+'"></div>&nbsp;<a href="'+record.get("layerModelUrl")+'"  data-qclass="yellowTip"  data-qtip="'+record.get("systemTitle")+'">'+value+'</a>';
		};
		storeFields.push('system');
		storeFields.push('systemTitle');
		storeFields.push('systemIconClass');
		storeFields.push('systemIconTitle');
		storeFields.push('layerModelUrl');
		storeFields.push('endUserUrl');
		storeFields.push('MaintenanceTime');
		storeFields.push('configChange');
		systemColumn.draggable=false;

		columns.push(systemColumn);
		
		/*var widthPad="180px";
		var colLenVal=3;
		var colLen=(jsonData.columns.length-1);
		if(jsonData!=null && jsonData!=undefined && jsonData.columns!=null && jsonData.columns!=undefined && (jsonData.columns.length-1)<5)
		{
			var viewSizeVal=Ext.getBody().getViewSize().width;
			colLenVal=jsonData.columns.length;
			if(viewSizeVal>1400)
			{
				widthPad="980px";
			}
			else
			{
				widthPad="780px";
			}
		}*/

		var ary=[],aryIndex=0,maxLength=0;
		if(!Ext.isEmpty(jsonData) && !Ext.isEmpty(jsonData.measures) && jsonData.measures!="undefiend")
		{
			if(jsonData.measures.length>0)
			{
				for(var j=0;j<jsonData.columns.length;j++)
				{
					ary=[];
					maxLength=0;
					for(var k=0;k<jsonData.measures.length;k++)
					{
						if((jsonData.measures[k][""+j+"MeasureValueLenWidth"])>0 && jsonData.measures[k][""+j+"MeasureValueLenWidth"]!="-" && jsonData.measures[k][""+j+"MeasureValueLenWidth"]!="undefined")
						{
							ary[aryIndex]=jsonData.measures[k][""+j+"MeasureValue"];
							aryIndex++;
						}
					}
					if(ary.length>0)
					{
						for(var i=0;i<ary.length;i++)
						{
							if( ary[i]!=null && ary[i]!="undefined")
							{
								if(ary[i].indexOf(".")!=-1){
									if(maxLength < (ary[i].substr(0,ary[i].indexOf("."))).length)
									{
										maxLength=(ary[i].substr(0,ary[i].indexOf("."))).length;
									}
								}
								else
								{
									if(maxLength < ary[i].length)
									{
										maxLength = ary[i].length;
									}
								}
							}
						}
					}
					for(var l=0;l<jsonData.measures.length;l++)
					{
						if((jsonData.measures[l][""+j+"MeasureValueLenWidth"])>0 && jsonData.measures[l][""+j+"MeasureValueLenWidth"]!="-" && jsonData.measures[l][""+j+"MeasureValueLenWidth"]!="undefined")
						{
							jsonData.measures[l][""+j+"MeasureValueLenWidth"]=maxLength*7;
						}
					}
				}
			}
		}
		for(var j=1;j<jsonData.columns.length;j++){
			var recMeasureCol=jsonData.columns[j];
			var measureCol=new Object();
			measureCol.text = '<span style="margin-top:2px;display:inline-block">'+recMeasureCol.text+'</span></br><span class="gridUnitText">'+recMeasureCol.unit+'</span>';
			measureCol.cls = 'textAlignCenter';
			//measureCol.html ='<div>' + '('+recMeasureCol.unit+')</div>';// Prem
			measureCol.menuDisabled = true;
			measureCol.sortable = true;
			measureCol.dataIndex=recMeasureCol.dataIndex;
			measureCol.measureOrgName=recMeasureCol.measureOrgName;
			measureCol.sortType=recMeasureCol.sortType;
			measureCol.url=url;
			//measureCol.width=150;
			/*if(recMeasureCol.text.length > 20)
			{
				//measureCol.width='auto !important';
				measureCol.width=(recMeasureCol.text.length*8);
			}
			else
			{
				measureCol.width=150;
			}*/
			
			/*if(recMeasureCol.text.length > 20)
			{
				//measureCol.width='auto !important';
				if(recMeasureCol.columnWith!=null && recMeasureCol.columnWith!=undefined && recMeasureCol.columnWith!="" && recMeasureCol.columnWith!="-1")
				{
					if(colLen<=8)
						measureCol.flex = 1;
					else
						measureCol.width=parseInt(recMeasureCol.columnWith);
				}
				else
				{
					measureCol.width=(recMeasureCol.text.length*8);
				}

				try
				{
					if((recMeasureCol.text.length*8)>300)
					{
						widthPad="780px";
					}
					else
					{
						widthPad="180px";
						if(colLenVal<5)
						{
							var viewSizeVal=Ext.getBody().getViewSize().width;
							if(viewSizeVal>1400)
							{
								widthPad="980px";
							}
							else
							{
								widthPad="780px";
							}
						}
					}
				}
				catch (e)
				{
					widthPad="180px";
				}
			}
			else
			{
				if(recMeasureCol.columnWith!=null && recMeasureCol.columnWith!=undefined && recMeasureCol.columnWith!="" && recMeasureCol.columnWith!="-1")
				{
					if(colLen<=8)
						measureCol.flex = 1;
					else
						measureCol.width=parseInt(recMeasureCol.columnWith);
				}
				else
				{
					measureCol.width=150;
				}
			}

			if(recMeasureCol.columnWith!=null && recMeasureCol.columnWith!=undefined && recMeasureCol.columnWith!="" && recMeasureCol.columnWith!="-1")
			{
				//if(false && colLen<=8)
					//measureCol.flex = 1;
			}
			else
			{
				if(colLen<=8)
					measureCol.flex = 0.75;
			}
*/
			measureCol.listeners= {
				'headerclick':function(gridheader,eventobj,tml){
					key=eventobj.measureOrgName;
					DirProperty=eventobj.dataIndex;
					sortState=eventobj.sortType;
					var fromPageView=jsonData.pageParams.fromPageView;
					Ext.ComponentQuery.query("#"+meComp.itemId)[0].sortByGridColumn(key,sortState,fromPageView,url);
				}
			};
			measureCol.renderer=function(value,metaData,record,rowIndex,colIndex,store){
				
				var isLocked=false;
				var veryFirstCol = columns[0];
				if(!Ext.isEmpty(veryFirstCol) && veryFirstCol!=undefined && veryFirstCol!=null)
				{
					try
					{
						if(!Ext.isEmpty(veryFirstCol.locked) && veryFirstCol.locked!=undefined && veryFirstCol.locked!=null && veryFirstCol.locked==true)
						{
							isLocked=true;
						}
						else
						{
							isLocked=false;
						}
					}
					catch (e)
					{
						isLocked=false;
					}
				}
				
				if(isLocked)
				{
					colIndex = colIndex + 1;
				}
				
				var currentCol =columns[colIndex];
				var widthAttr=currentCol.dataIndex+"Width";
				var urlAttr=currentCol.dataIndex+"Url";
				var width=record.get(widthAttr);
				var Measureurl=record.get(urlAttr);
				var lenWidthAttr = currentCol.dataIndex+"LenWidth";
			
				var strDecimal='';
				var str='';

				var temValue = value;
				if(!isNaN(parseFloat(value)))
				{
					if(value!=null && value.indexOf(".")>-1)
					{
						strDecimal = value.substring(value.indexOf("."));
						str = value.substring(0,value.indexOf("."));
				    value='<span class="decimal-align dottedText">'+str+'</span><span class="decimal-align2 dottedText">'+strDecimal+'</span>';
					}
					else if(value!=null && (value.indexOf("Yr")> -1 || value.indexOf("Mth")> -1 || value.indexOf("Day")> -1 ||  value.indexOf("Hr")> -1 || value.indexOf("Min")> -1 || value.indexOf("Sec")> -1 ))
					{
						value='<span>'+value+'</span>';
					}
					else
					{
						value='<span class="decimal-align">'+value+'</span>';
					}
				}

				if(!Ext.isEmpty(width)){
					return '<table cellspacing="0" cellpadding="0" border="0" style="table-layout:auto;margin:auto;position:relative;"><col width="80px"><col width="40px">'
					      +'<tr>'
					      +'<td>'
					      +'<table width="80" cellpadding="0" cellspacing="0" border="0"  height="6" class="prog_border">'
								 +'<tr>'
								 +'<td align="left" width="100%" height="6px" class="prog_line" >'
								 	+'<a href='+Measureurl+'><table width="'+width+'%" height="6" cellpadding="0" cellspacing="0" border="0">'
								 	+'<tr>'
								 	+'<td class ="progress_GOOD" width="100%"></td>'
								 	+'</tr>'
								 	+'</table></a>'
								 +'</td>'
								 +'</tr>'
						 +'</table>'
						 +'</td>'
						 +'<td align="right" style="padding-left:5px;width:45px"><a href='+Measureurl+'>'+value+'</td>'			// Prem
						 +'</tr>'
						 +'</table>';
				}
				else if(!Ext.isEmpty(Measureurl))
				{
					/*return '<table cellspacing="0" cellpadding="0" border="0" style="table-layout:auto;width:100%;margin:auto;position:relative;">'
						+'<tr>'
							+'<td align="right" style="width:100%;padding-right: 30px;"><a style ="display:block;width:100%" href='+Measureurl+'>'+value+'</a></td>'			// Prem
						+'</tr>'
						+'</table>';*/	
					var divElement = "<div style='width:100%; text-align:center' data-qtip='"+temValue+"'><a href="+Measureurl+">"+value+"</a></div>";
					return divElement;
				}
				else
				{
					if(value==='-'){
						value='<span class="decimal-align" style="position:relative;">'+value+'</span>';
						//return value;
						return '<table cellspacing="0" cellpadding="0" border="0" style="table-layout:auto;margin:auto;">'
						+'<tr>'
							+'<td align="right" style="padding-left:5px;">'+value+'</td>'			// Prem
						+'</tr>'
						+'</table>';
					}
					else if(value == "No metrics configured")
						value='<p align="center">'+value+'</p>';	
					else{
						return value;			// Prem
					}
				}

				//error message grouping -code start
				if(temValue == 'No metrics configured')
				{
					var first = !rowIndex || temValue !== store.data.items[rowIndex].data['0MeasureValue'];
					  if (first) { 
							var i = rowIndex +1, span = 1; 
							while (i < store.getCount() && temValue === store.data.items[rowIndex].data['0MeasureValue']) { 
							i++; 
							span++; 
						} 
						metaData.tdAttr = 'rowspan = ' + span; 
					 } 
						else{ 
							metaData.tdAttr='style="display:none;"'; 
						} 

						return first ? value : ''; 
				}
				//error message grouping -code end 
			};
			var fieldType = {
				name:recMeasureCol.dataIndex,
				sortType:recMeasureCol.textType
			}
			storeFields.push(fieldType);
			storeFields.push(recMeasureCol.dataIndex+"Width");
			storeFields.push(recMeasureCol.dataIndex+"Url");
			storeFields.push(recMeasureCol.dataIndex+"LenWidth");
			measureCol.draggable=false;

			columns.push(measureCol);
		}
		
		var gridStore=Ext.create('Ext.data.Store',{
			fields:storeFields,
			remoteSort:true,
		    proxy: {
		        type: 'memory',
		        reader: {
		            type: 'json',
		            root:'measures'
		        }
		    },
		    data:jsonData,
			sortOnLoad: true,
			sorters:
			{
				property: DirProperty,
				direction: sortState
			}			
		});

//		this.removeAll();
		var toolbarConfig=this.formToolbar(jsonData,isRefresh);
		try
		{
			if(!Ext.isEmpty(jsonData.selectFieldData.selectedValue))
				compType = jsonData.selectFieldData.selectedValue;
			else
				compType = 'default';
		}
		catch (e)
		{
			compType = 'default';
		}
		if(gridStore.getCount()>0){
			if(!Ext.isEmpty(urlForRefresh) && urlForRefresh.indexOf('Refreshing=true') > -1)
			{
				var gridPanel = this.down('dashboardgeneralmeasuresgrid');
				gridPanel.getStore().loadRawData(jsonData);

			}
			else
			{
				var gridCls="";
				var isLock=false;
				
				//gridCls="gridSkin gridSkin_locking";
				//gridCls="gridSkin gridSkin_locking";
				gridCls="newGridPanel removeTableBg";
				isLock=true;
				var systemGrid=null;
				systemGrid=Ext.create('DashboardGeneralMeasuresGrid',{
					columns:columns,
					//cls:'gridSkin',
					//cls:gridCls,
					ui:gridCls,
					enableLocking:isLock,
					store:gridStore,
					//tbar:toolbarConfig,
					frame:false,
					style:{'z-index':'0'},
					border:false,
					listeners:{
						'columnresize':function( ct, column, width, eOpts )
						{
							try
							{
								var tempColumnDataIndex= (Ext.decode(Ext.util.Cookies.get('tempColumnDataIndex')));
								var tempColumnObj= (Ext.decode(Ext.util.Cookies.get('tempColumnObj')));
								if(tempColumnDataIndex == undefined || tempColumnDataIndex == null)
									tempColumnDataIndex = [];
								if(tempColumnObj == undefined || tempColumnObj == null)
									tempColumnObj = [];
							}
							catch (er)
							{
								var tempColumnDataIndex=[];
								var tempColumnObj=[];
							}
							if(tempColumnObj.size > 0)
							{
								if(tempColumnDataIndex.indexOf(column.dataIndex) != -1)
								{
									var indexVal = tempColumnDataIndex.indexOf(column.dataIndex);
									if(tempColumnObj[indexVal].compType == compType)
									{
										tempColumnDataIndex.splice(indexVal, 1);
										tempColumnObj.splice(indexVal, 1);
									}
									tempColumnDataIndex.push(column.dataIndex);
									tempColumnObj.push({
										"dataIndex":column.dataIndex,
										//"measureOrgName":column.measureOrgName,
										"dashboardName":tabValue,
										"compType":compType,
										"width":width
									});
								}
								else
								{
									tempColumnDataIndex.push(column.dataIndex);
									tempColumnObj.push({
										"dataIndex":column.dataIndex,
										//"measureOrgName":column.measureOrgName,
										"dashboardName":tabValue,
										"compType":compType,
										"width":width
									});
								}
							}
							//Ext.util.Cookies.clear('tempColumnObj');
							//Ext.util.Cookies.clear('tempColumnDataIndex');
							Ext.util.Cookies.set('tempColumnObj',Ext.encode(tempColumnObj));
							Ext.util.Cookies.set('tempColumnDataIndex',Ext.encode(tempColumnDataIndex));
						}
					},
					dockedItems: [{
						hidden:jsonData.countJson['isHidePaging'],
						xtype: 'pagingtoolbar',
						id:'pagingtoolbarCustom'+meComp.itemId,
						store: gridStore,   // same store GridPanel is using
						dock: 'bottom',
						cls:'pagingtoolbar',
						afterPageText:'of '+ totalPageNo,
						displayInfo: true,
						displayMsg: disptxt+' '+ gridMsg,
						moveFirst:function()
						{
							if(glUrl.indexOf("pageNo") > -1)
							{
								glUrl=glUrl.replace(/(pageNo=)[^\&]+/, '$1' +'1');
								Refurl=glUrl;
							}
							else
							{
								glUrl=glUrl+"&pageNo=1";
								Refurl=glUrl;
							}
							if(glUrl.indexOf('&Refreshing=true') > -1)
							{
								glUrl=glUrl.replace(/&Refreshing=true/gi, '')
							}
							Ext.ComponentQuery.query("#"+meComp.itemId)[0].loadTab(glUrl,tabValue,totalRecords,'1',totalPageNo);
							RefpageVal='1';
							Reftot=totalRecords;
							ReftotalPageno=totalPageNo;
						},
						movePrevious:function()
						{
							var pageVal = Ext.getCmp('afterTextColumn').getValue();
							if(pageVal == null || pageVal == '' || pageVal == undefined || pageVal == 'undefined')
								return;
							else
							{
								pageVal = pageVal - 1;
								if(glUrl.indexOf("pageNo") > -1)
								{
									glUrl=glUrl.replace(/(pageNo=)[^\&]+/, '$1' +pageVal);
									Refurl=glUrl;
								}
								else
								{
									glUrl=glUrl+"&pageNo="+pageVal;
									Refurl=glUrl;
								}
								if(glUrl.indexOf('&Refreshing=true') > -1)
								{
									glUrl=glUrl.replace(/&Refreshing=true/gi, '')
								}
								RefpageVal=pageVal;
								Reftot=totalRecords;
								ReftotalPageno=totalPageNo;
								Ext.ComponentQuery.query("#"+meComp.itemId)[0].loadTab(glUrl,tabValue,totalRecords,pageVal,totalPageNo);
							}
						},
						moveNext : function()
						{
							var pageVal = Ext.getCmp('afterTextColumn').getValue();
							if(pageVal == null || pageVal == '' || pageVal == undefined || pageVal == 'undefined')
								return;
							else if(pageVal==totalPageNo)
							{
								Ext.Msg.alert('alert','No More Pages');
								return;
							}
							else
							{
								pageVal = pageVal + 1;
								if(glUrl.indexOf("pageNo") > -1)
								{
									glUrl=glUrl.replace(/(pageNo=)[^\&]+/, '$1' +pageVal);
									Refurl=glUrl;
								}
								else
								{
									glUrl=glUrl+"&pageNo="+pageVal;
									Refurl=glUrl;
								}
								if(glUrl.indexOf('&Refreshing=true') > -1)
								{
									glUrl=glUrl.replace(/&Refreshing=true/gi, '')
								}
								Ext.ComponentQuery.query("#"+meComp.itemId)[0].loadTab(glUrl,tabValue,totalRecords,pageVal,totalPageNo);
							}
							RefpageVal=pageVal;
							Reftot=totalRecords;
							ReftotalPageno=totalPageNo;
						},
						moveLast : function()
						{
							var pageVal = Ext.getCmp('afterTextColumn').getValue();
							if(pageVal==totalPageNo)
							{
								Ext.Msg.alert('alert','No More Pages');
								return;
							}
							
							if(glUrl.indexOf("pageNo") > -1)
							{
								glUrl=glUrl.replace(/(pageNo=)[^\&]+/, '$1' +totalPageNo);
								Refurl=glUrl;
							}
							else
							{
								glUrl=glUrl+"&pageNo="+totalPageNo;
								Refurl=glUrl;
							}
							if(glUrl.indexOf('&Refreshing=true') > -1)
							{
								glUrl=glUrl.replace(/&Refreshing=true/gi, '')
							}
							Ext.ComponentQuery.query("#"+meComp.itemId)[0].loadTab(glUrl,tabValue,totalRecords,totalPageNo,totalPageNo);
							RefpageVal=totalPageNo;
							Reftot=totalRecords;
							ReftotalPageno=totalPageNo;
						},
						onPagingKeyDown:function(field, e)
						{
							var me = this,
							k = e.getKey();
							if (k == e.RETURN) 
							{
								var pageVal = Ext.getCmp('afterTextColumn').getValue();
								if(pageVal == null || pageVal == '' || pageVal == undefined || pageVal == 'undefined')
									return;
								else if(pageVal > totalPageNo)
								{
									Ext.Msg.alert('alert','No More Pages');
									return;
								}
								else
								{
									RefpageVal=pageVal;
									Reftot=totalRecords;
									ReftotalPageno=totalPageNo;
									
									if(glUrl.indexOf("pageNo") > -1)
									{
										glUrl=glUrl.replace(/(pageNo=)[^\&]+/, '$1' +pageVal);
										Refurl=glUrl;
									}
									else
									{
										glUrl=glUrl+"&pageNo="+pageVal;
										Refurl=glUrl;
									}
									if(glUrl.indexOf('&Refreshing=true') > -1)
									{
										glUrl=glUrl.replace(/&Refreshing=true/gi, '')
									}
									Ext.ComponentQuery.query("#"+meComp.itemId)[0].loadTab(glUrl,tabValue,totalRecords,pageVal,totalPageNo);
								}
							}
						},
						emptyMsg: "No topics to display"
					}],
		//			cls:'systemsGrid'
				});
				systemGrid.addDocked({
							xtype: 'toolbar',
							dock: 'top',
							cls:'linebottom',
							padding:'1 10 1 2',
							style:{'background-color':'transparent'},
							items: toolbarConfig
						});
				this.add(systemGrid);
			}
		}else{
			var error_msg=jsonData.screenLabels[this.screenLabelPath+'.noDataMsg'];
			var error_panel={
					xtype:'emptypanel',
					//tbar:toolbarConfig,
					style:{'border':'0px !important'},
					border:false,
					frame:false,
					bodyStyle:{'background-color':'transparent !important','background-image':'none !important'},
					cls:'egDummyClass',
					items: [{
							xtype: 'container',
							//padding: 50,
							style: {
								'text-align': 'center'
							},
							html: '<div class = "iconInformation" style="margin:15% auto 0px auto"></div><div>'+error_msg+'</div>'
							}
					]

				//	xtype:'errorpanel',
				//	errorMsg:error_msg,
				//	tbar:toolbarConfig
			};
			error_panel.addDocked({
						xtype: 'toolbar',
						dock: 'top',
						cls:'linebottom toolbarBg',
						//bodyStyle:{'background-color':'transparent !important','background-image':'none !important'},
						//style:{'background-color':'transparent !important','background-image':'none !important'},
						padding:'1 10 1 2',
						items: toolbarConfig
			});
			this.add(error_panel);
		}
	},
	sortByGridColumn:function(measureOrgName,measureSortType,fromPageView,url)
	{
		var temp_url=url
		if(measureOrgName!=null && measureOrgName!='-1')
		{
			if(temp_url.indexOf("appcolumn") > -1)
			{
				temp_url=temp_url.replace(/(appcolumn=)[^\&]+/, '$1' +measureOrgName);
			}
			else
			{
				temp_url=temp_url=temp_url+"&appcolumn="+measureOrgName;
			}
			if(glUrl.indexOf("appsortOrder") > -1)
			{
				temp_url=temp_url.replace(/(appsortOrder=)[^\&]+/, '$1' +measureSortType);
			}
			else
			{
				temp_url=temp_url=temp_url+"&appsortOrder="+measureSortType;
			}
			if(glUrl.indexOf("pageNo") > -1)
			{
				temp_url=temp_url.replace(/(pageNo=)[^\&]+/, '$1' +" ");
			}
			Refurl=temp_url;
		}
		else
		{
			if(temp_url.indexOf("appcolumn") > -1)
			{
				temp_url=temp_url.replace(/&appcolumn=-2/gi, '')
			}
			if(glUrl.indexOf("appsortOrder") > -1)
			{
				temp_url=temp_url.replace(/&appsortOrder=ASC/gi, '')
			}
			if(glUrl.indexOf("pageNo") > -1)
			{
				temp_url=temp_url.replace(/(pageNo=)[^\&]+/, '$1' +" ");
			}
			Refurl=temp_url;
		}
		Ext.ComponentQuery.query("#"+this.itemId)[0].loadTab(temp_url);
	}
});
