<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 ajaxExportUrl = null;
    /**
     * 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 ajax URL to save export request in db.
     * @param {string} source
     *
     */
    this.setAjaxExportUrl = function (source) {
        ajaxExportUrl = 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) {
                            if ($(data[0]).attr("checked") == "checked") {
                                $(row).addClass("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();
        selfObj.exportRecords();
        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;
        var selectedrecords = '';
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
                selectedrecords = 'all';
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                    selectedrecords = id;
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked')) {
                checked = 1;
                selectedrecords = id;
            }
        }
        $("#selectedrecords").val(selectedrecords);
        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function () {
        $('.export').click(function (e) {
            if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                var exportType = $(this).attr('data-type');
                var selectedrecords = $("#selectedrecords").val();
                $.Dialog({
                    overlay: true,
                    shadow: true,
                    flat: true,
                    title: 'Export Records',
                    content: 'Are you sure you want to export the record(s)?',
                    closeButton: true,
                    buttonsAlign: 'right',
                    width: 400,
                    height: 150,
                    padding: 10,
                    'buttons': {
                        'Ok': {
                            'action': function () {
                            }
                        },
                        'Cancel': {
                            'action': function () {
                            }
                        }
                    }
                });
//                $.ajax({
//                    type: 'POST',
//                    url: ajaxExportUrl,
//                    data: {type: exportType, records: selectedrecords},
//                    dataType: 'json',
//                    success: function (response)
//                    {
//
//                    }
//                });
            } else {
                $.Dialog({
                    'title': 'Error',
                    'content': 'Please select any record.',
                    'draggable': true,
                    'overlay': true,
                    'closeButton': false,
                    'buttonsAlign': 'right',
                    shadow: true,
                    flat: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'position': {
                        'zone': 'right'
                    },
                });
            }
        });
    }
}

<commit_msg>export records<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 ajaxExportUrl = null;
    /**
     * 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 ajax URL to save export request in db.
     * @param {string} source
     *
     */
    this.setAjaxExportUrl = function (source) {
        ajaxExportUrl = 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) {
                            if ($(data[0]).attr("checked") == "checked") {
                                $(row).addClass("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();
        selfObj.exportRecords();
        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;
        var selectedrecords = '';
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
                selectedrecords = 'all';
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                    selectedrecords = id;
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked')) {
                checked = 1;
                selectedrecords = id;
            }
        }
        $("#selectedrecords").val(selectedrecords);
        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function () {
        $('.export').click(function (e) {
            if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                var exportType = $(this).attr('data-type');
                var selectedrecords = $("#selectedrecords").val();
                $.Dialog({
                    overlay: true,
                    shadow: true,
                    flat: true,
                    title: 'Export Records',
                    content: 'Are you sure you want to export the record(s)?',
                    closeButton: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'buttons': {
                        'Ok': {
                            'action': function () {
                            }
                        },
                        'Cancel': {
                            'action': function () {
                            }
                        }
                    }
                });
//                $.ajax({
//                    type: 'POST',
//                    url: ajaxExportUrl,
//                    data: {type: exportType, records: selectedrecords},
//                    dataType: 'json',
//                    success: function (response)
//                    {
//
//                    }
//                });
            } else {
                $.Dialog({
                    'title': 'Error',
                    'content': 'Please select any record.',
                    'draggable': true,
                    'overlay': true,
                    'closeButton': false,
                    'buttonsAlign': 'right',
                    shadow: true,
                    flat: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'position': {
                        'zone': 'right'
                    },
                });
            }
        });
    }
}

<|endoftext|>


<commit_before>var os = require('os');
var webdriver = require('selenium-webdriver');
var path = require('path');

function getLocalBrowser() {
    var chrome = require('selenium-webdriver/chrome'),
    	exeName = {
    		"Linux": "bin/linux/chromedriver",
    		"Darwin": "bin/mac/chromedriver",
    		"Windows_NT": "bin/windows/chromedriver.exe"
    	}
        exeLocation = path.resolve(__dirname, path.relative(__dirname, exeName[os.type()])),
        service = new chrome.ServiceBuilder(exeLocation).build(),
        driver = new chrome.Driver(webdriver.Capabilities.chrome(), service),
        driverWindow = driver.manage().window();

    driverWindow.maximize();

    return driver;
}

module.exports = {
    getLocalBrowser: getLocalBrowser
}<commit_msg>Update index.js<commit_after>var os = require('os');
var webdriver = require('selenium-webdriver');
var path = require('path');

function getLocalBrowser() {
    var chrome = require('selenium-webdriver/chrome'),
    	exeName = {
    		"Linux": "bin/linux/chromedriver",
    		"Darwin": "bin/mac/chromedriver",
    		"Windows_NT": "bin/windows/chromedriver.exe"
    	},
        exeLocation = path.resolve(__dirname, path.relative(__dirname, exeName[os.type()])),
        service = new chrome.ServiceBuilder(exeLocation).build(),
        driver = new chrome.Driver(webdriver.Capabilities.chrome(), service),
        driverWindow = driver.manage().window();

    driverWindow.maximize();

    return driver;
}

module.exports = {
    getLocalBrowser: getLocalBrowser
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  files: {
    javascripts: {
      joinTo: {
        'app.js': /^app/,
        'vendor.js': /^node_modules/
      }
    },

    stylesheets: {
      joinTo: {
        'app.css': /^app/
      }
    }
  },

  plugins: {
    babel: {
      presets: ['es2015', 'react']
    }
  },

  server: {
    port: 8000
  }
};
<commit_msg>Be more explicit<commit_after>'use strict';

module.exports = {
  files: {
    javascripts: {
      joinTo: {
        'app.js': /^app\//,
        'vendor.js': /^node_modules\//
      }
    },

    stylesheets: {
      joinTo: {
        'app.css': /^app\//
      }
    }
  },

  plugins: {
    babel: {
      presets: ['es2015', 'react']
    }
  },

  server: {
    port: 8000
  }
};
<|endoftext|>


<commit_before>var GifEncoder = require('gif.js/src/GIFEncoder');
var fs = require('fs');

// var WIDTH = 200;
// var HEIGHT = 200;

var WIDTH = 600;
var HEIGHT = 392;

var Canvas = require('canvas');
var canvas = new Canvas(WIDTH, HEIGHT);

var ctx = canvas.getContext('2d');

var img = new Canvas.Image();
img.src = fs.readFileSync(__dirname + '/test1-orig.jpg');

ctx.drawImage(img, 0, 0);

// ctx.font = '30px Impact';
// ctx.fillText("Awesome!", 50, 100);

// var te = ctx.measureText('Awesome!');
// ctx.strokeStyle = 'rgba(0,0,0,0.5)';
// ctx.beginPath();
// ctx.lineTo(50, 102);
// ctx.lineTo(50 + te.width, 102);
// ctx.stroke();

// console.log('');
// console.log(canvas.toDataURL());
// var fs = require('fs');
// fs.writeFileSync(__dirname + '/test.png', canvas.toDataURL().replace('data:image/png;base64,', ''), 'base64');

// Load in image-data.json
// var imageData = require('./image-data');
// var imageData = require('./image-data2');
// var data = new Uint8ClampedArray(imageData.length);
// data.set(imageData);
// var imgKeys = Object.getOwnPropertyNames(imageData).map(function (int) {
//   return parseInt(int, 10);
// });
// var maxKey = imgKeys.reduce(function (a, b) {
//   return Math.max(a, b);
// }, 0);
// var data = new Uint8ClampedArray(maxKey + 1);
// for (var i = 0; i < maxKey; i++) {
//   data[i] = imageData[i];
// }
// console.log(data);

