﻿var map = null;
var maptimize = null;
var geocoder = null;
//var mgr = null;
var maxTableRows = 500;
var defaultMinZoom = 5;
var minZoom = defaultMinZoom;
var xmlfile = "./outputxml.aspx";
var zoomTowerMessage = "<p style='font-size:12px;'>Zoom in to see tower details</p>";
var noTowerMessage = "<p style='font-size:12px;'>No towers found</p>";

var stateZooms = new Array();

stateZooms["AL"] = 6;
stateZooms["AK"] = 4;
stateZooms["AZ"] = 5;
stateZooms["AR"] = 6;
stateZooms["CA"] = 4;
stateZooms["CO"] = 6;
stateZooms["CT"] = 8;
stateZooms["DE"] = 8;
stateZooms["DC"] = 10;
stateZooms["FL"] = 5;
stateZooms["GA"] = 5;
stateZooms["HI"] = 6;
stateZooms["ID"] = 5;
stateZooms["IL"] = 6;
stateZooms["IN"] = 6;
stateZooms["IA"] = 6;
stateZooms["KS"] = 6;
stateZooms["KY"] = 6;
stateZooms["LA"] = 5;
stateZooms["ME"] = 6;
stateZooms["MD"] = 7;
stateZooms["MA"] = 7;
stateZooms["MI"] = 5;
stateZooms["MN"] = 5;
stateZooms["MS"] = 6;
stateZooms["MO"] = 6;
stateZooms["MT"] = 5;
stateZooms["NE"] = 6;
stateZooms["NV"] = 5;
stateZooms["NH"] = 6;
stateZooms["NJ"] = 6;
stateZooms["NM"] = 5;
stateZooms["NY"] = 6;
stateZooms["NC"] = 6;
stateZooms["ND"] = 6;
stateZooms["OH"] = 6;
stateZooms["OK"] = 6;
stateZooms["OR"] = 6;
stateZooms["PA"] = 6;
stateZooms["RI"] = 8;
stateZooms["SC"] = 7;
stateZooms["SD"] = 6;
stateZooms["TN"] = 6;
stateZooms["TX"] = 5;
stateZooms["UT"] = 5;
stateZooms["VT"] = 6;
stateZooms["VA"] = 6;
stateZooms["WA"] = 5;
stateZooms["WV"] = 6;
stateZooms["WI"] = 6;
stateZooms["WY"] = 6;


