function actionFormatter (value, row, index) {
    return '<a href="#' + value + '" class="details"><i class="glyphicon glyphicon-info-sign"></i></a>';
}

function getLabel(value) {
    var column;
    for (var i in all_columns) {
        column = all_columns[i];
        if (column.field === value)
            return column.title;
    }
}

function showBillModal(bill) {
    var modal = $('#billModal');
    modal.find('.modal-title').text(bill.title);
    modal.find('a.detailed-bill').attr('href', bill.titleLink);
    var output = [],
        column;
    for (var i in all_columns) {
        column = all_columns[i];
        if (!bill.hasOwnProperty(column.field) || column.field == 'id' || column.field == 'title')
            continue;
        // Get label
        output.push('<div class="row row-details">');
        output.push('<div class="col-sm-4"><strong>' + column.title + '</strong></div>');
        output.push('<div class="col-sm-8">' + bill[column.field] + '</div>');
        output.push('</div>');
    }
    modal.find('.modal-body').html(output.join(''));
    modal.on('hidden.bs.modal', function () {
        history.pushState("", document.title, window.location.pathname);
    });
    modal.modal('show');
}

function showBillModalByHash(data) {
    // Check for #<BILL-ID> in url
    if (window.location.hash) {
        var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
        hash = parseInt(hash)
        // Find bill
        for (i = 0; i < data.length; i++) {
            if (data[i].id == hash) {
                showBillModal(data[i]);
                break;
            }
        }
    }
}

window.actionEvents = {
    'click .details': function(e, value, row, index) {
        showBillModal(row);
    }
}

var table,
    options,
    columns = [
{
    field: "id",
    title: "Bill Detail",
    sortable: false,
    formatter: actionFormatter,
    events: actionEvents,
}, {
    field: "state",
    title: "State",
    sortable: true,
    filter: {
        type: "select"
    }
}, {
    field: "sponsor",
    title: "Sponsor",
    sortable: true,
    filter: {
        type: "input"
    }
}, {
    field: "title",
    title: "Title",
    sortable: true,
    filter: {
        type: "input"
    }
}, {
    field: "legislativeSession",
    title: "Legislative Session",
    sortable: true,
    filter: {
        type: "select",
        data: [
            '2010',
            '2011',
            '2012',
            '2013',
            '2014',
            '2015',
            '2016',
            '2017',
        ]
    }
}, {
    field: "synopsis",
    title: "Synopsis",
    sortable: true,
    visible: false,
    filter: {
        type: "input"
    }
}, {
    field: "status",
    title: "Status",
    sortable: true,
    filter: {
        type: "select"
    }
}, {
    field: "keyterms",
    title: "Key Terms",
    sortable: true,
    visible: true,
    filter: {
        type: "select",
        data: [
            "American Laws for American Courts",
            "Family Law",
            "Foreign Law",
            "Foreign Laws",
            "International Law",
            "Islam",
            "Religious Law",
            "Sharia"
        ]
    }
}, {
    field: "supporters",
    title: "Advocates",
    sortable: true,
    visible: true,
    filter: {
        type: "input"
    }
}
],
    all_columns = columns.concat([
{
    field: "usesAlac",
    title: "Bill uses ALAC language",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}, {
    field: "exemptsCorporations",
    title: "Bill exempts corporations",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}, {
    field: "barsCourts",
    title: "Bill does not exempt individuals",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}, {
    field: "instigatesFear",
    title: "Bill instigates fear of Sharia",
    sortable: true,
    visible: false,
    filter: {
        type: "select",
        data: ["Yes", "No"]
    }
}, {
    field: "increasesMistrust",
    title: "Bill others Muslims",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}, {
field: "fomentsIntolerance",
    title: "Bill foments a climate of intolerance",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}, {
    field: "impactsMuslims",
    title: "Bill violates Muslims' civil rights",
    sortable: true,
    visible: false,
    filter: {
        type: "select"
    }
}
/*, {
    field: "notes",
    title: "Notes",
    sortable: true,
    visible: false,
    filter: {
        type: "input"
    }
}*/
]);

