//GMap2
var map;
//GMarker
var marker;

//input fields
var countryField;
var cityField;
var latField;
var lngField;

var geoIndicator;

function attachMarkerEvent(marker, url)
{
  GEvent.addListener(marker, "click", function() {
                                            window.location = url; 
                    });
}

function initialize() {
    countryField = $('#register_location_country');
    cityField = $('#register_location_city');
    latField = $('#register_location_latitude');
    lngField = $('#register_location_longitude');
    geoIndicator = $('#geoIndicator');

    latField.addClass("disabled");
    latField.attr("readonly", "readonly");
    lngField.addClass("disabled");
    lngField.attr("readonly", "readonly");
    $('#geoMapHelp').show();
    
    countryField.change(
            function(event) {
                geoCountry();
            });
}

function geoNames(latitude, longitude) {
    geoIndicator.show();
    $.get('http://ws.geonames.org/findNearbyPlaceNameJSON',
              {lat: latitude, lng: longitude, style: 'FULL'},
              geoNamesResult,
              'jsonp'
        );
}

function geoNamesResult(json) {
    geoIndicator.hide();

//alert(print_r(json));

    if (json.geonames && json.geonames[0]) {
        var iso2 = json.geonames[0].countryCode;
        var city = (json.geonames[0].fcode == 'PPLX') ? json.geonames[0].adminName1 : json.geonames[0].name
    
        var origCountry = countryField.selectedValues()[0];
        if (iso2) {
            countryField.selectOptions(iso2);
        }
        if (city) {
            cityField.val(city);
        } else if (origCountry != countryField.selectedValues()[0]) {
            // erase city if country is changed
            cityField.val('');
        }
    }
}

function geoCountry() {
    geoIndicator.show();
    $.get('http://ws.geonames.org/searchJSON',
              {country: countryField.selectedValues()[0], maxRows: '1'},
              geoCountryResult,
              'jsonp'
        );
}

function geoCountryResult(json) {
    geoIndicator.hide();
    cityField.val('');

    var latLng = new GLatLng(json.geonames[0].lat, json.geonames[0].lng);
    marker.setLatLng(latLng);
    map.setCenter(latLng, 6);
    
}




function initGoogleMap() {
  var element = $("#googleMapRegister").get(0);

  var map = new GMap2(element);

  map.addMapType(G_SATELLITE_3D_MAP); // Google Earth button

  //map.enableScrollWheelZoom();

  map.addControl(new GLargeMapControl());
  map.addControl(new GHierarchicalMapTypeControl());


      var center = new GLatLng(47.497917, 19.040200);
      
      if (latField.val() && lngField.val()) {
          if (!isNaN(latField.val()) && !isNaN(lngField.val())) {
              center = new GLatLng(latField.val(), lngField.val());
          } else {
              latField.val('');
              lngField.val('');
          }
      } else {
          latField.val('');
          lngField.val('');
      }
      
      map.setCenter(center, 9);

  var ownIcon = new GIcon();
  ownIcon.image = "/images/icons/map/flag-red.png";
  ownIcon.shadow = "/images/icons/map/flag-shadow.png";
  ownIcon.iconSize = new GSize(34, 25);
  ownIcon.shadowSize = new GSize(34, 25);
  ownIcon.iconAnchor = new GPoint(1, 23);
  ownIcon.infoWindowAnchor = new GPoint(10, 10);
  ownIcon.transparent = "/images/icons/map/flag-red.png";

      // create draggable marker
      marker = new GMarker(center, { icon: ownIcon, draggable: true, bouncy: false});

      // move marker to clicked location
      GEvent.addListener(map, "click", function(marker_, position_) {
          marker.setPoint(position_);
          latField.val(position_.lat());
          lngField.val(position_.lng());
          
          geoNames(marker.getPoint().lat(), marker.getPoint().lng());
      });

      // hide marker info when dragged
      GEvent.addListener(marker, "dragstart", function() {
          map.closeInfoWindow();
      });

      // marker dragged
      GEvent.addListener(marker, "drag", function() {
      });

      // show marker info
      GEvent.addListener(marker, "dragend", function() {
          point = marker.getPoint();
          latField.val(point.lat());
          lngField.val(point.lng());
          
          geoNames(marker.getPoint().lat(), marker.getPoint().lng());
      });        
      
      map.addOverlay(marker);            

      /* lookup initial values */
      //geoNames(marker.getPoint().lat(), marker.getPoint().lng());
}

$(document).ready(function() {
	if (GBrowserIsCompatible())
  {
    initialize();
    initGoogleMap();
	}
});

$(document.body).unload(function() {
  if (GBrowserIsCompatible())
  {
    GUnload();
  }
});
