var google_ad_client = "pub-7251478393613561";
var google_ad_channel = "1139148215";
var google_ad_width = 160;
var google_ad_height = 600;
var google_ad_format = "160x600_as";
var google_ad_type = "text_image";
var google_alternate_color = "F9F9F9";
var google_color_border = "8898BF";
var google_color_bg = "FFFFFF";
var google_color_link = "0000CC";
var google_color_text = "000000";
var google_cof = "cof=LH%3A50%3BLW%3A791%3BGALT%3A%23008000%3BGL%3A1%3BDIV%3A%23AAAAAA%3BVLC%3A5A3696%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3AFFCC66%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1";
var google_ad_searchchannel = "9414679865";

var ready = false;
var actID = "XXX";
var namesNumbered = 's';
var sortMode = 0;
var currCol = -1;
var infoRow = null;
var google_search_e = new Array("Hotels","Restaurants","Shopping", "Sights", "Maps")
var google_search_d = new Array("Hotels","Restaurants","Einkaufen", "Attraktionen", "Karten")

var reqID = 0;
var searchID = 0;
var map = null;
var selMarker = null;
var display = 'size';
var doScroll = true;
var sizeMarkers = new Array();
var densityMarkers = new Array();
var changeMarkers = new Array();
var currMarkers = new Array();
var adsManager = null;
var markerBounds = null;
var currArea = null;

function sym(id) {
  if (! ready)
    return;
  if (id != actID) {
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    if (infoRow != null) {
      infoRow.parentNode.removeChild(infoRow)
      infoRow = null
    }
    actID = ""+id
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor;
        cell.style.backgroundColor = '#ffcc33';
        doScroll = false;
        searchMarker(id);
      }
      else
        actID = "XXX"
    }
  }
}

function sym2(id) {
  if (! ready)
    return;
  if (id != actID) {
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    if (infoRow != null) {
      infoRow.parentNode.removeChild(infoRow)
      infoRow = null
    }
    actID = ""+id
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor;
        cell.style.backgroundColor = '#ffcc33';
        searchMarker(id);
      }
      else
        actID = "XXX"
    }
  }
}

function symArea(id) {
  if (! ready)
    return;
  if (id != actID) {
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    if (infoRow != null) {
      infoRow.parentNode.removeChild(infoRow)
      infoRow = null
    }
    actID = ""+id
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor;
        cell.style.backgroundColor = '#ffcc33';
        doScroll = false;
        searchArea(id);
      }
      else
        actID = "XXX"
    }
  }
}

function showID (newActID) {
  if (! ready)
    return;
  if (newActID != actID) {
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    actID = ""+newActID
    if (actID != "XXX") {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor
        cell.style.backgroundColor = '#ffcc33'
      }
      else {
        actID = "XXX"
      }
    }
  }
}

