﻿var map;
var m1;
var m2;
var m3;
var m4;
var p1;
var p2;
var p3;
var p4;
var CancelMarker;
var SaveMarker;
var rectangle;
var weight = 2;
var lineColor = "#000040";
var offset = 0.003; //starting offset from margin    
var mnorthWest;
var zoom;
var maximize;
var mapWidth;
var mapHeight;
var mapTop;
var mapLeft;
var originalLngSpan;
var originalLatSpan;
var chicago = new GLatLng(41.91132484, -87.64017105);

function load() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    zoom = 16;
    map.setCenter(chicago, zoom);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    var mbounds = map.getBounds();
    var msouthWest = mbounds.getSouthWest();
    var mnorthEast = mbounds.getNorthEast();
    mnorthWest = new GLatLng(mnorthEast.lat(), msouthWest.lng());
    originalLngSpan = mnorthEast.lng() - msouthWest.lng();
    originalLatSpan = mnorthEast.lat() - msouthWest.lat();

    SW = new GLatLng(41.85728792769134, -87.68325805664062);
    NE = new GLatLng(41.965361748830624, -87.59708404541016);

    p4 = new GLatLng(SW.lat(), SW.lng());
    p1 = new GLatLng(NE.lat(), SW.lng());
    p2 = new GLatLng(NE.lat(), NE.lng());
    p3 = new GLatLng(SW.lat(), NE.lng());

    drawRectangle(p1, p2, p3, p4, weight);
    var BoxIcon1 = new GIcon(G_DEFAULT_ICON);
    BoxIcon1.image = "../images/dot.jpg";
    BoxIcon1.shadowSize = new GSize(0, 0);
    BoxIcon1.iconSize = new GSize(16, 16);
    BoxIcon1.iconAnchor = new GPoint(0, 0);
    var BoxIcon2 = new GIcon(BoxIcon1);
    BoxIcon2.iconAnchor = new GPoint(16, 0);
    var BoxIcon3 = new GIcon(BoxIcon1);
    BoxIcon3.iconAnchor = new GPoint(16, 16);
    var BoxIcon4 = new GIcon(BoxIcon1);
    BoxIcon4.iconAnchor = new GPoint(0, 16);

    var SaveIcon = new GIcon(G_DEFAULT_ICON);
    SaveIcon.image = "../images/save2.jpg";
    SaveIcon.shadowSize = new GSize(0, 0);
    SaveIcon.iconSize = new GSize(67, 19);
    SaveIcon.iconAnchor = new GPoint(0, 0);
    sim = new Array();
    sim[0] = 0; sim[1] = 0; sim[2] = 67; sim[3] = 0; sim[4] = 67; sim[5] = 19; sim[6] = 0; sim[7] = 19; SaveIcon.imageMap = sim;
    SaveOption = {
      icon: SaveIcon,
      draggable: false
    };
    SavePoint = new GLatLng(p1.lat() + offset, p1.lng() + offset);
    SaveMarker = new GMarker(SavePoint, SaveOption);
    GEvent.addListener(SaveMarker, "click",
    function() {
      savePoints();
      closeMap();
    });
    map.addOverlay(SaveMarker);
    var CancelIcon = new GIcon(G_DEFAULT_ICON);
    CancelIcon.image = "../images/cancel2.jpg";
    CancelIcon.shadowSize = new GSize(0, 0);
    CancelIcon.iconSize = new GSize(67, 19);
    CancelIcon.iconAnchor = new GPoint(0, 0);
    im = new Array();
    im[0] = 0; im[1] = 0; im[2] = 67; im[3] = 0; im[4] = 67; im[5] = 19; im[6] = 0; im[7] = 19; CancelIcon.imageMap = im;
    CancelOption = {
      icon: CancelIcon,
      draggable: false
    };
    CancelPoint = new GLatLng(p1.lat() + offset, p1.lng() + 3 * offset);
    CancelMarker = new GMarker(CancelPoint, CancelOption);
    GEvent.addListener(CancelMarker, "click",
    function() {
    	closeMap();
    });
    map.addOverlay(CancelMarker);

    //        var SizeIcon = new GIcon(G_DEFAULT_ICON);
    //        SizeIcon.image = "../images/maxim.jpg";        
    //        SizeIcon.shadowSize = new GSize(0,0);        
    //        SizeIcon.iconSize = new GSize(60,20);
    //        SizeIcon.iconAnchor = new GPoint(0, 0);
    //        sizeim = new Array();
    //        sizeim[0]=0
    //        sizeim[1]=0
    //        sizeim[2]=60
    //        sizeim[3]=0
    //        sizeim[4]=60
    //        sizeim[5]=20
    //        sizeim[6]=0
    //        sizeim[7]=20        
    //        SizeIcon.imageMap= sizeim;
    //        SizeOption = { icon:SizeIcon, draggable: false};
    //        SizePoint = new GLatLng(p1.lat()+ offset, p1.lng()+4.5*offset);        
    //        SizeMarker  = new GMarker(SizePoint, SizeOption);                
    //        GEvent.addListener(SizeMarker, "click", function() 
    //        {
    //            sizeMap();
    //        });        
    //      map.addOverlay(SizeMarker); 
    maximize = false;

    markerOptions1 = {
      icon: BoxIcon1,
      draggable: true,
      bouncy: false,
      dragCrossMove: true
    };
    markerOptions2 = {
      icon: BoxIcon2,
      draggable: true,
      bouncy: false,
      dragCrossMove: true
    };
    markerOptions3 = {
      icon: BoxIcon3,
      draggable: true,
      bouncy: false,
      dragCrossMove: true
    };
    markerOptions4 = {
      icon: BoxIcon4,
      draggable: true,
      bouncy: false,
      dragCrossMove: true
    };
    m1 = new GMarker(p1, markerOptions1);
    m2 = new GMarker(p2, markerOptions2);
    m3 = new GMarker(p3, markerOptions3);
    m4 = new GMarker(p4, markerOptions4);
    GEvent.addListener(map, "moveend",
    function() {
      relocate();
    });
    //lat() = y -> yukarı artar, asagı azalır
    //lng() = x -> saga dogru artar, sola dogru azalır
    GEvent.addListener(m1, "drag",
    function() {
      if (m1.getLatLng().lng() > m2.getLatLng().lng() - 0) {
	m1.setLatLng(new GLatLng(m2.getLatLng().lat(), m2.getLatLng().lng() - 0));
      } else if (m1.getLatLng().lat() < m4.getLatLng().lat() + 0) {
	m1.setLatLng(new GLatLng(m4.getLatLng().lat() + 0, m4.getLatLng().lng()))
      }
      m2.setLatLng(new GLatLng(m1.getLatLng().lat(), m2.getLatLng().lng()));
      m4.setLatLng(new GLatLng(m4.getLatLng().lat(), m1.getLatLng().lng()));
      relocate();
      drawRectangleOfMarker();
    });
    GEvent.addListener(m2, "drag",
    function() {
      if (m2.getLatLng().lng() < m1.getLatLng().lng() + 0) {
	m2.setLatLng(new GLatLng(m1.getLatLng().lat(), m1.getLatLng().lng() + 0));
      } else if (m2.getLatLng().lat() < m3.getLatLng().lat() + 0) {
	m2.setLatLng(new GLatLng(m3.getLatLng().lat() + 0, m3.getLatLng().lng()))
      }
      m1.setLatLng(new GLatLng(m2.getLatLng().lat(), m1.getLatLng().lng()));
      m3.setLatLng(new GLatLng(m3.getLatLng().lat(), m2.getLatLng().lng()));
      relocate();
      drawRectangleOfMarker();
    });
    GEvent.addListener(m3, "drag",
    function() {
      if (m3.getLatLng().lng() < m4.getLatLng().lng() + 0) {
	m3.setLatLng(new GLatLng(m4.getLatLng().lat(), m4.getLatLng().lng() + 0));
      } else if (m3.getLatLng().lat() > m2.getLatLng().lat() - 0) {
	m3.setLatLng(new GLatLng(m2.getLatLng().lat() - 0, m2.getLatLng().lng()))
      }
      m2.setLatLng(new GLatLng(m2.getLatLng().lat(), m3.getLatLng().lng()));
      m4.setLatLng(new GLatLng(m3.getLatLng().lat(), m4.getLatLng().lng()));
      relocate();
      drawRectangleOfMarker();
    });
    GEvent.addListener(m4, "drag",
    function() {
      if (m4.getLatLng().lng() > m3.getLatLng().lng() - 0) {
	m4.setLatLng(new GLatLng(m3.getLatLng().lat(), m3.getLatLng().lng() - 0));
      } else if (m4.getLatLng().lat() > m1.getLatLng().lat() - 0) {
	m4.setLatLng(new GLatLng(m1.getLatLng().lat() - 0, m1.getLatLng().lng()))
      }
      m1.setLatLng(new GLatLng(m1.getLatLng().lat(), m4.getLatLng().lng()));
      m3.setLatLng(new GLatLng(m4.getLatLng().lat(), m3.getLatLng().lng()));
      relocate();
      drawRectangleOfMarker();
    });
    map.addOverlay(m1);
    map.addOverlay(m2);
    map.addOverlay(m3);
    map.addOverlay(m4);
    relocate();
    //GEvent.addListener(map, "zoomend", calculateNewBoundries(oldLevel,newLevel));
    GEvent.addListener(map,"zoomend", function(oldLevel,newLevel) {
	if(oldLevel > newLevel){
	  return;
	}
	ratio = oldLevel/newLevel;
	if(!map.getBounds().containsLatLng(m1.getLatLng()) || !map.getBounds().containsLatLng(m3.getLatLng())){
	  northPoint = map.getBounds().getNorthEast().lat() - (map.getBounds().getNorthEast().lat() - map.getBounds().getSouthWest().lat())/12;
	  southPoint = map.getBounds().getSouthWest().lat() + (map.getBounds().getNorthEast().lat() - map.getBounds().getSouthWest().lat())/12;
	  eastPoint = map.getBounds().getNorthEast().lng() - (map.getBounds().getNorthEast().lng() - map.getBounds().getSouthWest().lng())/12;
	  westPoint = map.getBounds().getSouthWest().lng() + (map.getBounds().getNorthEast().lng() - map.getBounds().getSouthWest().lng())/12;
	  m1.setLatLng(new GLatLng(northPoint,westPoint));
	  m2.setLatLng(new GLatLng(northPoint,eastPoint));
	  m3.setLatLng(new GLatLng(southPoint,eastPoint));
	  m4.setLatLng(new GLatLng(southPoint,westPoint));
	  relocate();
	  drawRectangleOfMarker();
	}
    });
  } //if   

  updateCheckbox();
  
} //function

