/* map.js

This javascript page contains the code for using maps.
*/

var map = null;//variable for google map
var mapVE;//variable for virtual earth map
var mapMode = 'g';// g or ve
var geocoder = null;
//var noLoad = '';
var bounds = new GLatLngBounds();
var batch = [];
//var addrCount = 0;
//var notFound = '';
var mgr = null;
//var markerCount = 0;
var G_ZONING_MAP;
var mrkArray = new Array();
var mapW = null;
var zoomS = 19;
var zoomE = 1;
var tOn = false;
var tOverlay = new GTrafficOverlay();
var mId = 0;
var mX = 0; //expected number of markers
var mY = 0; //current count of markers found
var captureObj;//used for setting the div to return captured HTML when manually setting
var pW;
var pClient;
var pDiv;
var defaultIcon = null;

//standard icon
var icon = new GIcon();
icon.image = "../images/gicon.gif";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(20,34);
icon.shadowSize = new GSize(22, 20);
//icon.iconAnchor = new GPoint(6, 20);
icon.iconAnchor = new GPoint(10, 34);
icon.infoWindowAnchor = new GPoint(5, 1);

function DirCtrl() {
    }
    DirCtrl.prototype = new GControl();
    DirCtrl.prototype.initialize = function(map) {
      var container = document.createElement("div");
      var dirDiv = document.createElement("div");
	  dirDiv.innerHTML = '<center><span onclick="sH(\'Dirs\')" class="e3 p">Directions</span></center><div id="Dirs" style="display:none; height:200; background-color:FFFFFF; overflow:auto;"></div>';
      this.setButtonStyle_(dirDiv);
      container.appendChild(dirDiv);

      map.getContainer().appendChild(container);
      return container;
    }
    DirCtrl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(2, 20));
    }
    DirCtrl.prototype.setButtonStyle_ = function(button) {
      button.style.backgroundColor = "990000";
	  button.style.width = '217';
      button.style.border = "1px solid black";
      button.style.padding = "1px";
    }


function initMap(clear){
try{
	if(mapW != null){
		mapMode = 'g';
		zoomS = 19;
		zoomE = 1;
		setZoomer();
		if(clear == null){
			var choice = confirm("You already have a map open.\n\nClick OK to add to the existing results.\n\nClick Cancel to clear the existing results.");
		}
		cWin('W' + mapW);
		if(choice == false || clear != null){
			mrkArray.splice(0,mrkArray.length);
			mId = 0;
			bounds = new GLatLngBounds();
		}
	} else {
		mrkArray.splice(0,mrkArray.length);
		mId = 0;
	}
	return mrkArray.length; 
}
catch(ex){
	alert('Error on initMap(): ' + ex);
}
}

function loadGMap(m,w) {
try{
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(m));
		mapW = w;
		geocoder = new GClientGeocoder();
		map.disableDoubleClickZoom();
		map.disableScrollWheelZoom();
		/*document.getElementById(m).oncontextmenu = function(){
			cxt('g_map',mapW);
		}*/
	}
	//Add Zoning Map
	var copyright = new GCopyright(1,
	new GLatLngBounds(new GLatLng(40.7820037,-73.9397478),new GLatLng(40.7687442,-73.9213371) ),17, "NYC Zoning");
	var copyrightCollection = new GCopyrightCollection('Map Data:');
	copyrightCollection.addCopyright(copyright);    
	CustomGetTileUrl=function(a,b){
		if(b==17 &&( (a.x > 38621 && a.x < 38655 && a.y > 49182 && a.y < 49194) || (a.x > 38608 && a.x < 38673 && a.y > 49193 && a.y < 49226) || (a.x>38593 && a.x < 38676 && a.y>49225 && a.y < 49248) || (a.x > 38576 && a.x < 38706 && a.y > 49247 && a.y < 49289) || (a.x > 38576 && a.x < 38694 && a.y > 49288 && a.y < 49342) || (a.x>38576 && a.x<38657 && a.y>49341 && a.y<49353) )){
			return 'http://www.dyrealty.com/map/zoning/' + a.x+"_"+a.y+"_"+ b +".gif";
		} else if(b == 16 && ( (a.x > 19296 && a.x < 19305) && (a.y > 24612 && a.y < 24623) ) || ( (a.x > 19289 && a.x < 19305) && (a.y > 24622 && a.y < 24677)) || ( a.x==19289 && a.y>24654 && a.y < 24666 ) || ( (a.x > 19304 && a.x < 19337) && (a.y > 24591 && a.y < 24677)) || ( (a.x > 19336 && a.x < 19352) && (a.y > 24623 && a.y < 24655) )  || ( (a.x > 19336 && a.x < 19349) && (a.y > 24654 && a.y < 24672) )){
				return 'http://www.dyrealty.com/map/zoning/' + a.x+"_"+a.y+"_"+ b +".gif";
		} else if(b==15 &&( (a.x == 9644 && a.y > 12327 && a.y < 12333) || (a.x > 9644 && a.x < 9649 && a.y > 12311 && a.y < 12338) || (a.x > 9648 && a.x < 9652 && a.y > 12306 && a.y < 12338) || (a.x > 9651 && a.x < 9654 && a.y > 12301 && a.y < 12338) || (a.x == 9654 && a.y > 12298 && a.y < 12338)|| (a.x > 9654 && a.x < 9665 && a.y > 12295 && a.y < 12338)|| (a.x > 9651 && a.x < 9668 && a.y > 12301 && a.y < 12338)|| (a.x > 9667 && a.x < 9676 && a.y > 12311 && a.y < 12322)|| (a.x > 9667 && a.x < 9674 && a.y > 12321 && a.y < 12338)    ) ) {
			return 'http://www.dyrealty.com/map/zoning/' + a.x+"_"+a.y+"_"+ b +".gif";
		} else {
			return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
		}
	}
	var tilelayers = [new GTileLayer(copyrightCollection,15,17)];
	tilelayers[0].getTileUrl = CustomGetTileUrl;    
	tilelayers[0].getCopyright = function(a,b) {
		var c= copyrightCollection.getCopyrightNotice(a,b);
		if (!c) {
			c = G_NORMAL_MAP.getTileLayers()[0].getCopyright(a,b);
		}
		return c;
	}
	var _mMapError = 'Error';
	G_ZONING_MAP = new GMapType(tilelayers, new GMercatorProjection(18), "ZONING",{errorMessage:_mMapError});
	map.addMapType(G_ZONING_MAP);
	map.setCenter(new GLatLng(0,0),0);
	//create marker manager
	mgr = new GMarkerManager(map, {trackMarkers:true});
	var customUI = map.getDefaultUI();
	customUI.controls.scalecontrol = true;
	customUI.maptypes.normal = false;
	customUI.maptypes.satellite = false;
	customUI.maptypes.hybrid = false;
	customUI.maptypes.ZONING = false;
	customUI.maptypes.physical = false;
	customUI.zoom.scrollwheel = false;
	customUI.zoom.doubleclick = false;
	customUI.keyboard = false;
	customUI.controls.largemapcontrol3d = false;
	customUI.controls.smallzoomcontrol3d = false;
	customUI.controls.maptypecontrol = false;
	customUI.controls.menumaptypecontrol = false;
	map.setUI(customUI);
	switchType('m');
	
	/*lstner = GEvent.addListener(map, 'click', function(overlay, point){
		alert(point.lng() + ' ' + point.lat());
	});*/
}
catch(ex){
	alert('The system was unable to open the map at this time: ' + ex);
}
}

