var map;

Function.prototype.bind = function(obj) { 
var method = this, 
temp = function() { 
return method.apply(obj, arguments); 
}; 

return temp; 
}
function Ajax(url,options) {
if (!(this instanceof Ajax)) return new Ajax(url, options);
this.initialize(url,options);
}
Ajax.prototype = {
initialize: function(url, options){
this.transport = this.getTransport();
this.postBody = options.postBody || "";
this.method = options.method || 'post';
this.onComplete = options.onComplete || null;
this.update = document.getElementById(options.update) || null;
this.request(url);
},
request: function(url){
this.transport.open(this.method, url, true);
this.transport.onreadystatechange = this.onStateChange.bind(this);
if (this.method == 'post') {
this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
}
this.transport.send(this.postBody);
},
onStateChange: function(){
if (this.transport.readyState == 4 && this.transport.status == 200) {
if (this.onComplete) 
setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
if (this.update)
setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
this.transport.onreadystatechange = function(){};
}
},
getTransport: function() {
if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else return false;
}
};

function load() {
  if(GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(55, -3), 6);
	map.setMapType(G_SATELLITE_MAP);

    // add geotude grids
//    recalculateGeotude(map.getBounds(), map.getZoom());
    recalculateGeoHash(map.getBounds(), map.getZoom());

    // add event for future adjustment of visible geotudes
    GEvent.addListener(map, "moveend", function() {
      recalculateGeoHash(map.getBounds(), map.getZoom());
/*      recalculateGeotude(map.getBounds(), map.getZoom());*/
      map.addOverlay(new GMarker(new GLatLng(0, 0)));
    });
  }
}

function recalculateGeoHash(bounds,zoom) {
  var dec = 0;
  var inc = 0;
  var sub = 12;
  var lineColor = "white";
  var textColor = "black";

  if(zoom <= 30) {
    dec = 1000;
    inc = 1/dec;
    sub = 8;
    lineColor = "green";
  }
  if(zoom <= 16) {
    dec = 100;
    inc = 1/dec;
    sub = 7;
    lineColor = "blue";
  }
  if(zoom <= 12) {
    dec = 10;
    inc = 1/dec;
    sub = 5;
    lineColor = "indigo";
  }
  if(zoom <= 11) {
    dec = 10;
    inc = 1/dec;
    sub = 4;
    lineColor = "indigo";
  }
  if(zoom <= 8) {
    dec = 1;
    inc = 1/dec;
    sub = 3;
    lineColor = "violet";
  }
  if(zoom <= 4) {
    dec = 0.1;
    inc = 1/dec;
    sub = 2;
    lineColor = "white";
  }
  if(zoom <= 3) {
    dec = 0.1;
    inc = 1/dec;
    sub = 1;
    lineColor = "white";
  }
  if(zoom < 2) {
    map.clearOverlays();
    return;
  }
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  var blat = Math.floor(sw.lat() * dec) / dec;
  var elat = Math.ceil(ne.lat() * dec) / dec;
  var blng = Math.floor(sw.lng() * dec) / dec;
  var elng = Math.ceil(ne.lng() * dec) / dec;
  var grids = new Array();
  for(var ilat = blat; ilat < elat; ilat += inc) {
    for(var ilng = blng; ilng < elng; ilng += inc) {
      var gt = encodeGeoHash(ilat+inc, ilng, sub);
      
      //GLog.write(ilat + ":" + ilng + ":[" + gt + "]");
    
      grids.push(
          new Geotude(
              new GLatLngBounds(
                  new GLatLng(ilat, ilng), new GLatLng(ilat + inc, ilng + inc)),
                  gt,
                  1,
                  'white',
                  'black'));
    }
  }

  // remove all the existing overlays
  map.clearOverlays();

  //add new overlays
  for(var i = 0; i < grids.length; i++) {
    map.addOverlay(grids[i]);
  }
  
}

