var $j=jQuery.noConflict();
$j(document).ready(function(){
    var providerInfo;
    $j.ajax({
            url: 'https://s3-us-west-2.amazonaws.com/geolpublist/json/providers_20180424.json',
            dataType: 'json',
            type: 'Get',
            success: function (data) {
                providerInfo = data;
                // Find records in the json file that match the county that the user clicked on the map.
                var countySearchTable = $j("#countySearchTable");
                var countyTableElem = '<table id=countyTable></table>';
                countySearchTable.append(countyTableElem);
                var providerObjStr = '<tbody >';
                providerObjStr += '<tr class="dataRows">';
                if (providerInfo&& providerInfo.length > 0) {
                    // Add the data to the table for this county
                    providerInfo.forEach(function (providerObj, i) {
                        providerObjStr += '<tr class="dataRows">';
                        providerObjStr += '<td>' + providerObj.Organization + '</td>';
                        providerObjStr += '<td>' + providerObj.Contact + '</td>';
                        providerObjStr += '<td>' + providerObj.Street + '</td>';
                        providerObjStr += '<td>' + providerObj.City + '</td>';
                        providerObjStr += '<td>' + providerObj.Phone + '</td>';
                        providerObjStr += '<td>' + providerObj.Email + '</td>';
                        providerObjStr += '<td>' + providerObj.Website + '</td>';
                        providerObjStr += '<tr>';
                    });
                    providerObjStr += '</tbody >';
                    $j('#provider_table tbody').html('');
                    $j('#provider_table').append(providerObjStr);
                }
            }
        }
    );
    function countySearch() {
        //Get width and heigth of Div
        var width = d3.select("#countySearch").style("width"),
            height = 420,
            scale;
        width = width.substring(0, width.length - 2);
        if(isNaN(width)){
            width = 550
        }
        if (width > 500 && width < 700) scale = width * 10;
        else if (width >= 700 && width < 1000) scale = width * 7;
        else if (width >= 1000 && width < 1500) scale = width * 4;
        else if (width >= 1500 && width < 2000) scale = width * 3;
        else if (width >= 2000) scale = width * 1.5;
        else scale = width * 10;
        //Set projection to projection close to State Plane
        var projection = d3.geo.conicConformal()
            .rotate([120.5, 0])
            .center([0, 47.3])
            .parallels([45.83, 47.33])
            .scale(scale)
            //center
            .translate([width / 2, height / 2])
            .precision(.1);
        //load projection into path variable
        var path = d3.geo.path()
            .projection(projection);
        var svg = d3.select("#countySearch").append("svg")
            .attr("width", width)
            .attr("height", height);
        var g = svg.append("g");
        queue()
            .defer(d3.json, "https://s3-us-west-2.amazonaws.com/geolpublist/counties.json")
            .defer(d3.json, "https://s3-us-west-2.amazonaws.com/geolpublist/cities.json")
            .await(drawMap);

        function drawMap(error, wa, cities) {
            g.append("g")
                .attr("id", "state")
                .selectAll("path")
                .data(topojson.feature(wa, wa.objects.counties).features)
                .enter().append("path")
            //draw coords
                .attr("d", path)
                //selects each piece
                .attr("class", "county")
                .on("mouseup", function (d) {
                    //queryCounty(d.properties.COUNTY_LAB);
                    queryCounty(d.properties.COUNTY_CD);
                });
            //append city
            g.append("g")
                .attr("id", "cities")
                .selectAll("path")
                .data(topojson.feature(cities, cities.objects.cities).features)
                .enter().append("path")
                .attr("d", path.pointRadius(3))
                .attr("class", "city");
            //label
            g.append("g")
                .attr("id", "names")
                .selectAll("labels")
                .data(topojson.feature(cities, cities.objects.cities).features)
                .enter().append("text")
                .attr("transform", function (d) {
                    return "translate(" + projection(d.geometry.coordinates) + ")";
                })
                .attr("dy", -5)
                .attr("dx", -2)
                .text(function (d) {
                    return d.properties.NAME;
                })
                .attr("class", "labels");
        }

        function queryCounty(county) {
            console.log(county);
            //console.log($j('#countySearchTable'));
            var countySearchTable = $j("#countySearchTable");
            var countyTableElem = '<table id=countyTable></table>';
            countySearchTable.append(countyTableElem);
            var countyTable = $j("#countyTable");
            countyTable.empty();  // Clear any rows in table
            // Check that provider info and county variables are valid
            if (county && providerInfo && providerInfo.length > 0) {
                // Find records in the json file that match the county that the user clicked on the map.
                var providerObjArr = findObjectsByKey(providerInfo, 'COUNTY_CD', county);
                var newRow;
                var providerObjStr = '<tbody >';
                providerObjStr += '<tr class="dataRows">';
                if (providerObjArr && providerObjArr.length > 0) {
                    // Add the data to the table for this county
                    providerObjArr.forEach(function (providerObj, i) {
                        providerObjStr += '<tr class="dataRows">';
                        providerObjStr += '<td>' + providerObj.Organization + '</td>';
                        providerObjStr += '<td>' + providerObj.Contact + '</td>';
                        providerObjStr += '<td>' + providerObj.Street + '</td>';
                        providerObjStr += '<td>' + providerObj.City + '</td>';
                        providerObjStr += '<td>' + providerObj.Phone + '</td>';
                        providerObjStr += '<td>' + providerObj.Email + '</td>';
                        providerObjStr += '<td>' + providerObj.Website + '</td>';
                        providerObjStr += '<tr>';
                    });
                    providerObjStr += '</tbody >';
                    $j('#provider_table tbody').html('');
                    $j('#provider_table').append(providerObjStr);
                }
                else {
                    countyTable.empty();
                    countySearchTable = $j("#countySearchTable");
                    countyTableElem = '<table id=countyTable></table>';
                    countySearchTable.append(countyTableElem);
                        providerObjStr = '<tbody >';
                        providerObjStr +=  '<tr><td id="noData" colspan="100">' + "No data available for county" + '</td></tr>';
                        providerObjStr += '<tr class="dataRows">';
                            // Add the data to the table for this county
                            providerInfo.forEach(function (providerObj, i) {
                                providerObjStr += '<tr class="dataRows">';
                                providerObjStr += '<td>' + providerObj.Organization + '</td>';
                                providerObjStr += '<td>' + providerObj.Contact + '</td>';
                                providerObjStr += '<td>' + providerObj.Street + '</td>';
                                providerObjStr += '<td>' + providerObj.City + '</td>';
                                providerObjStr += '<td>' + providerObj.Phone + '</td>';
                                providerObjStr += '<td>' + providerObj.Email + '</td>';
                                providerObjStr += '<td>' + providerObj.Website + '</td>';
                                providerObjStr += '<tr>';
                            });
                            providerObjStr += '</tbody >';
                            $j('#provider_table tbody').html('');
                            $j('#provider_table').append(providerObjStr);
                }

            }
            else {
                console.log("No data");
            }

        }

        function findObjectsByKey(array, key, value) {
            // Returns the matching elements in an array who's key matches the value passed in
            var objArr = [];
            for (var i = 0; i < array.length; i++) {
                if (array[i][key] === value) {
                    // Add object to return array
                    objArr.push(array[i]);
                }
            }
            return objArr;
        }
    }
    countySearch();
});