function initStreetView(){
	if(pW == null){
		nWin('d','../map/street_view.cfm','s','Street View');
		pW = winArray.length-1;
		pClient = new GStreetviewClient();
		GEvent.addListener(map, "click", function(overlay, latlng){
			pClient.getNearestPanorama(latlng, showPano);  
		});
		setTimeout("pDiv = new GStreetviewPanorama($('StreetView' + pW));pClient.getNearestPanorama(map.getCenter(), showPano);",250);
	} else {
		alert('You already have a street view window open.');
	}
}

function showPano(panoData){
	if(panoData.code != 200){
		alert('Sorry, no street view is available for that location.');
		return;
	}
	pDiv.setLocationAndPOV(panoData.location.latlng);
}

function getLatLng(a,ueid,entryName,i){
try{//d('Getting ' + a + ' for ' + entryName + ' @ ' + i);
	if (geocoder) {
		geocoder.getLocations(
			a,
			function(response) {
				if(!response || response.Status.code != 200){//d('Bad Response');
					var status = 'NA';
					var lat = null;
					var lng = null;
				} else {
					place = response.Placemark[0];
					if(!place){//d('No Place');
						var status = 'NA';
						var lat = null;
						var lng = null;
					} else {
						var status = 'Found';
						var lat = place.Point.coordinates[1];
						var lng = place.Point.coordinates[0];
						if(isNaN(ueid) == false && ueid != ''){
							ajaxLoader('../map/record_coords.cfm?UEID=' + ueid + '&Latitude=' + lat + '&Longitude=' + lng,'NA','j');
						}
						
						//createMarker(lat,lng,i,ueid,entryName);
					}
				}//d('Adding to Array');
				mrkArray[i] = new Array();
				mrkArray[i][0] = mId;
				mrkArray[i][1] = status;
				mrkArray[i][2] = lat;
				mrkArray[i][3] = lng;
				mrkArray[i][4] = entryName;
				mrkArray[i][5] = ueid;
				mId++;
				mY++;
				//d('Done Adding! ' + mrkArray.valueOf());
			}
		);
	}
}
catch(ex){
	alert('Error on getLatLng(): ' + ex);
}
}

var tM=0;
function timeAddMarkers(){
try{
	if(mX == mY){
		addMarkers();
	} else if(tM < 1000) {
		setTimeout('timeAddMarkers()',100);
		tM++;
	} else {
		var choice = confirm('The system has not finished processing all the locations.\n\nTo continue loading locations, click "OK".\n\nTo stop processing and display what has been found, click "Cancel".');
		if(choice){
			tM=0;
			timeAddMarkers()
		} else {
			addMarkers();
		}
	}
}
catch(ex){
	alert('Error on timeAddMarkers(): ' + ex);
}
}

function addMarkers(){
try{//d('W ' + mapW + ' ' + mrkArray.length);
	$('DragContainer' + mapW).innerHTML = '';//d(mrkArray.valueOf());
	for(i=0; i<mrkArray.length; i++){//d(mrkArray[i][4] + ' is ' + mrkArray[i][1]);
		var point = new GLatLng(mrkArray[i][2],mrkArray[i][3]);
		if(!point || mrkArray[i][1] == 'NA'){
			mrkArray[i][1] = 'NA';
			$('DragContainer' + mapW).innerHTML += '<div id="M' + mrkArray[i][0] + '" oncontextmenu="cxt(\'map_list\',' + mapW + ',\'ID=' + mrkArray[i][0] + '\')" class="g2 p">' + (i + 1) + '. ' + mrkArray[i][4] + ' could not be found</div>';
		} else {
			bounds.extend(point);
			$('DragContainer' + mapW).innerHTML += '<div id="M' + mrkArray[i][0] + '" onclick="goTo(' + i + ');highlightMapItem(' + mrkArray[i][0] + ');" oncontextmenu="cxt(\'map_list\',' + mapW + ',\'ID=' + mrkArray[i][0] + '\')" class="DragBox" style="font-size:10; color:006633;">' + (i + 1) + '. ' + mrkArray[i][4] + '<span id="MapComment' + mrkArray[i][0] + '" style="display:none; margin-left:10;" class="d2"></span></div>';//d('Going to Add ' + i + ' Marker: ' + mrkArray[i][5]);
			if(mrkArray[i][6] != null && mrkArray[i][6] != ''){
				$('MapComment' + mrkArray[i][0]).innerHTML = mrkArray[i][6];
				$('MapComment' + mrkArray[i][0]).style.display = 'block';
			}
			var marker = createMarker(mrkArray[i][2],mrkArray[i][3],i,mrkArray[i][5],mrkArray[i][4]);//has to be done in a separate function because of variables in a GEvent
			if(mapMode == 'g'){
				batch.push(marker);
			}
		}d('Finished ' + mrkArray[i][4]);
		//d('Current Index=' + i + ' of ' + mrkArray.length);
		//d('Next is: ' + mrkArray[i+1][4] + ' which is ' + mrkArray[i+1][1]);
	}
	//$('DragContainer' + mapW).innerHTML += '<a href="javascript: loadDD(\'TagDiv' + mapW + '\',' + mapW + ');">Move</a>';
	if(mapMode == 'g'){
		mgr.addMarkers(batch, 7,17);
		mgr.refresh();
		batch = [];
		map.setCenter(bounds.getCenter());
		if(map.getBoundsZoomLevel(bounds) > 15){
			map.setZoom(15);
		} else {
			map.setZoom(map.getBoundsZoomLevel(bounds));
		}
		if($('Zoomer') != null){
			setZoomer();
		}
	} else {
		//alert('Need code?');
	}
}
catch(ex){
	alert('Error on addMarkers(): ' + ex);
	d(mrkArray.valueOf());
}
}

