/*
* The programming and software materials herein are copyright Cyberhomes LLC (CH).
* The programming and software materials are owned, held, or licensed by CH. Personal, educational,
* non-commercial, commercial or any other use of these materials, without the written permission of the
* CH, is strictly prohibited.
*/


var map = null;
var labelID = 0;
var getCountFromCache = false;
var doMapResize = 1;
var noMapPinPanel = 0;
var isOfficeSearch = document.location.search.toLowerCase().indexOf('searchtype=office') > -1 ? 1 : 0;
var myParcel = null;
var setLatLongVars = false;

//Fixes
function Firefox2Fix()
{
	// If the browser is Firefox get the version number
	var ffv = 0;
	var ffn = "Firefox/"
	var ffp = navigator.userAgent.indexOf(ffn);
	if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
	// If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
	if (ffv >= 1.5) 
	{
		Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
	}
}

function is_supportedBrowser()
{
    var b = jQuery.browser;
    var v = parseFloat(b.version.substring(0, 3));

    return ((b.msie && v >= 6) || (b.mozilla && v >= 1.8) || (b.safari && v >= 416));
}
function BrowserNotSupported()
{
	document.getElementById('mapDiv').style.visibility='hidden';
	document.getElementById('MapNotSupported').style.display='block';
}
//Map
/*function to Load VE Map
	parameters:
		latitude
		longitude
		zoom - The zoom level to display. Valid values range from 1 through 19. 
		style - Valid values are a for aerial, h for hybrid, o for oblique (bird's eye), and r for road.
		isLocked - A Boolean value that specifies whether the map view is displayed as a fixed map that the user cannot change. 
*/
function getMap(midLat, midLong, zoom, style, isLocked) //only used from custom top level map
{
	renderMap(midLat, midLong, 0, 0, 0, 0, zoom, style, isLocked, 1, 0, 0);
	getCountFromCache = true;
}

function renderMap(midLat, midLong, neLat, neLong, swLat, swLong, zoom, style, isLocked, showListingCount, captureLatLong, mapScale)         
{
    // No need to do listing count on office search page       		
    if (isOfficeSearch == 1)
    {        
        showListingCount = 0;
        hideControlPanel();     
    }   
          
	if (is_supportedBrowser())
	{	
	    if (midLat == 0)
	    {	        
	        midLat = (parseFloat(neLat) + parseFloat(swLat))/2;
	        midLong = (parseFloat(neLong) + parseFloat(swLong))/2;
	        
	        if (zoom == 0)
	        {
	            zoom = getZoomBetweenTwoLatLongs(neLat, neLong, swLat, swLong)+1;
	        }
	    }	
	        
		if (zoom <= 0)
		{	
			if (mapScale > 0)
				zoom = getZoomFromScale(midLat, mapScale);
			else
				zoom = 10;	//set default
		}
		
		Firefox2Fix();		
		
		if (document.ListingSearch && document.ListingSearch.doMapResize)
            doMapResize = document.ListingSearch.doMapResize.value;
        if (doMapResize == 1 && isLocked != 1)
            document.getElementById('mapDiv').style.width = GetMapWidth();         
		
		map = new VEMap('mapDiv');   
    	map.LoadMap(new VELatLong(parseFloat(midLat), parseFloat(midLong)), zoom, style, isLocked, VEMapMode.Mode2D, 0);       		

		if (isLocked == 1) //if static map - change cursor from hand to pointer
		{
			document.getElementById("mapDiv").childNodes[0].style.cursor = "default";
			window.onresize = null;
		}
		else
		{
		    DoResize(); //if not static map - resize map on window resize
		}
		
		if (showListingCount == 1)
		{
			map.AttachEvent('onendpan', onEndPan); //doListingCount and toggleBirdsEye
			map.AttachEvent('onendzoom', onEndZoom);
		}
		else
		{
			map.AttachEvent('onendpan', onEndPan2);
			map.AttachEvent('onendzoom', onEndZoom2);
		}

		map.AttachEvent('onobliquechange', setBirdsEyeSceneHtml);
		setLatLongVars = (captureLatLong == 1);
		
		showSearchCriteria();
		if (showListingCount == 1)
		{
			doListingCount(getCountFromCache);
		}
		else
		{
			setLatLongFormFields();
		}
		
	    showCustomControl();
		
		myParcel = Parcel(map);
	}
	else
	{
		BrowserNotSupported();
	}
}

//Map Resize

window.onresize = function()
{
    DoResize();
}
function DoResize()
{
    var mapWidth = 640;
    var mapHeight = 444; // map height will not change

    if(map && doMapResize != 0 && !(mapWidth == (GetMapWidth())))
    {
        var lat = map.vemapcontrol.GetCenterLatitude();
		var lon = map.vemapcontrol.GetCenterLongitude();
		mapWidth = GetMapWidth(); 
		// POI lock layer needs to cover entire map
		var lockLayer = document.getElementById('tblLockLayer');
		if (lockLayer != null)
		{
		    lockLayer.style.width  = mapWidth;
            lockLayer.style.height = mapHeight;
        }
       
        if (mapWidth < 640) 
            mapWidth = 640;
	   	map.vemapcontrol.Resize(mapWidth,mapHeight);
		map.vemapcontrol.PanToLatLong(lat,lon);
	}
	else
	{
	    setLatLongFormFields();
	    updatePOI(); // Map This Property
	}
}
function GetMapWidth()
{
		var x;
		if (self.clientWidth) // all except Explorer
		{
			x = self.innerWidth;
		}
		else if (document.documentElement && document.documentElement.clientWidth)
			// Explorer 6 Strict Mode
		{
			x = document.documentElement.clientWidth;
		}
		else if (document.body) // other Explorers
		{
			x = document.body.clientWidth;
		}
		x = x - 190; // minus space on the left
		if (x < 680) // mininum width
		    x = 680;
		    
		if (noMapPinPanel != 1)
		    x = x - 50;  // minus the size of POI panel
		
		return x;
}


