<!-- Original:  Chris Hettinger (chettinger@visionary.com) -->
<!-- Web Site:  http://www.iowarealty.com -->

var map = null;
var mapG = null;
var latLong = null;
var zoomLevel = 10;
var mapCenter = null;
var locArray = new Array();
var prevFocus = null;
var pins = new Array();
var veToken = "";

function VirtualEarthLoad(loadLat, loadLong, loadZoom, map_type) {
	if (loadLat=='' || loadLat < 40.0 || loadLat > 43.0) {
		loadLat = 41.58836548867729;
	}
	if (loadLong == '' || loadLong < -96.0 || loadLong > -90.0) {
		loadLong = -93.61767768859863;
	}
	if (loadZoom == '' || loadZoom < 0 || loadZoom > 19) {
		loadZoom = 13;
	}
	if (map_type == '') {
		map_type = VEMapStyle.Road;
	}
	
	//Creating a Map instance and loading the map with initial parameters
	map = new VEMap('RsMap_VEMap');
	//map.SetClientToken(getVEtoken());
	//map.AttachEvent('ontokenexpire', getVEtoken);
	//map.AttachEvent('ontokenerror', getVEtoken);
	
	// Hide the default dashboard controls
	map.HideDashboard();
	// LoadMap, setting default center point and zoon level
	latlong = new VELatLong(loadLat, loadLong);
	map.LoadMap(latlong, loadZoom, map_type, false, VEMapMode.Mode2D, true, 1);
	// zoom to cursor and center
	map.SetMouseWheelZoomToCenter(false);

	// Add attach event calls from later listings here
	map.AttachEvent("onendpan", VSiInitMap);
	map.AttachEvent("onendzoom", VSiInitMap);
	map.AttachEvent("onclick", getcoord);

	//map.AttachEvent("onclick", GetLatLong);
	VSiInitMap();
}

// part of testing, pulled from docs, onclick echo lat/long by pixel value on map
function GetLatLong(e) {
	var x = e.mapX;
	var y = e.mapY;
	pixel = new VEPixel(x, y);
	var LL = map.PixelToLatLong(pixel);
	document.getElementById("mapConsole").innerHTML = "Pixel X: " + x + " | Pixel Y: " + y + "<br /> LatLong: " + LL;
}

function setMapShape(list_numb,list_type,property_class,beds,lat,long,pin_title,pin_txt,isSaved) {
	pins[list_numb] = createPin(lat, long);
	if ( map != null ) {
		pins[list_numb].SetTitle(pin_title);
		pins[list_numb].SetDescription(pin_txt);
		icon = setCustomIRIcons(list_type,property_class,beds,"map","t",isSaved)
		pins[list_numb].SetCustomIcon(icon);
		map.AddShape(pins[list_numb]);
	} else {
		if(pin_title != '' || pin_txt != '') {
			GEvent.addListener(pins[list_numb], 'click', function() {
				pins[list_numb].openInfoWindowHtml(pin_title+"<br>"+pin_txt);
			});
			GEvent.addListener(pins[list_numb], 'mouseover', function() {
				pins[list_numb].openInfoWindowHtml(pin_title+"<br>"+pin_txt);
			});
		}
		mapG.addOverlay(pins[list_numb]);
	}
}

function createPin(lat, long) {
	if (map != null) {
		var point = new VELatLong(lat, long);
		var pin = new VEShape(VEShapeType.Pushpin, point);
	} else {
		var point = new GLatLng(lat, long);
		var pin = new GMarker(point);
	}
	
	return pin;
}

function focusOnListing(list_numb,board_id,lat,long) {
	// Focus the map on the listing selected
	// If the filters box is showing when the user clicks on the grid, this will close the filter prior to showing the info box
	// this avoids a z-indexing problem where the infobox displays over the filters
	elem = document.getElementById('RsMap_Filters');
	elem2 = document.getElementById('btnToggleFilters');
	if (elem && elem.className == "RsMap_Filters_On") {
		//alert("hide filters, make className RsMap_Filters_Off");
		elem2.style.display = "";
		closeFilters(elem);
	}
	// if lat long is unavialble (unmapped) skip the map focus call
	setMapFocus(list_numb,lat, long);
	// Highlight grid row
	setGridFocus(list_numb);
	// Set Listing Summary window with this listings details
	setListingSummary(list_numb);
	thisThmb = 0;
	thmbA = new Array();
	url = '/buying/getimages.asp?list_numb='+list_numb+'&board_id='+board_id
	imgs = getHtmlAjax(url, "GET");
	oImgs = new String(imgs);
	codes = oImgs.slice(oImgs.indexOf("#")+1,oImgs.lastIndexOf("#"));
	codeA = codes.split("#");
	for(i=0; i<codeA.length; i++) {
		thmbA.push(codeA[i]);
	}
}

