var map;
var shadow_overlay;
var ETOPO_overlay;
var clouds_overlay;
var rain_overlay;
var lightning_overlay;
var strikes_overlay;

var rain_overlay_set= 0;
var clouds_overlay_set= 0;
var lightnings_overlay_set= 0;

function strikes_Url(p, z)
{
  if (selection&0x07FF) {
    var Datum = new Date()
    var min= parseInt(Datum.getTime()/60000);
    return 'http://www.blitzortung.org/Scripts_php/tile_strikes.php?x=' + p.x + '&y=' + p.y + '&z=' + z + '&t=' + selection + '&username=' + uselect + '&login_string=' + login_string + '&min=' + min; }
  else {
    return ''; }
}

function ETOPO_Url(p, z)
{
  if (document.display_options.ETOPO_opacity.value > 0.0) {
    // return 'http://www.maps-for-free.com/layer/relief/z' + z + '/row' + p.y + '/' + z +'_' + p.x + '-' + p.y + '.jpg'; }
    // return 'http://www.maps-for-free.com/layer/water/z' + z + '/row' + p.y + '/' + z +'_' + p.x + '-' + p.y + '.gif'; }
    // return 'http://www.maps-for-free.com/layer/admin/z' + z + '/row' + p.y + '/' + z +'_' + p.x + '-' + p.y + '.gif'; }
    // return 'http://www.shaded-relief.com/googletiles/demo/tile_' + p.x + '_' + p.y + '_' + z + '.jpg'; }
    return 'http://blitzortung.tmt.de/Tile_Data/A_' + p.x + '_' + p.y + '_' + z + '.png'; }
    // return 'http://mt2.google.com/mapslt?lyrs=weather_c_kph|invert:1&x=' + p.x + '&y=' + p.y + '&z=' + z + '&w=256&h=256&gl=de&hl=de'; }
    // return 'http://www.rechenserver.de/GMT/Tile_Data/A_' + p.x + '_' + p.y + '_' + z + '.png'; }
  else {
    return ''; }
}