function updateTotals(data) {
    var htmlTotals = [];
    // Get visible columns with type select
    var columns = [];
    var totalCount = 0;
    var skippedRows = [];
    var statusColumn;
    var stateColumn;
    var tableColumns = $('#table').bootstrapTable('getOptions').columns;
    if (tableColumns == undefined) {
        return;
    } else {
        tableColumns = tableColumns[0];
    }
    for (var i in tableColumns) {
        var column = tableColumns[i];
        if (!column.visible || !column.filter || column.filter.type !== 'select') {
            continue;
        }
        if (column.title == 'Status') {
            statusColumn = column;
        } else if (column.title == 'State') {
            stateColumn = column;
        }
        column.choice_totals = [];
        columns.push(column);
    }
    // Count choices for visible columns
    for (i in data) {
        var row = data[i];
        // skip rows with status 'None Introduced'
        if (row[statusColumn.field] == 'None Introduced') {
            skippedRows.push(row);
            continue;
        }
        totalCount ++;
        for (var j in columns) {
            column = columns[j];
            var choice = row[columns[j].field];
            if (!choice) {
                if (column.title == "Key Terms") {
                    choice = '<i>No Key Term Mentioned</i>';
                } else {
                    choice = '';
                }
            }
            choice = choice.toString().trim();
            var found = false;
            for (var k in column.choice_totals) {
                total = column.choice_totals[k];
                if (total.title == choice) {
                    total.count += 1;
                    found = true;
                }
            }
            if (!found) {
                columns[j].choice_totals.push({
                    field: column.field,
                    title: choice,
                    count: 1
                })
            }
        }
    }
    // show states with status 'None introduced' with 0 if no filter is active
    if (skippedRows.length + totalCount == data.length) {
        for (i in skippedRows) {
            var row = skippedRows[i];
            stateColumn.choice_totals.push({
                field: stateColumn.field,
                title: row[stateColumn.field],
                count: 0
            })
        }
    }
    function compare(a,b) {
        if (a.count < b.count)
            return 1;
        if (a.count > b.count)
            return -1;
        return 0;
    }
    for (i in columns) {
        column = columns[i];
        htmlTotals.push('<div class="col-sm-3">');
        htmlTotals.push('<div class="panel panel-default">');
        htmlTotals.push('<div class="panel-heading">');
        htmlTotals.push('<h3 class="panel-title">' + column.title + '</h3> <span class="bill-count">Bills</span>');
        htmlTotals.push('</div>');
        tableID = column.title.replace(/\s+/g, '-').toLowerCase();
        htmlTotals.push('<table id="' + tableID + '-table" class="table">');

        // Sort by total count
        column.choice_totals.sort(compare);
        for (j in column.choice_totals) {
            var total = column.choice_totals[j];
            htmlTotals.push('<tr>');
            htmlTotals.push('<th>' + total.title + '</th>');
            htmlTotals.push('<td>' + total.count + '</td>');
            htmlTotals.push('</tr>');
        }
        htmlTotals.push('</table>');
        htmlTotals.push('</div>');
        htmlTotals.push('</div>');
    }
    $('#totals').empty().append(htmlTotals.join(''));   

    function sortTable(table, order) {
        var asc   = order === 'asc',
            tbody = table.find('tbody');

        tbody.find('tr').sort(function(a, b) {
            if (asc) {
                return $('th:first', a).text().localeCompare($('th:first', b).text());
            } else {
                return $('th:first', b).text().localeCompare($('th:first', a).text());
            }
        }).appendTo(tbody);
    }

    function removeRow(selector, text) {
        $(selector).each(function() { 
            if( $(this).text() === text ) {
                $(this).closest('tr').remove();
            }
        });
    }

    function removeString(selector, str, strToFind) {

        var container = $(selector).filter(function(index) {
            return $(this).text() === str;
        });     
        
        var str = container.text();
        var newstr = str.replace(strToFind,'');

        container.text(newstr);
    }
    
    var keyTable = $('#key-terms-table tr th');


    console.log($('#key-terms-table tr th').length);

    var textToRemove = [
        'No Key Term Mentioned',
        'International Law, Sharia',
        'Foreign Laws, Religious Law',
        'Foreign Laws, International Law',
        'Family Law, Foreign Laws'
    ];

    $.each( textToRemove, function( index, value ) {
        removeRow(keyTable, value);
    });

    removeString(keyTable, 'Religious Law, Islam, Sharia', 'Religious Law,');
    

    // Re-sort legislative session based on year.
    sortTable($('#legislative-session-table'),'asc');

    // Insert total bills tr into first row of Status table.
    $('#status-table tbody').prepend('<tr><th>Total Bills Introduced</th><td>' + totalCount + '</td></tr>');
    
    
}

