﻿var google_ad_client = "pub-7251478393613561";
var google_ad_channel = "8220287810";
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 = "79C6D0";
var google_color_border = "8898BF";
var google_color_bg = "FFFFFF";
var google_color_link = "0000CC";
var google_color_text = "000000";
var google_search_e = new Array("Hotels","Restaurants","Shopping", "Sights", "Maps")
var google_search_d = new Array("Hotels","Restaurants","Einkaufen", "Attraktionen", "Karten")
var google_cse_client = "partner-pub-7251478393613561:54544cvf3xn";
var google_cse_client_de = "partner-pub-7251478393613561:stwu7c6wfzh";

var javaVersion = 'unk';
var appletReady = -1;
var ready = false;
var actID = -1;
var diagramReady = -1;
var namesNumbered = 's';
var globNum = true;
var currCol = -1;
var infoRow = null;
var language = 'E';
var useGMap = false;

var vizMode = "";
try { 
  var agent = navigator.userAgent.toLowerCase();
  if ((screen.width <= 640) || (agent.indexOf("android")>=0) || (agent.indexOf("iphone")>=0) || (agent.indexOf("ipod")>=0) || (agent.indexOf("opera mobi")>=0) || (agent.indexOf("blackberry")>=0) || (agent.indexOf("symbianos")>=0)) {
    if (window.innerWidth < 1.3*window.innerHeight)
      vizMode = "320";
	else
      vizMode = "480";
    document.writeln('<meta name="viewport" content="width='+vizMode+',initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0" />');
    document.writeln('<link rel="apple-touch-icon" href="http://www.citypopulation.de/apple-touch-icon.png" />');
    document.writeln('<meta name="apple-mobile-web-app-capable" content="yes" />');
  }
} catch (ex) {
} 
document.writeln('<link rel="stylesheet" type="text/css" href="bymap'+vizMode+'.css" media="all,handheld" />');
document.writeln('<meta name="format-detection" content="telephone=no" />');

function getWindowHeight() {
  if (window.self && self.innerHeight)
    return self.innerHeight;
  if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  return 600;
}

function getWindowWidth() {
  if (window.self && self.innerWidth)
    return self.innerWidth;
  if (document.documentElement && document.documentElement.clientWidth)
    return document.documentElement.clientWidth;
  return 600;
}

function getActId () {
  return actID;
}

function activate_wms() {
  var today = new Date()
  var expire = new Date()
  expire.setTime(today.getTime() + 1000*60*60*24*92)
  document.cookie = "wms=true; expires=" + expire.toGMTString()
}

function call_javainfo() {
  document.writeln('<applet id="viewer" mayscript="true" codebase="../java" code="javainfo/JavaInfo.class" name="JavaInfo" width="0" height="0" vspace="0" hspace="0">')
  document.writeln('</applet>')
}

function load_diagram(country,lang) {
  language = lang;
  if (useGMap || (vizMode != ""))
    return;
  document.writeln('<applet id="diagram" mayscript="true" codebase="../java14" code="diagram/WorldCityMapDiagramApplet.class" archive="diagram.jar" name="DiagramApplet">')
  document.writeln('<param name="country" value="'+country+'" />')
  document.writeln('<param name="language" value="'+lang+'" />')
  document.writeln('<param name="rsc" value="worldcitydiagram_messages">')
  document.writeln('</applet>')
}

function start_mapviewer(file,country,maxscale,minscale,scale,basescale,width,height,lang) {
  var agent = navigator.userAgent.toLowerCase();
  if (agent.match(/android/i))
    window.scrollTo(0,1);
  language = lang;
  if (useGMap || (vizMode != ""))
    return;
  document.writeln('<applet id="mapviewer" mayscript="true" codebase="../java14" code="mapviewer/WorldMapViewer.class" archive="countrymapviewer14.jar" name="ShowMap" ">')
  document.writeln('<param name="country" value="'+country+'">')
  document.writeln('<param name="url" value="Daten5/'+file+'.zip">')
  document.writeln('<param name="maxscale" value="'+maxscale+'">')
  document.writeln('<param name="minscale" value="'+minscale+'">')
  document.writeln('<param name="scale" value="'+scale+'">')
  document.writeln('<param name="basescale" value="'+basescale+'">')
  document.writeln('<param name="viewwidth" value="'+(width-190)+'">')
  document.writeln('<param name="viewheight" value="'+(height-10)+'">')
  document.writeln('<param name="language" value="'+lang+'">')
  document.writeln('<param name="provinces" value="yes">')
  document.writeln('<param name="browser" value="'+navigator.appname+'">')
  document.writeln('<param name="agent" value="'+navigator.userAgent+'">')
  document.writeln('<param name="configfile" value="worldcitymapviewer.zip">')
  document.writeln('<param name="rsc" value="worldcityviewer_messages">')
  document.writeln('</applet>')
}

