//Deve voltar um nível senão apresenta problemas com setar tamanho de coluna
document.write('<link href="../grid/styles/xp/grid.css" rel="stylesheet" type="text/css"></link>');
document.write("<script type=\"text/javascript\" language=\"JavaScript1.2\" src=\"grid/lib/grid.js\"></script>");

var EDIT   = 0;
var INSERT = 1;
var UNKNOW = -1;

function HTMLGrid(sys, formID, code, posX, posY, width, height, formCode) {
  this.create(sys, formID, code, posX, posY, width, height, '', '');
  this.type             = 1;
  this.callForm         = true;
  this.formCode         = formCode;
  this.able             = true;
  this.gridini          = 0;
  this.formWidth        = this.width;
  this.formHeight       = this.height;
  this.tabable          = true;
  this.hasdata          = false;
  this.editRow          = -1;
  this.currentRow       = -1;
  this.editComponents   = new Array();
  this.report           = false;
  this.grid             = new Active.Controls.Grid;
  this.currentSelection = -1;
  this.rowHeight        = 20; 
  this.lineHeight		    = 15;
  this.headerWidth      = 28;
  this.fontSize         = 8; 
  this.allowsOrder      = false;
  this.autoRowSize      = true;
  this.buttonHeight     = 12;
  this.buttonWidth      = 14;
}

HTMLGrid.inherits(HTMLElementBase);

HTMLGrid.prototype.loadScripts = function() {
	this.My=[];
	this.My.Templates=[];

	this.My.Templates.Input = Active.Templates.Text.subclass();

	this.My.Templates.Input.create = function() {
	  var obj = this.prototype;

	  var template;

	  obj.setEvent("ondblclick", function() { this.parent.dblClickEditableRow(this); } );
	  obj.setEvent("onclick",    function() { this.parent.clickEditableRow(this); } );
	};

	this.My.Templates.Input.create();
}

HTMLGrid.prototype.name = 'HTMLGrid';
HTMLGrid.prototype.zindex = 99999;
HTMLGrid.prototype.tagName = 'grid';

HTMLGrid.prototype.setGridPageEnd = function(v) {
  this.gridend = v;
  if (this.paging)
    this.paging.setGoto(v);	
}

HTMLGrid.prototype.setGridPageIni = function(v) {
  this.gridini = v;	
}

HTMLGrid.prototype.setEnabled = function(v) {
  this.enabled = v;
  if (this.nav) this.nav.setEnabled(v);
}

HTMLGrid.prototype.isReport = function() {
  return this.report;
}

HTMLGrid.prototype.setHint = function(hint) {
  this.callMethod(HTMLElementBase, "setHint", [hint]);
	
  if (this.gridDiv) {
    this.gridDiv.alt = hint;
    this.gridDiv.title = hint;
  }
}

HTMLGrid.prototype.setReadOnly = function(v) {
  this.readOnly = v;
  if (this.nav) this.nav.setReadOnly(v);
}

HTMLGrid.prototype.setMainImages = function(imgInclude, imgEdit, imgDelete, imgRefresh) {
  this.imgInclude = imgInclude;
  this.imgEdit    = imgEdit;
  this.imgDelete  = imgDelete;
  this.imgRefresh = imgRefresh;
}

HTMLGrid.prototype.setEditImages = function(imgPost, imgCancel) {
  this.imgPost   = imgPost;
  this.imgCancel = imgCancel;
}

HTMLGrid.prototype.setIncludeImages = function(imgPost, imgCancel) {
  this.imgPost   = imgPost;
  this.imgCancel = imgCancel;
}

HTMLGrid.prototype.setColumns = function(cols, width, components) {
  this.columns      = cols;
  this.columnsWidth = width;
  this.components   = components;
}

HTMLGrid.prototype.setData = function(data) {
  if (this.editing) this.completeCancelEdit();
  if (this.inserting) this.completeCancelInclude();
  this.resetColors();
  this.data = data;
}

HTMLGrid.prototype.gridFocus = function() {
  controller.activeElement = this;
  try { this.grid.element().focus(); } catch(e){}
}

HTMLGrid.prototype.refreshData = function(notFocus) {
  var currentScroll = this.scroll.element().scrollTop;
  	
  var row = this.grid.getProperty("selection/index");
  
  this.paging.setGoto(this.gridend);
  this.grid.setRowProperty('count', this.data.length);
  this.grid.setColumnProperty('count', this.columns.length);
  this.grid.refresh();
  if (this.nav) this.nav.normal();
  if (!notFocus) this.gridFocus();

  if (!this.doNotScroll)
    this.timeout(this.scrollTop, 10, [currentScroll]);
  this.doNotScroll = false;  
  if (this.nav) this.nav.setVisible(this.editable && this.parentHasData);
}

HTMLGrid.prototype.selectGridRow = function(i) {
  this.grid.setProperty("selection/index", i) 
}

HTMLGrid.prototype.getRowDiv = function(i, j) {

}

//Retorna o número de linhas do grid
HTMLGrid.prototype.getRowCount = function() {
  return this.data.length;
}

HTMLGrid.prototype.getSelectedRow = function() {

  if (this.template.getRowProperty("index") >= 0)
    return this.data[this.template.getRowProperty("index")];
  else
    throw getLocaleMessage("INFO.GRID_RECORD_SELECT");

}

HTMLGrid.prototype.getSelectedValue = function(colName) {

  var idx = -1;
  for (var i=0;i<this.columns.length;i++) {
    if (this.columns[i] == colName) {
      idx = i;
      break
    }
  }

  if (idx == -1)
    throw getLocaleMessage("INFO.GRID_COLUMN_NOT_FOUND",colName,this.id);

  if (this.template.getRowProperty("index") >= 0)
    return this.data[this.template.getRowProperty("index")][idx];
  else
    throw getLocaleMessage("INFO.GRID_RECORD_SELECT");

}


HTMLGrid.prototype.setNumericFormat = function(i) {
  if (!this.numericColumns) this.numericColumns = new Array();
  this.numericColumns[i] = true;
}

HTMLGrid.prototype.getColumnCount = function(com) {
  var idx =arrayIndexOf(this.components, com);
  var r = 0;
  for (var i=0;i<this.data.length;i++)
    r = r + parseInt(this.data[i][idx]);
  return r;
}