global.atob = require('atob');
// Compare to canvas data
// https://gist.github.com/borismus/1032746
var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  // var raw = window.atob(base64);
  var raw = atob(base64);
  var rawLength = raw.length;
  var array = new Uint8ClampedArray(new ArrayBuffer(rawLength));

  for(i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

// http://stackoverflow.com/questions/16194908/how-can-i-create-a-canvas-imagedata-array-from-an-arraybuffer-representation-of
// function convertDataURIToBinary(dataURI) {
//   // uri to Base64
//   b64 = dataURI.slice(dataURI.indexOf(',')+1);
//   // to String
//   str = atob(b64);
//   // to Array
//   arr = str.split('').map(function (e) {return e.charCodeAt(0);});
//   // to Uint8ClampedArray
//   u = new Uint8ClampedArray(arr); // [255, 56, 201, 8]

//   return u;
// }

// console.log(convertDataURIToBinary(canvas.toDataURL()));
// var buffer = canvas.toBuffer();
// var data = new Uint8ClampedArray(buffer.length);

// var i = 0;
// for (; i < data.length; i++) {
//   data[i] = buffer.readUInt8(i);
// }

// var data = convertDataURIToBinary(canvas.toBuffer());
var data = convertDataURIToBinary(canvas.toDataURL());

console.log(JSON.stringify([].slice.call(data)));

// var data = canvas.toBuffer();

// console.log(data.length);

// TODO: Output canvas data to gif
// Output pre-built image data to gif
var gif = new GifEncoder(WIDTH, HEIGHT);

gif.writeHeader();

gif.addFrame(data);

gif.finish();

// console.log(gif.out);

// taken and modified from master/gif.coffee
finishRendering = function () {
  var len = 0;
  var imageParts = [gif];
  var frame;
  for (var i = 0; i < imageParts.length; i++) {
    frame = imageParts[i].out;
    len += (frame.pages.length - 1) * frame.constructor.pageSize + frame.cursor;
  }

  len += frame.constructor.pageSize - frame.cursor;

  // console.log(len);

  // console.log "rendering finished - filesize #{ Math.round(len / 1000) }kb"
  var data = new Uint8Array(len);
  var offset = 0;
  for (i = 0; i < imageParts.length; i++) {
    frame = imageParts[i].out;
    for (var j = 0; j < frame.pages.length; j++) {
      var page = frame.pages[j];
      // console.log(page, offset);
      // console.log(j, offset);
      data.set(page, offset);
      if (j === frame.pages.length - 1) {
        offset += frame.cursor;
      } else {
        offset += frame.constructor.pageSize;
      }
    }
  }

  return data;
};

// // console.log(finishRendering());
var gifData = finishRendering();
global.btoa = require('btoa');
// from gh-pages/scripts/main.js
buildDataURL = (function() {
  var charMap, i, _i;

  charMap = {};
  for (i = _i = 0; _i < 256; i = ++_i) {
    charMap[i] = String.fromCharCode(i);
  }
  return function(data) {
    var str, _j, _ref3;

    str = '';
    for (i = _j = 0, _ref3 = data.length; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) {
      str += charMap[data[i]];
    }
    return 'data:image/gif;base64,' + btoa(str);
  };
})();

// console.log(buildDataURL(gifData));
<commit_msg>Still banging head against the wall<commit_after>var GifEncoder = require('gif.js/src/GIFEncoder');
var fs = require('fs');

// var WIDTH = 200;
// var HEIGHT = 200;

var WIDTH = 600;
var HEIGHT = 392;

var Canvas = require('canvas');
var canvas = new Canvas(WIDTH, HEIGHT);

var ctx = canvas.getContext('2d');

var img = new Canvas.Image();
img.src = fs.readFileSync(__dirname + '/test1-orig.jpg');

ctx.drawImage(img, 0, 0);

// ctx.font = '30px Impact';
// ctx.fillText("Awesome!", 50, 100);

// var te = ctx.measureText('Awesome!');
// ctx.strokeStyle = 'rgba(0,0,0,0.5)';
// ctx.beginPath();
// ctx.lineTo(50, 102);
// ctx.lineTo(50 + te.width, 102);
// ctx.stroke();

// console.log('');
// console.log(canvas.toDataURL());
// var fs = require('fs');
// fs.writeFileSync(__dirname + '/test.png', canvas.toDataURL().replace('data:image/png;base64,', ''), 'base64');

// Load in image-data.json
// var imageData = require('./image-data');
// var imageData = require('./image-data2');
// var data = new Uint8ClampedArray(imageData.length);
// data.set(imageData);
// var imgKeys = Object.getOwnPropertyNames(imageData).map(function (int) {
//   return parseInt(int, 10);
// });
// var maxKey = imgKeys.reduce(function (a, b) {
//   return Math.max(a, b);
// }, 0);
// var data = new Uint8ClampedArray(maxKey + 1);
// for (var i = 0; i < maxKey; i++) {
//   data[i] = imageData[i];
// }
// console.log(data);

global.atob = require('atob');
// Compare to canvas data
// https://gist.github.com/borismus/1032746
var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  // var raw = window.atob(base64);
  var raw = atob(base64);
  var rawLength = raw.length;
  var array = new Uint8ClampedArray(new ArrayBuffer(rawLength));

  for(i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

// http://stackoverflow.com/questions/16194908/how-can-i-create-a-canvas-imagedata-array-from-an-arraybuffer-representation-of
function convertDataURIToBinary(dataURI) {
  // uri to Base64
  b64 = dataURI.slice(dataURI.indexOf(',')+1);
  // to String
  str = atob(b64);
  // to Array
  arr = str.split('').map(function (e) {return e.charCodeAt(0);});
  // to Uint8ClampedArray
  u = new Uint8ClampedArray(arr); // [255, 56, 201, 8]

  return u;
}

// console.log(convertDataURIToBinary(canvas.toDataURL()));
// var buffer = canvas.toBuffer();
// var data = new Uint8ClampedArray(buffer.length);

// var i = 0;
// for (; i < data.length; i++) {
//   data[i] = buffer.readUInt8(i);
// }

// var data = convertDataURIToBinary(canvas.toBuffer());
// var data = convertDataURIToBinary(canvas.toDataURL());

var data = canvas.toBuffer();

console.log(JSON.stringify([].slice.call(data)));

// console.log(data.length);

// TODO: Output canvas data to gif
// Output pre-built image data to gif
var gif = new GifEncoder(WIDTH, HEIGHT);

gif.writeHeader();

gif.addFrame(data);

gif.finish();

// console.log(gif.out);

// taken and modified from master/gif.coffee
finishRendering = function () {
  var len = 0;
  var imageParts = [gif];
  var frame;
  for (var i = 0; i < imageParts.length; i++) {
    frame = imageParts[i].out;
    len += (frame.pages.length - 1) * frame.constructor.pageSize + frame.cursor;
  }

  len += frame.constructor.pageSize - frame.cursor;

  // console.log(len);

  // console.log "rendering finished - filesize #{ Math.round(len / 1000) }kb"
  var data = new Uint8Array(len);
  var offset = 0;
  for (i = 0; i < imageParts.length; i++) {
    frame = imageParts[i].out;
    for (var j = 0; j < frame.pages.length; j++) {
      var page = frame.pages[j];
      // console.log(page, offset);
      // console.log(j, offset);
      data.set(page, offset);
      if (j === frame.pages.length - 1) {
        offset += frame.cursor;
      } else {
        offset += frame.constructor.pageSize;
      }
    }
  }

  return data;
};

// // console.log(finishRendering());
var gifData = finishRendering();
global.btoa = require('btoa');
// from gh-pages/scripts/main.js
buildDataURL = (function() {
  var charMap, i, _i;

  charMap = {};
  for (i = _i = 0; _i < 256; i = ++_i) {
    charMap[i] = String.fromCharCode(i);
  }
  return function(data) {
    var str, _j, _ref3;

    str = '';
    for (i = _j = 0, _ref3 = data.length; 0 <= _ref3 ? _j < _ref3 : _j > _ref3; i = 0 <= _ref3 ? ++_j : --_j) {
      str += charMap[data[i]];
    }
    return 'data:image/gif;base64,' + btoa(str);
  };
})();

// console.log(buildDataURL(gifData));
<|endoftext|>


<commit_before>var fs = require('fs');
var async = require('async');
var GifEncoder = require('../lib/gif.js/GIFEncoder');
var imageInfo = require('../lib/image-info');

module.exports = function writeGifToStream(stream) {
  var WIDTH = 600;
  var HEIGHT = 392;

  // Output canvas data to gif
  var gif = new GifEncoder(WIDTH, HEIGHT);

  var i = 0;
  function delay(fn) {
    // setTimeout(fn, i * 100);
    fn();
    i += 1;
  }
  function writeToStream(buffer) {
    delay(function () {
      stream.write(buffer);
    });
  }

  var activeData = [];
  gif.on('data', function (val) {
    activeData.push(val);
  });
  function outputActiveData() {
    var buffer = new Buffer(activeData);
    activeData = [];
    writeToStream(buffer);
  }
  gif.on('writeHeader#stop', outputActiveData);
  gif.on('frame#stop', outputActiveData);
  gif.on('finish#stop', function () {
    outputActiveData();

    gif.on('end', function () {
      delay(function () {
        stream.end();
      });
    });
  });

  // Open the gif
  gif.writeHeader();

  // Configure the gif
  // gif.setDelay(100);
  // gif.setRepeat(0);
  gif.setQuality(10);

  async.eachSeries([
    'Hello',
    'Hello World',
    'Hello World!',
    'Hello World!!!'
  ], function getFrameInfo (text, cb) {
    // TODO: Accept canvas as a parameter
    function drawImage(cb) {
      context.font = '30px Impact';
      context.fillStyle = '#FFFFFF';
      context.fillText('TEXT', 50, 100);
      cb(null);
    }

    var fn = (drawImage + '')
              .replace('TEXT', text)
              .replace('function drawImage(cb) {', '')
              .replace(/}$/, '');

    imageInfo({
      width: WIDTH,
      height: HEIGHT,
      js: fn
    }, function parseFrameInfo (err, unparsedJson) {
      if (err) {
        return cb(err);
      }

      var dataArr = JSON.parse(unparsedJson);
      // TODO: Do we really need to double the memory here?
      var data = new Uint8ClampedArray(dataArr.length);
      data.set(dataArr);
      gif.addFrame(data);

      cb(null);
    });
  }, function finishGif (err) {
    if (err) {
      throw err;
    }

    // Complete the gif
    gif.finish();
  });
};

if (module.parent === null) {
  var stream = fs.createWriteStream(__dirname + '/test.gif');

  stream.on('finish', function () {
    console.log('finished');
    process.exit();
  });

  module.exports(stream);
}<commit_msg>Rearranging comments<commit_after>var fs = require('fs');
var async = require('async');
var GifEncoder = require('../lib/gif.js/GIFEncoder');
var imageInfo = require('../lib/image-info');

module.exports = function writeGifToStream(stream) {
  var WIDTH = 600;
  var HEIGHT = 392;

  // Output canvas data to gif
  var gif = new GifEncoder(WIDTH, HEIGHT);

  var i = 0;
  function delay(fn) {
    // setTimeout(fn, i * 100);
    fn();
    i += 1;
  }
  function writeToStream(buffer) {
    delay(function () {
      stream.write(buffer);
    });
  }

  var activeData = [];
  gif.on('data', function (val) {
    activeData.push(val);
  });
  function outputActiveData() {
    var buffer = new Buffer(activeData);
    activeData = [];
    writeToStream(buffer);
  }
  gif.on('writeHeader#stop', outputActiveData);
  gif.on('frame#stop', outputActiveData);
  gif.on('finish#stop', function () {
    outputActiveData();

    gif.on('end', function () {
      delay(function () {
        stream.end();
      });
    });
  });

  // Open the gif
  gif.writeHeader();

  // Configure the gif
  // gif.setDelay(100);
  // gif.setRepeat(0);
  gif.setQuality(10);

  async.eachSeries([
    'Hello',
    'Hello World',
    'Hello World!',
    'Hello World!!!'
  ], function getFrameInfo (text, cb) {
    // TODO: Accept canvas as a parameter
    function drawImage(cb) {
      context.font = '30px Impact';
      context.fillStyle = '#FFFFFF';
      context.fillText('TEXT', 50, 100);
      cb(null);
    }

    var fn = (drawImage + '')
              .replace('TEXT', text)
              .replace('function drawImage(cb) {', '')
              .replace(/}$/, '');

    imageInfo({
      width: WIDTH,
      height: HEIGHT,
      js: fn
    }, function parseFrameInfo (err, unparsedJson) {
      if (err) {
        return cb(err);
      }

      // TODO: Do we really need to double the memory here?
      var dataArr = JSON.parse(unparsedJson);
      var data = new Uint8ClampedArray(dataArr.length);
      data.set(dataArr);
      gif.addFrame(data);

      cb(null);
    });
  }, function finishGif (err) {
    if (err) {
      throw err;
    }

    // Complete the gif
    gif.finish();
  });
};