// called in results_map when a result set has only 1 result, that may fall outside of
// the default map view due to default zoom level or window view area.
function centerOnListing(list_numb,board_id,lat,long) {
	//alert("lat: " + lat + " long: " + long + " loadZoom: " + zoomLevel);
	map.SetCenterAndZoom(new VELatLong(lat, long), zoomLevel);
	focusOnListing(list_numb,board_id,lat,long) ;
	tbl = document.getElementById('RsMap_ListingsTbl');
	if(tbl) {
		tbl.innerHTML = '';
	}

	url = "results_map_results.asp?" + getCoordQS() + '&' + GetQueryString('lat1,lon1,lat2,lon2');
	//alert(url);
	//thehtml = getHtmlAjax(url, "GET");
	rslts = document.getElementById('RsMap_ListingsTbl');
	if(tbl) {
		//tbl.innerHTML = thehtml;
		new Ajax.Updater('RsMap_ListingsTbl', url, {asynchronous:true});
	}
}

function setGrid(lat1, lon1, lat2, lon2) {
	url = 'results_map_results.asp?';
	//html = getHtmlAjax(url, "GET");
	new Ajax.Updater('mydiv', '/foo/bar', {asynchronous:true});
}

function setGridFocus(list_numb) {
	var id = 'list' + eval(list_numb);
	
	if (prevFocus != "" && prevFocus != null) {
		clearGridFocus(prevFocus);
	}
	elem = document.getElementById(id);
	if(elem) {
		elem.className += " RsMap_ListingsTbl_Row_selected";
	}
	prevFocus = id;
}

function clearGridFocus(prevFocus) {
	//alert("I last focused on: "+prevFocus);
	elem = document.getElementById(prevFocus);
	if(elem) {
		myStr = new String(elem.className);
		//alert(myStr);
		rExp = / RsMap_ListingsTbl_Row_selected/;
		newStr = new String();
		result = myStr.replace(rExp, newStr);
		//alert(result);
		elem.className = result;
	}
}

function setMapFocus(list_numb, lat,long) {
	map.HideInfoBox();
	map.ShowInfoBox(pins[list_numb]);
}

function setListingSummary(list_id) {
	url = 'results_map_summary.asp?list_numb=' + list_id + '&' + GetQueryString('list_numb');
	//new Ajax.Updater('RsMap_Summary_content', url, {asynchronous:true});
	thehtml = getHtmlAjax(url, "GET");
	document.getElementById('RsMap_Summary_content').innerHTML = thehtml;
}

function setCustomIRIcons(list_type,property_class,beds,dispOn,mapped,fav) {
	var prefix = "";
	var prop_class = "";
	var unmapped = "";
	var filename = "";
	var saved = "";
		
	//	PART 1 - DispOn = "Displayed on" contextually, icon will be displayed on the map or list, sets image prefix
	if (dispOn == "map") {
		prefix = "map_pin_";
	} else {
		prefix = "list_ico_";
	}
	
	//	PART 2 - listing type
	list_type = list_type.toLowerCase();
	
	//	PART 3 - proptery class
	if(list_type=="res") {
		prop_class = "_res"
	
		if (beds == "1") {
			prop_class = prop_class + "_1b"
		} else if (beds == "2") {
			prop_class = prop_class + "_2b"
		} else if (beds == "3") {
			prop_class = prop_class + "_3b"
		} else if (beds == "4") {
			prop_class = prop_class + "_4b"
		} else if (beds >= "5") {
			prop_class = prop_class + "_5b"
		}
	} else {
		prop_class = "";
	}

	/*
	//removed the seperate distinction for each property class for now, to fit these within the by bedroom number coloring.
	if (list_type == "res" && property_class != "") {
		if (property_class == "RESIDENT") {
			prop_class = "_res"
		} else if (property_class == "ACREAGES") {
			prop_class = "_acre"
		} else if (property_class == "CONDTOWN") {
			prop_class = "_cdtn"
		} else {
			prop_class = "_res"	
		}
	}
	*/
	
	//	PART 4 - Unmapped properties
	//	If we are unable to map the property, it is skipped from the map display
	if (mapped == "f") {
		unmapped = "_unmapped"; 	// image filename suffix for homes saved in MyIowaRealty (DSM,FR only)
	}
	
	//	PART 5 - Saved in MyIowaRealty favorites (DSM,FR only)
	// no yet implemented
	if (fav == true) {
		saved = "_fav";
	}
	
	filename = prefix+list_type+prop_class+unmapped+saved+".gif"
	imgpath = "<img src='/images/results_map/"+filename+"' alt='"+list_type+","+prop_class+"' />";
	return imgpath;
}