//Event Functions
function getLatLong()
{
	var lblLat = document.getElementById("lbl_latitude");
	var lblLong = document.getElementById("lbl_longitude");
	
	var ll = map.GetCenter();
	var latitude = ll.Latitude.toFixed(5);
	var longitude = ll.Longitude.toFixed(5);
	
	if (lblLat)
		lblLat.innerHTML = latitude;
	if (lblLong)
		lblLong.innerHTML = longitude;
	// map.DeletePushpin('mylisting');
	deleteAllPushpins();
	addMapPushpin('mylisting', latitude, longitude, 1, 'Selected Location', null);
	
}
function onEndPan(e) //with ListingCount
{	
	doListingCount(getCountFromCache); 
	toggleBirdsEye();
	getCountFromCache = false;
	displayPOI();
	if (setLatLongVars == true)
	    getLatLong();
}
function onEndPan2(e) //without ListingCount
{
	//doListingCount(getCountFromCache);
	setLatLongFormFields();
	toggleBirdsEye();
	displayPOI();
    deleteAllPushpins()
	loadOfficePins();
    if (document.ListingSearch && document.ListingSearch.pinLat && document.ListingSearch.pinLong && document.ListingSearch.pinDesc)
        addMapPushpin('mylisting', document.ListingSearch.pinLat.value,document.ListingSearch.pinLong.value, 1, null, document.ListingSearch.pinDesc.value);
	if (setLatLongVars == true)
	    getLatLong();
}
function onEndZoom(e) //with ListingCount
{
	doListingCount(); 
	toggleBirdsEye();	
	// HSET19458 - No longer use custom control
    // setSlider();
	displayPOI();
	myParcel.updateDisplay(isZoomedIn()); // Enable/Disable Parcels checkbox for some ZoomInLevel
	if (setLatLongVars == true)
	    getLatLong();
}
function onEndZoom2(e) //without ListingCount
{
	//doListingCount();
	toggleBirdsEye();	
	setLatLongFormFields();
	// HSET19458 - No longer use custom control
    // setSlider();
	displayPOI();
	deleteAllPushpins()
	loadOfficePins();
    if (document.ListingSearch && document.ListingSearch.pinLat && document.ListingSearch.pinLong && document.ListingSearch.pinDesc)
        addMapPushpin('mylisting', document.ListingSearch.pinLat.value,document.ListingSearch.pinLong.value, 1, null, document.ListingSearch.pinDesc.value);
	myParcel.updateDisplay(isZoomedIn());  // Enable/Disable Parcels checkbox for some ZoomInLevel
	if (setLatLongVars == true)
	    getLatLong();
}

//Control
function showCustomControl()
{
	if (document.getElementById('customMapControl') != null)
	{
		//HSET 19385
		//map.HideDashboard(); 
		//document.getElementById('customMapControl').style.visibility='visible';
	// HSET19458 - No longer use custom control
    // setSlider();
		//map.AttachEvent('onendzoom', setSlider);
		//toggleBirdsEye();
	}
	if (document.getElementById('mapPinControl') != null)
	{
	    document.getElementById('mapPinControl').style.visibility='visible';
	}
}

function hideControlPanel()
{
    if (document.getElementById("mapPinControl") != null)
    {
        document.getElementById("mapPinControl").style.display = 'none';
    }
}

// Used only by AgentSearch (office search)
function loadOfficePins()
{
    docLoading= false;        
    if (isOfficeSearch && map.pushpins.length == 0)
    {                
        var neLat = document.getElementById('SearchMapNELat').value;
        var neLong = document.getElementById('SearchMapNELong').value;
        var swLat = document.getElementById('SearchMapSWLat').value;
        var swLong = document.getElementById('SearchMapSWLong').value;
        var midLat = parseFloat(neLat) + parseFloat(swLat);
        var midLong = parseFloat(neLong) + parseFloat(swLong);
        
        // We want to get all offices in the US
        //var neLat = "180.0";
        //var neLong = "180.0";
        //var swLat = "-180.0";
        //var swLong = "-180.0";
       
        url = Utils.PublicAppName + '/Office/OfficeMapSearch.ashx?neLat=' + neLat + '&neLong=' + neLong + '&swLat=' + swLat + '&swLong=' + swLong;
        loadXMLDoc(url, processOfficeMapSearch);         
    }
}

function processOfficeMapSearch()
{    
    if (xmlhttp.readyState == 4) 
    { 
        try
        {             
            eval(xmlhttp.responseText);
        }
        catch(e)
        {         
        }
    }
}

function hidexControl(val)
{
	var xControl = document.getElementById("xControl");
	var carrot_up = document.getElementById("carrot_up");
	var carrot_down = document.getElementById("carrot_down");
	
	if (xControl)
	{
		if (val == 1)
		{
			xControl.style.display = "none";
			carrot_up.style.display = "none";
			carrot_down.style.display = "inline";
		}
		else
		{
			xControl.style.display = "inline";
			carrot_up.style.display = "block";
			carrot_down.style.display = "none";
		}
	}
}

//Control Functions
function getZoomFromScale(lat, mapScale)
{	
	var zoom = 0;
	var log2 = 0.30102999566398119521373889472449;
	var veConstant = 616309948.48;
	var piDiv180 = 0.017453292519943295769236907684886;
	zoom = parseInt((Math.log(veConstant * Math.cos(lat * piDiv180)/mapScale)/Math.log(10))/log2);
	if (zoom > 0)
		return zoom;
	else
		return 10;
}
function getZoomBetweenTwoLatLongs(neLat, neLong, swLat, swLong)
{
    var zoom = 0;
    var mapDiagonalLengthInMiles = 0.000093724963365725027097464813077603; //The length of the diagonal line between the top right and bottom left, in miles.
	var mapScale;
	var myDistance;

	//Distance in miles between the top right and bottom left coords that the MapPoint would represent
	myDistance = distanceBtwnTwoLatLongs(neLat, neLong, swLat, swLong);
	mapScale = myDistance / mapDiagonalLengthInMiles;  //On the MapPoint map generated, 1 inch represents whatever "scale" is
	
	zoom = getZoomFromScale(neLat, mapScale);
	return zoom;
}
function distanceBtwnTwoLatLongs(neLat, neLong, swLat, swLong)
{
    var theta;
    var dist;
    var piDiv180 = 0.017453292519943295769236907684886;

    theta = neLong - swLong;
    dist = Math.sin(neLat * piDiv180) * Math.sin(swLat * piDiv180) + Math.cos(neLat * piDiv180) * Math.cos(swLat * piDiv180) * Math.cos(theta * piDiv180);
    dist = Math.acos(dist);
    dist = dist * 57.295779513082320876798154814105;
    dist = dist * 60 * 1.1515; 
    return dist;
}
function setMapStyle(style)
{
    var r = document.getElementById("control_road");
	var be = document.getElementById("control_birdseye");
	var cb = document.getElementById("chkbx_labels");
	var label = document.getElementById("cbToggleLabel");
	
	switch(style)
	{
		case 'r':
			map.SetMapStyle(VEMapStyle.Road);
			be.style.display = "none";
			r.style.display = "block";
			cb.style.display = "none";
			break;
		case 'h':
			map.SetMapStyle(VEMapStyle.Hybrid);
			be.style.display = "none";
			r.style.display = "block";
			cb.style.display = "block";
			label.checked = true;
			break;
		case 'a':
			map.SetMapStyle(VEMapStyle.Aerial);
			be.style.display = "none";
			r.style.display = "block";
			cb.style.display = "block";
			label.checked = false;
			break;
		case 'b':
			map.SetMapStyle(VEMapStyle.Birdseye);
			r.style.display = "none";
			be.style.display = "block";
			cb.style.display = "none";
			setBirdsEyeSceneHtml();
			hidePOIIcons();
			break;
	}
}