function createMarker(lat,lng,i,ueid,title) {
try{//d(i + '. ' + ueid + ' ' + title)
	if(document.getElementById('PrintDiv') != null){
		var iconExt = '.gif';
	} else {
		var iconExt = '.png';
	}
	if(defaultIcon == null){
		if(i < 99){
			var iconPath = '../images/gicon' + (i+1) + iconExt;
		} else {
			var iconPath = '../images/gicon' + iconExt;
		}
	} else {
		var iconPath = '../images/' + defaultIcon;
	}
	if(isNaN(ueid)){
		var html = ueid;
	} else {
		var html = '<div id="MInfo' + mapMode + mrkArray[i][0] + '" style="width:240; height:150; background-color:FFFFFF; overflow:auto;" class="c2"></div>';
	}
	if(mapMode == 'g'){
		var thisIcon = new GIcon(icon);
		thisIcon.image = iconPath;
		var point = new GLatLng(lat,lng);
		var marker = new GMarker(point, {icon:thisIcon,draggable:true});
		marker.disableDragging();
		mrkArray[i][10] = marker;
		var obj = "MInfog" + mrkArray[i][0];//d(obj);
		var url = "../listings/entry_info.cfm?Simple=Yes&UEID=" + ueid + "&W=" + mapW;
		if(isNaN(ueid) == false && ueid != ''){
			GEvent.addListener(marker, "click", function() {
				highlightMapItem(mrkArray[i][0]);
				marker.openInfoWindowHtml(html);//alert(html);
				setTimeout("ajaxLoader('" + url + "','" + obj + "','r');",500);
				if(pW != null){
					point = new GLatLng(mrkArray[i][2],mrkArray[i][3]);
					pDiv = new GStreetviewPanorama($('StreetView' + pW));
					pClient.getNearestPanorama(point, showPano);
				}
			});
			GEvent.addListener(marker, "dragend", function() {
				mrkArray[i][2] = marker.getLatLng().lat();
				mrkArray[i][3] = marker.getLatLng().lng();
				if(isNaN(mrkArray[i][5]) == false){
					var choice = confirm('Do you want to permanently save this as the listing\'s location?');
					if(choice){
						ajaxLoader('../map/record_coords.cfm?UEID=' + mrkArray[i][5] + '&Latitude=' + marker.getLatLng().lat() + '&Longitude=' + marker.getLatLng().lng(),'NA','j');
					}
				}
				marker.disableDragging();
			});
		} else {
			GEvent.addListener(marker, "click", function() {
				highlightMapItem(mrkArray[i][0]);
				marker.openInfoWindowHtml(html);
				if(pW != null){
					point = new GLatLng(mrkArray[i][2],mrkArray[i][3]);
					pDiv = new GStreetviewPanorama($('StreetView' + pW));
					pClient.getNearestPanorama(point, showPano);
				}
			});
			GEvent.addListener(marker, "dragend", function() {
				mrkArray[i][2] = marker.getLatLng().lat();
				mrkArray[i][3] = marker.getLatLng().lng();
				marker.disableDragging();
			});
		}
		return marker;
	} else {
		var marker = new VEPushpin('VE'+i,new VELatLong(lat, lng),iconPath,'',html,'vepushpin');
		var url = "../listings/entry_info.cfm?Simple=Yes&UEID=" + ueid + "&W=" + mapW;
		var obj = "MInfove" + mrkArray[i][0];
		mapVE.AddPushpin(marker);
		$('VE' + i).onmouseover = function(){
			highlightMapItem(mrkArray[i][0]);
			if(isNaN(ueid) == false && ueid != ''){
				setTimeout("ajaxLoader('" + url + "','" + obj + "','r');",500);
			}
		};
		return marker;
	}
}
catch(ex){
	alert('Error on createMarker(): ' + ex);
}
}

var addMrkIndex = null;
function addMapItem(){
try{
	if(addMrkIndex == null){
		addMrkIndex = mrkArray.length;
		var textBubble = '<div class="a3">' + $('NewAddress').value + '</div><div class="b2">' + $('NewAddressText').value + '</div>';
		textBubble = textBubble.replace(/\n/gi,'<br>');
		getLatLng($('NewAddress').value,textBubble,$('NewAddress').value,addMrkIndex);
		setTimeout("addMapItem()",100);
	} else {
		if(mrkArray[addMrkIndex] != null){
			if(mrkArray[addMrkIndex][1] != 'NA'){
				alert('Address was found and added!');
			} else {
				alert('Sorry, but that address could not be found.');
			}
			$('NewAddress').value = '';
			$('NewAddress').selection = '';
			$('NewAddressText').value = '';
			addMrkIndex = null;
			sMarker();
		} else {
			setTimeout("addMapItem()",100);
		}
	}
}
catch(ex){
	alert('Error on addMapItem(): ' + ex);
}
}