if (module.parent === null) {
  var stream = fs.createWriteStream(__dirname + '/test.gif');

  stream.on('finish', function () {
    console.log('finished');
    process.exit();
  });

  module.exports(stream);
}<|endoftext|>


<commit_before>var dom = require('./miniDom');
var adsSetupPlugin = require('./ads-setup-plugin');
var messages = require('./messages');
var custom_xhr = {};

xhook.before(function(request, callback) {
  var intercept_urls = Object.keys(custom_xhr);
  var i, len, match, intercept_url;

  for (i = 0, len = intercept_urls.length; i < len; i++) {
    intercept_url = intercept_urls[i];
    match = new RegExp(intercept_url + "$", "gi");
    if (request.url.match(match)) {
      return callback({
        status: 200,
        data: custom_xhr[intercept_url]
      });
    }
  }
  callback();
});

videojs.plugin('ads-setup', adsSetupPlugin);

dom.onReady(function() {
  var vastForm = document.querySelector('form#vast-form');
  var vpaidForm = document.querySelector('form#vpaid-form');

  initForm(vastForm);
  initForm(vpaidForm);

  /*** Local functions ***/
  function initForm(formEl) {
    var tagTypeEl = formEl.querySelector('input.tag-type-radio');
    var xmlTypeEl = formEl.querySelector('input.xml-type-radio');
    var customTypeEl = formEl.querySelector('input.custom-type-radio');
    var updateBtn = formEl.querySelector('.button.button-primary');
    var pauseBtn = formEl.querySelector('.pause');
    var resumeBtn = formEl.querySelector('.resume');
    var tagEl = formEl.querySelector('input.tag-el');
    var xmlEl = formEl.querySelector('select.xml-el');
    var customEl = formEl.querySelector('textarea.custom-el');
    var videoContainer = formEl.querySelector('div.vjs-video-container');
    var player;

    updateVisibility();
    dom.addEventListener(tagTypeEl, 'change', updateVisibility);
    dom.addEventListener(xmlTypeEl, 'change', updateVisibility);
    dom.addEventListener(customTypeEl, 'change', updateVisibility);
    dom.addEventListener(updateBtn, 'click', function() {
      updateDemo();
      messages.success("Demo updated!!!");
    });

    if (pauseBtn) {
      dom.addEventListener(pauseBtn, 'click', function() {
        pauseAd();
        messages.success("ad paused");
      });
    }
    if (resumeBtn) {
      dom.addEventListener(resumeBtn, 'click', function() {
        resumeAd();
        messages.success("ad resumed");
      });
    }

    updateDemo();

    /*** Local functions ***/
    function updateVisibility() {
      dom.removeClass(formEl, 'TAG');
      dom.removeClass(formEl, 'XML');
      dom.removeClass(formEl, 'CUSTOM');
      dom.addClass(formEl, activeMode());
    }

    function pauseAd() {
      if (player) {
        player.vast.adUnit.pauseAd();
        pauseBtn.style.display = 'none';
        resumeBtn.style.display = 'inline-block';
      }
    }

    function resumeAd() {
      if (player) {
        player.vast.adUnit.resumeAd();
        pauseBtn.style.display = 'inline-block';
        resumeBtn.style.display = 'none';
      }
    }

    function updateDemo() {
      createVideoEl(videoContainer, function(videoEl) {
        var adsTag;
        var mode = activeMode();
        if (mode === 'TAG') {
          adsTag = tagEl.value;
        } else if (mode === 'XML') {
          adsTag = xmlEl.value;
        } else {
          adsTag = 'CUSTOM_AD_TAG' + new Date().getTime();
          custom_xhr[adsTag] = customEl.value;
        }

        player = videojs(videoEl, {
          "plugins": {
            "ads-setup":{
              "adCancelTimeout":20000,// Wait for ten seconds before canceling the ad.
              "adsEnabled": true,
              "adsTag": adsTag
            }
          }
        });

        //We hide the pause btn every time we update
        if(pauseBtn){
          pauseBtn.style.display = 'none';
        }

        player.on('vast.adStart', function() {
          pauseBtn.style.display = 'inline-block';
        });

        player.on('vast.adEnd', function() {
          pauseBtn.style.display = 'none';
        });
      });
    }

    function activeMode() {
      if (tagTypeEl.checked) {
        return 'TAG';
      }

      if (xmlTypeEl.checked) {
        return 'XML';
      }

      return 'CUSTOM'
    }

    function createVideoEl(container, cb) {
      var videoTag = '<video class="video-js vjs-default-skin" controls preload="auto" poster="http://video-js.zencoder.com/oceans-clip.png" >' +
        '<source src="http://video-js.zencoder.com/oceans-clip.mp4" type="video/mp4"/>' +
        '<source src="http://video-js.zencoder.com/oceans-clip.webm" type="video/webm"/>' +
        '<source src="http://video-js.zencoder.com/oceans-clip.ogv" type="video/ogg"/>' +
        '
To view this video please enable JavaScript, and consider upgrading to a web browser that ' +
        'supports HTML5 video' +
        '
' +
        '</video>';
      container.innerHTML = videoTag;

      //We do this asynchronously to give time for the dom to be updated
      setTimeout(function() {
        var videoEl = container.querySelector('.video-js');
        cb(videoEl);
      }, 0);
    }
  }
});<commit_msg>Adapted demo to changes on player.api<commit_after>var dom = require('./miniDom');
var adsSetupPlugin = require('./ads-setup-plugin');
var messages = require('./messages');
var custom_xhr = {};