function showHTMLInfo(marker) {
  if (! ready)
    return;
  if (selMarker != null) {
    var mt = selMarker.markertext;
    selMarker = null;
    mt.redraw(true);
  }
  if (infoRow != null) {
    infoRow.parentNode.removeChild(infoRow)
    infoRow = null
  }
  var id = marker.key;
  var rowe = document.getElementById('i'+id)
  if (rowe == null)
    return;
  var row = rowe.parentNode
  var rowParent = row.parentNode
  var tabId = rowParent.parentNode.id
  var cells = row.getElementsByTagName('td')
  infoRow = document.getElementById('inforow')
  if (infoRow == null)
    return
  infoRow = infoRow.cloneNode(true)
  var infoCell = infoRow.firstChild

  var newP = document.createElement('p');
  var txt = '';
  if (marker.area > 0)
    if (pagelang == 'de')
      txt += ('Fläche: ' + (marker.area/100) + ' qkm - ').replace('.',',');
    else
      txt += 'Area: ' + (marker.area/100) + ' sq.km - ';
  if (marker.density != null)  
    if (pagelang == 'de')
      txt += ('Dichte: ' + marker.density).replace('.',',') + ' Einw./qkm - ';
    else
      txt += 'Density: ' + marker.density + ' inh./sq.km - ';
  if (marker.incr != null) {
    txt += (pagelang == 'de'? 'Änderung: ' : 'Change: ');
    if (marker.incr > 0)
      txt += '+';
    txt += (pagelang == 'de'? (marker.incr+'%/Jahr - ').replace('.',',') : marker.incr+'%/year - ');
  }
  newP.appendChild(document.createTextNode(txt));

  var aElem = document.createElement('a');
  aElem.setAttribute('href','diagram.php?pageid='+pageid+'&type=C&id='+id)
  aElem.setAttribute('target','diagram')
  aElem.appendChild(document.createTextNode((pagelang == 'de'? 'Bevölkerungsdiagramm' : 'Population Graph')))
  newP.appendChild(aElem)

  if (years > 0)
    infoCell.appendChild(newP);

  newP = document.createElement('p');
  
  aElem = document.createElement('a');
  aElem.setAttribute('href',computeWikiCall(marker))
  aElem.setAttribute('target','extern')
  aElem.appendChild(document.createTextNode('Wikipedia'))
  newP.appendChild(aElem)

  newP.appendChild(document.createTextNode(' - '))
  var google_search = (pagelang == 'de'? google_search_d : google_search_e)
  for (var i=0; i<google_search.length; i++) {
    var aElem = document.createElement('a');
    aElem.setAttribute('href',computeGoogleCall(marker,google_search[i]))
    aElem.setAttribute('target','extern')
    aElem.appendChild(document.createTextNode(google_search[i]))
    newP.appendChild(aElem)
    newP.appendChild(document.createTextNode(' - '));
  }

  aElem = document.createElement('a');
  aElem.setAttribute('href','http://images.google.com/images?gbv=2&hl='+pagelang+'&q='+encodeURI(marker.name));
  aElem.setAttribute('target','extern');
  aElem.appendChild(document.createTextNode((pagelang == 'de'? 'Bilder' : 'Images')))
  newP.appendChild(aElem);

  infoCell.appendChild(newP);

  if (row.nextSibling != null)
    rowParent.insertBefore(infoRow,row.nextSibling)
  else
    rowParent.appendChild(infoRow)
  if (doScroll) {
    rowe.scrollIntoView();
    //var div = document.getElementById('ts');
    //div.scrollTop = row.scrollHeight;
  }
  doScroll = true;
  
  selMarker = marker;
  selMarker.markertext.redraw(true);
  
  var graphlink = document.getElementById('graphlink')
  if (graphlink != null)
    graphlink.setAttribute('href','diagram.php?pageid='+pageid+'&type=C&id='+id)
  var graphimage = document.getElementById('graphimage')
  if (graphimage != null)
    graphimage.setAttribute('src','smallpopgraph.php?pageid='+pageid+'&type=C&id='+id)
}

function showAreaHTMLInfo(key, area, density, incr) {
  if (infoRow != null) {
    infoRow.parentNode.removeChild(infoRow)
    infoRow = null
  }
  var id = key;
  var row = document.getElementById('i'+id)
  if (row == null)
    return;
  var row = row.parentNode
  var rowParent = row.parentNode
  var tabId = rowParent.parentNode.id
  var cells = row.getElementsByTagName('td')
  infoRow = document.getElementById('inforow')
  if (infoRow == null)
    return
  infoRow = infoRow.cloneNode(true)
  var infoCell = infoRow.firstChild

  var newP = document.createElement('p');
  var txt = '';
  if (area > 0)
    if (pagelang == 'de')
      txt += ('Fläche: ' + (area/100) + ' qkm - ').replace('.',',');
    else
      txt += 'Area: ' + (area/100) + ' sq.km - ';
  if (density != null)  
    if (pagelang == 'de')
      txt += ('Dichte: ' + density).replace('.',',') + ' Einw./qkm - ';
    else
      txt += 'Density: ' + density + ' inh./sq.km - ';
  if (incr != null) {
    txt += (pagelang == 'de'? 'Änderung: ' : 'Change: ');
    if (incr > 0)
      txt += '+';
    txt += (pagelang == 'de'? (incr+'%/Jahr - ').replace('.',',') : incr+'%/year - ');
  }
  newP.appendChild(document.createTextNode(txt));

  var aElem = document.createElement('a');
  aElem.setAttribute('href','diagram.php?pageid='+pageid+'&type=ADM2&id='+id)
  aElem.setAttribute('target','diagram')
  aElem.appendChild(document.createTextNode((pagelang == 'de'? 'Bevölkerungsdiagramm' : 'Population Graph')))
  newP.appendChild(aElem)

  infoCell.appendChild(newP);

  if (row.nextSibling != null)
    rowParent.insertBefore(infoRow,row.nextSibling)
  else
    rowParent.appendChild(infoRow)
  doScroll = true;

  var graphlink = document.getElementById('graphlink')
  graphlink.setAttribute('href','diagram.php?pageid='+pageid+'&type=ADM2&id='+id)
  var graphimage = document.getElementById('graphimage')
  graphimage.setAttribute('src','smallpopgraph.php?pageid='+pageid+'&type=ADM2&id='+id)
}