HTMLGrid.prototype.designComponent = function(doc) {
  if(this.isReport()) {
    this.designComponentReport();
    return "";
  }

  var grid_top = 0;
  this.grid_height = this.height;

  this.nav = new HTMLNavigationGrid(this.sys, this.formCode, 0, 0);
  this.nav.tabindex = this.tabindex;
  this.nav.design(this.context);
  this.nav.parent = this;
  grid_top = 21;
  this.grid_height = this.height - 22;
  if (this.editable) {
    this.nav.setMainImages(this.imgInclude, this.imgEdit, this.imgDelete, this.imgRefresh, -1);
    this.nav.setIncludeImages(this.imgPost, this.imgCancel);
    this.nav.setEditImages(this.imgPost, this.imgCancel);
  } else {
    this.nav.setMainImages(-1, -1, -1, -1, -1);
  }

  this.grid['grid'] = this;
  this.grid['parent'] = this;
  this.grid.setId('grid'+this.code);
  this.grid.setRowProperty('count', this.data.length);
  this.grid.setColumnProperty('count', this.columns.length);

  this.template = new this.My.Templates.Input;
  this.grid.setColumnTemplate(this.template);
  this.template.parent = this;

  this.grid.setDataProperty('text', this.getRow);
  this.grid.setColumnProperty('text', this.getColumn);
  
  this.grid.setAction("selectionChanged", function(e) { this.parent.selectionChanged(e); } );
  this.grid.actKeydown = this.grid.getEvent("onkeydown");

  this.grid.setEvent("onkeydown", function (e) {
    var keyCode  = e.keyCode || e.which;
    if ((this.parent.editRow != -1) && this.parent.disableSelectionRowOnEdit) {
      if ((keyCode == 35/*END*/) || (keyCode == 36/*HOME*/) || (keyCode == 38/*UP*/) || (keyCode == 40/*DOWN*/) || (keyCode == 33/*PAGE UP*/) || (keyCode == 34/*PAGE DOWN*/)) {
        return false;
      }
    }
    var currentLine = this.getProperty("selection/index");
    this.actKeydown(e);
    this.changeLine = false;
    if (currentLine != this.getProperty("selection/index"))
      this.changeLine = true;
    this.parent.gridKeyPress(e);
  });

  this.context.className = 'grid';
  this.context.style.width = (pt(this.context.style.width)+2+(IE?2:0))+'px';
  this.context.style.height = (pt(this.context.style.height)+2+(IE?2:0))+'px';
  this.grid.setEvent("onfocus", function (e){ this.parent.gridDiv.className = 'gridMark' });
  this.grid.setEvent("onblur", function (e){ this.parent.gridDiv.className = 'gridDiv' });

  this.grid.getTemplate("layout").grid = this;
  this.act = this.grid.getTemplate("layout").getAction("adjustSize");
  this.grid.getTemplate("layout").setAction("adjustSize", function(e) { this.grid.act.call(this, e); this.grid.repaintEditElems(e); this.grid.saveSize(this); });

  this.header = new Active.Templates.Header;
  this.header.parent = this;
  this.header.grid = this;

  this.header.setEvent("onmousedown", function(e) { } );
      
  this.defineOrder();
  
  this.grid.setTemplate("top/item", this.header);

  this.grid.getStatusTemplate().grid = this;
  this.grid.getStatusTemplate().setEvent('ondblclick', this.clickEmptyGrid);
  this.grid.setEvent('ondblclick', this.clickEmptyGrid);

  if (navigator.userAgent.match("WebKit")) {

    this.stylesheetList = HTMLGrid.prototype.getAllSheets();
    this.stylesheet = this.stylesheetList[0].sheet;

    if (this.stylesheet == null)
      this.stylesheet = this.stylesheetList[this.stylesheetList.length-1].sheet;

  }	else {
    this.stylesheet = document.styleSheets[document.styleSheets.length-1];
  }

  if (!this.bgColor) { 
    this.bgColor = '#FFFFFF';
  }
  
  // DECORATION
  var fontStyle = "";
  if (this.font) {
    fontStyle += ("font-family: " + this.font + ";");
  }
  if (this.size) {
    fontStyle += ("font-size: " + pt(this.size) + "pt;");
    if (this.autoRowSize) {
      var fontSize = Math.round((4 * pt(this.size)) / 3);
      this.rowHeight = fontSize + 9.3;
      this.headerWidth = this.rowHeight + (this.rowHeight * 0.3);
  	  
      var inc = (this.rowHeight - 28) / 28;
    }   
  }
  if (this.weight) {
    fontStyle += ("font-weight: bold;");
  }
  if (this.italic) {
    fontStyle += ("font-style: italic;");
  }
  if (this.underline) {
    fontStyle += ("text-decoration: underline;");
  } 
  
  if (this.strikeout) {
    fontStyle += ("text-decoration: line-through;");
  }
  if (this.color) {
    fontStyle += ("color: " + this.color + ";");
  }
  if (this.bgColor) {
    fontStyle += ("background-color: " + this.bgColor + ";");
  }

  this.grid.setColumnHeaderHeight(this.rowHeight+'px');
  this.grid.setRowHeaderWidth(this.headerWidth+'px');  
  
  if (this.decorationChanged) {
    this.timeout(
      function() {
        this.stylesheet.addRule('#grid'+this.code+'.active-controls-grid', 'width: '+this.width+'; height: '+this.grid_height+';' + fontStyle);
        this.stylesheet.addRule('#grid'+this.code+' .active-grid-row', 'height: '+this.rowHeight+'px; line-height: '+this.rowHeight+'px;');
        this.stylesheet.addRule('#grid'+this.code+' .active-list-item', 'height: '+this.rowHeight+'px; line-height: '+this.lineHeight+'px;');
        this.stylesheet.addRule('#grid'+this.code+' .active-scroll-data', 'height: '+this.rowHeight+'px; line-height: '+this.rowHeight+'px;');
        this.stylesheet.addRule('#grid'+this.code+' .active-templates-row', 'height: '+this.rowHeight+'px; line-height: '+this.rowHeight+'px;');
        this.stylesheet.addRule('#grid'+this.code+' .active-row-cell', 'height: '+this.rowHeight+'px; line-height: '+this.rowHeight+'px;');
      }, 0);
  }
  
  if (!IE)
    this.timeout(this.ajustSize);
  else
    this.ajustSize();

  this.gridDiv = this.getDiv('WFRGrid'+this.code, 0, grid_top, this.width+(IE?2:0), this.grid_height+(IE?2:0), 3, true);
  this.gridDiv.style.overflow = 'hidden';
  this.gridDiv.innerHTML = this.grid;
  this.context.appendChild(this.gridDiv);
  this.paging = new HTMLPaging(this.sys, this.formID, this.code, this.width-(163), 5, 40, 15);
  this.paging.onnavigate = this.getAction(this.pagingNavigateAction);
  this.paging.design(this.context);
  this.scroll = this.grid.getTemplate("layout").getContent("scrollbars");
  this.paging.enableButtons(false, false, false, false);
  if (this.nav) this.nav.setVisible(this.editable && this.parentHasData);
  this.grid.setEvent("oncontextmenu", "return true");
  this.grid.setEvent("onselectstart", "return true");
  this.gridDiv.className = 'gridDiv';
}

HTMLGrid.prototype.getAllSheets = function() {
  var linkTag;
  if( document.getElementsByTagName ) {
    linkTag = document.getElementsByTagName('link');
  } else if( document.styleSheets && document.all ) {
    linkTag = document.all.tags('LINK');
  } else {
    return [];
  }
  for( var i = 0, rel, sheetsList = []; i < linkTag.length; i++ ) {
    if( linkTag[i].rel ) {
      rel = linkTag[i].rel;
    } else if( linkTag[i].getAttribute ) {
      rel = linkTag[i].getAttribute('rel');
    } else {
      rel = '';
    }
    if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) {
      sheetsList[sheetsList.length] = linkTag[i];
    }
  }
  return sheetsList;
}

HTMLGrid.prototype.onFormLoadAction = function() {
  if (!this.masterDefined) {
  	this.masterDefined = true; 	
    this.defineGridMaster();
  }  
  
  if (this.gridMaster) {
    var gm = $c(this.gridMaster);
    if (gm)
      gm.timeout(gm.selectRow, 0, [0, true]);
  }  
}

HTMLGrid.prototype.markFirst = function() {
  if (this.gridMaster) {
    var gm = $c(this.gridMaster);
    if (gm)
      gm.timeout(gm.selectRow, 0, [0, true]);
  }  
}


HTMLGrid.prototype.defineGridMaster = function() {
  if (this.gridMaster) {
    var gm = $c(this.gridMaster);
    if (gm) {
      gm.addDependentGrid(this.id, this.gridMasterFilter);	
    }
  }
}  

HTMLGrid.prototype.defineOrder = function() {
  this.header.setEvent("onmousedown", function(e) { } );
  this.header.setEvent("ondblclick", function(e) { } );
  this.header.setEvent("onclick", function(e) { } );

  this.header.setEvent(this.allowsOrder?"onclick":"ondblclick",  function(evt) { 
    var shiftKey = false;
    
    if (w3c) {
      if (document.layers) {
        shiftKey = ((evt.modifiers & Event.SHIFT_MASK) > 0);
      } else {
        shiftKey = evt.shiftKey;
      }
    } else {
      shiftKey = evt.shiftKey;
    }    
    
    if (this.grid.allowsOrder) {
      if (shiftKey)
        this.grid.openGridManager();
      else  
        this.grid.orderColumn(); 
    } else {
      if (shiftKey)
        this.grid.orderColumn(); 
      else  
        this.grid.openGridManager();
    }
  });
}