xhook.before(function(request, callback) {
  var intercept_urls = Object.keys(custom_xhr);
  var i, len, match, intercept_url;

  for (i = 0, len = intercept_urls.length; i < len; i++) {
    intercept_url = intercept_urls[i];
    match = new RegExp(intercept_url + "$", "gi");
    if (request.url.match(match)) {
      return callback({
        status: 200,
        data: custom_xhr[intercept_url]
      });
    }
  }
  callback();
});

videojs.plugin('ads-setup', adsSetupPlugin);

dom.onReady(function() {
  var vastForm = document.querySelector('form#vast-form');
  var vpaidForm = document.querySelector('form#vpaid-form');

  initForm(vastForm);
  initForm(vpaidForm);

  /*** Local functions ***/
  function initForm(formEl) {
    var tagTypeEl = formEl.querySelector('input.tag-type-radio');
    var xmlTypeEl = formEl.querySelector('input.xml-type-radio');
    var customTypeEl = formEl.querySelector('input.custom-type-radio');
    var updateBtn = formEl.querySelector('.button.button-primary');
    var pauseBtn = formEl.querySelector('.pause');
    var resumeBtn = formEl.querySelector('.resume');
    var tagEl = formEl.querySelector('input.tag-el');
    var xmlEl = formEl.querySelector('select.xml-el');
    var customEl = formEl.querySelector('textarea.custom-el');
    var videoContainer = formEl.querySelector('div.vjs-video-container');
    var player;

    updateVisibility();
    dom.addEventListener(tagTypeEl, 'change', updateVisibility);
    dom.addEventListener(xmlTypeEl, 'change', updateVisibility);
    dom.addEventListener(customTypeEl, 'change', updateVisibility);
    dom.addEventListener(updateBtn, 'click', function() {
      updateDemo();
      messages.success("Demo updated!!!");
    });

    if (pauseBtn && resumeBtn) {
      dom.addEventListener(pauseBtn, 'click', function() {
        pauseAd();
        messages.success("ad paused");
      });

      dom.addEventListener(resumeBtn, 'click', function() {
        resumeAd();
        messages.success("ad resumed");
      });

    }

    updateDemo();

    /*** Local functions ***/
    function updateVisibility() {
      dom.removeClass(formEl, 'TAG');
      dom.removeClass(formEl, 'XML');
      dom.removeClass(formEl, 'CUSTOM');
      dom.addClass(formEl, activeMode());
    }

    function pauseAd() {
      if (player) {
        player.vast.adUnit.pauseAd();
        showResumeBtn();
      }
    }

    function resumeAd() {
      if (player) {
        player.vast.adUnit.resumeAd();
        showPauseBtn();
      }
    }

    function showResumeBtn(){
      pauseBtn.style.display = 'none';
      resumeBtn.style.display = 'inline-block';
    }

    function showPauseBtn(){
      pauseBtn.style.display = 'inline-block';
      resumeBtn.style.display = 'none';
    }

    function updateDemo() {
      createVideoEl(videoContainer, function(videoEl) {
        var adsTag;
        var mode = activeMode();
        if (mode === 'TAG') {
          adsTag = tagEl.value;
        } else if (mode === 'XML') {
          adsTag = xmlEl.value;
        } else {
          adsTag = 'CUSTOM_AD_TAG' + new Date().getTime();
          custom_xhr[adsTag] = customEl.value;
        }

        player = videojs(videoEl, {
          "plugins": {
            "ads-setup":{
              "adCancelTimeout":20000,// Wait for ten seconds before canceling the ad.
              "adsEnabled": true,
              "adsTag": adsTag
            }
          }
        });

        //We hide the pause and resume btns every time we update
        if (pauseBtn) {
          pauseBtn.style.display = 'none';
          resumeBtn.style.display = 'none';
        }

        if(player) {
          player.on('vast.adStart', function() {
            showPauseBtn();
            player.on('play', showPauseBtn);
            player.on('pause', showResumeBtn);
            player.one('vast.adEnd', function() {
              pauseBtn.style.display = 'none';
              resumeBtn.style.display = 'none';

              player.off('play', showPauseBtn);
              player.off('pause', showResumeBtn);
            });
          });
        }
      });
    }

    function activeMode() {
      if (tagTypeEl.checked) {
        return 'TAG';
      }

      if (xmlTypeEl.checked) {
        return 'XML';
      }

      return 'CUSTOM'
    }

    function createVideoEl(container, cb) {
      var videoTag = '<video class="video-js vjs-default-skin" controls preload="auto" poster="http://video-js.zencoder.com/oceans-clip.png" >' +
        '<source src="http://video-js.zencoder.com/oceans-clip.mp4" type="video/mp4"/>' +
        '<source src="http://video-js.zencoder.com/oceans-clip.webm" type="video/webm"/>' +
        '<source src="http://video-js.zencoder.com/oceans-clip.ogv" type="video/ogg"/>' +
        '
To view this video please enable JavaScript, and consider upgrading to a web browser that ' +
        'supports HTML5 video' +
        '
' +
        '</video>';
      container.innerHTML = videoTag;

      //We do this asynchronously to give time for the dom to be updated
      setTimeout(function() {
        var videoEl = container.querySelector('.video-js');
        cb(videoEl);
      }, 0);
    }
  }
});<|endoftext|>


<commit_before>let Diascope = window.Diascope;

let frame = document.querySelector('.js-diascope-frame');
let reel = document.querySelector('.js-diascope-reel');
let options = {
	step: 3,
	shouldCenter: true
};

new Diascope(frame, reel, options);
<commit_msg>Added navigate elements in options<commit_after>const Diascope = window.Diascope;

let frame, reel, navigateNext, navigatePrevious, options;

frame = document.querySelector('.js-diascope-frame');
reel = document.querySelector('.js-diascope-reel');
navigateNext = document.querySelector('.js-diascope-navigate-next');
navigatePrevious = document.querySelector('.js-diascope-navigate-previous');

options = {
	elementNavigateNext: navigateNext,
	elementNavigatePrevious: navigatePrevious,
};

