var mainResultsGrid;
var attachRecord;

function getResultsGrid(ds, a, mapName, sessionId) {
    var rowActions = new Ext.ux.grid.RowActions({
        header: '',
        keepSelection: true
			, actions: [
			{
			    iconCls: 'icon-izpis',
			    tooltip: 'Izpis'
			},
			{
			    iconCls: 'icon-analiza',
			    tooltip: 'Analiza'
			},
			{
			    iconCls: 'icon-select',
			    tooltip: 'Izberi vsebino na karti'
			},
			{
			    iconCls: 'icon-zoom',
			    tooltip: 'Izberi in prikaži vsebino na karti'
			},
			{
			    iconCls: 'icon-chart',
			    tooltip: 'Analiza količin izbranih elementov'
			}
			]
    });
    rowActions.on({ action: function(grid, record, action, row, col) {
        if (action == 'icon-izpis') onReportIzpis(grid, record);
        if (action == 'icon-analiza') onReportAnaliza(grid, record);
        if (action == 'icon-zoom') onZoomLayer(grid, record);
        if (action == 'icon-select') onSelectLayer(grid, record);
		if (action == 'icon-chart') onAnalizaKolicin(grid, record);
    }
    });
    mainResultsGrid = new Ext.grid.GridPanel({
        id: 'mainResultsGrid',
        store: ds,
        colModel: new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), rowActions,
		{ header: '<b>Ime Vsebine</b>', width: 200, sortable: false, dataIndex: 'LayerDescription', sortable: true },
		{ header: '<b>Ime Poročila</b>', width: 250, dataIndex: 'LayerReportsFormatted' },
		{ header: '<b>Zadetki</b>', forceFit: true, dataIndex: 'FeatIdsCount', sortable: true }
	]),
         viewConfig: {
             forceFit: false
         },
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true })
        	, listeners: {
        	    cellclick: function(grid, rowIndex, columnIndex, e) {
        	        try {
        	            var fieldName = grid.getColumnModel().getDataIndex(columnIndex);
        	            if (fieldName == "") return;
        	            var rec = grid.getStore().getAt(rowIndex);
        	            var lName = rec.data.LayerName;
        	            if (lName != "Google rezultati") {
        	                var lDesc = rec.data.LayerDescription;
        	                var lReports = rec.data.LayerReports;
        	                var fIds = rec.data.FeatIds;
        	                var lReportsFormatted = rec.data.LayerReportsFormatted;
        	                showLayerReports(a, mapName, sessionId, lName, lDesc, lReports, fIds, lReportsFormatted);
        	            }
        	        } catch (err) { }
        	    }
        	}
	, plugins: rowActions
    });
    return mainResultsGrid;
}