HTMLGrid.prototype.setWidth = function(width) {
  width = parseInt(width);
  this.callMethod(HTMLElementBase, 'setWidth', width);
  this.gridDiv.style.width = (width+(IE?2:0))+'px';
  this.grid.element().style.width = width+'px';
  this.context.style.width = (pt(this.context.style.width)+2+(IE?2:0))+'px';

}

HTMLGrid.prototype.setHeight = function(height) {
  height = parseInt(height);
  this.grid_height = height - (this.height - this.grid_height);
  this.callMethod(HTMLElementBase, 'setHeight', height);
  this.gridDiv.style.height = ((this.nav?height-22:height)+(IE?2:0))+'px';
  this.grid.element().style.height = (this.nav?height-22:height)+'px';
  this.context.style.height = (pt(this.context.style.height)+2+(IE?2:0))+'px';
  this.stylesheet.addRule('#grid' + this.code + '.active-controls-grid', 'height: ' + this.grid_height + ';');
}

HTMLGrid.prototype.designComponentReport = function() {
  var mainDiv = MM_findObj("lay");
  var content;

  if (this.data.length) {

    // Cria o container
    var div = this.getDiv('WFRGrid'+this.code, this.posX, this.posY, this.width+(IE?2:0), this.height+(IE?2:0), 3, true);
    content = "<table width='100%' border='1' cellpadding='3' cellspacing='0' bordercolor='#000000'>";

    // Desenha os títulos
    content += "<tr>";
    for(j = 0; j < this.columns.length; j++) {
      content += "<td align='center'>"+ this.columns[j] +"</td>";
    }
    content += "</tr>";

    // Desenha os dados
    for(i = 0; i < this.data.length; i++) {
      if (this.data[i]) {
        content += "<tr>";
        for(j = 0; j < this.columns.length; j++) {
          content += "<td>" + this.data[i][j] + "</td>";
        }
        content += "</tr>";
      }
    }
    content += "</table>";

    div.innerHTML = content;

    mainDiv.appendChild(div);
  }
}

HTMLGrid.prototype.getGridAction = function(owner, func) {
  return function(e) {
    return func.call(owner);
  }
}

HTMLGrid.prototype.permissionClick = function() {
  this.divHint.style.display = "none";
  interaction(getLocaleMessage("INFO.FORM_PERMISSION_CONFIG"),
  [ getLocaleMessage("LABEL.COMPONENT"), getLocaleMessage("LABEL.COMPONENT_FORM_ASSOCIATION") ],
  [ openComAccess, openFormAccess ],
  [ [this.sys, this.formID, this.code, document.title, 'Grid: '+this.formName],
    [this.sys, this.formCode, this.formName]
  ]
);
}

HTMLGrid.prototype.getCellData = function(i, j) {
  if (i == -1)
    i = this.getSelectedRow();
  return this.data[i][j];
}

HTMLGrid.prototype.setCellData = function(row, col, value) {
  this.data[row][col] = value;
  this.refreshData(false);
  return true;
}

HTMLGrid.prototype.getData = function(row, com) {
  var r = '';	
  var idx = arrayIndexOf(this.components, com);
  if (idx != -1) {
    r = this.data[row][idx];
    if (r == '&nbsp' || r == '&nbsp;' || r == '&&nbsp' || r == '&&nbsp;') {
      r = '';
    }
  }  
  return r;  
}

HTMLGrid.prototype.ajustSize = function() {
  for (var i=0;i<this.columnsWidth.length;i++)
    this.setColumnStyle(i, this.columnsWidth[i], null, null, this.numericColumns?this.numericColumns[i]:false);
}

HTMLGrid.prototype.setColumnStyle = function(idx, width, color, bg, rightAlign) {
  var s = 'width:'+width+'px';
  if (color) s += '; color: '+color;
  if (bg) s += '; background-color: '+bg;
  if (rightAlign) s += '; text-align: right;';
  this.stylesheet.addRule('#grid'+this.code+' .active-column-'+idx, s);

}

HTMLGrid.prototype.setBGColor = function(color) {
  if (color)
    this.stylesheet.addRule('#grid'+this.code+'.active-controls-grid', 'width: '+this.width+'; height: '+this.grid_height+'; background-color: '+color);
}

HTMLGrid.prototype.resetColors = function() {
  if (this.grid && this.columns)
    for (var i=0;i<this.columns.length;i++)
      this.grid.getColumnTemplate(i).colors = null;
}

HTMLGrid.prototype.setCellColor = function(i, j, color) {
  var template = this.grid.getColumnTemplate(j);
  if (!template.colors) template.colors = new Array();
  template.colors[i] = color ;
  template.bgColor = this.bgColor;
  template.parent = this;
  template.setStyle("background-color", getColor);
  template.setEvent("onclick",    function() { this.parent.clickEditableRow(this); } );
  template.setEvent("ondblclick", function() { this.parent.dblClickEditableRow(this); } );
}

HTMLGrid.prototype.setConditionalColor = function(j, condition) {
  var template = this.grid.getColumnTemplate(j);
  template.colors = new Array(this.data.length);
  template.parent = this;
  for (var i=0;i<this.data.length;i++) {
    template.colors[i] = condition;
  }
  template.setStyle("background-color", getColor);
  template.setEvent("onclick",    function() { this.parent.clickEditableRow(this); } );
  template.setEvent("ondblclick", function() { this.parent.dblClickEditableRow(this); } );
}

HTMLGrid.prototype.setRowColor = function(i, color) {
  var template;
  var selectColorRow;
  if (arguments.length > 2) {
    for (var r = 2; r < arguments.length; r++) {
      template = this.grid.getColumnTemplate(arguments[r]);
      if (!template.colorsRow) {
        template.colorsRow = new Array();
      }
      template.colorsRow[i] = color;
      selectColorRow = function() {
        return this.colorsRow[this.getProperty("row/index")];
      }
      template.setStyle("background-color", selectColorRow);
      template.parent = this;
      template.setEvent("onclick",    function() { this.parent.clickEditableRow(this); } );
      template.setEvent("ondblclick", function() { this.parent.dblClickEditableRow(this); } );
    }
  } else {
    template = this.grid.getTemplate("row");
    if (!template.colorsRow) {
      template.colorsRow = new Array();
    }
    template.colorsRow[i] = color;
    selectColorRow = function() {
      return this.colorsRow[this.getProperty("row/index")];
    }
    template.setStyle("background", selectColorRow);
  }
}

HTMLGrid.prototype.resetRowColor = function() {
  var template;
  var selectColorRow = function() {}
  for (var i = 0; i < this.grid.getColumnProperty('count'); i++) {
    template = this.grid.getColumnTemplate(i);
    template.colorsRow = new Array();
    template.setStyle("background-color", selectColorRow);
  }
  template = this.grid.getTemplate("row");
  template.colorsRow = new Array();
  template.setStyle("background-color", selectColorRow);
}

function getColor() {
  var row = this.getProperty("row/index");
  if (this.colors && row < this.colors.length && this.colors[row])
    return this.colors[row].call(this.parent, row);
  else
    return this.bgColor;
}

HTMLGrid.prototype.saveSize = function(e) {
  if (this.components && this.components.length > 0) {
    var selector = "#" + this.grid.getId() + " .active-column-" + this.header.$index;
    var ss = document.styleSheets[document.styleSheets.length-1];
    var w = 0;
    for(i=0; i<ss.rules.length;i++){
      if(ss.rules[i].selectorText == selector){
        w = ss.rules[i].style.width;
      }
    }
    getAndEvalSync('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=setsize&formID='+this.formID+'&comID='+this.code+'&gt=-1&fieldID='+this.components[this.header.$index]+'&size='+pt(w));
  }
}


HTMLGrid.prototype.getRow = function(i, j) {
  return this.grid.data[i][j];
}

HTMLGrid.prototype.getColumn = function(i) {
  if (!isNullable(this.grid.ordered) && this.grid.ordered.index == i) {
    var img = ' <img src=' + skin + 'grid_order_'+(this.grid.ordered.desc?'desc':'asc')+'.gif align=absmiddle>';
    return this.grid.columns[i]+img;
  }
    	
  return this.grid.columns[i];
}