// recalculate the visible geotudes
function recalculateGeotude(bounds, zoom) {
  // calculate geotude level
  var dec = 0;
  var inc = 0;
  var sub = 0;
  var lineColor = "white";
  var textColor = "black";

  if(zoom <= 30) {
    dec = 1000;
    inc = 1/dec;
    sub = 3;
    lineColor = "green";
  }
  if(zoom <= 16) {
    dec = 100;
    inc = 1/dec;
    sub = 2;
    lineColor = "blue";
  }
  if(zoom <= 12) {
    dec = 10;
    inc = 1/dec;
    sub = 1;
    lineColor = "indigo";
  }
  if(zoom <= 8) {
    dec = 1;
    inc = 1/dec;
    sub = 0;
    lineColor = "violet";
  }
  if(zoom < 5) {
    dec = 0.1;
    inc = 1/dec;
    sub = 0;
    lineColor = "white";
  }
  if(zoom <= 2) {
    map.clearOverlays();
    return;
  }

  // calculate text color
  var mapType = map.getCurrentMapType();
  if(mapType == G_NORMAL_MAP)
    textColor = "#808080";
  else if(mapType == G_SATELLITE_MAP || mapType == G_HYBRID_MAP) {
    textColor = "#D3D3D3";
  }

  // calculate grids
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();

  //  alert("sw.lat[" + sw.lat() + "] ne.lat[" + ne.lat() + "] sw.lng[" + sw.lng() + "] ne.lng[" + ne.lng() + "]")

  var blat = Math.floor(sw.lat() * dec) / dec;
  var elat = Math.ceil(ne.lat() * dec) / dec;
  var blng = Math.floor(sw.lng() * dec) / dec;
  var elng = Math.ceil(ne.lng() * dec) / dec;

  //  alert("blat[" + blat + "] elat[" + elat + "] blng[" + blng + "] elng[" + elng + "]")

  // create all the geotudes
  var grids = new Array();
  for(var ilat = blat; ilat < elat; ilat += inc) {
    for(var ilng = blng; ilng < elng; ilng += inc) {
      var gt = latLng2GT(ilat + inc, ilng, sub);
      
      //GLog.write(ilat + ":" + ilng + ":[" + gt + "]");
    
      grids.push(
          new Geotude(
              new GLatLngBounds(
                  new GLatLng(ilat, ilng), new GLatLng(ilat + inc, ilng + inc)),
                  latLng2GT(ilat + inc, ilng, sub),
                  1,
                  lineColor,
                  textColor));
    }
  }

  // remove all the existing overlays
  map.clearOverlays();

  //add new overlays
  for(var i = 0; i < grids.length; i++) {
    map.addOverlay(grids[i]);
  }
}

// A DIV that represents a Geotude grid.
function Geotude(bounds, text, opt_weight, opt_linecolor, opt_textcolor) {
  this.bounds_ = bounds;
  this.text_ = text;
  this.weight_ = opt_weight || 1;
  this.linecolor_ = opt_linecolor || "#888888";
  this.textcolor_ = opt_textcolor || "#000000";
}
Geotude.prototype = new GOverlay();

// Creates the DIV representing this geotude.
Geotude.prototype.initialize = function(map) {
  // Create the DIV representing our rectangle
  var div = document.createElement("div");
  div.style.position = "absolute";
  div.id=String(this.text_)
/* div.style.borderBottom = "1px dashed " + this.linecolor_;
 div.style.borderLeft = "1px dashed " + this.linecolor_;
  div.innerHTML = this.text_;
*/
 div.style.color = 'white';
 div.style.fontFamily = "Verdana";
 div.style.fontSize = "x-small";
/*  div.id=String(div.id).replace(/\./g,"-");
  div.id=String(div.id).replace(/\./g,"-");
  div.id=String(div.id).replace(/\./g,"-");
*/
  new Ajax('retrieve.php?gt='+this.text_, {onComplete: addWeather});

  map.getPane(G_MAP_MAP_PANE).appendChild(div);
  
  this.map_ = map;
  this.div_ = div;
}

function addWeather(request) {
	var r = String(request.responseText).split(":");
	var d = document.getElementById(r[0]);
	var showText = document.getElementById('showtext').checked;
	if(d) {
		if(r[1]!='') {
			if(showText) {
				d.innerHTML=r[1]+'('+r[2]+')';
			}
//			d.style.backgroundColor='#ffffff';
			switch(r[1]) {
				case 'rain':
						d.style.backgroundImage='url(icons/rain.png)';break;
				case 'snow':
						d.style.backgroundImage='url(icons/snow.png)';break;
				case 'thunder':
						d.style.backgroundImage='url(icons/storm.png)';break;
				case 'lightning':
						d.style.backgroundImage='url(icons/lightning.png)';break;
				case 'hailstone':
						d.style.backgroundImage='url(icons/hail.png)';break;
				case 'blizzard':
						d.style.backgroundImage='url(icons/blizzard.png)';break;
				
			}
		}
	}
}

// Remove the main DIV from the map pane
Geotude.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

// Redraw the rectangle based on the current projection and zoom level
Geotude.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if(!force) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
  this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
  this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
  this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
}
window.onload=load;
window.onunload=GUnload;