function relocate() {
  mbounds = map.getBounds();
  msouthWest = mbounds.getSouthWest();
  mnorthEast = mbounds.getNorthEast();
  mnorthWest = new GLatLng(mnorthEast.lat(), msouthWest.lng());
  zoom = map.getZoom();
  SaveMarker.setLatLng(new GLatLng(mnorthWest.lat() - getOffset(zoom + 3), mnorthWest.lng() + 2 * getOffset(zoom)));
  CancelMarker.setLatLng(new GLatLng(mnorthWest.lat() - getOffset(zoom + 3), mnorthWest.lng() + 3.95 * getOffset(zoom)));
  //SizeMarker.setLatLng(new GLatLng(mnorthWest.lat(), mnorthWest.lng() + 4.3 * getOffset(zoom)));
}

function getOffset(zoom) {
  if (zoom < 0 || zoom > 20) return 0;
  var o = new Array();
  o[0] = 49.152; o[1] = 24.576; o[2] = 12.288; o[3] = 6.144; o[4] = 3.072; o[5] = 1.536; o[6] = 0.768; o[7] = 0.384; o[8] = 0.192; o[9] = 0.096; o[10] = 0.048; o[11] = 0.024; o[12] = 0.012; o[13] = 0.006; o[14] = 0.003; o[15] = 0.0015; o[16] = 0.00075; o[17] = 0.000375; o[18] = 0.0001875; o[19] = 0.00009375; o[20] = 0.000046875;
  return o[zoom];
}

