archwhite
11/29/2017 - 10:08 PM

Knockout table

var mApp = mApp || {};

mApp.isDateTime = function(str) {
    return /\d{2}\.\d{2}\.\d{4}\s(\d{2}:\d{2}:\d{2}|\d{2}:\d{2})/.test(str);
};

mApp.changeDateFormat = function(d) {
    var r = d.match(/^\s*(\d+)\s*\.\s*(\d+)\s*\.\s*(\d+)(.*)$/);
    return r[3] + "-" + r[2] + "-" + r[1] + r[4];
};

mApp.numbersDeclaration = function (number, titles) {
    var cases = [2, 0, 1, 1, 1, 2];
    return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
};

mApp.createNumericArray =  function (startIndex, len) {
    console.log(startIndex, len);
    var resultArray = [];

    for (var i = startIndex; i <= len; i++) {
        resultArray.push(i);
    }

    return resultArray;
};



(function () {
    var indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

    window.DataTable = (function () {
        var primitiveCompare, pureComputed;

        pureComputed = ko.pureComputed || ko.computed;

        primitiveCompare = function (item1, item2) {
            if (item2 == null) {
                return item1 == null;
            } else if (item1 != null) {
                if (typeof item1 === 'boolean') {
                    return item1 === item2;
                } else {
                    return item1.toString().toLowerCase().indexOf(item2.toString().toLowerCase()) >= 0 || item1 === item2;
                }
            } else {
                return false;
            }
        };

        function DataTable(rows, options) {
            var serverSideOpts;
            if (!options) {
                if (!(rows instanceof Array)) {
                    options = rows;
                    rows = [];
                } else {
                    options = {};
                }
            }
            this.options = {
                recordWord: options.recordWord || 'record',
                recordWordPlural: options.recordWordPlural,
                recordWordPlural2: options.recordWordPlural2,
                sortDir: options.sortDir || 'asc',
                sortField: options.sortField || void 0,
                perPage: options.perPage || 15,
                filterFn: options.filterFn || void 0,
                unsortedClass: options.unsortedClass || '',
                descSortClass: options.descSortClass || '',
                ascSortClass: options.ascSortClass || ''
            };
            this.initObservables();
            if ((serverSideOpts = options.serverSidePagination) && serverSideOpts.enabled) {
                if (!(serverSideOpts.path && serverSideOpts.loader)) {
                    throw new Error("`path` or `loader` missing from `serverSidePagination` object");
                }
                this.options.paginationPath = serverSideOpts.path;
                this.options.resultHandlerFn = serverSideOpts.loader;
                this.options.afterLoadingCallback = serverSideOpts.callback || function () { };
                this.options.pagesDotted = serverSideOpts.pagesDotted;
                this.initWithServerSidePagination();
            } else {
                this.initWithClientSidePagination(rows);
            }
        }

        DataTable.prototype.initObservables = function () {
            this.sortDir = ko.observable(this.options.sortDir);
            this.sortField = ko.observable(this.options.sortField);
            this.perPage = ko.observable(this.options.perPage);
            this.currentPage = ko.observable(1);
            this.filter = ko.observable('');
            this.loading = ko.observable(false);
            return this.rows = ko.observableArray([]);
        };

        DataTable.prototype.initWithClientSidePagination = function (rows) {
            var _defaultMatch;
            this.filtering = ko.observable(false);
            this.filter.subscribe((function (_this) {
                return function () {
                    return _this.currentPage(1);
                };
            })(this));
            this.perPage.subscribe((function (_this) {
                return function () {
                    return _this.currentPage(1);
                };
            })(this));
            this.rows(rows);
            this.rowAttributeMap = pureComputed((function (_this) {
                return function () {
                    var attrMap, key, row;
                    rows = _this.rows();
                    attrMap = {};
                    if (rows.length > 0) {
                        row = rows[0];
                        for (key in row) {
                            if (row.hasOwnProperty(key)) {
                                attrMap[key.toLowerCase()] = key;
                            }
                        }
                    }
                    return attrMap;
                };
            })(this));
            this.filteredRows = pureComputed((function (_this) {
                return function () {
                    var filter, filterFn;
                    _this.filtering(true);
                    filter = _this.filter();
                    rows = _this.rows.slice(0);
                    if ((filter != null) && filter !== '') {
                        filterFn = _this.filterFn(filter);
                        rows = rows.filter(filterFn);
                    }
                    if ((_this.sortField() != null) && _this.sortField() !== '') {
                        rows.sort(function (a, b) {
                            var aVal, bVal;
                            aVal = ko.utils.unwrapObservable(a[_this.sortField()]);
                            bVal = ko.utils.unwrapObservable(b[_this.sortField()]);
                            if (typeof aVal === 'string') {
                                aVal = aVal.toLowerCase();
                            }
                            if (typeof bVal === 'string') {

                                bVal = bVal.toLowerCase();
                            }
                            if (mApp.isDateTime(aVal)) {
                                aVal = +new Date(mApp.changeDateFormat(aVal));
                            }
                            if (mApp.isDateTime(bVal)) {
                                bVal = +new Date(mApp.changeDateFormat(bVal));
                            }
                            if (_this.sortDir() === 'asc') {
                                if (aVal < bVal || aVal === '' || (aVal == null)) {
                                    return -1;
                                } else {
                                    if (aVal > bVal || bVal === '' || (bVal == null)) {
                                        return 1;
                                    } else {
                                        return 0;
                                    }
                                }
                            } else {
                                if (aVal < bVal || aVal === '' || (aVal == null)) {
                                    return 1;
                                } else {
                                    if (aVal > bVal || bVal === '' || (bVal == null)) {
                                        return -1;
                                    } else {
                                        return 0;
                                    }
                                }
                            }
                        });
                    } else {
                        rows;
                    }
                    _this.filtering(false);
                    return rows;
                };
            })(this)).extend({
                rateLimit: 50,
                method: 'notifyWhenChangesStop'
            });
            this.pagedRows = pureComputed((function (_this) {
                return function () {
                    var pageIndex, perPage;
                    pageIndex = _this.currentPage() - 1;
                    perPage = _this.perPage();
                    return _this.filteredRows().slice(pageIndex * perPage, (pageIndex + 1) * perPage);
                };
            })(this));
            this.pages = pureComputed((function (_this) {
                return function () {
                    return Math.ceil(_this.filteredRows().length / _this.perPage());
                };
            })(this));
            this.leftPagerClass = pureComputed((function (_this) {
                return function () {
                    if (_this.currentPage() === 1) {
                        return 'disabled';
                    }
                };
            })(this));
            this.rightPagerClass = pureComputed((function (_this) {
                return function () {
                    if (_this.currentPage() === _this.pages()) {
                        return 'disabled';
                    }
                };
            })(this));
            this.total = pureComputed((function (_this) {
                return function () {
                    return _this.filteredRows().length;
                };
            })(this));
            this.from = pureComputed((function (_this) {
                return function () {
                    return (_this.currentPage() - 1) * _this.perPage() + 1;
                };
            })(this));
            this.to = pureComputed((function (_this) {
                return function () {
                    var to;
                    to = _this.currentPage() * _this.perPage();
                    if (to > _this.total()) {
                        return _this.total();
                    } else {
                        return to;
                    }
                };
            })(this));
            this.recordsText = pureComputed((function (_this) {
                return function () {
                    var from, pages, recordWord, recordWordPlural, recordWordPlural2, to, total;
                    pages = _this.pages();
                    total = _this.total();
                    from = _this.from();
                    to = _this.to();
                    recordWord = _this.options.recordWord;
                    recordWordPlural = _this.options.recordWordPlural || recordWord + 's';
                    recordWordPlural2 = _this.options.recordWordPlural2 || recordWord + 's';
                    if (pages > 1) {
                        return from + " - " + to + " из " + total.toFloatStr(0, true) + " " + mApp.numbersDeclaration(total, [recordWord, recordWordPlural, recordWordPlural2]);

                    } else {
                        //return total + " " + (total > 1 || total === 0 ? recordWordPlural : recordWord);
                        return total + " " + (mApp.numbersDeclaration(total, [recordWord, recordWordPlural, recordWordPlural2]));
                    }
                };
            })(this));
            this.showNoData = pureComputed((function (_this) {
                return function () {
                    return _this.pagedRows().length === 0 && !_this.loading();
                };
            })(this));
            this.showLoading = pureComputed((function (_this) {
                return function () {
                    return _this.loading();
                };
            })(this));
            this.sortClass = (function (_this) {
                return function (column) {
                    return pureComputed(function () {
                        if (_this.sortField() === column) {
                            return 'sorted ' + (_this.sortDir() === 'asc' ? _this.options.ascSortClass : _this.options.descSortClass);
                        } else {
                            return _this.options.unsortedClass;
                        }
                    });
                };
            })(this);
            this.addRecord = (function (_this) {
                return function (record) {
                    return _this.rows.push(record);
                };
            })(this);
            this.removeRecord = (function (_this) {
                return function (record) {
                    _this.rows.remove(record);
                    if (_this.pagedRows().length === 0) {
                        return _this.prevPage();
                    }
                };
            })(this);
            this.replaceRows = (function (_this) {
                return function (rows) {
                    _this.rows(rows);
                    _this.currentPage(1);
                    return _this.filter(void 0);
                };
            })(this);
            _defaultMatch = function (filter, row, attrMap) {
                var key, val;
                return ((function () {
                    var results1;
                    results1 = [];
                    for (key in attrMap) {
                        val = attrMap[key];
                        results1.push(val);
                    }
                    return results1;
                })()).some(function (val) {
                    return primitiveCompare((ko.isObservable(row[val]) ? row[val]() : row[val]), filter);
                });
            };
            return this.filterFn = this.options.filterFn || (function (_this) {
                    return function (filterVar) {
                        var filter, ref, specials;
                        ref = [[], {}], filter = ref[0], specials = ref[1];
                        filterVar.split(' ').forEach(function (word) {
                            var words;
                            if (word.indexOf(':') >= 0) {
                                words = word.split(':');
                                return specials[words[0]] = (function () {
                                    switch (words[1].toLowerCase()) {
                                        case 'yes':
                                        case 'true':
                                            return true;
                                        case 'no':
                                        case 'false':
                                            return false;
                                        case 'blank':
                                        case 'none':
                                        case 'null':
                                        case 'undefined':
                                            return void 0;
                                        default:
                                            return words[1].toLowerCase();
                                    }
                                })();
                            } else {
                                return filter.push(word);
                            }
                        });
                        filter = filter.join(' ');
                        return function (row) {
                            var conditionals, key, val;
                            conditionals = (function () {
                                var results1;
                                results1 = [];
                                for (key in specials) {
                                    val = specials[key];
                                    results1.push((function (_this) {
                                        return function (key, val) {
                                            var rowAttr;
                                            if (rowAttr = _this.rowAttributeMap()[key.toLowerCase()]) {
                                                return primitiveCompare((ko.isObservable(row[rowAttr]) ? row[rowAttr]() : row[rowAttr]), val);
                                            } else {
                                                return false;
                                            }
                                        };
                                    })(this)(key, val));
                                }
                                return results1;
                            }).call(_this);
                            return (indexOf.call(conditionals, false) < 0) && (filter !== '' ? (row.match != null ? row.match(filter) : _defaultMatch(filter, row, _this.rowAttributeMap())) : true);
                        };
                    };
                })(this);
        };

        DataTable.prototype.initWithServerSidePagination = function () {
            var _gatherData, _getDataFromServer;
            _getDataFromServer = (function (_this) {
                return function (data, cb) {
                    var key, req, url, val;
                    url = _this.options.paginationPath + "?" + (((function () {
                            var results1;
                            results1 = [];
                            for (key in data) {
                                val = data[key];
                                results1.push((encodeURIComponent(key)) + "=" + (encodeURIComponent(val)));
                            }
                            return results1;
                        })()).join('&'));
                    /**@for abort*/
                    mApp.tableModelGetDataFromServer =  req = new XMLHttpRequest();
                    req.open('GET', url, true);
                    req.setRequestHeader('Content-Type', 'application/json');
                    req.onload = function () {
                        if (req.status >= 200 && req.status < 400) {
                            return cb(null, JSON.parse(req.responseText));
                        } else {
                            return cb(new Error("Error communicating with server"));
                        }
                    };
                    req.onerror = function () {
                        return cb(new Error("Error communicating with server"));
                    };
                    return req.send();
                };
            })(this);
            _gatherData = function (perPage, currentPage, filter, sortDir, sortField) {
                var data;
                data = {
                    perPage: perPage,
                    page: currentPage
                };
                if ((filter != null) && filter !== '') {
                    data.filter = filter;
                }
                if ((sortDir != null) && sortDir !== '' && (sortField != null) && sortField !== '') {
                    data.sortDir = sortDir;
                    data.sortBy = sortField;
                }
                return data;
            };
            this.filtering = ko.observable(false);
            this.pagedRows = ko.observableArray([]);
            this.numFilteredRows = ko.observable(0);
            this.filter.subscribe((function (_this) {
                return function () {
                    /**test*/
                    if (_this.options.pagesDotted) {
                        console.log("this.filter.subscribe");
                        _this.pagesDotted();
                    }
                    /**test*/
                    return _this.currentPage(1);
                };
            })(this));
            this.perPage.subscribe((function (_this) {
                return function () {
                    if (_this.options.pagesDotted) {
                        _this.pagesDotted();
                    }
                    return _this.currentPage(1);
                };
            })(this));
            ko.computed((function (_this) {
                return function () {
                    var data;
                    _this.loading(true);
                    _this.filtering(true);
                    data = _gatherData(_this.perPage(), _this.currentPage(), _this.filter(), _this.sortDir(), _this.sortField());
                    console.log("_getDataFromServer");
                    return _getDataFromServer(data, function (err, response) {
                        var results, total;
                        _this.loading(false);
                        _this.filtering(false);
                        if (err) {
                            return console.log(err);
                        }
                        //total = response.total, results = response.results;
                        total = response.total, results = response.value;
                        _this.numFilteredRows(total);

                        if (_this.options.pagesDotted /*&& !_this.pagesDottedArray().length*/) {
                            _this.pagesDotted();
                        }

                        let result;

                        if (!!results) {
                            result = _this.pagedRows(results.map(_this.options.resultHandlerFn));
                        }
                        _this.options.afterLoadingCallback();
                        return result;
                    });
                };
            })(this)).extend({
                rateLimit: 500,
                method: 'notifyWhenChangesStop'
            });
            this.pages = pureComputed((function (_this) {
                return function () {
                    return Math.ceil(_this.numFilteredRows() / _this.perPage());
                };
            })(this));

            this.pagesDottedArray = ko.observableArray();
            this.pagesDotted = pureComputed({
                read:(function (_this) {
                    return function () {
                        var pages = Math.ceil(_this.numFilteredRows() / _this.perPage());
                        console.log("pages:", pages);
                        return _this.pagesDottedArray(pages > 5 ? mApp.createNumericArray(1, 5) : mApp.createNumericArray(1, pages));
                    };
                })(this),
                write: function (value) {
                    (function(_this) {
                        _this.pagesDottedArray(value);
                    })(this);
                },
                owner:(function(_this) { return _this; })(this)
            });
            /**pages dotted*/
            this.leftPagerClass = pureComputed((function (_this) {
                return function () {
                    if (_this.currentPage() === 1) {
                        return 'disabled';
                    }
                };
            })(this));
            this.rightPagerClass = pureComputed((function (_this) {
                return function () {
                    if (_this.currentPage() === _this.pages()) {
                        return 'disabled';
                    }
                };
            })(this));
            this.from = pureComputed((function (_this) {
                return function () {
                    return (_this.currentPage() - 1) * _this.perPage() + 1;
                };
            })(this));
            this.to = pureComputed((function (_this) {
                return function () {
                    var to, total;
                    to = _this.currentPage() * _this.perPage();
                    if (to > (total = _this.numFilteredRows())) {
                        return total;
                    } else {
                        return to;
                    }
                };
            })(this));
            this.recordsText = pureComputed((function (_this) {
                return function () {
                    var from, pages, recordWord, recordWordPlural, recordWordPlural2, to, total;
                    pages = _this.pages();
                    total = _this.numFilteredRows();
                    from = _this.from();
                    to = _this.to();
                    recordWord = _this.options.recordWord;
                    recordWordPlural = _this.options.recordWordPlural || recordWord + 's';
                    recordWordPlural2 = _this.options.recordWordPlural2 || recordWord + 's';
                    if (pages > 1) {
                        return from + " - " + to + " из " + total.toFloatStr(0, true) + " " + mApp.numbersDeclaration(total, [recordWord, recordWordPlural, recordWordPlural2]);
                    } else {
                        //return total + " " + (total > 1 || total === 0 ? recordWordPlural : recordWord);
                        return total + " " + (mApp.numbersDeclaration(total, [recordWord, recordWordPlural, recordWordPlural2]));
                    }
                };
            })(this));
            this.showNoData = pureComputed((function (_this) {
                return function () {
                    return _this.pagedRows().length === 0 && !_this.loading();
                };
            })(this));
            this.showLoading = pureComputed((function (_this) {
                return function () {
                    return _this.loading();
                };
            })(this));
            this.sortClass = (function (_this) {
                return function (column) {
                    return pureComputed(function () {
                        if (_this.sortField() === column) {
                            return 'sorted ' + (_this.sortDir() === 'asc' ? _this.options.ascSortClass : _this.options.descSortClass);
                        } else {
                            return _this.options.unsortedClass;
                        }
                    });
                };
            })(this);
            this.addRecord = function () {
                throw new Error("#addRecord() not applicable with serverSidePagination enabled");
            };
            this.removeRecord = function () {
                throw new Error("#removeRecord() not applicable with serverSidePagination enabled");
            };
            this.replaceRows = function () {
                throw new Error("#replaceRows() not applicable with serverSidePagination enabled");
            };
            return this.refreshData = (function (_this) {
                return function () {
                    var data;
                    _this.loading(true);
                    _this.filtering(true);
                    data = _gatherData(_this.perPage(), _this.currentPage(), _this.filter(), _this.sortDir(), _this.sortField());
                    return _getDataFromServer(data, function (err, response) {
                        var results, total;
                        _this.loading(false);
                        _this.filtering(false);
                        if (err) {
                            return console.log(err);
                        }
                        //total = response.total, results = response.results;
                        total = response.total, results = response.value; 

                        _this.numFilteredRows(total);
                        let result = _this.pagedRows((results||[]).map(_this.options.resultHandlerFn));
                        _this.options.afterLoadingCallback();
                        return result;
                    });
                };
            })(this);
        };

        DataTable.prototype.toggleSort = function (field) {
            return (function (_this) {
                return function () {
                    _this.currentPage(1);
                    if (_this.sortField() === field) {
                        return _this.sortDir(_this.sortDir() === 'asc' ? 'desc' : 'asc');
                    } else {
                        _this.sortDir('asc');
                        return _this.sortField(field);
                    }
                };
            })(this);
        };

        DataTable.prototype.prevPage = function () {
            var page;
            page = this.currentPage();

            if (this.options.pagesDotted) {

                if (this.pagesDottedArray().indexOf(page) === 4 && page !== this.pages()) {
                    this.pagesDotted(window.mApp.createNumericArray(page - 1, page + 3 > this.pages() ? this.pages() : page + 3));
                }
                if (this.pagesDottedArray().indexOf(page) === 0 && page !== 1) {
                    //this.pagesDotted(window.mApp.createNumericArray(page - 3, page + 1));
                    this.pagesDotted(window.mApp.createNumericArray(page - 3 < 0 ? 1 : page - 3, page - 3 < 0 ? (this.pages() >= 5 ? 5 : this.pages()) : page + 1));
                }
            }
            if (page !== 1) {
                return this.currentPage(page - 1);
            }
        };

        DataTable.prototype.nextPage = function () {
            var page;
            page = this.currentPage();

            if (this.options.pagesDotted) {
                if (this.pagesDottedArray().indexOf(page) === 4 && page !== this.pages()) {
                    this.pagesDotted(window.mApp.createNumericArray(page - 1, page + 3 > this.pages() ? this.pages() : page + 3));
                }
                if (this.pagesDottedArray().indexOf(page) === 0 && page !== 1) {
                    this.pagesDotted(window.mApp.createNumericArray(page - 3, page + 1));
                }
            }
            if (page !== this.pages()) {
                return this.currentPage(page + 1);
            }
        };

        DataTable.prototype.gotoPage = function (page) {
            return (function (_this) {
                return function () {
                    return _this.currentPage(page);
                };
            })(this);
        };


        DataTable.prototype.updatePaging = function (extra) {
            return (function (_this) {
                return function () {
                    var page = !!extra ? extra : _this.currentPage();

                    /**@last*/
                    if (!!extra && extra === _this.pages()) {
                        return _this.pagesDotted(window.mApp.createNumericArray(_this.pages() - 4, _this.pages()));
                    }

                    /**@first*/
                    if (!!extra && extra === 1) {
                        return _this.pagesDotted(window.mApp.createNumericArray(1, 5));
                    }


                    if (_this.pagesDottedArray().indexOf(page) === 4 && page !== _this.pages()) {
                        return _this.pagesDotted(window.mApp.createNumericArray(page-1, page + 3 > _this.pages() ? _this.pages() : page + 3));
                    }


                    if (_this.pagesDottedArray().indexOf(page) === 0 && page !== 1) {
                        return _this.pagesDotted(window.mApp.createNumericArray(page - 3 < 0 ? 1 : page - 3, page - 3 < 0 ? (_this.pages() >= 5 ? 5 : _this.pages()) : page + 1));
                    }
                };
            })(this);
        };

        DataTable.prototype.pageClass = function (page) {
            return pureComputed((function (_this) {
                return function () {
                    if (_this.currentPage() === page) {
                        return 'active';
                    }
                };
            })(this));
        };

        return DataTable;

    })();

}).call(this);

