var targetZoom; //global variable used when transform point returns

var transit;
var geo; 
var mymc;
    // ====== Array for decoding the failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Onnistui";
reasons[G_GEO_MISSING_ADDRESS]    = "Osoite puuttuu";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Osoite tuntematon";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Osoitetta ei tavoitettu";
reasons[G_GEO_BAD_KEY]            = "V&auml;&auml;r&auml; avain";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Liian monta kysely&auml;";

function MapControl(form){
	this.zoomTo = true;
	geo = new GClientGeocoder()
	geo.control = this; 
	if(!form){
        	this.form = document.forms.sform;
		}
	}

MapControl.prototype.locate = function (nsearch) {
	if(!nsearch && !!this.form){
			nsearch = this.form.search.value;
			}

	var p;	if(!nsearch){ return false; }
		
	// ====== Perform the Geocoding ======  
	//refinement possible 
	//viewport could be set to allow improved accuracy on the search
	//would require another go round to TNTserver for converting the
	//local crs to latlon.
		
        geo.getLocations(nsearch, function (result) { 
            if (result.Status.code == G_GEO_SUCCESS) {
              var mess = $("message");
	      if(mess){ mess.innerHTML = "Found " +result.Placemark.length +" results"; }
		var p;
              for (var i=0; i<result.Placemark.length; i++) {
                 p = result.Placemark[i].Point.coordinates;
              }
		
	      var z = result.Placemark[0].AddressDetails.Accuracy;
	      if(z == 9) { z = 1; }	
	       var zoom = 2 + 2 * parseInt(z,10);
	       targetZoom = zoom; //global variable used when transform point returns
	      if(activeLayer.crs == 'EPSG:4326'){
		        if(!geo.control.zoomTo){
				targetZoom = map.getZoom();
	     			}
		       map.setCenter(new OpenLayers.LonLat(p[0],p[1]),targetZoom);
	       	}
	       else {
		       transit = new Transformer("http://www.geospatialgateway.com/GeoComment/proxy.php?","http://publicatlas.microimages.com/global_cgi/global.cgi?", null); 		       
		       pt = new OpenLayers.LonLat(p[0],p[1]);
		      
		       transit.transformPoint('EPSG:4326',activeLayer.crs,pt);
		       }
            }
            else {
				var reason = "";
			    if(typeof reasons[result.Status.code]!= "undefined" ) {reason = reasons[result.Status.code]; }
				alert("Ongelmia haussa, Google Earth palautti syyn "+reason);		 
               }
          }
	);
	return false;
      } 

mymc = new MapControl(g$('sform'));