function Row (value, row) {
  this.value = value
  if (this.value == '...')
    this.value = -1;
  this.row = row
}

function cValue (cell, num) {
  if (num) {
    txt = cell.innerHTML;
    txt1 = "";
    if (pagelang == 'de')
      for (var i=0; i<txt.length; i++) {
        ch = txt.charAt(i);
        if (ch != ".")
          txt1 += String.fromCharCode(txt.charCodeAt(i));
      }
    else
      for (var i=0; i<txt.length; i++) {
        ch = txt.charAt(i);
        if (ch != ",")
          txt1 += String.fromCharCode(txt.charCodeAt(i));
      }
    return txt1
  }
  else {
    if (cell.firstChild == null)
      txt = cell.innerHTML;
    else if (cell.firstChild.nodeName.toLowerCase() == "a")
      txt = cell.firstChild.firstChild.nodeValue;
    else
      txt = cell.innerHTML;
    txt = txt.toLowerCase()
    var p1 = txt.indexOf("<br");
    if (p1 >= 0)
        txt = txt.substr(0,p1);
    return txt
  }
}

function compare(a, b) {
  if (sortMode == 2) {
    var diff = b.value-a.value;
    if (diff != 0)
      return diff;
    else
      return a.row.getAttribute("ordNum")-b.row.getAttribute("ordNum")
  }
  if (sortMode == 0)
    return a.row.getAttribute("ordNum")-b.row.getAttribute("ordNum");
  if (a.value < b.value)
    return -1;
  else if (a.value == b.value)
    return a.row.getAttribute("ordNum")-b.row.getAttribute("ordNum")
  return 1
}

function sort (tabid, column, num, ign) {
  var table = document.getElementById(tabid);
  if (table == null)
    return;
  if (infoRow != null) {
    infoRow.parentNode.removeChild(infoRow);
    infoRow = null;
  }
  var tableBody = table.firstChild;
  if (tableBody.nodeName.toUpperCase() != "TBODY")
    tableBody = table.childNodes[1];
  if (tableBody.nodeName.toUpperCase() != "TBODY") {
    alert("For this browser, sorting is not supported!");
    return;
  }
  if ((namesNumbered != 'f') && (namesNumbered != tabid)) {
    for (var i=0; i<table.rows.length-ign; i++)
      table.rows[i].setAttribute('ordNum',i);
    if (namesNumbered != 's')
      namesNumbered = 'f';
    else
      namesNumbered = tabid;
  }
  if (column == 0)
    sortMode = 0;
  else if (num)
    sortMode = 2;
  else
    sortMode = 1;
  var data = new Array();
  var max = table.rows.length - ign;
  for (var i=1; i<max; i++)
    data[i-1] = new Row(cValue(table.rows[i].cells[column],num),table.rows[i]);
  data.sort(compare)
  for (var i=0; i<max-1; i++)
    tableBody.appendChild(data[i].row);
  if (ign > 0)
    for (var i=1; i<=ign; i++)
      tableBody.appendChild(table.rows[1]);
}