function load()
{
  initialize_selections();

  if (GBrowserIsCompatible()) {

    map= new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(lat, lon), zoomlevel);

    // var m2 = document.getElementById("map");
    // m2.style.opacity= 0.5;
    //var tile = new GTileLayerOverlay(new GTileLayer(null,null,null,{tileUrlTemplate: 'tile.php?x={X}&y={Y}&z={Z}&t=1015',isPng:true, opacity:1.0}));

    var shadow_layer= new GTileLayer(null,null,null,{tileUrlTemplate:'../Scripts_php/tile_black.php',isPng:true, opacity:shadow_opacity});
    shadow_layer.getOpacity= function() { return document.display_options.shadow_opacity.value;};
    shadow_overlay = new GTileLayerOverlay(shadow_layer);
    map.addOverlay(shadow_overlay);

    var rain_boundaries = new GLatLngBounds(new GLatLng(rain_overlay_south,rain_overlay_west), new GLatLng(rain_overlay_north,rain_overlay_east));
    if (logged_in == 0) {
      rain_overlay = new GGroundOverlay("", rain_boundaries); }
    else {
      rain_overlay = new GGroundOverlay(rain_overlay_url, rain_boundaries); }
    if ((selection)&0x0800) {
      map.addOverlay(rain_overlay); }

    var clouds_boundaries = new GLatLngBounds(new GLatLng(clouds_overlay_south,clouds_overlay_west), new GLatLng(clouds_overlay_north,clouds_overlay_east));
    if (logged_in == 0) {
      clouds_overlay = new GGroundOverlay("", clouds_boundaries); }
    else {
      clouds_overlay = new GGroundOverlay(clouds_overlay_url, clouds_boundaries); }
    if ((selection)&0x1000) {
      map.addOverlay(clouds_overlay); }

    var lightnings_boundaries = new GLatLngBounds(new GLatLng(lightnings_overlay_south,lightnings_overlay_west), new GLatLng(lightnings_overlay_north,lightnings_overlay_east));
    if (logged_in == 0) {
      lightnings_overlay = new GGroundOverlay("", lightnings_boundaries); }
    else {
      lightnings_overlay = new GGroundOverlay(lightnings_overlay_url, lightnings_boundaries); }
    if ((selection)&0x2000) {
      map.addOverlay(lightnings_overlay); }

    var ETOPO_layer= new GTileLayer(null, null, null, {tileUrlTemplate:'',isPng:true, opacity:ETOPO_opacity});
    ETOPO_layer.getTileUrl= ETOPO_Url;
    ETOPO_layer.getOpacity= function() { return document.display_options.ETOPO_opacity.value;};
    ETOPO_overlay = new GTileLayerOverlay(ETOPO_layer);
    map.addOverlay(ETOPO_overlay);

    var strikes_layer= new GTileLayer(null, null, null, {tileUrlTemplate:'',isPng:true, opacity:1.0});
    strikes_layer.getTileUrl= strikes_Url;
    strikes_overlay = new GTileLayerOverlay(strikes_layer);
    map.addOverlay(strikes_overlay);

    //var boundaries = new GLatLngBounds(new GLatLng(0.0,0.0), new GLatLng(80.0,90.0));
    //var density_overlay = new GGroundOverlay("http://www.blitzortung.eu/ELView/Maps/C_0_0_80_90.png", boundaries);
    //map.addOverlay(density_overlay);
    //var density_layer.getTileUrl= density_MygetTileUrl;
    //var lightning_layer= new GTileLayer(null,null,null,{tileUrlTemplate:'',isPng:true, opacity:0.3});
    //lightning_overlay = new GTileLayerOverlay(lightning_layer);

    //map.addControl(new GLargeMapControl3D());
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    // map.addControl(new GHierarchicalMapTypeControl());
    // _mPreferMetric = true;
    // map.addControl(new GScaleControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100,20)));
    // map.enableGoogleBar();
    // var scalePos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70,10));
    // map.addControl(new MapCursorControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(108, 56)));
    map.addControl(new MapCursorControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 34)));
    map.addControl(new MapTimeControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 7)));
    draw_date_time();

    GEvent.addListener(map, "mouseover", function(){ map.showControls(); });
    GEvent.addListener(map, "mouseout", function(){ map.hideControls(); });
    GEvent.addListener(map, "moveend", function(){ store_map_options(); });
    GEvent.addListener(map, "zoomend", function(){ store_map_options(); });
    GEvent.addListener(map, "maptypechanged", function(){ store_map_options(); });

    map.addMapType(G_PHYSICAL_MAP);

    // ETOPO
    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, 'Maps made with <a href="http://gmt.soest.hawaii.edu">GMT</a> and <a href="http://www.ngdc.noaa.gov/mgg/global/global.html">ETOPO1</a> by Blitzortung.org');
    var copyrightCollection = new GCopyrightCollection('');
    copyrightCollection.addCopyright(copyright);

    var ETOPO_layer= new GTileLayer(copyrightCollection, 0, 6, {tileUrlTemplate:'http://www.maps-for-free.com/layer/country/z{Z}/row{Y}/{Z}_{X}-{Y}.png',isPng:true, opacity:1.0});
    // var ETOPO_layer= new GTileLayer(copyrightCollection, 0, 6,{tileUrlTemplate:'http://www.maps-for-free.com/layer/relief/z{Z}/row{Y}/{Z}_{X}-{Y}.jpg',isPng:true, opacity:1.0});

    // var ETOPO_layer= new GTileLayer(copyrightCollection, 0, 6,{tileUrlTemplate:'http://www.shaded-relief.com/googletiles/demo/tile_{X}_{Y}_{Z}.jpg',isPng:true, opacity:1.0});
    // var ETOPO_layer= new GTileLayer(copyrightCollection, 0, 6,{tileUrlTemplate:'http://www.rechenserver.de/GMT/Tile_Data/B_{X}_{Y}_{Z}.png',isPng:true, opacity:1.0});

    // var ETOPO_layer= new GTileLayer(copyrightCollection, 0, 6, {tileUrlTemplate:'http://blitzortung.tmt.de/Tile_Data/A_{X}_{Y}_{Z}.png',isPng:true, opacity:1.0});
    var ETOPO_layers = [ETOPO_layer];
    var ETOPO = new GMapType(ETOPO_layers, new GMercatorProjection(8), "ETOPO", {errorMessage:"No data available"});
    // map.addMapType(ETOPO);

    // Add Admin Layer