function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.enableDoubleClickZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(34.597041, -96.679687), 4);

        // create theme
        var theme = {
            markerOptions: { icon: new GIcon({ image: "/images/map/Magenta_Tower.png",
                iconSize: new GSize(40, 40),
                iconAnchor: new GPoint(20, 20),
                infoWindowAnchor: new GPoint(20, 20),
                infoShadowAnchor: new GPoint(20, 20)
            })
            },
            clusterOptions: [
                { icon: new GIcon({ image: "/images/map/yellow.png",
                    iconSize: new GSize(40, 40),
                    iconAnchor: new GPoint(20, 20),
                    infoWindowAnchor: new GPoint(20, 20),
                    infoShadowAnchor: new GPoint(20, 20)
                }),
                    labelClass: 'maptimize_cluster_0',
                    labelOffset: new GSize(-25, -24)
                },
                { icon: new GIcon({ image: "/images/map/orange.png",
                    iconSize: new GSize(50, 50),
                    iconAnchor: new GPoint(25, 25),
                    infoWindowAnchor: new GPoint(25, 25),
                    infoShadowAnchor: new GPoint(25, 25)
                }),
                    labelClass: 'maptimize_cluster_1',
                    labelOffset: new GSize(-29, -28)
                },
                { icon: new GIcon({ image: "/images/map/magenta.png",
                    iconSize: new GSize(50, 50),
                    iconAnchor: new GPoint(25, 25),
                    infoWindowAnchor: new GPoint(25, 25),
                    infoShadowAnchor: new GPoint(25, 25)
                }),
                    labelClass: 'maptimize_cluster_2',
                    labelOffset: new GSize(-31, -31)
                },
                { icon: new GIcon({ image: "/images/map/purple.png",
                    iconSize: new GSize(60, 60),
                    iconAnchor: new GPoint(30, 30),
                    infoWindowAnchor: new GPoint(30, 30),
                    infoShadowAnchor: new GPoint(30, 30)
                }),
                    labelClass: 'maptimize_cluster_3',
                    labelOffset: new GSize(-36, -35)
                }
                ],

            createMarker: function(marker) {
                return new GMarker(marker.getGLatLng(), theme.markerOptions);
            },

            createCluster: function(cluster) {
                var pointsCount = cluster.getPointsCount();
                var indexLevel = Math.min(parseInt(Math.log(pointsCount) / Math.log(10)), theme.clusterOptions.length - 1);
                var options = theme.clusterOptions[indexLevel];
                options.labelText = pointsCount;
                return new Maptimize.LabeledMarker(cluster.getGLatLng(), options);
            }
        };

        // Attach maptimize service
        maptimize = new Maptimize.Map(map, {
            theme: theme,
            onMarkerClicked: function(marker) {
            
                // marker: is an instance of Maptimize.Marker

                // Open info window with response as content when receive response
                displayMapPopup(marker);
            },
            onZoomMaxClusterClicked: function(cluster, ids) {
                alert('Multiple towers found at this address!');
                var content = ['IDs: ' + ids.join(','),
                       'Latitude: ' + cluster.getGLatLng().lat(),
                       'Longitude: ' + cluster.getGLatLng().lng()]
                cluster.getGMarker().openInfoWindowHtml(content.join('<br/>'));
            }
        });

        geocoder = new GClientGeocoder();
        GEvent.addListener(map, "dragend", function() { refreshMarkers('drag') });
        GEvent.addListener(map, "zoomend", function() { refreshMarkers('zoom') });
    } // GBrowserIsCompatible
} // initialize()