function WMarker (key, point, name, admin, status, pop, area, incr, density, wiki, tooltip, img, w, h) {
  var icon = new GIcon();
  icon.image = img;
  icon.iconSize = new GSize(w, h);
  icon.iconAnchor = new GPoint(w/2, h/2);
  icon.infoWindowAnchor = new GPoint(w/2, h/2);
  var options = new Object();
  options.icon = icon;
  options.title = tooltip;
  this.key = key;
  this.name = name;
  this.admin = admin;
  this.status = status;
  this.pop = pop;
  this.area = area;
  this.incr = incr;
  this.density = density;
  this.wiki = wiki;
  this.markertext = null;
  GEvent.addListener(this, "click", this.showInfo);
  GEvent.addListener(this, "infowindowopen", this.handleInfoOpen);
  GMarker.call(this, point, options);
}

WMarker.prototype = new GMarker(new GLatLng(0,0));
    
WMarker.prototype.showInfo = function() {
  //this.openInfoWindowHtml('<span style="font-family: sans-serif; font-size: 2.8mm;">' + this.text + '</span>');
  showID (this.key);
  showHTMLInfo(this);
}

WMarker.prototype.handleInfoOpen = function() {
}

function MarkerText(key, pos, text, pxheight, pxoffset, opt_color) {
  this.key = key;
  this.pos = pos;
  this.text = text;
  this.pxheight = pxheight;
  this.pxoffset = pxoffset;
  this.color_ = opt_color || "#ffffff";
}

MarkerText.prototype = new GOverlay();

MarkerText.prototype.initialize = function(map) {
  var div = document.createElement("div");
  var textnode = document.createTextNode(this.text);
  div.appendChild(textnode);
  div.style.position = "absolute";
  map.getPane(G_MAP_MAP_PANE).appendChild(div);
  this.map = map;
  this.div = div;
}

MarkerText.prototype.remove = function() {
  this.div.parentNode.removeChild(this.div);
}

MarkerText.prototype.copy = function() {
  return new MarkerText(this.pos, this.text, this.pxheight, this.pxoffset, this.color_,
                       this.backgroundColor_, this.opacity_);
}

MarkerText.prototype.redraw = function(force) {
  if (!force)
    return;
  var c1 = this.map.fromLatLngToDivPixel(this.pos);
  var isSelected = false;
  if (selMarker != null)
    isSelected = (selMarker.markertext == this);
  this.div.style.visibility = ((map.getCurrentMapType() == G_SATELLITE_MAP) || isSelected) ? 'visible' : 'hidden';
  this.div.style.color = isSelected? '#ff0000' : this.color_;
  this.div.style.fontWeight = "bold";
  this.div.style.fontFamily = "sans-serif";
  this.div.style.fontSize = this.pxheight + "px";
  var cnt = new Array(0.0,0.0,0.0,0.0);
  var w = this.pxheight*this.text.length*0.667;
  for (var i=0; i<currMarkers.length; i++)
    if (currMarkers[i].markertext != this) {
      var w2 = this.pxheight*currMarkers[i].markertext.text.length*0.667;
      var mPos = this.map.fromLatLngToDivPixel(currMarkers[i].getPoint());
      if (Math.abs(c1.y-mPos.y) < this.pxheight*2) {
        if ((mPos.x > c1.x) && (mPos.x - w - w2 < c1.x)) {
          cnt[0] = cnt[0]+w+w2-Math.abs(mPos.x-c1.x);
        }
        if ((mPos.x < c1.x) && (mPos.x + w + w2 > c1.x)) {
          cnt[3] = cnt[3]+w+w2-Math.abs(mPos.x-c1.x);
        }
      }
      if ((Math.abs(mPos.x - c1.x) < w) && (Math.abs(mPos.y - c1.y) < this.pxoffset*2+this.pxheight*2)) {
        if (mPos.y < c1.y) {
          cnt[1] = cnt[1]+w-Math.abs(mPos.x-c1.x);
        }
        if (mPos.y > c1.y) {
          cnt[2] = cnt[2]+w-Math.abs(mPos.x-c1.x);
        }
      }
    }
  if ((cnt[0] <= cnt[1]) && (cnt[0] <= cnt[2]) && (cnt[0] <= cnt[3])) {
    this.div.style.left = (c1.x + this.pxoffset) + "px";
    this.div.style.textAlign = "left";
    this.div.style.top = (c1.y - this.pxheight/2) + "px";
    this.div.style.width = w + "px";
  }
  else if ((cnt[1] <= cnt[2]) && (cnt[1] <= cnt[3])) {
    this.div.style.left = (c1.x - w) + "px";
    this.div.style.textAlign = "center";
    this.div.style.top = (c1.y - this.pxoffset - this.pxheight) + "px";
    this.div.style.width = (2*w) + "px";
  }
  else if (cnt[2] <= cnt[3]) {
    this.div.style.left = (c1.x - w) + "px";
    this.div.style.textAlign = "center";
    this.div.style.top = (c1.y + this.pxoffset - this.pxheight*0.15) + "px";
    this.div.style.width = (2*w) + "px";
  }
  else {
    this.div.style.left = (c1.x - this.pxoffset - w) + "px";
    this.div.style.textAlign = "right";
    this.div.style.top = (c1.y - this.pxheight/2) + "px";
    this.div.style.width = w + "px";
  }
}