//    var Admin_layer = new GTileLayer(copyrightCollection, 0, 6);
//    Admin_layer.getTileUrl = function (a,b) { return "http://maps-for-free.com/layer/admin/z" + b + "/row" + a.y + "/" + b + "_" + a.x + "-" + a.y + ".gif"; };
//    adminLayer = new GTileLayerOverlay(Admin_layer);
//    map.addOverlay(adminLayer);
//    adminLayer.visible = true;

    // Add Label Layer
//    Label_layer = new GTileLayerOverlay(G_HYBRID_MAP.getTileLayers()[1]);
//    map.addOverlay(Label_layer);
//    Label_layer.visible = true;

    map.setMapType(map.getMapTypes()[parseInt(maptype_no)]); }

  store_map_options ();
  store_selections ();
}

function MapTimeControl() {}
MapTimeControl.prototype = new GControl();                // Create new map control
MapTimeControl.prototype.initialize = function(map) {     // Setup map container div to display latitude & longitude.
  var container = document.createElement("div");
  var ptr = document.createElement("div");                // Div type, size & id.
  ptr.id = "DateTxt";
  container.appendChild(ptr);
  map.getContainer().appendChild(container);              // Add container to map.
  return container;
}


function MapCursorControl() {}
MapCursorControl.prototype = new GControl();              // Create new map control
MapCursorControl.prototype.initialize = function(map) {   // Setup map container div to display latitude & longitude.
  var container = document.createElement("div");
  var ptr = document.createElement("div");                // Div type, size & id.
  ptr.id = "LatLonTxt";
  container.appendChild(ptr);
  var tim = 0;
  GEvent.addListener(map, "mousemove", function(point) {  // Listener for mousemove in map area.
    var tim2 = new Date();
    if (tim2.getTime() > tim) { //avoid continuous run
      var ptr = document.getElementById('LatLonTxt');    // Point to display container overlay div.
      var ws= '<table border="0" cellpadding="1" cellspacing="0" style="background-color: black;"><tr><td><table border="0" cellpadding="2" cellspacing="0" style="background-color: white;"><tr><td><table border="0" cellpadding="0" cellspacing="0">';
      ws+= '<tr><td style="color:black; font-size:12px;">&nbsp;Lat:&nbsp;</td><td align="right" style="color:black; font-size:12px;">' + (point.lat()).toFixed(6) + '&nbsp;</td></tr><tr><td style="color:black; font-size:12px;">&nbsp;Lon:&nbsp;</td><td align="right" style="color:black; font-size:12px;">' + (point.lng()).toFixed(6) + '&nbsp;</td></tr>';
      ws+= "</table></td></tr></table></td></tr></table>";

      ptr.innerHTML = ws;                                     // Display latitude & longitude of point where mouse cursor in map.
      tim = tim2.getTime() + 50; } });

  map.getContainer().appendChild(container);              // Add container to map.
  return container;
}