function Parcel (map) {
    //jchurchill 20070928 - saigono...
    //private members
    var that = object();
    var p_dplToggle = false;
    //public members
    that.isEnabled = document.getElementById("hParcelLines") != null; // If the object is there (see incVEMap.xsl line ~420), we're enabled.
    //public methods
    that.updateDisplay = function (isZoomedIn) {
        if (! that.isEnabled ) {
            return;
        }
        if (document.getElementById("hParcelLines")) {
            if( p_dplToggle != isZoomedIn )
            {
                SetParcelLayerVisibility(map, isZoomedIn);
                p_dplToggle = isZoomedIn;
            }
        }
    };
    //initialize
    if ( that.isEnabled && typeof AddDMPParcelLayer != 'undefined') {
        //alert('enabled');
        self.setTimeout('AddDMPParcelLayer(map)', 100); // Call it with a slight delay because the PS.com JS may not be ready and the lines won't show.
        p_isDplInitialized = true;
        that.updateDisplay();
    }
    return that;
}
function object(o) {
    function F() {};
    F.prototype = o;
    return new F();
}

function setZoomFromSlider(val)
{
    // HSET19458 - No more custom slider
    return;
	if (map && map.GetZoomLevel() != val)
		map.SetZoomLevel(val);
}
function setSlider()
{
	// HSET19458 - No longer use custom control
    return;

    if (isOfficeSearch == 1)
    {
       A_SLIDERS[0].s_form =  'OfficeMapSearch';
    }
	if (A_SLIDERS[0])
	{
		A_SLIDERS[0].f_setValue(map.GetZoomLevel());
		A_SLIDERS[0].S0OA.style.visibility='visible';
	}
}

function continuousPan(x, y, count)
{
	map.vemapcontrol.ContinuousPan(x, y, count, false);
}

function pan(dir)
{
	switch(dir)
	{
		case 'east':
			continuousPan(10, 0, 20); 
			break;
		case 'west':
			continuousPan(-10, 0, 20);  
			break;
		case 'north':
			continuousPan(0, -10, 20);
			break;
		case 'south':
			continuousPan(0, 10, 20);
			break;
		case 'northwest':
			continuousPan(-10, -10, 20);
			break;
		case 'northeast':
			continuousPan(10, -10, 20);
			break;
		case 'southwest':
			continuousPan(-10, 10, 20);
			break;
		case 'southeast':
			continuousPan(10, 10, 20);
			break;
	}

}


function toggleLabel()
{
	var cb = document.getElementById("cbToggleLabel");
	
	if (cb)
	{
		if (cb.checked)
			setMapStyle('h');
		else
			setMapStyle('a');
	}

}

//Search Criteria
function setLatLongFormFields()
{
	if(map)
	{
		var c = document.getElementById('mapDiv');
		var mapZoom =  map.GetZoomLevel();
		//alert(mapZoom);

		var s = map.GetMapStyle();
		if  (s == VEMapStyle.Birdseye) 
		{
			var birdView = map.GetBirdseyeScene();
		   	//ne_LatLong = map.PixelToLatLong(new VEPixel(c.offsetWidth, 0));
			//sw_LatLong = map.PixelToLatLong(new VEPixel(0, c.offsetHeight));
		}
		else
		{
			ne_LatLong = map.PixelToLatLong(new VEPixel(c.offsetWidth, 0));
			sw_LatLong = map.PixelToLatLong(new VEPixel(0, c.offsetHeight));
		}
        
        var SearchMapNELat = document.getElementById('SearchMapNELat');
        var SearchMapNELong = document.getElementById('SearchMapNELong');
        var SearchMapSWLat = document.getElementById('SearchMapSWLat');
        var SearchMapSWLong = document.getElementById('SearchMapSWLong');
        var SearchMapZoom = document.getElementById('SearchMapZoom');
        
		if(SearchMapNELat) SearchMapNELat.value = ne_LatLong.Latitude;
		if(SearchMapNELong)SearchMapNELong.value = ne_LatLong.Longitude;
		if(SearchMapSWLat) SearchMapSWLat.value = sw_LatLong.Latitude;
		if(SearchMapSWLong)SearchMapSWLong.value = sw_LatLong.Longitude;
		if(SearchMapZoom) SearchMapZoom.value = mapZoom;
	}
}

function showSearchCriteria() 
 {
 //BOET 5679  added extra chk "document.getElementById('Criteria/ListingSearchID').value==''" for showing "td_displayproperties"
 	if ((document.getElementById('td_displayproperties') != null)&& (document.getElementById('Criteria/ListingSearchID') == null || document.getElementById('Criteria/ListingSearchID').value==''))document.getElementById('td_displayproperties').style.display='inline';
    if (document.getElementById('rowSearchTypeSpecificCriteria') != null)document.getElementById('rowSearchTypeSpecificCriteria').style.display='inline';
    if (document.getElementById('rowBasicSearchCriteria') != null)document.getElementById('rowBasicSearchCriteria').style.display='inline';
    if (document.getElementById('rowAdvancedSearchCriteria') != null)document.getElementById('rowAdvancedSearchCriteria').style.display='inline';
    if (document.getElementById('tblSubmitSearchButtons') != null) document.getElementById('tblSubmitSearchButtons').style.display='inline';
    if (document.getElementById('tblDisclaimer') != null) document.getElementById('tblDisclaimer').style.display='block';    
    if (document.getElementById('clearSearch1') != null) document.getElementById('clearSearch1').style.display='inline';
    if (document.getElementById('clearSearch2') != null) document.getElementById('clearSearch2').style.display='inline';
    if (document.getElementById('td_tip') != null) document.getElementById('td_tip').style.display='inline';//BOET 5583
    //document.images.MapSearchInstructions.src = 'mapsearch_level2_instructions.gif';
    
   //Dashboard();
 }
 
//Pushpin
function addMapPushpin(id, pinLat, pinLong, pinTypeID, pinTitle, pinDesc)
{
    if (map) 
	{
	    var pinImgUrl = getPinImgUrl(pinTypeID);
	    //map.DeleteAllPushpins();
		var pin = new VEPushpin(
				id, 
				new VELatLong(parseFloat(pinLat), parseFloat(pinLong)), 
				MapUIImagePath + pinImgUrl, 
				pinTitle, 
				pinDesc
				);
		try {
		    map.AddPushpin(pin);
		}
		catch (e) 
		{
		}
		
		//AddLabel(pinLat, pinLong, pinDesc);
    }
}

//Show Office Message
function showOfficeMessage(message)
{
    if (map)
    {
        try
        {
            var c = document.getElementById('mapDiv');
		    		    
            document.getElementById("OfficeMessage").style.position = "absolute";
            document.getElementById("OfficeMessage").style.left = (c.offsetParent.offsetLeft + c.offsetWidth - 170) + "px";          
            document.getElementById("OfficeMessage").style.top = (c.offsetParent.offsetTop + 5) + "px";            
            document.getElementById("OfficeMessage").innerHTML = message;                         
        }
        catch(e)
        {
        }
    }
}

function deleteAllPushpins()
{
    if (map)
        map.DeleteAllPushpins();
}

function deletePushpin(id)
{
    if (map)
    {
        try
        {
            map.DeletePushpin(id);
        }
        catch (e) 
        {
            // Caused by composite id values created when two points overlap
        }
    }
}  

