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

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

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

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

            });
        }

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

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

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

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

        });
    }

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

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

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

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

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

        }

    }

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

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

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

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

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

            }
        });
    }
}

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

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

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

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

            });
        }

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

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

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

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

        });
    }

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

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

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

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

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

        }

    }

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

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

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

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

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

            }
        });
    }
}

<|endoftext|>


<commit_before>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 2.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.SelfService = {

    autoLogoutTimer : 180,
    currentLogoutTimer : 0,

    init : function() {
        foodcoopshop.ModalLogout.init(document.location.href);
        this.initWindowResize();
        if (!foodcoopshop.Helper.isMobile()) {
            this.initAutoLogout();
        }
        this.initSearchForm();
        this.initDepositPayment();
    },

    isMobileBarcodeScanningSupported : function() {
        return navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function';
    },

    bindCameraButtonToggle : function() {

        var button = $('.btn-toggle-camera');

        button.on('click', function() {

            var elementToToggle = $('#camera');
            var toggleMode = elementToToggle.css('display');

            if (toggleMode == 'none') {
                foodcoopshop.SelfService.initMobileBarcodeScanning();
            } else {
                Quagga.stop();
            }

            elementToToggle.animate({
                height: 'toggle'
            }, 400);

            $('body,html').animate({
                scrollTop: 0
            }, 400);
        });

        button.trigger('click');

    },

    initMobileBarcodeScanning : function() {

        if (!foodcoopshop.SelfService.isMobileBarcodeScanningSupported()) {
            return;
        }

        var onQuaggaLoad = null;
        if ($(this)[0].onQuaggaLoad) {
            onQuaggaLoad = $(this)[0].onQuaggaLoad;
        }

        if ($('#camera').length == 0) {
            $('#content .header').after($('
').attr('id', 'camera').height(200).hide());
        }

        Quagga.init({
            inputStream : {
                name : "Live",
                type : "LiveStream",
                target: document.querySelector('#camera')
            },
            decoder : {
                readers : ["code_39_reader"]
            },
          }, function(err) {
              if (err) {
                  console.log(err);
                  return;
              }

              Quagga.start();

              if (onQuaggaLoad) {
                onQuaggaLoad();
              }

          });

          Quagga.offDetected();
          Quagga.onDetected(function(result) {
              Quagga.stop();
              $('#camera').hide();
              var button = $('.btn-toggle-camera');
              foodcoopshop.Helper.addSpinnerToButton(button, 'fa-camera');
              foodcoopshop.Helper.disableButton(button);
              var redirectUrl = '/selbstbedienung?keyword=' + result.codeResult.code;
              document.location.href = redirectUrl;
          });

    },

    initLoginForm : function() {

        var barcodeInputField = $('#barcode');
        barcodeInputField.on('keyup focus', function (e) {
            $(this).prop('type', 'password'); // to avoid autocomplete
        });

        var loginForm = $('#LoginForm');
        var formIsSubmitted = false;
        loginForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        barcodeInputField.on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
            }, 1000)
        );

        barcodeInputField.focus();

    },

    initDepositPayment : function() {
        foodcoopshop.ModalPaymentAdd.initDepositSingle('.btn-add-deposit', $('#add-payment-deposit-form'));
    },

    initSearchForm : function() {

        var searchForm = $('#product-search');

        var formIsSubmitted = false;
        searchForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        if (!foodcoopshop.Helper.isMobile()) {
            foodcoopshop.Helper.initBootstrapSelect(searchForm);
        }
        searchForm.find('select, input[type="text"]').on('change', function() {
            foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
        });
        searchForm.find('select, input[type="text"]').on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
            }, 1000)
        );

        searchForm.find('input[type="text"]').focus();
    },

    submitForm : function(searchForm, icon) {
        var submitButton = searchForm.find('.btn[type="submit"]');
        foodcoopshop.Helper.addSpinnerToButton(submitButton, icon);
        foodcoopshop.Helper.disableButton(submitButton);
        searchForm.submit();
    },

    initHighlightedProductId: function(productId) {
        var rowId = '#product-wrapper-' + productId;
        $.scrollTo(rowId, 1000, {
            offset: {
                top: -100
            }
        });
        $(rowId).css('background-color', '#f3515c');
        $(rowId).css('color', 'white');
        $(rowId).one('mouseover', function () {
            $(this).removeAttr('style');
        });
        $(rowId).find('.quantity-in-units-input-field-wrapper input').focus();
    },

    initCartErrors: function (cartErrors) {
        cartErrors = $.parseJSON(cartErrors);
        for (var key in cartErrors) {
            var productContainer = $('#cart .product.' + key);
            productContainer.addClass('error');
            productContainer.after('

' + cartErrors[key].join('

') + '

');
        }
    },

    initWindowResize: function () {
        $(window).on('resize', function () {
            foodcoopshop.SelfService.onWindowResize();
        });
        foodcoopshop.SelfService.onWindowResize();
    },

    setFocusToSearchInputField : function() {
        $('#product-search input[name="keyword"]').focus();
    },

    onWindowResize : function() {
        $('.right-box').css('max-height', parseInt($(window).height()));
    },

    initAutoLogout : function() {

        this.resetTimer();
        this.renderTimer();

        $(document).idle({
            startAtIdle : true,
            onActive: function(){
                foodcoopshop.SelfService.resetTimer();
                foodcoopshop.SelfService.renderTimer();
            },
            onIdle: function() {
                foodcoopshop.SelfService.currentLogoutTimer--;
                foodcoopshop.SelfService.renderTimer();
                if (foodcoopshop.SelfService.currentLogoutTimer == 0) {
                    document.location.href = '/' + foodcoopshop.LocalizedJs.helper.routeLogout + '?redirect=' + document.location.href;
                }
            },
            recurIdleCall : true,
            idle: 1000
        });

    },

    resetTimer : function() {
        this.currentLogoutTimer = this.autoLogoutTimer;
    },

    renderTimer : function() {
        $('.auto-logout-timer').html(this.currentLogoutTimer);
    }

};<commit_msg>video was too big after second click<commit_after>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 2.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.SelfService = {

    autoLogoutTimer : 180,
    currentLogoutTimer : 0,

    init : function() {
        foodcoopshop.ModalLogout.init(document.location.href);
        this.initWindowResize();
        if (!foodcoopshop.Helper.isMobile()) {
            this.initAutoLogout();
        }
        this.initSearchForm();
        this.initDepositPayment();
    },

    isMobileBarcodeScanningSupported : function() {
        return navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function';
    },

    bindCameraButtonToggle : function() {

        var button = $('.btn-toggle-camera');

        button.on('click', function() {

            var elementToToggle = $('#camera');
            var toggleMode = elementToToggle.css('display');

            if (toggleMode == 'none') {
                foodcoopshop.SelfService.initMobileBarcodeScanning();
            } else {
                Quagga.stop();
            }

            elementToToggle.animate({
                height: 'toggle'
            }, 400);

            $('body,html').animate({
                scrollTop: 0
            }, 400);
        });

    },

    initMobileBarcodeScanning : function() {

        if (!foodcoopshop.SelfService.isMobileBarcodeScanningSupported()) {
            return;
        }

        var onQuaggaLoad = null;
        if ($(this)[0].onQuaggaLoad) {
            onQuaggaLoad = $(this)[0].onQuaggaLoad;
        }

        $('#camera').remove();
        $('#content .header').after($('
').attr('id', 'camera').height(200).hide());

        Quagga.init({
            inputStream : {
                name : "Live",
                type : "LiveStream",
                target: document.querySelector('#camera')
            },
            decoder : {
                readers : ["code_39_reader"]
            },
          }, function(err) {
              if (err) {
                  console.log(err);
                  return;
              }

              Quagga.start();

              if (onQuaggaLoad) {
                onQuaggaLoad();
              }

              $('#camera').animate({
                  height: 'toggle'
              }, 400);

          });

          Quagga.offDetected();
          Quagga.onDetected(function(result) {
              Quagga.stop();
              $('#camera').remove();
              var button = $('.btn-toggle-camera');
              foodcoopshop.Helper.addSpinnerToButton(button, 'fa-camera');
              foodcoopshop.Helper.disableButton(button);
              var redirectUrl = '/selbstbedienung?keyword=' + result.codeResult.code;
              document.location.href = redirectUrl;
          });

    },

    initLoginForm : function() {

        var barcodeInputField = $('#barcode');
        barcodeInputField.on('keyup focus', function (e) {
            $(this).prop('type', 'password'); // to avoid autocomplete
        });

        var loginForm = $('#LoginForm');
        var formIsSubmitted = false;
        loginForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        barcodeInputField.on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(loginForm, 'fa-sign-in-alt');
            }, 1000)
        );

        barcodeInputField.focus();

    },

    initDepositPayment : function() {
        foodcoopshop.ModalPaymentAdd.initDepositSingle('.btn-add-deposit', $('#add-payment-deposit-form'));
    },

    initSearchForm : function() {

        var searchForm = $('#product-search');

        var formIsSubmitted = false;
        searchForm.on('submit', function(e) {
            if (formIsSubmitted) {
                return false;
            }
            formIsSubmitted = true;
        });

        if (!foodcoopshop.Helper.isMobile()) {
            foodcoopshop.Helper.initBootstrapSelect(searchForm);
        }
        searchForm.find('select, input[type="text"]').on('change', function() {
            foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
        });
        searchForm.find('select, input[type="text"]').on('keypress', foodcoopshop.Helper.debounce(
            function() {
                foodcoopshop.SelfService.submitForm(searchForm, 'fa-search');
            }, 1000)
        );

        searchForm.find('input[type="text"]').focus();
    },

    submitForm : function(searchForm, icon) {
        var submitButton = searchForm.find('.btn[type="submit"]');
        foodcoopshop.Helper.addSpinnerToButton(submitButton, icon);
        foodcoopshop.Helper.disableButton(submitButton);
        searchForm.submit();
    },

    initHighlightedProductId: function(productId) {
        var rowId = '#product-wrapper-' + productId;
        $.scrollTo(rowId, 1000, {
            offset: {
                top: -100
            }
        });
        $(rowId).css('background-color', '#f3515c');
        $(rowId).css('color', 'white');
        $(rowId).one('mouseover', function () {
            $(this).removeAttr('style');
        });
        $(rowId).find('.quantity-in-units-input-field-wrapper input').focus();
    },

    initCartErrors: function (cartErrors) {
        cartErrors = $.parseJSON(cartErrors);
        for (var key in cartErrors) {
            var productContainer = $('#cart .product.' + key);
            productContainer.addClass('error');
            productContainer.after('

' + cartErrors[key].join('

') + '

');
        }
    },

    initWindowResize: function () {
        $(window).on('resize', function () {
            foodcoopshop.SelfService.onWindowResize();
        });
        foodcoopshop.SelfService.onWindowResize();
    },

    setFocusToSearchInputField : function() {
        $('#product-search input[name="keyword"]').focus();
    },

    onWindowResize : function() {
        $('.right-box').css('max-height', parseInt($(window).height()));
    },

    initAutoLogout : function() {

        this.resetTimer();
        this.renderTimer();

        $(document).idle({
            startAtIdle : true,
            onActive: function(){
                foodcoopshop.SelfService.resetTimer();
                foodcoopshop.SelfService.renderTimer();
            },
            onIdle: function() {
                foodcoopshop.SelfService.currentLogoutTimer--;
                foodcoopshop.SelfService.renderTimer();
                if (foodcoopshop.SelfService.currentLogoutTimer == 0) {
                    document.location.href = '/' + foodcoopshop.LocalizedJs.helper.routeLogout + '?redirect=' + document.location.href;
                }
            },
            recurIdleCall : true,
            idle: 1000
        });

    },

    resetTimer : function() {
        this.currentLogoutTimer = this.autoLogoutTimer;
    },

    renderTimer : function() {
        $('.auto-logout-timer').html(this.currentLogoutTimer);
    }

};<|endoftext|>


