var zhistory;
var map;
var mapBound;
var zoomXY;
var mouseXY;
var zoomLayer;
var startTracking = false;
var inBounds = false;
var ZOOMAREA_KEYCODE = 90; // 'z' key zooms an area when the mouse is moved (not dragged).

function History(){
  var undo = new Array();
  var redo = new Array();
  
  this.add = function(state){
    undo.push(state);
  }
  
  this.clear = function(){
    redo = new Array();
  }
  
  this.undo = function(){
    var gp;
    if(gp = undo.pop()){
      map.setCenter(gp.getCenter(),map.getBoundsZoomLevel(gp));
    }
  }
  
  this.redo = function(){
    var gp;
    if(gp = redo.pop()){
      map.setCenter(gp.getCenter(),map.getBoundsZoomLevel(gp));
    }
  }
}

function getObjectTop(refobj) {
 var y = refobj.offsetTop;
 var obj = refobj.offsetParent;
  while (obj != null) {
    y += obj.offsetTop;
    obj = obj.offsetParent;
  }
 return y;
}

function getObjectLeft(refobj) {
 var x = refobj.offsetLeft;
 var obj = refobj.offsetParent;
  while (obj != null) {
    x += obj.offsetLeft;
    obj = obj.offsetParent;
  }
 return x;
}

/**********************************************************
 *                                                        *
 *  Given a point relative to the DOM (pixel), return     *
 *  the latitude and longitude.                           *
 *    1. Find the point relative to the map               *
 *    2. Convert pixel the point to lat/lon               *
 *                                                        *
 **********************************************************/
function myGetLatLng(point) {
  point = new GPoint(point.x - mapBound.min().x, point.y - mapBound.min().y);
  return map.fromContainerPixelToLatLng(point);
}

/**********************************************************
 *                                                        *
 *             Find the map's DOM position                *
 *                                                        *
 **********************************************************/
function myGetBounds(bound){
  var mapAdjust = (navigator.appName == "Microsoft Internet Explorer") ? 0 : 6;
  var mapWidth = map.getSize().width - mapAdjust;
  var mapHeight = map.getSize().height - mapAdjust;
  var mapDiv = map.getContainer();
  var nw = new GPoint(getObjectLeft(mapDiv),getObjectTop(mapDiv));
  var se = new GPoint(nw.x + mapWidth,nw.y + mapHeight);
  
  return new GBounds(nw.x,nw.y,se.x,se.y);
}

function myGetLatLngBounds(pointA,pointB){
  var SW;
  var NE;
  //Dragged up, left
  if(pointA.x > pointB.x && pointA.y > pointB.y){
   SW = new GPoint(pointB.x,pointA.y);
   NE = new GPoint(pointA.x,pointB.y);
  }  
  //Dragged down, left
  else if(pointA.x > pointB.x && pointA.y < pointB.y){
   SW = pointB;
   NE = pointA;
  }  
  //Dragged down, right
  else if(pointA.x < pointB.x && pointA.y < pointB.y){
   SW = new GPoint(pointA.x,pointB.y);
   NE = new GPoint(pointB.x,pointA.y);
  }  
  //Dragged up, right (pointA.x < pointB.x and pointA.y > pointB.y)
  else{
   SW = pointA;
   NE = pointB;
  }
  
  return new GLatLngBounds(myGetLatLng(SW),myGetLatLng(NE));
}

function setValidZoomArea(mouse) {
  var max = mapBound.max();
  var min = mapBound.min();
  var x = mouse.x;
  var y = mouse.y; 

  if (mouse.x >= max.x) x = max.x; 
  if (mouse.x <= min.x) x = min.x;
  if (mouse.y <= min.y) y = min.y;
  if (mouse.y >= max.y) y = max.y;
  
  return new GPoint(x,y);
}

function getMouseXY(e){

  return setValidZoomArea(getOffset(e.clientX,e.clientY));

}

function getOffset(x,y){

  if (self.pageXOffset){
    x += self.pageXOffset;
    y += self.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop){
    x += document.documentElement.scrollLeft;
    y += document.documentElement.scrollTop;
  }
  else if (document.body){
    x += document.body.scrollLeft;
    y += document.body.scrollTop;
  }

  return new GPoint(x,y);
}

function mouseMoveHandler(e){
  if (!e) e = window.event;

  mouseXY = getMouseXY(e);

  if (!startTracking)  return;

  var width = mouseXY.x - zoomXY.x;
  var height = mouseXY.y - zoomXY.y;
 
  if (width < 0) {
    width = Math.abs(width);
    zoomLayer.style.left = mouseXY.x + "px";
  }  
  zoomLayer.style.width = width + "px";

  if (height < 0) {
    height = Math.abs(height);
    zoomLayer.style.top = mouseXY.y + "px";
  }
  zoomLayer.style.height = height + "px";
}

/*
 *  If the key pressed is the "zoom" key and were aren't already tracking, 
 */