function getZoom(ratio) {
  zoomLevel = new Array();
  ratioLevel = new Array();

  for (i = 0; i < 20; i++) {
    if (i == 0) {
      zoomLevel[i] = 19;
      ratioLevel[i] = 0.0625;
    } else {
      zoomLevel[i] = zoomLevel[i - 1] - 1;
      ratioLevel[i] = ratioLevel[i - 1] * 2;
    }
  }

  for (i = 0; i < 19; i++) {
    if (ratio <= ratioLevel[2]) return zoomLevel[2];

    if (ratio >= ratioLevel[19]) return zoomLevel[19];

    if (ratio > ratioLevel[i] && ratio <= ratioLevel[i + 1]) return zoomLevel[i + 1] + 2;
  }
}

function drawRectangle(p1, p2, p3, p4, lineWeight) {
  rectangle = new GPolyline([p1, p2, p3, p4, p1], lineColor, lineWeight);
  map.addOverlay(rectangle);
}

function drawRectangleOfMarker() {
  p1 = m1.getLatLng();
  p2 = m2.getLatLng();
  p3 = m3.getLatLng();
  p4 = m4.getLatLng();
  map.removeOverlay(rectangle);
  drawRectangle(p1, p2, p3, p4, weight);
}

function savePoints() {
  $('North').value = Math.min(p4.lat(), p1.lat()).toFixed(8);
  $('South').value = Math.max(p4.lat(), p1.lat()).toFixed(8);
  $('East').value = Math.min(p4.lng(), p2.lng()).toFixed(8);
  $('West').value = Math.max(p4.lng(), p2.lng()).toFixed(8);
  $('map').style.visibility = 'hidden';
  $('map-coordinates').style.display = "inline";
}

