var map;
var currentCenter;
var currentZoom;
var currentLang;
var moveListener;
var currentAction = '';

function gmap_parse_url() {
  var query = location.search.substr(1);
  var tmp = query.split('&');
  for(var i = 0;i < tmp.length;i++) {
    var tmp2 = tmp[i].split('=');
    if (tmp2[0] == 'action') {
      var action = tmp2[1];
      var m = action.match(/(.*?)atlas:(.+)/);
      if (m) {
        currentAction = m[1];
        var atlas = m[2];
        var tmp3 = atlas.split(':');
	var lng;
	var lat;
        if (query.indexOf('geo=true') != -1) {
	  lng = tmp3[0];
	  lat = tmp3[1];
	} else {
	  lng = - tmp3[0] / 3600;
	  lat = tmp3[1] / 3600;
	}
	gmap_changezoom(new GLatLng(lat, lng), 13);
        return true;
      } else {
	var geocoder = new GClientGeocoder();
        geocoder.getLatLng(decodeURI(action), function(point) {
          if (point) {
	    currentAction = action;
            gmap_changezoom(point, 13);
          } else {
            gmap_changezoom(new GLatLng(0, 0), 2);
	  }
        });
	return true;
      }
    }
  }

  return false;
}

function gmap_init(lang) {
  currentLang = lang;
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("carte"));

    if (! gmap_parse_url())
      gmap_changezoom(new GLatLng(0, 0), 2);

    map.setUIToDefault();

    moveListener = GEvent.addListener(map, "moveend", function() {
      gmap_draw_articles();
    });
  }
}

function gmap_get_child(element, childname, ns) {
  if ((typeof ns != "undefined") && (element.getElementsByTagNameNS)) {
    var tmp = childname.split(':');
    var child = element.getElementsByTagNameNS(ns, tmp[1]);
  } else {
    var child = element.getElementsByTagName(childname);
  }
  if (child.length == 0) return false;
  if (child[0].firstChild == null) return false;
  return child[0].firstChild.data;
}

function gmap_create_html(title, url, content) {
  var html = '<div class="search-resulr-box"';
  html += '<h2><a href="' + url + '">' + title + '</a></h2>';
  html += '<div class="info-box">';
  var image = gmap_get_child(content, 'image');
  if (image) {
    html += '<div class="img-box"><img style="float:left; margin-right: 6px; height: 56px; width: 56px;" src="http://img.wikiwix.com/img.php?imgtitle=' + gmap_get_child(content, 'image') + '&width=151x151&lang=' + currentLang + '"/><span class="zoom"></span></div>';
    html += '<div class="text-box with-img">';
  } else {
    html += '<div class="text-box">';
  }
  var ab = gmap_get_child(content, 'abstract');
  if (ab) html += '<p>' + gmap_get_child(content, 'abstract') + '</p>';
  var modtime = gmap_get_child(content, 'modtime');
  if (modtime) html += '<span><a href="' + url + '?action=history">Derni&egrave;re modification ' + modtime + '</a></span>';
  html += '<a href="' + url + '">' + url + '</a>';
  html += '</div>';
  html += '</div>';
  html += '</div>';
  return html;
}

function gmap_create_marker(point, title, url) {
  var icon = new GIcon(G_DEFAULT_ICON);
  if (title.toLowerCase() == currentAction.toLowerCase())
    icon.image = 'http://www.wikiwix.com/images/punrouge.png';
  else
    icon.image = 'http://www.wikiwix.com/images/punbleu.png';
  icon.iconSize = new GSize(20,23);

  var marker = new GMarker(point, {icon: icon});
  GEvent.addListener(marker, "infowindowclose", function() {
    moveListener = GEvent.addListener(map, "moveend", function() {
      gmap_draw_articles();
    });
  });

  GEvent.addListener(marker, "click", function() {
    GDownloadUrl("api.php?lang=" + currentLang + "&getabstract=:" + title, function(doc, http_status) {
      if ((doc == null) || (http_status == -1)) return;

      GEvent.removeListener(moveListener);

      map.openInfoWindowHtml(point, gmap_create_html(title, url, GXml.parse(doc)));
    });
  });

  return marker;
}

function gmap_parse_rdf(doc, http_status) {
  if ((doc == null) || (http_status == -1)) return;

  map.clearOverlays();

  var dom = GXml.parse(doc);
  var rdf = dom.lastChild;

  for(var i = 0;i < rdf.childNodes.length;i++) {
    var child = rdf.childNodes[i];
    if (child.nodeName == 'item') {
      var title = gmap_get_child(child, 'title');
      var url = gmap_get_child(child, 'link');
      var point = gmap_get_child(child, 'georss:point', "http://www.georss.org/georss");
      var tmp = point.split(' ');
      map.addOverlay(gmap_create_marker(new GLatLng(tmp[0], tmp[1]), title, url));
    }
  }
}

function gmap_draw_articles() {
  var center = map.getCenter();
  var size = map.getSize();
  var zoom = map.getZoom();
  if (( currentCenter != center )||( currentZoom != zoom )) {
    currentCenter = center;
    currentZoom = zoom;
    var w_deg = 360 / ((zoom - 1) * (zoom - 1) * (zoom - 1));
    var url1 = "atlas.xml.php?lang=" + currentLang + "\x26center=lon=" + center.lng() + ",lat=" + center.lat() + "\x26rayon=" + w_deg;
    GDownloadUrl(url1, gmap_parse_rdf);
  }
}

function gmap_changezoom(point, zoom) {
   map.setCenter(point, zoom);
   gmap_draw_articles();
}

function gmap_search(action) {
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(action, function(point) {
		if (point) {
			currentAction = action;
			gmap_changezoom(point, 13);
		}
	});
}