function getReportGrid(reportName, ds, columns, tooltips, filters, rowActions, isCollapsed, reportNameFormatted) {
    var colModel = new Ext.grid.ColumnModel({
        columns: columns,
        defaults: {
            forceFit: false,
            sortable: true,
            menuDisabled: false
        }
    });
    colModel.defaultSortable = true;
    var cellTips = new Ext.ux.plugins.grid.CellToolTips(tooltips);
    var search = new Ext.ux.grid.Search({
        searchText: 'Iskanje'
				, mode: 'local'
				, iconCls: true
				//, position: 'top'
    });
    var myPagingToolbar = new Ext.PagingToolbar({
        pageSize: 500,
        displayInfo: true,
        displayMsg: 'Prikazujem rezultate {0} - {1} od {2}',
        emptyMsg: "Ni rezultatov za prikaz",
        firstText: 'Prva stran',
        lastText: 'Zadnja stran',
        prevText: 'Prejšnja stran',
        nextText: 'Naslednja stran',
        beforePageText: 'Stran',
        afterPageText: 'od {0}',
        refreshText: 'Osveži',
        store: ds,
        plugins: [filters]
    });
    var grid = new Ext.grid.GridPanel({
        store: ds,
        colModel: colModel,
        id: reportName,
        title: '<b>' + reportNameFormatted + '</b>',
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        fitContainer: false,
        border: true,
        frame: false,
        stripeRows: true,
        autoSizeColumns: true,
        collapsed: isCollapsed,	
        tbar: [{
            iconCls: 'icon-zoom',
            text: 'Prikaži vse na karti',
            handler: function() {
                var grid = this.ownerCt.ownerCt;                
                var layer = reportTabPanel.getActiveTab().id;                
                var featIds = '';
                grid.store.each(function(record) {
                    if (featIds == '') {
                        var featIdValue = record.get("FEATURE_ID");
                        featIds = featIdValue;
                    }
                    else {
                        var featIdValue = record.get("FEATURE_ID");                        
                        featIds = featIds + ',' + featIdValue;
                    }
                });
                zoomToSelected(layer, featIds);
            }
        },
		{
		    iconCls: 'icon-save-table',
		    text: 'Izvozi v SDF',
		    handler: function() {
		        var grid = this.ownerCt.ownerCt;
		        var mf = mainframe.viewerFrame.mapFrame;
		        var sessionId = mf.GetSessionId();
		        var mapName = mf.GetMapName();
		        var layer = reportTabPanel.getActiveTab().id;
		        var featIds = '';
		        grid.store.each(function(record) {					
		            if (featIds == '')
		                featIds = record.get("FEATURE_ID");
		            else
		                featIds = featIds + ',' + record.get("FEATURE_ID");
		        });

		        var paramss = new Array(
						"a", appName,
                        "sessionId", sessionId,
                        "mapName", mapName,
                        "layer", layer,
						"featIds", featIds);
		        var pageUrl = "../KaliopaFDOService/CreateSDF.aspx";
		        mf.parent.formFrame.Submit(pageUrl, paramss, "_self");
		    }
		},
		{
		    iconCls: 'icon-page-excel',
		    text: 'Izvozi v Excel',
		    handler: function() {
		         var mf = mainframe.viewerFrame.mapFrame;
		        var htmlTable = getExtGridTable(grid);
				var paramss = new Array(	
						"a", appName,				
						"tableHtml", htmlTable,
						"type", "xls");						
		        var pageUrl = "../KaliopaFDOService/ExportByType.aspx";
		        mf.parent.formFrame.Submit(pageUrl, paramss, "_self");
		    }
		},
		{
		    iconCls: 'icon-page-word',
		    text: 'Izvozi v Word',
		    handler: function() {
		         var mf = mainframe.viewerFrame.mapFrame;
		        var htmlTable = getExtGridTable(grid);
				var paramss = new Array(
						"a", appName,
						"tableHtml", htmlTable,
						"type", "doc");						
		        var pageUrl = "../KaliopaFDOService/ExportByType.aspx";
		        mf.parent.formFrame.Submit(pageUrl, paramss, "_self");
		    }
		},
		{
		    iconCls: 'icon-page-pdf',
		    text: 'Izvozi v PDF',
		    handler: function() {
		        var mf = mainframe.viewerFrame.mapFrame;
		        var htmlTable = getExtGridTable(grid);
				var paramss = new Array(
						"a", appName,
						"tableHtml", htmlTable,
						"type", "pdf");						
		        var pageUrl = "../KaliopaFDOService/ExportByType.aspx";
		        mf.parent.formFrame.Submit(pageUrl, paramss, "_self");
		    }
		},
		{
			text   : 'Natisni', 
			iconCls: 'icon-print', 
			handler: function() { 
				Ext.ux.GridPrinter.print(grid);       
			} 
		}
		],
        bbar: myPagingToolbar,
        loadMask: true,
        trackMouseOver: false,
        viewConfig: { forceFit: false },
        view: new Ext.grid.GroupingView({
            forceFit: false,
            startCollapsed: true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Elementov" : "Item"]})',
            groupTextTpl: '{text} ({values.rs.length})',
            showGroupsText: 'Prikaži v skupinah',
            groupByText: 'Združi vrednosti stolpca v skupine',
            sortAscText: 'Sortiraj (naraščajoče)',
            sortDescText: 'Sortiraj (padajoče)',
            columnsText: 'Stolpci (ON/OFF)'
        }),
        plugins: [cellTips, filters, search, rowActions]

    });
	
	grid.on('expand', function(panel){
						if (panel.store.data.length>0) return;
						panel.store.load({params:{start: 0, limit: 500}});
					});
	grid.on('afterRender', function() {
			 if (this.getView().cm.columns.length<11)
				 this.getView().forceFit = true;
			 else
				 this.getView().forceFit = false;
			 this.autoWidth = false;
             this.getView().updateAllColumnWidths();//Bug Ext 3.0
    }); 
	
    return grid;
}