function change_selection ()
{
  var old_selection= selection;

  if (document.display_options.show_stations_active.checked) {
    selection|=0x0001; }
  else {
    selection&=0xFFFE; }
  if (document.display_options.show_stations_idle.checked) {
    selection|=0x0002; }
  else {
    selection&=0xFFFD; }
  if (document.display_options.show_stations_inactive.checked) {
    selection|=0x0004; }
  else {
    selection&=0xFFFB; }
  if (document.display_options.show_strikes_white.checked) {
    selection|=0x0008; }
  else {
    selection&=0xFFF7; }
  if (document.display_options.show_strikes_yellow.checked) {
    selection|=0x0010; }
  else {
    selection&=0xFFEF; }
  if (document.display_options.show_strikes_orange.checked) {
    selection|=0x0020; }
  else {
    selection&=0xFFDF; }
  if (document.display_options.show_strikes_red_light.checked) {
    selection|=0x0040; }
  else {
    selection&=0xFFBF; }
  if (document.display_options.show_strikes_red.checked) {
    selection|=0x0080; }
  else {
    selection&=0xFF7F; }
  if (document.display_options.show_strikes_red_dark.checked) {
    selection|=0x0100; }
  else {
    selection&=0xFEFF; }
  if (document.display_options.show_statistics.checked) {
    selection|=0x0200; }
  else {
    selection&=0xFDFF; }
  if (document.display_options.show_userdata.checked) {
    selection|=0x0400; }
  else {
    selection&=0xFBFF; }
  if (document.display_options.show_rain.checked) {
    selection|=0x0800; }
  else {
    selection&=0xF7FF; }
  if (document.display_options.show_clouds.checked) {
    selection|=0x1000; }
  else {
    selection&=0xEFFF; }
  if (document.display_options.show_lightnings.checked) {
    selection|=0x2000; }
  else {
    selection&=0xDFFF; }

  if ((old_selection)^(selection)) {
    reload_overlays(); }

  if ((!(old_selection&0x0800))&&(selection&0x0800)) {
    map.addOverlay(rain_overlay); }
  if ((old_selection&0x0800)&&(!(selection&0x0800))) {
    map.removeOverlay(rain_overlay); }
  if ((!(old_selection&0x1000))&&(selection&0x1000)) {
    map.addOverlay(clouds_overlay); }
  if ((old_selection&0x1000)&&(!(selection&0x1000))) {
    map.removeOverlay(clouds_overlay); }
  if ((!(old_selection&0x2000))&&(selection&0x2000)) {
    map.addOverlay(lightnings_overlay); }
  if ((old_selection&0x2000)&&(!(selection&0x2000))) {
    map.removeOverlay(lightnings_overlay); }

  store_selections ();
}

function change_opacity ()
{
  map.removeOverlay(shadow_overlay);
  map.addOverlay(shadow_overlay);
  map.removeOverlay(ETOPO_overlay);
  map.addOverlay(ETOPO_overlay);
  map.removeOverlay(strikes_overlay);
  map.addOverlay(strikes_overlay);
//  change_overlays;

  store_selections ();
}

function change_overlays ()
{
  if (document.display_options.show_clouds.checked) {
    map.addOverlay(clouds_overlay); }
  else {
    map.removeOverlay(clouds_overlay); }
  if (document.display_options.show_rain.checked) {
    map.addOverlay(rain_overlay); }
  else {
    map.removeOverlay(rain_overlay); }
  if (document.display_options.show_lightnings.checked) {
    map.addOverlay(lightning_overlay); }
  else {
    map.removeOverlay(lightning_overlay); }
}

function reload_overlays ()
{
  shadow_overlay.refresh();
  ETOPO_overlay.refresh();
  strikes_overlay.refresh();
  draw_date_time();
}

function draw_date_time ()
{
  var Datum = new Date();
  var ws= '<table border="0" cellpadding="1" cellspacing="0" style="background-color: black;"><tr><td><table border="0" cellpadding="2" cellspacing="0" style="background-color: white;"><tr><td><table border="0" cellpadding="0" cellspacing="0">';
  ws+= '<tr><td style="color:black; font-size:12px;">&nbsp;'+Datum.format("Y-m-d T H:i:s")+'&nbsp;</td></tr>';
  ws+= "</table></td></tr></table></td></tr></table>";
  document.getElementById("DateTxt").innerHTML = ws;
}