function openMap() {
  minLat = $('North').value;
  maxLat = $('South').value;
  minLon = $('East').value;
  maxLon = $('West').value;
  
  if (minLat == '' || maxLat == '' || minLon == '' || maxLon == '') {
    zoom = 12;
    map.setCenter(chicago, zoom);
  }
  else {
	  try {
		  lat = (eval(minLat) + eval(maxLat)) / 2;
		  lon = (eval(minLon) + eval(maxLon)) / 2;
		  latSpan = Math.abs(maxLat - minLat);
		  lonSpan = Math.abs(maxLon - minLon);
		  ratio1 = latSpan / originalLatSpan;
		  ratio2 = lonSpan / originalLngSpan;
		  ratio = Math.max(ratio1, ratio2);
		  zoom = getZoom(ratio);
		  currentCenter = new GLatLng(lat, lon);
		  map.setCenter(currentCenter, zoom);
		  m1.setLatLng(new GLatLng(eval(maxLat), eval(minLon)));
		  m2.setLatLng(new GLatLng(eval(maxLat), eval(maxLon)));
		  m3.setLatLng(new GLatLng(eval(minLat), eval(maxLon)));
		  m4.setLatLng(new GLatLng(eval(minLat), eval(minLon)));
		  drawRectangleOfMarker();

		  var bounds = new GLatLngBounds();
		  bounds.extend(m1.point);
		  bounds.extend(m2.point);
		  bounds.extend(m3.point);
		  bounds.extend(m4.point);
		  map.setZoom(map.getBoundsZoomLevel(bounds));

alert("here");
	  } catch(e) {
		  zoom = 16;
		  map.setCenter(chicago, zoom);
	  }
  }
  sizeMap();
  $('map').style.visibility = 'visible';
  $('mainbody').style.display = 'none';
}

function sizeMap() {
  minLat = Math.min(m4.getLatLng().lat(), m1.getLatLng().lat());
  maxLat = Math.max(m4.getLatLng().lat(), m1.getLatLng().lat());
  minLon = Math.min(m4.getLatLng().lng(), m2.getLatLng().lng());
  maxLon = Math.max(m4.getLatLng().lng(), m2.getLatLng().lng());
  adjustRatio = 1;

  latSpan = Math.abs(maxLat - minLat);
  lonSpan = Math.abs(maxLon - minLon);
  ratio1 = latSpan / originalLatSpan;
  ratio2 = lonSpan / originalLngSpan;
  ratio = Math.max(ratio1, ratio2) / adjustRatio;
  zoom = getZoom(ratio) == 0 ? zoom: getZoom(ratio);
  lat = (eval(minLat) + eval(maxLat)) / 2;
  lon = (eval(minLon) + eval(maxLon)) / 2;
  currentCenter = new GLatLng(lat, lon);
  map.checkResize();
  map.setCenter(currentCenter, zoom);
  
}

function closeMap() {
    $('map').style.visibility = 'hidden';
    $('mainbody').style.display = 'block';
    $('mapCheckbox').focus();
    updateCheckbox();
}

function updateCheckbox() {
    $('mapCheckbox').checked = ($('North').value > 0 ? true : false);
}

function mapCheckboxChanged() {
	if(!$('mapCheckbox').checked && $('North').value > 0) {
		$('North').value = '';
		$('South').value = '';
		$('East').value = '';
		$('West').value = '';
		$('map-coordinates').style.display = "none";
	}
	else if ($('mapCheckbox').checked && $('North').value == '') {
		openMap();
	}
	else {
		$('mapCheckbox').checked = false;
	}
}


