﻿// Copyright (C) 2007 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alexander Ilyin
// Created:    2007.09.25

Ext.namespace("Xtensive");

Xtensive.LinkColumn = function(cfg) {
  Xtensive.LinkColumn.superclass.constructor.call(this);
  this.innerColumn = cfg.innerColumn;
  this.linkDataIndex = cfg.linkDataIndex;
  this.gridPanel = cfg.gridPanel;
  this.id = cfg.id;
  if (!this.id)
    throw "Id attribute is required for Xtensive.LinkColumn";
  this.addEvents({linkClick : true});
}

Ext.extend(Xtensive.LinkColumn, Ext.util.Observable, {
  init: function() {
    this.oldRender = this.innerColumn.renderer || function(v) { return v };
    this.innerColumn.renderer = this.render.createDelegate(this); // hack columm renderer :(
    if (!this.gridPanel.rendered)
      this.gridPanel.on('render', this.onGridPanelRendered, this);
    else
      this.onGridPanelRendered();
  },

  onGridPanelRendered: function() {
    var gridPanelView = this.gridPanel.getView();
    gridPanelView.mainBody.on('mousedown', this.onGridPanelMouseDown, this);
  },

  onGridPanelMouseDown: function(e, t) {
    if (e.button === 0 && Ext.fly(t).hasClass(this.getLinkCss())) {
      var row = e.getTarget('.x-grid3-row');
      var cell = e.getTarget('.x-grid3-cell');
      if (cell && row) {
        var record = this.gridPanel.getStore().getAt(row.rowIndex);
        var link = record.get(this.linkDataIndex);
        e.stopPropagation();
        this.fireEvent('linkClick', this, link);
      }
    }
  },

  getLinkCss: function() {
    return 'linkcol_' + this.id;
  },

  render: function() {
    var text = this.oldRender.apply(this, arguments);
    if (text)
      return '<a href="javascript:;" class="xt-linkcolumn-link ' + this.getLinkCss() + '">' + text + '</a>';
    else
      return '';
  }
});

if(typeof(Sys)!=='undefined')
    Sys.Application.notifyScriptLoaded();