function sMarker(){
try{
	status('Reindexing Map Markers');
	if(mapMode == 'g'){
		var oldCenter = map.getCenter();
		var oldZoom = map.getZoom();
		var oldType = map.getCurrentMapType().getName().substring(0,1).toLowerCase();
		var istOn = tOn;
		var isdirOn = dirOn;
	} else {
		var oldType = 'a-' + mapVE.GetBirdseyeScene().GetOrientation();
		mapVE.SetMapStyle(VEMapStyle.Road);
		var oldCenter =  new GLatLng(mapVE.GetCenter().Latitude,mapVE.GetCenter().Longitude);
		var oldZoom = mapVE.GetZoomLevel();
		mapMode = 'g';
	}
	loadGMap('Map' + mapW,mapW);
	addMarkers();
	if(mapMode == 'g'){
		if(istOn == true){
			tOn = false;
			traffic();
		}
		if(isdirOn == true){
			dirOn = false;
			directions();
		}
	}
	map.setCenter(oldCenter);
	if(oldType != 'm'){
		switchType(oldType);
	} else {
		
	}
	map.setZoom(oldZoom);
	setZoomer();
	status();
	docDefaults();
}
catch(ex){
	alert('Error on sMarker(): ' + ex);
}
}

function switchType(t){
try{
	zoomS = 19;//default values
	zoomE = 1;
	if(t.substring(0,1) == 'a' && mapMode == 'g'){
		loadLive(map.getCenter().lat(),map.getCenter().lng());
	} else if(mapMode == 've' && t.substring(0,1) != 'a'){
		mapVE.SetMapStyle(VEMapStyle.Road);
		loadGoogle(mapVE.GetCenter().Latitude,mapVE.GetCenter().Longitude);
	}
	if(t == 'm'){
		map.setMapType(G_NORMAL_MAP);
		zoomE = 10;
	} else if (t == 's'){
		map.setMapType(G_SATELLITE_MAP);
		zoomS = 19;
		zoomE = 10;
	} else if (t == 'h'){
		map.setMapType(G_HYBRID_MAP);
		zoomS = 19;
		zoomE = 10;
	} else if (t == 'k'){
		map.setMapType(G_SKY_VISIBLE_MAP);
		zoomS = 14;
		zoomE = 10;
		zoomTo(1);
	} else if (t == 'p'){
		map.setMapType(G_PHYSICAL_MAP);
		zoomS = 15;
		zoomE = 10;
	} else if (t.substring(0,1) == 'a'){
		zoomS = 2;
		setTimeout("aerialOrient('" + t.substring(2) + "')",1000);//have to give it time to load the Live Map before setting orientation
	} else if (t == 'z'){
		zoomS = 17;
		zoomE = 15;
		map.setMapType(G_ZONING_MAP);
	}
	setZoomer();
}
catch(ex){
	alert('Error on switchType(): ' + ex);
}
}

function loadLive(lat,lng){
try{
	tOn = false;
	dirOn = false;
	mapMode = 've'
	mapVE = new VEMap('Map' + mapW);
	mapVE.LoadMap(new VELatLong(lat,lng), 1,'o' , false);
	mapVE.HideDashboard();
	addMarkers();
}
catch(ex){
	alert('Error on loadLive(): ' + ex);
}
}

function loadGoogle(lat,lng,z){
try{
	mapMode = 'g';
	loadGMap('Map' + mapW,mapW);
	addMarkers();
	var point = new GLatLng(lat,lng);
	if(z == null){z=19;}
	map.setCenter(point,z);
}
catch(ex){
	alert('Error on loadGoogle(): ' + ex);
}
}

function aerialOrient(o){
try{
	if(!mapVE.IsBirdseyeAvailable()){
		alert(o + ' aerial view is not available for this area.');
	} else {
		mapVE.SetBirdseyeOrientation(o);
	}
}
catch(ex){
	alert('Error on aerialOrient(): ' + ex);
}
}

function zoomTo(zoom){
try{
	if(mapMode == 'g'){
		if(zoom == 'i'){
			map.zoomIn();
		} else if(zoom == 'o'){
			map.zoomOut();
		} else {
			map.setZoom(zoom);
		}
	} else {
		if(zoom == 'i'){
			mapVE.ZoomIn();
		} else if(zoom == 'o'){
			mapVE.ZoomOut();
		} else {
			mapVE.SetZoomLevel(zoom);
		}
	}
	setZoomer();
}
catch(ex){
	alert('Error on zoomTo(): ' + ex);
}
}

function setZoomer(){
try{
	if($('Zoomer') != null){
		var zooms = $('Zoomer').getElementsByTagName("span");
		for(i=0; i<zooms.length; i++){
			if(zooms.item(i).id.substring(0,4) == 'Zoom'){
				if(zoomS >= zooms.item(i).id.substring(4) && zooms.item(i).id.substring(4) >= zoomE){
					zooms.item(i).style.display = 'inline';
				} else {
					zooms.item(i).style.display = 'none';
				}
				zooms.item(i).style.backgroundColor = '66FFFF';
			}
		}
		if(mapMode == 'g'){
			$('Zoom' + map.getZoom()).style.backgroundColor = '0000FF';
		} else {
			$('Zoom' + mapVE.GetZoomLevel()).style.backgroundColor = '0000FF';
		}
	}
}
catch(ex){
	alert('Error on setZoomer(): ' + ex);
}
}

function goTo(i){
try{
	var lat = mrkArray[i][2];
	var lng = mrkArray[i][3];
	if(mapMode == 'g'){
		var point = new GLatLng(lat,lng);
		map.setCenter(point);
		//map.panTo(point);
		if(pW != null){
			pDiv = new GStreetviewPanorama($('StreetView' + pW));
			pClient.getNearestPanorama(point, showPano);
		}
	} else {
		mapVE.SetCenter(new VELatLong(lat,lng));
	}
}
catch(ex){
	alert('Error on goTo(): ' + ex);
}
}

function addToSearch(w,sw){
try{
	var mapSize = map.getBounds();
	var mapSize = map.getBounds();
	$('Lat1').value = mapSize.getSouthWest().lat();
	$('Lat2').value = mapSize.getNorthEast().lat();
	$('Lng1').value = mapSize.getNorthEast().lng();
	$('Lng2').value = mapSize.getSouthWest().lng();
	$('MapUEIDs').value = $('LookupUEIDs' + sw).value;
	$('UEType').value = $('SSection' + sw).value;
	ajaxLoader($('MapForm'),'NA','j');
}
catch(ex){
	alert('Error on addToSearch(): ' + ex);
}
}

