(function ($, app) {
	var TablesModel = app.Models._Tables;

	TablesModel.prototype.getDefaultRenderer = function() {
		return Handsontable.renderers.DefaultProRenderer;
	};
	TablesModel.prototype.saveTable = function(preview, rerender) {
		this._saveTable(preview, rerender);
		app.Editor.Conditions.saveConditions();
	};
	TablesModel.prototype._setFormatToDiagramsAxis = function(value, type) {
		value = value.replace(/[0-9]{1}/g, '#').replace(/\s+/g, '');
		$('select[name="hAxis[format]"] option[data-type="' + type + '"]').attr('value', value);
		$('select[name="vAxis[format]"] option[data-type="' + type + '"]').attr('value', value);
	};
	TablesModel.prototype.controlSettingsValues = function($element) {
		this._controlSettingsValues($element);
		if($element.is('#google-tables-automatically-update')) {
			if($('#google-tables-link').val().length) {
				$element.removeAttr('data-preview-not-redraw').attr('data-need-settings-save', '1');
			}
		}
	};
    TablesModel.prototype.sortingTable = function(editor, selection, sort) {
        var oSelection = selection[0];
        g_stbMultipleColumnsSorting = [];
        if (oSelection.start.col == oSelection.end.col) {
            g_stbMultipleColumnsSorting.push([oSelection.start.col,this.sortRand(sort)]);
            editor.getPlugin('multiColumnSorting').sort({ column: oSelection.start.col, sortOrder: this.sortRand(sort) });
        } else {
            var sortedColsSettings = [];
            for (var i = oSelection.start.col, n = oSelection.end.col; i <= n; i++) {
            	var sortOrder = this.sortRand(sort);
                sortedColsSettings.push(
                    { column: i, sortOrder: sortOrder }
                );
                g_stbMultipleColumnsSorting.push([i,sortOrder]);
            }
            editor.getPlugin('multiColumnSorting').sort(sortedColsSettings);
        }
    };
    TablesModel.prototype.clearSortingTable = function(editor) {
        g_stbMultipleColumnsSorting = [];
        editor.getPlugin('multiColumnSorting').clearSort();
        editor.render();
    };
    TablesModel.prototype.sortRand = function(sort) {
        if (sort == '') {
            var min= 1;
            var max= 9;
            var random = Math.floor(Math.random() * (+max - +min)) + +min;
            if (random < 5) {
                sort = 'asc';
            } else {
                sort = 'desc';
            }
        }

        return sort;
	};
}(window.jQuery, window.supsystic.Tables));