<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    var selected = [];
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');

            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            console.log(row);
                            console.log(data);
                            $.each(data, function (index, value) {
                                if(index==0 && $(value).attr("checked")=="checked"){
                                   $("#"+row.id).addClass("selected");
                                }else{
                                    $("#"+row.id).removeClass("selected");
                                }
                            });
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked")=="checked"){
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function(){

    }
}

<commit_msg>records selections<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    var selected = [];
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');

            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            if($(data[0]).attr("checked")=="checked"){
                                $(row).addClass("selected");
                            }
                            console.log(row);
                            console.log(data);
//                            $.each(data, function (index, value) {
//                                if(index==0 && $(value).attr("checked")=="checked"){
//                                   $("#"+row.id).addClass("selected");
//                                }else{
//                                    $("#"+row.id).removeClass("selected");
//                                }
//                            });
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked")=="checked"){
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function(){

    }
}

<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            var input = {};
                             input = $(row).find("td:first").html();
                            console.log($.isArray(input));
                            if($(input).attr("checked")=="checked"){
                                $("#"+row.id).addClass("selected");
                            }else{
                                $("#"+row.id).removeClass("selected");
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked")=="checked"){
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }
}

<commit_msg>records selections<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            var input = [];
                             input.push($(row).find("td:first").html());
                            console.log($.isArray(input));
                            if($(input).attr("checked")=="checked"){
                                $("#"+row.id).addClass("selected");
                            }else{
                                $("#"+row.id).removeClass("selected");
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked")=="checked"){
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }
}

<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
	/**
	 * Object of datatable.
	 */
	this.oTable = null;
	/**
	 * URL for managing calls of datatable
	 * @type {string}
	 */
	var ajaxSource = null;
	/**
	 * Set the ajax URL of datatable.
	 * @param {string} source
	 * @returns {Records}
	 */
	this.setAjaxSource = function (source) {
		ajaxSource = source;
		return this;
	}
	/**
	 *
	 * @returns {Records}
	 */
	this.initDataTable = function () {
		// check the existence of table on which we are going to apply datatable.
		if ($('#records').length > 0)
		{
			// Modify css for managing view.
			$('#container').removeClass('container');
			$('#container').css('margin', '20px');
			this.oTable =
			$('#records').window.dataTable(
			{
				"dom": '<"top"p><"clear">tir<"bottom"p>',
				"bProcessing": true,
				"bServerSide": true,
				"language": {
					"info": "Showing _START_ - _END_ of _MAX_"
				},
				"sAjaxSource": ajaxSource,
				"bStateSave": true,
				"fnInitComplete": function () {
					this.oTable.fnAdjustColumnSizing();
				},
				"fnServerData": function (sSource, aoData, fnCallback) {
					jQuery.getJSON(sSource, aoData, function (json) {
						fnCallback(json);

					});
				},
			});
		}
		return this;
	}
}
(this);

<commit_msg>added event listener and subscriber<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
	/**
	 * Object of datatable.
	 */
	this.oTable = null;
	/**
	 * URL for managing calls of datatable
	 * @type {string}
	 */
	var ajaxSource = null;
	/**
	 * Set the ajax URL of datatable.
	 * @param {string} source
	 * @returns {Records}
	 */
	this.setAjaxSource = function (source) {
		ajaxSource = source;
		return this;
	}
	/**
	 *
	 * @returns {Records}
	 */
	this.initDataTable = function () {
		// check the existence of table on which we are going to apply datatable.
		if ($('#records').length > 0)
		{
			// Modify css for managing view.
			$('#container').removeClass('container');
			$('#container').css('margin', '20px');
			this.oTable =
			$('#records').dataTable(
			{
				"dom": '<"top"p><"clear">tir<"bottom"p>',
				"bProcessing": true,
				"bServerSide": true,
				"language": {
					"info": "Showing _START_ - _END_ of _MAX_"
				},
				"sAjaxSource": ajaxSource,
				"bStateSave": true,
				"fnInitComplete": function () {
					this.oTable.fnAdjustColumnSizing();
				},
				"fnServerData": function (sSource, aoData, fnCallback) {
					jQuery.getJSON(sSource, aoData, function (json) {
						fnCallback(json);

					});
				},
			});
		}
		return this;
	}
}
(this);

<|endoftext|>


<commit_before>import React from 'react';

import { t } from "./Translations";

class ArticlesContainer extends React.Component {

