
var marker=[];
var html=[];
var iwn=0;
var poet=[];
var latitude=[];
var longitude=[];
var country=[];
// red mini marker icon
var icon = new GIcon();
var geo = new GClientGeocoder();
var lat = [];
var lng = [];
var bounds = new GLatLngBounds();
var map;

function createTileLayer(baseUrl, start, end, tileExt, opacity)
{
    var myCopyrightCollection = new GCopyrightCollection("© ");
    var copyright = new GCopyright(1,
          new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180) ),
          14, "Skyhook Wireless");
    myCopyrightCollection.addCopyright(copyright);

    var tilelayer = new GTileLayer(myCopyrightCollection, start, end);
    tilelayer.getTileUrl = function(tile, zoom) { return baseUrl + "/" + zoom + "/" + tile.x + "/" + tile.y + "." + tileExt; };
    tilelayer.isPng = function() { return (tileExt=="png");};
    tilelayer.getOpacity = function() { return opacity; }

    return tilelayer;
};

function heatMap()
{
    window.onload = initFormFieldFocus;

    miniMarker=[];
    precis=[];
    icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    //icon.infoWindowAnchor = new GPoint(5, 1);

    map = new GMap(document.getElementById("map"));

    // Create tile layers

    // ====== Create a GCopyrightCollection =======
    var copycol = new GCopyrightCollection("");
    // ====== Create a GCopyright for each region and add them to the Collection
    // In this case theres one copyright for the entire map
    var copy1 = new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180)), 0, "Skyhook");
    copycol.addCopyright(copy1);

    var tileCoverageURL = "http://www.skyhookwireless.com/coverage/Layers";
    var tileCoverage = createTileLayer(tileCoverageURL, 8, 18, "png", 1.0);

    var layer1=[G_NORMAL_MAP.getTileLayers()[0],tileCoverage];
    var layer2=[G_SATELLITE_MAP.getTileLayers()[0],tileCoverage];

    var custommap1 = new GMapType(layer1, G_NORMAL_MAP.getProjection(), "Normal", G_NORMAL_MAP);
    var custommap2 = new GMapType(layer2, G_NORMAL_MAP.getProjection(), "Sat", G_SATELLITE_MAP);

    map.getMapTypes().length = 0;
    map.addMapType(custommap1);
    map.addMapType(custommap2);

    map.setCenter(new GLatLng(37.8,-122.4819), 6);

    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

    map.centerAndZoom(new GPoint(-99.08387, 39.66330), 14);
    map.enableContinuousZoom();
    map.enableDoubleClickZoom();

    //  ======== Add a map overview ==========
    map.addControl(new GOverviewMapControl(new GSize(100,100)));
    GEvent.addListener(map, 'zoom', function(oldZoomLevel, newZoomLevel) {
       if(newZoomLevel < 8) {
         map.zoomTo(Math.min(oldZoomLevel, 8));
       }
    })

    map.hideControls();
    ////'mouseover' listener shows controls
    GEvent.addListener(map, "mouseover", function(){
            map.showControls();
    });

    ////'mouseout' listener hides controls
    GEvent.addListener(map, "mouseout", function(){
            map.hideControls();
    });

    //	GEvent.addListener(map.getOverviewMapControl(), "changed", updatePageUrl)
    //  ======== Cause the overview to be positioned AFTER IE sets its initial position ========
    setTimeout("positionOverview()",1);map.setMapType(custommap1);

}

function initFormFieldFocus()
{
    focusField(document.getElementById("search"));
    return true;
}

function luokse(){
    map.zoomIn();map.zoomIn();map.zoomIn();
};

function createIW(name,pin,lati,longi,addr,iso){
    GEvent.addListener(pin, "click", function() {
            poet[iwn]=addr;
            latitude[iwn]=lati;
            longitude[iwn]=longi;
            country[iwn]=iso;
            var closer = "<a href=javascript:luokse();>See Closer</a>"
            pin.openInfoWindowHtml(addr+"<br><br>"+lati+", "+longi+"<br><br>"+closer);
    })
    iwn++;
};