// rebuilds the tower list table below the map
// Sean Patterson    4/13/2011   [Updated]
//                               Updated querydata variable to include
//                               county information where applicable.
function refreshMarkers(mode) {

    // flag that a search has been done so filters can be supressed
    if (mode == "search") {
        document.getElementById('didSearch').value = "yes";
    } else {
        // change mode to search when a valid event fires
        if (document.getElementById('didSearch').value == "yes") {
            mode = "userEvent";
            // reset min zoom away from state special zoom
            minZoom = defaultMinZoom;
        }
    }

    // always disable the export button; we'll reenable later if needed
    document.getElementById("csvbutton").disabled = true;
    document.getElementById("kmlbutton").disabled = true;

    // always load the tower data table if we're zoomed in far enough, but only build the table if there aren't too many points
    if (map.getZoom() > minZoom) {
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();

        var selCounties = document.getElementById('county');
        var index = selCounties.selectedIndex;
        var splitResult = selCounties[index].value.split("|");
        var countyValue = '';

        if (index == 0) 
        {
           countyValue = '';
        }
        else
        {
           countyValue = splitResult[0];
        }

        var querydata = "lonne=" + northEast.lng() + "&latne=" + northEast.lat() + "&lonsw=" + southWest.lng() + "&latsw=" + southWest.lat() + "&structuretype=" + document.getElementById('type').value + "&status=" + document.getElementById('inventory_status').value;
        switch (document.getElementById('tabid').value) {
            case "0":
                querydata += "&county=" + countyValue + "&state=" + document.getElementById('state').value + "&zip=" + document.getElementById('zip').value + "&city=" + document.getElementById('city').value + "&towerid=";
                break;
            case "1":
               querydata += "&county=&state=&zip=&city=&towerid=";
                break;
            case "2":
               querydata += "&county=&state=&zip=&city=" + "&towerid=" + document.getElementById('towerid').value;
                break;
            default:
               querydata += "&county=&state=" + document.getElementById('state').value + "&zip=" + document.getElementById('zip').value + "&city=" + document.getElementById('city').value + "&towerid=";
                break;
        }

        querydata += "&mode=" + mode;
        // alert(xmlfile + "?type=moveend&" + querydata + "&state=" + document.getElementById('state').value + "&zip=" + document.getElementById('zip').value + "&city=" + document.getElementById('city').value + "&towerid=" + document.getElementById('towerid').value + "&mode=" + mode);
        // document.write(xmlfile + "?type=moveend&" + querydata + "&state=" + document.getElementById('state').value );
        GDownloadUrl(xmlfile + "?type=moveend&" + querydata, function(data) {
            var rowData = '<table style="width:100%;" cellspacing="3"><tr style="font-weight:bold;"><td>No.</td><td>Site No.</td><td>Name</td><td>City/State/Postal Code</td><td>County</td><td>Type</td><td style="width:60px"></td><td style="width:60px"></td></tr>';
            var xml = GXml.parse(data);

            var countElements = xml.documentElement.getElementsByTagName("count");
            if (countElements && countElements.length > 0) {
                if (countElements[0].getAttribute("num") > 0 && countElements[0].getAttribute("num") <= maxTableRows) {

                    var markers = xml.documentElement.getElementsByTagName("marker");

                    for (var i = 0; i < markers.length; i++) {
                        var curMarker = markers[i];
                        var siteid = curMarker.getAttribute("siteid");
                        var sitename = curMarker.getAttribute("towername");
                        var citystatezip = curMarker.getAttribute("address2");
                        var county = curMarker.getAttribute("county");
                        var towertype = curMarker.getAttribute("type");
                        var applyMode = escape(document.getElementById('applyMode').value);

                        rowData = rowData + "<tr><td >" + (i + 1) + "</td><td><a href=\"javascript:openTowerDetail('" + siteid + "');\">" + siteid + "</a></td><td>" + sitename + "</td><td>" + citystatezip + "</td><td>" + county + "</td><td>" + towertype + "</td><td><b><a href=\"javascript:openTowerDetail('" + siteid + "');\"><img src='/images/details.jpg' border=0></a></b></td><td><b><a href='GoApply.aspx?towerid=" + siteid + "&mode=" + applyMode + "'><img src='/images/apply.jpg' border=0></a></b></td></tr>";
                    }
                    document.getElementById("TowerDataArea").innerHTML = rowData + '</table>';

                    document.getElementById("csvlink").href = "getCSV.aspx?" + querydata;
                    document.getElementById("csvbutton").disabled = false;
                    document.getElementById("kmllink").href = "getKML.aspx?" + querydata;
                    document.getElementById("kmlbutton").disabled = false;
                } else if (countElements[0].getAttribute("num") == 0) {
                    document.getElementById("TowerDataArea").innerHTML = noTowerMessage;
                } else {
                    document.getElementById("TowerDataArea").innerHTML = zoomTowerMessage;
                }
            } else {
                document.getElementById("TowerDataArea").innerHTML = zoomTowerMessage;
            }
        });
    }
    else {
        document.getElementById("TowerDataArea").innerHTML = zoomTowerMessage;
    }
}