function printMap(){
try{
	var step = 0;
	if(tOn == true){
		alert("Current traffic conditions cannot be printed and will be removed from the printed version.");
	}step = 1;
	if(window.PrintWin == null){
		alert('The print window is not accessible.  Please contact your system administrator.');
		return;
	}
	var pWin = window.PrintWin;
	pWin.mapMode = 'g';
	if(pWin.document.getElementById('PrintDiv') == null){
		alert('There is a problem accessing the Print Div.  Please contact your system administrator.');
		return;
	}
	var pDiv = pWin.document.getElementById('PrintDiv');
	pDiv.innerHTML = '';step = 2;
	var searchDiv = $('Map' + mapW);
	pDiv.innerHTML = '<table cellpadding="0" cellspacing="0" bgcolor="ff0000"><tr><td><div id="SearchDivP" style="width:' + searchDiv.offsetWidth + ';height:' + searchDiv.offsetHeight + '; background-color:ff0000; display:inline;" class="brdb1"></div></td><td valign="top"><div id="DragContainerP" style="width:150;display=' + $('MItems').style.display + ';"> </div></td></table><div id="Dirs"></div>';
	pWin.loadGMap('SearchDivP','P');
	pWin.mrkArray = mrkArray;
	if($('mType').value.substring(0,1) != 'a'){
		pWin.addMarkers();
	}step = 3;
	if(mapMode == 'g'){
		var zoomTo = map.getZoom();
		pWin.map.setCenter(map.getCenter());
	} else {
		var zoomTo = mapVE.GetZoomLevel();
		mapVE.SetMapStyle(VEMapStyle.Road);
		pWin.map.setCenter(new GLatLng(mapVE.GetCenter().Latitude,mapVE.GetCenter().Longitude));
		switchType($('mType').getAttribute('selection'));
		setTimeout("mapVE.SetZoomLevel(" + zoomTo + ");",100);
		pWin.switchType($('mType').getAttribute('selection'));
	}step = 4;
	if($('mType').value != 'm'){
		pWin.switchType($('mType').getAttribute('selection'));
	}
	if(mapMode == 'g' && dirOn == true){
		pWin.directions();
	}
	if(mapMode == 've'){
		pWin.mapVE.SetZoomLevel(zoomTo);
	} else {
		pWin.map.setZoom(zoomTo);
	}
	nWin('d','../system/print_options.cfm?What=NA&AutoScale=Warn&WinW=' + mapW,'s','Map Printing - Options');
}
catch(ex){
	alert('Error on printMap() at step ' + step + ': ' + ex);
}
}

function resizeMap(){
try{
	if(mapMode == 'g'){
		var oldCenter = map.getCenter();
		map.checkResize();
		map.panTo(oldCenter);
	} else {
		var oldCenter = mapVE.GetCenter();
		mapVE.Resize($('Map' + mapW).offsetWidth,$('Map' + mapW).offsetHeight);
		mapVE.PanToLatLong(oldCenter);
	}
}
catch(ex){
	alert('Error on resizeMap(): ' + ex);
}
}

function mMarker(obj){
try{
	if(!curTarget){return false;}
	var id = curTarget.id;
	var mrks = $('DragContainer' + mapW).getElementsByTagName("div");
	for(i=0; i<mrks.length; i++){//first, find out where it's been moved to
		if(mrks.item(i).id == id){
			var nPos = i;
		}
	}
	for(i=0; i<mrkArray.length; i++){//second, find out where it was
		if(mrkArray[i][0] == id.substring(1)){
			var oPos = i;
		}
	}//save array values to variables, then cut it from array
	var id = mrkArray[oPos][0];
	var status = mrkArray[oPos][1];
	var lat = mrkArray[oPos][2];
	var lng = mrkArray[oPos][3];
	var title = mrkArray[oPos][4];
	var ueid = mrkArray[oPos][5];
	var comments = '';
	if(mrkArray[oPos][6] != null){
		comments = mrkArray[oPos][6];
	}
	var obj = mrkArray[oPos][10];
	mrkArray.splice(oPos,1);
	mrkArray.splice(nPos,0,'Add');
	mrkArray[nPos] = new Array();
	mrkArray[nPos][0] = id;
	mrkArray[nPos][1] = status;
	mrkArray[nPos][2] = lat;
	mrkArray[nPos][3] = lng;
	mrkArray[nPos][4] = title;
	mrkArray[nPos][5] = ueid;
	if(comments != ''){
		mrkArray[nPos][6] = comments;
	}
	mrkArray[nPos][10] = obj;
	return true;
}
catch(ex){
	alert('Error on mMarker(): ' + ex);
}
}



function mapComment(id){
try{
	if($('MapComment').value != ''){
		$('MapComment'+ id).innerHTML = $('MapComment').value.replace(/\n/gi,'<br>');
		$('MapComment'+ id).style.display = 'block';
	} else {
		$('MapComment'+ id).innerHTML = '';
		$('MapComment'+ id).style.display = 'none';
	}
	for(i=0; i<mrkArray.length; i++){
		if(id == mrkArray[i][0]){
			mrkArray[i][6] = $('MapComment'+ id).innerHTML;
		}
	}
}
catch(ex){
	alert('Error on mapComment(): ' + ex);
}
}

function removeMapItem(id){
try{
	for(i=0; i<mrkArray.length; i++){
		if(mrkArray[i][0] == id){
			var oPos = i;
		}
	}
	mrkArray.splice(oPos,1);
	sMarker();
}
catch(ex){
	alert('Error on removeMapItem(): ' + ex);
}
}

function highlightMapItem(id){
try{
	if($('DragContainer' + mapW) != null){
		var items = $('DragContainer' + mapW).getElementsByTagName("div");
		for(i=0; i<items.length; i++){
			items.item(i).style.backgroundColor = 'ffffff';
		}
		if(id != null){
			$('M' + id).style.backgroundColor = 'ffff00';
		}
	}
}
catch(ex){
	alert('Error on hightlightMapItem(): ' + ex);
}
}