function moveHandler() {
  redrawMap();
}

function zoomHandler(oldLevel, newLevel) {
  if (oldLevel == newLevel)
    return;
  redrawMap();
}

function createCityMarker(cityid, point, mtype, name, admin, status, pop, date, oldpop, olddate, area, wiki) {
  var incr = null;
  if ((oldpop > 0) && (years > 0))
    incr = Math.round(10000.0*(Math.exp(Math.log(pop/oldpop)/years)-1.0)) / 100;
  var density = null;
  if (area > 0)
    density = Math.round(1000*pop/area)/10;
  var img = 'http://www.bymap.org/';
  var tooltip = name;
  if (mtype == 'change') {
    img = getChangeImgName (incr);
    if (incr != null) {
      tooltip += ': ';
      if (incr > 0)
        tooltip += '+';
      tooltip += incr+(pagelang == 'de'? '%/Jahr' : '%/year');
    } 
  }
  else if (mtype == 'density') {
    img = getDensityImgName (density);
    if (density != null)
      tooltip += ': '+density+(pagelang == 'de'? ' Einw./qkm' : ' inh./sq.km');
  }
  else {
    img = getSizeImgName (pop);
    tooltip += ': '+pop+(pagelang == 'de'? ' Einw.' : ' inh.');
  }
  return new WMarker(cityid,point,name,admin,status,pop,area,incr,density,wiki,tooltip,img,20,20);
}

function retrieve () {
  if (map == null)
    return;
  GDownloadUrl('retrieve.php?reqid=' + (++reqID) + '&pageid=' + pageid , retrieveMarkers);
}

function retrieveMarkers (data, responseCode) {
  var xml = GXml.parse(data);
  var docElem = xml.documentElement;
  if (docElem == null) {
    alert ('Received no document from server -> refresh page!');
    return;
  }
  var markers = docElem.getElementsByTagName("marker");
  markerBounds = new GLatLngBounds();
  if (markers != null) {
    for (var i=0; i<markers.length; i++) {
      var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
      var mtext = new MarkerText(markers[i].getAttribute("k"), point, markers[i].getAttribute("name"), 16, 13);
      var marker = createCityMarker(markers[i].getAttribute("k"), point, "size", markers[i].getAttribute("name"), markers[i].getAttribute("adm"), markers[i].getAttribute("status"), markers[i].getAttribute("pop"), popDate, markers[i].getAttribute("oldpop"), oldPopDate, markers[i].getAttribute("area"), markers[i].getAttribute("wiki"));
      marker.markertext = mtext;
      sizeMarkers.push(marker);
      marker = createCityMarker(markers[i].getAttribute("k"), point, "density", markers[i].getAttribute("name"), markers[i].getAttribute("adm"), markers[i].getAttribute("status"), markers[i].getAttribute("pop"), popDate, markers[i].getAttribute("oldpop"), oldPopDate, markers[i].getAttribute("area"), markers[i].getAttribute("wiki"));
      marker.markertext = mtext;
      densityMarkers.push(marker);
      marker = createCityMarker(markers[i].getAttribute("k"), point, "change", markers[i].getAttribute("name"), markers[i].getAttribute("adm"), markers[i].getAttribute("status"), markers[i].getAttribute("pop"), popDate, markers[i].getAttribute("oldpop"), oldPopDate, markers[i].getAttribute("area"), markers[i].getAttribute("wiki"));
      marker.markertext = mtext;
      changeMarkers.push(marker);
      markerBounds.extend(point);
    }
    if ((objid != '') && (objtype == 'city')) {
      redrawMap();
      sym2(objid);
      objid = '';
    }
    if ((objid != '') && ((objtype == 'adm1') || (objtype == 'adm2'))) {
      redrawMap();
      symArea(objid);
      objid = '';
    }
    redrawMap();
  }
}