function getPinImgUrl(pinTypeID)
{
    var pinImgUrl = '';
    
    switch(pinTypeID)
	{
		case 1: // Listing Pin
		    pinImgUrl = '../map/images/POI/listing_active.gif';
		   //  pinImgUrl = 'MapControl/pin_listing.gif';
		    break;
		case 2: // New Listing Pin
		    pinImgUrl = 'MapControl/pin_newlisting.gif';
		    break;
		case 3: // Office Pin
		    pinImgUrl = 'MapControl/pin_office.gif';
		    break;
		case 4: // Multiple Listings
		    pinImgUrl = 'MapControl/pin_multilisting.gif';
		    break;
		case 5: // Child Care
		    pinImgUrl = 'POI/childcare_sel.gif';
            break;
        case 6: // Schools
		    pinImgUrl = 'POI/schools_sel.gif';
		    break;
		case 7: // Restaurants
		    pinImgUrl = 'POI/restaurants_sel.gif';
		    break;  
	    case 8: // Shopping
		    pinImgUrl = 'POI/shopping_sel.gif';
		    break;
		case 9: // Groceries
		    pinImgUrl = 'POI/grocery_sel.gif';
		    break;
		case 10: // Gas
		    pinImgUrl = 'POI/gas_sel.gif';
		    break;	
		case 11: // Bank
		    pinImgUrl = 'POI/bank_sel.gif';
		    break;
		case 12: // Recreation, Entertainment  
		    pinImgUrl = 'POI/park_sel.gif';
		    break;
		case 13: // Hospital
		    pinImgUrl = 'POI/hospital_sel.gif';
		    break;		    	    
		case 14: // Transportation
		    pinImgUrl = 'POI/transport_sel.gif';
		    break;	
	    case 15: // Lodging
		    pinImgUrl = 'POI/lodging_sel.gif';
		    break;		    
		case 16: // Worship
		    pinImgUrl = 'POI/worship_sel.gif';
		    break;		    	    	    
		case 17: // Police
		    pinImgUrl = 'POI/police_sel.gif';
		    break;		    
		case 18: // Fire
		    pinImgUrl = 'POI/fire_sel.gif';
		    break;
		case 19: // Library
		    pinImgUrl = 'POI/library_sel.gif';
		    break;
		case 20: // Post Office
		    pinImgUrl = 'POI/postoffice_sel.gif';
		    break;  
		case 21: // Cultural
		    pinImgUrl = 'POI/cultural_sel.gif';
		    break;
		case 22: // Multiple POI
		    pinImgUrl = 'POI/multiple_sel.gif';
		    break;
		// 5/16/2008 [Vince Horst]: BOET 8382: Don't enable multi-office pins for the time being.
		// case 23: // Icon for offices sharing same geo-location
		//    pinImgUrl = 'MapControl/pin_multipleoffice.gif';
		//    break;
    }
    return pinImgUrl;		    
}
function togglePins(id, pinTypeID) 
{
    if (docLoading)
        return;

    var flag = (document.getElementById('enbl_' + id).value == 0);
    if (flag)
    {
        document.getElementById('icon_' + id + '_sel').style.display = "block";
        document.getElementById('icon_' + id + '_unsel').style.display = "none";
        document.getElementById('enbl_' + id).value = 1;
    }
    else
    {
        document.getElementById('icon_' + id + '_sel').style.display = "none";
        document.getElementById('icon_' + id + '_unsel').style.display = "block";
        document.getElementById('enbl_' + id).value = 0;
    }

    if (flag)
        submitListingCount();
    else
        deleteListingOfficePins(id);
}
function togglePinBubble(newID, currID)
{
    var newDiv = document.getElementById('pin_' + newID);
    var currDiv = document.getElementById('pin_' + currID);
    if (newDiv && currDiv)
    {
        currDiv.style.display = "none";
        newDiv.style.display = "block";
    }
}
function addLabel(lat, lon, lblText)
{
	var point = map.LatLongToPixel(new VELatLong(lat, lon));
    var el = document.createElement("divLabel"); 
    el.setAttribute('id',"VELabel" + labelID++);
    el.style.top = (point.y + 1) + "px"; 
    el.style.left = (point.x + 1) + "px"; 
    el.style.border = "1px solid gray";
    el.style.font = "9px arial";
    el.style.background = "White";
    el.style.padding = "0px 2px 0px 2px";
    el.innerHTML = lblText;  
    map.AddControl(el);
}
function addControl(name, html, width, height, top, left)
{
	var el = document.createElement(name); 
    el.setAttribute('id', name);
    el.style.top = top + "px"; 
    el.style.left = left + "px"; 
    el.style.width = width + "px";
    el.style.height = height + "px";
    el.innerHTML = html;  
    map.AddControl(el);
}

//Driving Directions
function GetDrivingDirections()
{
	if (map)
	{
		var frm = document.forms["frmDrivingDirections"];
		//var frm = window.frmDrivingDirections;
		if (frm)
		{
			var from = FormatAddress(frm.taDDFrom.value); //Modified for BOET 5640 - Praveen Kumar
			var to = FormatAddress(frm.taDDTo.value); //Modified for BOET 5640 - Praveen Kumar
			
			if (from == '')
				alert("Please enter a start address");
			else if (to == '')
				alert("Please enter a end address");
			else
				map.GetRoute(from, to, null, null, onGotRoute);
		}
	}
}
//function Added for BOET 5640 - Praveen Kumar
function FormatAddress(str) {
    if (!str)
        return '';

    str = str.trim();
	while(str.match(/,(\S)/) != null)
	{
		var arr=str.match(/,(\S)/);		
		str=str.replace(arr[0],arr[0].replace(',',', '));
	}
	while(str.match(/,(\r)/) != null)
	{
		var arr=str.match(/,(\r)/);		
		str=str.replace(arr[0],arr[0].replace(',',', '));
	}
	str=str.replace('\r',', '); //replace carriage return with space
	str=str.replace('#',''); //invalid character

	return str.trim();
}
function onGotRoute(route)         
{           
	var routeinfo='';            
	                       
	
	var steps="";            
	var len = route.Itinerary.Segments.length;               
	steps+= '<table width="100%" border="0" cellspacing="0" cellpadding="0" style="border: #666666 solid 1px;">'; 
	steps+= '<tr class="BGColor2"><td></td><td width="85%" class="dd_header">Direction</td><td width="15%" class="dd_header">Distance</td></tr>'
	for(var i = 0; i < len ;i++)               
	{     
		if (i % 2 == 0)
			steps+= '<tr class="row-bg-color">';
		else
			steps+= '<tr>';
		
		if (i == 0)
			steps+= '<td><img src="' +  MapUIImagePath + 'DrivingDirection/dd_pinStart.gif"/></td>'
		else if (i == len-1)
			steps+= '<td><img src="' +  MapUIImagePath + 'DrivingDirection/dd_pinEnd.gif"/></td>'
		else
			steps+= '<td class="dd_step" align="center">&nbsp;&nbsp;&nbsp;' + eval(i-1) + '</td>'
		steps+= '<td class="dd_text">' + route.Itinerary.Segments[i].Instruction + '</td>';                  
		steps+= '<td class="dd_text">';
		if (route.Itinerary.Segments[i].Distance != null)
			steps+= route.Itinerary.Segments[i].Distance + ' ' + route.Itinerary.DistanceUnit;                  
		steps+= '</td></tr>';
	}            
	routeinfo+= steps;            
	routeinfo+= '<tr class="BGColor2"><td colspan="3" class="dd_header">';
	routeinfo+= 'Total Distance: ' + route.Itinerary.Distance + ' ' + route.Itinerary.DistanceUnit;            
	routeinfo+= '&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Total Estimated Time: ' + route.Itinerary.Time + '</td></tr>';    
	steps+= '</table>';
	document.getElementById("routeSummary").style.display = "block";
	document.getElementById("routeDirection").innerHTML = routeinfo;         
	document.getElementById("routeFrom").innerHTML = route.StartLocation.Address;
	document.getElementById("routeTo").innerHTML = route.EndLocation.Address;
	
	window.frmDrivingDirections.taDDFrom.value = route.StartLocation.Address;
	window.frmDrivingDirections.taDDTo.value = route.EndLocation.Address;
} 
function clear_dd()
{
	if (map)
	{
		document.forms["frmDrivingDirections"].taDDFrom.value = '';
		map.DeleteRoute();
		document.getElementById("routeSummary").style.display = "none";
	}
}

