$(document).ready(function() {
    $("#search-term").focus();
    $("#search-term").keypress(function(e) {
        code = (e.keyCode ? e.keyCode: e.which);
        if (code == 13) { // enter key
            runSearch();
        }
    });
    $("#display-filter-results").click(function() {
       $("#tr-filters").toggle();
    });


    $('#license-status').change(function() {
        runSearch();
    });
    $('#license-type').change(function() {
        runSearch();
    });
    $("#search-licensees-button").click(function() {
        runSearch();
    });
    $('#search-term').autocomplete( {
        minLength: 2,
        source: runSearch
    });

    $(document).on('click', "#licensees-list tr.row-data", function() {
        var license = $(this).find('td:nth-child(4)').text();
        runIndividualLookup("Individual", license);
    });
    $(document).on('click', '#results-table tr.row-data', function() {
        var recordType = $(this).find('td:first').text();
        var license = $(this).find('td:nth-child(2)').text();
        runIndividualLookup(recordType, license);
    });
    $(document).on('click', '#hyperlink-firm-name', function() {
        var license = $(this).data("license");
        runIndividualLookup("Firm", license);
    });
    var detailDialog = $( "#dialog-show-detail" ).dialog({
        autoOpen: false,
        height: 400,
        width: 850,
        //position: {my: "top-85%"},
        position : {
            my: "left+20 top+20",
            at: "left top",
            of: window
        },
        modal: true
    });

    function runIndividualLookup(recordType, license) {
        $.ajax({
            url: "ajax_lookup.php",
            dataType: "json",
            data: {
                recordType: recordType,
                license: license
            },
            success: function (data) {
                $("#dialog-show-detail").dialog("option", "height", 400);
                $("#dialog-show-detail").dialog("option", "width", 465);

                if (recordType == 'Individual') {
                    $("#detail-data").html(renderIndividualDetail(data));
                    if (data.complaints.toLowerCase() == 'yes') {
                        $("#dialog-show-detail").dialog("option", "height", 600);
                    }
                } else {
                    $("#detail-data").html(renderFirmDetail(data));
                    if (data.data.complaints.toLowerCase() == 'yes') {
                        $("#dialog-show-detail").dialog("option", "height", 600);
                    }
                    if (data.licensees.length > 0) {
                        $("#dialog-show-detail").dialog("option", "width", 850);
                    }

                }
                detailDialog.dialog( "open" );
            }
        });
    }


    function runSearch() {
        $("#loading").show();
        var status = $("#license-status option:selected").val();
        var type = $("#license-type option:selected").val();
        var qt = $("#search-term").val();

        if (qt === '' && status === '' && type === '') {
            alert("Please select or enter search criteria in order to perform a search.");
            return;
        }

        // clean up the query term and remove punctuation and replace with a " " (space)
        var punctuationless = qt.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
        var finalQt = punctuationless.replace(/\s{2,}/g," ");

        $.ajax({
            url: "ajax_search.php",
            dataType: "json",
            data: {
                qt: finalQt,
                status: status,
                type: type
            },
            success: function (data) {
                var count = data.length;
                var itemsOnPage = 20;
                $("#search-results-count").html(count);
                $("#search-results-count-records").html("records");
                if (count == 1) {
                    $("#search-results-count-records").html("record");
                }
                $("#search-results-description").show();

                var dataToBeRendered = data.slice(0, itemsOnPage);
                $("#search-results").html(renderTableData(dataToBeRendered, finalQt));

                if (count < itemsOnPage) {
                    $(".search-results-pagination").pagination("destroy");
                } else {
                    $(".search-results-pagination").pagination({
                        items: count,
                        itemsOnPage: itemsOnPage,
                        cssStyle: 'light-theme',
                        onPageClick : function(pageNumber) {
                            var startIndex = itemsOnPage * (pageNumber - 1);
                            var endIndex = startIndex + itemsOnPage;

                            dataToBeRendered = data.slice(startIndex, endIndex);
                            $("#search-results").html(renderTableData(dataToBeRendered, finalQt));


                        }
                    });
                }
                $("#loading").hide();
                $("#results-top-table").show();

            }
        })
    }
    function renderTableData(data, qt) {
        var html = "<table id=\"results-table\"><thead><tr><th>Type</th><th>License</th><th>Name</th><th>Address</th><th>Status</th><th>Expires</th><th>Disciplinary</th></tr></thead><tbody>";
        $.each(data, function(index, value) {
            html += "<tr class=\"row-data\">";
            html += "<td>" + value.type + "</td>";
            html += "<td>" + highlightPattern(value.license, qt) + "</td>";
            html += "<td>" + highlightPattern(value.name, qt) + "</td>";
            html += "<td>" + highlightPattern(value.address, qt) + "</td>";
            html += "<td>" + value.status + "</td>";
            html += "<td>" + value.expires + "</td>";
            html += "<td>" + value.complaints + "</td>";
            html += "</tr>";
        });
        html += "</tbody></table>";
        return html;
    }
    function highlightPattern(text, pattern) {
        if (pattern === '') {
            return text;
        }
        var trimmed = $.trim(pattern);
        var patterns = trimmed.split(" ");
        var newText = text;

        for (var i = 0; i < patterns.length; i++ ) {
            var regex = new RegExp( '(' + patterns[i] + ')', 'gi' );
            newText = newText.replace( regex, "<span class=\"highlight-pattern\">$1</span>" );

        }
        return newText;
    }
    function renderIndividualDetail(data) {
        var html = "<table><thead><tr><th colspan=\"2\">Individual Information</th></tr></thead><tbody>";
        html += "<tr><td>License Number</td><td>"+ data.license_no +"</td></tr>";
        html += "<tr><td>Status</td><td>"+ data.status +"</td></tr>";
        html += "<tr><td>Type</td><td>"+ data.type +"</td></tr>";
        html += "<tr><td>Name</td><td>"+ data.full_name +"</td></tr>";
        html += "<tr><td>Address</td><td>"+ doAddress(data) +"</td></tr>";
        html += "<tr><td>Date License Granted</td><td>"+ data.date_licensed +"</td></tr>";
        html += "<tr><td>Expires</td><td>"+ data.date_expires +"</td></tr>";
        html += "<tr><td>Firm Name</td><td>"+ doFirmNameLink(data.firm_name, data.firm_id) +"</td></tr>";
        html += "<tr><td>Muni</td><td>"+ data.muni +"</td></tr>";
        html += "<tr><td>CPE Carryover Hours</td><td>"+ data.cpe_carryover +"</td></tr>";
        html += "<tr><td>Disciplinary</td><td>"+ data.complaints +"</td></tr>";
        html += "</tbody></table>";

        html += doComplaints(data.complaints);
        return html;

    }
    function renderFirmDetail(data) {
        var firmData = data.data;
        var html = "<div id=\"firm-left\"><table><thead><tr><th colspan=\"2\">Firm Information</th></tr></thead><tbody>";
        html += "<tr><td>Firm Number</td><td>"+ firmData.license_no +"</td></tr>";
        html += "<tr><td>Name</td><td>"+ firmData.name +"</td></tr>";
        html += "<tr><td>Address</td><td>"+ doAddress(firmData) +"</td></tr>";
        html += "<tr><td>Status</td><td>"+ firmData.status +"</td></tr>";
        html += "<tr><td>Type</td><td>"+ firmData.type +"</td></tr>";
        html += "<tr><td>Date License Granted</td><td>"+ firmData.date_granted +"</td></tr>";
        html += "<tr><td>Expires</td><td>"+ firmData.date_expires +"</td></tr>";
        html += "<tr><td>Managing Partner</td><td>"+ firmData.owner +"</td></tr>";
        html += "<tr><td>Disciplinary</td><td>"+ firmData.complaints +"</td></tr>";
        html += "</tbody></table>";
        html += doComplaints(firmData.complaints);
        html += "</div>";

        if (data.licensees.length > 0) {
            html += "<div id=\"firm-right\"><table id=\"licensees-list\"><thead><tr><th>Licensees</th><th>Expires</th><th>Status</th></thead><tbody>";
            $.each(data.licensees, function(index, value) {
                html += "<tr class=\"row-data\">";
                html += "<td>" + value.full_name2 + "</td>";
                html += "<td>" + value.date_expires + "</td>";
                html += "<td>" + value.status + "</td>";
                html += "<td>" + value.license_no + "</td>";
                html += "</tr>";
            });
            html += "</tbody></table></div>";
        }

        return html;
    }

    function doAddress(data) {
        var address = "";
        if (typeof data.address != 'undefined') {
            address += data.address;
        }
        if (typeof data.address1 != 'undefined' && data.address1 != '') {
            address += data.address1;
        }
        if (typeof data.address2 != 'undefined' && data.address2 != '') {
            address += data.address2;
        }
        if (data.city == '' || data.state == '') {
            address += "<br />" + data.city  + " " + data.state + " " + data.zip;
        } else {
            address += "<br />" + data.city  + ", " + data.state + " " + data.zip;
        }
        return address;
    }
    function doComplaints(complaints) {
        var html = "";
        if (complaints.toLowerCase() == "yes" ) {
            html += "<div id=\"complaints\"> A 'Yes' answer in the disciplinary column indicates that the " +
            "Oregon Board of Accountancy's record of the CPA, PA or registered firm includes a final outcome " +
            "of one or more disciplinary actions.  More detail on disciplinary actions is available on the " +
            "front page of the Board’s web site through the continually updated Disciplinary Action Report, " +
            "posted in alphabetical and chronological order.  Discipline is reported as 'yes' when the outcome " +
            "is a final resolution of the matter.  This means that if the Board has proposed disciplinary action," +
            " but the matter is not yet resolved either through a legal process or settlement agreement, it " +
            "will not be flagged with a 'Yes' in the disciplinary column. If you need additional information " +
            "on a disciplinary action beyond what is reported on the Board's web site, " +
            "please contact Bethany Reeves at 503-378-2270 or by e-mail at bethany.reeves@state.or.us" +
            "</div>";
        }
        return html;
    }
    function doFirmNameLink(name, license) {
        if (typeof name != 'undefined' && name != '') {
            return "<a id=\"hyperlink-firm-name\" data-license=\"" + license + "\">" + name + "</a>";
        }
        return '';
    }

});