function go(lat,lng,zoom,num){
    map.setZoom(zoom);
    //map.panTo(new GLatLng(lat,lng));
    GEvent.trigger(marker[num],"click");
};

function showAddress()
{
    lat.length=0;
    document.getElementById("message").innerHTML = "searching";
    var search = document.getElementById("search").value;
    clearMaps();
    geo.getLocations(search, function (result)
        {
            var status = "Status Error";
            switch (result.Status.code) {
                case G_GEO_SUCCESS             : status = "Success"; break;
                case G_GEO_MISSING_ADDRESS     : status = "Missing Address"; break;
                case G_GEO_UNKNOWN_ADDRESS     : status = "Unknown Address"; break;
                case G_GEO_UNAVAILABLE_ADDRESS : status = "Unavailable Address"; break;
                case G_GEO_BAD_KEY             : status = "Bad Key"; break;
                case G_GEO_TOO_MANY_QUERIES    : status = "Too Many Queries"; break;
                case G_GEO_SERVER_ERROR        : status = "Server Error"; break;
            };

            // show status code
            document.getElementById("message").innerHTML = status +"<br>";
            if (result.Status.code == G_GEO_SUCCESS)
            {
                // Loop through the results, placing markers
                for (var i=0; i<result.Placemark.length; i++)
                {
                    lat[i]=result.Placemark[i].Point.coordinates[1];
                    lng[i]=result.Placemark[i].Point.coordinates[0];
                    html[i]=result.Placemark[i].address;

                    precis[i]=3*html[i].split(",").length;
                    var point=new GLatLng(lat[i],lng[i]);
                    var coords="<small> ("+lat[i]+", "+lng[i]+")</small>";

                    marker[i]=new GMarker(point, {title:i+1});;
                    map.addOverlay(marker[i]);
                    miniMarker[i]=new GMarker(point,icon);
                    theMini=miniMarker[i];
                    //mini.addOverlay(miniMarker[i]);
                    bounds.extend(marker[i].getPoint());
                    var addr=result.Placemark[i].address;
                    var iso=result.Placemark[i].AddressDetails.Country.CountryNameCode;
                    createIW(i+1,marker[i],lat[i],lng[i],addr,iso);

                    document.getElementById("message").innerHTML +="<a href=javascript:go("+lat[i]+","+lng[i]+","+precis[i]+","+i+")>"+ html[i]+" "+coords+"</a><br>";
                }
                spit();
            }
        }
    );
};

function showLocation() {
    var loc = this.map.getCenter();

    /* should send update to a view */
    document.getElementById("area").innerHTML = (Math.floor(loc.y * 10000) / 10000) + ',' + (Math.floor(loc.x * 10000) / 10000);
}

function spit(){
    var center = bounds.getCenter();
    map.closeInfoWindow();
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(center);
    map.panDirection(0,0.2);
};

// Clear function

function clearMaps(){
    map.clearOverlays();
    //mini.clearOverlays();
    marker.length=0;
    miniMarker.length=0;
    document.getElementById("message").innerHTML="-";
    bounds = new GLatLngBounds();
    iwn=0;
};



//  ======== A function to adjust the positioning of the overview ========
function positionOverview() {
    var omap=document.getElementById("map_overview");
    if (omap) {
        var mapElem = document.getElementById("map");
        var newx = parseInt(mapElem.offsetWidth)-100;
        var newy = parseInt(mapElem.offsetHeight)-100;
        omap.style.left = newx+"px";
        omap.style.top = newy+"px";

        // == restyling ==
        omap.firstChild.style.border = "1px solid gray";

        omap.firstChild.firstChild.style.left="4px";
        omap.firstChild.firstChild.style.top="4px";
        omap.firstChild.firstChild.style.width="190px";
        omap.firstChild.firstChild.style.height="190px";
    }
}