function print_dd()
{
	if (map)
	{
	    try
	    {	  
	        A_SLIDERS[0].S0OA.style.visibility='hidden';
		    window.print();
		    A_SLIDERS[0].S0OA.style.visibility='visible';
	    }
	    catch(error)
	    {      
	        window.print();		    
		 }
		
	}
}
function email_dd(listing)
{
	if (map)
	{
		if (document.getElementById("routeSummary").style.display == "none")
			alert("There are no directions to Email.");
		else
			popup("EmailDirections.aspx?Listing="+ listing, "EmailDD", "height=250,width=500,scrollbars=no,menubar=no,toolbar=no,resizable=yes");
	}
}
//Listing Count
function doListingCount(useCache)
{
	//alert(useCache);
	setLatLongFormFields();   
	getListingCount(useCache);
}

//Birds Eye
function isBirdseyeAvailable()
{
    if (map.IsBirdseyeAvailable())
        return true;
    else
        return false;
}
function toggleBirdsEye(setStyleToBE)
{
	var be_tab = document.getElementById("tab_birdseye");
       
	if (map.IsBirdseyeAvailable())
	{
	    //alert('YES');
	    if (be_tab)
        {
		    be_tab.style.display = "block";
			
			    
		    if (setStyleToBE == '1')
		    {
		        setMapStyle('b');
		        document.getElementById("rbBE").checked = true;    
		    }
		 }
		 
		  if (document.ListingSearch && document.ListingSearch.val_IsBirdsEyeAvailable)
		    document.ListingSearch.val_IsBirdsEyeAvailable.value = 1;
	}
	else
	{
	    //alert('NO');
	    if (be_tab)
		    be_tab.style.display = "none";	
		if (document.ListingSearch && document.ListingSearch.val_IsBirdsEyeAvailable)
		    document.ListingSearch.val_IsBirdsEyeAvailable.value = 0;
	}
}
function setBirdsEyeSceneHtml()
{
	document.getElementById("birdsEyeView").innerHTML = getBirdsEyeSceneHtml();
	//selectBEZoomLevel(map.GetZoomLevel());
}
function getBirdsEyeSceneHtml()
{
    var scene = map.vemapcontrol.GetObliqueScene();
    var sceneID = scene.GetID();
    var neighbors = map.vemapcontrol.GetObliqueScene().neighborScenes;
    var sceneOrientation = scene.GetOrientation();
    var thumbnailImagePath = 'http://thumbs.oblique.tiles.virtualearth.net/tiles/ot';

    
    var northScene = neighbors['North'];
    var northEastScene = neighbors['Northeast'];
    var eastScene = neighbors['East'];
    var southEastScene = neighbors['Southeast'];
    var southScene = neighbors['South'];
    var southWestScene = neighbors['Southwest'];
    var westScene = neighbors['West'];
    var northWestScene = neighbors['Northwest'];
    
    var topScene = northScene;
    var topRightScene = northEastScene;
    var rightScene = eastScene;
    var bottomRightScene = southEastScene;
    var bottomScene = southScene;
    var bottomLeftScene = southWestScene;
    var leftScene = westScene;
    var topLeftScene = northWestScene;
    
    var html = '';
    var northOrientationLink = '<a href="#" onclick="map.SetBirdseyeOrientation(VEOrientation.North); return false" title="Turn to the north">N</a>';
    var eastOrientationLink = '<a href="#" onclick="map.SetBirdseyeOrientation(VEOrientation.East); return false" title="Turn to the east">E</a>';
    var southOrientationLink = '<a href="#" onclick="map.SetBirdseyeOrientation(VEOrientation.South); return false" title="Turn to the south">S</a>';
    var westOrientationLink = '<a href="#" onclick="map.SetBirdseyeOrientation(VEOrientation.West); return false" title="Turn to the west">W</a>';
    
    var topOrientationLink = northOrientationLink;
    var rightOrientationLink = eastOrientationLink;
    var bottomOrientationLink = southOrientationLink;
    var leftOrientationLink = westOrientationLink;
    
    if(sceneID != null)
    {        
        if(sceneOrientation == VEOrientation.East)
        {
            topScene = eastScene;
            topRightScene = southEastScene;
            rightScene = southScene;
            bottomRightScene = southWestScene;
            bottomScene = westScene;
            bottomLeftScene = northWestScene;
            leftScene = northScene;
            topLeftScene = northEastScene;
            
            topOrientationLink = eastOrientationLink;
            rightOrientationLink = southOrientationLink;
            bottomOrientationLink = westOrientationLink;
            leftOrientationLink = northOrientationLink;
        }
        else if(sceneOrientation == VEOrientation.South)
        {
            topScene = southScene;
            topRightScene = southWestScene;
            rightScene = westScene;
            bottomRightScene = northWestScene;
            bottomScene = northScene;
            bottomLeftScene = northEastScene;
            leftScene = eastScene;
            topLeftScene = southEastScene;
            
            topOrientationLink = southOrientationLink;
            rightOrientationLink = westOrientationLink;
            bottomOrientationLink = northOrientationLink;
            leftOrientationLink = eastOrientationLink;
        }
        else if(sceneOrientation == VEOrientation.West)
        {
            topScene = westScene;
            topRightScene = northWestScene;
            rightScene = northScene;
            bottomRightScene = northEastScene;
            bottomScene = eastScene;
            bottomLeftScene = southEastScene;
            leftScene = southScene;
            topLeftScene = southWestScene;
            
            topOrientationLink = westOrientationLink;
            rightOrientationLink = northOrientationLink;
            bottomOrientationLink = eastOrientationLink;
            leftOrientationLink = southOrientationLink;
        }
        
        html += '<table id="beControl">';
        html += '<tr><td><table cellpadding="0" cellspacing="0" border="0" id="beCompass">';
        html += '<tr><td colspan="3" class="be_orientation" align="center">' + topOrientationLink + '</td></tr>';
        html += '<tr><td class="be_orientation">' + leftOrientationLink + '</td>';
        html += '<td><img src="' + MapUIImagePath + 'MapControl/be_compass.gif"/></td>';
        html += '<td class="be_orientation">' + rightOrientationLink + '</td></tr>';
        html += '<tr><td colspan="3" class="be_orientation" align="center">' + bottomOrientationLink + '</td></tr></table>';
    }
  
    return html;
    
}
function setBirdseyeScene(scene)
{
	map.SetBirdseyeScene(scene)
	//selectBEZoomLevel(map.GetZoomLevel());
}
function setBirdsEyeZoom(zoom)
{
	map.SetZoomLevel(zoom);
	//selectBEZoomLevel(zoom);
}
function selectBEZoomLevel(zoom)
{
	if (zoom == 2)
	{
		document.getElementById("be_ZoomIn").className='Selected';
		document.getElementById("be_ZoomOut").className='';
	}
	else
	{
		document.getElementById("be_ZoomIn").className='';
		document.getElementById("be_ZoomOut").className='Selected';
	}
}