HTMLGrid.prototype.clickEmptyGrid = function(evt) {
  if (!this.grid.editing && !this.grid.inserting && this.grid.data.length == 0) {
    controller.activeElement = this;
    
    if (this.grid.ondblclick && this.grid.enabled) {
      this.grid.ondblclick.call(this, -1, -1);
    }
    
    if (!this.grid.ondblclick || !this.grid.doubleClickOnly) {
      if (!this.grid.editable && this.grid.callForm) {
        this.grid.openNormalForm();
      }
    }
    
    return cancelEvents(evt);
  }
  
  return true;
}

HTMLGrid.prototype.clickGrid = function(template) {
  if (!this.inserting && !this.editing) {
    controller.activeElement = this;
  }
  
  var clickedRow = template.getRowProperty("index");
  this.selectRow(clickedRow);
	
  if (this.onclick) {
    this.onclick.call(this, parseInt(template.getRowProperty("index"))+this.gridini, parseInt(template.getRowProperty("index")));
  }
}

HTMLGrid.prototype.switchToTextMode = function(e) {
  this.template.element().removeChild(this.div);
  this.template.element().innerHTML = this.getValue();
  var row = this.template.getRowProperty("index");
  var col = this.template.getColumnProperty("index");
  this.parent.data[row][col] = this.getValue();
}

HTMLGrid.prototype.addDependentGrid = function(gridName, filter) {
  if (!this.dependentGrids)
    this.dependentGrids = new Array();
  this.dependentGrids.push({gridName: gridName, filter: filter});
}

HTMLGrid.prototype.selectionChanged = function(e) {
  if (this.canPost(this.template)) {
    if (this.disableSelectionRowOnEdit) {
      this.selectRow(this.editRow);
      return false;
    } else {
      if (controller && controller.activeElement && controller.activeElement.blur) {
        controller.activeElement.blur();
      }
      this.timeout(this.post, 0, []);
    }
  }
  
  var newRow = parseInt(this.grid.getProperty("selection/index")) + this.gridini + 1;
  var newSelection =  parseInt(this.grid.getProperty("selection/index"));
  
  if (this.currentSelection != newSelection && newSelection != -1) {
    if (this.onchange) {
      var realLine = parseInt(this.grid.getProperty("selection/index"));
      if (realLine == -1) {
        this.onchange.call(this, 0, -1);
      } else {
        this.onchange.call(this, newRow, realLine);
      }
    }
    if (this.dependentGrids) {         
      var gt = newRow;
      if (newSelection == -1)
        gt = 0; 
      for (var i=0;i<this.dependentGrids.length;i++) {
      	var gridData = this.dependentGrids[i];
      	var url = 'gridEdit.do?sys='+this.sys+'&param=refreshDependence&formID='+this.formID+'&comID='+this.code+'&gt='+gt+'&dependentGrid='+gridData.gridName+'&dependentGridFilter='+URLEncode(gridData.filter);
        getAndEvalSync2(url);
        $c(gridData.gridName).refreshURL = url;
      }
    	
    }  
  } 
  this.currentRow = newRow;
  this.currentSelection = this.grid.getProperty("selection/index");
}

HTMLGrid.prototype.pagingNavigateAction = function(param) {
}

HTMLGrid.prototype.filter = function(f) {
  var url = 'gridEdit.do?sys='+this.sys+'&param=filter&formID='+this.formID+'&comID='+this.code+'&filter='+URLEncode(f);
  getAndEvalSync2(url);
  this.refreshURL = url;
}

HTMLGrid.prototype.orderColumn = function() {
  var row = parseInt(this.header.getProperty("item/index"));
  if (!isNullable(this.ordered) && this.ordered.index == row)
    this.order(row, !this.ordered.desc);
  else
    this.order(row, false);
}

HTMLGrid.prototype.order = function(field, desc) {
  var type = '';
  if (desc)
    type = 'DESC';
  var idx = field;  
  if (isNumeric(field)) {
    field = this.components[parseInt(field)];
    this.ordered = {index : idx, desc : desc};
  }
  getAndEvalSync2('gridEdit.do?sys='+this.sys+'&param=order&formID='+this.formID+'&comID='+this.code+'&field='+field+'&type='+type);
  if (isNumeric(field)) {
    this.refreshHeader();
  }  
}

HTMLGrid.prototype.refreshHeader = function() {
  this.header.refresh();
  this.header.refresh();
}


HTMLGrid.prototype.canPost = function(template) {
  var row = template.getRowProperty("index");
  var t = this.editRow != -1 && row != this.editRow;
  return t;
}

HTMLGrid.prototype.include = function() {
  if (!this.enabled || this.readOnly || !this.editable || this.editing || this.inserting || (this.nav && !this.nav.btInclude)) return;
  getAndEval('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=insert&formID='+this.formID+'&comID='+this.code+'&gt=-1');
}

HTMLGrid.prototype.evtScroll = function(e) {

  var arr = eval('document.editComponents'+this.code);

  for (var i=0;i<arr.length;i++) {
    var elem = arr[i];
    var idx = arrayIndexOf(this.components, elem.getCode());
    if (idx != -1) {
      var template = this.template.getItemTemplate(idx);

      y = findPosY(template.element())+2;

      var data = this.grid.getTemplate("layout").getContent("data");
      y = y - data.element().scrollTop;

      elem.setY(y);
    }
  }
}

HTMLGrid.prototype.completeIncludePost = function() {
  this.timeout(this.scrollIntoView, 30, [this.template.getRowProperty("index")]);
  this.grid.setProperty("selection/index", this.data.length-1);
  this.gridFocus();
}

HTMLGrid.prototype.completeInclude = function() {
  this.includeNewRow();
  this.grid.setProperty("selection/index", this.data.length-1);

  this.editCells = new Array();
  var arr = eval('document.editComponents'+this.code);
  var first = null;

  for (var i=0;i<arr.length;i++) {
    var elem = arr[i];
    var idx = arrayIndexOf(this.components, elem.getCode());
    var template = null;
    if (idx != -1) {
      template = this.template.getItemTemplate(idx);
      var com = this.editCell(template, true, idx);
      if (idx == 0) first = com;
    }
    if (template != null) {
      elem.design(template.element(), true);
      if (elem.div) elem.div.style.backgroundColor = '#FFFFFF';
    } else {
      elem.design(MM_findObj('lay'), false);
    }
    
    if (elem.hint != null && typeof elem.hint != "undefined" && trim(elem.hint) != "") {
      elem.setHint(elem.hint);
    }
  }
  if (first) this.timeout(this.focusElement, 15, [first, arr]);

  this.nav.insert();
  this.navWasVisible = this.paging.getVisible();
  this.paging.setVisible(false);
  this.inserting = true;
  this.timeout(this.scrollToLast, 0);
}

HTMLGrid.prototype.cancel = function() {
  if (this.editing)
    this.cancelEdit();
  else if (this.inserting)
    this.cancelInclude();
}

HTMLGrid.prototype.cancelEdit = function() {
  getAndEval('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=canceledit&formID='+this.formID+'&comID='+this.code+'&gt=-1');
}

HTMLGrid.prototype.completeCancelEdit = function() {
  this.completePost(true);
  this.gridFocus();
}

HTMLGrid.prototype.cancelInclude = function() {
  getAndEval('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=cancelinsert&formID='+this.formID+'&comID='+this.code+'&gt=-1');
}

HTMLGrid.prototype.completeCancelInclude = function() {
  this.completePost(true);
  this.data.pop();
  this.grid.setRowProperty("count", this.data.length);
  this.grid.refresh();
  this.nav.normal();
  if (this.data.length > 0) {
    this.grid.setProperty("selection/index", this.data.length-1);
    this.timeout(this.scrollIntoView, 15, [this.template.getRowProperty("index")]);
  }
  this.gridFocus();
}