function retrieveArea (data, responseCode) {
  var xml = GXml.parse(data);
  var docElem = xml.documentElement;
  if (docElem == null) {
    return;
  }
  var pols = new Array();
  var coords = new Array();
  var coordElems = docElem.getElementsByTagName("coord");
  if ((coordElems != null) && (coordElems.length >= 3)) {
    var oldIndex = 0;
    for (var i=0; i<coordElems.length; i++) {
      var y = parseFloat(coordElems[i].getAttribute("lat"));
      var x = parseFloat(coordElems[i].getAttribute("lng"));
      var index = coordElems[i].getAttribute("i");
      if (index != null)
      	index = parseFloat(index);
      else
        index = 0;
      if (index < oldIndex) {
        pols.push(new GPolygon(coords,'#ffff00',0,0.15,'#ffff00',0.15));
        coords = new Array();
      }
      var point = new GLatLng(y, x);
      coords.push(point);
      oldIndex = index;
    }
    pols.push(new GPolygon(coords,'#ffff00',0,0.15,'#ffff00',0.15));
    if (currArea != null)
      for (var i=0; i<currArea.length; i++)
        map.removeOverlay(currArea[i]);
    currArea = pols;
    var areaBounds = new GLatLngBounds();
    for (var i=0; i<currArea.length; i++) {
      map.addOverlay(currArea[i]);
      var b = currArea[i].getBounds();
      areaBounds.extend(b.getSouthWest());
      areaBounds.extend(b.getNorthEast());
    }
    setAreaColor();
    var area = getBoundsArea(areaBounds);
    var mapArea = getBoundsArea(map.getBounds());
    var zoomLevel = map.getZoom();
    if (area > mapArea)
      while (area / mapArea > 1.3) {
        mapArea *= 4;
        zoomLevel--;
      }
    else 
      while (mapArea / area > 4) {
        mapArea /= 4;
        zoomLevel++;
      }
    var areaInfo = docElem.getElementsByTagName("area");
    var pop = parseFloat(areaInfo[0].getAttribute("pop"));
    var oldpop = parseFloat(areaInfo[0].getAttribute("oldpop"));
    area = parseFloat(areaInfo[0].getAttribute("area"));
    var incr = null;
    if ((oldpop > 0) && (years > 0))
      incr = Math.round(10000.0*(Math.exp(Math.log(pop/oldpop)/years)-1.0)) / 100;
    var density = null;
    if (area > 0)
      density = Math.round(1000*pop/area)/10;
    showAreaHTMLInfo(areaInfo[0].getAttribute("k"), area, density, incr);
    map.setCenter(areaBounds.getCenter(), zoomLevel);
  }
}

function getBoundsArea(b) {
  var sw = b.getSouthWest();
  var ne = b.getNorthEast();
  var a = ne.distanceFrom(new GLatLng(ne.lat(),sw.lng()));
  var b = ne.distanceFrom(new GLatLng(sw.lat(),ne.lng()));
  return a*b;
}

function setAreaColor() {
  var mtype = map.getCurrentMapType();
  if (currArea != null)
    for (var i=0; i<currArea.length; i++)
      if (mtype == G_SATELLITE_MAP) {
        currArea[i].setFillStyle({color:"#ffffff",opacity:0.4});
      }
      else if (mtype == G_PHYSICAL_MAP) {
        currArea[i].setFillStyle({color:"#ff00ff",opacity:0.1});
      }
      else {
        currArea[i].setFillStyle({color:"#ffff00",opacity:0.1});
      }
}