  constructor(props){
    super(props);
  }

  renderPagination(){
    return (

«

»

    );
  }

  render () {
    const { locale } = this.props;
    return (

 Page header

 Project One

 Subheading

Subheading fdsjkvjsdv d sv kd jfkdlndsks kdsjdgldsgqslkgjqdklg kgjdkgqkdsljgkldsqgj kjqgkdlgjkldsgjdkgjlsqgjk

              View project

 Project Two

 Subheading

Subheading fdsjkvjsdv d sv kd jfkdlndsks kdsjdgldsgqslkgjqdklg kgjdkgqkdsljgkldsqgj kjqgkdlgjkldsgjdkgjlsqgjk

              View project

    );
  }
}

export default ArticlesContainer;<commit_msg>use child element to fill articles container<commit_after>import React from 'react';

import { t } from "./Translations";
import Article from "./Article.react";

const nbArticles = 5;

class ArticlesContainer extends React.Component {

  constructor(props){
    super(props);
    this.renderPagination = this.renderPagination.bind(this);
    this.renderChildren = this.renderChildren.bind(this);
  }

  renderPagination(){
    const { children } = this.props;
    const nodes = children.map((child, index) => {
      return (
{index+1}
);
    })
    return (

«

            {nodes}

»

    );
  }

  renderChildren() {
    const { children } = this.props;
    return children.map((child, index) => {
      return (

          {child}

      );
    });
  }

  render () {
    const { locale, title, children } = this.props;
    return (

{title}

        {this.renderChildren()}

    );
  }
}

ArticlesContainer.propTypes = {
  title: React.PropTypes.string
};

ArticlesContainer.defaultProps = {
  title: 'Page header'
};

export default ArticlesContainer;<|endoftext|>


<commit_before>"use strict";

(function () {
    angular
        .module("argo")
        .factory("streamService", streamService);

    streamService.$inject = ["$http", "$timeout", "ngSocket",
                        "quotesService", "activityService",
                        "tradesService", "ordersService", "accountsService"];
    function streamService($http, $timeout, ngSocket,
                        quotesService, activityService,
                        tradesService, ordersService, accountsService) {
        var service = {
            startStream: startStream
        };

        return service;

        function startStream(data) {
            $http.post("/api/startstream", {
                environment: data.environment,
                accessToken: data.token,
                accountId: data.accountId,
                instruments: data.instruments
            }).success(function () {
                getStream();
            });
        }

        function getStream() {
            var ws = ngSocket("ws://localhost:8000/stream");

            ws.onMessage(function (event) {
                var data,
                    tick,
                    transaction;

                try {
                    data = angular.fromJson(event.data);
                    tick = data.tick;
                    transaction = data.transaction;
                    if (tick) {
                        quotesService.updateTick(tick);
                        tradesService.updateTrades(tick);
                        ordersService.updateOrders(tick);
                    }
                    if (transaction) {
                        activityService.addActivity(transaction);

                        $timeout(function () {
                            tradesService.refresh();
                            $timeout(function () {
                                ordersService.refresh();
                                $timeout(function () {
                                    accountsService.refresh();
                                }, 100);
                            }, 100);
                        }, 100);
                    }
                /*eslint-disable no-empty */
                } catch (e) {
                    // Discard "incomplete" json
                }
                /*eslint-enable no-empty */
            });
        }
    }

}());
<commit_msg>Fix timeout to refresh views.<commit_after>"use strict";

(function () {
    angular
        .module("argo")
        .factory("streamService", streamService);

    streamService.$inject = ["$http", "$timeout", "ngSocket",
                        "quotesService", "activityService",
                        "tradesService", "ordersService", "accountsService"];
    function streamService($http, $timeout, ngSocket,
                        quotesService, activityService,
                        tradesService, ordersService, accountsService) {
        var service = {
            startStream: startStream
        };

        return service;

        function startStream(data) {
            $http.post("/api/startstream", {
                environment: data.environment,
                accessToken: data.token,
                accountId: data.accountId,
                instruments: data.instruments
            }).success(function () {
                getStream();
            });
        }

        function getStream() {
            var ws = ngSocket("ws://localhost:8000/stream");

            ws.onMessage(function (event) {
                var data,
                    tick,
                    transaction;

                try {
                    data = angular.fromJson(event.data);
                    tick = data.tick;
                    transaction = data.transaction;
                    if (tick) {
                        quotesService.updateTick(tick);
                        tradesService.updateTrades(tick);
                        ordersService.updateOrders(tick);
                    }
                    if (transaction) {
                        activityService.addActivity(transaction);

                        $timeout(function () {
                            tradesService.refresh();
                            $timeout(function () {
                                ordersService.refresh();
                                $timeout(function () {
                                    accountsService.refresh();
                                }, 500);
                            }, 500);
                        }, 500);
                    }
                /*eslint-disable no-empty */
                } catch (e) {
                    // Discard "incomplete" json
                }
                /*eslint-enable no-empty */
            });
        }
    }

}());
<|endoftext|>