function deleteListingOfficePins(type)
{
    var ids = [];
    var delCnt = 0;
    
    if (map == undefined)
        return;
    
    try
    {    
        for(var i = 0; i < map.pushpins.length; i++) {
            if (map.pushpins[i].ID.search(type) > -1) {
                ids[delCnt] = map.pushpins[i].ID;
                delCnt++;
            }
        }

        for (var i = 0; i < delCnt; i++) {
            deletePushpin(ids[i]);
        }
    }  
    catch(e) {}
}

//POI
var xmlhttp;
var docLoading = false;
var url;
var isLocked = false;

var selected = 1;
var unselected = 0;
var disabled = -1;

var lockTimerID = null;
var waitTimerID = null;
var eventTimerID = null;
var WAIT_TIMER_MS = 1000; // Time to wait before we request data for an area
var LOCK_TIMER_MS = 250; // Time to wait with processing message displaying
var EVENT_TIMER_MS = 1000;

function clearLockTimer()
{
    setLockLayer('hidden');
}

function clearWaitTimer()
{
    clearTimeout(waitTimerID);
    updatePOI();
}

function displayPOI()
{
    togglePOILinks();
    
    if (isZoomedIn())
    {
        displayInformationBubble('poiMessageDisplay', null);
    }
    clearTimeout(waitTimerID);
    waitTimerID = self.setTimeout('clearWaitTimer()', WAIT_TIMER_MS);
}

function togglePOILinks()
{
    if (window.poiIcons == undefined)
        return;
        
    var links = document.getElementById('poi_links');
    
    if (isZoomedIn() && links != null)
    {
        links.style.visibility = 'visible';
    }
    else
    {
        links.style.visibility = 'hidden';
    }
}

// Alleviate rapid clicks on different icons
function toggleEventDelay(status)
{
    for(var i=0; i<poiIcons.length; i++)
    {
        // Using opposite value because of toggle functionality
        var curStatus = getIconStatus(i);

        if ((status == selected && curStatus == unselected) ||
           (status == unselected && curStatus == selected))
        {
            togglePOICategory(i);
        }
    }
   setLockLayer('hidden');
   isLocked = false;
}

function updatePOI()
{
    if (window.poiIcons == undefined)
        return;
    
    if (isZoomedIn())
    {
        if (isInCachedArea())
        {
            for(var i=0; i<poiIcons.length; i++)
            {
               var status = getIconStatus(i);
               var value = getCategoryValue(i);
               var isAlreadyVisible = poiIcons[i][3];
               var evalText = '';
               var categoryCount = getCategoryCount(i)
               
               if (status == disabled)
               {    
                    setCategoryIconStatus(i, unselected);
               }
               
               if (value == selected && !isAlreadyVisible)
               {
                    poiIcons[i][3] = true;
                    setCategoryIconStatus(i, selected);
                    evalText = 'poi' + i;
                    addPushPinArrayToMap(eval(evalText));
               }
           }
        }
        else // not in cached area
        {
            var evalText = '';
            for(var i=0; i<poiIcons.length; i++)
            {
                if (poiIcons[i][3])
                {
                    poiIcons[i][3] = false;
                    evalText = 'poi' + i;
                   
                    removePushPinArrayFromMap(eval(evalText), i + '_');
                }
                evalText = 'poi' + i  + ' = new Array();'
                eval(evalText);
            }
            getPOIData();
        }
    }
    else // zoomed Out
    {
        hidePOIIcons();
    }
}

function hidePOIIcons()
{
    if (window.poiIcons == undefined)
        return;
        
    for(var i=0; i<poiIcons.length; i++)
    {
        var status = getIconStatus(i);
        var evalText = '';
        poiIcons[i][3] = false;

        if (status != disabled)
        {
            setCategoryIconStatus(i, disabled);
            evalText = 'poi' + i;
            removePushPinArrayFromMap(eval(evalText), i + '_');
        }
    }
}

function setLockLayer(status)
{
    document.getElementById('tblLockLayer').style.width  = document.getElementById('mapDiv').offsetWidth;
    document.getElementById('tblLockLayer').style.height = document.getElementById('mapDiv').offsetHeight;
    if (status == 'visible')
    {
        document.getElementById('customMapControl').style.zIndex = document.getElementById('mapDiv').style.zIndex - 1;
    }
    else
    {
       document.getElementById('customMapControl').style.zIndex = document.getElementById('mapDiv').style.zIndex + 1;
    }
    document.getElementById('lockLayer').style.visibility = status;  
}

function getPOIData()
{
    // Perform Ajax call and set timed event to add pushpins
    // when response is processed
    var neLat = document.ListingSearch.SearchMapNELat.value;
    var neLong = document.ListingSearch.SearchMapNELong.value;
    var swLat = document.ListingSearch.SearchMapSWLat.value;
    var swLong = document.ListingSearch.SearchMapSWLong.value;
    var midLat = parseFloat(neLat) + parseFloat(swLat);
    var midLong = parseFloat(neLong) + parseFloat(swLong);

    url = (document.location.href.toUpperCase().search('BROKEROFFICE.ADMIN') > -1) ? '/BrokerOffice.Admin' : '/Public';
    url += '/GetSearchMap.aspx?neLat=' + neLat + '&neLong=' + neLong + '&swLat=' + swLat + '&swLong=' + swLong;
    loadXMLDoc(url, processAjaxResponse);
    setLockLayer('visible');
}

function getIconStatus(id)
{
   // var string = document.getElementById('poi_' + poiIcons[id][1] + ').src;
    
    if (document.getElementById('poi_' + poiIcons[id][1] + '_dis').style.display == 'block')
        return disabled;
    if (document.getElementById('poi_' + poiIcons[id][1] + '_unsel').style.display == 'block')
        return unselected;
    if (document.getElementById('poi_' + poiIcons[id][1] + '_sel').style.display == 'block')
        return selected;
    
    return iconStatus;
}

