var map;
var numpoints = 10;
var centered = false;
var first = true;
var dotti = new GIcon();
dotti.image = "http://www.breakingnews.fi/kartta/dotti3.png";
dotti.iconSize = new GSize(35, 35);
dotti.iconAnchor = new GPoint(17, 17);
dotti.infoWindowAnchor = new GPoint(15,0);


var pos = new GMarker(new GLatLng(0.0,0.0),{icon:dotti});


var centerToCurrpos = function() {
    $.getJSON('getdata.php',function(data) {
        currpos = data.positions[0];
        currpos_latlng = new GLatLng(currpos.latitude,currpos.longitude);
        if (!first) map.setCenter(currpos_latlng);
        else map.setCenter(currpos_latlng,15);
        first=false;
        pos.setLatLng(currpos_latlng);
        pos.show();
        map.addOverlay(pos);
        time = new Date();
        time.setTime(parseInt(currpos.timestamp*1000));
        var h=time.getHours();
        var i=time.getMinutes();
        var s=time.getSeconds();
        var y=time.getFullYear()
        var m=time.getMonth()+1;
        var d=time.getDate();
        if (i < 10) i = '0'+i;
        if (m < 10) m = '0'+m;
        if (d < 10) d = '0'+d;
        if (s < 10) s = '0'+s;
        if (h < 10) h = '0'+h;

        $('#info').html('Sijainnin aikaleima: '+d+'.'+m+'.'+y+' '+h+':'+i+':'+s);
        centered = true;
    });
}
var initMap = function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.enableScrollWheelZoom();
        centerUpdater();        
        if (!centered) {
            map.setCenter(new GLatLng(60.201577, 24.931195), 12);
            map.addOverlay(pos);
        }
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        centered = true;
        $(window).resize(function() {centerToCurrpos()});
        
    }

}

var centerUpdater = function() {
    centerToCurrpos();
    setTimeout('centerUpdater()',16000);
}

$(window).load(function() {
    initMap('map');
});


$(window).unload(function() {
    GUnload();
});
