var fg = 0;
var map = null;
var geocoder = null;
var icon=null;
var markeropts=null;
var marker=null;

function load() {
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(35.68581, 139.64529), 11);

        icon = new GIcon();
        icon.image = "http://kuttoku.com/img/fr.png";
        icon.iconSize = new GSize(64,64);
        icon.iconAnchor = new GPoint(32,32);

        markeropts = new Object();
        markeropts.icon = icon;

        marker = new GMarker(map.getCenter(), markeropts);
        map.addOverlay(marker);

        GEvent.addListener(map, 'moveend', getAddr );
    }
}

function load2() {
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
    }
}


function getAddr() {
    var xy = map.getCenter();

    document.getElementById("show_x").innerHTML = "<b>緯度"+(Math.floor(xy.lat() * 100000) / 100000)+"</b>";
    document.getElementById("show_y").innerHTML = "<b>経度"+(Math.floor(xy.lng() * 100000) / 100000)+"</b>";

    if (marker != null) {
        map.removeOverlay(marker);
        marker = new GMarker(map.getCenter(),{icon:icon,clickable:false});
        map.addOverlay(marker);
    }

    if (fg==0){
        fg=1;

        var a = new Ajax.Request('./getAddress.php',
                                    {
                                        method:'post', 
                                        parameters:'lon='+(Math.floor(xy.lng() * 100000) / 100000)+'&lat='+(Math.floor(xy.lat() * 100000) / 100000),
                                        onComplete:recvAddr,
                                        onFailure:recvError
                                    });

        $('addr').innerHTML = "住所検索中・・・";
    }
}

function recvAddr(r) {
    fg=0;
    $('address').value = r.responseText;
    $('addr').innerHTML = "";
}

function recvError(r) {
    fg=0;
}


function showAddress() {
    if (geocoder) {
        geocoder.getLatLng($('sel').value,
                            function(point) {
                                map.setCenter(point, 13);
                            });
    }
}


function searchAddress(address){
    geocoder.getLocations(address, recvSearchAddress);
}

function recvSearchAddress(locations){
    var url="http://address.kuttoku.com/search.php";
    if (locations.Status.code == G_GEO_SUCCESS){
        if (locations.Placemark.length==1){
            window.location = url+'?address='+encodeURI($('address').value)+'&google='+encodeURI(locations.Placemark[0].address);
        }else{
            window.location = url+'?address='+encodeURI($('address').value);
        }
    }else{
            window.location = url+'?address='+encodeURI($('address').value);
    }
}