HTMLGrid.prototype.checkRequireds = function() {
  var arr = eval('document.editComponents'+this.code);
  for (var i=0;i<arr.length;i++) {
    if (arr[i].required && arr[i].getValue() == '') {
      interactionError(getLocaleMessage("ERROR.REQUIRED_FIELD",arr[i]._description), function(e) { e.getFocus(true); }, [arr[i]]);
      this.grid.setProperty("selection/index", this.editRow);
      return false;
    }

    if (arr[i].cpf && !CPF(arr[i].getValue())) {
      interactionError(getLocaleMessage("ERROR.INVALID_CPF_FIELD",arr[i]._description), function(e) { e.getFocus(true); }, [arr[i]]);
      return false;
    }
    if (arr[i].cnpj && !CNPJ(arr[i].getValue())) {
      interactionError(getLocaleMessage("ERROR.INVALID_CNPJ_FIELD",arr[i]._description), function(e) { e.getFocus(true); }, [arr[i]]);
      return false;
    }

    if (arr[i].validateDataType && !arr[i].validateDataType())
      return false;

  }
  return true;
}

/**
 * Inicia o post
 * @param includeNew Flag indicando se deve ser incluida um novo arrow em seguida
 */
HTMLGrid.prototype.post = function(includeNew) {
  if (!this.editing && !this.inserting)
    return;

  if (this.checkRequireds()) {
    try {
      //Se estiver editando, chama evento de antes de alterar
      if (this.editing && this.beforeUpdate)
        this.beforeUpdate();

      //Se estiver inserindo, chama evento de antes de inserir
      if (this.inserting && this.beforeInsert)
        this.beforeInsert();

      var arr = eval('document.editComponents'+this.code);
      var url = 'gridEdit.do?sys='+this.sys+'&action=gridEdit&param=post&formID='+this.formID+'&comID='+this.code+'&gt=-1&gridComID=-1&storedProcedureName=&storedProcedureParams=&align=0';
      if (includeNew) {
        url += '&includeNew=true'; 
      }
      for (var i=0;i<arr.length;i++) {
        var editor = arr[i];
        if (editor.isBinary)
          continue;
        url = url + '&WFRInput'+editor.getCode()+'='+URLEncode(editor.getValue());
      }
      getAndEvalSync2(url);

    } catch (e) {
      handleException(e);
    }
  }
}

HTMLGrid.prototype.completeNotPost = function(cancel) {
  this.grid.setProperty("selection/index", this.editRow);
}

HTMLGrid.prototype.completePost = function(cancel, newDataRow) {
  try {
  	var row = this.editRow;
    var arr = eval('document.editComponents'+this.code);
    if (!arr) {
      this.editRow = -1;
      return;
    }

    for (var i=0;i<arr.length;i++) {
      var elem = arr[i];
      var idx = arrayIndexOf(this.components, elem.getCode());
      if (idx != -1) {
        elem.element.removeChild(elem.div);
        if (!cancel)
          this.data[this.editRow][idx] = elem.getGridShowValue(this, parseInt(this.editRow)+1, idx, this.data[this.editRow][idx], newDataRow);
        this.grid.getRowTemplate(this.editRow).getItemTemplate(idx).refresh();
      }
    }
    
    // Se estiver editando, chama evento de depois de atualizar
    if (this.editing && this.afterUpdate && !cancel) this.afterUpdate();

    // Se estiver inserindo, chama evento de depois de inserir
    // Se houver exceção, ela será capturada, pois não há como dar rollback na transação.
    if (this.inserting && this.afterInsert && !cancel) try { this.afterInsert(); } catch(e) { handleException(e); }

    // Remove os componentes criados para o modo de inserção ou alteração
    for (var i=0;i<arr.length;i++) {
      var elem = arr[i];
      eval('document.c_'+elem.getCode()+' = null;');
      try {
        elem.free(true);
      } catch(e) {
        alert('erro'+elem);
      }
    }

    this.editRow = -1;
    arr.length = 0;
    this.nav.normal();
    this.paging.setVisible(this.navWasVisible);
    this.editing = false;
    this.inserting = false;
  } catch (e) {
    handleException(e);
  }
}

HTMLGrid.prototype.clickEditableRow = function(template) {
  this.focusColumn = template.getColumnProperty("index");
  this.clickGrid(template);
}

HTMLGrid.prototype.repaintEditElems = function(e) {
  var arr = eval('document.editComponents'+this.code);
  if (arr) {
    for (var i=0;i<arr.length;i++) {
      var elem = arr[i];
      var idx = arrayIndexOf(this.components, elem.getCode());
      if (elem.element) {
        var cell = elem.element;
        var x, y, w, h;
        w = cell.offsetWidth;
        h = cell.offsetHeight;
        if (IE) {
          x = 0; y = -1;
        } else {
          x = cell.offsetLeft;
          y = cell.offsetTop;
        }
        elem.setX(x);
        elem.setY(y);
        elem.setWidth(w);
      }
    }
    event.cancelBubble = false;
  }
}
HTMLGrid.prototype.edit = function() {
  if (!this.enabled || this.readOnly || !this.editable || (this.nav && !this.nav.btEdit)) return;
  if (this.data.length == 0) {
    this.include();
  } else {
    var gridrn = this.grid.getProperty("selection/index");
    if (gridrn > this.data.length-1) gridrn = -2;

    var gt = 1 + parseInt(gridrn) + parseInt(this.gridini);
    if (gt <= 0) {
      this.focusColumn = 0;
      this.grid.setProperty("selection/index", 0);
      gt = this.gridini+1;
    }
    getAndEval('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=edit&formID='+this.formID+'&comID='+this.code+'&gridComID=-1&gt='+gt);
  }
}

HTMLGrid.prototype.completeEdit = function() {
  this.grid.setProperty("selection/index", this.grid.getProperty("selection/index"));
  this.editCells = new Array();
  var editComs = new Array();
  var arr = eval('document.editComponents'+this.code);
  var first = null;
  for (var i=0;i<arr.length;i++) {
    var elem = arr[i];
    var idx = arrayIndexOf(this.components, elem.getCode());
    var template = null;
    if (idx != -1) {
      template = this.template.getItemTemplate(idx);
      var com = this.editCell(template, false, idx);
      editComs[idx] = com;
      if (idx == 0) first = com;
    }
    if (template != null) {
      elem.design(template.element(), true);
      if (elem.div) elem.div.style.backgroundColor = '#FFFFFF';
    } else {
      elem.design(MM_findObj('lay'), false);
    }
    
    if (elem.hint != null && typeof elem.hint != "undefined" && trim(elem.hint) != "") {
      elem.setHint(elem.hint);
    }
  }
  this.focusElement(editComs[this.focusColumn], editComs);
  editComs = null;
  this.navWasVisible = this.paging.getVisible();
  this.paging.setVisible(false);
  this.editing = true;
}

HTMLGrid.prototype.focusElement = function(o, elems) {
  var e = o;
  if (o != null) {
    var i = arrayIndexOf(elems, o);
    while(!e.getFocus(true)) {
      document.fromDblClick = false;
      i++;
      if (i > elems.length-1) i = 0;
      e = elems[i];
      if (o == e) {
        e.getFocus(true);
        break;
      }
    }
  }
}

function decimalFormat(value, qtt) {
  if (qtt <= 0) {
    return value;
  }

  if (isNullable(value)) {
    value = "";
    while (qtt-- > 0) {
      value += "0";
    }
    return value;
  }

  value = new String(value);

  if (value.length == qtt) {
    return value;
  }

  if (value.length > qtt) {
    return value.substring(0, qtt);
  }

  qtt -= value.length;
  while (qtt-- > 0) {
    value = "0" + value;
  }

  return value;
} 