function keyDownHandler(e){
  if (!e) e = window.event;



  if (e.keyCode == ZOOMAREA_KEYCODE && !e.shiftKey && !startTracking && inBounds){
    startTracking = true;
    zoomXY = mouseXY;
    zoomLayer.style.visibility = "visible";
    zoomLayer.style.left = zoomXY.x + "px";
    zoomLayer.style.top = zoomXY.y + "px";
    zoomLayer.style.width = 0 + "px";
    zoomLayer.style.height = 0 + "px";
  }
}

function keyUpHandler(e){
  var gp;

  if (!e) e = window.event;
  if (e.keyCode != ZOOMAREA_KEYCODE && (!e.shiftKey || !startTracking)) return;
//  else if (e.shiftKey && e.keyCode == ZOOMAREA_KEYCODE) zhistory.undo();
  
  startTracking = false;  
  
  zoomLayer.style.visibility = "hidden";
  
  if(mouseXY.x == zoomXY.x && mouseXY.y == zoomXY.y) return;
 
  gp = myGetLatLngBounds(zoomXY,mouseXY);
  
  document.location.href="MapSearchDefined.aspx?MinLongitude=" + gp.getNorthEast().x + "&MaxLongitude=" + gp.getSouthWest().x + "&MinLatitude=" + gp.getSouthWest().y + "&MaxLatitude=" + gp.getNorthEast().y + "&zoomLevel=" + (16 - map.getBoundsZoomLevel(gp));
}

function addZoomLayer(){
  var obj = document.createElement("div");
  
  obj.setAttribute("id","zoomLayer");
  obj.style.backgroundColor = "#ffffff";
  obj.style.border = "3px solid #ff0000";
  obj.style.filter = "alpha(opacity=60)";
  obj.style.height = "0px";
  obj.style.lineHeight = "0px";
  obj.style.margin = "0px";
  obj.style.opacity = ".6";
  obj.style.position = "absolute";
  obj.style.left = "0px";
  obj.style.top = "0px";
  obj.style.padding = "0px";
  obj.style.visibility = "hidden";
  obj.style.width = "0px";
  obj.style.zIndex = "100";
  
  document.body.appendChild(obj);
  
  return obj;
}

function addZoom(){
  zoomLayer = addZoomLayer();
  GEvent.addListener(map, "mouseover",insideTheMap);
  GEvent.addListener(map, "mouseout",outsideTheMap);

  mapBound = myGetBounds(map.getBounds());
  
//  zhistory = new History();

  document.onmousemove = mouseMoveHandler;
  document.onkeydown = keyDownHandler;
  document.onkeyup = keyUpHandler;
}

function insideTheMap(){
  inBounds = true;
}

function outsideTheMap(){
  inBounds = false;
}

function load(){
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(39.10,-94.60), 9); 
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
        
    addZoom();
  }
}

window.onunload = function(){
  GUnload();
}

// Create a base icon for all of our markers that specifies the shadow, icon
// dimensions, etc.
var root = new String("/");
var baseIcon = new GIcon();
baseIcon.shadow = "/images/Google_Map/shadow.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var MiddleX;
var MiddleY;
var doMoveEnd = true;

function LoadMap() {
  GEvent.addListener(map,"click",function() {
	  var M = map.getCenterLatLng();
		MiddleX = M.x;
		MiddleY = M.y;
	});
	GEvent.addListener(map,"infowindowclose",function() {
		map.recenterOrPanToLatLng(new GPoint(MiddleX, MiddleY));
		doMoveEnd = false;
	});
	GEvent.addListener(map,"moveend",function() {
		if (doMoveEnd) {
			var M = map.getCenterLatLng();
			MiddleX = M.x;
			MiddleY = M.y;
		}
    ShowPins();
		doMoveEnd = true;
	});

  ShowPins();
}

function ShowPins() {
	var request = GXmlHttp.create();
	request.open('GET', NumHomesURL(), true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
		}
	}
	request.send(null);
	this.focus();
}

function NumHomesURL() {
	url = root + "HomeSearch/MapSearchXML.aspx";
	url += "?SearchType=Map";
	//url += "&Values=x";
	
	return url;
}

function createMarker(point, Text, Marker) {
  var icon = new GIcon(baseIcon);
  icon.image = "/images/Google_Map/" + Marker + ".png";
  var marker = new GMarker(point, icon);
  
  var html = Text;
  GEvent.addListener(marker, "click", function() {
  	doMoveEnd = false;
  	marker.openInfoWindowHtml(html);
  });
  
  return marker;
}

//addEvent() by John Resig
function addEvent(obj,type,fn){ 
  if (obj.addEventListener) obj.addEventListener(type, fn, false);
  else if (obj.attachEvent){ 
    obj["e"+type+fn] = fn; 
    obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); } 
    obj.attachEvent("on"+type, obj[type+fn]); 
  } 
} 

//addEvent(window,'load',LoadMap);