
/* Popula a grid com os campos conforme conteudo de opts.fieldsgrid*/
function populaGrid(grid,opts) {
	opts.callback = function(data) {
		grid.clearAll(false);
		grid.loadXMLString(data);
	};
	invokeMetodo(opts);
}

/* Instancia a grid e carrega as definições das colunas via xml */
function getGrid(opts) {
	opts = $.extend({qtdepag: 5}, opts || {}  );
	var grid = null;
	if (opts.windows) {
		var w1 = getWindows(opts);
		grid = w1.attachGrid();
	} else {
		grid = new dhtmlXGridObject(opts.divgrid);
		if(opts.qtderegpagina!='' && opts.qtderegpagina!=0 && opts.divpaggrid!='')
		{
			grid.enablePaging(true,opts.qtderegpagina,opts.qtdepag,opts.divpaggrid,true);
		}
		grid.setPagingSkin(opts.pagingskin);
		grid.attachEvent("onBeforePageChanged", function() {
			if (opts.filter!="") {
				opts.params.filter = getFil(this);
			}
			this.setXMLAutoLoading(getUrl(opts) + "&" + getQueryString(opts.params));
			if (!this.getRowsNum())	return false;
			return true;
		});
	}

	grid.setImagePath("http://www.sindijusms.org.br/admin/components/dhtmlxGrid/codebase/imgs/");
	grid.setSkin(opts.skin);
	
	if (opts.filter!="") {
		grid.attachEvent("onFilterStart", function(cols, vals) {
			opts.params.filter = getFil(this);
			this.clearAll(false);
			this.loadXML(getUrl(opts) + "&" + getQueryString(opts.params));
			return false;
		});
	}
	
	grid.attachEvent("onBeforeSorting",function(ind,gridObj,direct){
		opts.params.orderby = grid.getColumnId(ind);
		opts.params.direct = direct;		
	    this.clearAll(false);
		this.loadXML(getUrl(opts) + "&" + getQueryString(opts.params));
	    this.setSortImgState(true,ind,direct);
	    return false;
	});
	
	if(opts.dataProc==true)
	{
		DataProcessor = new dataProcessor("update.php?"+ getQueryString(opts.params));
		//set error handler (handler for action with type "error")
		DataProcessor.defineAction("error",myErrorHandler);
		//use column IDs instead of column indexes naming request parameters
		DataProcessor.enableDataNames(true);
		//specify transaction method - POST or GET (default is GET)
		DataProcessor.setTransactionMode("GET");
		//initialize data processor for the grid object (in our case - mygrid)	
		DataProcessor.init(grid);	
	}
	
	/*grid.attachEvent("onBeforeRowDeleted",function(rowId) {
		if (grid.getUserData(rowId,"!nativeeditor_status")=="true_deleted") return true;
		if (!confirm("Are you sure you want to delete data?")) {
			window.setTimeout(function(){
				DataProcessor.setUpdated(rowId,false);
				grid.setRowTextStyle(rowId,"text-decoration : none;");
				grid.clearSelection();
			},1);
			return false;
		}
		return true;		
	})*/
	
	if (opts.filter!="") {
		grid.attachHeader(opts.filter);
	}
	grid.loadXML(opts.xmlpath);
	return grid;
}

 //Example of error handler. It gets <action> tag object as incomming argument.
function myErrorHandler(obj){
    alert("Error occured.\n"+obj.firstChild.nodeValue);
    DataProcessor.stopOnError = true;
    return false;
}

/* Invoca o metodo no servidor */
function invokeMetodo(opts){
	$.get(getUrl(opts),getQueryString(opts.params),opts.callback,opts.tipo);  // Invoca método e retorna json na funcao de callback
}

function getUrl(opts){
	return opts.logic;
}

function getQueryString(arr){
	return $.param(arr);
}

/* Restorna uma string a partir de um objeto json */
function getStrJSON(data) {
	var strjson;
	strjson = "{";
	jQuery.each(data, function(i, val) {
		strjson += "'" + i + "':'" + val + "',";
	});
	strjson += "}";
	return strjson;
}

/* Retorna as colunas com filtros da gride */
function getFilters(grid, cols, vals) {
	//alert(grid.fldSort[1]);
	var filter = "";
	for ( var i = 0; i < cols.length; i++) {
		if (vals[i] != "") {
			filter += grid.fldSort[i] + "-" + grid.getColumnId(cols[i]) + ">" + vals[i] + ":";
		}
	}
	return filter;
}

function getFil(grid) {
	var a = [];
	var b = [];
	for ( var i = 0; i < grid.filters.length; i++) {
		var ind = grid._m_order ? this._m_order[grid.filters[i][1]]	: grid.filters[i][1];		
		b.push(ind);
		var val = grid.filters[i][0]._filter ? v.filters[i][0]._filter(): grid.filters[i][0].value;
		var vals;
		if (typeof val != "function" && (vals = grid.combos[ind])) {
			ind = vals.values._dhx_find(val);
			val = (ind == -1) ? val : vals.keys[ind];
		}
		a.push(val);
	}
	return getFilters(grid, b, a);
}
