var map;
var marker;

var geocoder;

var dirn;
var firstpoint = true;
var gmarkers = [];
var gpolys = [];
var dist = 0;

GPolygon.prototype.Distance = function() {
   var dist = 0;
   for (var i=1; i < this.getVertexCount(); i++) {
      dist += this.getVertex(i).distanceFrom(this.getVertex(i-1));
   }
   return dist;
}
GPolyline.prototype.Distance = GPolygon.prototype.Distance;



function str_replace (search, replace, subject, count) {
   // Replaces all occurrences of search in haystack with replace
   // version: 909.322
   // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
   f = [].concat(search),
   r = [].concat(replace),
   s = subject,
   ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
   if (count) {
      this.window[count] = 0;
   }
   for (i=0, sl=s.length; i < sl; i++) {
      if (s[i] === '') {
         continue;
      }
      for (j=0, fl=f.length; j < fl; j++) {
         temp = s[i]+'';
         repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
         s[i] = (temp).split(f[j]).join(repl);
         if (count && s[i] !== temp) {
            this.window[count] += (temp.length-s[i].length)/f[j].length;
         }
      }
   }
   return sa ? s : s[0];
}

function loadMap() {
   if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(44.5, 20.48),6)
      map.setUIToDefault();
      dirn = new GDirections();

      //      GEvent.addListener(map, "click", function(overlay,point) {
      //        // == When the user clicks on a the map, get directiobns from that point to itself ==
      //        if (!overlay) {
      //          if (firstpoint) {
      //            dirn.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
      //          } else {
      //            dirn.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
      //          }
      //        }
      //      });

      // == when the load event completes, plot the point on the street ==
      GEvent.addListener(dirn, "load", function() {
         // snap to last vertex in the polyline
         // var n = dirn.getPolyline().getVertexCount();
         // var p = dirn.getPolyline().getVertex(n-1);
         // var marker=new GMarker(p);
         // map.addOverlay(marker);
         // store the details
         // gmarkers.push(marker);
         // if (!firstpoint) {
         map.addOverlay(dirn.getPolyline());
         gpolys.push(dirn.getPolyline());
         dist += dirn.getPolyline().Distance();
         document.getElementById("distance").innerHTML="Path length: "+(dist/1000).toFixed(2)+" km. "+(dist/1609.344).toFixed(2)+" miles.";
      // }
      // firstpoint = false;
      });

   }
}

function getAddress(overlay, latlng) {
   if (latlng != null) {
      clicked_latlng = latlng;
      address = latlng;
      geocoder.getLocations(latlng, showAddress);
   }
}

function showAddress(response) {
   if (!response || response.Status.code != 200) {
      //alert("Status Code:" + response.Status.code);
      return;
   } else {
      $('lat' + (current_map_id - 1)).value = clicked_latlng.lat().toFixed(6);
      $('lon' + (current_map_id - 1)).value = clicked_latlng.lng().toFixed(6);

      for (i = 0; i < response.Placemark.length; i++) {
         place = response.Placemark[i];
         var locality = null;
         var address = null;
         try {
            locality = place.AddressDetails.Country.Locality.LocalityName;
         }
         catch (err) {
            try {
               locality = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
            }
            catch(err) {
               try {
                  locality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.AddressLine[0];
               }
               catch(err) {
                  try {
                     locality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                  } catch (err) {}
               }
            }
         }
         if (locality != null) {
            break;
         }
      }
      if (locality != null) {
         var needle = Array("\u0410", "\u0411", "\u0412", "\u0413", "\u0414", "\u0402",
            "\u0415", "\u0416", "\u0417", "\u0418", "\u0408", "\u041a", "\u041b", "\u0409", "\u041c", "\u041d", "\u040a", "\u041e", "\u041f",
            "\u0420", "\u0421", "\u0422", "\u040b", "\u0423", "\u0424", "\u0425", "\u0426", "\u0427", "\u040f", "\u0428", "\u0430", "\u0431",
            "\u0432", "\u0433", "\u0434", "\u0452", "\u0435", "\u0436", "\u0437", "\u0438", "\u0458", "\u043a", "\u043b", "\u0459", "\u043c",
            "\u043d", "\u045a", "\u043e", "\u043f", "\u0440", "\u0441", "\u0442", "\u045b", "\u0443", "\u0444", "\u0445", "\u0446", "\u0447",
            "\u045f", "\u0448");
         var replacement = Array("A", "B", "V", "G", "D", "\u0110", "E",
            "\u017d", "Z", "I", "J", "K", "L", "Lj", "M", "N", "Nj", "O", "P", "R",
            "S", "T", "\u0106", "U", "F", "H", "C", "\u010c", "D\u017e", "\u0160", "a", "b", "v",
            "g", "d", "\u0111", "e", "\u017e", "z", "i", "j", "k", "l", "lj", "m", "n",
            "nj", "o", "p", "r", "s", "t", "\u0107", "u", "f", "h", "c", "\u010d", "d\u017e",
            "\u0161");

         locality = str_replace(needle, replacement, locality);
         address = str_replace(needle, replacement, place.address);
         markers[current_map_id].openInfoWindowHtml(address + '<br />' +
            '<strong><img src="img/car.gif" /> ' + locality + '</strong>');

         $('city' + current_map_id).value = locality;
         Element.removeClassName($('city' + current_map_id), 'city-helptext');
         $('addressdata' + (current_map_id - 1)).value = address;
      }
      

   }
}

var markerIndex = 0;
function createMarker(point) {
   var marker = new GMarker(point);
   marker.value = markerIndex++;
   return marker;
}