function updateAdvancedSearch(field, checked) {
    window.location.reload();
}

function toggleIcon(e) {
    $(e.target)
        .prev('.card-header')
        .find(".more-less")
        .toggleClass('glyphicon-plus glyphicon-minus');
}


$(document).ready(function () {
    options = {
        url: "bills.json",
        toggle: "table",
        trimOnSearch: false,
        pagination: true,
        search: true,
        //showColumns: true,
        cookie: true,
        cookieIdTable: "islamophobia",
        useRowAttrFunc: true,
        advancedSearch: true,
        advancedSearchIcon: "glyphicon-filter",
        idTable: "advancedTable",
        showExport: true,
        exportDataType: "all",
        columns: columns,
        filter: true,
        filterValues: {},
        onPostBody: function (data) {
            updateTotals(data);
            showBillModalByHash(data);
        },
        onColumnSwitch: updateAdvancedSearch
    };
    $.get("choices.json", function (data) {
        // Update filter choices
        for (var i = 0; i < options.columns.length; i++) {
            var column = options.columns[i];
            if (data.hasOwnProperty(column.field) && !column.filter.data) {
                column.filter.type = "select";
                column.filter.data = data[column.field];
            }
        }
        table = $('#table').bootstrapTable(options);

        // Set state options
        var state_select = [];
        state_select.push('<div class="row">');
        state_select.push('<div class="col-sm-3 filter-state">');
        state_select.push('<select id="filter-state" class="form-control select2">');
        state_select.push('<option value=""></option>');
        for (i = 0; i < data.state.length; i++) {
            var state = data.state[i];
            state_select.push('<option value="' + i + '">' + state + '</option>');
        }
        state_select.push('</select>');
        state_select.push('</div>');
        state_select.push('</div>');
        $('.fixed-table-toolbar').append($(state_select.join('')));
        $('#filter-state').select2({
            allowClear: true,
            placeholder: 'Filter by state'
        }).change(function () {
            // Trigger search
            $('#advancedSearch #state').val($(this).val()).trigger('change');
        });
        $('#advancedSearch #state').change(function () {
            $('#filter-state').val($(this).val());
        });
    });
    $('#toolbar').find('select').change(function () {
        $("#table").bootstrapTable('destroy').bootstrapTable({
            exportDataType: $(this).val()
        });
    });

    $('.panel-group').on('hidden.bs.collapse', toggleIcon);
    $('.panel-group').on('shown.bs.collapse', toggleIcon);

    $(".islamophobia-database-links[href^='#']").on('click', function(e) {

       // prevent default anchor click behavior
       e.preventDefault();

       // store hash
       var hash = this.hash;

       // animate
       $('html, body').animate({
           scrollTop: $(hash).offset().top
         }, 300, function(){

           // when done, add hash to url
           // (default click behaviour)
           window.location.hash = hash;
         });
    });
});