function getCategoryValue(id)
{
    var value = -1;
    value = document.getElementById('poi_' + poiIcons[id][1] + '_sel').value;
    return value;
}

function setCategoryIconStatus(id, status)
{
    if (status == selected)
    {
        document.getElementById('poi_' + poiIcons[id][1] + '_sel').style.display = 'block';
        document.getElementById('poi_' + poiIcons[id][1] + '_unsel').style.display = 'none';
        document.getElementById('poi_' + poiIcons[id][1] + '_dis').style.display = 'none';
    }
    if (status == unselected)
    {
        document.getElementById('poi_' + poiIcons[id][1] + '_sel').style.display = 'none';
        document.getElementById('poi_' + poiIcons[id][1] + '_unsel').style.display = 'block';
        document.getElementById('poi_' + poiIcons[id][1] + '_dis').style.display = 'none';
    }
    if (status == disabled)
    {
        document.getElementById('poi_' + poiIcons[id][1] + '_sel').style.display = 'none';
        document.getElementById('poi_' + poiIcons[id][1] + '_unsel').style.display = 'none';
        document.getElementById('poi_' + poiIcons[id][1] + '_dis').style.display = 'block';
    }
    
 
    
}

function setCategoryValue(id, value)
{
    document.getElementById('poi_' + poiIcons[id][1] + '_sel').value = value;
}


function toggleAllPOICategories(status)
{
    if (docLoading || isLocked)
        return;
        
    if (isZoomedIn())
    {
        isLocked = true;
        setLockLayer('visible');
        self.setTimeout('toggleEventDelay(' + status + ')', EVENT_TIMER_MS);
    }
    else
    {
        if (map.GetMapStyle() == VEMapStyle.Birdseye)
            displayInformationBubble('poiMessageDisplay', 'Points of Interest are not available on Birds Eye View maps.');
        else
            displayInformationBubble('poiMessageDisplay', 'Please zoom in to see Points of Interest.');
    }
}

function togglePOICategory(id)
{
    var evalText = 'poi' + id;
    var categoryCount = getCategoryCount(id);

    if (isZoomedIn())
    {
        if (docLoading)
            return;
            
        var status = getIconStatus(id);
        
        if (status == selected)
        {
            poiIcons[id][3] = false;
            removePushPinArrayFromMap(eval(evalText), id + '_');
            setCategoryIconStatus(id, unselected);
            setCategoryValue(id, unselected);
        }
        else 
        {
            poiIcons[id][3] = true;
            addPushPinArrayToMap(eval(evalText));
            setCategoryIconStatus(id, selected);
            setCategoryValue(id, selected);
            displayInformationBubble('poiMessageDisplay', null);
        }
    }
    else
    {
        if (map.GetMapStyle() == VEMapStyle.Birdseye)
            displayInformationBubble('poiMessageDisplay', 'Points of Interest are not available on Birds Eye View maps.');
        else
            displayInformationBubble('poiMessageDisplay', 'Please zoom in to see Points of Interest.');
    }
}

function getCategoryCount(id)
{
    var evalText = 'poi' + id + '.length';
    return eval(evalText);
}

function checkForPushPinCollision(curItem)
{
   if (curItem == undefined)
       return '';
       
   for(var i = 0; i < map.pushpins.length; i++)
   {
        // If lat and long are identical, we have a collision
        if (curItem[1] == map.pushpins[i].LatLong.Latitude && 
            curItem[2] == map.pushpins[i].LatLong.Longitude)  
        {
            return map.pushpins[i].ID;
        }
   }
   
   return '';
}

function getCollisionHtml(pinIDs)
{
    if (pinIDs == undefined)
        return;
        
    var html = '';
    var pinIDArray = pinIDs.split(",");
    var arrayAndIndex;
    var evalText = '';
    
    for (var i = 0; i < pinIDArray.length; i++)
    {
        arrayAndIndex = pinIDArray[i].split("_");
        
        html += '<table width=100% valign=top cellspacing=1 cellpadding=1 class=vepp ';
        if (i > 0)
            html += 'style="display:none;"';
        html += ' id=pin_' + i + '>';
        html += getToggleBubbleHtml(pinIDArray.length, i, 'Points of Interest');
        // poiX[Y][5]
        evalText = 'poi' + arrayAndIndex[0] + '[' + (arrayAndIndex[1]) + '][5];'
        // dynamically call the array containing the appropriate html
        html += '<tr><td>' + eval(evalText) + '</tr></td>';
        html += '</table>';
    }

    return html;
}

function getToggleBubbleHtml(count, curPosition, displayName)
{
    var html = '';
    
    html += '<tr><td valign=top><table cellspacing=0 cellpadding=0 border=0 class=vepp_text3 width=100%>';
    html += '<tr><td colspan=3>Multiple ' + displayName + ' found here</td></tr>';
    html += '<tr><td align=left width=30%>';
    if (curPosition > 0)
        html += '<a href="javascript:togglePinBubble(' + (curPosition - 1) + ',' + curPosition +')"/>< Prev</a>';
    html += '</td><td align=center width=40%>';
    html += '<b>' + (curPosition + 1) + ' of ' + count + '</b>';
    html += '</td><td align=right width=30%>';
    if (curPosition < count -1)
        html += '<a href="javascript:togglePinBubble(' + (curPosition + 1) + ',' + curPosition + ')"/>Next ></a>';
    html += '</td></tr></table></td></tr>';
    
    return html;
}

function addPushPinArrayToMap(curArray)
{
    if (curArray == undefined || curArray == '')
        return;
   
    var html = '';
    var pinIDs = '';
    var pinID = '';
    
    for(var i = 0; i < curArray.length; i++)
    {
        addPushPinItemToMap(curArray[i]);
    }
}

function addPushPinItemToMap(curItem)
{
    if (curItem == undefined || curItem == '')
        return;
        
    var html = '';
    var pinIDs = '';
    var pinID = '';
    
    pinID = checkForPushPinCollision(curItem);
    
    // Listing and office pins have precendence. Do not overwrite
    if (pinID.search('listing') > 0 || pinID.search('office') > 0)
        return;
        
    if(pinID.length > 0)
    {
        // Remove previous pin(s) so we can add them back with additional pin info
        deletePushpin(pinID);
        pinIDs = pinID + ',' + curItem[0];
        html = getCollisionHtml(pinIDs);
        addMapPushpin(pinIDs, curItem[1], curItem[2], 22, 'Multiple Points of Interest', html);
    }
    else
    {
         addMapPushpin(curItem[0], curItem[1], curItem[2], curItem[3], curItem[4], curItem[5]);
    }
}