HTMLGrid.prototype.editCell = function(template, notedit, idx) {
  var row = template.getRowProperty("index");
  var col = template.getColumnProperty("index");

  var x, y, w, h;
  w = template.element().offsetWidth;
  h = template.element().offsetHeight;
  if (IE) {
    x = 0; y = -1;
  } else {
    x = template.element().offsetLeft;
    y = template.element().offsetTop;
  }

  var gridrn = this.grid.getProperty("selection/index");
  if (gridrn > this.data.length-1) gridrn = -2;

  var gt = 1 + parseInt(gridrn) + parseInt(this.gridini);

  if (this.nav.getMode() == 2) gt = -1;

  var editor = eval('document.c_'+this.components[col]);
  editor.height = h;
  editor.width  = w;
  editor.posX   = x;
  editor.posY   = y;
  editor.tabindex = parseFloat(this.tabindex + '.' + decimalFormat(idx, 5));
  editor._description = editor.description;
  editor.description = '';
  editor.template = template;
  editor.grid = this.grid;
  editor.parent = this;
  editor.toGrid = true;
  editor.element = template.element();
  editor.element.align = 'center';
  editor.scroll = this.grid.getTemplate("layout").getContent("scrollbars").element();
  editor.data = this.grid.getTemplate("layout").getContent("data").element();
  editor.onfocusGrid = editor.onfocus;
  editor.onfocus = this.elemFocusAction;
  if (!editor.field && !editor.isBinary)
    editor.value = this.data[row][col]!='&nbsp;'?this.data[row][col]:'';
  if (!notedit && this.nav.getMode() == 0) this.nav.edit();
  this.editRow = row;
  this.editCells.push(template.element());
  return editor;
}

HTMLGrid.prototype.gridKeyPress = function(evt) {
  var altKey   = false;
  var ctrlKey  = false;
  var shiftKey = false;
  var target   = evt.target || evt.srcElement;
  var keyCode  = evt.keyCode || evt.which;
  var targtype = target.type;
  var chr      = String.fromCharCode(keyCode).toUpperCase();

  if (w3c) {
    if (document.layers) {
      altKey = ((evt.modifiers & Event.ALT_MASK) > 0);
      ctrlKey = ((evt.modifiers & Event.CONTROL_MASK) > 0);
      shiftKey = ((evt.modifiers & Event.SHIFT_MASK) > 0);
    } else {
      altKey = evt.altKey;
      ctrlKey = evt.ctrlKey;
      shiftKey = evt.shiftKey;
    }
  } else {
    altKey = evt.altKey;
    ctrlKey = evt.ctrlKey;
    shiftKey = evt.shiftKey;
  }
 
  if (this.canPost(this.template) && this.disableSelectionRowOnEdit) {
    if ((keyCode == 35/*END*/) || (keyCode == 36/*HOME*/) || (keyCode == 38/*UP*/) || (keyCode == 40/*DOWN*/)) {
      return false;
    }
  }

  var r = true;

  if ((keyCode == 33/*PAGE UP*/) || (keyCode == 34/*PAGE DOWN*/)) {
    r = false;
  }

  if (((!altKey && !ctrlKey && keyCode == 27))) { //Cancelar
    this.cancel();
    r = false;
  }

  else if (!altKey && ctrlKey && (keyCode == 45 || chr == 'I')) { //Insert
    if (!this.editable && this.callForm) {
         this.timeout(this.openNormalForm, 0, [true]);
    } else { 
	    if (this.editing || this.inserting) {
	      if (controller && controller.activeElement) {
	        controller.activeElement.blur();
	      }
	      this.timeout(this.post, 0, [true]);
	    } else {
	      this.include();
	    }
	}    
    r = false;
  }

  else if (!altKey && ctrlKey && chr == 'E') { //Edit
    if (!this.editable && this.callForm) {
      this.timeout(this.openNormalForm, 0, [this]);
    } else { 
      this.edit();
    }
    r = false;
  }

  else if (!altKey && ctrlKey && chr == 'S') { //Gravar
    if (this.editing || this.inserting) {
      if (controller && controller.activeElement) {
        controller.activeElement.blur();
      }
      this.timeout(this.post, 0);
      r = false;
    }
  }

  else if (!altKey && ctrlKey && (chr == '+' || chr == '=' || keyCode == 187 || chr == 'G')) { //Gravar +
    if (this.editing || this.inserting) {
      if (controller && controller.activeElement) {
        controller.activeElement.blur();
      }
      this.timeout(this.post, 0);
      r = false;
    }
  }

  else if (!altKey && ctrlKey && (keyCode == 46 || chr == 'D')) { //Delete
    if ((!this.editing || (this.editing == undefined)) && (!this.inserting || (this.inserting == undefined))) {
      this.deleteRow();
    }
    r = false;
  }

  else if (keyCode == 40 && this.grid.getProperty("selection/index") == this.data.length-1 && !this.grid.changeLine) {
    if (this.editing || this.inserting) {
      if (controller && controller.activeElement) {
        controller.activeElement.blur();
      }
      this.timeout(this.post, 0, [true]);
    } else {
      this.include();
    }
    r = false;
  } 
  
  else if (!altKey && !ctrlKey && keyCode == 39 && (!this.editing && !this.inserting)) { //Próxima Página	 
	    if (this.paging && this.paging.btNext) this.paging.btNext.click();
	    this.timeout(this.gridFocus, 100);	    
	    r = false;
  } 
 
  else if (!altKey && !ctrlKey && keyCode == 37 && (!this.editing && !this.inserting)) { //Página Anterior
    if (this.paging && this.paging.btPrevious) this.paging.btPrevious.click();
    this.timeout(this.gridFocus, 100);
    r = false;
  }  

  else if (!altKey && ctrlKey && keyCode == 39) { //Última Página
    if (this.paging && this.paging.btLast) this.paging.btLast.click();
    r = false;
  }

  else if (!altKey && ctrlKey && keyCode == 37) { //Primeira Página
    if (this.paging && this.paging.btFirst) this.paging.btFirst.click();
    r = false;
  }
  
  else if (!altKey && !ctrlKey && keyCode == 112) { // F1
    if (this.hint != null && typeof this.hint != "undefined" && trim(this.hint) != "") {
      interactionInfo(this.hint, this.gridFocus, [evt], this);
    }
    r = false;
  }

  if (r) r = checkKey(evt, this, this.tabKeys);

  if (!r) {
    document.disableEvents = true;
    if (evt.preventDefault) {
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      evt.keyCode = 0;
      evt.returnValue = false;
    }
    return false;
  } else
    return true;
}

HTMLGrid.prototype.elemFocusAction = function(e) {
  if (this.fromKeyBoard) {
    if (!document.fromDblClick) {
      var elementWidth = this.width>this.data.offsetWidth?this.data.offsetWidth - 30:this.width;
      var newPos = this.element.offsetLeft-this.data.offsetWidth+elementWidth+(IE?30:0);
      this.scroll.scrollLeft = newPos;
    } else
      document.fromDblClick = false;
  } else
    document.fromDblClick = false;
  this.parent.timeout(this.parent.scrollIntoView, 15, [this.template.getRowProperty("index")]);
  if (this.onfocusGrid) this.onfocusGrid.call(this, e);
}

HTMLGrid.prototype.scrollToLast = function(){
    var data = this.grid.getTemplate("layout").getContent("data");
    var left = this.grid.getTemplate("layout").getContent("left");
    var scrollbars = this.grid.getTemplate("layout").getContent("scrollbars");
    	
    var top = data.element().offsetHeight;
    left.element().scrollTop = top;
    data.element().scrollTop = top;
    scrollbars.element().scrollTop = top;
}

HTMLGrid.prototype.scrollIntoView = function(index){

  try {
    var row = this.grid.getTemplate("row", index);
    var data = this.grid.getTemplate("layout").getContent("data");
    var left = this.grid.getTemplate("layout").getContent("left");
    var scrollbars = this.grid.getTemplate("layout").getContent("scrollbars");

    var top, padding = parseInt(data.element().currentStyle.paddingTop);
    if (data.element().scrollTop > row.element().offsetTop - padding) {
      top = row.element().offsetTop  - padding;
      left.element().scrollTop = top;
      data.element().scrollTop = top;
      scrollbars.element().scrollTop = top;
    }

    if (data.element().offsetHeight + data.element().scrollTop <
      row.element().offsetTop + row.element().offsetHeight ) {
      top = row.element().offsetTop + row.element().offsetHeight - data.element().offsetHeight;
      left.element().scrollTop = top;
      data.element().scrollTop = top;
      scrollbars.element().scrollTop = top;
    }
  }
  catch(error){
    // ignore errors
  }
}