function initialize_selections ()
{
  if (selection&0x0001) {
    document.display_options.show_stations_active.checked= true; }
  else {
    document.display_options.show_stations_active.checked= false; }
  if (selection&0x0002) {
    document.display_options.show_stations_idle.checked= true; }
  else {
    document.display_options.show_stations_idle.checked= false; }
  if (selection&0x0004) {
    document.display_options.show_stations_inactive.checked= true; }
  else {
    document.display_options.show_stations_inactive.checked= false; }
  if (selection&0x0008) {
    document.display_options.show_strikes_white.checked= true; }
  else {
    document.display_options.show_strikes_white.checked= false; }
  if (selection&0x0010) {
    document.display_options.show_strikes_yellow.checked= true; }
  else {
    document.display_options.show_strikes_yellow.checked= false; }
  if (selection&0x0020) {
    document.display_options.show_strikes_orange.checked= true; }
  else {
    document.display_options.show_strikes_orange.checked= false; }
  if (selection&0x0040) {
    document.display_options.show_strikes_red_light.checked= true; }
  else {
    document.display_options.show_strikes_red_light.checked= false; }
  if (selection&0x0080) {
    document.display_options.show_strikes_red.checked= true; }
  else {
    document.display_options.show_strikes_red.checked= false; }
  if (selection&0x0100) {
    document.display_options.show_strikes_red_dark.checked= true; }
  else {
    document.display_options.show_strikes_red_dark.checked= false; }
  if (selection&0x0200) {
    document.display_options.show_statistics.checked= true; }
  else {
    document.display_options.show_statistics.checked= false; }
  if (selection&0x0400) {
    document.display_options.show_userdata.checked= true; }
  else {
    document.display_options.show_userdata.checked= false; }
  if (selection&0x0800) {
    document.display_options.show_rain.checked= true; }
  else {
    document.display_options.show_rain.checked= false; }
  if (selection&0x1000) {
    document.display_options.show_clouds.checked= true; }
  else {
    document.display_options.show_clouds.checked= false; }
  if (selection&0x2000) {
    document.display_options.show_lightnings.checked= true; }
  else {
    document.display_options.show_lightnings.checked= false; }

  document.display_options.shadow_opacity.selectedIndex= parseInt(shadow_opacity*10.0);
  document.display_options.ETOPO_opacity.selectedIndex= parseInt(ETOPO_opacity*10.0);
}

function store_map_options() {
  for (var i = 0; i < map.getMapTypes().length; i++) {
    if (map.getCurrentMapType() == map.getMapTypes()[i]) {
      write_Cookie("maptype_no", i, 365); } }
  write_Cookie("lon", (map.getBounds().getSouthWest().lng()+map.getBounds().getNorthEast().lng())/2.0, 365);
  write_Cookie("lat", (map.getBounds().getSouthWest().lat()+map.getBounds().getNorthEast().lat())/2.0, 365);
  write_Cookie("zoomlevel", map.getZoom(), 365);
}

function store_selections() {
  write_Cookie('shadow_opacity', document.display_options.shadow_opacity.value, 365);
  write_Cookie('ETOPO_opacity', document.display_options.ETOPO_opacity.value, 365);
  write_Cookie('selection', selection.toString(), 365);
  write_Cookie('rain_overlay_url', rain_overlay_url, 365);
  write_Cookie('rain_overlay_south', rain_overlay_south, 365);
  write_Cookie('rain_overlay_north', rain_overlay_north, 365);
  write_Cookie('rain_overlay_west', rain_overlay_west, 365);
  write_Cookie('rain_overlay_east', rain_overlay_east, 365);
  write_Cookie('clouds_overlay_url', clouds_overlay_url, 365);
  write_Cookie('clouds_overlay_south', clouds_overlay_south, 365);
  write_Cookie('clouds_overlay_north', clouds_overlay_north, 365);
  write_Cookie('clouds_overlay_west', clouds_overlay_west, 365);
  write_Cookie('clouds_overlay_east', clouds_overlay_east, 365);
  write_Cookie('lightnings_overlay_url', lightnings_overlay_url, 365);
  write_Cookie('lightnings_overlay_south', lightnings_overlay_south, 365);
  write_Cookie('lightnings_overlay_north', lightnings_overlay_north, 365);
  write_Cookie('lightnings_overlay_west', lightnings_overlay_west, 365);
  write_Cookie('lightnings_overlay_east', lightnings_overlay_east, 365);
}