Number.prototype.toFloatStr = function (n, triads) {
    var s, d = 0, k, m;

    if (typeof (n) == 'number')
        if (n.isInt())
            if (n >= -6 && n <= 6) d = n;

    s = this.roundTo(d).toString().replace('.', ',');

    if (d > 0) {
        k = s.indexOf(',');
        if (k == -1)
            s += ',' + '0'.repeat(d);
        else
            s += '0'.repeat(d - (s.length - k - 1));
    }

    k = s.indexOf(',');
    if (k == -1) k = s.length;
    m = s.indexOf('-');
    if (m == -1)
        m = 0;
    else
        m = 1;

    if (triads)
        for (d = k - 3; d > m; d = d - 3) {
            s = s.substr(0, d) + ' ' + s.substr(d, s.length - d + 1);
        }

    return s;
};

Number.prototype.isInt = function (){
    return (Math.round(this) == this);
};

Number.prototype.roundTo = function (n){
    var x = 0;
    if (typeof (n) == 'number')
        if (n.isInt())
            if (n >= -6 && n <= 6) x = n;
    x = Math.pow(10, x);
    return Math.round(this * x) / x;
}
var Statistics = function () {
  var controller = this;

  this.strings = {};

  this.api = {
      list: {
          get: '/Statistics/Statistics/GetLegalData',
          setStatus: '/Statistics/Statistics/SetLegalStatus',
          loadNew: '/Statistics/Statistics/GetNewLegalData',
          search: '/Statistics/Statistics/SearchLegals',
          logSearch: '/Search/Search/LogSearch'
      },
      getDetails:'/'

  };

  this.actions = {
    list: {
        get: function () {
            $.get(controller.api.list.get, {page: 0, perPage: 200}).done(this.getDone);
        },
        getDone: function (response) {
            var rows = response.value.map(function (row) {
                return new controller.models.Company(row, model);
            });
        },
        loadNew: function () {
            $.get(controller.api.list.loadNew).done(function (response) {

                for (var i in response) {
                    if (response.value.hasOwnProperty(i)){
                        controller.ViewModel.table.rows.push(new controller.models.Company(response[i], model));
                    }
                }
            });
        },
        setStatus: function (legalId, status) {
            $.post(controller.api.list.setStatus, { legalId: legalId, value: status }).done(function (response) {
            });
        },
        filters:{
            get: function (type) {
                $.get(controller.api.list.get, type).done(controller.actions.list.getDone);
            }
        },
        search: function(string) {
            if (!string) {
              $('body').unhighlight();
              controller.ViewModel.table.filter('{}');
              controller.ViewModel.searchText = "";
            } else {
              controller.ViewModel.searchText = string;
              controller.ViewModel.table.filter(`{ text: ${string} }`);
            }
            // log search query
            $.get(controller.api.list.logSearch, {"whence": "МОШЕННИКИ", "text": string});
        }
    }
  };

  this.models = {
      Company: (function () {
          function Company(row, view) {
              var self = this;

              this.view = view;

              this.Id = row.Id;

              this.Classification = ko.observable(row.Classification);

              this.Name = ko.observable(row.Name || '');

              this.Inn = ko.observable(row.Inn || '');
              this.Ogrn = ko.observable(row.Ogrn || '');
              this.Okpo = ko.observable(row.Okpo || '');

              this.FactAdress = ko.observable(row.FactAdress || '');
              this.JurAddress = ko.observable(row.JurAddress || '');

              this.Head = ko.observable(row.Head || '');
              
              this.CheckReason = ko.observable(row.CheckReason || '');
              this.Info = ko.observable(row.Info || '');
              this.InfoSource = ko.observable(row.InfoSource || '');

              this.Phone = ko.observable(row.Phone || '');
              this.Bank = ko.observable(row.Bank || '');

              this.DateRegistration = ko.observable(
                moment(Number(row.DateRegistration.match(/\/Date\((-?\d+)\)\/$/)[1])).format('DD.MM.YYYY') || '');
          }
          return Company;
      })()
  };

  this.list = [];


  this.ViewModel = function () {

    var rows, tableOptions, _this = this;
    controller.ViewModel.searchText = '';

    tableOptions = {
        recordWord: 'правило',
        recordWordPlural: 'правила',
        recordWordPlural2: 'правил',
        sortDir: 'desc',
        sortField: 'DateCreated',
        perPage: 20,
        unsortedClass: "red-sunglo",
        ascSortClass: "fa fa-angle-up red-sunglo",
        descSortClass: "fa fa-angle-down red-sunglo",
        serverSidePagination: {
          enabled: true,
          path: "/Statistics/Statistics/GetLegalData",
          loader: response => new controller.models.Company(response, controller.model),
          pagesDotted: false,
          callback: () => {setTimeout(_ => $('table').highlight(controller.ViewModel.searchText), 1000);}
        }
    };

    rows = controller.list.map(function (row) {
        return new controller.models.Company(row, _this);
    });

    this.details = {
      Name: ko.observable(''),
      DateRegistration: ko.observable(''),
      Inn: ko.observable(''),
      Ogrn: ko.observable(''),
      WorkingStatus: ko.observable(''),
      JurAddress: ko.observable(''),
      Fio: ko.observable(''),
      Okved: ko.observable('')
    };

    this.loadNewDisable = ko.observable(false);

    this.filter = ko.observable('0');

    this.actions = {
        list:{
            loadNew: function () {
                controller.actions.list.loadNew();
                _this.loadNewDisable(true);
            },
            toActive: function () {
                //if (_this.filter() !== '0') {
                    _this.table.pagedRows.remove(this);
                //}

                controller.actions.list.setStatus(this.Id, 0);
            },
            toArchive: function () {
                //if (_this.filter() !== '0'){
                    _this.table.pagedRows.remove(this);
                //}

                controller.actions.list.setStatus(this.Id, 1);
            },
            toControl: function () {
                //if (_this.filter() !== '0'){
                    _this.table.pagedRows.remove(this);
               // }

                controller.actions.list.setStatus(this.Id, 2);
            },
            all:function () {
                _this.filter('0');

                controller.actions.list.get();
            }
        },
        getDetails:function(){
            var item = ko.toJS(this);

            _this.details.Name(item.Name||'');
            _this.details.DateRegistration(item.DateRegistration||'');
            _this.details.Inn(item.Inn||'');
            _this.details.Ogrn(item.Ogrn||'');
            _this.details.WorkingStatus(item.WorkingStatus||'');
            _this.details.JurAddress(item.JurAddress||'');
            _this.details.Fio(item.Fio||'');
            _this.details.Okved(item.Okved||'');


            $('#detail').modal('show');
        },
        filters:{
            /** @type {String} type all archived controlling */
            get: function (type, t) {

                _this.filter(t);
                _this.table.filter(`{ status: ${t} }`);
                //controller.actions.list.filters.get(type);
                // _this.table.refreshData();
            }
        }


    };

    this.table = new DataTable(rows, tableOptions);
    

    this.table.nextPage = function() {
      DataTable.prototype.nextPage.call(this);
      if(_this.searchText)
        setTimeout(_ => $('table').highlight(_this.searchText), 1000);
    }

    this.table.prevPage = function() {
      DataTable.prototype.prevPage.call(this);
      if(_this.searchText)
        setTimeout(_ => $('table').highlight(_this.searchText), 1000);
    }
    this.table.gotoPage = function(page) {
      if (page <= 0) return;

      DataTable.prototype.gotoPage.call(this, page)();
      if(_this.searchText)
        setTimeout(_ => $('table').highlight(_this.searchText), 1000);
    }

    window.model = this;
  };


  this.init = function () {
      controller.ViewModel = new controller.ViewModel();

      ko.applyBindings(controller.ViewModel, document.getElementById("vm"));

      // controller.actions.list.get();
  }




};