HTMLGrid.prototype.dblClickEditableRow = function(template) {

  if (!this.editing && !this.inserting) {
    controller.activeElement = this;
    
    if (this.ondblclick && this.enabled) {
      var currentRow = parseInt(template.getRowProperty("index"));
      var absoluteRow = currentRow + this.gridini;
  		
      this.ondblclick.call(this, absoluteRow, currentRow);
    }
    
    if (!this.ondblclick || !this.doubleClickOnly) {
      if (this.editable) {
        document.fromDblClick = true;
        this.edit();
      } else {
        if (this.callForm) {
          this.openNormalForm();
        }
      }
    }
  }
}

HTMLGrid.prototype.openNormalForm = function(include) {
  if (!this.enabled || this.readOnly || !this.parentHasData) return;

  var gridrn = this.grid.getProperty("selection/index");
  if (gridrn > this.data.length-1) gridrn = -2;
  var gridini = this.grid.gridini;

  var gotoRow = 1 + parseInt(gridrn) + parseInt(this.gridini);
 
  var properties = getContent("gridOpenForm.do?sys=" + this.sys + "&formID=" + this.formCode);
  var otherProperties = (", gotoRow: " + gotoRow + ", onClose: 'var windowDocument = getOpenerWindow(top).d; if (!windowDocument) {windowDocument = opener.d} windowDocument.c_" + this.code + ".refreshPage();'");
  var content = ("openForm({" + properties + otherProperties + "})");

  if (include == true) {
    content = content.replace('mode: 0', 'mode: 1');
    content = content.replace('mode: -1', 'mode: 1');
  }
    
  eval(content);
}

HTMLGrid.prototype.completeDeleteRow = function() {
  //Chama evento depois de deletar
  if (this.afterDelete)
    try { this.afterDelete(); } catch(e) { handleException(e); }
  if (this.data.length > 0 && parseInt(this.lastSelectionIndex)-1 == this.data.length-1) {
    this.grid.setProperty("selection/index", this.lastSelectionIndex-1);  	
    this.timeout(this.scrollIntoView, 15, [this.lastSelectionIndex-1]);
  }
  this.timeout(this.gridFocus, 100);
}

HTMLGrid.prototype.deleteRow = function(src) {
  if (!this.enabled || this.readOnly || !this.editable || (this.nav && !this.nav.btDelete)) return;
  this.lastSelectionIndex = this.grid.getProperty("selection/index");
  var gridrn = this.grid.getProperty("selection/index");
  if (gridrn > this.data.length-1) gridrn = -2;
  var gridini = this.gridini;

  var gt = 1 + parseInt(gridrn) + parseInt(gridini);

  if (gridrn < 0) {
    interactionError(getLocaleMessage("INFO.GRID_RECORD_SELECT"));
  } else {
    var okFunction = function() {
      try {
        //Chama evento antes de deletar
        if (this.beforeDelete)
          this.beforeDelete();

        //Remove seleção atual
        getAndEvalSync('gridEdit.do?sys='+this.sys+'&action=gridEdit&param=delete&formID='+this.formID+'&comID='+this.code+'&gridComID=-1&gt='+gt);
      } catch (e) {
        handleException(e);
      }
    };
    
    var self = this;
    var cancelFunction = function() {
      self.timeout(self.focus, 0);
    };
    
    interactionConfirmWithEvents(getLocaleMessage("INFO.REMOVE_CONFIRM"), okFunction, [gt], this, cancelFunction);
  }
}

HTMLGrid.prototype.openGridManager = function() {
  if (!this.enabled || this.readOnly || !this.parentHasData) return;
  l = (screen.width - 300) / 2;
  t = (screen.height - 300) / 2;
  MM_openBrWindow('grid_sort.jsp?sys='+this.sys+'&formID='+this.formGUID+'_'+this.id,'WFRGridSort','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=300,height=300,left='+l+',top='+t);
}

HTMLGrid.prototype.refresh = function() {
  var url = 'gridEdit.do?sys='+this.sys+'&action=gridEdit&param=refresh&formID='+this.formID+'&comID='+this.code+'&gridComID=-1&gt=-1';
  
  var components = d.t.dependences[this.code];
  if (components && components.length > 0) {
    for (var code in components) {
      var component = eval("$mainform().d.c_" + components[code]);
      if (component) {
        url += ("&WFRInput" + component.code + "=" + URLEncode(component.value));
      }
    }
  }
  
  if (this.refreshURL) 
    url = this.refreshURL;
    
  var content = getContent(url);
  lastReceivedContent = content;
  this.ordered = null;
  eval(content);
}

HTMLGrid.prototype.refreshPage = function() {
  var url = 'gridEdit.do?sys='+this.sys+'&action=gridEdit&param=refreshpage&formID='+this.formID+'&comID='+this.code+'&gridComID=-1&gt=-1';
  var content = getContent(url);
  lastReceivedContent = content;
  eval(content);
}

HTMLGrid.prototype.enableNavigation = function(f, p, n, l) {
  this.paging.enableButtons(f, p, n, l);
}

HTMLGrid.prototype.focus = function() {
  var r = this.enabled && this.visible && !this.readonly;
  if (this.doc) r = r && isVisibleDiv(this.doc);
  if (r) this.gridFocus();
  return r;
}

HTMLGrid.prototype.blur = function() {
  if (controller.activeElement == this) {
    controller.activeElement = null;
  }
  var r = this.enabled && this.visible && !this.readonly && this.editable;
  if (this.doc) r = r && isVisibleDiv(this.doc);
  if (r) this.grid.element().blur();
  return r;
}

HTMLGrid.prototype.checkPost = function() {
  if (this.editing || this.inserting) {
    interactionError(getLocaleMessage("INFO.GRID_EDIT_FINALIZE"), function() { arguments[0].getFocus(true);  }, [this]);
    return false;
  }
  return true;
}

HTMLGrid.prototype.gridButton = function(func, code, img, componentProperties) {
  var hintCode = "";
  
  if (!isNullable(componentProperties)) {
    var hint = componentProperties.hint;
    if (hint != null && typeof hint != "undefined" && hint != "") {
      hintCode = (' alt="' + hint + '" title="' + hint + '" ');
    }
  }
  
  var cb = '<table height=100% width=100% cellpadding=1><tr><td align=center valign=middle' + hintCode + '>'
  if (func) 
    cb += '<a href="#">';
  
  var icon = skin+'grid_button.gif';
  
  if (img)
    icon = img;  

  cb += '<img src="'+icon+'" height="'+this.buttonHeight+'" width="'+this.buttonWidth+'" border=0 ';

  if (func)
    cb += ' onDblClick="return cancelEvents(event)" onClick="'+func+'"';
    
  cb += '>';
  
  if (func) 
    cb += '</a>';
    
  cb += '</td></tr></table>';    
  
  return cb;
}