<commit_before>(function () {
	"use strict";

	Math.randomLimit = function (min, max) {
		/// <param name="min" type="Number"></param>
		/// <param name="max" type="Number"></param>
		/// <returns type="Number"></returns>
		return Math.floor(Math.random() * (max - min + 1) + min);
	};

	String.prototype.format = function (array) {
		/// <param name="array" type="Array" elementType="String"></param>
		/// <returns type="String"></returns>
		var theString = this.toString();

		for (var i = 0; i < array.length; i++) {
			var regEx = new RegExp("\\{" + (i) + "\\}", "gm");
			theString = theString.replace(regEx, array[i]);
		}

		return theString;
	};

	String.format = function (text, array) {
		/// <param name="text" type="String"></param>
		/// <param name="array" type="Array" elementType="String"></param>
		/// <returns type="String"></returns>
		return text.format(array);
	};

	String.prototype.randomLimit = function(size) {
		var option = this;
		var text = '';

		for(var i = 0; i < size; i++){
			text += option.charAt(Math.floor(Math.random() * option.length));
		}

		return text;
	};

	String.randomString = function(size, kase) {
		var option = 'abcdefghijklmnopqrstuvwxyz0123456789';
		if(kase){
			option = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		}

		return option.randomLimit(size);
	};

	Array.prototype.removeFirstItem = function (item) {
	  var pos = this.indexOf(item);
	  if (pos > -1) {
	    this.splice(pos, 1);
	  }
	};

	Array.prototype.removeLastItem = function (item) {
	  var pos = this.lastIndexOf(item);
	  if (pos > -1) {
	    this.splice(pos, 1);
	  }
	};

	Array.prototype.removeAllItems = function (item) {
	  for (var i = this.length - 1; i >= 0; i--) {
	    if (this[i] == item) {
	      this.splice(i, 1);
	    }
	  }
	};

	Array.prototype.insert = function(index, item){
		this.splice(index, 0, item);
	};

	Array.insert = function(array, index, item){
		array.insert(index, item);
	};

	Array.prototype.first = function () {
	  return this[0];
	};

	Array.prototype.last = function () {
	  return this[this.length - 1];
	};

	Array.create = function(dimensions, value) {
    // Create new array
    var array = new Array(dimensions[0] || 0);
    var i = dimensions[0];

    // If dimensions array's length is bigger than 1
    // we start creating arrays in the array elements with recursions
    // to achieve multidimensional array
    if (dimensions.length > 1) {
	    // Remove the first value from the array
	    var args = Array.prototype.slice.call(dimensions, 1);
	    // For each index in the created array create a new array with recursion
	    while(i--) {
	        array[dimensions[0]-1 - i] = Array.create(args, value);
	    }
    // If there is only one element left in the dimensions array
    // assign value to each of the new array's elements if value is set as param
    } else {
      if (typeof value !== 'undefined') {
        while(i--) {
            array[dimensions[0]-1 - i] = value;
        }
      }
    }

    return array;
	};

})();<commit_msg>add "contains" functions to String and String.prototype<commit_after>(function () {
	"use strict";

	Math.randomLimit = function (min, max) {
		/// <param name="min" type="Number"></param>
		/// <param name="max" type="Number"></param>
		/// <returns type="Number"></returns>
		return Math.floor(Math.random() * (max - min + 1) + min);
	};

	String.prototype.format = function (array) {
		/// <param name="array" type="Array" elementType="String"></param>
		/// <returns type="String"></returns>
		var theString = this.toString();

		for (var i = 0; i < array.length; i++) {
			var regEx = new RegExp("\\{" + (i) + "\\}", "gm");
			theString = theString.replace(regEx, array[i]);
		}

		return theString;
	};

	String.format = function (text, array) {
		/// <param name="text" type="String"></param>
		/// <param name="array" type="Array" elementType="String"></param>
		/// <returns type="String"></returns>
		return text.format(array);
	};

	String.prototype.randomLimit = function(size) {
		var option = this;
		var text = '';

		for(var i = 0; i < size; i++){
			text += option.charAt(Math.floor(Math.random() * option.length));
		}

		return text;
	};

	String.randomString = function(size, kase) {
		var option = 'abcdefghijklmnopqrstuvwxyz0123456789';
		if(kase){
			option = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		}

		return option.randomLimit(size);
	};

	String.prototype.contains = function(contain) {
		return this.indexOf(contain) != -1;
	};

	String.contains = function(str, contain) {
		return str.contains(contain);
	};

	Array.prototype.removeFirstItem = function (item) {
	  var pos = this.indexOf(item);
	  if (pos > -1) {
	    this.splice(pos, 1);
	  }
	};

	Array.prototype.removeLastItem = function (item) {
	  var pos = this.lastIndexOf(item);
	  if (pos > -1) {
	    this.splice(pos, 1);
	  }
	};

	Array.prototype.removeAllItems = function (item) {
	  for (var i = this.length - 1; i >= 0; i--) {
	    if (this[i] == item) {
	      this.splice(i, 1);
	    }
	  }
	};

	Array.prototype.insert = function(index, item){
		this.splice(index, 0, item);
	};

	Array.insert = function(array, index, item){
		array.insert(index, item);
	};

	Array.prototype.first = function () {
	  return this[0];
	};

	Array.prototype.last = function () {
	  return this[this.length - 1];
	};

	Array.create = function(dimensions, value) {
    // Create new array
    var array = new Array(dimensions[0] || 0);
    var i = dimensions[0];

    // If dimensions array's length is bigger than 1
    // we start creating arrays in the array elements with recursions
    // to achieve multidimensional array
    if (dimensions.length > 1) {
	    // Remove the first value from the array
	    var args = Array.prototype.slice.call(dimensions, 1);
	    // For each index in the created array create a new array with recursion
	    while(i--) {
	        array[dimensions[0]-1 - i] = Array.create(args, value);
	    }
    // If there is only one element left in the dimensions array
    // assign value to each of the new array's elements if value is set as param
    } else {
      if (typeof value !== 'undefined') {
        while(i--) {
            array[dimensions[0]-1 - i] = value;
        }
      }
    }

    return array;
	};

})();<|endoftext|>