function ToggleFilters() {
	elem = document.getElementById('RsMap_Filters');
	elem2 = document.getElementById('btnToggleFilters');
	if (elem.className == "RsMap_Filters_Off") {
		//alert("show filters, make className RsMap_Filters_On");
		elem2.style.display = "none";
		document.frmFilter.search_text.value = '';
		openFilters(elem);
	} else if (elem.className == "RsMap_Filters_On") {
		//alert("hide filters, make className RsMap_Filters_Off");
		elem2.style.display = "";
		document.frmFilter.search_text.value = 'Enter an Address or MLS #';
		closeFilters(elem);
	}
	
}

function openFilters(e) {
	// Hides any open info boxes before the filters box is opened
	map.HideInfoBox();
	e.className = ""; // clear any other values
	e.className = "RsMap_Filters_On";
}

function closeFilters(e) {
	e.className = ""; // clear any other values
	e.className = "RsMap_Filters_Off";
}

function ToggleDefinition() {
	elem = document.getElementById('RsMap_Results_definition');
	//elem2 = document.getElementById('btnToggleFilters');
	if (elem.className == "divOff") {
		//alert("show filters, make className RsMap_Filters_On");
		//elem2.style.display = "none";
		openDefinition(elem);
	} else if (elem.className == "divOn") {
		//alert("hide filters, make className RsMap_Filters_Off");
		//elem2.style.display = "";
		closeDefinition(elem);
	}
	
}
function openDefinition(e) {
	// Hides any open info boxes before the filters box is opened
	//map.HideInfoBox();
	e.className = ""; // clear any other values
	e.className = "divOn";
}
function closeDefinition(e) {
	e.className = ""; // clear any other values
	e.className = "divOff";
}

function clearInput() {
	elem = document.getElementById('RsMap_FilterForm_searchtext');
	elem.value = "";
}

function populateInput() {
	elem = document.getElementById('RsMap_FilterForm_searchtext');
	if (elem.value == "") {
		elem.value = "Enter Address or MLS #";
	}
}

function setIRDashboard() {	
}

function ZoomIn(){
	map.ZoomIn();
}
function ZoomOut(){
	map.ZoomOut();
}
function PanUp(){
	map.Pan(0,-25);
}
function PanDown(){
	map.Pan(0,25);
}
function PanLeft(){
	map.Pan(25,0);
}
function PanRight(){
	map.Pan(-25,0);
}
function viewRoad(){
	map.SetMapStyle(VEMapStyle.Road);
}
function viewAerial(){
	map.SetMapStyle(VEMapStyle.Aerial);
}
function viewHybrid(){
	map.SetMapStyle(VEMapStyle.Hybrid);
}
function viewBirdsEye(){
	if (map.IsBirdseyeAvailable()) {
		map.SetMapStyle(VEMapStyle.Birdseye);
	} else {
		alert("Bird's Eye View is unavailable for this area");
	}
}
function viewNorth() {
	map.SetBirdseyeOrientation(VEOrientation.North);
}
function viewSouth() {
	map.SetBirdseyeOrientation(VEOrientation.South);
}
function viewEast() {
	map.SetBirdseyeOrientation(VEOrientation.East);
}
function viewWest() {
	map.SetBirdseyeOrientation(VEOrientation.West);
}
function VSiInitWindow() {
	VSISetMapHeight();
	VSiInitMap();
}

function VSiInitMap() {
	map.Clear();
	setDashboard();
	tbl = document.getElementById('RsMap_ListingsTbl');
	if(tbl) {
		tbl.innerHTML = '';
	}

	url = "results_map_results.asp?" + getCoordQS() + '&' + GetQueryString('lat1,lon1,lat2,lon2');
	//alert(url);
	//thehtml = getHtmlAjax(url, "GET");
	rslts = document.getElementById('RsMap_ListingsTbl');
	if(tbl) {
		//tbl.innerHTML = thehtml;
		new Ajax.Updater('RsMap_ListingsTbl', url, {asynchronous:true});
	}
	setPins();
}

function viewListing(list_numb) {
	url = '../buying/detail_ml.asp?rt=map&list_numb=' + list_numb + '&' + getCoordQS() + '&' + GetQueryString('list_numb,lat1,lon1,lat2,lon2,zoom,rt');
	//alert(url);
	document.location.href = url;
}

