// Add the default callBack-handler:
Widget.addCallBack("SuperGrid", function(params) {
	
});

/**
 * The SuperGrid static class.
 * 
 * @version 2010-11-30
 * @author <a href="mailto:r.tennapel@griponservice.nl?SUBJECT=SuperGrid script.js">R. ten Napel, ing.</a>
 **/
function SuperGrid() {}

// SuperGrid vars:
SuperGrid.selectedColumn = null;
SuperGrid.pressedKey = null;
SuperGrid.grids = [];

/**
 * Refresh the grid with the given ID.
 * 
 * @param id				The grid ID.
 * @param url				The URL to request.
 **/
SuperGrid.refresh = function(id, url) {
	// Hide the grid, show the loader:
	$(id).hide();
	$(id + "_loader").show();
	
	// Make the request:
	$(id).request(url, function() {
			$(id + "_loader").hide();
			$(id).show();
		});
};

/**
 * Select a column (filter) in the grid.
 * 
 * @param column			The column element that is selected.
 **/
SuperGrid.selectColumn = function(column) {
	SuperGrid.selectedColumn = column;
};

/**
 * Toggle a row in the given grid.
 * 
 * @param id				The grid ID to select the row from.
 * @param url				The Ajaxgrid URL.
 * @param row				The row to toggle.
 **/
SuperGrid.toggleRow = function(id, url, row) {
	// Select the row with an Ajax-call:
	var tempDiv = document.createElement("DIV");
	tempDiv.id = id + "_temp";
	document.body.appendChild(tempDiv);
	SuperGrid.refresh(tempDiv.id, url + "?grid=" + id + "&row=" + row);
};

/**
 * Place the given operand in the currently selected column (filter).
 * 
 * @param operand			The operand to place.
 **/
SuperGrid.placeOperand = function(operand) {
	if (SuperGrid.selectedColumn != null) {
		SuperGrid.selectedColumn.value += operand;
		SuperGrid.selectedColumn.focus();
	}
};

/**
 * Set a particular filter.
 * 
 * @param id				The grid ID.
 * @param column			The column to set.
 * @param filter			The column filter to set.
 **/
SuperGrid.setFilter = function(id, column, filter) {
	//Debugger.write("ID: " + id + ", COL: " + column + ", FILTER: " + filter);
	
	// Retrieve the grid index:
	for (var i = 0; i < SuperGrid.grids.length; i++) {
		if (SuperGrid.grids[i].id == id) {
			break;
		}
	}
	
	// Set index to -1 when grid ID was not found:
	i = (i >= SuperGrid.grids.length) ? -1 : i;
	
	// If not yet exists, add the grid column and filter:
	if (i == -1) {
		SuperGrid.grids.add({ "id": id, "columns": [ { "column": column, "filter": filter } ] });
		
		i = SuperGrid.grids.length;
	// Else change the filter:
	} else {
		// Retrieve the column index:
		for (var c = 0; c < SuperGrid.grids[i].columns.length; c++) {
			// If the right column was found, change the filter:
			if (SuperGrid.grids[i].columns[c].column == column) {
				SuperGrid.grids[i].columns[c].filter = filter;
				
				return;
			}
		}
		
		// Add the column & filter:
		SuperGrid.grids[i].columns.add({ "column": column, "filter": filter });
	}
};

/**
 * Apply all the set filters of the given grid.
 * 
 * @param id				The grid ID.
 * @param url				The URL to the ajaxgrid.
 **/
SuperGrid.applyFilters = function(id, url) {
	// Extend the URL:
	url += "?grid=" + id + "&filters=";
	
	// Retrieve the grid index:
	for (var i = 0; i < SuperGrid.grids.length; i++) {
		if (SuperGrid.grids[i].id == id) {
			break;
		}
	}
	
	// Return if the grid ID was not found:
	if (i >= SuperGrid.grids.length) {
		return;
	}
	
	// Create (URL-encoded) JSON-text of all the filters (and URL-encode all filters):
	var grid = SuperGrid.grids[i];
	var columns = [];
	for (var i = 0; i < grid.columns.length; i++) {
		columns.add({ "column": grid.columns[i].column, "filter": grid.columns[i].filter.escape() });
	}
	var json = JSON.stringify(columns).escape();
	
	// Apply & refresh filters:
	SuperGrid.refresh(id, url + json);
};