<commit_before>/**
 * Application
 */
define(['lib/page', 'data/buttons', 'quiz'], function(Page, Buttons, Quiz) {

	function Application() {

		this.show();
	}

	Application.prototype = {

		keyCache: [],

		/**
		 * Initializes the Application object
		 *
		 * @param  {Page}		Page object
		 * @return {undefined}
		 */

		show: function() {

			new Page('index').then(this.init.bind(this));
		},

		init: function(Page) {

			this.physicalButtons = Buttons;

			this.page = Page;

			this.bindEvents();
		},

		/**
		 * Binds the Application events
		 *
		 * @return {undefined}
		 */
		bindEvents: function() {

			$(document).keyup(this.keyUp.bind(this));
			$(document).keydown(this.keyDown.bind(this));
			this.page.$el.bind('click', this.startQuiz.bind(this));
		},

		/**
		 * Runs when a key is pressed
		 * Checks if the key is in the physical key list
		 *
		 * @param  {jQuery.event}
		 * @return {undefined}
		 */
		keyUp: function(event) {

			var buttonData = this.getButtonColorByEventcode(event.which);

			/**
			 * Remove the current button from the keycache
			 */
			var keyCacheIndex = this.keyCache.indexOf(event.which);

			if (keyCacheIndex > -1) {
				this.keyCache.splice(keyCacheIndex, 1);
			}

			if (!buttonData || this.keyPause) {
				return;
			}

			this.triggerAnyElement();

			this.triggerButton(buttonData.color);
		},

		keyDown: function() {

			var removeQuiz = true;

			this.keyCache.push(event.which);

			/**
			 * If all buttons are pressed, quit the quiz
			 */
			$.each(this.physicalButtons, function(key, buttonData) {

				if (this.keyCache.indexOf(buttonData.eventcode) == -1) {
					removeQuiz = false;
				}
			}.bind(this));

			if (this.quiz && removeQuiz) {

				this.removeQuiz();

				this.setKeyPause();
			}
		},

		triggerAnyElement: function() {

			$('.interactive.any:visible').trigger('click');
		},

		setKeyPause: function(howLong) {

			this.keyPause = true;

			setTimeout(function(){

				this.keyPause = false;
				delete this.keyPause;
			}.bind(this), howLong || 3000);
		},

		/**
		 * Compares the pressed button with the set button colors
		 * If the button is in the set, return the color
		 *
		 * @param  {Int}			eventcode
		 * @return {false|string}	the Buttoncolor
		 */
		getButtonColorByEventcode: function(eventcode) {

			return this.getButtonByFilter('eventcode', eventcode);
		},

		/**
		 * Gets button by filter
		 *
		 * @param  {[type]} filtername  [description]
		 * @param  {[type]} filtervalue [description]
		 * @return {[type]}             [description]
		 */
		getButtonByFilter: function(filtername, filtervalue) {

			var find = this.physicalButtons.filter(function(buttonData) {

				return buttonData[filtername] == filtervalue;
			});

			return find.length ? find.pop() : false;
		},

		/**
		 * Triggers a button with the corresponding color class if the
		 * physical button is triggered
		 *
		 * @param  {string}		button color
		 * @return {jQuery.object}
		 */
		triggerButton: function(color) {

			this.setKeyPause(1000);

			return $('.interactive.' + color + ':visible').trigger('click');
		},

		/**
		 * Starts the quiz
		 *
		 * @return {undefined}
		 */
		startQuiz: function() {

			this.quiz = new Quiz(this);
		},

		removeQuiz: function() {
			this.quiz.destroy();
			delete this.quiz;
			this.show();
		}
	}

	return Application;

});<commit_msg>memoved endless binding in application<commit_after>/**
 * Application
 */
