function closePrint () {
    document.body.removeChild(this.__container__);
}

function setPrint () {
    this.contentWindow.__container__ = this;
    this.contentWindow.onbeforeunload = closePrint;
    this.contentWindow.onafterprint = closePrint;
    this.contentWindow.focus(); // Required for IE
    this.contentWindow.print();
}

function printPage (sURL) {
    var oHiddFrame = document.createElement("iframe");
    oHiddFrame.onload = setPrint;
    oHiddFrame.style.visibility = "hidden";
    oHiddFrame.style.position = "fixed";
    oHiddFrame.style.right = "0";
    oHiddFrame.style.bottom = "0";
    oHiddFrame.src = sURL;
    document.body.appendChild(oHiddFrame);
}


$(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, null);
    });
    $(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();
        var licenseStatus = $(this).find('td:nth-child(5)').text();
        runIndividualLookup(recordType, license, licenseStatus);
    });
    $(document).on('click', '#hyperlink-firm-name', function() {
        var license = $(this).data("license");
        runIndividualLookup("Firm", license, null);
    });
    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, licenseStatus) {
	if (!licenseStatus) {
		licenseStatus = '';
	}
        $.ajax({
            url: "ajax_lookup.php",
            dataType: "json",
            data: {
                recordType: recordType,
                license: license,
		licenseStatus: licenseStatus
            },
            success: function (data) {
                $("#dialog-show-detail").dialog("option", "height", 430);
                $("#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", 630);
                    }
                } else {
                    $("#detail-data").html(renderFirmDetail(data));
                    if (data.data.complaints.toLowerCase() == 'yes') {
                        $("#dialog-show-detail").dialog("option", "height", 630);
                    }
                    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 = '';
        html +="<div id='print-link'><a href='javascript:;' onclick=\"printPage('print.php?recordType=Individual&license=" + data.license_no + "');return false;\">"
            + "<div class=\"boa-print\"></div><span>Print</span></a></div>";

        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 = '';
        html +="<div id='print-link'><a href='javascript:;' onclick=\"printPage('print.php?recordType=Firm&license=" + firmData.license_no + "');return false;\">"
            + "<div class=\"boa-print\"></div><span>Print</span></a></div>";

        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 Joel Parks at 503-378-2262 or by e-mail at joel.parks@oregon.gov" +
            "</div>";
        }
        return html;
    }
    function doFirmNameLink(name, license) {
        if (typeof name != 'undefined' && name != '') {
            return "<a id=\"hyperlink-firm-name\" data-license=\"" + license + "\">" + name + "</a>";
        }
        return '';
    }

});