function getSimpleReportGrid(reportName, ds, columns, tooltips, filters) {
    var colModel = new Ext.grid.ColumnModel({
        columns: columns,
        defaults: {
            forceFit: false,
            sortable: true,
            menuDisabled: false
        }
    });
    colModel.defaultSortable = true;
    var cellTips = new Ext.ux.plugins.grid.CellToolTips(tooltips);
    var search = new Ext.ux.grid.Search({
        searchText: 'Iskanje'
				, mode: 'local'
				, iconCls: true
				, position: 'top'
    });
    var myPagingToolbar = new Ext.PagingToolbar({
        pageSize: 500,
        displayInfo: true,
        store: ds,
        plugins: [filters]
    });
    var grid = new Ext.grid.GridPanel({
        store: ds,
        colModel: colModel,
        id: reportName,        
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        fitContainer: false,
        border: true,
        frame: false,
        stripeRows: true,
        autoSizeColumns: true,
        tbar: [{
		    id: 'grid-excel-button',
		    iconCls: 'icon-page-excel',
		    text: 'Izvozi v Excel...',
		    handler: function() {
		        var grid = this.ownerCt.ownerCt;
		        var jsonData = getStoreJson(grid).toString();
		        jsonData = encodeURIComponent(jsonData);
		        var mf = mainframe.viewerFrame.mapFrame;
		        var sessionId = mf.GetSessionId();
		        var mapName = mf.GetMapName();
		        var layer = reportTabPanel.getActiveTab().id;
		        var reportName = reportTabPanel.getActiveTab().title;
		        var paramss = new Array(
						"a", appName,
                        "sessionId", sessionId,
                        "mapName", mapName,
                        "layer", layer,
						"jsonData", jsonData,
						"reportName", reportName);
		        var pageUrl = "../KaliopaFDOService/ExportToExcel.aspx";
		        mf.parent.formFrame.Submit(pageUrl, paramss, "_self");
		    }
		}
		],
        bbar: myPagingToolbar,
        loadMask: true,
        trackMouseOver: false,
        viewConfig: { forceFit: false },
        view: new Ext.grid.GroupingView({
            forceFit: true
        }),
        plugins: [cellTips, filters, search]

    });	
    return grid;
}

function showLayerReports(a, mapName, sessionId, layerName, layerDescription, layerReports, featIds, layerReportsFormatted) {
    var TabExists = reportTabPanel.getItem(layerName);
    if (TabExists != null) {
        reportTabPanel.setActiveTab(TabExists);
        return;
    }
    var reportsSplit = layerReports.split(",");
    var reportsSplitFormatted = layerReportsFormatted.split("<br/>");
    var accordPanels = [];
    var firstPanel = true;
    var collapseGrid = false;
	var grid = null;
    if (reportsSplit.length > 1) collapseGrid = true;
    for (i = 0; i < reportsSplit.length; i++) {
		try {
			var reportName = reportsSplit[i];
			var reportNameFormatted = reportsSplitFormatted[i];
			var reportFields = getReportFields(a, sessionId, mapName, layerName, reportName);
			var showAttach = showAttachments(reportFields);
			var rowActions = getRowActions(showAttach);
			var columns = getLayerGridColumns(reportFields, rowActions);
			var tooltips = getLayerGridTooltips(reportFields);
			var gridFilters = getReportFilters(reportFields);
			var filters = new Ext.ux.grid.GridFilters({
				local: true,
				filters: gridFilters
			});

			var reportStore = getReportData(a, sessionId, mapName, layerName, reportName, featIds, reportFields, firstPanel);
			if (columns[2]!=null) reportStore.setDefaultSort(columns[2].dataIndex, 'ASC');
			grid = getReportGrid(reportName, reportStore, columns, tooltips, filters, rowActions, collapseGrid, reportNameFormatted)
			accordPanels.push(grid);
			firstPanel = false;
        } catch (err) { }        
    }
	var tabResultLayout = 'accordion';
	var tabResultItems = accordPanels;
	if (reportsSplit.length==1){
		tabResultLayout = 'fit';
		tabResultItems = grid;
	}	
    var tabResult = reportTabPanel.add({
        id: layerName,
        title: layerDescription,
        split: true,
        closable: true,
        layout: tabResultLayout,
        autoScroll: false,
        items: tabResultItems
    });
    reportWindow.add(reportTabPanel);
    reportTabPanel.setActiveTab(tabResult);
    reportTabPanel.doLayout();
    reportWindow.doLayout();
}