define(['lib/page', 'data/buttons', 'quiz'], function(Page, Buttons, Quiz) {

	function Application() {

		this.bindEvents();
		this.show();
	}

	Application.prototype = {

		keyCache: [],

		/**
		 * Initializes the Application object
		 *
		 * @param  {Page}		Page object
		 * @return {undefined}
		 */

		show: function() {

			new Page('index').then(this.init.bindPageEvents(this));
		},

		init: function(Page) {

			this.physicalButtons = Buttons;

			this.page = Page;

			this.bindEvents();
		},

		/**
		 * Binds the Application events
		 *
		 * @todo  move to main.js
		 * @return {undefined}
		 */
		bindEvents: function() {

			$(document).keyup(this.keyUp.bind(this));
			$(document).keydown(this.keyDown.bind(this));
		},

		bindPageEvents: function() {

			this.page.$el.bind('click', this.startQuiz.bind(this));
		},

		/**
		 * Runs when a key is pressed
		 * Checks if the key is in the physical key list
		 *
		 * @param  {jQuery.event}
		 * @return {undefined}
		 */
		keyUp: function(event) {

			var buttonData = this.getButtonColorByEventcode(event.which);

			/**
			 * Remove the current button from the keycache
			 */
			var keyCacheIndex = this.keyCache.indexOf(event.which);

			if (keyCacheIndex > -1) {
				this.keyCache.splice(keyCacheIndex, 1);
			}

			if (!buttonData || this.keyPause) {
				return;
			}

			this.triggerAnyElement();

			this.triggerButton(buttonData.color);
		},

		keyDown: function() {

			var removeQuiz = true;

			this.keyCache.push(event.which);

			/**
			 * If all buttons are pressed, quit the quiz
			 */
			$.each(this.physicalButtons, function(key, buttonData) {

				if (this.keyCache.indexOf(buttonData.eventcode) == -1) {
					removeQuiz = false;
				}
			}.bind(this));

			if (this.quiz && removeQuiz) {

				this.removeQuiz();

				this.setKeyPause();
			}
		},

		triggerAnyElement: function() {

			$('.interactive.any:visible').trigger('click');
		},

		setKeyPause: function(howLong) {

			this.keyPause = true;

			setTimeout(function(){

				this.keyPause = false;
				delete this.keyPause;
			}.bind(this), howLong || 3000);
		},

		/**
		 * Compares the pressed button with the set button colors
		 * If the button is in the set, return the color
		 *
		 * @param  {Int}			eventcode
		 * @return {false|string}	the Buttoncolor
		 */
		getButtonColorByEventcode: function(eventcode) {

			return this.getButtonByFilter('eventcode', eventcode);
		},

		/**
		 * Gets button by filter
		 *
		 * @param  {[type]} filtername  [description]
		 * @param  {[type]} filtervalue [description]
		 * @return {[type]}             [description]
		 */
		getButtonByFilter: function(filtername, filtervalue) {

			var find = this.physicalButtons.filter(function(buttonData) {

				return buttonData[filtername] == filtervalue;
			});

			return find.length ? find.pop() : false;
		},

		/**
		 * Triggers a button with the corresponding color class if the
		 * physical button is triggered
		 *
		 * @param  {string}		button color
		 * @return {jQuery.object}
		 */
		triggerButton: function(color) {

			this.setKeyPause(1000);

			return $('.interactive.' + color + ':visible').trigger('click');
		},

		/**
		 * Starts the quiz
		 *
		 * @return {undefined}
		 */
		startQuiz: function() {

			this.quiz = new Quiz(this);
		},

		removeQuiz: function() {
			this.quiz.destroy();
			delete this.quiz;
			this.show();
		}
	}

	return Application;

});<|endoftext|>


<commit_before>'use strict';

var cheerio = require('cheerio');
var curl = require('../../curl');

function messageListener(db, from, channel, message, reply) {
  var match = /(https?:\/\/[^ ]+)/.exec(message);
  if (match) {
    curl(match[1], function (res) {

      var $ = cheerio.load(res);
      var lines = [];

      if ($('meta[property="og:description"]').length === 1) {
        var desc = $('meta[property="og:description"]').attr("content");
        lines = desc.trim().split('\n');
      } else if ($('title').length === 1) {
        var title = $('title').text();
        lines = title.trim().split('\n');
      }

      for (var i = 0; i < lines.length; i++) {
        reply({ to: channel, message: lines[i] });
      }

    });
  }

}

module.exports = messageListener;
<commit_msg>Truncate long replies<commit_after>'use strict';

var cheerio = require('cheerio');
var curl = require('../../curl');

function messageListener(db, from, channel, message, reply) {
  var match = /(https?:\/\/[^ ]+)/.exec(message);
  if (match) {
    curl(match[1], function (res) {

      var $ = cheerio.load(res);
      var lines = [];

      if ($('meta[property="og:description"]').length === 1) {
        var desc = $('meta[property="og:description"]').attr("content");
        lines = desc.trim().split('\n');
      } else if ($('title').length === 1) {
        var title = $('title').text();
        lines = title.trim().split('\n');
      }

      var res = lines.join(' ');
      if (res.length > 83) {
        res = res.substring(0, 80) + '...';
      }
      reply({ to: channel, message: res });

    });
  }

}

module.exports = messageListener;
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('shelljs/global');

var filename = __filename.replace(__dirname + '/', '');

function run(testFile) {
  var logFile = 'elm-test.test.log';
  var retVal;

  if (!testFile) {
    retVal = exec('elm-test');
  } else {
    logFile = testFile + '.test.log';
    retVal = exec('elm-test ' + testFile);
  }

  retVal.toEnd(logFile);
  return retVal.code;
}

function assertTestFailure(testFile) {
  var code = run(testFile);
  if (code !== 1) {
    exec('echo ' + filename + ': ERROR: ' + (testFile ? testFile + ': ' : '') + 'Expected tests to fail >&2');
    exit(1);
  }
}

function assertTestSuccess(testFile) {
  var code = run(testFile);
  if (code !== 0) {
    exec('echo ' + filename + ': ERROR: ' + (testFile ? testFile + ': ' : '') + 'Expected tests to pass >&2');
    exit(1);
  }
}

echo(filename + ': Installing elm-test...');
exec('npm install --global');

echo(filename + ': Verifying installed elm-test version...');
exec('elm-test --version');

echo(filename + ': Testing examples...');

cd('examples/tests');
exec('elm-package install --yes');
assertTestSuccess('PassingTests.elm');
assertTestFailure('FailingTests.elm');
cd('../..');

echo(filename + ': Testing elm-test init...');
mkdir('-p', 'tmp');
cd('tmp');
exec('elm-test init --yes');
cd('tests');
exec('elm-package install --yes');
cd('..');
assertTestFailure();

// update failing test to passing test
sed('-i', /should fail/, 'should pass', 'tests/Tests.elm');
sed('-i', /Expect.fail "failed as expected!"/, 'Expect.pass', 'tests/Tests.elm');
rm('-Rf', 'tests/elm-stuff');
cd('tests');
exec('elm-package install --yes');
cd('..');
assertTestSuccess();

cd('..');
rm('-Rf', 'tmp');

echo('');
echo(filename + ': Everything looks good!');
echo('                                                            ');
echo('  __   ,_   _  __,  -/-     ,         __   __   _   ,    ,  ');
echo('_(_/__/ (__(/_(_/(__/_    _/_)__(_/__(_,__(_,__(/__/_)__/_)_');
echo(' _/_                                                        ');
echo('(/                                                          ');
<commit_msg>use local node-test-runner<commit_after>#!/usr/bin/env node

require('shelljs/global');
var _ = require('lodash');
var fs = require('fs-extra');

var filename = __filename.replace(__dirname + '/', '');

function run(testFile) {
  var logFile = 'elm-test.test.log';
  var retVal;

  if (!testFile) {
    retVal = exec('elm-test');
  } else {
    logFile = testFile + '.test.log';
    retVal = exec('elm-test ' + testFile);
  }

  retVal.toEnd(logFile);
  return retVal.code;
}

function assertTestFailure(testFile) {
  var code = run(testFile);
  if (code !== 1) {
    exec('echo ' + filename + ': ERROR: ' + (testFile ? testFile + ': ' : '') + 'Expected tests to fail >&2');
    exit(1);
  }
}

function assertTestSuccess(testFile) {
  var code = run(testFile);
  if (code !== 0) {
    exec('echo ' + filename + ': ERROR: ' + (testFile ? testFile + ': ' : '') + 'Expected tests to pass >&2');
    exit(1);
  }
}

echo(filename + ': Installing elm-test...');
exec('npm install --global');

echo(filename + ': Verifying installed elm-test version...');
exec('elm-test --version');

echo(filename + ': Testing examples...');

cd('examples/tests');
exec('elm-package install --yes');
assertTestSuccess('PassingTests.elm');
assertTestFailure('FailingTests.elm');
cd('../..');

echo(filename + ': Testing elm-test init...');
rm('-Rf', 'tmp');
mkdir('-p', 'tmp');
cd('tmp');
exec('elm-test init --yes');
cd('tests');
// use local node-test-runner
var tmpPackage = fs.readJsonSync('./elm-package.json');
tmpPackage['source-directories'].push('../../src');
var keys = _.reject(_.keys(tmpPackage.dependencies), function(name) {
  return name === "rtfeldman/node-test-runner";
});
tmpPackage.dependencies = _.pick(tmpPackage.dependencies, keys);
fs.writeJsonSync('./elm-package.json', tmpPackage);
exec('elm-package install --yes');
cd('..');
assertTestFailure();