function log(txt) {
  try { 
    if (window.console)
      window.console.log(txt);
  } catch (ex) {
  } 
}

function load_script (url,callback) {
  var s = document.createElement('script');
  s.type = 'text/javascript'; s.src = url;
  if (callback != null)
    s.onload = function(){ callback(); };
  document.getElementsByTagName("head")[0].appendChild(s);
}

function start_gmap() {
  if (vizMode != "")
    return;
  var java = navigator.javaEnabled();
  var agent = navigator.userAgent.toLowerCase();
  if ((agent.indexOf("version/5") >= 0) && (agent.indexOf("safari/") >= 0)) {
    java = false;
  }
  if (java)
    try { 
      var version = document.JavaInfo.getVersion();
      if ((version == "unk") || (version < '1.2'))
        java = false;
    } catch (ex) {
    }
  if (java)
    return;
  log("*** load gapi");
  useGMap = true;
  load_script("http://maps.googleapis.com/maps/api/js?sensor=false&callback=load_gmap",null);
}

function load_gmap() {
  log("*** load gmap.js");
  load_script("http://www.citypopulation.de/world/gmap.js",call_init_gmap);
}

function call_init_gmap() {
  log("*** call init_gmap");
  init_gmap();
}

function showHelp (langID) {
  window.open('../info/appletinfo_e.html','nw','directories=no,location=no,menubar=no,status=no,scrollbars=yes,resizable=yes')
}

function setAppletReady () {
  appletReady = 1
}

function sym(id) {
  if (id != actID) {
    if (actID >= 0) {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    actID = id
    if (actID >= 0) {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor
        cell.style.backgroundColor = '#ffcc33'
        changeToMap();
      }
      else
        actID = -1
    }
  }
  if (appletReady == 1)
    document.ShowMap.movePosByApplet(id)
  else if (ready)
    searchMarker(id);
  showinfo(id)
}

function showID (newActID) {
  if (newActID != actID) {
    if (actID >= 0) {
      var cell = document.getElementById ("i"+actID);
      if (cell != null)
        cell.style.backgroundColor = oldBackground
    }
    actID = newActID
    if (actID >= 0) {
      var cell = document.getElementById ("i"+actID);
      if (cell != null) {
        oldBackground = cell.style.backgroundColor
        cell.style.backgroundColor = '#ffcc33'
        showinfo(actID)
        cell.scrollIntoView()
      }
      else {
        actID = -1
        showinfo(actID)
      }
    }
    else
      showinfo(actID)
  }
}