<commit_before>const React = require('react');
const h = require('react-hyperscript');
const _ = require('lodash');
const queryString = require('query-string');
const Loader = require('react-loader');
const hideTooltips = require('../../common/cy/events/click').hideTooltips;
const removeStyle= require('../../common/cy/manage-style').removeStyle;
const make_cytoscape = require('../../common/cy/');
const interactionsStylesheet= require('../../common/cy/interactions-stylesheet');
const { ServerAPI } = require('../../services/');
const FilterMenu= require('./filter-menu');
const { BaseNetworkView } = require('../../common/components');
const { getLayoutConfig } = require('../../common/cy/layout');
const downloadTypes = require('../../common/config').downloadTypes;

const interactionsConfig={
  toolbarButtons:_.differenceBy(BaseNetworkView.config.toolbarButtons,[{'id': 'expandCollapse'}],'id'),
  menus: BaseNetworkView.config.menus,
  useSearchBar: true
};

const filterMenuId='filter-menu';
const interactionsConfig={
  toolbarButtons: BaseNetworkView.config.toolbarButtons.concat({
    id: 'filter',
    icon: 'filter_list',
    type: 'activateMenu',
    menuId: filterMenuId,
    description: 'Filter interaction types'
  }),
  menus: BaseNetworkView.config.menus.concat({
    id: filterMenuId,
    width: 25, //%
    func: props => h(FilterMenu, props)
  }),
  useSearchBar: true
};