function redrawMap() {
try {
  if (map == null)
    return;
  for (var i=0; i<currMarkers.length; i++) {
    var m = currMarkers[i];
    map.removeOverlay(m);
    map.removeOverlay(m.markertext);
  }
  var bounds = map.getBounds();
  if (! bounds.intersects(markerBounds))
    return;
  var existMarkers = sizeMarkers;
  if (display == 'change')
    existMarkers = changeMarkers;
  else if (display == 'density')
    existMarkers = densityMarkers;
  var lng1 = Math.max(bounds.getSouthWest().lng(),markerBounds.getSouthWest().lng());
  var lng2 = Math.min(bounds.getNorthEast().lng(),markerBounds.getNorthEast().lng());
  var lat1 = Math.max(bounds.getSouthWest().lat(),markerBounds.getSouthWest().lat());
  var lat2 = Math.min(bounds.getNorthEast().lat(),markerBounds.getNorthEast().lat());
  var mapSpan = bounds.toSpan();
  var mapArea = mapSpan.lng()*mapSpan.lat();
  var covArea = (lng2-lng1)*(lat2-lat1);
  var limit = Math.round(covArea/mapArea * rowlimit);
  if (limit < 3)
    limit = 3;

  currMarkers = new Array();
  for (var i=existMarkers.length-1; i>=0; i--)
    if (bounds.contains(existMarkers[i].getPoint())) {
      currMarkers.push(existMarkers[i]);
      if (currMarkers.length >= limit)
        break;
    }
    
  for (var i=0; i<currMarkers.length; i++) {
    var m = currMarkers[i];
    map.addOverlay(m);
    map.addOverlay(m.markertext);
    if ((""+m.key) == actID) {
      GEvent.trigger(m,'click');
      selMarker = m;
    }
  }
  ready = true;
  
} catch (ex) {
}
}

function searchMarker (id) {
  for (var i=0; i<sizeMarkers.length; i++) {
    var m = sizeMarkers[i];
    if (m.key == id) {
//      if (adsManager != null) {
//        adsManager.enable();
//      }
      if (currArea != null) {
        for (var j=0; j<currArea.length; j++)
          map.removeOverlay(currArea[j]);
        currArea = null;
      }
      map.setCenter(m.getPoint(), computeZoom(m.pop));
      return;
    }
  }
}

function searchArea (id) {
  if (currArea != null) {
    for (var j=0; j<currArea.length; j++)
      map.removeOverlay(currArea[j]);
      currArea = null;
  }
  GDownloadUrl('retrieveArea.php?reqid=' + (++reqID) + '&pageid=' + pageid + '&id=' + id, retrieveArea);
}


function MapModeControl() {}

MapModeControl.prototype = new GControl();

MapModeControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  
  var sizeDiv = document.createElement("div");
  this.setButtonStyle_(sizeDiv);
  sizeDiv.style.fontWeight = "bold";
  sizeDiv.style.backgroundColor = "orange";
  container.appendChild(sizeDiv);
  sizeDiv.appendChild(document.createTextNode((pagelang == 'de'? 'Einwohner' : 'Population')));
  GEvent.addDomListener(sizeDiv, "click", function() {
    sizeDiv.style.fontWeight = "bold";
    devDiv.style.fontWeight = "normal";
    densityDiv.style.fontWeight = "normal";
    sizeDiv.style.backgroundColor = "orange";
    devDiv.style.backgroundColor = "white";
    densityDiv.style.backgroundColor = "white";
    display = 'size';
    redrawMap();
  });
  var devDiv = document.createElement("div");
  this.setButtonStyle_(devDiv);
  container.appendChild(devDiv);
  devDiv.appendChild(document.createTextNode((pagelang == 'de'? 'Änderung' : 'Change')));
  if (years > 0)
  GEvent.addDomListener(devDiv, "click", function() {
    sizeDiv.style.fontWeight = "normal";
    devDiv.style.fontWeight = "bold";
    densityDiv.style.fontWeight = "normal";
    sizeDiv.style.backgroundColor = "white";
    devDiv.style.backgroundColor = "orange";
    densityDiv.style.backgroundColor = "white";
    display = 'change';
    redrawMap();
  });
  else
    devDiv.style.display = "none";
  var densityDiv = document.createElement("div");
  this.setButtonStyle_(densityDiv);
  container.appendChild(densityDiv);
  densityDiv.appendChild(document.createTextNode((pagelang == 'de'? 'Dichte' : 'Density')));
  GEvent.addDomListener(densityDiv, "click", function() {
    sizeDiv.style.fontWeight = "normal";
    devDiv.style.fontWeight = "normal";
    densityDiv.style.fontWeight = "bold";
    sizeDiv.style.backgroundColor = "white";
    devDiv.style.backgroundColor = "white";
    densityDiv.style.backgroundColor = "orange";
    display = 'density';
    redrawMap();
  });
  map.getContainer().appendChild(container);
  return container;
}

MapModeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 33));
}

MapModeControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "none";
  button.style.color = "#000000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.fontSize = "12px";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "0px";
  button.style.textAlign = "center";
  button.style.width = "80px";
  button.style.height = "16px";
  button.style.cursor = "pointer";
}


function MapSizeControl() {}

MapSizeControl.prototype = new GControl();

MapSizeControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  
  var decrDiv = document.createElement("div");
  this.setButtonStyle_(decrDiv);
  container.appendChild(decrDiv);
  decrDiv.appendChild(document.createTextNode((pagelang == 'de'? 'Karte ^' : 'Map ^')));
  GEvent.addDomListener(decrDiv, "click", function() {
    var m = document.getElementById('map');
    var h = m.style.height;
    h = parseInt(h.substr(0,h.length-2));
    if (h >= 230) {
      var table = document.getElementById('table');
      var top = table.style.top;
      top = parseInt(top.substr(0,top.length-2));
      m.style.height = ''+(h-50)+'px';
      table.style.top = ''+(top-50)+'px';
      map.checkResize();
      redrawMap();
    }
  });
  var incrDiv = document.createElement("div");
  this.setButtonStyle_(incrDiv);
  container.appendChild(incrDiv);
  incrDiv.appendChild(document.createTextNode((pagelang == 'de'? 'Karte v' : 'Map v')));
  GEvent.addDomListener(incrDiv, "click", function() {
    var m = document.getElementById('map');
    var h = m.style.height;
    h = parseInt(h.substr(0,h.length-2));
      var table = document.getElementById('table');
      var top = table.style.top;
      top = parseInt(top.substr(0,top.length-2));
      m.style.height = ''+(h+50)+'px';
      table.style.top = ''+(top+50)+'px';
      map.checkResize();
      redrawMap();
  });
  map.getContainer().appendChild(container);
  return container;
}

MapSizeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 100));
}

MapSizeControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "none";
  button.style.color = "#000000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.fontSize = "12px";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "0px";
  button.style.textAlign = "center";
  button.style.width = "80px";
  button.style.height = "16px";
  button.style.cursor = "pointer";
}


function load() {
  if (map != null)
    return;
  if (! GBrowserIsCompatible()) {
    alert('The browser is not compatible for Google Maps!');
    return;
  }
  
  map = new GMap2(document.getElementById("map"), { mapTypes: new Array (G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP) });
  
  map.addControl(new GLargeMapControl());
  map.addControl(new GScaleControl());
  map.addControl(new GMapTypeControl());
  map.addControl(new MapModeControl());
  map.addControl(new MapSizeControl());
  try {
    map.addControl(new GOverviewMapControl());
  } catch (ex) {
  }
  map.setCenter(new GLatLng(start_y,start_x), start_level);
  map.enableDoubleClickZoom();

  var adsOptions = { channel: '7929309486', minZoomLevel: 10 };  
  //adsManager = new GAdsManager(map, 'ca-pub-7251478393613561', adsOptions);
  //adsManager.enable();
  
  retrieve();
 
  GEvent.addListener(map, "moveend", moveHandler);
  GEvent.addListener(map, "zoomend", zoomHandler);
  GEvent.addListener(map, "maptypechanged", setAreaColor);
  try {
    if (startmap == 'phys')
      map.setMapType(G_PHYSICAL_MAP);
    else if (startmap == 'street')
      map.setMapType(G_NORMAL_MAP);
    else
      map.setMapType(G_SATELLITE_MAP);
  } catch (ex) {
  }
}