var sc = new Statistics();

sc.init();

// input filter setup
$("#filter-submit")
.click(function () {
    var string = $('#filter-input').val();
    sc.actions.list.search(string);
});

$('#filter-input').keyup(function(event) {
   if(event.keyCode == 13){
        $("#filter-submit").click();
    }
}).focus();
@using Project.Helpers

@{
    ViewBag.Title = Html.T(""); 
}

<link rel="stylesheet" type="text/css" href="~/Content/Control/styles.css"/>

<div class="center-col page-content-js default-font">
    
    <div class="padding">
        
        <div class="s-row">
            <div class="" id="vm">
                
                <div class="b-filters row">
                    <div class="b-filters-left col-md-10">
                        <a data-bind="css:{'f-sel': filter() === '0'}, click:actions.filters.get.bind(null, {lgStatus: 0}, '0')" href="javascript:void(0)">@Html.T("C.SecOfficer.All")</a>
                        <a data-bind="css:{'f-sel': filter() === '2'}, click:actions.filters.get.bind(null, {lgStatus: 2}, '2')" href="javascript:void(0)">@Html.T("C.SecOfficer.UnderControl")</a>
                        <a data-bind="css:{'f-sel': filter() === '1'}, click:actions.filters.get.bind(null, {lgStatus: 1}, '1')" href="javascript:void(0)">@Html.T("C.SecOfficer.InArchive")</a>
                    </div>
                    <div class="b-filters-right col-md-2">
                        <button data-bind="disable:loadNewDisable, click:actions.list.loadNew" 
                           class="s-float_r btn purple filter-submit-btn">@Html.T("C.SecOfficer.Refresh")</button>
                    </div>
                </div>
        
                <div class="b-control-table">
                    <div data-bind="with: table">
                        <!-- BEGIN Portlet PORTLET-->
                        <div class="portlet light">
                            <div class="portlet-title s-mb_0i">
                              
                                <ul data-bind="visible: pages() > 1" class="pagination pagination-sm s-ml_10i">
                                    <li data-bind="css: leftPagerClass, click: prevPage">
                                        <a href="#"><i class="fa fa-angle-left"></i></a>
                                    </li>
                                    <li data-bind="visible:currentPage() > 1">
                                        <a href="#" data-bind="click:gotoPage(1)">
                                            <i class="fa fa-angle-double-left"></i>
                                        </a>
                                    </li>
                                    <li class="s-p_0i" data-bind="">
                                        <input class="paging-input" data-bind="textInput: currentPage" type="text"/>
                                    </li>
                                    <li data-bind="visible:currentPage() < pages()">
                                        <a href="#" data-bind="click:gotoPage(pages())">
                                            <i class="fa fa-angle-double-right"></i>
                                        </a>
                                    </li>
                                    <li data-bind="css: rightPagerClass, click: nextPage">
                                        <a href="#"><i class="fa fa-angle-right"></i></a>
                                    </li>
                                </ul>
                                <div class="s-float_r s-ta_r s-p_18_0">
                                    <div class="s-float_l s-mr_17">
                                        <input id="filter-input" class="form-control s-transparent w362 query-input" placeholder = @Html.T("C.SearchPage.AddSearchTerms") />
                                    </div>
                                    <button id="filter-submit" type="submit" class="s-float_r btn purple filter-submit-btn">
                                        <span style="margin-right: 3px;" class="spinner"><i class="fa fa-spin fa-refresh"></i></span>
                                        @Html.T("C.SearchPage.Search")
                                    </button>

                                </div>
                                <div class="actions">
                                </div>
                            </div>
                            <div class="portlet-body s-p_0i">
                                <div class="">
                                    <table class="table table-striped table-condensed table-hover table-bordered">
                                        <thead>
                                        <tr>
                                            <th style="width: 145px;" class="s-sortable" data-bind="click: toggleSort('Classification')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.Classification")
                                                    <i class="s-sort-element" data-bind="css: sortClass('Classification')"></i>
                                                </div>
                                            </th>
                                            <th class="s-sortable s-fs_12i" data-bind="click: toggleSort('Name')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.CompanyName")
                                                    <i class="s-sort-element" data-bind="css: sortClass('Name')"></i>
                                                </div>
                                            </th>
                                            <th class="s-sortable s-fs_12i" data-bind="click: toggleSort('Bank')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.BankName")
                                                    <i class="s-sort-element" data-bind="css: sortClass('Bank')"></i>
                                                </div>
                                            </th>
                                            <th class="s-sortable s-fs_12i /*s-ta_c*/" data-bind="click: toggleSort('Inn')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.Inn")
                                                    <i class="s-sort-element" data-bind="css: sortClass('Inn')"></i>
                                                </div>
        
                                            </th>
                                            <th class="s-sortable s-fs_12i" data-bind="click: toggleSort('Ogrn')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.Ogrn")
                                                    <i class="s-sort-element" data-bind="css: sortClass('Ogrn')"></i>
                                                </div>
                                            </th>
                                            <th class="s-sortable s-fs_12i" data-bind="click: toggleSort('DateRegistration')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.RegDate")
                                                    <i class="s-sort-element" data-bind="css: sortClass('DateRegistration')"></i>
                                                </div>
                                            </th>
                                            <th class="s-sortable s-fs_12i" data-bind="click: toggleSort('InfoSource')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.InfoSource")
                                                    <i class="s-sort-element" data-bind="css: sortClass('InfoSource')"></i>
                                                </div>
                                            </th>
                                            <th style="display:none" class="s-sortable s-fs_12i" data-bind="click: toggleSort('FocusHref')">
                                                <div class="s-sort-element-wrapper">
                                                    @Html.T("C.SecOfficer.URLSource")
                                                    <i class="s-sort-element" data-bind="css: sortClass('FocusHref')"></i>
                                                </div>
                                            </th>
                                            <th style="width: 300px;" class="s-sortable s-fs_12i"></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr class="s-display_n" data-bind="visible: showNoData">
                                            <td colspan="8" class="s-ta_c">
                                                @Html.T("C.SecOfficer.NoData")
                                            </td>
                                        </tr>
                                        <tr data-bind="visible: showLoading">
                                            <td colspan="8" class="s-ta_c">
                                                <i data-bind="css: {'icon-spin': showLoading}" class="fa fa-spin font-blue fa-circle-o-notch s-fix-loader"></i>
                                                @Html.T("C.SecOfficer.Loading")
                                            </td>
                                        </tr>
                                        <!-- ko foreach: {data: pagedRows, as: '$row'} -->
                                        <tr data-bind="click:$root.getDetails">
                                            <td class="s-ta_c">
                                                <!-- ko if: $row.Classification() === 0 -->
                                                <div class="b-classification green"></div>
                                                <!-- /ko -->
        
                                                <!-- ko if: $row.Classification() === 1 -->
                                                <div class="b-classification yellow"></div>
                                                <!-- /ko -->
        
                                                <!-- ko if: $row.Classification() === 2 -->
                                                <div class="b-classification red"></div>
                                                <!-- /ko -->
                                            </td>
                                            <td data-bind="">
                                                <a data-bind="text: $row.Name, click:$root.actions.getDetails" 
                                                   href="javascript:void(0)"></a>
                                            </td>
                                            <td data-bind="text: $row.Bank"></td>
                                            <td data-bind="text: $row.Inn"></td>
                                            <td data-bind="text: $row.Ogrn"></td>
                                            <td data-bind="text: $row.DateRegistration"></td>
                                            <td data-bind="text: $row.InfoSource"></td>
                                            <td style="display:none">
                                                <a data-bind="attr:{'href':$row.FocusHref}" href="/" target="_blank">
                                                    <!-- ko text: "Ссылка" --><!-- /ko -->
                                                </a>
        
                                            </td>
        
        
                                            <td class="s-ta_c" data-bind="">
                                                <!-- ko ifnot:$root.filter() === '0' -->
                                                <a data-bind="click:$root.actions.list.toActive"
                                                   href="javascript:void(0)" class="btn-success btn-sm">@Html.T("C.SecOfficer.Active")</a>
                                                <!-- /ko -->

                                                <!-- ko ifnot:$root.filter() === '1' -->
                                                <a data-bind="click:$root.actions.list.toArchive"
                                                   href="javascript:void(0)" class="btn-primary btn-sm">@Html.T("C.SecOfficer.ToArchive")</a>
                                                <!-- /ko -->
                                                
                                                <!-- ko ifnot:$root.filter() === '2' -->
                                                <a data-bind="click:$root.actions.list.toControl"
                                                   href="javascript:void(0)" class="btn-danger btn-sm s-red">@Html.T("C.SecOfficer.Control")</a>
                                                <!-- /ko -->
                                            </td>
                                        </tr>
                                        <!-- /ko -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="clear">
                            </div>
                        </div>
                        <!-- END Portlet PORTLET-->
                    </div>
                </div>
        
        
                <!-- global -->
                <div class="modal fade" id="detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                                <h4 class="modal-title">@Html.T("C.SecOfficer.CompanyDetails")</h4>
                            </div>
                            <div class="modal-body">
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Company"):</strong>
                                    <span data-bind="text:$root.details.Name"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.RegDate"):</strong>
                                    <span data-bind="text:$root.details.DateRegistration"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Inn"):</strong>
                                    <span data-bind="text:$root.details.Inn"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Ogrn"):</strong>
                                    <span data-bind="text:$root.details.Ogrn"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Status"):</strong>
                                    <span data-bind="text:$root.details.WorkingStatus"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Address"):</strong>
                                    <span data-bind="text:$root.details.JurAddress"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Position"):</strong>
                                    <span>@Html.T("C.SecOfficer.Director")</span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Name")</strong>
                                    <span data-bind="text:$root.details.Fio"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.OkvedBase"):</strong>
                                    <span data-bind="text:$root.details.Okved"></span>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.InnMessages"):</strong>
                                    <a href="/" target="_blank" data-bind="attr:{'href':('/Blacklist/Search/ViewEntityPosts?enName='+ $root.details.Inn() +'&entType=8')}, text:$root.details.Inn"></a>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.OgrnMessages"):</strong>
                                    <a href="/" target="_blank" data-bind="attr:{'href':('/Blacklist/Search/ViewEntityPosts?enName='+ $root.details.Ogrn() +'&entType=9')}, text:$root.details.Ogrn"></a>
                                </div>
                                
                                <div class="s-mb_9">
                                    <strong>@Html.T("C.SecOfficer.Info"):</strong>
                                    <span></span>
                                </div>

                            </div>
    
                        </div>
                        <!-- /.modal-content -->
                    </div>
                    <!-- /.modal-dialog -->
                </div>
                <!-- global -->
        
            </div>
        </div>
    </div>
</div>

@section Scripts{
    @Scripts.Render("~/Scripts/knockout/knockout-3.4.2.js")
    @Scripts.Render("~/Scripts/moment.js")
    @Scripts.Render("~/Scripts/knockout/data-table.js")
    @Scripts.Render("~/Scripts/Control/index.js")
    @Scripts.Render("~/Scripts/Control/word-highlighter.js")
}