function removePushPinArrayFromMap(pins, categoryID)
{
    if (pins == undefined)
        return;

    // Delete those pins that we know exist and can find by ID
    try
    {
    for (var i = 0; i < pins.length; i++)
    {
        deletePushpin(pins[i][0]);
    }
 
    var collisionIDs = '';
    // Find collision IDs so we can check for
    // the category being removed
    for (var j = 0; j < map.pushpins.length; j++)
    {
        if (map.pushpins[j].ID.search(',') > -1)
        {
            if (collisionIDs.length > 0)
            collisionIDs += ":";
            collisionIDs += map.pushpins[j].ID;
        }
    }

    var arrayOfCollisionIDs = collisionIDs.split(':');
    // We need to loop through each collision ID value
    for (var k = 0; k < arrayOfCollisionIDs.length; k++)
    {
        var arrayOfPinIDsToCheck = arrayOfCollisionIDs[k].split(',');
        var pinIDsAfter = '';
        for (var l = 0; l < arrayOfPinIDsToCheck.length; l++)
        {
            if (arrayOfPinIDsToCheck[l].search(categoryID) == -1)
            {
                if (pinIDsAfter.length == 0)
                    pinIDsAfter += arrayOfPinIDsToCheck[l];
                else
                    pinIDsAfter += ',' + arrayOfPinIDsToCheck[l];
            }
        }       
        // If the collision pin has been altered, add back remaining pins
        if (arrayOfCollisionIDs[k] != pinIDsAfter)
        {
            deletePushpin(arrayOfCollisionIDs[k]);
            pinsToAddBack = pinIDsAfter.split(',');

            for (var m = 0; m < pinsToAddBack.length; m++)
            {
                addPushPinItemToMap(getArrayObjectFromID(pinsToAddBack[m]));
            }
        }
    }
    }
    catch(e) {}
}

// Takes ID and finds the necessary array 
// containing information such as pinID, html ...
function getArrayObjectFromID(ID)
{
    var evalText = '';
    var parts = ID.split('_');
    
    if (parts.length != 2)
        return null;
    evalText = 'poi' + parts[0] + '[' + parts[1] + ']';
    return eval(evalText);
}

function setPOIIcons()
{
    var onClickEvent = '';
    
    document.write("<table width='100%' cellspacing='4'>")
    for(var i=0; i<poiIcons.length; i++)
    {
        if (i % 2 == 0)
        {
            document.write("<tr>");
        }
        if (i % 2 == 0)
        {
            document.write("<td align='right'>");
        }
        else
        {
            document.write("<td align='left'>");
        }
        //onClickEvent = 'javascript:toggleEventDelay("togglePOICategory(' + i + ')")';
        onClickEvent = 'javascript:togglePOICategory(' + i + ')';
        document.write("<a href=\"javascript:;\"  onClick=" + onClickEvent + ";>");
		document.write("<img style=\"display:none\" border=\"0\" id=\"poi_" + poiIcons[i][1] + "_dis\" alt=\"" + poiIcons[i][2] + " (Please zoom in to enable the Points of Interest icons)\" src=\"" + MapUIImagePath + "POI/" + poiIcons[i][1] + "_dis.gif\"\>");
		document.write("<img style=\"display:none\" border=\"0\" id=\"poi_" + poiIcons[i][1] + "_sel\" alt=\"" + poiIcons[i][2] + "\" src=\"" + MapUIImagePath + "POI/" + poiIcons[i][1] + "_sel.gif\"\>");
		document.write("<img style=\"display:none\" border=\"0\" id=\"poi_" + poiIcons[i][1] + "_unsel\" alt=\"" + poiIcons[i][2] + "\" src=\"" + MapUIImagePath + "POI/" + poiIcons[i][1] + "_unsel.gif\"\>");
        document.write("</a></td>");
       // document.write("<input type=\"hidden\" name=\"POI/enbl_" + poiIcons[i][1] + "\" id=\"enbl_" + poiIcons[i][1] + "\" value=\"0\"/>");
        if (i % 2 != 0)
        {
            document.write("</tr>");
        }
       
        setCategoryValue(i, 0);
        setCategoryIconStatus(i, -1);
    }
    document.write("</table>");
}

function setPOICoordinates(neLat, neLong, swLat, swLong)
{
    cachedCoordinates[0] = neLat;
    cachedCoordinates[1] = neLong;
    cachedCoordinates[2] = swLat;
    cachedCoordinates[3] = swLong;
}


function displayInformationBubble(id, message)
{
    var layer = document.getElementById('messageBox');
    
    if (layer)
    {
        if (message == null)
        {
           document.getElementById(id).innerText = '';
           if (isZoomedIn() && document.getElementById('listingMessageDisplay').innerHTML == '')
           {
               layer.style.visibility = 'hidden';
           }
        }
        else
        {
            layer.style.visibility = 'visible';
            document.getElementById(id).innerText = message;
        }
    }
}

function loadXMLDoc(url, callback)
{
	// Only do this if the doc isn't already loading	
	if (!docLoading) 
	{
	    docLoading = true;
		// code for Mozilla, etc.
		if (window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
			xmlhttp.onreadystatechange = callback;
			xmlhttp.open("GET",url,true);
			xmlhttp.send(null);
		}
		// code for IE
		else if (window.ActiveXObject)
		{			
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
			if (xmlhttp)
			{		
				xmlhttp.onreadystatechange = callback;
				xmlhttp.open("GET",url,true);
				xmlhttp.send();
			}
		}
	}
}

function processAjaxResponse() 
{   
    if (xmlhttp.readyState == 4) 
    { 
        try
        {
            eval(xmlhttp.responseText);
        }
        catch(e)
        {
            // Sometimes the async calls get invalidated by an exception.
            // It is unclear what causes the exception. Iterim solution is 
            // to reinitalize.
            getPOIData();
            setLockLayer('hidden');
            return;
        }
        var neLat = document.ListingSearch.SearchMapNELat.value;
        var neLong = document.ListingSearch.SearchMapNELong.value;
        var swLat = document.ListingSearch.SearchMapSWLat.value;
        var swLong = document.ListingSearch.SearchMapSWLong.value;
                
        setPOICoordinates(neLat, neLong, swLat, swLong);
        lockTimerID = self.setTimeout('clearLockTimer()', LOCK_TIMER_MS);
        updatePOI();
        docLoading = false;
    }
}

function isInCachedArea()
{
    var neLat = document.ListingSearch.SearchMapNELat.value;
    var neLong = document.ListingSearch.SearchMapNELong.value;
    var swLat = document.ListingSearch.SearchMapSWLat.value;
    var swLong = document.ListingSearch.SearchMapSWLong.value;

    if (neLat <= parseFloat(cachedCoordinates[0]) && 
        neLat >= parseFloat(cachedCoordinates[2]) &&
        neLong <= parseFloat(cachedCoordinates[1]) &&
        neLong >= parseFloat(cachedCoordinates[3]) &&
        swLat <= parseFloat(cachedCoordinates[0]) && 
        swLat >= parseFloat(cachedCoordinates[2]) &&
        swLong <= parseFloat(cachedCoordinates[1]) &&
        swLong >= parseFloat(cachedCoordinates[3]))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function isZoomedIn()
{
    if (map && map.GetZoomLevel() >= 15)
        return true;
    else
        return false;
}