function sHMapItems(){
try{
	//alert($('MapTable').offsetWidth + ' - ' + parseInt($('MBar').style.width) + ' -10');
	//$('MapTD').height = $('MapTable').offsetHeight-$('MSet').offsetHeight;
	if($('MBar').style.display == 'block'){
		$('MBar').style.display = 'none';
		$('SHML').src = "../images/l_arr.jpg";
		
					$('Map' + mapW).style.width = '100%';
					$('Map' + mapW).style.height = '100%';
		$('MapTD').width = $('MapTable').offsetWidth-15;
	} else {
		$('MBar').style.display = 'block';
		$('SHML').src = "../images/r_arr.jpg";
		
					$('Map' + mapW).style.width = '100%';
					$('Map' + mapW).style.height = '100%';
		$('MapTD').width = $('MapTable').offsetWidth-parseInt($('MBar').style.width)-15;
	}
	resizeMap();
}
catch(ex){
	alert('Error on sHMapItems(): ' + ex);
}
}



var dirs;
var dirCtrl = new DirCtrl();
var dirOn = false;
function directions(){
try{
	if(dirOn == false){
		if(mrkArray.length > 1){
			if(window.name != 'PrintWin'){
				map.addControl(dirCtrl);
			}
			dirs = new GDirections(map,$('Dirs'));
			var wayArray = new Array();
			for(i=0; i<mrkArray.length; i++){
				if(mrkArray[i][1] == 'Found'){
					wayArray[wayArray.length] =  mrkArray[i][2] + ',' + mrkArray[i][3];
				}
			}
			dirs.loadFromWaypoints(wayArray);
			dirOn = true;
			setTimeout("for(i=0; i<" + wayArray.length + "; i++){dirs.getMarker(i).hide();}setZoomer();",1000);
			setTimeout("dirText()",500);
		} else {
			var choice = confirm('You must have two or more locations plotted in order to get directions.  Would you like to add a location?');
			if(choice){
				nWin('d','../map/add_map_item.cfm','f','Add Address');
			}
		}
	} else {
		map.removeControl(dirCtrl);
		dirs.clear();
		//$('Dirs').innerHTML = '';d('3');
		dirOn = false;
	}
}
catch(ex){
	alert('Error on directions(): ' + ex);
}
}

function dirText(){
try{
	if($('Dirs').innerHTML != ''){
		var tds = $('Dirs').getElementsByTagName("td");
		var mI = 0;
		for(i=0; i<tds.length; i++){
			if(tds.item(i).jscontent == 'address'){
				while(mrkArray[mI][1] != 'Found'){
					mI++;
				}
				tds.item(i).innerHTML = mrkArray[mI][4];
				tds.item(i).className = 'f3';
				tds.item(i).offsetParent.style.backgroundColor = 'CCFFFF';
				mI++;
			} else {
				tds.item(i).className = 'b2';
			}
		}
		var divs = $('Dirs').getElementsByTagName("div");
		for(i=0; i<divs.length; i++){
			divs.item(i).className = 'a3';
		}
		var imgs = $('Dirs').getElementsByTagName("img");
		var imgC = 0;
		for(i=0; i<imgs.length; i++){
			while(mrkArray[imgC][1] == 'NA'){
				imgC++;
			}
			imgC++;
			imgs.item(i).src = '../images/gicon' + imgC + '.png';
		}
		sH('Dirs');
	} else {
		setTimeout("dirText()",500);
	}
}
catch(ex){
	alert('Error on dirText(): ' + ex);
}
}


function traffic(){
try{
	if(tOn == false){
		if(mapMode == 'g'){
			map.addOverlay(tOverlay);
			tOn = true;
		} else {
			alert('The traffic overlay is not available on Aerial views.');
		}
	} else {
		map.removeOverlay(tOverlay);
		tOn = false;
	}
}
catch(ex){
	alert('Error on traffic(): ' + ex);
}
}

var first;
var rest;
function editMapItemTitle(id){
try{
	var html = $('M' + id).innerHTML;
	first = html.substring(0,(html.indexOf('. ') + 2));
	var title = html.substring((html.indexOf('. ') + 2),html.indexOf('<SPAN'));
	rest = html.substring(html.indexOf('<SPAN'));
	$('M' + id).innerHTML =  first + '<input id="EditMITitle" type="text" size="15" value="' + title + '" class="b2"><span class="a2 p" onclick="saveMapItemTitle(' + id + ')">OK</span>' + rest;
}
catch(ex){
	alert('Error on editMapItemTitle(): ' + ex);
}
}

function saveMapItemTitle(id){
try{
	var title = $('EditMITitle').value;
	for(i=0; i<mrkArray.length; i++){
		if(mrkArray[i][0] == id){
			mrkArray[i][4] = title;
		}
	}
	$('M' + id).innerHTML = first + title + rest;
}
catch(ex){
	alert('Error on saveMapItemTitle(): ' + ex);
}
}

function saveMap(title,desc,mode){
try{
	if(mapMode == 'g'){
		$("MapTitle").value = title;
		$("MapDesc").value= desc;
		var mrks = '';
		for(i=0; i<mrkArray.length; i++){//uses i2 to avoid interfering with saveSettings() process
			mrks += '^' + mrkArray[i][0] + '|' + mrkArray[i][1] + '|' + mrkArray[i][2] + '|' + mrkArray[i][3] + '|' + mrkArray[i][4] + '|' + mrkArray[i][5]; 
			if(mrkArray[i][6] != null){
				mrks += '|' + mrkArray[i][6];
			}
		}
		$('Markers').value = mrks.substring(1);
		if(mapMode == 've'){
			$('Zoom').value = mapVE.GetZoomLevel();
			mapVE.SetMapStyle(VEMapStyle.Road);
			$('Center').value = mapVE.GetCenter().Latitude + ',' + mapVE.GetCenter().Longitude;
			switchType($('mType').value);
			setTimeout("mapVE.SetZoomLevel(" + $('Zoom').value + ");setZoomer();",100);
		} else {
			$('Zoom').value = map.getZoom();
			$('Center').value = map.getCenter().lat() + ',' + map.getCenter().lng();d($('Center').value);
		}
		
		$('MapType').value = $('mType').selection + '|' + $('mType').value;
		if(tOn == true){
			$('Traffic').value = 'On';
		} else{
			$('Traffic').value = 'Off';
		}
		if(dirOn == true){
			$('Directions').value = 'On';
		} else{
			$('Directions').value = 'Off';
		}
		$('Mode').value = mode;
		ajaxLoader($('MapForm'),'NA','j');
	} else if(mode != 'reload') {
		alert("Maps in an Aerial view cannot be saved currently.  Please switch to another map type to continue.");
	}
}
catch(ex){
	alert('Error on saveMap(): ' + ex);
}
}


