var map, autocomplete;
var resultsDiv = 'MTQ-LS';


MapToolkit.MTQSearch = function(ev) {
   // navigate in result
   ev = ev || window.event;
   if (ev.keyCode == 40) { // down key
      MapToolkit.LocationSearch.selectRow("down", resultsDiv);
      if (ev.preventDefault) ev.preventDefault();
      else ev.returnValue = false;
      return;
   } else if (ev.keyCode == 38) { // up key
      MapToolkit.LocationSearch.selectRow("up", resultsDiv);
      if (ev.preventDefault) ev.preventDefault();
      else ev.returnValue = false;
      return;
   } else if (ev.keyCode == 13) {
      MapToolkit.LocationSearch.select(resultsDiv);
      $('MTQ-LS-query').blur();
      $('MTQ-LS').hide();
		   $('MTQ-Info').show(); setTimeout(function(){ $('MTQ-Info').hide(); },4000);
      return;
   } else if (ev.keyCode == 27) {
   	MapToolkit.LocationSearch.cancel(resultsDiv);
   	$('MTQ-LS-query').blur();
      return;
   }
   
   // search location
   if (autocomplete) clearTimeout(autocomplete);
   autocomplete = setTimeout(function() {
      if ($('MTQ-LS-query').value) {
         MapToolkit.LocationSearch.search($('MTQ-LS-query').value, 'map', resultsDiv);
      } else {
         MapToolkit.LocationSearch.cancel(resultsDiv);               
      }
   }, 200);
};


MapToolkit.MTQzoomToAddress = function(query, mapDiv) {
   var geocoder = new GClientGeocoder();
   var map = MapToolkit.getMap(mapDiv).gmap;

   // define geocoder callback
   var callback = function(res) {
      if (!res) return;
      if (res && res.Status.code == 200) {
         var p = res.Placemark[0];

         // calculate zoom for LatLonBox
         if (p.ExtendedData && p.ExtendedData.LatLonBox) {
            var b = p.ExtendedData.LatLonBox;
            var bounds = new GLatLngBounds($P(b.south, b.west), $P(b.north, b.east));
            zoom = map.getBoundsZoomLevel(bounds);
         }

         var point = $P(p.Point.coordinates[1], p.Point.coordinates[0]);
         map.setCenter(point, zoom);
      }
   };
   
   geocoder.getLocations(query, callback);
}	