function InitResizableGrid(selector, heightOffset, menuOptions) {
    $(selector).each(function (index, table) {
        __initResizableGrid($(table), heightOffset, menuOptions);
    });
}

var InitGridMenu = function ($menu) {
};

function __initResizableGrid($table, heightOffset, menuOptions) {
    var controller = $table.parents('#tableholder').find('#tablecontroller').val();
    var tableaction = $table.parents('#tableholder').find('#tableaction').val();
    var scrollkeyCookieKey = controller + '_' + tableaction;

    if (!$table || $table.length === 0)
        return;

    if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {
        $table.find('th').each(function (i, th) {
            var $th = $(th);
            $th.attr('width', $th.attr('data-default-width'));
        });
        $table.find('.k-header-column-menu').remove();
        $table.addClass('data');
        $table.css('visibility', '');
        return;
    }
    if ($table.data('init')) {
        return;
    } else {
        $table.data('init', true);
    }

    $table.find('tbody>tr:first').addClass('first-row');
    $table.addClass('data');
    $table.css('visibility', '');
    if (!heightOffset)
        heightOffset = 165;

    var height = $(window).height() - $table.position().top - heightOffset;
    if (height < 200)
        height = 200;
    var $container = $('<div></div>').css({ 'overflow-y': 'hidden', 'height': height });
    $table.wrap($container);
    var columns = [];
    var $columns = $table.find('th[data-field]');
    var isPixelGrid = false;

    $columns.each(function (i, th) {
        var $th = $(th);
        var pixelWidth = parseInt($th.attr('data-width'), 10);
        var strMinWidth = $th.css('min-width');
        var minWidth = parseInt(strMinWidth.replace('px', ''), 10);
        var linkWidth = $th.find('nobr:first').outerWidth(true) + 5;

        if (minWidth < linkWidth) {
            $th.css('min-width', linkWidth);
        }

        if (pixelWidth) {
            isPixelGrid = true;
        }
    });

    $columns.each(function (i, th) {
        var $th = $(th);
        var pixelWidth = parseInt($th.attr('data-width'), 10);
        var percentWidth = $th.attr('data-default-width');
        var columnWidth = pixelWidth || percentWidth;
        if (isPixelGrid && !pixelWidth) {
            columnWidth = 100;
        }

        columns[i] = {
            field: $th.attr('data-field'),
            width: columnWidth,
            title: $th.attr('title'),
            defaultWidth: percentWidth
        };
    });

    var setApplyFilterAttributes = function () {
        var $clearfilter = $('#clearfilter');
        var $showsavefilter = $('#showsavefilter');

        if ($clearfilter.length) {
            $clearfilter.removeClass('disabled');
            var $clearfilterImg = $clearfilter.find('img');
            $clearfilterImg.attr('src', $clearfilterImg.attr('src').replace('_disabled', ''));
        }
        if ($showsavefilter.length) {
            $showsavefilter.removeClass('disabled');
            var $showsavefilterImg = $showsavefilter.find('img');
            $showsavefilterImg.attr('src', $showsavefilterImg.attr('src').replace('_disabled', ''));
        }
    };

    var kendoGrid = $table.kendoGrid({
        height: height,
        resizable: true,
        columnResize: function (arg) {
            var url = base + controller + '.ivp/SaveColumnResizeGridState';
            var id = arg.column.field;
            var columnsWidth = {};
            columnsWidth[id] = parseInt(arg.newWidth, 10);
            var kendoColumns = $table.data('kendoGrid').columns;
            for (var i = 0; i < kendoColumns.length; i++) {
                var column = kendoColumns[i];
                if (column.field != id) {
                    columnsWidth[column.field] = parseInt(column.width, 10);
                }
            }

            $.ajax({
                type: "POST",
                data: columnsWidth,
                success: function () {
                    setApplyFilterAttributes();
                },
                url: url
            });
        },
        columnReorder: function (arg) {
            var url = base + controller + '.ivp/SaveColumnReorderGridState';
            var data = { columnId: arg.column.field, newIndex: arg.newIndex };
            $.ajax({
                type: "POST",
                data: data,
                success: function () {
                    setApplyFilterAttributes();
                    kendoGrid.thead.find('th').removeClass('last');
                    kendoGrid.thead.find('th').last().addClass('last');
                },
                url: url
            });
        },
        reorderable: true,
        columns: columns,
        autoBind: false,
        dataSource: null
    }).data('kendoGrid');

    var scroll = $.cookie(scrollkeyCookieKey);
    var timer;
    var $gridContent = $('.k-grid-content');
    var $lastth = kendoGrid.thead.find('th').last().addClass('last');
    kendoGrid.thead.find('th[data-field="options"]').find('a.k-header-column-menu').remove();
    $table.css('visibility', '');
    $('.k-resize-handle').css({ 'width': '12px', 'z-index': '9999' });

    if (columns[0].width.toString().indexOf('%') !== -1) {
        KendoGridToPixelWidth($table);
        //ie не успевает рендерить содержимое таблиы....
        KendoGridToPercentWidth($table);
        KendoGridToPixelWidth($table);
    }

    $('body').on('click', 'a.k-header-column-menu', function (event) {
        event.preventDefault();
        var $self = $(this);
        var position = $self.offset();
        var $th = $self.parents('th:first');

        $('.grid-contextmenu').remove();
        var $menu = $('<ul></ul>').addClass('contextmenu grid-contextmenu').css({
            'top': $th.offset().top + $th.outerHeight(),
            left: position.left + 15
        }).show();

        $menu.append($('<li class="grid-filter" onclick="return loadColumns();">' + GridMenuResources.TableSettings + '</li>'))
            .append($('<li class="grid-column-settings" onclick="return loadFilter();">' + GridMenuResources.Filter + '</li>'))
            .append($('<li>' + GridMenuResources.ResetColumnsWidth + '</li>').click(function () {
                var url = base + controller + '.ivp/ClearColumnResizeGridState';
                $.ajax({ type: "GET", url: url });
                $menu.remove();
                $gridContent.scrollLeft(0);
                KendoGridToPercentWidth($table);
                KendoGridToPixelWidth($table);

                return false;
            }));
        if (InitGridMenu) {
            InitGridMenu($menu);
        }
        $('body').append($menu);

        $('body').one("click", function () {
            $menu.remove();
        });

        return false;
    });

    if (scroll) {
        $gridContent.scrollTop(scroll);
    }

    $gridContent.scroll(function (event) {
        clearTimeout(timer);
        timer = setTimeout(refresh, 150);
    });

    var refresh = function () {
        var currentScroll = $gridContent.scrollTop();
        $.cookie(scrollkeyCookieKey, currentScroll);
    };

    var thHeight = $lastth.outerHeight(true);
    var menuTop = (thHeight / 2 - 8);
    kendoGrid.thead.find('a.k-header-column-menu').css('top', menuTop);
    kendoGrid.thead.find('.k-header-column-menu-wrap').css('float', 'right');
}
//Переводим проценты в пиксели для KendoGrid
function KendoGridToPixelWidth($table) {
    var kendoGrid = $table.data('kendoGrid');
    var $headerTable = kendoGrid.wrapper.find('.k-grid-header-wrap table:first');
    var $bodyTable = kendoGrid.wrapper.find('.k-grid-content table:first');
    var $contentCol = kendoGrid.wrapper.find('.k-grid-content colgroup col');
    var $headerCol = kendoGrid.wrapper.find('.k-grid-header-wrap colgroup col');
    var columns = kendoGrid.columns;
    var pixelColumnWidth = [];

    $headerTable.css({ 'table-layout': 'inherit', 'width': '100%' });
    $bodyTable.css({ 'table-layout': 'inherit', 'width': '100%' });

    var $td = kendoGrid.wrapper.find('.k-grid-content table:first tr').not('td tr').last().children();

    var $th = $headerTable.find('thead:first tr').last().children();

    if ($td.length === 0)
        $td = $th;

    for (var i = 0; i < columns.length; i++) {
        if ($.browser.chrome) {
            $td.eq(i).css({ 'overflow': 'visible' });
        }
        var width = $td.eq(i).outerWidth(false);

        var minWidth = $th.eq(i).find('nobr').outerWidth(true);
        if ($.browser.chrome) {
            $td.eq(i).css({ 'overflow': '' });
        }
        if (i === 0) {
            width = width - 2;
        }
        if (width < minWidth) {
            width = minWidth;
        }

        pixelColumnWidth[i] = width;
        columns[i].width = pixelColumnWidth[i];
    }

    for (var j = 0; j < columns.length; j++) {
        $headerCol.eq(j).css('width', pixelColumnWidth[j] + 'px');
        $contentCol.eq(j).css('width', pixelColumnWidth[j] + 'px');
    }

    $headerTable.css({ 'table-layout': 'fixed', 'width': '' });
    $bodyTable.css({ 'table-layout': 'fixed', 'width': '' });
}

function KendoGridToPercentWidth($table) {
    var kendoGrid = $table.data('kendoGrid');
    var $headerTable = kendoGrid.wrapper.find('.k-grid-header-wrap table:first');
    var $bodyTable = kendoGrid.wrapper.find('.k-grid-content table:first');
    var $contentCol = kendoGrid.wrapper.find('.k-grid-content colgroup col');
    var $headerCol = kendoGrid.wrapper.find('.k-grid-header-wrap colgroup col');
    var columns = kendoGrid.columns;

    $headerTable.css('width', '100%');
    $bodyTable.css('width', '100%');

    for (var i = 0; i < columns.length; i++) {
        $headerCol.eq(i).css('width', columns[i].defaultWidth);
        $contentCol.eq(i).css('width', columns[i].defaultWidth);
    }
}