//Grid Plugins
function getRowActions(showAttach) {
    var rowActions;
    if (showAttach) {
        rowActions = new Ext.ux.grid.RowActions({
            header: '',
            keepSelection: true
			, actions: [
			{
			    iconCls: 'icon-zoom',
			    tooltip: 'Približaj izbrano območje'
			},
			{
			    iconCls: 'icon-attach',
			    tooltip: 'Urejaj priponke'
			}
			]
        });
        rowActions.on({ action: function(grid, record, action, row, col) {
            if (action == 'icon-zoom') onZoomToAction(grid, record);
            if (action == 'icon-attach') onAtachAction(grid, record);
        }
        });
    } else {
        rowActions = new Ext.ux.grid.RowActions({
            header: '',
            keepSelection: true
			, actions: [
			{
			    iconCls: 'icon-zoom',
			    tooltip: 'Približaj izbrano območje'
}]
        });
        rowActions.on({ action: function(grid, record, action, row, col) {
            if (action == 'icon-zoom') onZoomToAction(grid, record);
        }
        });
    }
    return rowActions;
}


function onZoomToAction(grid, record) {
    var mf = mainframe.viewerFrame.mapFrame;
    var layer = reportTabPanel.getActiveTab().id;
    if (!mf.IsLayerVisible(layer)) {
		mf.ChangeLayerState(layer, true, true);		
			
    }
	featId = record.get("FEATURE_ID");
	zoomToSelected(layer, featId);
}

function onAtachAction(grid, record) {
    var attachmentId = record.data.PRIPONKE;
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var layer = reportTabPanel.getActiveTab().id;
    var featId = record.get("FEATURE_ID");
    var params = '?appName=' + appName + '&sessionId=' + sessionId + '&mapName=' + mapName + '&layerName=' + layer + '&featId=' + featId + '&attachmentId=' + attachmentId;
    showDialogWindow('Urejevalnik priponk', 815, 520, '../mapguide/Attachments/Index.htm' + params);
    attachRecord = record;
}