function xmlLoad(i,zoom,type,dir,tf){
try{
	if(dir == 'On'){
		directions();
	}
	if(tf == 'On'){
		traffic();
	}
	switchType(type);
	setTimeout("zoomTo(" + zoom + ");",500);
}
catch(ex){
	alert('Error on xmlLoad(): ' + ex);
}
}

var mContainer;
var mRun;
function getMap(mapDiv,ueids,containers,w,mapType){
try{
	mContainer = mapDiv;
	var moreURL = '';
	if(mapType != null){
		moreURL = '&MapType=' + mapType;
	}
	var mapURL = '../map/map.cfm?W=100&UEIDs=' + ueids + '&Containers=' + containers + '&MWidth=' + $(containers).parentNode.parentNode.offsetWidth + '&MHeight=' + $(containers).parentNode.parentNode.offsetHeight + '&Mode=Capture&Load=Immediate' + moreURL;
	ajaxLoader(mapURL,mapDiv,'r','pageCode(100);');
	
}
catch(ex){
	alert('Error on getMap(): ' + ex);
}
}

function img2Map(obj){
try{
	var theID = obj.id;
	var theName = obj.getAttribute('name');
	var maxW = obj.getAttribute('maxW');
	var maxH = obj.getAttribute('maxH');
	/*var context = obj.oncontextmenu.toString();
	context = context.substring(context.indexOf('{')+1);
	context = context.substring(0,context.lastIndexOf('}')-1).replace(/"/gi,'\'');*/
	var context = event2String(obj);
	if(obj.style.marginBottom){
		var margin = obj.style.marginBottom;
	}
	if(obj.tagName == 'IMG'){
		obj.outerHTML = '<div id="NewObj" style="overflow:hidden; width:' + maxW + '; height:' + maxH + ';" map="yes" oncontextmenu="' + context + '"><div style="width:' + maxW + '; height:' + maxH + '; clip:rect(0,' + maxW + ',' + maxH + ',0); position:relative;"><div id="BFM' + theID.substring(2) + '" style="LEFT: 0px; OVERFLOW: hidden; WIDTH: 100%; POSITION: absolute; TOP: 0px; HEIGHT: 100%"></div></div></div>';
		put = 'BFM' + theID.substring(2);
	} else if(obj.tagName == 'DIV'){
		obj.outerHTML = '<img id=NewObj src="" style=width:' + maxW + '; height:auto; margin-bottom:5; map=yes resize=yes oncontextmenu="' + context + '">';
		put = theID;
	}
	$('NewObj').setAttribute('name',theName);
	$('NewObj').id = theID;
	$(theID).setAttribute('maxW',maxW);
	$(theID).setAttribute('maxH',maxH);
	if(margin){
			$(theID).style.marginBottom = margin;
	}
	return put;
}
catch(ex){
	alert('Error on img2Map(): ' + ex);
}
}

//var noMove = false;
function capture(repeat){
try{
	if(mapMode == 'g' && $('mType').getAttribute('selection') != 'z'){
		var obj = captureObj.parentNode.parentNode;
		if($('mType').getAttribute('selection').substring(0,1) != 'a'){
			obj.setAttribute('name',$('mType').value + ' Map of');
		} else {
			obj.setAttribute('name',$('mType').value + ' at');
		}
		var w = parseInt(obj.getAttribute('maxW'));
		var h = parseInt(obj.getAttribute('maxH')) + 60;
		var latlng = map.getCenter().lat() + ',' + map.getCenter().lng();
		if(w > 640 || h > 580){
			alert('Google imposes a limit of 640 pixels x 580 pixels.  Your map is: ' + w + ' pixels x ' + (h-60) + '.  As a result, some edges may be cropped.');
			w = 640;
			h= 640;
		}
		if($('mType').getAttribute('selection') == 'm'){
			var mapType = 'roadmap';	
		} else if($('mType').getAttribute('selection') == 's'){
			var mapType = 'satellite';	
		} else if($('mType').getAttribute('selection') == 'h'){
			var mapType = 'hybrid';		
		} else if($('mType').getAttribute('selection') == 'p'){
			var mapType = 'terrain';	
		} else {
			alert('Sorry, but ' + $('mType').value + ' maps cannot be converted to an image at present.');	
			return;
		}
		var left = (obj.offsetWidth - w)/2;
		var top = ((obj.offsetHeight - (h-60))/2)-30;
		var url = 'http://maps.google.com/maps/api/staticmap?zoom=' + map.getZoom() + '&format=jpg-baseline&size=' + w + 'x' + h + '&sensor=false&center=' + latlng + '&maptype=' + mapType + '&markers=icon:' + encodeURIComponent('http://www.dyrealty.com/images/gicon.gif') + '|' + mrkArray[0][2] + ',' + mrkArray[0][3];
		//$(mrkArray[0][6]).innerHTML = '<img src="' + url + '" style="width:' + w + '; height:' + h + '; position:absolute; left:0; top:-30;">';
		captureObj.innerHTML = '<img src="' + url + '" style="width:' + w + '; height:' + h + '; position:absolute; left:' + left + '; top:' + top + ';">';
		if(mRun != null){
			eval(mRun);
		}
		if($('W' + mapW)){
			cWin('W' + mapW);
		}
		resetMap();
	} else {
		if(mapMode == 've' && repeat == null){//must reload the ve map to get the captured html correctly
			status('Capturing map, please wait');
			var zLive = mapVE.GetZoomLevel();
			mapVE.SetMapStyle(VEMapStyle.Road);
			loadLive(mapVE.GetCenter().Latitude,mapVE.GetCenter().Longitude);
			switchType($('mType').getAttribute('selection'));
			setTimeout("zoomTo(" + zLive + ");",1000);
			setTimeout("capture(1);",2000);
			return;
		} else if (mapMode == 'g' && repeat == null){
			status('Capturing map, please wait');
			loadGoogle(map.getCenter().lat(),map.getCenter().lng(),map.getZoom());
			switchType($('mType').getAttribute('selection'));
			setTimeout("capture(1);",2000);
			return;
		}
		var mapHTML = '';
		var obj = captureObj.parentNode.parentNode;
		if($('mType').getAttribute('selection').substring(0,1) != 'a'){
			obj.setAttribute('name',$('mType').value + ' Map of');
		} else {
			obj.setAttribute('name',$('mType').value + ' at');
		}
		
		var w = parseInt(obj.getAttribute('maxW'));
		var h = parseInt(obj.getAttribute('maxH'));
		var mImgs = byTag('img','Map' + mapW);
		for(i2=0; i2<mImgs.length; i2++){
			if(mapMode == 'g'){
				if(mImgs.item(i2).coordX != null && ((parseInt(mImgs.item(i2).style.left) <= w && parseInt(mImgs.item(i2).style.top) <= h) && (parseInt(mImgs.item(i2).style.left) >= -256 && parseInt(mImgs.item(i2).style.top) >= -256))){
					mImgs.item(i2).style.zIndex = 1000;
					mapHTML += mImgs.item(i2).outerHTML;d(i2 + ' outerHTML: ' + mImgs.item(i2).outerHTML);
				} else if(mImgs.item(i2).src.indexOf('gicon') > 1 && mImgs.item(i2).style.visibility != 'hidden'){
					mImgs.item(i2).style.zIndex = 1001;
					mapHTML += mImgs.item(i2).outerHTML;
				}
			} else if(mapMode == 've'){
				if(mImgs.item(i2).className.indexOf('MSVE_ImageTile') > -1){
					mapHTML += mImgs.item(i2).outerHTML;
				}
			}
		}
		captureObj.innerHTML = mapHTML;
		status();
		if(mRun != null){
			eval(mRun);
		}
		if($('C' + mapW) != null){
			cWin('W' + mapW);
		} else {
			purge(mContainer);
			$(mContainer).innerHTML = '';
		}
		resetMap();
	}
}
catch(ex){
	alert('Error on capture(): ' + ex);
	resetMap();
}
}