class Interactions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cy: make_cytoscape({ headless: true, stylesheet: interactionsStylesheet, showTooltipsOnEdges:true }),
      componentConfig: {},
      layoutConfig: {},
      networkJSON: {},
      networkMetadata: {
        name: '',
        datasource: '',
        comments: []
      },
      id:'',
      loading: true,
      categories: new Map (),
      buttonsClicked:{
        Binding:false,
        Phosphorylation:false,
        Expression:false
      }
    };

    const query = queryString.parse(props.location.search);
    ServerAPI.getNeighborhood(query.ID,'TXT').then(res=>{
      const layoutConfig = getLayoutConfig('interactions');
      const network= this.parse(res,query.ID);
      this.setState({
        componentConfig: interactionsConfig,
        layoutConfig: layoutConfig,
        networkJSON: network.network ,
        networkMetadata: Object.assign({}, this.state.networkMetadata, {
          name: (network.id+' Interactions'),
          datasource: 'Pathway Commons',
        }),
        id: network.id,
        loading: false
      });

    });

    ServerAPI.getProteinInformation(query.ID).then(result=>{
      this.setState({
      networkMetadata: Object.assign({}, this.state.networkMetadata, {
        comments: _.compact(['Full Name: '+result[0].protein.recommendedName.fullName.value,
          result[0].protein.alternativeName && 'Synonyms: '+result[0].protein.alternativeName.map(obj => obj.fullName.value).join(', '),
          result[0].comments[0].type==='FUNCTION'&&'Function: '+result[0].comments[0].text[0].value]),
      }),
     });
    });

    this.state.cy.on('trim', () => {
      const categories=this.state.categories;
      const mainNode=this.state.cy.nodes(node=> node.data().id===this.state.id);
      const nodesToKeep=mainNode.merge(mainNode.connectedEdges().connectedNodes());
      this.state.cy.remove(this.state.cy.nodes().difference(nodesToKeep));
      _.forEach(this.state.buttonsClicked,(value,type)=>{
        const edges= this.state.cy.edges().filter(`.${type}`);
        const nodes = edges.connectedNodes();
        categories.set(type,{
          edges:edges,
          nodes:nodes
        });
        if(type!='Binding'){
          this.filterUpdate(type);
        }
      });
      this.setState({
        categories:categories
      });
    });
  }

  edgeType(type){
    switch(type){
      case 'in-complex-with':
      case 'interacts-with':
        return 'Binding';
      case 'controls-phosphorylation-of':
        return 'Phosphorylation';
      case 'controls-expression-of':
        return 'Expression';
      default:
        return '';
    }
  }

  findId(data,id){
    let hgncId;
    data.forEach((value,key)=> {
      if (value[2].includes(id)){
        hgncId=key;
      }
    });
    return hgncId;
  }

  interactionMetadata(mediatorIds,pubmedIds){
    let metadata = [['Detailed views',[]],['Database IDs',[]]];//Format expected by format-content
    mediatorIds.split(';').forEach( link => {
      const splitLink=link.split('/');
      const view = splitLink[2]==='pathwaycommons.org';
      view ? metadata[0][1].push(['Pathway Commons',splitLink[4]]) :
        metadata[1][1].push(['Reactome',splitLink[4]]);
    });
    if(pubmedIds){
     pubmedIds.split(';').forEach(id=>metadata[1][1].push(['PubMed_Interactions',id]));
    }
   return metadata;
}

  addInteraction(nodes,edge,sources,network,nodeMap,nodeMetadata){
    const interaction= this.edgeType(edge);
   nodes.forEach((node)=>{
    if(!nodeMap.has(node)){
      const metadata=nodeMetadata.get(node);
      nodeMap.set(node,true);
      const links=_.uniqWith(_.flatten(metadata.slice(-2).map(entry => entry.split(';').map(entry=>entry.split(':')))),_.isEqual).filter(entry=>entry[0]!='intact');
      network.nodes.push({data:{class: "ball",id: node,label: node,parsedMetadata:[
        ['Type','bp:'+metadata[0].split(' ')[0].replace(/Reference/g,'').replace(/;/g,',')],['Database IDs', links]]}});
      }
    });

    network.edges.push({data: {
      id: nodes[0]+'\t'+edge+'\t'+nodes[1] ,
      label: nodes[0]+' '+edge.replace(/-/g,' ')+' '+nodes[1] ,
      source: nodes[0],
      target: nodes[1],
      class: interaction,
      parsedMetadata:sources
    },classes:interaction});
  }

  parse(data,query){
    let network = {
      edges:[],
      nodes:[],
    };
    let nodeMap=new Map(); //keeps track of nodes that have already been added
    const dataSplit=data.split('\n\n');
    const nodeMetadata= new Map(dataSplit[1].split('\n').slice(1).map(line =>line.split('\t')).map(line => [line[0], line.slice(1) ]));
    dataSplit[0].split('\n').slice(1).forEach(line => {
      const splitLine=line.split('\t');
      const edgeMetadata = this.interactionMetadata(splitLine[6],splitLine[4]);
      this.addInteraction([splitLine[0],splitLine[2]],splitLine[1],edgeMetadata,network,nodeMap,nodeMetadata);
    });
    const id=this.findId(nodeMetadata,query);
    return {id,network};
  }
  filterUpdate(type) {
    const state=this.state;
    const categories = state.categories;
    const buttonsClicked=state.buttonsClicked;
    const cy= state.cy;
    const edges=categories.get(type).edges;
    const nodes=categories.get(type).nodes;

    hideTooltips(cy);
    const hovered = cy.filter(ele=>ele.scratch('_hover-style-before'));
    cy.batch(()=>{
      removeStyle(cy, hovered, '_hover-style-before');
      if(!buttonsClicked[type]){
          cy.remove(edges);
          cy.remove(nodes.filter(nodes=>nodes.connectedEdges().empty()));
      }
      else{
        edges.union(nodes).restore();
      }
    });

    buttonsClicked[type]=!buttonsClicked[type];
    this.setState({
      buttonsClicked:buttonsClicked
    });
  }
  render(){
    const state = this.state;
    const baseView = h(BaseNetworkView.component, {
      layoutConfig: state.layoutConfig,
      componentConfig: state.componentConfig,
      cy: state.cy,
      networkJSON: state.networkJSON,
      networkMetadata: state.networkMetadata,
      //interaction specific
      activeMenu:filterMenuId,
      filterUpdate:(evt,type)=> this.filterUpdate(evt,type),
      buttonsClicked: state.buttonsClicked,
      download: {
        types: downloadTypes.filter(ele=>ele.type==='png'||ele.type==='sif'),
        promise: () => Promise.resolve(_.map(state.cy.edges(),edge=> edge.data().id).sort().join('\n'))
      },
    });
    const loadingView = h(Loader, { loaded: !state.loading, options: { left: '50%', color: '#16A085' }});

    // create a view shell loading view e.g looks like the view but its not
    const content = state.loading ? loadingView : baseView;
    return h('div', [content]);
  }
}
module.exports = Interactions;<commit_msg>Fixed a issue that occured from the PR<commit_after>const React = require('react');
const h = require('react-hyperscript');
const _ = require('lodash');
const queryString = require('query-string');
const Loader = require('react-loader');
const hideTooltips = require('../../common/cy/events/click').hideTooltips;
const removeStyle= require('../../common/cy/manage-style').removeStyle;
const make_cytoscape = require('../../common/cy/');
const interactionsStylesheet= require('../../common/cy/interactions-stylesheet');
const { ServerAPI } = require('../../services/');
const FilterMenu= require('./filter-menu');
const { BaseNetworkView } = require('../../common/components');
const { getLayoutConfig } = require('../../common/cy/layout');
const downloadTypes = require('../../common/config').downloadTypes;