function onReportIzpis(grid, record) {
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var args = '{"a":"' + appName + '","sessionId":"' + sessionId + '","mapName":"' + mapName + '","layerName":"' + record.data.LayerName + '","featIds":"' + record.data.FeatIds + '"}';
    var featDataJson = calWebService('../mapguide/KaliopaFDOService/Service.asmx/GetFeatures', args);
    var fields = ['FeatId', 'FeatXml'];
    var featData = new Ext.data.Store({
        data: featDataJson,
        reader: new Ext.data.JsonReader({
            idProperty: 'Id',
            root: 'd.rows',
            totalProperty: 'd.totalRows',
            fields: fields
        })
    });
    featData.each(function(rec) {
        mf.MultiGridShow2(rec.data.FeatXml);
    });
}
function onAnalizaKolicin(grid, record) {
	var TabExists = reportTabPanel.getItem("tabAnalizaKolicin");
    if (TabExists != null) {
        reportTabPanel.setActiveTab(TabExists);
        return;
    }
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
	var webLayout = mf.parent.webLayout;
	var p = mf.GetVisiblePodloge();
	var t = mf.GetVisiblePodlogeTransparency();
	var w = mf.mapDevW;
	var h = mf.mapDevH;
	var s = mf.curScale;
	var selection = "";
	var paramss = new Array(
                        "Session", sessionId, 
                        "mapName", mapName,
                        "a", appName,
						"selection", "",
						"WEBLAYOUT", webLayout,
						"p", p,
						"t", t,
						"w", w,
						"h", h,
						"s", s,
						"SEQ", Math.random());

	var lName = record.data.LayerName;
	var featIds = record.data.FeatIds;
	var layReps = record.data.LayerReports;		
	paramss.push("LAYERNAME0");
	paramss.push(lName);
	paramss.push("FEATIDS0");
	paramss.push(featIds);
	paramss.push("LAYERREPORTS0");		
	paramss.push(layReps);
	
	var pageUrl = "../KaliopaFDOService/AnalizaKolicin.aspx";
	var pnlAnalizaKolicin = new Ext.Panel({
		id: 'analizaKolicinPanel',
        html: '<div style="width:100%; height:100%" id="analizaKolicinDiv" >'+
			  '<iframe id="analizaKolicinDivFrame" name="analizaKolicinDivFrame" frameborder="no" allowtransparency="true"'+
              ' style="border: 0" src="" width="100%"'+
              ' height="100%"></iframe>'+
			  '</div>',
		layout: 'fit'        
    });
    var tabAnalizaKolicin = reportTabPanel.add({
        id: "tabAnalizaKolicin",
        title: "Analiza količin",
        //split: true,
        closable: true,
        layout: 'fit',
        //autoScroll: false,
        items: pnlAnalizaKolicin
    });
    reportTabPanel.setActiveTab(tabAnalizaKolicin);
    reportTabPanel.doLayout();
	mf.parent.formFrame.Submit(pageUrl, paramss, "analizaKolicinDivFrame");
}
function onReportAnaliza(grid, record) {
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var lName = record.data.LayerName;
    if (lName != "Google rezultati") {
        var lDesc = record.data.LayerDescription;
        var lReports = record.data.LayerReports;
        var fIds = record.data.FeatIds;
        var lReportsFormatted = record.data.LayerReportsFormatted;
        showLayerReports(appName, mapName, sessionId, lName, lDesc, lReports, fIds, lReportsFormatted);
    }
}
function onZoomLayer(grid, record) {
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var args = '{"a":"' + appName + '","sessionId":"' + sessionId + '","mapName":"' + mapName + '","layerName":"' + record.data.LayerName + '","featIds":"' + record.data.FeatIds + '"}';
    var featDataJson = calWebService('../mapguide/KaliopaFDOService/Service.asmx/GetFeatures', args);
    var fields = ['FeatId', 'FeatXml'];
    var featData = new Ext.data.Store({
        data: featDataJson,
        reader: new Ext.data.JsonReader({
            idProperty: 'Id',
            root: 'd.rows',
            totalProperty: 'd.totalRows',
            fields: fields
        })
    });
    featData.each(function (rec) {
        mf.SetSelectionXML(rec.data.FeatXml);
        mf.ExecuteMapAction(10);
    });
}
function onSelectLayer(grid, record) {
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var args = '{"a":"' + appName + '","sessionId":"' + sessionId + '","mapName":"' + mapName + '","layerName":"' + record.data.LayerName + '","featIds":"' + record.data.FeatIds + '"}';
    var featDataJson = calWebService('../mapguide/KaliopaFDOService/Service.asmx/GetFeatures', args);
    var fields = ['FeatId', 'FeatXml'];
    var featData = new Ext.data.Store({
        data: featDataJson,
        reader: new Ext.data.JsonReader({
            idProperty: 'Id',
            root: 'd.rows',
            totalProperty: 'd.totalRows',
            fields: fields
        })
    });
    featData.each(function (rec) {
        mf.SetSelectionXML(rec.data.FeatXml);
    });
}

function zoomToSelected(layer, featId) {
    var mf = mainframe.viewerFrame.mapFrame;
    var sessionId = mf.GetSessionId();
    var mapName = mf.GetMapName();
    var args = '{"a":"' + appName + '","sessionId":"' + sessionId + '","mapName":"' + mapName + '","layerName":"' + layer + '","featIds":"' + featId + '"}';
    var featDataJson = calWebService('../mapguide/KaliopaFDOService/Service.asmx/GetFeatures', args);
    var fields = ['FeatId', 'FeatXml'];
    var featData = new Ext.data.Store({
        data: featDataJson,
        reader: new Ext.data.JsonReader({
            idProperty: 'Id',
            root: 'd.rows',
            totalProperty: 'd.totalRows',
            fields: fields
        })
    });
    featData.each(function(record) {
        mf.SetSelectionXML(record.data.FeatXml);
        mf.ExecuteMapAction(10);
    });
}

function getStoreJson(grid) {
    var da = [];
    var cm = grid.getColumnModel();
    var store = grid.store;
    for (var i = 0, it = store.data.items, l = it.length; i < l; i++) {
        r = it[i].data;
        var row = {};
        for (var j = 0; j < cm.getColumnCount(); j++) {
            if (!cm.isHidden(j)) {
                var cellValue = r[cm.getDataIndex(j)];
                var colHeader = cm.getColumnHeader(j);
                colHeader = colHeader.replace("<b>", "");
                colHeader = colHeader.replace("</b>", "");
                row[colHeader] = cellValue;
            }
        }
        da.push(Ext.encode(row));
    }
    var data = '[' + da.join(',') + ']';
    return data;
}