function map2jpg(mode){
	if(mapMode == 've' || (mapMode == 'g' && $('mType').getAttribute('selection') == 'z')){
		status('Creating the image...');
		var w = parseInt($('Map' + mapW).offsetWidth);
		var h = parseInt($('Map' + mapW).offsetHeight);
		var lOff = 0;
		var tOff = 0;
		var mDivs = byTag('div','Map' + mapW);
		for(i2=0; i2<mDivs.length; i2++){
			if(mDivs.item(i2).className.indexOf('MSVE_Map') > -1){
				lOff = 	parseInt(mDivs.item(i2).style.left);
				tOff = 	parseInt(mDivs.item(i2).style.top);
				break;
			}
		}
		var mImgs = byTag('img','Map' + mapW);
		var srcs = '';
		for(i2=0; i2<mImgs.length; i2++){
			if(mapMode == 've'){
				if(((parseInt(mImgs.item(i2).style.left)+lOff <= w && parseInt(mImgs.item(i2).style.top)+tOff <= h) && (parseInt(mImgs.item(i2).style.left)+lOff >= -256 && parseInt(mImgs.item(i2).style.top)+tOff >= -256))){
					if(mImgs.item(i2).className.indexOf('MSVE_ImageTile') > -1){
						if(srcs != ''){srcs += '^';}
						srcs += mImgs.item(i2).src + '~' + (parseInt(mImgs.item(i2).style.left) + lOff) + '~' + (parseInt(mImgs.item(i2).style.top) + tOff);
					}
				}
			} else {
				if(mImgs.item(i2).coordX != null && ((parseInt(mImgs.item(i2).style.left) <= w && parseInt(mImgs.item(i2).style.top) <= h) && (parseInt(mImgs.item(i2).style.left) >= -256 && parseInt(mImgs.item(i2).style.top) >= -256))){
					if(srcs != ''){srcs += '^';}
					src = srcs += mImgs.item(i2).src + '~' + parseInt(mImgs.item(i2).style.left) + '~' + parseInt(mImgs.item(i2).style.top);
				}	
			}
		}
		ajaxLoader('../map/map_2_jpg.cfm?Imgs=' + encodeURIComponent(srcs) + '&Width=' + w + '&Height=' + h,'NA','j','status()');
	} else {
		var latlng = map.getCenter().lat() + ',' + map.getCenter().lng();
		var w = parseInt($('Map' + mapW).offsetWidth);
		var h = parseInt($('Map' + mapW).offsetHeight) + 60;
		if(w > 640 || h > 580){
			alert('Google imposes a limit of 640 pixels x 580 pixels.  Your map is: ' + w + ' pixels x ' + (h-60) + '.  As a result, some edges may be cropped.');
			w = 640;
			h= 640;
		}
		
		if($('mType').getAttribute('selection') == 'm'){
			var mapType = 'roadmap';	
		} else if($('mType').getAttribute('selection') == 's'){
			var mapType = 'satellite';	
		} else if($('mType').getAttribute('selection') == 'h'){
			var mapType = 'hybrid';		
		} else if($('mType').getAttribute('selection') == 'p'){
			var mapType = 'terrain';	
		} else {
			alert('Sorry, but ' + $('mType').value + ' maps cannot be converted to an image at present.');	
			return;
		}
		var url = 'http://maps.google.com/maps/api/staticmap?zoom=' + map.getZoom() + '&format=jpg-baseline&size=' + w + 'x' + h + '&sensor=false&center=' + latlng + '&maptype=' + mapType;
		ajaxLoader('../map/map_2_jpg.cfm?GetURL=' + encodeURIComponent(url) + '&Width=' + w + '&Height=' + h,'NA','j','status()');
	}
}

function resetMap(){
	if(mapVE){
		mapVE.Dispose();
	}
	if(tOn == true){traffic()}
	if(dirOn == true){directions()}
	dirs = null;
	dirCtrl = new DirCtrl();
	mapW = null;
	mapMode = 'g';
	zoomS = 19;
	zoomE = 1;
	//mX = 0;  //Removed because breaking multiple properties
	//mY = 0;
	bounds = new GLatLngBounds();
	GUnload();
}