// update failing test to passing test
sed('-i', /should fail/, 'should pass', 'tests/Tests.elm');
sed('-i', /Expect.fail "Failed as expected!"/, 'Expect.pass', 'tests/Tests.elm');
rm('-Rf', 'tests/elm-stuff');
cd('tests');
exec('elm-package install --yes');
cd('..');
assertTestSuccess();

cd('..');
rm('-Rf', 'tmp');

echo('');
echo(filename + ': Everything looks good!');
echo('                                                            ');
echo('  __   ,_   _  __,  -/-     ,         __   __   _   ,    ,  ');
echo('_(_/__/ (__(/_(_/(__/_    _/_)__(_/__(_,__(_,__(/__/_)__/_)_');
echo(' _/_                                                        ');
echo('(/                                                          ');
<|endoftext|>


<commit_before>import React from 'react';
import Footer from './../../components/footer';

class AboutPage extends React.Component {

    render() {
        return (

Autoriai

Mes esame Ieva ir Jonas. Gražiu oru mėgstame dviračiais
                                        važinėtis po Lietuvą.

Šiame bloge rasite visus mūsų išbandytus maršrutus.

                                        Mes esame ne dviračių sporto, o labiau poilsio dviračiais entuziastai.
                                        Todėl siūlomi maršrutai yra skirti pradedantiesiems arba vidutiniokams.
                                        Tačiau idėjų savo žygiams pasisems ir labiau patyrę.

Linkime smagių kelionių!

        );
    }
}

export default AboutPage;

<commit_msg>IE image fix 11<commit_after>import React from 'react';
import Footer from './../../components/footer';

class AboutPage extends React.Component {

    render() {
        return (

Autoriai

Mes esame Ieva ir Jonas. Gražiu oru mėgstame dviračiais
                                        važinėtis po Lietuvą.

Šiame bloge rasite visus mūsų išbandytus maršrutus.

                                        Mes esame ne dviračių sporto, o labiau poilsio dviračiais entuziastai.
                                        Todėl siūlomi maršrutai yra skirti pradedantiesiems arba vidutiniokams.
                                        Tačiau idėjų savo žygiams pasisems ir labiau patyrę.

Linkime smagių kelionių!

        );
    }
}

export default AboutPage;

<|endoftext|>


<commit_before>/**
 * This file depends on form.js.
 *
 * Format for the span/input identifiers for selectors:
 *
 * {dataelementid}-{optioncomboid}-val // data value
 * {dataelementid}-dataelement name of data element
 * {optioncomboid}-optioncombo // name of category option combo
 * {dataelementid}-cell // table cell for data element name
 * {dataelementid}-{optioncomboid}-min // min value for data value
 * {dataelementid}-{optioncomboid}-max // max value for data value
 */

// -----------------------------------------------------------------------------
// Save
// -----------------------------------------------------------------------------

/**
 * Updates totals for data element total fields.
 *
 * @param dataElementId the id of the data element to update total fields, if
 *        omitted then all total fields are updated.
 */
dhis2.de.updateDataElementTotals = function( dataElementId )
{
	var currentTotals = [];

	$( 'input[name="total"]' ).each( function( index )
	{
		var de = $( this ).attr( 'dataelementid' );

		if ( !dataElementId || dataElementId == de )
		{
			var total = dhis2.de.getDataElementTotalValue( de );

			$( this ).attr( 'value', total );
		}
	} );
}

/**
 * Updates all indicator input fields with the calculated value based on the
 * values in the input entry fields in the form.
 */
dhis2.de.updateIndicators = function()
{
    $( 'input[name="indicator"]' ).each( function( index )
    {
        var indicatorId = $( this ).attr( 'indicatorid' );

        var formula = dhis2.de.indicatorFormulas[indicatorId];

        if ( isDefined( formula ) )
        {
	        var expression = dhis2.de.generateExpression( formula );

	        if ( expression )
	        {
		        var value = eval( expression );

		        value = isNaN( value ) ? '-' : roundTo( value, 1 );

		        $( this ).attr( 'value', value );
	        }
        }
        else
        {
        	log( 'Indicator does not exist in form: ' + indicatorId );
        }
    } );
}

/**
 * Returns the total sum of values in the current form for the given data element
 * identifier.
 */
dhis2.de.getDataElementTotalValue = function( de )
{
	var sum = new Number();

	$( '[id^="' + de + '"]' ).each( function( index )
	{
		var val = $( this ).attr( 'value' );

		if ( val && dhis2.validation.isNumber( val ) )
		{
			sum += new Number( $( this ).attr( 'value' ) );
		}
	} );

	return sum;
}

/**
 * Returns the value in the current form for the given data element and category
 * option combo identifiers. Returns 0 if the field does not exist in the form.
 */
dhis2.de.getFieldValue = function( de, coc )
{
    var fieldId = '#' + de + '-' + coc + '-val';

    var value = '0';

    if ( $( fieldId ).length )
    {
        value = $( fieldId ).val() ? $( fieldId ).val() : '0';
    }

    return value;
}

/**
 * Parses the expression and substitutes the operand identifiers with the value
 * of the corresponding input entry field.
 */