// Sean Patterson     4/4/2011   [Updated]
//                               Updated method to check for county search and
//                               process that before a state search.
// Sean Patterson    4/13/2011   [Updated]
//                               Updated method to map bounds of location found to
//                               better dispaly an entire county in the search results.
function searchLocations(addressstring) {

    // reset back to filtering results by location info
   document.getElementById('didSearch').value = "no";
    document.getElementById('tabid').value = 0;

    var selCounties = document.getElementById('county');
    var index = selCounties.selectedIndex;
    var countyValue = '';

    if (index > 0) 
    {
       var splitResult = selCounties[index].value.split("|");
       countyValue = splitResult[0] + ' County';
    }     
 
    if (addressstring === undefined) 
    {
        addressstring = document.getElementById('street').value + ' ' + document.getElementById('city').value + ' ' + countyValue + ' ' + document.getElementById('state').value + ' ' + document.getElementById('zip').value;
        addressstring = addressstring.replace(/^\s+|\s+$/g, '');
        var zoomlevel = 11;
        // reset here - state search will override as needed
        minZoom = defaultMinZoom;
        if ((document.getElementById('street').value == "") && (document.getElementById('zip').value == "")) { zoomlevel = 11; }
        // state search typically
        if (addressstring.length == 2) {
            if (document.getElementById('state').value != "") {
                zoomlevel = stateZooms[document.getElementById('state').value];
                minZoom = zoomlevel - 1;
            } else {
                zoomLevel = 7;
            }
        }
    }
    addressstring = addressstring + ", USA";
    geocoder.getLatLng(addressstring, function(latlng) {
       if (!latlng) {
          alert(addressstring + ' not found');
       }
       else {
          //map.setCenter(latlng, zoomlevel);
          geocoder.getLocations(addressstring, function(locations) 
          {
             var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
             var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
             var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
             var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
             var bounds = new GLatLngBounds(new GLatLng(south, west),
                                             new GLatLng(north, east));
             
             map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));   
          });

          refreshMarkers('search');
       }
    });
}

function searchTowers() {
    var towerID = document.getElementById('towerInput').value;
    GDownloadUrl(xmlfile + "?type=findtower&id=" + towerID + "&state=" + document.getElementById('state').value + "&zip=" + document.getElementById('zip').value + "&city=" + document.getElementById('city').value, function(data) {

        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        if (markers.length > 0) {
            var latlng = new GLatLng(parseFloat(markers[0].getAttribute("lat")), parseFloat(markers[0].getAttribute("lng")));
            map.setCenter(latlng, 13);
            refreshMarkers('search');
        }
        else {
            alert("No Towers found");
        }
    });
}

function searchMTA(element_id) {
    var MTA = document.getElementById(element_id).value;
    GDownloadUrl(xmlfile + "?type=MTA&id=" + MTA, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        if (markers.length > 0) {
            var latlng = new GLatLng(parseFloat(markers[0].getAttribute("lat_center")), parseFloat(markers[0].getAttribute("lon_center")));
            map.setCenter(latlng, 11);
            refreshMarkers('search');
        }
        else {
            alert("No Towers found");
        }
    });
}

function searchBTA(element_id) {
    var BTA = document.getElementById(element_id).value;
    GDownloadUrl(xmlfile + "?type=BTA&id=" + BTA, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        if (markers.length > 0) {
            var latlng = new GLatLng(parseFloat(markers[0].getAttribute("lat_center")), parseFloat(markers[0].getAttribute("lon_center")));
            map.setCenter(latlng, 11);
            refreshMarkers('search');
        }
        else {
            alert("No Towers found");
        }
    });
}

function searchTowerID() {
    var towerid = document.getElementById('towerid').value;
    $get('tabid').value = 2;
    GDownloadUrl(xmlfile + "?type=findtower&id=" + towerid, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        if (markers.length > 0) {
            var latlng = new GLatLng(parseFloat(markers[0].getAttribute("lat_center")), parseFloat(markers[0].getAttribute("lon_center")));
            map.setCenter(latlng, 13);
            refreshMarkers('search');
            
            setTimeout("waitAndDisplayPopup()", 3000);
        }
        else {
            alert("No Towers found");
        }
    });
}

function waitAndDisplayPopup()
{
    var towerid = document.getElementById('towerid').value;
    var maptimizeMarkers = maptimize.getMarkers();
    for (var index = 0; index < maptimizeMarkers.length; index++)
    {
        if (maptimizeMarkers[index].getId() == towerid)
            displayMapPopup(maptimizeMarkers[index]);
    }
}

function setMap(lat, lng, zoomlevel) {

    var zoom = parseInt(zoomlevel);

    var latlon = new GLatLng(lat, lng)
    map.setCenter(latlon, zoom);
    refreshMarkers('search');
}

function searchCoords() {
    var latinput = document.getElementById('latitude').value
    var loninput = document.getElementById('longitude').value
    $get('tabid').value = 1;

    var latlon = new GLatLng(latinput, loninput)
    map.setCenter(latlon, 13);
    refreshMarkers('search');
}