/**
 * Remove all filters set on a particular grid.
 * 
 * @param id				The grid ID.
 **/
SuperGrid.clearFilters = function(id) {
	// Retrieve the grid index:
	for (var i = 0; i < SuperGrid.grids.length; i++) {
		if (SuperGrid.grids[i].id == id) {
			break;
		}
	}
	
	// Return if the grid ID was not found:
	if (i >= SuperGrid.grids.length) {
		return;
	}
	
	SuperGrid.grids.removeByIndex(i);
};

/**
 * Update the given element width a dropdown list of distinct values.
 * 
 * @param id				The grid ID.
 * @param url				The Ajaxgrid URL.
 * @param e					The element to update.
 * @param column			The column key to retrieve the distinct values for.
 * @param selected			The selected value (to show in the select-box).
 **/
SuperGrid.parseDistinctValues = function(id, url, e, column, selected) {
	$(e).setBColor("#ffdddd");
	
	// Call the ajaxgrid to retrieve all distinct values:
	new Ajax(null, url + "?grid=" + id + "&distinctColumn=" + column, null, null, function(response) {
		// Convert the JSON-response to an array / object:
		var values = JSON.parse(response);
		
		// Clear all select options:
		for (var i = e.options.length; i >= 0; i--) {
			e.options[i] = null;
		}
		
		// Set all new select options (first one is empty):
		e.selectedIndex = 0;
		e.options[0] = new Option("", "");
		for (var i = 0; i < values.length; i++) {
			e.options[i + 1] = new Option(values[i], values[i]);
			
			// Set the selected index when option == selected:
			if (values[i] == selected) {
				e.selectedIndex = i + 1;
			}
		}
		
		// Enable the selection:
		e.disabled = false;
		
		// Set the border style to green:
		$(e).setBColor("#ddffdd");
	}).request();
};

/**
 * Refresh the grid with the given skin.
 * 
 * @param id				The grid ID to refresh.
 * @param url				The Ajaxgrid URL.
 * @param graphicsPath		The path to the SuperGrid graphics.
 * @param skin				The skin to set for the grid.
 **/
SuperGrid.setSkin = function(id, url, graphicsPath, skin) {
	// Update the search bar background image, loading and logo:
	$(id).$().parentNode.parentNode.children[0].children[0].src = graphicsPath + "/Skins/" + skin + "/small_logo.png";
	$(id + "_loader").$().children[0].src = graphicsPath + "/Skins/" + skin + "/logo.png";
	
	// Refresh the grid:
	SuperGrid.refresh(id, url + "?grid=" + id + "&skin=" + skin);
};

/**
 * This function checks if a CTRL-click event was done on a grid row.
 * 
 * @param element			The element (row) that is clicked.
 * @param id				The grid ID.
 * @param url				The Ajaxgrid URL.
 * @param row				The row to toggle.
 * 
 * @return					If it was a normal click or not (like CTRL-click).
 **/
SuperGrid.clickRow = function(element, id, url, row) {
	// Check if the CTRL-key is pressed:
	if (SuperGrid.pressedKey == 17) {
		$(element).toggleClass("selected");
		SuperGrid.toggleRow(id, url, row);
		
		return false;
	}
	
	return true;
};

/**
 * Handle row data according to the given action.
 * 
 * @param id				The grid ID.
 * @param url				The Ajaxgrid URL.
 * @param action			The action to perform (add, copy, (un)delete, etc.).
 * @param row				The row index.
 **/
SuperGrid.handleRowData = function(id, url, action, row) {
	// Ensure action is set:
	if (action == null) {
		Debugger.write("Handling row data is not possible when no action is set!");
		
		return;
	}
	
	// Refresh the grid:
	var row = (row != null) ? row : "";
	SuperGrid.refresh(id, url + "?grid=" + id + "&handleRowData=" + action + "," + row);
};

//Store the SuperGrid static JS class:
Widget.addClass("SuperGrid", SuperGrid);

// Store the pressed key in the SuperGrid:
$(document).on("keydown", function(e) {
	var keyCode = (window.event) ? window.event.keyCode : e.which;
	
	SuperGrid.pressedKey = keyCode;
}).on("keyup", function(e) {
	var keyCode = (window.event) ? window.event.keyCode : e.which;
	
	SuperGrid.pressedKey = null;
});