function getCoordQS() {
	if(map.GetMapStyle() == VEMapStyle.Birdseye) {
		var bemap = map.GetBirdseyeScene();
		var view = bemap.GetBoundingRectangle();
	} else {
		var view = map.GetMapView();
	}
	topleft = view.TopLeftLatLong;
	lat1 = topleft.Latitude;
	lon1 = topleft.Longitude;
	bottomright = view.BottomRightLatLong;
	lat2 = bottomright.Latitude;
	lon2 = bottomright.Longitude;
	zoom = map.GetZoomLevel()
	
	//alert(lat1+":"+lon1+"::"+lat2+":"+lon2+":"+zoom);
	return "lat1="+lat1+"&lon1="+lon1+"&lat2="+lat2+"&lon2="+lon2+"&zoom="+zoom;

}

function VSISetMapHeight() {
	wh = getWindowHeight();
	bh = document.getElementById("tblBanner").clientHeight;
	tnh = document.getElementById("tblTopNav").clientHeight;
	resh = 175;
	fh = 25;//document.getElementById("IRFooter").clientHeight;
	mh = wh - bh - tnh - fh;
	document.getElementById('RsMap').style.height = mh;
	document.getElementById('RsMap_VEMap').style.height = mh - resh;
	document.getElementById('RsMap_MapDiv').style.height = mh - resh;
}

function getVEtoken() {
	/*url = '/ve/getIRtoken.aspx';
	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) {
	    //veToken = $('vetoken');
		//ghetto
		resp = new String(transport.responseText);
		veToken = resp.slice(resp.indexOf(">")+1, resp.indexOf("</"));
	  }
	});*/
	
}

function setDashboard() {
	if(map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapMode() == VEMapMode.Mode3D) { 
		img = new Image();
		img.src = "/images/results_map/ui_birdseye_active.gif";
		document.getElementById('veDashboard').src = img.src;
		addArea("ControlMap","veCWMap","rect","42,60,62,80","javascript:rotateCW()");
		addArea("ControlMap","veCCWMap","rect","42,82,62,102","javascript:rotateCCW()");
	} else {
		veMap = document.getElementById('ControlMap');
		if(veMap) {
			cwArea = document.getElementById("veCWMap");
			if(cwArea) {
				veMap.removeChild(cwArea);
			}
			ccwArea = document.getElementById("veCCWMap");
			if(ccwArea) {
				veMap.removeChild(ccwArea);
			}
		}
		if(map.IsBirdseyeAvailable()) {
			img = new Image();
			img.src = "/images/results_map/ui_birdseye_available.gif";
			document.getElementById('veDashboard').src = img.src;
			o = document.getElementById('veBirdsEyeTip');
			if(o) { o.style.display = ""; }
			addArea("ControlMap","veAreaMap","rect","3,186,47,207","javascript:viewBirdsEye()");
		} else {
			img = new Image();
			img.src = "/images/results_map/ui_birdseye_unavailable.gif";
			document.getElementById('veDashboard').src = img.src;
			o = document.getElementById('veBirdsEyeTip');
			if(o) { o.style.display = "none"; }
			if(veMap) {
				beArea = document.getElementById("veAreaMap");
				if(beArea) {
					veMap.removeChild(beArea);
				}
			}
		}
	}
}
function addArea(parent,id,shape,coords,href) {
	o = document.getElementById(id);
	if(!o) {
		p = document.getElementById(parent);
		if(p) {
			e = document.createElement("area");
			e.id = id;
			e.shape = shape;
			e.coords = coords;
			e.href = href;
			p.appendChild(e);
		}
	}
}
function rotateCW() {
	var bemap = map.GetBirdseyeScene();
	switch(bemap.GetOrientation()) {
		case VEOrientation.East: map.SetBirdseyeOrientation(VEOrientation.South);
			break;
		case VEOrientation.South: map.SetBirdseyeOrientation(VEOrientation.West);
			break;
		case VEOrientation.West: map.SetBirdseyeOrientation(VEOrientation.North);
			break;
		default: map.SetBirdseyeOrientation(VEOrientation.East);
			break;
	}
}
function rotateCCW() {
	var bemap = map.GetBirdseyeScene();
	switch(bemap.GetOrientation()) {
		case VEOrientation.East: map.SetBirdseyeOrientation(VEOrientation.North);
			break;
		case VEOrientation.South: map.SetBirdseyeOrientation(VEOrientation.East);
			break;
		case VEOrientation.West: map.SetBirdseyeOrientation(VEOrientation.South);
			break;
		default: map.SetBirdseyeOrientation(VEOrientation.West);
			break;
	}
}
function getcoord(e) {
	var x = e.mapX;
	var y = e.mapY;
	pixel = new VEPixel(x, y);
	//var LL = map.PixelToLatLong(pixel);
	var LL = map.GetCenter();
	if(o=document.getElementById("bvacoords")) { o.innerHTML = "LatLong: " + LL + " zoom:"+map.GetZoomLevel(); }
}