// Sean Patterson     5/8/2011   [Updated]
//                               Updated method to include county processing.
function openTowerDetail(towerID) {

    // also save search	
    var street = escape(document.getElementById('street').value);
    var city = escape(document.getElementById('city').value);
    var state = escape(document.getElementById('state').value);
    var zip = escape(document.getElementById('zip').value);
    var county = escape(document.getElementById('county').value);

    var latitude = escape(document.getElementById('latitude').value);
    var longitude = escape(document.getElementById('longitude').value);
    var BTA = escape(document.getElementById('ctl00_ctl00_MasterContent_PageContent_BTA').value);
    var MTA = escape(document.getElementById('ctl00_ctl00_MasterContent_PageContent_MTA').value);

    //var radius 	= escape(document.getElementById('radius').value);
    var type = escape(document.getElementById('type').value);
    var inventory_status = escape(document.getElementById('inventory_status').value);
    var tabid = escape(document.getElementById('tabid').value);

    var applyMode = escape(document.getElementById('applyMode').value);

    window.location.href = "TowerDetail.aspx?towerid=" + towerID + "&a=" + street + "&c=" + city + "&s=" + state + "&zip=" + zip + "&county=" + county + "&lat=" + latitude + "&lon=" + longitude + "&b=" + BTA + "&m=" + MTA + "&t=" + type + "&i=" + inventory_status + "&mlat=" + map.getCenter().lat() + "&mlng=" + map.getCenter().lng() + "&mz=" + map.getZoom() + "&tabid=" + tabid + "&mode=" + applyMode;
}


function saveSearch(btaid, mtaid) {

    var street = escape(document.getElementById('street').value);
    var city = escape(document.getElementById('city').value);
    var state = escape(document.getElementById('state').value);
    var zip = escape(document.getElementById('zip').value);
    var county = escape(document.getElementById('county').value);

    // The pipe character is HTML encoded. If only the pipe exists, then no
    // item has been specified.
    if (county == '%7C')
    {
       county = '';
    }

    var latitude = escape(document.getElementById('latitude').value);
    var longitude = escape(document.getElementById('longitude').value);
    var BTA = escape(document.getElementById(btaid).value);
    var MTA = escape(document.getElementById(mtaid).value);

    var towerid = escape(document.getElementById('towerid').value);

    //var radius 	= escape(document.getElementById('radius').value);       
    var type = escape(document.getElementById('type').value);
    var inventory_status = escape(document.getElementById('inventory_status').value);
    var tabid = escape(document.getElementById('tabid').value);

    window.location.href = "MyAccount/TowerSaveSearch.aspx?a=" + street + "&c=" + city + "&s=" + state + "&zip=" + zip + "&county=" + county + "&lat=" + latitude + "&lon=" + longitude + "&b=" + BTA + "&m=" + MTA + "&tid=" + towerid + "&t=" + type + "&i=" + inventory_status + "&mlat=" + map.getCenter().lat() + "&mlng=" + map.getCenter().lng() + "&mz=" + map.getZoom() + "&tabid=" + tabid;
}

function resetdd(cntlid) {
    var cntl = document.getElementById(cntlid);
    cntl.value = 0;
    //return false;
}

function displayMapPopup(marker){
    var xmlhttp = false;
    // from http://www.ibm.com/developerworks/web/library/wa-ajaxintro2/
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                xmlhttp = false;
            }
        }
    }

    if (!xmlhttp) {
        alert("Error initializing XMLHttpRequest!");
    } else {
        xmlhttp.open('GET', '/MapTowerDetails.aspx?id=' + marker.getId() + '&applyMode=' + escape(document.getElementById('applyMode').value), true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    return marker.getGMarker().openInfoWindowHtml(xmlhttp.responseText);
                } else {
                    alert("Error: status code is " + xmlhttp.status);
                }
            }
        }
        xmlhttp.send(null);
    }
}