new Diascope(frame, reel, options);
<|endoftext|>


<commit_before>import React from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBarIOS, TabBarItemIOS} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home', title: 'Home'},
  {key: 'notifications', title: 'Notifications'},
  {key: 'tweet', title: 'Tweet', trackCrumbTrail: true},
  {key: 'timeline', title: 'Timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

timeline.getTitle = ({sceneTitle}) => sceneTitle;
var getSceneTitle = (state, data) => {
  var {getTitle, title} = state;
  return getTitle ? getTitle(data) : title;
}

var notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');
notificationsNavigator.navigate('notifications');

export default () => (
  Platform.OS === 'ios' ? (
    <TabBarIOS>
      <TabBarItemIOS title="Home">
        <NavigationHandler stateNavigator={stateNavigator}>
          <NavigationStack
            title={getSceneTitle}>
          </NavigationStack>
        </NavigationHandler>
      </TabBarItemIOS>
      <TabBarItemIOS title="Notifications">
        <NavigationHandler stateNavigator={notificationsNavigator}>
          <NavigationStack
            title={getSceneTitle}>
            </NavigationStack>
        </NavigationHandler>
      </TabBarItemIOS>
    </TabBarIOS>
  ) : (
    <NavigationHandler stateNavigator={stateNavigator}>
      <NavigationStack
        crumbStyle={from => from ? 'scale_in' : 'scale_out'}
        unmountStyle={from => from ? 'slide_in' : 'slide_out'}>
      </NavigationStack>
    </NavigationHandler>
  )
);
<commit_msg>Tweaked format<commit_after>import React from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBarIOS, TabBarItemIOS} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home', title: 'Home'},
  {key: 'notifications', title: 'Notifications'},
  {key: 'tweet', title: 'Tweet', trackCrumbTrail: true},
  {key: 'timeline', title: 'Timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

timeline.getTitle = ({sceneTitle}) => sceneTitle;
var getSceneTitle = (state, data) => {
  var {getTitle, title} = state;
  return getTitle ? getTitle(data) : title;
}

var notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');
notificationsNavigator.navigate('notifications');

export default () => (
  Platform.OS === 'ios' ? (
    <TabBarIOS>
      <TabBarItemIOS title="Home">
        <NavigationHandler stateNavigator={stateNavigator}>
          <NavigationStack
            title={getSceneTitle}>
          </NavigationStack>
        </NavigationHandler>
      </TabBarItemIOS>
      <TabBarItemIOS title="Notifications">
        <NavigationHandler stateNavigator={notificationsNavigator}>
          <NavigationStack
            title={getSceneTitle}>
          </NavigationStack>
        </NavigationHandler>
      </TabBarItemIOS>
    </TabBarIOS>
  ) : (
    <NavigationHandler stateNavigator={stateNavigator}>
      <NavigationStack
        crumbStyle={from => from ? 'scale_in' : 'scale_out'}
        unmountStyle={from => from ? 'slide_in' : 'slide_out'}>
      </NavigationStack>
    </NavigationHandler>
  )
);
<|endoftext|>


<commit_before>'use strict';

const Client = require('../client'),
      CLI = require('./index');

class ClientCLI extends CLI {

  constructor(yargs) {

    this.client = false;

    super({
      type: 'client',
      yargs: yargs,
      required: 2
    });

  }

  setup() {

    if(! process.env.AIO_CLIENT_USER || ! process.env.AIO_CLIENT_KEY)
      return this.requireAuth(this.yargs);

    const options = {
      success: this.setupAPI.bind(this),
      failure: this.error.bind(this)
    };

    if(process.env.AIO_CLIENT_HOST)
      options.host = process.env.AIO_CLIENT_HOST;

    if(process.env.AIO_CLIENT_PORT)
      options.port = process.env.AIO_CLIENT_PORT;

    this.client = new Client(process.env.AIO_CLIENT_USER, process.env.AIO_CLIENT_KEY, options);

  }

  setupAPI() {

    this.yargs.usage('Usage: adafruit-io client <api> [options]');
    this.required = 1;

    this.yargs.command('config', 'configure the client', this.requireAuth.bind(this));

    const apis = this.client.swagger.apis;

    Object.keys(apis).forEach(api => {

      if(api === 'help') return;

      const lower = api.toLowerCase();

      this.yargs.command(lower, `${lower} API`, this.setupOperations.bind(this, api));

    });

    this.argv = this.yargs.help('help').wrap(null).argv;

  }

  setupOperations(api, yargs) {

    const operations = this.client.swagger.apis[api].operations;

    yargs.usage(`Usage: $0 client ${api} [options]`);

    Object.keys(operations).forEach(operation => {
      yargs.command(operation, operations[operation].summary, y => {
        this.info(`${api} ${operation}`);
      });
    });

    const argv = yargs
      .help('help')
      .updateStrings({
        'Commands:': 'Actions:'
      })
      .wrap(null)
      .argv;

  }

  requireAuth(yargs) {

    this.argv = yargs
      .usage('Usage: adafruit-io client [options]')
      .alias('h', 'host').nargs('h', 1).default('h','io.adafruit.com').describe('h', 'Server hostname')
      .alias('p', 'port').nargs('p', 1).default('p', '8080').describe('p', 'Server port')
      .alias('u', 'username').demand('username').nargs('u', 1).describe('u', 'Adafruit IO Username')
      .alias('k', 'key').demand('key').nargs('k', 1).describe('k', 'Adafruit IO Key')
      .help('help').wrap(null).argv;

    process.env.AIO_CLIENT_HOST = this.argv.host;
    process.env.AIO_CLIENT_PORT = this.argv.port;
    process.env.AIO_CLIENT_USER = this.argv.username;
    process.env.AIO_CLIENT_KEY  = this.argv.key;

    this.saveEnv();

    this.info('Client settings saved');

  }

}

exports = module.exports = ClientCLI;
<commit_msg>tweaks to cli client sub commands<commit_after>'use strict';

const Client = require('../client'),
      CLI = require('./index'),
      Yargs = require('yargs'),
      util = require('util');

class ClientCLI extends CLI {

  constructor() {

    super('client');

    this.yargs = Yargs(process.argv.slice(3));
    this.client = false;

    this.init();

  }

  init() {

    if(! process.env.AIO_CLIENT_USER || ! process.env.AIO_CLIENT_KEY)
      return this.requireAuth(this.yargs);

    const options = {
      success: this.setupAPI.bind(this, this.yargs),
      failure: this.error.bind(this)
    };

    if(process.env.AIO_CLIENT_HOST)
      options.host = process.env.AIO_CLIENT_HOST;

    if(process.env.AIO_CLIENT_PORT)
      options.port = process.env.AIO_CLIENT_PORT;

    this.client = new Client(process.env.AIO_CLIENT_USER, process.env.AIO_CLIENT_KEY, options);

  }

  setupAPI(yargs) {

    yargs
      .usage('Usage: adafruit-io client <command> [options]')
      .command('config', 'configure the client');

    const apis = this.client.swagger.apis;

    Object.keys(apis).forEach(api => {

      if(api === 'help') return;

      yargs.command(api.toLowerCase(), `Adafruit IO ${api} API commands`);

    });

    yargs.command('help', 'Show help');

    const argv = yargs
      .demand(1, 'You must supply a valid client command')
      .help('help').argv;

    const command = argv._[0];

    if(command === 'help')
      return yargs.showHelp();

    if(command === 'config')
      return this.requireAuth(Yargs(process.argv.slice(4)));

    this.setupOperations(command[0].toUpperCase() + command.slice(1), Yargs(process.argv.slice(4)));

  }

  setupOperations(api, yargs) {

    const operations = this.client.swagger.apis[api].operations;

    yargs.usage(`Usage: adafruit-io client ${api.toLowerCase()} <action>`);

    Object.keys(operations).forEach(operation => {
      yargs.command(operation, operations[operation].summary);
    });

    yargs.command('help', 'Show help');

    const argv = yargs
      .demand(1, 'you must supply a valid command')
      .updateStrings({
        'Commands:': 'Actions:'
      })
      .argv;

    const command = argv._[0];

    if(command === 'help')
      return yargs.showHelp();

    this.client[api][command]({}).then(res => this.info(util.inspect(res.obj))).catch(console.log);

  }

  requireAuth(yargs) {

    const argv = yargs
      .usage('Usage: adafruit-io client [options]')
      .alias('h', 'host').nargs('h', 1).default('h','io.adafruit.com').describe('h', 'Server hostname')
      .alias('p', 'port').nargs('p', 1).default('p', '8080').describe('p', 'Server port')
      .alias('u', 'username').demand('username').nargs('u', 1).describe('u', 'Adafruit IO Username')
      .alias('k', 'key').demand('key').nargs('k', 1).describe('k', 'Adafruit IO Key')
      .help('help').argv;

    process.env.AIO_CLIENT_HOST = argv.host;
    process.env.AIO_CLIENT_PORT = argv.port;
    process.env.AIO_CLIENT_USER = argv.username;
    process.env.AIO_CLIENT_KEY  = argv.key;

    this.saveEnv();

    this.info('Client settings saved');

  }

}

exports = module.exports = ClientCLI;
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* eslint-env node */
/* eslint-disable no-console */

const fs = require('fs');
const mongoose = require('mongoose');
const uuidV4 = require('uuid/v4');

const utils = require('./util');

const serverSchema = {
  _id: { type: String, required: true, default: uuidV4 },
  name: { type: String },
  domain: { type: String, required: true },
  description: { type: String },
  contacted: { type: Date, default: Date.now },
  keypair: {
    private: { type: String },
    public: { type: String, required: true }
  },
  authoritative: { type: Boolean, default: false },
  created: { type: Date, default: Date.now, required: true },
  updated: { type: Date, default: Date.now }
};

function createServer(datas) {
  return new Promise((resolve, reject) => {
    const Server = mongoose.model('Server', serverSchema);
    Server
      .findOne({ authoritative: true })
      .exec()
      . then((server) => {
        if (server) {
          return reject('An authoritative server already exists...');
        }
        return resolve(Server.create(datas));
      });
  });
}

function getAuthoritative() {
  return new Promise((resolve, reject) => {
    const Server = mongoose.model('Server', serverSchema);
    Server
      .findOne({ authoritative: true })
      .exec()
      .then((server) => {
        if (server) {
          return resolve(server);
        }
        return reject('No authoritative server was found...');
      })
      .catch(err => reject(err))
  });
};

module.exports.exportServer = function (options) {
  utils.mongooseConnect();
  let targetFile = options.file ? options.file : 'server.json';
  targetFile = targetFile.endsWith('.json') ? targetFile : targetFile.concat('.json');
  getAuthoritative()
    .then((server) => {
      fs.writeFile(targetFile, JSON.stringify(server), (err) => {
        if (err) {
          console.log(err);
          process.exit(1);
        }
        console.log(`Server records saved in ${targetFile}`);
        process.exit(0);
      });
    })
    .catch((err) => {
      console.log(err);
      process.exit(1);
    });
};

module.exports.newServer = function (domain, publicKeyFile, privateKeyFile, options) {
  utils.mongooseConnect();
  const validOptions = ['name', 'description'];
  if (!domain) {
    console.error('Domain missing');
    process.exit(1);
  } else if (!publicKeyFile) {
    console.error('Public key file path missing');
    process.exit(1);
  } else if (!privateKeyFile) {
    console.error('Private key file path missing');
  }

  const publicKey = fs.readFileSync(publicKeyFile, 'utf8');
  const privateKey = fs.readFileSync(privateKeyFile, 'utf8');

  const keypair = {
    public: publicKey,
    private: privateKey
  };

  const finalDatas = {
    domain, publicKeyFile, keypair
  };

  validOptions.forEach(function (i) {
    if (options[i] && typeof options[i] !== 'function') {
      finalDatas[i] = options[i];
    }
  });
  finalDatas.authoritative = true;
  createServer(finalDatas)
    .then(() => {
      console.log('Success !');
      process.exit(0);
    })
    .catch((e) => {
      console.error(e);
      process.exit(1);
    });
};
<commit_msg>lint + fixes<commit_after>#!/usr/bin/env node
/* eslint-env node */
/* eslint-disable no-console */

const fs = require('fs');
const mongoose = require('mongoose');
const uuidV4 = require('uuid/v4');

const utils = require('./util');

const serverSchema = {
  _id: { type: String, required: true, default: uuidV4 },
  name: { type: String },
  domain: { type: String, required: true },
  description: { type: String },
  contacted: { type: Date, default: Date.now },
  keypair: {
    private: { type: String },
    public: { type: String, required: true }
  },
  authoritative: { type: Boolean, default: false },
  created: { type: Date, default: Date.now, required: true },
  updated: { type: Date, default: Date.now }
};

function createServer(datas) {
  return new Promise((resolve, reject) => {
    const Server = mongoose.model('Server', serverSchema);
    Server
      .findOne({ authoritative: true })
      .exec()
      . then((server) => {
        if (server) {
          return reject('An authoritative server already exists...');
        }
        return resolve(Server.create(datas));
      });
  });
}

function getAuthoritative() {
  return new Promise((resolve, reject) => {
    const Server = mongoose.model('Server', serverSchema);
    Server
      .findOne({ authoritative: true })
      .exec()
      .then((server) => {
        if (server) {
          return resolve(server);
        }
        return reject('No authoritative server was found...');
      })
      .catch(err => reject(err));
  });
}

module.exports.exportServer = function (options) {
  utils.mongooseConnect();
  let targetFile = options.file ? options.file : 'server.json';
  targetFile = targetFile.endsWith('.json') ? targetFile : targetFile.concat('.json');
  getAuthoritative()
    .then((server) => {
      fs.writeFile(targetFile, JSON.stringify(server), (err) => {
        if (err) {
          console.log(err);
          process.exit(1);
        }
        console.log(`Server records saved in ${targetFile}`);
        process.exit(0);
      });
    })
    .catch((err) => {
      console.log(err);
      process.exit(1);
    });
};

module.exports.newServer = function (domain, publicKeyFile, privateKeyFile, options) {
  utils.mongooseConnect();
  const validOptions = ['name', 'description'];
  if (!domain) {
    console.error('Domain missing');
    process.exit(1);
  } else if (!publicKeyFile) {
    console.error('Public key file path missing');
    process.exit(1);
  } else if (!privateKeyFile) {
    console.error('Private key file path missing');
    process.exit(1);
  }

  const publicKey = fs.readFileSync(publicKeyFile, 'utf8');
  const privateKey = fs.readFileSync(privateKeyFile, 'utf8');

  const keypair = {
    public: publicKey,
    private: privateKey
  };

  const finalDatas = {
    domain, publicKeyFile, keypair
  };

  validOptions.forEach(function (i) {
    if (options[i] && typeof options[i] !== 'function') {
      finalDatas[i] = options[i];
    }
  });
  finalDatas.authoritative = true;
  createServer(finalDatas)
    .then(() => {
      console.log('Success !');
      process.exit(0);
    })
    .catch((e) => {
      console.error(e);
      process.exit(1);
    });
};
<|endoftext|>


<commit_before>// global variables

// TODO: button sizes proportional to duration
// TODO: autoplay controls that periodically start sounds in order to reach desired average density
// TODO: weight random choice of sound to pick short ones more often

window.AudioContext = window.AudioContext||window.webkitAudioContext;

var theCollection = new FreesoundCollection(new AudioContext());

var gTemplates = {};

// create a play button for the sound info

function displaySoundInfo(inSearchText, inInfo) {
    // add the newly created element and its content into the DOM
    var containerDiv = $('tbody[data-search="' + inSearchText + '"]');
    containerDiv.append(gTemplates['sound-button'](inInfo));

    $('#play-sound-' + inInfo.id).click(function(event) {
        console.log('clicked', event);
        theCollection.onPlayButtonClicked(inInfo);
    });

    //TODO: combine with FreesoundCollection.prototype.handleBufferSourceListUpdated
    $('.remove-sound[data-sound-id="'+inInfo.id+'"]').click(function(event) {
        console.log('remove-sound', event.target);
        // stop playing,  remove from arrays, notify observers
        theCollection.deleteBufferForID(inInfo.id);
        // remove from table`
        $('#sound-button-row-' + inInfo.id).remove();
    }.bind(this));
}

// respond to an update in the buffer list by updating the count

function handleBufferListUpdate(inID) {
    var bufferCount = Object.keys(theCollection.bufferByID).length;

    if (theCollection.bufferByID[inID]) {
        console.log('buffer list adding', theCollection.soundInfoByID[inID].name);
        $('#autoplayon').removeAttr('disabled');
    } else {
        console.log('buffer list removing', inID);

        if (bufferCount == 0) {
            $('#autoplayon').attr('disabled', 'true');
        }
    }
}

// handle the event handler by starting a Freesound text search

function doSearch(inString) {

    $('#soundcontainer').append(gTemplates['search-results']({term: inString}));

    $('button[data-search-term="' + inString + '"]').click(function(e) {
        var searchTerm = e.target.getAttribute('data-search-term');
        deleteBuffersForSearch(searchTerm);

        // remove whole category
        $('div[data-search="' + inString + '"]').remove();
        delete gSearchHistory[searchTerm];
    });

    console.log('about to search', inString);
    theCollection.search(inString);
}

// handle search event by tokenizing the string and doing a separate search for each token

function handleSearch(event) {
    event.preventDefault();

    var searchText = document.getElementById('searchtext').value;
    console.log('handleSearh', searchText);

    var stringTokens = searchText.split(' ');
    for (var index = 0; index < stringTokens.length; index++) {
        doSearch(stringTokens[index]);
    }
}

// choose a random ID from the buffer dictionary and start playing

function autoPlayTask() {
    var autoPlayCount = document.getElementById('autoplaycount').value;
    var autoPlayDelay = document.getElementById('autoplaydelay').value;

    // if autoplay still checked
    if (document.getElementById('autoplayon').checked) {
        // and there's not enough sounds playing
        if (Object.keys(theCollection.bufferSourceByID).length < autoPlayCount) {
            console.log('autoplay random buffer');
            theCollection.playRandomBuffer();
        } else {
            console.log('autoPlayTask do nothing')
        }

        // do it again soon
        window.setTimeout(autoPlayTask, 1000 * autoPlayDelay);
    } else {
        console.log('autoPlayTask already off');
    }
}

function handleAutoPlay(event) {
    var autoPlayDelay = document.getElementById('autoplaydelay').value;

    if (event.target.checked) {
        console.log('autoplay', event.target.checked, autoPlayDelay);
        window.setTimeout(autoPlayTask, 1000 * autoPlayDelay);
    } else {
        console.log('stop all');
        for (var bufferSourceID in theCollection.bufferSourceByID) {
            console.log('STOP', bufferSourceID);
            theCollection.bufferSourceByID[bufferSourceID].stop();
        }
    }
}

function elapsedTask() {
    var timers = document.querySelectorAll('.elapsed');

    if (timers) {
        for (var index = 0; index < timers.length; index++) {
            var delta = new Date() - new Date(timers[index].getAttribute('data-starttime'));
            timers[index].innerHTML = Math.round(delta / 1000);
        }
    }
    window.setTimeout(elapsedTask, 1000);
}

// when the window is loaded, set up search and play event handlers

window.onload = function(){
    document.getElementById('autoplayon').checked = false;

    gTemplates['sound-button'] = Handlebars.compile($('#sound-button-template').html());
    gTemplates['search-results'] = Handlebars.compile($('#search-results-template').html());
    gTemplates['buffer-playing'] = Handlebars.compile($('#buffer-playing-template').html());

    Handlebars.registerHelper('round', function (num) {
        return Math.round(num);
    });

    document.getElementById('searchbutton').addEventListener('click', handleSearch);
    document.getElementById('autoplayon').addEventListener('click', handleAutoPlay);

    console.log('start moo');
    window.setTimeout(elapsedTask, 1000);
};

// Check if the Web MIDI API is supported by the browser
if (navigator.requestMIDIAccess) {
    navigator.requestMIDIAccess().then(midiSucess, midiFailure);
} else {
    console.log("Web MIDI API not supported!");
}

function dispatchMIDIMessage(message) {
{
    // Mask off the lower nibble (MIDI channel, which we don't care about)
    switch (event.data[0] & 0xf0) {
        case 0x90:
            if (event.data[2]!=0) {  // if velocity != 0, this is a note-on message
                console.log('START', event.data[1]);
                playRandomBuffer();
                return;
            }
        // if velocity == 0, fall thru: it's a note-off.  MIDI's weird, y'all.
        case 0x80:
            console.log('STOP', event.data[1]);
            return;
        case 0xA0:
            console.log('aftertouch', event.data[1], event.data[2]);
            return;
        case 0xB0:
            console.log('knob', event.data[1], event.data[2]);
            return;
        case 0xC0:
            console.log('patch change', event.data[1], event.data[2]);
            return;
        case 0xD0:
            console.log('channel pressure', event.data[1], event.data[2]);
            return;
        case 0xE0:
            console.log('pitch bend', event.data[1], event.data[2]);
            return;
        }
    }
}

// Function executed on successful connection
function midiSucess(interface) {
    // Grab an array of all available devices
    var iter = interface.inputs.values();

    for (var i = iter.next(); i && !i.done; i = iter.next()) {
        console.log('input', i.value);
        i.value.addEventListener('midimessage', function (e) {
            dispatchMIDIMessage(e);
        });
    }
}

// Function executed on failed connection
function midiFailure(error) {
    console.log("Could not connect to the MIDI interface", error);
}
<commit_msg>fix code when removing category<commit_after>// global variables

// TODO: button sizes proportional to duration
// TODO: autoplay controls that periodically start sounds in order to reach desired average density
// TODO: weight random choice of sound to pick short ones more often

window.AudioContext = window.AudioContext||window.webkitAudioContext;

var theCollection = new FreesoundCollection(new AudioContext());

var gTemplates = {};

// create a play button for the sound info

function displaySoundInfo(inSearchText, inInfo) {
    // add the newly created element and its content into the DOM
    var containerDiv = $('tbody[data-search="' + inSearchText + '"]');
    containerDiv.append(gTemplates['sound-button'](inInfo));

    $('#play-sound-' + inInfo.id).click(function(event) {
        console.log('clicked', event);
        theCollection.onPlayButtonClicked(inInfo);
    });

    //TODO: combine with FreesoundCollection.prototype.handleBufferSourceListUpdated
    $('.remove-sound[data-sound-id="'+inInfo.id+'"]').click(function(event) {
        console.log('remove-sound', event.target);
        // stop playing,  remove from arrays, notify observers
        theCollection.deleteBufferForID(inInfo.id);
        // remove from table`
        $('#sound-button-row-' + inInfo.id).remove();
    }.bind(this));
}

// respond to an update in the buffer list by updating the count

function handleBufferListUpdate(inID) {
    var bufferCount = Object.keys(theCollection.bufferByID).length;

    if (theCollection.bufferByID[inID]) {
        console.log('buffer list adding', theCollection.soundInfoByID[inID].name);
        $('#autoplayon').removeAttr('disabled');
    } else {
        console.log('buffer list removing', inID);

        if (bufferCount == 0) {
            $('#autoplayon').attr('disabled', 'true');
        }
    }
}

// handle the event handler by starting a Freesound text search

function doSearch(inString) {

    $('#soundcontainer').append(gTemplates['search-results']({term: inString}));

    $('button[data-search-term="' + inString + '"]').click(function(e) {
        var searchTerm = e.target.getAttribute('data-search-term');
        theCollection.deleteBuffersForSearch(searchTerm);

        // remove whole category
        $('div[data-search="' + inString + '"]').remove();
        delete gSearchHistory[searchTerm];
    });

    console.log('about to search', inString);
    theCollection.search(inString);
}

// handle search event by tokenizing the string and doing a separate search for each token

function handleSearch(event) {
    event.preventDefault();

    var searchText = document.getElementById('searchtext').value;
    console.log('handleSearh', searchText);

    var stringTokens = searchText.split(' ');
    for (var index = 0; index < stringTokens.length; index++) {
        doSearch(stringTokens[index]);
    }
}

// choose a random ID from the buffer dictionary and start playing

function autoPlayTask() {
    var autoPlayCount = document.getElementById('autoplaycount').value;
    var autoPlayDelay = document.getElementById('autoplaydelay').value;

    // if autoplay still checked
    if (document.getElementById('autoplayon').checked) {
        // and there's not enough sounds playing
        if (Object.keys(theCollection.bufferSourceByID).length < autoPlayCount) {
            console.log('autoplay random buffer');
            theCollection.playRandomBuffer();
        } else {
            console.log('autoPlayTask do nothing')
        }

        // do it again soon
        window.setTimeout(autoPlayTask, 1000 * autoPlayDelay);
    } else {
        console.log('autoPlayTask already off');
    }
}

function handleAutoPlay(event) {
    var autoPlayDelay = document.getElementById('autoplaydelay').value;

    if (event.target.checked) {
        console.log('autoplay', event.target.checked, autoPlayDelay);
        window.setTimeout(autoPlayTask, 1000 * autoPlayDelay);
    } else {
        console.log('stop all');
        for (var bufferSourceID in theCollection.bufferSourceByID) {
            console.log('STOP', bufferSourceID);
            theCollection.bufferSourceByID[bufferSourceID].stop();
        }
    }
}

function elapsedTask() {
    var timers = document.querySelectorAll('.elapsed');

    if (timers) {
        for (var index = 0; index < timers.length; index++) {
            var delta = new Date() - new Date(timers[index].getAttribute('data-starttime'));
            timers[index].innerHTML = Math.round(delta / 1000);
        }
    }
    window.setTimeout(elapsedTask, 1000);
}

// when the window is loaded, set up search and play event handlers

window.onload = function(){
    document.getElementById('autoplayon').checked = false;

    gTemplates['sound-button'] = Handlebars.compile($('#sound-button-template').html());
    gTemplates['search-results'] = Handlebars.compile($('#search-results-template').html());
    gTemplates['buffer-playing'] = Handlebars.compile($('#buffer-playing-template').html());

    Handlebars.registerHelper('round', function (num) {
        return Math.round(num);
    });

    document.getElementById('searchbutton').addEventListener('click', handleSearch);
    document.getElementById('autoplayon').addEventListener('click', handleAutoPlay);

    console.log('start moo');
    window.setTimeout(elapsedTask, 1000);
};

// Check if the Web MIDI API is supported by the browser
if (navigator.requestMIDIAccess) {
    navigator.requestMIDIAccess().then(midiSucess, midiFailure);
} else {
    console.log("Web MIDI API not supported!");
}

function dispatchMIDIMessage(message) {
{
    // Mask off the lower nibble (MIDI channel, which we don't care about)
    switch (event.data[0] & 0xf0) {
        case 0x90:
            if (event.data[2]!=0) {  // if velocity != 0, this is a note-on message
                console.log('START', event.data[1]);
                playRandomBuffer();
                return;
            }
        // if velocity == 0, fall thru: it's a note-off.  MIDI's weird, y'all.
        case 0x80:
            console.log('STOP', event.data[1]);
            return;
        case 0xA0:
            console.log('aftertouch', event.data[1], event.data[2]);
            return;
        case 0xB0:
            console.log('knob', event.data[1], event.data[2]);
            return;
        case 0xC0:
            console.log('patch change', event.data[1], event.data[2]);
            return;
        case 0xD0:
            console.log('channel pressure', event.data[1], event.data[2]);
            return;
        case 0xE0:
            console.log('pitch bend', event.data[1], event.data[2]);
            return;
        }
    }
}

// Function executed on successful connection
function midiSucess(interface) {
    // Grab an array of all available devices
    var iter = interface.inputs.values();

    for (var i = iter.next(); i && !i.done; i = iter.next()) {
        console.log('input', i.value);
        i.value.addEventListener('midimessage', function (e) {
            dispatchMIDIMessage(e);
        });
    }
}

// Function executed on failed connection
function midiFailure(error) {
    console.log("Could not connect to the MIDI interface", error);
}
<|endoftext|>


<commit_before>'use strict';
var chalk = require('chalk');
var table = require('text-table');
var logSymbols = require('log-symbols');
var stringLength = require('string-length');

function pluralize(str, count) {
	return str + (count === 1 ? '' : 's');
}

module.exports = {
	reporter: function (result, config, options) {
		var total = result.length;
		var ret = '';
		var headers = [];
		var prevfile;
		var errorCount = 0;
		var warningCount = 0;

		options = options || {};

		ret += table(result.map(function (el, i) {
			var err = el.error;
			// E: Error, W: Warning, I: Info
			var isError = err.code && err.code[0] === 'E';

			var line = [
				'',
				chalk.gray('line ' + err.line),
				chalk.gray('col ' + err.character),
				isError ? chalk.red(err.reason) : (process.platform !== 'win32' ? chalk.blue(err.reason) : chalk.cyan(err.reason))
			];

			if (el.file !== prevfile) {
				headers[i] = el.file;
			}

			if (options.verbose) {
				line.push(chalk.gray('(' + err.code + ')'));
			}

			if (isError) {
				errorCount++;
			} else {
				warningCount++;
			}

			prevfile = el.file;

			return line;
		}), {
			stringLength: stringLength
		}).split('\n').map(function (el, i) {
			return headers[i] ? '\n' + chalk.underline(headers[i]) + '\n' + el : el;
		}).join('\n') + '\n\n';

		if (total > 0) {
			if (errorCount > 0) {
				ret += '  ' + logSymbols.error + '  ' + errorCount + pluralize(' error', errorCount) + (warningCount > 0 ? '\n' : '');
			}

			ret += '  ' + logSymbols.warning + '  ' + warningCount + pluralize(' warning', total);
		} else {
			ret += '  ' + logSymbols.success + ' No problems';
			ret = '\n' + ret.trim();
		}

		console.log(ret + '\n');
	}
};
<commit_msg>remove blur color windows hack now that chalk fixes it for us<commit_after>'use strict';
var chalk = require('chalk');
var table = require('text-table');
var logSymbols = require('log-symbols');
var stringLength = require('string-length');

function pluralize(str, count) {
	return str + (count === 1 ? '' : 's');
}

module.exports = {
	reporter: function (result, config, options) {
		var total = result.length;
		var ret = '';
		var headers = [];
		var prevfile;
		var errorCount = 0;
		var warningCount = 0;

		options = options || {};

		ret += table(result.map(function (el, i) {
			var err = el.error;
			// E: Error, W: Warning, I: Info
			var isError = err.code && err.code[0] === 'E';

			var line = [
				'',
				chalk.gray('line ' + err.line),
				chalk.gray('col ' + err.character),
				isError ? chalk.red(err.reason) : chalk.blue(err.reason)
			];

			if (el.file !== prevfile) {
				headers[i] = el.file;
			}

			if (options.verbose) {
				line.push(chalk.gray('(' + err.code + ')'));
			}

			if (isError) {
				errorCount++;
			} else {
				warningCount++;
			}

			prevfile = el.file;

			return line;
		}), {
			stringLength: stringLength
		}).split('\n').map(function (el, i) {
			return headers[i] ? '\n' + chalk.underline(headers[i]) + '\n' + el : el;
		}).join('\n') + '\n\n';

		if (total > 0) {
			if (errorCount > 0) {
				ret += '  ' + logSymbols.error + '  ' + errorCount + pluralize(' error', errorCount) + (warningCount > 0 ? '\n' : '');
			}

			ret += '  ' + logSymbols.warning + '  ' + warningCount + pluralize(' warning', total);
		} else {
			ret += '  ' + logSymbols.success + ' No problems';
			ret = '\n' + ret.trim();
		}

		console.log(ret + '\n');
	}
};
<|endoftext|>