function showinfo(id) {
  if (infoRow != null) {
    infoRow.parentNode.removeChild(infoRow)
    infoRow = null
  }
  var row = document.getElementById('i'+id)
  if (row == null)
    return;
  var wiki = row.getAttribute('abbr');
  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 pos = '';
  var text = (language == 'D'? 'Geographische Lage: ' : 'Geographical Location: ')
  if (appletReady == 1) {
    pos = document.ShowMap.getPositionOfSelectedObject()
    newP.appendChild(document.createTextNode(text + pos))
    //infoCell.appendChild(newP)
  }

  var place = encodeURI(trim(cells[2].firstChild.nodeValue));
  var adminname = trim(cells[3].firstChild.nodeValue);
  var gstxt = place;
  if (wiki != null)
    gstxt = wiki.replace(/_/g,' ').replace(/,|\(|\)/g,'');
  var google_search = (language == 'D'? google_search_d : google_search_e)
  var hl = (language == 'D'? 'de' : 'en')
  //var addr = (language == 'D'? 'http://de.wikipedia.org/wiki/Spezial:Suche?go=Artikel&search=' : 'http://en.wikipedia.org/wiki/Special:Search?go=Article&search=')
  var addr = 'http://'+hl+'.wikipedia.org/wiki?search=';
  if (vizMode != "")
    addr = 'http://'+hl+'.m.wikipedia.org/wiki?search=';
  if (wiki == null)
    addr += place
  else
    addr += wiki

  newP = document.createElement('p');
  if (vizMode == '') {
    text = (language == 'D'? 'Google-Suche nach: ' : 'Google Search for: ')
    newP.appendChild(document.createTextNode(text))
    for (var i=0; i<google_search.length; i++) {
      var aElem = document.createElement('a');
      aElem.setAttribute('href',computeGoogleCall(gstxt,google_search[i]))
      aElem.setAttribute('target','_blank')
      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='+hl+'&q='+gstxt)
    aElem.setAttribute('target','_blank')
    text = (language == 'D')? 'Bilder' : 'Images'
    aElem.appendChild(document.createTextNode(text))
    newP.appendChild(aElem)
    infoCell.appendChild(newP)

    newP = document.createElement('p');
    var aElem = document.createElement('a');
    aElem.setAttribute('href',addr)
    aElem.setAttribute('target','_blank')
    aElem.appendChild(document.createTextNode('Wikipedia'))
    newP.appendChild(aElem)
  }
  else {
    newP.innerHTML = '<a href="http://www.google.com/m?hl='+hl+'&q='+gstxt+'" target="_blank"><img class="img48" src="../images/ggsearch48.png" /></a>' +
      '<a href="http://www.google.com/m?site=images&hl='+hl+'&q='+gstxt+'" target="_blank"><img class="img48" src="../images/ggimg48.png" /></a>' +
      '<a href="'+addr+'" target="_blank"><img class="img48" src="../images/wiki48.png" /></a>' +
      '<a href="http://www.citypopulation.de/gmaps/mobi.php?LANG='+language+'&ID='+id+ '&MAPTYPE=normal" target="_blank"><img class="img48" src="../images/gmaps48.png" /></a>';
    infoCell.appendChild(newP)
  }

  var sep = pos.indexOf(' ; ')
  if ((vizMode=='') && (sep > 0)) {
    var pop = document.ShowMap.getPopOfSelectedObject()
    var popdate = document.ShowMap.getPopDateOfSelectedObject()
    newP.appendChild(document.createTextNode(' - Google Maps: '))
    var x = parseFloat(pos.substr(0,sep));
    var y = -1*parseFloat(pos.substr(sep+3));
    var zoom = '12'
    if (tabId == 'tl')
      zoom = '8';
    aElem = document.createElement('a');
    aElem.setAttribute('href','javascript:showmap('+id+',"'+((tabId=="ts")?'C':'L')+'","'+place+'","'+adminname+'","sat")')
     aElem.appendChild(document.createTextNode(language == 'D' ? 'Satellitenkarte' : 'Satellite Map'))
    newP.appendChild(aElem)
    newP.appendChild(document.createTextNode('/'))
    aElem = document.createElement('a');
    aElem.setAttribute('href','javascript:showmap('+id+',"'+((tabId=="ts")?'C':'L')+'","'+place+'","'+adminname+'","normal")')
    aElem.appendChild(document.createTextNode(language == 'D' ? 'Strassenkarte' : 'Street Map'))
    newP.appendChild(aElem)
    newP.appendChild(document.createTextNode(' - '))
    aElem = document.createElement('a');
    aElem.setAttribute('href','javascript:showmap('+id+',"'+((tabId=="ts")?'C':'L')+'","'+place+'","'+adminname+'","osm")')
    aElem.appendChild(document.createTextNode('Open Street Map'))
    newP.appendChild(aElem)
  }
  else if (vizMode=='') {
    newP.appendChild(document.createTextNode(' - Google: '))
    aElem = document.createElement('a');
    aElem.setAttribute('href','http://www.citypopulation.de/gmaps/mobi.php?LANG=' + language + '&ID=' + id + '&MAPTYPE=sat')
    aElem.setAttribute('target','_blank')
    aElem.appendChild(document.createTextNode(language == 'D' ? 'Satelliten-' : 'Satellite Map'))
    newP.appendChild(aElem)
    newP.appendChild(document.createTextNode('/'))
    aElem = document.createElement('a');
    aElem.setAttribute('href','http://www.citypopulation.de/gmaps/mobi.php?LANG=' + language + '&ID=' + id + '&MAPTYPE=normal')
    aElem.setAttribute('target','_blank')
    aElem.appendChild(document.createTextNode(language == 'D' ? 'Strassenkarte' : 'Street Map'))
    newP.appendChild(aElem)
 }

  if (appletReady == 1) {
   var webaddr = document.ShowMap.getWebAddrOfSelectedObject()
   if ((webaddr != null) && (webaddr != '')) {
    newP.appendChild(document.createTextNode(' - '))
    aElem = document.createElement('a');
    aElem.setAttribute('href',webaddr)
    aElem.setAttribute('target','extern')
    text = (language == 'D'? 'Offizielle Web Site' : 'Official Web Site')
    aElem.appendChild(document.createTextNode(text))
    newP.appendChild(aElem)
   }
  }

  infoCell.appendChild(newP)
  
  if (row.nextSibling != null)
    rowParent.insertBefore(infoRow,row.nextSibling)
  else
    rowParent.appendChild(infoRow)
}

function computeGoogleCall(place,obj) {
  if (language == 'D')
    return "http://www.google.de/cse?q="+place+' '+obj+"&lang=de&sa=Suche&cx="+google_cse_client_de+"&ie=UTF-8"
  else
    return "http://www.google.com/cse?q="+place+' '+obj+"&lang=en&sa=Search&cx="+google_cse_client+"&ie=UTF-8"
}

var rep = new Array (/'/g,"",/-/g,"",/ /g,"",/ã/g,"a",/ô/,"o",/è/g,"e",/é/g,"e",/ó/g,"o",/ú/g,"u",/ä/g,"a",/ö/g,"o",/ü/g,"u",/ā/g,"a",/ī/,"i",/ō/g,"o",/ū/g,"u",/č/,"c",/ḥ/,"h",/ṭ/g,"t",/ṣ/,"s",/ş/,"s",/ø/,"o");

function Row (value, row) {
  var v = value;
  if (v == '...')
    v = -1;
  this.row = row
  if (! globNum) {
    v = v.toLowerCase();
    for (var i=0; i<rep.length; i=i+2)
       v = v.replace(rep[i],rep[i+1]);
  }
  this.value = v;
}

function value (cell, num) {
  if (!num)
    return cValue(cell);
  txt = cell.innerHTML;
  txt1 = "";
  for (var i=0; i<txt.length; i++) {
    ch = txt.charAt(i);
    if (ch != ",")
      txt1 += String.fromCharCode(txt.charCodeAt(i));
  }
  return txt1
}

function compare(a, b) {
  if (globNum) {
    var diff = b.value-a.value;
    if (diff != 0)
      return diff;
    else
      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 (column, num) {
  var table = document.getElementById('tl');
  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') {
    for (var i=0; i<table.rows.length-1; i++)
      table.rows[i].setAttribute('ordNum',i);
    namesNumbered = 'f';
  }
  globNum = num;
  var data = new Array();
  var max = table.rows.length;
  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)
  tableBody.appendChild(table.rows[1]);
  for (var i=0; i<max-1; i++)
    tableBody.appendChild(data[i].row);
}

function show_diagram (id,minusRows) {
  if (diagramReady < 0)
    return;
  var table = document.getElementById(id);
  if (table == null)
    return;
  document.DiagramApplet.openDiagram(id)
}

function setDiagramAppletReady () {
  diagramReady = 0
}

function setDiagramAppletData () {
  setData('tl',1)
  document.DiagramApplet.openDiagram('tl')
}

function trim (s) {
  if (s == "")
    return s;
  while (s.indexOf(" ") == 0)
    s = s.substr(1);
  while (s.lastIndexOf(" ") == s.length-1)
    s = s.substr(0,s.length-1);
  return s;
}

function cValue (cell, num) {
  if (num) {
    txt = cell.innerHTML;
    txt1 = "0";
    for (var i=0; i<txt.length; i++) {
      ch = txt.charAt(i);
      if ((ch >= '0') && (ch <= '9'))
        txt1 += String.fromCharCode(txt.charCodeAt(i));
    }
    return parseInt(txt1,10);
  }
  else {
    if (cell.firstChild == null)
      txt = cell.innerHTML;
    else if (cell.firstChild.nodeName.toLowerCase() == "a")
      txt = cell.firstChild.firstChild.nodeValue;
    else
      txt = cell.innerHTML;
    return txt
  }
}

function setData (id,minusRows) {
  var table = document.getElementById(id);
  if (table == null)
    return;
  var max = table.rows.length-minusRows;
  var colNum = table.rows[0].cells.length;
  header = "ID##Name##"
  for (var j=2; j<colNum-1; j++) {
    var cellValue = table.rows[0].cells[j]
    header +=  cValue(cellValue,false)+ '##';
  }
  var cells = "";
  for (var i=1; i<max; i++) {
    cells += table.rows[i].cells[1].getAttribute('id') + "##";
    for (var j=1; j<colNum-1; j++)
      cells += cValue(table.rows[i].cells[j], j>3) + "##";
  }
  document.DiagramApplet.setData(id,header,cells,max,colNum-1)
  if (currCol >= 0)
    document.DiagramApplet.selectValueColumn(currCol);
}

function getData (tid,oid) {
  var cell0 = document.getElementById('i'+oid);
  if (cell0 == null)
    return null;
  var row = cell0.parentNode;
  var cv = cValue(row.cells[4],true);
  currPopNum = parseInt(cv);
  var intro = document.getElementsByTagName("p")[0].innerHTML;
  var cYear = intro.substr(intro.indexOf("20"),4);
  var resObj = {
    params: '',
    popCols: 1,
    years: 0,
    currPopNum: currPopNum,
    oldPopNum: 0,
    currYear: cYear,
    oldYear: null
  }
  return resObj;
}

function showDiagramHelp (lang) {
  window.open('../info/diagraminfo_e.html','nw','directories=no,location=no,menubar=no,status=no,scrollbars=yes,resizable=yes')
}

function showObjectDiagram(id,type) {
  changeToDiagram();
}

function showLegendWindow(page, lang) {
  if (lang == 'de')
    window.open('legend/'+page+'_d.html','nw','directories=no,location=no,menubar=no,status=no,scrollbars=yes,resizable=yes,width=550,height=990')
  else
    window.open('legend/'+page+'.html','nw','directories=no,location=no,menubar=no,status=no,scrollbars=yes,resizable=yes,width=550,height=990')
}

function changeToDiagram() {
  var viewer = document.getElementById("mapviewer");
  if (viewer != null)
    viewer.style.visibility = 'hidden';
  var diagr = document.getElementById("diagram");
  if (diagr != null)
    diagr.style.visibility = 'visible';
  sym(-1)
}

function changeToMap() {
  var diagr = document.getElementById("diagram");
  if (diagr != null)
    diagr.style.visibility = 'hidden';
  var viewer = document.getElementById("mapviewer");
  if (viewer != null)
    viewer.style.visibility = 'visible';
}

function showmap (id,objtype,place,countryname,maptype) {
  var url = (maptype == "osm")? 'http://www.citypopulation.de/osm/index.html' : 'http://www.citypopulation.de/gmaps/index.html';
  url += '?id=' + id + '&objtype=' + objtype + '&name=' + place + '&country=' + encodeURI(countryname) + '&maptype=' + maptype + '&lang=' + language;
  var frm = document.getElementById("gmapframe");
  if (frm == null) {
    var div = document.createElement('div');
    div.setAttribute("id","gmap");
    var closeTitle = (language == 'D') ? 'Fenster schliessen' : 'Close Window';
    div.innerHTML = '<iframe id="gmapframe" scrolling="no" frameborder="0" src="'+url+'"></iframe><img id="gmapclose" src="../images/close.gif" alt="close" title="'+closeTitle+'" onclick="closeGMap()" />';
    document.getElementsByTagName("body")[0].appendChild(div);
    frm = document.getElementById("gmapframe");
  }
  else {
    frm.setAttribute('src',url);
  }
  var gmap = document.getElementById("gmap");
  gmap.style.right = "10px";
  gmap.style.bottom = "10px";
  gmap.style.visibility = "visible";
}

function closeGMap() {
  var gmap = document.getElementById("gmap");
  gmap.style.visibility = "hidden";
}

function set_mobiadv() {
window.googleAfmcRequest = {
  client: 'ca-mb-pub-7251478393613561',
  ad_type: 'text_image',
  output: 'html',
  channel: '4644677663',
  format: '320x50_mb',
  oe: 'utf8',
  color_border: '8898BF',
  color_bg: 'FFFFFF',
  color_link: '0000FF',
  color_text: '000000',
  color_url: '0066CC'
};
}

function writeTwitter(lang) {
  var txt = document.title;
  if (txt.length > 120)
    txt = txt.substring(0,120);
  //document.writeln('<a href="https://twitter.com/share?original_referer='+encodeURIComponent(window.location.href)+'&amp;source=tweetbutton&amp;text='+encodeURIComponent(txt)+'&amp;url='+encodeURIComponent(window.location.href)+'" class="twitter-share-button" data-count="horizontal" target="_blank"><img id="twimg" src="../images/twimg_'+lang+'.gif" /></a>')
  document.writeln('<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?text='+encodeURIComponent(txt)+'&lang='+lang+'" style="width:130px; height:20px;"></iframe>')
}

function writeFacebook(lang) {
  document.writeln('<iframe src="//www.facebook.com/plugins/like.php?href='+encodeURIComponent(window.location.href)+'&amp;send=false&amp;layout=button_count&amp;width=90&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true"></iframe>');
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-19698339-1']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