dhis2.de.generateExpression = function( expression )
{
    var matcher = expression.match( dhis2.de.cst.formulaPattern );

    for ( k in matcher )
    {
        var match = matcher[k];

        // Remove brackets from expression to simplify extraction of identifiers

        var operand = match.replace( /[#\{\}]/g, '' );

        var isTotal = !!( operand.indexOf( dhis2.de.cst.separator ) == -1 );

        var value = '0';

        if ( isTotal )
        {
        	value = dhis2.de.getDataElementTotalValue( operand );
        }
        else
        {
	        var de = operand.substring( 0, operand.indexOf( dhis2.de.cst.separator ) );
	        var coc = operand.substring( operand.indexOf( dhis2.de.cst.separator ) + 1, operand.length );
	        value = dhis2.de.getFieldValue( de, coc );
        }

        expression = expression.replace( match, value );

        // TODO signed numbers
    }

    return expression;
}

function saveVal( dataElementId, optionComboId, fieldId, feedbackId )
{
    var fieldIds = fieldId.split( "-" );

    feedbackId = '#' + ( feedbackId || fieldId );

    if ( fieldIds.length > 3 )
    {
      dhis2.de.currentOrganisationUnitId = fieldIds[0];
    }

    fieldId = '#' + fieldId;

    var dataElementName = getDataElementName( dataElementId );
    var value = $( fieldId ).val();
    var type = getDataElementType( dataElementId );

    $( feedbackId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var warning = undefined;

    var existing = !!( dhis2.de.currentExistingValue && dhis2.de.currentExistingValue != '' );

    if ( value )
    {
        if ( type == 'TEXT' || type == 'NUMBER' || type == 'INTEGER' || type == 'INTEGER_POSITIVE' || type == 'INTEGER_NEGATIVE'
          || type == 'INTEGER_ZERO_OR_POSITIVE' || type == 'UNIT_INTERVAL' || type == 'PERCENTAGE' || type == 'COORDINATE')
        {
            if ( value.length > dhis2.de.cst.valueMaxLength )
            {
                return dhis2.de.alertField( fieldId, i18n_value_too_long + '\n\n' + dataElementName );
            }
            if ( type == 'NUMBER' && !dhis2.validation.isNumber( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_number + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER' && !dhis2.validation.isInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_POSITIVE' && !dhis2.validation.isPositiveInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_positive_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_NEGATIVE' && !dhis2.validation.isNegativeInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_negative_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_ZERO_OR_POSITIVE' && !dhis2.validation.isZeroOrPositiveInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_zero_or_positive_integer + '\n\n' + dataElementName );
            }
            if ( type == 'COORDINATE' && !dhis2.validation.isCoordinate( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_coordinate + '\n\n' + dataElementName );
            }
            if ( type == 'UNIT_INTERVAL' && !dhis2.validation.isUnitInterval( value ) )
            {
            	return dhis2.de.alertField( fieldId, i18n_value_must_unit_interval + '\n\n' + dataElementName );
            }
            if ( type == 'PERCENTAGE' && !dhis2.validation.isPercentage( value ) )
            {
            	return dhis2.de.alertField( fieldId, i18n_value_must_percentage + '\n\n' + dataElementName );
            }
            if ( !existing && dhis2.validation.isValidZeroNumber( value ) )
            {
                // If value = 0 and zero not significant for data element, skip
            	// If existing value, let through and delete on server

                if ( dhis2.de.significantZeros.indexOf( dataElementId ) == -1 && dhis2.validation.isNumericType(type) )
                {
                    $( fieldId ).css( 'background-color', dhis2.de.cst.colorGreen );
                    return false;
                }
            }

            var minString = dhis2.de.currentMinMaxValueMap[dataElementId + '-' + optionComboId + '-min'];
            var maxString = dhis2.de.currentMinMaxValueMap[dataElementId + '-' + optionComboId + '-max'];

            if ( minString && maxString ) // TODO if only one exists?
            {
                var valueNo = new Number( value );
                var min = new Number( minString );
                var max = new Number( maxString );

                if ( valueNo < min )
                {
                    warning = i18n_value_of_data_element_less + ': ' + min + '\n\n' + dataElementName;
                }

                if ( valueNo > max )
                {
                    warning = i18n_value_of_data_element_greater + ': ' + max + '\n\n' + dataElementName;
                }
            }
        }
    }

    var color = warning ? dhis2.de.cst.colorOrange : dhis2.de.cst.colorGreen;

    var valueSaver = new ValueSaver( dataElementId,	periodId, optionComboId, value, feedbackId, color );
    valueSaver.save();

    dhis2.de.updateIndicators(); // Update indicators for custom form
    dhis2.de.updateDataElementTotals( dataElementId ); // Update data element totals for custom forms

    if ( warning )
    {
    	window.alert( warning );
    }
}

function saveBoolean( dataElementId, optionComboId, _fieldId )
{
    var fieldId = '#' + _fieldId;

    var value = $('input[id=' + _fieldId + ']:checked').val();

    $( fieldId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new ValueSaver( dataElementId, periodId, optionComboId, value, fieldId, dhis2.de.cst.colorGreen );
    valueSaver.save();
}

function saveTrueOnly( dataElementId, optionComboId, fieldId )
{
    fieldId = '#' + fieldId;

    var value = $( fieldId ).is( ':checked' );

    value = ( value == true) ? value : undefined; // Send nothing if un-ticked

    $( fieldId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new ValueSaver( dataElementId, periodId, optionComboId, value, fieldId, dhis2.de.cst.colorGreen );
    valueSaver.save();
}

function saveFileResource( dataElementId, optionComboId, fieldId, fileResource, onSuccessCallback )
{
    fieldId = '#' + fieldId;

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new FileResourceValueSaver( dataElementId, periodId, optionComboId, fileResource, fieldId, dhis2.de.cst.colorGreen, onSuccessCallback );
    valueSaver.save();
}

/**
 * Supportive method.
 */
dhis2.de.alertField = function( fieldId, alertMessage )
{
    var $field = $( fieldId );
    $field.css( 'background-color', dhis2.de.cst.colorYellow );

    window.alert( alertMessage );

    var val = dhis2.de.currentExistingValue || '';
    $field.val( val );

    $field.focus();

    return false;
}

// -----------------------------------------------------------------------------
// Saver objects
// -----------------------------------------------------------------------------

/**
 * @param de data element identifier.
 * @param pe iso period.
 * @param co category option combo.
 * @param value value.
 * @param fieldId identifier of data input field.
 * @param resultColor the color code to set on input field for success.
 */
function ValueSaver( de, pe, co, value, fieldId, resultColor )
{
	var ou = dhis2.de.getCurrentOrganisationUnit();

    var dataValue = {
        'de' : de,
        'co' : co,
        'ou' : ou,
        'pe' : pe,
        'value' : value
    };

    var cc = dhis2.de.getCurrentCategoryCombo();
    var cp = dhis2.de.getCurrentCategoryOptionsQueryValue();

    if ( cc && cp )
    {
    	dataValue.cc = cc;
    	dataValue.cp = cp;
    }

    this.save = function()
    {
    	dhis2.de.storageManager.saveDataValue( dataValue );

        $.ajax( {
            url: '../api/dataValues',
            data: dataValue,
            dataType: 'json',
            type: 'post',
            success: handleSuccess,
            error: handleError
        } );
    };

    var afterHandleSuccess = function() {};

    this.setAfterHandleSuccess = function( callback ) {
        afterHandleSuccess = callback;
    };

    function handleSuccess()
    {
        dhis2.de.storageManager.clearDataValueJSON( dataValue );
        markValue( fieldId, resultColor );
        $( document ).trigger( dhis2.de.event.dataValueSaved, [ dhis2.de.currentDataSetId, dataValue ] );
        afterHandleSuccess();
    }

    function handleError( xhr, textStatus, errorThrown )
    {
    	if ( 409 == xhr.status || 500 == xhr.status ) // Invalid value or locked
    	{
    		markValue( fieldId, dhis2.de.cst.colorRed );
        var errorText = JSON.parse( xhr.responseText );
    		setHeaderDelayMessage( errorText.message );
    	}
    	else // Offline, keep local value
    	{
    		markValue( fieldId, resultColor );
    		setHeaderDelayMessage( i18n_offline_notification );
    	}
    }

    function markValue( fieldId, color )
    {
        $( fieldId ).css( 'background-color', color );
    }
}

function FileResourceValueSaver( de, pe, co, fileResource, fieldId, resultColor, onSuccessCallback )
{
    var valueSaver = new ValueSaver( de, pe, co, fileResource.id, fieldId, resultColor );

    valueSaver.setAfterHandleSuccess( onSuccessCallback );

    return valueSaver;
}
<commit_msg>trigger dataValueSaved event when value saved whether offline or online<commit_after>/**
 * This file depends on form.js.
 *
 * Format for the span/input identifiers for selectors:
 *
 * {dataelementid}-{optioncomboid}-val // data value
 * {dataelementid}-dataelement name of data element
 * {optioncomboid}-optioncombo // name of category option combo
 * {dataelementid}-cell // table cell for data element name
 * {dataelementid}-{optioncomboid}-min // min value for data value
 * {dataelementid}-{optioncomboid}-max // max value for data value
 */

// -----------------------------------------------------------------------------
// Save
// -----------------------------------------------------------------------------

/**
 * Updates totals for data element total fields.
 *
 * @param dataElementId the id of the data element to update total fields, if
 *        omitted then all total fields are updated.
 */
dhis2.de.updateDataElementTotals = function( dataElementId )
{
	var currentTotals = [];

	$( 'input[name="total"]' ).each( function( index )
	{
		var de = $( this ).attr( 'dataelementid' );

		if ( !dataElementId || dataElementId == de )
		{
			var total = dhis2.de.getDataElementTotalValue( de );

			$( this ).attr( 'value', total );
		}
	} );
}

/**
 * Updates all indicator input fields with the calculated value based on the
 * values in the input entry fields in the form.
 */
dhis2.de.updateIndicators = function()
{
    $( 'input[name="indicator"]' ).each( function( index )
    {
        var indicatorId = $( this ).attr( 'indicatorid' );

        var formula = dhis2.de.indicatorFormulas[indicatorId];

        if ( isDefined( formula ) )
        {
	        var expression = dhis2.de.generateExpression( formula );

	        if ( expression )
	        {
		        var value = eval( expression );

		        value = isNaN( value ) ? '-' : roundTo( value, 1 );

		        $( this ).attr( 'value', value );
	        }
        }
        else
        {
        	log( 'Indicator does not exist in form: ' + indicatorId );
        }
    } );
}

/**
 * Returns the total sum of values in the current form for the given data element
 * identifier.
 */
dhis2.de.getDataElementTotalValue = function( de )
{
	var sum = new Number();

	$( '[id^="' + de + '"]' ).each( function( index )
	{
		var val = $( this ).attr( 'value' );

		if ( val && dhis2.validation.isNumber( val ) )
		{
			sum += new Number( $( this ).attr( 'value' ) );
		}
	} );

	return sum;
}

/**
 * Returns the value in the current form for the given data element and category
 * option combo identifiers. Returns 0 if the field does not exist in the form.
 */
dhis2.de.getFieldValue = function( de, coc )
{
    var fieldId = '#' + de + '-' + coc + '-val';

    var value = '0';

    if ( $( fieldId ).length )
    {
        value = $( fieldId ).val() ? $( fieldId ).val() : '0';
    }

    return value;
}

/**
 * Parses the expression and substitutes the operand identifiers with the value
 * of the corresponding input entry field.
 */
dhis2.de.generateExpression = function( expression )
{
    var matcher = expression.match( dhis2.de.cst.formulaPattern );

    for ( k in matcher )
    {
        var match = matcher[k];

        // Remove brackets from expression to simplify extraction of identifiers

        var operand = match.replace( /[#\{\}]/g, '' );

        var isTotal = !!( operand.indexOf( dhis2.de.cst.separator ) == -1 );

        var value = '0';

        if ( isTotal )
        {
        	value = dhis2.de.getDataElementTotalValue( operand );
        }
        else
        {
	        var de = operand.substring( 0, operand.indexOf( dhis2.de.cst.separator ) );
	        var coc = operand.substring( operand.indexOf( dhis2.de.cst.separator ) + 1, operand.length );
	        value = dhis2.de.getFieldValue( de, coc );
        }

        expression = expression.replace( match, value );

        // TODO signed numbers
    }

    return expression;
}

function saveVal( dataElementId, optionComboId, fieldId, feedbackId )
{
    var fieldIds = fieldId.split( "-" );

    feedbackId = '#' + ( feedbackId || fieldId );

    if ( fieldIds.length > 3 )
    {
      dhis2.de.currentOrganisationUnitId = fieldIds[0];
    }

    fieldId = '#' + fieldId;

    var dataElementName = getDataElementName( dataElementId );
    var value = $( fieldId ).val();
    var type = getDataElementType( dataElementId );

    $( feedbackId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var warning = undefined;

    var existing = !!( dhis2.de.currentExistingValue && dhis2.de.currentExistingValue != '' );

    if ( value )
    {
        if ( type == 'TEXT' || type == 'NUMBER' || type == 'INTEGER' || type == 'INTEGER_POSITIVE' || type == 'INTEGER_NEGATIVE'
          || type == 'INTEGER_ZERO_OR_POSITIVE' || type == 'UNIT_INTERVAL' || type == 'PERCENTAGE' || type == 'COORDINATE')
        {
            if ( value.length > dhis2.de.cst.valueMaxLength )
            {
                return dhis2.de.alertField( fieldId, i18n_value_too_long + '\n\n' + dataElementName );
            }
            if ( type == 'NUMBER' && !dhis2.validation.isNumber( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_number + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER' && !dhis2.validation.isInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_POSITIVE' && !dhis2.validation.isPositiveInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_positive_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_NEGATIVE' && !dhis2.validation.isNegativeInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_negative_integer + '\n\n' + dataElementName );
            }
            if ( type == 'INTEGER_ZERO_OR_POSITIVE' && !dhis2.validation.isZeroOrPositiveInt( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_zero_or_positive_integer + '\n\n' + dataElementName );
            }
            if ( type == 'COORDINATE' && !dhis2.validation.isCoordinate( value ) )
            {
                return dhis2.de.alertField( fieldId, i18n_value_must_coordinate + '\n\n' + dataElementName );
            }
            if ( type == 'UNIT_INTERVAL' && !dhis2.validation.isUnitInterval( value ) )
            {
            	return dhis2.de.alertField( fieldId, i18n_value_must_unit_interval + '\n\n' + dataElementName );
            }
            if ( type == 'PERCENTAGE' && !dhis2.validation.isPercentage( value ) )
            {
            	return dhis2.de.alertField( fieldId, i18n_value_must_percentage + '\n\n' + dataElementName );
            }
            if ( !existing && dhis2.validation.isValidZeroNumber( value ) )
            {
                // If value = 0 and zero not significant for data element, skip
            	// If existing value, let through and delete on server

                if ( dhis2.de.significantZeros.indexOf( dataElementId ) == -1 && dhis2.validation.isNumericType(type) )
                {
                    $( fieldId ).css( 'background-color', dhis2.de.cst.colorGreen );
                    return false;
                }
            }

            var minString = dhis2.de.currentMinMaxValueMap[dataElementId + '-' + optionComboId + '-min'];
            var maxString = dhis2.de.currentMinMaxValueMap[dataElementId + '-' + optionComboId + '-max'];

            if ( minString && maxString ) // TODO if only one exists?
            {
                var valueNo = new Number( value );
                var min = new Number( minString );
                var max = new Number( maxString );

                if ( valueNo < min )
                {
                    warning = i18n_value_of_data_element_less + ': ' + min + '\n\n' + dataElementName;
                }

                if ( valueNo > max )
                {
                    warning = i18n_value_of_data_element_greater + ': ' + max + '\n\n' + dataElementName;
                }
            }
        }
    }

    var color = warning ? dhis2.de.cst.colorOrange : dhis2.de.cst.colorGreen;

    var valueSaver = new ValueSaver( dataElementId,	periodId, optionComboId, value, feedbackId, color );
    valueSaver.save();

    dhis2.de.updateIndicators(); // Update indicators for custom form
    dhis2.de.updateDataElementTotals( dataElementId ); // Update data element totals for custom forms

    if ( warning )
    {
    	window.alert( warning );
    }
}

function saveBoolean( dataElementId, optionComboId, _fieldId )
{
    var fieldId = '#' + _fieldId;

    var value = $('input[id=' + _fieldId + ']:checked').val();

    $( fieldId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new ValueSaver( dataElementId, periodId, optionComboId, value, fieldId, dhis2.de.cst.colorGreen );
    valueSaver.save();
}

function saveTrueOnly( dataElementId, optionComboId, fieldId )
{
    fieldId = '#' + fieldId;

    var value = $( fieldId ).is( ':checked' );

    value = ( value == true) ? value : undefined; // Send nothing if un-ticked

    $( fieldId ).css( 'background-color', dhis2.de.cst.colorYellow );

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new ValueSaver( dataElementId, periodId, optionComboId, value, fieldId, dhis2.de.cst.colorGreen );
    valueSaver.save();
}

function saveFileResource( dataElementId, optionComboId, fieldId, fileResource, onSuccessCallback )
{
    fieldId = '#' + fieldId;

    var periodId = $( '#selectedPeriodId' ).val();

    var valueSaver = new FileResourceValueSaver( dataElementId, periodId, optionComboId, fileResource, fieldId, dhis2.de.cst.colorGreen, onSuccessCallback );
    valueSaver.save();
}

/**
 * Supportive method.
 */
dhis2.de.alertField = function( fieldId, alertMessage )
{
    var $field = $( fieldId );
    $field.css( 'background-color', dhis2.de.cst.colorYellow );

    window.alert( alertMessage );

    var val = dhis2.de.currentExistingValue || '';
    $field.val( val );

    $field.focus();

    return false;
}

// -----------------------------------------------------------------------------
// Saver objects
// -----------------------------------------------------------------------------

/**
 * @param de data element identifier.
 * @param pe iso period.
 * @param co category option combo.
 * @param value value.
 * @param fieldId identifier of data input field.
 * @param resultColor the color code to set on input field for success.
 */
function ValueSaver( de, pe, co, value, fieldId, resultColor )
{
	var ou = dhis2.de.getCurrentOrganisationUnit();

    var dataValue = {
        'de' : de,
        'co' : co,
        'ou' : ou,
        'pe' : pe,
        'value' : value
    };

    var cc = dhis2.de.getCurrentCategoryCombo();
    var cp = dhis2.de.getCurrentCategoryOptionsQueryValue();

    if ( cc && cp )
    {
    	dataValue.cc = cc;
    	dataValue.cp = cp;
    }

    this.save = function()
    {
    	dhis2.de.storageManager.saveDataValue( dataValue );

        $.ajax( {
            url: '../api/dataValues',
            data: dataValue,
            dataType: 'json',
            type: 'post',
            success: handleSuccess,
            error: handleError
        } );
    };

    var afterHandleSuccess = function() {};

    this.setAfterHandleSuccess = function( callback ) {
        afterHandleSuccess = callback;
    };

    function handleSuccess()
    {
        dhis2.de.storageManager.clearDataValueJSON( dataValue );
        markValue( fieldId, resultColor );
        $( document ).trigger( dhis2.de.event.dataValueSaved, [ dhis2.de.currentDataSetId, dataValue ] );
        afterHandleSuccess();
    }

    function handleError( xhr, textStatus, errorThrown )
    {
    	if ( 409 == xhr.status || 500 == xhr.status ) // Invalid value or locked
    	{
    		markValue( fieldId, dhis2.de.cst.colorRed );
        var errorText = JSON.parse( xhr.responseText );
    		setHeaderDelayMessage( errorText.message );
    	}
    	else // Offline, keep local value
    	{
            $( document ).trigger( dhis2.de.event.dataValueSaved, [ dhis2.de.currentDataSetId, dataValue ] );
    		markValue( fieldId, resultColor );
    		setHeaderDelayMessage( i18n_offline_notification );
    	}
    }

    function markValue( fieldId, color )
    {
        $( fieldId ).css( 'background-color', color );
    }
}

function FileResourceValueSaver( de, pe, co, fileResource, fieldId, resultColor, onSuccessCallback )
{
    var valueSaver = new ValueSaver( de, pe, co, fileResource.id, fieldId, resultColor );

    valueSaver.setAfterHandleSuccess( onSuccessCallback );

    return valueSaver;
}
<|endoftext|>


<commit_before>import React from "react";
import { Link } from "react-router";

import CatalogItem from "../../components/catalog/CatalogItem";

import Golang from "../../assests/images/catalog/golang.png";
import PHP from "../../assests/images/catalog/php.png";
import Node from "../../assests/images/catalog/node.png";
import Python from "../../assests/images/catalog/python.png";
import Wordpress from "../../assests/images/catalog/wordpress.png";
import MySQL from "../../assests/images/catalog/mysql.png";
import Postgres from "../../assests/images/catalog/postgres.png";
import Rails from "../../assests/images/catalog/rails.png";
import Ubuntu from "../../assests/images/catalog/ubuntu.png";
import Centos from "../../assests/images/catalog/centos.png";
import Laravel from "../../assests/images/catalog/laravel.png";

export default class Catalog extends React.Component {
	render() {
		return (

            <form action="#" method="get" className="katalog-form">

                <input type="text" name="q" className="form-control" placeholder="Search..." />

                  <button type='submit' name='seach' id='search-btn' className="btn btn-default"></button>

            </form>

Language Stack

          <CatalogItem url="/stack/new" img={ Golang } name="Golang">
            Go (golang) is a general purpose, higher-level, imperative
            programming language.
          </CatalogItem>

          <CatalogItem url="/stack/new" img={ PHP } name="PHP">
            While designed for web development, the PHP scripting language
            also provides general-purpose use.
          </CatalogItem>

          <CatalogItem url="/stack/new" img={ Node } name="NodeJS">
            Node.js is a JavaScript-based platform for server-side and
            networking applications.
          </CatalogItem>

CMS

          <CatalogItem url="/stack/new" img={ Wordpress } name="Wordpress">
            The WordPress rich content management system can utilize plugins,
            widgets, and themes.
          </CatalogItem>

Database

          <CatalogItem url="/services/new" img={ MySQL } name="MySQL 5.6">
            MySQL is a widely used, open-source relational database
            management system (RDBMS).
          </CatalogItem>

          <CatalogItem url="/services/new" img={ Postgres } name="PostgreSQL">
            The PostgreSQL object-relational database system provides
            reliability and data integrity.
          </CatalogItem>

Framework

          <CatalogItem url="/stack/new" img={ Rails } name="Ruby on Rails">
            Open-source web application framework written in Ruby.
          </CatalogItem>

          <CatalogItem url="/stack/new" img={ Laravel } name="Laravel">
            Web application framework with expressive, elegant syntax.
          </CatalogItem>

            <button className="btn btn-primary btn-block">BUILD NEW IMAGE</button>

		);
	}
}<commit_msg>FIX: link on catalog page<commit_after>import React from "react";
import { Link } from "react-router";

import CatalogItem from "../../components/catalog/CatalogItem";

import Golang from "../../assests/images/catalog/golang.png";
import PHP from "../../assests/images/catalog/php.png";
import Node from "../../assests/images/catalog/node.png";
import Python from "../../assests/images/catalog/python.png";
import Wordpress from "../../assests/images/catalog/wordpress.png";
import MySQL from "../../assests/images/catalog/mysql.png";
import Postgres from "../../assests/images/catalog/postgres.png";
import Rails from "../../assests/images/catalog/rails.png";
import Ubuntu from "../../assests/images/catalog/ubuntu.png";
import Centos from "../../assests/images/catalog/centos.png";
import Laravel from "../../assests/images/catalog/laravel.png";

export default class Catalog extends React.Component {
	render() {
		return (

            <form action="#" method="get" className="katalog-form">

                <input type="text" name="q" className="form-control" placeholder="Search..." />

                  <button type='submit' name='seach' id='search-btn' className="btn btn-default"></button>

            </form>

Language Stack

          <CatalogItem url="/stacks/new" img={ Golang } name="Golang">
            Go (golang) is a general purpose, higher-level, imperative
            programming language.
          </CatalogItem>

          <CatalogItem url="/stacks/new" img={ PHP } name="PHP">
            While designed for web development, the PHP scripting language
            also provides general-purpose use.
          </CatalogItem>

          <CatalogItem url="/stacks/new" img={ Node } name="NodeJS">
            Node.js is a JavaScript-based platform for server-side and
            networking applications.
          </CatalogItem>

CMS

          <CatalogItem url="/stacks/new" img={ Wordpress } name="Wordpress">
            The WordPress rich content management system can utilize plugins,
            widgets, and themes.
          </CatalogItem>

Database

          <CatalogItem url="/services/new" img={ MySQL } name="MySQL 5.6">
            MySQL is a widely used, open-source relational database
            management system (RDBMS).
          </CatalogItem>

          <CatalogItem url="/services/new" img={ Postgres } name="PostgreSQL">
            The PostgreSQL object-relational database system provides
            reliability and data integrity.
          </CatalogItem>

Framework

          <CatalogItem url="/stacks/new" img={ Rails } name="Ruby on Rails">
            Open-source web application framework written in Ruby.
          </CatalogItem>

          <CatalogItem url="/stacks/new" img={ Laravel } name="Laravel">
            Web application framework with expressive, elegant syntax.
          </CatalogItem>

            <button className="btn btn-primary btn-block">BUILD NEW IMAGE</button>

		);
	}
}<|endoftext|>