HTMLGrid.prototype.gridCheckBox = function(state, valueCheck, valueUnCheck, com, row, componentProperties) {
	var hintCode = "";
	
	if (!isNullable(componentProperties)) {
	  var hint = componentProperties.hint;
    if (hint != null && typeof hint != "undefined" && hint != "") {
      hintCode = (' alt="' + hint + '" title="' + hint + '" ');
    }
	}
  
  var canEdit = (this.editable && this.enabled && !this.readonly && (isNullable(componentProperties) || (componentProperties.enabled && !componentProperties.readonly)));
  var cb = '<table height=100% width=100% cellpadding=1><tr><td align=center valign=middle' + hintCode + '>'
  if (canEdit) cb += '<a href="#">';

  cb += '<img src="'+skin;
  
  var activation = "";
  var disableImage = (!this.enabled || isNullable(componentProperties) || !componentProperties.enabled);
  if (disableImage) {
  	activation = "_des";
  }
  
  if (parseInt(state) == 1) {
  	cb += ('check' + activation + '.gif');
  } else if (parseInt(state) == 0) {
  	cb += ('uncheck' + activation + '.gif');
  } else {
  	cb += ('unknowcheck' + activation + '.gif');
  }  
    
  cb += '" border=0';  
    
  if (canEdit) cb += ' onMouseOver="return cancelEvents(event)" onDblClick="return cancelEvents(event)" state="'+state+'" onClick="postCheckOption(event, '+this.code+', '+com+', this.getAttribute(\'state\'), \''+valueCheck+'\', \''+valueUnCheck+'\', '+row+', this); return cancelEvents(event);"';
  cb += ">";
  if (canEdit) cb += "</a>";
  cb += "</td></tr></table>";
  return cb;
}

function cancelEvents(evt) {
  if (evt.preventDefault) {
    evt.preventDefault();
    evt.stopPropagation();
  } else {
    evt.keyCode = 0;
    evt.returnValue = false;
  }
  return false;
}

function postCheckOption(evt, grid, com, state, valueCheck, valueUnCheck, row, img) {
  var obj = controller.getElementByCode(grid);
  obj.timeout(obj.postCheckOption, 0, [com, state, valueCheck, valueUnCheck, row, img]);
}

HTMLGrid.prototype.postCheckOption = function(com, state, valueCheck, valueUnCheck, row, img) {
  if (this.editing || this.inserting || httpprocessing || this.imgEdit != 1 || !this.enabled || this.readonly)
    return;

  var checked = state == 1;

  var removeRuleErrors = true;

  var url = 'gridEdit.do?sys='+this.sys+'&action=gridEdit&param=post&formID='+this.formID+'&comID='+this.code+'&gt='+row+'&gridComID=-1&storedProcedureName=&storedProcedureParams=&align=0&postSameIfNotPresent=true&checkBoxPost=true';
  url += '&WFRInput'+com+'='+URLEncode(checked?valueUnCheck:valueCheck);

  var gridrn = row - parseInt(this.gridini) - 1;  

  this.completePostCheckOption = this.getAction(this.completePostCheckOptionAction, [com, state, valueCheck, valueUnCheck, row, img, gridrn]);
  this.navWasVisible = this.paging.getVisible();
  getAndEvalSync(url);
}

HTMLGrid.prototype.completePostCheckOptionAction = function(com, state, valueCheck, valueUnCheck, row, img, gridrn) {
  var checked = (img.src.indexOf(skin+'check.gif') != -1);

  var img_src;
  
  if (parseInt(state) == 0 || parseInt(state) == 2) {
    img_src = 'check.gif';
    state = 1;
  } else if (parseInt(state) == 1) {
    img_src = 'uncheck.gif';
    state = 0;
  }  
    
  img.setAttribute('src', skin+img_src);
  img.setAttribute('state', state);
  removeRuleErrors = false;

  var idx = arrayIndexOf(this.components, com);
  this.data[gridrn][idx] = this.gridCheckBox(state, valueCheck, valueUnCheck, com, row);
}

function gridImage(u, w, h) {
  return '<img src="' + u + '&dataTime='+(new Date()).getTime()+'" border=0 width="20" height="18" onclick="WFRZoomImg(\''+u+'\', '+w+', '+h+');">';
}

HTMLGrid.prototype.includeNewRow = function() {
  var newdata = new Array(this.columns.length);
  for (var i =0; i<newdata.length; i++) { 
    newdata[i] = '';
  }  
  this.data.push(newdata);
  this.grid.setRowProperty("count", this.data.length);
  this.grid.refresh();
}

HTMLGrid.prototype.selectRow = function(row, dontCallEvents) {
  this.timeout(this.selectRowSync, 0, [row, dontCallEvents]);  
}

HTMLGrid.prototype.selectRowSync = function(row, dontCallEvents) {
  if (dontCallEvents == true) {
    this.currentSelection = row;
  }
  this.grid.setProperty("selection/index", row);
}

HTMLGrid.prototype.removeDataRow = function(row) {
  this.data = arrayIndexRemove(this.data, row);
  this.grid.setRowProperty('count', this.data.length);
  this.grid.refresh();
}

HTMLGrid.prototype.addColumn = function(column) {
  var idx = arrayIndexOf(this.columns, column);
  if (idx != -1)
    throw getLocaleMessage("INFO.GRID_ALREADY_CONTAINS_COLUMN", column, this.description);
     
  this.columns.push(column);
  this.columnsWidth.push(50);
  this.components.push(-1);
   
  for (var i =0; i<this.data.length; i++)
    this.data[i].push('');

  this.grid.setColumnProperty('count', this.columns.length);
   
  this.grid.refresh();
}

HTMLGrid.prototype.removeColumn = function(column) {
  var idx = this.findColumn(column);
   
  this.columns.splice(idx, 1);
  this.columnsWidth.splice(idx, 1);
  this.components.splice(idx, 1);
   
  for (var i =0; i<this.data.length; i++)
    this.data[i] = arrayIndexRemove(this.data[i], idx);
   
  this.grid.setColumnProperty('count', this.columns.length);
   
  this.grid.refresh();
}

HTMLGrid.prototype.setCellDataByColumn = function(row, column, value) {
  this.data[row][this.findColumn(column)] = value;
  this.grid.refresh();
}

HTMLGrid.prototype.getDataByColumn = function(row, column) {
  return this.data[row][this.findColumn(column)];
}

HTMLGrid.prototype.findColumn = function(column) {
  var idx = arrayIndexOf(this.columns, column);
  if (idx == -1) {
    throw getLocaleMessage("INFO.GRID_COLUMN_NOT_FOUND", column, (this.description ? this.description : this.id));
  }
  return idx;
}

HTMLGrid.prototype.setColumn = function(column, newName) {
  var idx = this.findColumn(column);
  this.columns[idx] = newName;
  
  var key = "grid" + this.code;
  var firstElement = $(key + ".top.item:" + idx);
  if (firstElement && firstElement.childNodes[0] != null && firstElement.childNodes[0].childNodes[1] != null) {
    firstElement.childNodes[0].childNodes[1].nodeValue = newName;
  }
}

HTMLGrid.prototype.getSelectedRow = function() {
  return this.grid.getProperty("selection/index")
}

HTMLGrid.prototype.getRowCount = function() {
  return this.data.length;
}

HTMLGrid.prototype.getColumnCode = function(column) {
  return this.components[this.findColumn(column)];
}

HTMLGrid.prototype.getRowNo = function() {
  var gridrn = this.grid.getProperty("selection/index");
  if (gridrn > this.data.length-1) gridrn = -2;

  var gt = 1 + parseInt(gridrn) + parseInt(this.gridini);
    
  return gt;
}

HTMLGrid.prototype.scrollLeft = function(v) {
  this.scroll.element().scrollLeft = v;	
}

HTMLGrid.prototype.scrollTop = function(v) {
  this.scroll.element().scrollTop = v;	
}

HTMLGrid.prototype.cleanEvents = function() {

  this.openGridManager = function(){};
  this.saveSize = function(){};
  this.openNormalForm = function(){};

}

HTMLGrid.prototype.cleanGrid = function() {

  this.setGridPageIni(0);
  this.setGridPageEnd(0);
                                                      
  this.setData([]);
  this.setColumns([], [], []);
  this.grid.setColumnProperty('count', 0);
  this.resetRowColor();
  this.hasdata = false;
  this.refreshData(true);
  this.enableNavigation(false, false, false, false);
  
}

HTMLGrid.prototype.getPermissionDescription = function() {
  if (!isNullable(this.permissionDescription)) {
    return this.permissionDescription;
  }
  return this.callMethod(HTMLElementBase, "getPermissionDescription");
}
HTMLGrid.prototype.flush = function() {
	  recursiveFlush(this);
}