<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_tree.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");

$idProject = $_POST['id_project'];
$tabId = $_POST['uniqueTabId'];
$projName = $_POST['projName'];
$tableName = $projName;
$tableLimits = $projName.'___quotaLimits';
$tableCalc = $projName.'___quotaCalc';


?>
function change(val) {
        if (val > 0) {
            return '<span style=\"color:green;">' + val + '</span>';
        } else if (val < 0) {
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    }

    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
    function pctChange(val) {
    if(val)
    	val = parseFloat(val).toFixed(1);
        if (val > 0) {
            return '<span style="color:green;">' + val + '%</span>';
        } else if (val < 0) {
            return '<span style="color:red;">' + val + '%</span>';
        }
        return val;
    }
    function greyChange(val) {
    	 if(val){
    	val = parseFloat(val).toFixed(1);
            return '<span style="color:gray;">' + val + '%</span>';
            }

    }

//Marko 16.4.2015
    function createSorterButton(config) {
        config = config || {};


        Ext.applyIf(config, {
            listeners: {
                click: function(button, e) {
                	var grid = button.findParentByType('editorgrid');
                    changeSortDirection(button, true, config.store, grid);
                }
            },
            iconCls: 'sort-' + config.sortData.direction.toLowerCase(),
            reorderable: true
        });

        return new Ext.Button(config);
    };
    function changeSortDirection(button, changeDirection, store, grid) {
        var sortData = button.sortData,
            iconCls  = button.iconCls;

        if (sortData != undefined) {
            if (changeDirection !== false) {
                button.sortData.direction = button.sortData.direction.toggle("ASC", "DESC");
                button.setIconClass(iconCls.toggle("sort-asc", "sort-desc"));
            }

            store.clearFilter();
            doSort(store, grid);
        }
    };
    function doSort(store, grid) {
    	store.clearFilter();
    	var params = store.baseParams;

    	params.customSort = JSON.stringify(getSorters(grid));
        store.load(params);
        delete store.baseParams.customSort;
    };
    function getSorters(grid) {
        var sorters = [];

        Ext.each(grid.getTopToolbar().findByType('button'), function(button) {
        	if(typeof button.sortData != 'undefined')
	            sorters.push(button.sortData);

        }, this);

        return sorters;
    }
<?php
function addFinalColumns($grid)
{
			$grid->addColumn('q_value','Needed<br>(N)');
			$grid->addColumn('q_val_percent','Needed<br>(col %)')->renderer("function(val){ if(val) {val = parseFloat(val).toFixed(1); return val+'%'}}");

			$grid->addColumn('q_done','Done<br>(N)')->renderer('function(val){ return \'<span style="color:gray;">\' + val + \'</span>\'}');
			$grid->addColumn('q_done_total','Done<br>(total %)')->renderer('greyChange');
			$grid->addColumn('q_done_row','Done<br>(row %)')->renderer("greyChange");
			$grid->addColumn('q_done_percent','Done<br>(col %)')->renderer("greyChange");

			$grid->addColumn('q_todo','To do')->renderer("change");
			$grid->addColumn('q_todo_total','To do<br>(total %)')->renderer('pctChange');
			$grid->addColumn('q_todo_row','To do<br>(row %)')->renderer("pctChange");
			$grid->addColumn('q_todo_percent','To do<br>(col %)')->renderer("pctChange");

}
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

$defaultLayer = $db->get('_Projects',$idProject,'id_select_layer');

$sql = "SELECT * FROM quota_layer WHERE id_project = $idProject ORDER BY layer,zap_st";
$resLayers = $db->SQLexecute($sql);
$curLayerId = 0;
$allGrids = array();

?>
	var menu = new Ext.menu.Menu();
	/*menu.add(new Ext.menu.CheckItem({
	text:'Select all'
	,hideOnClick:false //our menu won't close on click, so that we can check multiple
	,handler:function(item) {

		if(item !== i && i.setChecked && !i.disabled) {
		i.setChecked(checked);
		var chStr = 'checked['+i.qType+']';
		if(checked)
			{ //we add bgc classes and filter string to base params (so that we can dynamicly check newly loaded nodes)

				t.getLoader().baseParams[chStr] = true;
			}
			else
			{

				t.getLoader().baseParams[chStr] = false;
			}

		}


	}
	}),'-');*/

	<?php

/*	coppied from basestatistics
 * $db->ChangeDatabase(DB_WARPIT_WEBCATI );
	//we fetch all the questions in the database to create a menu item for it!
	$qRS = $db->SQLexecute("SELECT name,id FROM _QuestionTypes" );
	while ($qRow = $db->fetchArray($qRS)  )
	{
		$type = $qRow[1];
		$qTmp = Question::createQuestion( $qRow[1]  );
		//for each question we add a checkItem in the menu

	}
	*/

while ($rowLayer = $db->fetchAssoc($resLayers))
{
	if($rowLayer['layer'] != $curLayerId)
	{
		if($curLayerId)//finish the grid
		{

			$notDef = $curLayerId != $defaultLayer;
			if(false && $notDef)
					$grid->addConfig('hidden','true');

			addFinalColumns($grid);
			$grid->selectSQL = "SELECT a.*,(SELECT count(*) FROM $tableCalc b WHERE ".implode(' AND ',$countWhere). " ) AS q_done FROM $tableLimits a";
			$grid->addConfig('hidden','true');

			/*$grid->addExportButton();
			$grid->addTbarItem("{
				text:'Reset Quotas',
				handler: function(){
					Ext.Msg.confirm('Reset Quotas', 'Are you sure you wish to reset the quotas?', function(btn){
						if(btn == 'yes'){
							Ext.Ajax.request({
								url: 'webcati/_ajax/quotas/ajax.quotaStat.php',
								params:{
									action: 'resetQuotas',
									RMtable: '".$projName."___quotaCalc'
								},
								success: function(resp, opt){
									var res = Ext.decode(resp.responseText);
									if(res.success){
										Ext.getCmp('".$grid->getName()."').getStore().reload();
									}
								}
							});
						}
					});
				}
			}");
			$grid->addTbarItem("'-'");
			$grid->addTbarItem("createSorterButton({
				text: '".$rowLayer['q_name']."',
				store: ".$grid->getStoreName().",
				sortData:{
					field: '".$colName."',
					direction: 'DESC'
				}
			})");*/
			$reorderable = "new Ext.ux.ToolbarReorderer()";
			$droppable = "new Ext.ux.ToolbarDroppable({
		        /**
		         * Creates the new toolbar item from the drop event
		         */
		        createItem: function(data) {
		            var column = this.getColumnFromDragDrop(data);

		            return createSorterButton({
		                text    : column.header,
		                store: ".$grid->getStoreName().",
		                sortData: {
		                    field: column.dataIndex,
		                    direction: 'ASC'
		                }
		            });
		        },

		        /**
		         * Custom canDrop implementation which returns true if a column can be added to the toolbar
		         * @param {Object} data Arbitrary data from the drag source
		         * @return {Boolean} True if the drop is allowed
		         */
		        canDrop: function(dragSource, event, data) {
		        	console.log(dragSource);
		            var sorters = getSorters(),
		                column  = this.getColumnFromDragDrop(data);

		            for (var i=0; i < sorters.length; i++) {
		                if (sorters[i].field == column.dataIndex) return false;
		            }

		            return true;
		        },

		        afterLayout: doSort,

		        /**
		         * Helper function used to find the column that was dragged
		         * @param {Object} data Arbitrary data from
		         */
		        getColumnFromDragDrop: function(data) {
		            var index    = data.header.cellIndex,
		                colModel = grid.colModel,
		                column   = colModel.getColumnById(colModel.getColumnId(index));

		            return column;
		        }
		    })";
			$menus = array();
			$menus[] = $grid->addExportButton("Export", "RMicon_export", array(), false, true);
			$menus[] = "{
				text:'Reset Quotas',
				handler: function(){
					Ext.Msg.confirm('Reset Quotas', 'Are you sure you wish to reset the quotas?', function(btn){
						if(btn == 'yes'){
							Ext.Ajax.request({
								url: 'webcati/_ajax/quotas/ajax.quotaStat.php',
								params:{
									action: 'resetQuotas',
									RMtable: '".$projName."___quotaCalc'
								},
								success: function(resp, opt){
									var res = Ext.decode(resp.responseText);
									if(res.success){
										Ext.getCmp('".$grid->getName()."').getStore().reload();
									}
								}
							});
						}
					});
				}
			}";
			$menus[] = "'-'";
			foreach ($menuCols as $key => $value) {
				$menus[] = "createSorterButton({
					text: '".$value."',
					store: ".$grid->getStoreName().",
					sortData:{
						field: '".$menuColsDataIndex[$key]."',
						direction: 'DESC'
					}
				})";
			}

			$toolbar = "new Ext.Toolbar({
		        items  : [".implode(",", $menus)."],
		        plugins: [$reorderable, $droppable],
		        listeners: {
		            scope    : this,
		            reordered: function(button) {
		            	var grid = button.findParentByType('editorgrid');
		                changeSortDirection(button, false, ".$grid->getStoreName().", grid);
		            }
		        }
		    })";

			$grid->addConfig("tbar", $toolbar);
			$grid->addConfig("listeners", "{
				scope: this,
				render: function(){
					var dragProxy = grid.getView().columnDrag,
	                    ddGroup   = dragProxy.ddGroup;

	                droppable.addDDGroup(ddGroup);
	            }
			}");
			echo $grid->createGrid();
			$allGrids[] = $grid->getName();

			//we add this menu to activate/deactivete the current grid!

				echo "menu.add(new Ext.menu.CheckItem( {text:'".implode(' -- ',$menuCols)."' ,hideOnClick:false,checked: ".( $notDef ? 'false' : 'true' ).",
				handler:function(item){
					var checked = ! item.checked;
					if(checked)
					{	//if item is checked we add a bgc color and set the filter to true to check newly loaded nodes
						$grid.show();
					}
					else
					{
						$grid.hide();
					}


					$grid.ownerCt.doLayout();

				}
			} ));";
			$menuCols = array();
			$menuColsDataIndex = array();


		}
		$grid = new MakeGrid();
		$grid->setMainTable($projName.'___quotaLimits',DB_WARPIT_WEBCATI_BASE);
		$grid->addConfig('flex',1);
		$grid->setSortable(false);
		$grid->baseParams = "id_layer : " .$rowLayer['layer'];
		$grid->reqUrl = "webcati/_ajax/quotas/ajax.quotaStat.php";
		$grid->setPaging(1000);

		//array that holds the where clouse for inner select count
		$countWhere = array();

		$curLayerId = $rowLayer['layer'];





	}
	if ($rowLayer['q_name'] == "user") $colName = 'QT_user_id';
	elseif($rowLayer['source'] == 2 )
		$colName = 'QT_'.$rowLayer['q_name'];
	else
		$colName = 'TP_'.$rowLayer['q_name'];

	$countWhere[] = "a.$colName = b.$colName";

	$menuCols[] = $rowLayer['q_name'];
	$menuColsDataIndex[] = $colName;

	$grid->addColumn($colName,$rowLayer['q_name'])->renderer("function(val,md,rec){return '<b>'+val+'</b>'+' '+rec.data.{$colName}_lab}");
	$grid->addColumn($colName.'_lab');


}
if($curLayerId)//finish the grid
		{
			addFinalColumns($grid);
			$grid->selectSQL = "SELECT a.*,(SELECT count(*) FROM $tableCalc b WHERE ".implode(' AND ',$countWhere). " ) AS q_done FROM $tableLimits a";

			$notDef = $curLayerId != $defaultLayer;
			if($notDef)
					$grid->addConfig('hidden','true');

/*
			;
			$grid->addTbarItem("{
				text:'Reset Quotas',
				handler: function(){
					Ext.Msg.confirm('Reset Quotas', 'Are you sure you wish to reset the quotas?', function(btn){
						if(btn == 'yes'){
							Ext.Ajax.request({
								url: 'webcati/_ajax/quotas/ajax.quotaStat.php',
								params:{
									action: 'resetQuotas',
									RMtable: '".$projName."___quotaCalc'
								},
								success: function(resp, opt){
									var res = Ext.decode(resp.responseText);
									if(res.success){
										Ext.getCmp('".$grid->getName()."').getStore().reload();
									}
								}
							});
						}
					});
				}
			}");
			$grid->addTbarItem("'-'");
			foreach ($menuCols as $key => $value) {
				$grid->addTbarItem("createSorterButton({
					text: '".$value."',
					store: ".$grid->getStoreName().",
					sortData:{
						field: '".$menuColsDataIndex[$key]."',
						direction: 'DESC'
					}
				})");
			}*/
			$reorderable = "new Ext.ux.ToolbarReorderer()";
			$droppable = "new Ext.ux.ToolbarDroppable({
		        /**
		         * Creates the new toolbar item from the drop event
		         */
		        createItem: function(data) {
		            var column = this.getColumnFromDragDrop(data);

		            return createSorterButton({
		                text    : column.header,
		                store: ".$grid->getStoreName().",
		                sortData: {
		                    field: column.dataIndex,
		                    direction: 'ASC'
		                }
		            });
		        },

		        /**
		         * Custom canDrop implementation which returns true if a column can be added to the toolbar
		         * @param {Object} data Arbitrary data from the drag source
		         * @return {Boolean} True if the drop is allowed
		         */
		        canDrop: function(dragSource, event, data) {
		        	console.log(dragSource);
		            var sorters = getSorters(),
		                column  = this.getColumnFromDragDrop(data);

		            for (var i=0; i < sorters.length; i++) {
		                if (sorters[i].field == column.dataIndex) return false;
		            }

		            return true;
		        },

		        afterLayout: doSort,

		        /**
		         * Helper function used to find the column that was dragged
		         * @param {Object} data Arbitrary data from
		         */
		        getColumnFromDragDrop: function(data) {
		            var index    = data.header.cellIndex,
		                colModel = grid.colModel,
		                column   = colModel.getColumnById(colModel.getColumnId(index));

		            return column;
		        }
		    })";
			$menus = array();
			$menus[] = $grid->addExportButton("Export", "RMicon_export", array(), false, true);
			$menus[] = "{
				text:'Reset Quotas',
				handler: function(){
					Ext.Msg.confirm('Reset Quotas', 'Are you sure you wish to reset the quotas?', function(btn){
						if(btn == 'yes'){
							Ext.Ajax.request({
								url: 'webcati/_ajax/quotas/ajax.quotaStat.php',
								params:{
									action: 'resetQuotas',
									RMtable: '".$projName."___quotaCalc'
								},
								success: function(resp, opt){
									var res = Ext.decode(resp.responseText);
									if(res.success){
										Ext.getCmp('".$grid->getName()."').getStore().reload();
									}
								}
							});
						}
					});
				}
			}";
			$menus[] = "'-'";
			foreach ($menuCols as $key => $value) {
				$menus[] = "createSorterButton({
					text: '".$value."',
					store: ".$grid->getStoreName().",
					sortData:{
						field: '".$menuColsDataIndex[$key]."',
						direction: 'DESC'
					}
				})";
			}

			$toolbar = "new Ext.Toolbar({
		        items  : [".implode(",", $menus)."],
		        plugins: [$reorderable, $droppable],
		        listeners: {
		            scope    : this,
		            reordered: function(button) {
		            	var grid = button.findParentByType('editorgrid');
		                changeSortDirection(button, false, ".$grid->getStoreName().", grid);
		            }
		        }
		    })";
			$grid->addConfig("tbar", $toolbar);
			$grid->addConfig("listeners", "{
				scope: this,
				render: function(){
					var dragProxy = grid.getView().columnDrag,
	                    ddGroup   = dragProxy.ddGroup;

	                droppable.addDDGroup(ddGroup);
	            }
			}");



			echo $grid->createGrid();


			$allGrids[] = $grid->getName();



				echo "menu.add(new Ext.menu.CheckItem( {text:'".implode(' -- ',$menuCols)."' ,hideOnClick:false,checked: ".( $notDef ? 'false' : 'true' ).",
				handler:function(item){
					var checked = ! item.checked;
					if(checked)
					{	//if item is checked we add a bgc color and set the filter to true to check newly loaded nodes
						$grid.show();
					}
					else
					{
						$grid.hide();
					}


					$grid.ownerCt.doLayout();

				}
			} ));

			";

		}
echo "mainTabPanel.add({
		id:'$tabId',
		title:'quota Stat - $projName',
		tbar: [{ text: 'Layers',menu:menu }],
		closable:true,
		layout:'vbox',
		items: [".implode(',',$allGrids)."],
		listeners:{
			afterrender: function(){

			}
		}
}).show();";

// iz tbar sem vzel ven tole:" , { text: 'Print', handler: function() { window.open('export_quota.php?id_project=".$idProject."')} }"
// Borut 26.8.2012 - 16:35
?>