const filterMenuId='filter-menu';
const interactionsConfig={
  toolbarButtons: _.differenceBy(BaseNetworkView.config.toolbarButtons,[{'id': 'expandCollapse'}],'id').concat({
    id: 'filter',
    icon: 'filter_list',
    type: 'activateMenu',
    menuId: filterMenuId,
    description: 'Filter interaction types'
  }),
  menus: BaseNetworkView.config.menus.concat({
    id: filterMenuId,
    width: 25, //%
    func: props => h(FilterMenu, props)
  }),
  useSearchBar: true
};

class Interactions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cy: make_cytoscape({ headless: true, stylesheet: interactionsStylesheet, showTooltipsOnEdges:true }),
      componentConfig: {},
      layoutConfig: {},
      networkJSON: {},
      networkMetadata: {
        name: '',
        datasource: '',
        comments: []
      },
      id:'',
      loading: true,
      categories: new Map (),
      buttonsClicked:{
        Binding:false,
        Phosphorylation:false,
        Expression:false
      }
    };

    const query = queryString.parse(props.location.search);
    ServerAPI.getNeighborhood(query.ID,'TXT').then(res=>{
      const layoutConfig = getLayoutConfig('interactions');
      const network= this.parse(res,query.ID);
      this.setState({
        componentConfig: interactionsConfig,
        layoutConfig: layoutConfig,
        networkJSON: network.network ,
        networkMetadata: Object.assign({}, this.state.networkMetadata, {
          name: (network.id+' Interactions'),
          datasource: 'Pathway Commons',
        }),
        id: network.id,
        loading: false
      });

    });

    ServerAPI.getProteinInformation(query.ID).then(result=>{
      this.setState({
      networkMetadata: Object.assign({}, this.state.networkMetadata, {
        comments: _.compact(['Full Name: '+result[0].protein.recommendedName.fullName.value,
          result[0].protein.alternativeName && 'Synonyms: '+result[0].protein.alternativeName.map(obj => obj.fullName.value).join(', '),
          result[0].comments[0].type==='FUNCTION'&&'Function: '+result[0].comments[0].text[0].value]),
      }),
     });
    });

    this.state.cy.on('trim', () => {
      const categories=this.state.categories;
      const mainNode=this.state.cy.nodes(node=> node.data().id===this.state.id);
      const nodesToKeep=mainNode.merge(mainNode.connectedEdges().connectedNodes());
      this.state.cy.remove(this.state.cy.nodes().difference(nodesToKeep));
      _.forEach(this.state.buttonsClicked,(value,type)=>{
        const edges= this.state.cy.edges().filter(`.${type}`);
        const nodes = edges.connectedNodes();
        categories.set(type,{
          edges:edges,
          nodes:nodes
        });
        if(type!='Binding'){
          this.filterUpdate(type);
        }
      });
      this.setState({
        categories:categories
      });
    });
  }

  edgeType(type){
    switch(type){
      case 'in-complex-with':
      case 'interacts-with':
        return 'Binding';
      case 'controls-phosphorylation-of':
        return 'Phosphorylation';
      case 'controls-expression-of':
        return 'Expression';
      default:
        return '';
    }
  }

  findId(data,id){
    let hgncId;
    data.forEach((value,key)=> {
      if (value[2].includes(id)){
        hgncId=key;
      }
    });
    return hgncId;
  }

  interactionMetadata(mediatorIds,pubmedIds){
    let metadata = [['Detailed views',[]],['Database IDs',[]]];//Format expected by format-content
    mediatorIds.split(';').forEach( link => {
      const splitLink=link.split('/');
      const view = splitLink[2]==='pathwaycommons.org';
      view ? metadata[0][1].push(['Pathway Commons',splitLink[4]]) :
        metadata[1][1].push(['Reactome',splitLink[4]]);
    });
    if(pubmedIds){
     pubmedIds.split(';').forEach(id=>metadata[1][1].push(['PubMed_Interactions',id]));
    }
   return metadata;
}

  addInteraction(nodes,edge,sources,network,nodeMap,nodeMetadata){
    const interaction= this.edgeType(edge);
   nodes.forEach((node)=>{
    if(!nodeMap.has(node)){
      const metadata=nodeMetadata.get(node);
      nodeMap.set(node,true);
      const links=_.uniqWith(_.flatten(metadata.slice(-2).map(entry => entry.split(';').map(entry=>entry.split(':')))),_.isEqual).filter(entry=>entry[0]!='intact');
      network.nodes.push({data:{class: "ball",id: node,label: node,parsedMetadata:[
        ['Type','bp:'+metadata[0].split(' ')[0].replace(/Reference/g,'').replace(/;/g,',')],['Database IDs', links]]}});
      }
    });

    network.edges.push({data: {
      id: nodes[0]+'\t'+edge+'\t'+nodes[1] ,
      label: nodes[0]+' '+edge.replace(/-/g,' ')+' '+nodes[1] ,
      source: nodes[0],
      target: nodes[1],
      class: interaction,
      parsedMetadata:sources
    },classes:interaction});
  }

  parse(data,query){
    let network = {
      edges:[],
      nodes:[],
    };
    let nodeMap=new Map(); //keeps track of nodes that have already been added
    const dataSplit=data.split('\n\n');
    const nodeMetadata= new Map(dataSplit[1].split('\n').slice(1).map(line =>line.split('\t')).map(line => [line[0], line.slice(1) ]));
    dataSplit[0].split('\n').slice(1).forEach(line => {
      const splitLine=line.split('\t');
      const edgeMetadata = this.interactionMetadata(splitLine[6],splitLine[4]);
      this.addInteraction([splitLine[0],splitLine[2]],splitLine[1],edgeMetadata,network,nodeMap,nodeMetadata);
    });
    const id=this.findId(nodeMetadata,query);
    return {id,network};
  }
  filterUpdate(type) {
    const state=this.state;
    const categories = state.categories;
    const buttonsClicked=state.buttonsClicked;
    const cy= state.cy;
    const edges=categories.get(type).edges;
    const nodes=categories.get(type).nodes;

    hideTooltips(cy);
    const hovered = cy.filter(ele=>ele.scratch('_hover-style-before'));
    cy.batch(()=>{
      removeStyle(cy, hovered, '_hover-style-before');
      if(!buttonsClicked[type]){
          cy.remove(edges);
          cy.remove(nodes.filter(nodes=>nodes.connectedEdges().empty()));
      }
      else{
        edges.union(nodes).restore();
      }
    });

    buttonsClicked[type]=!buttonsClicked[type];
    this.setState({
      buttonsClicked:buttonsClicked
    });
  }
  render(){
    const state = this.state;
    const baseView = h(BaseNetworkView.component, {
      layoutConfig: state.layoutConfig,
      componentConfig: state.componentConfig,
      cy: state.cy,
      networkJSON: state.networkJSON,
      networkMetadata: state.networkMetadata,
      //interaction specific
      activeMenu:filterMenuId,
      filterUpdate:(evt,type)=> this.filterUpdate(evt,type),
      buttonsClicked: state.buttonsClicked,
      download: {
        types: downloadTypes.filter(ele=>ele.type==='png'||ele.type==='sif'),
        promise: () => Promise.resolve(_.map(state.cy.edges(),edge=> edge.data().id).sort().join('\n'))
      },
    });
    const loadingView = h(Loader, { loaded: !state.loading, options: { left: '50%', color: '#16A085' }});

    // create a view shell loading view e.g looks like the view but its not
    const content = state.loading ? loadingView : baseView;
    return h('div', [content]);
  }
}
module.exports = Interactions;<|endoftext|>