﻿// JScript File

//mapping variables
var mapControl = null;

//used to temporarily hide the map bubbles on zoomin/zoomout operations
var tempHide = false;

//amount to pan map when clicking the compass
var panDelta = 200;

//zoom level to show neighborhood data on
var minZoomRequired = 10;

//current filter for neighborhood data
var currentFilter = "";

//var __sliderValueControl;
var sliderControl;

var neighborhoodSelectedArray;

var isAmenitySelected = false;
/*
var amenities = new Array();

amenities[0] = "Restaurants";
amenities[1] = "Bars";
amenities[2] = "CoffeeShops";
amenities[3] = "Schools";
amenities[4] = "GroceryStores";
amenities[5] = "DepartmentStores";
amenities[6] = "BookStores";
amenities[7] = "DrugStores";
amenities[8] = "WineLiquor";
amenities[9] = "MovieTheaters";
amenities[10] = "HealthClubs";
amenities[11] = "GolfCourses";
amenities[12] = "StadiumsConvention";
amenities[13] = "Recreation";
amenities[14] = "TouristAttractions";
amenities[15] = "Clinics";
amenities[16] = "Hospitals";
amenities[17] = "PostOffices";
amenities[18] = "PublicLibraries";
amenities[19] = "FireDepartments";
amenities[20] = "PoliceDepartments";
amenities[21] = "Courts";
amenities[22] = "Airports";
amenities[23] = "Banks";
amenities[24] = "Laundry";
amenities[25] = "PlacesOfWorship";
*/

document.write('<script language="javascript" src="./js/Types.js"></script>');
document.write('<script language="javascript" src="./js/AmenityBubbles.js"></script>');
document.write('<script language="javascript" src="./js/HomeBubbles.js"></script>');
document.write('<script language="javascript" src="./js/SchoolBubbles.js"></script>');
//document.write('<script language="javascript" src="./js/neighborhood.js"></script>');

//executed on first page load
function pageLoad()
{
    //try {
	    PopulateSelectedHomeID();
    	
	    LoadMyMap();
	
	    //initialize slider
        InitSlider();
        
        InitNeighborhoodCheckboxes();
        
        RefreshNeighborhoodData()
    //} 
    //catch (e) {
    //    alert("The following error occurred: " + e.name + " - " + e.message); 
    //} 
    //finally {
    //    alert ("Come back soon!");
    //}
}

function InitNeighborhoodCheckboxes()
{
    var onImgSrc = "img/map_checkbox_on.gif";
    var offImgSrc = "img/map_checkbox_off.gif";
    
    on = document.getElementById("Input.AmenitiesOn");
    off = document.getElementById("Input.AmenitiesOff");
    
    if (on != null)
    {
        resetImg(on.value, onImgSrc, "true");
    }

    if (off != null)
    {
        resetImg(off.value, offImgSrc, "false");
    }
}

function resetImg(elements, imgSrc, checkedState)
{
    array = elements.split(',');

    for(i=0; i<array.length; i++)
    {
        element = document.getElementById(array[i]);
        
        if (element && element.src)
        {
            //alert (array[i] + " > " + checkedState);
            element.src = imgSrc;
            element.setAttribute("checked", checkedState);
            
            if (checkedState) isAmenitySelected = true;
        }
    }
}

function SearchNeighborhood(innerHtml)
{
    array = innerHtml.getElementsByTagName('img');
    tmpImgSrc = "img/map_checkbox_on_tmp.gif";
    
    if (array)
    {
        img = array[0];
        if (img) 
        {
            img.src = tmpImgSrc;
            
            addFilter = (img.getAttribute("checked")=="false"); // true for add, else remove

            //alert (img.id + " >> " + addFilter);
            SetFilter(img.id, addFilter);
            UpdateNeighborhood();
        }
    }
}

//set the current neighborhood filter string
function SetFilter(filter, addFilter)
{
	var neighborhoodFilter = document.getElementById("Input.AmenitiesOn"); //FindHPControl("neighborhoodFilter");
    var filterElements = "";
    
    if (neighborhoodFilter)
	{
	    
        array = neighborhoodFilter.value.split(',');

        for(i=0; i<array.length; i++)
        {
            if (array[i] != filter)
            {
                filterElements += (filterElements!="")
                                    ? "," + array[i]
                                    : array[i];
            }
        }
        
        neighborhoodFilter.value = filterElements;

        if (addFilter)
        {
            neighborhoodFilter.value += (neighborhoodFilter.value != "")
                                    ? "," + filter
                                    : filter;
        }
        
        //alert ("FILTER: " + neighborhoodFilter.value);
    }
}

//populate the currently selected home based on the current dom's xml 
//and set it into selectedHomeID
function PopulateSelectedHomeID()
{	
	var selectedHomeList = document.getElementsByTagName("selectedhome");
	for(var i = 0 ; i < selectedHomeList.length; i++)
	{
		var selectedHomeElement = selectedHomeList[i];		
		selectedHomeID = selectedHomeElement.getAttribute("homepagesid");	
	}
}

//update the map view buttons (on/off) based on the current map view
function UpdateButtons()
{
    var style = mapControl.GetMapStyle();
    
	var streetViewBtn   = $get("mapStreetView");
	var satViewBtn      = $get("mapSatelliteView");
	var birdseyeViewBtn = $get("mapBirdsEyeView");
	var mapMover        = $get("mapMoverDiv");
	var mapRotator      = $get("mapRotatorDiv");
	
	if (!streetViewBtn 
	    || !satViewBtn
	    || !birdseyeViewBtn )
	{
	    return;
	}
	
    var streetImgOn     = "img/map_button_street_on.gif";
    var streetImgOff    = "img/map_button_street_off.gif";
    var satImgOn        = "img/map_button_satellite_on.gif";
    var satImgOff       = "img/map_button_satellite_off.gif";
    var birdseyeImgOn   = "img/map_button_birdseye_on.gif";
    var birdseyeImgOff  = "img/map_button_birdseye_off.gif";

	switch (style)
	{
        case VEMapStyle.Road:
    		streetViewBtn.src = streetImgOn;
	        satViewBtn.src = satImgOff;
	        birdseyeViewBtn.src = birdseyeImgOff;
	        mapMover.style.display = "block";
	        mapRotator.style.display = "none";
	        break;
	        
        case VEMapStyle.Birdseye:
    		if (mapControl.IsBirdseyeAvailable()){
    		    streetViewBtn.src = streetImgOff;
	            satViewBtn.src = satImgOff;
	            birdseyeViewBtn.src = birdseyeImgOn;
	            mapMover.style.display = "none";
	            mapRotator.style.display = "block";
	        }
	        break;

        //case VEMapStyle.Aerial:
        case VEMapStyle.Hybrid:
    		streetViewBtn.src = streetImgOff;
	        satViewBtn.src = satImgOn;
	        birdseyeViewBtn.src = birdseyeImgOff;
	        mapMover.style.display = "block";
	        mapRotator.style.display = "none";
	        break;
	}

	//alert (mapControl.IsBirdseyeAvailable());
	if (mapControl.IsBirdseyeAvailable())
	{
	    birdseyeViewBtn.style.visibility="visible";
	}
	else 
	{
	    birdseyeViewBtn.style.visibility="hidden";
	}
}

//Loads map into the div element "mapControlDiv" 
//and initializes its pushpins based on xml elements from the document
function LoadMyMap()
{
	var mapControlDiv = document.getElementById('mapControlDiv');

	if(mapControlDiv != null)
	{
		//check to see if we have a valid map control
		if(mapControl == null)
		{	
			mapControl = new VEMap('mapControlDiv');
			mapControl.LoadMap();
			
			//set map to hybrid view
			//mapControl.SetMapStyle('h');     
			SetMapStyle(VEMapStyle.Hybrid);
			
			mapControl.HideDashboard();
			
			//update buttons
			//UpdateButtons();
			
			//load homes from page
			LoadHomes();
			
			//draw homes on map
			DrawHomes();
			
			//add address center point if available
	        AddAddressCenterPoint();
			
			//set map bubble
			RefreshHomeBubble();
			
			//set events for map control
			mapControl.AttachEvent("onchangeview", RefreshMapView);
			mapControl.AttachEvent("onchangemapstyle", RefreshMapView);
			mapControl.AttachEvent("onobliquechange", RefreshMapView);

			mapControl.AttachEvent("onresize", RefreshMapView);
			mapControl.AttachEvent("onendzoom", EndZoom);			
			mapControl.AttachEvent("onstartzoom", StartZoom);
			
			//update buttons
			//UpdateButtons();

	        window.setTimeout("SetSliderValue(" + mapControl.GetZoomLevel() + ");", 2000);
		}
	}
}

function AddAddressCenterPoint()
{
    try
    {
        if (null != addressLocation)
        {
            if ((null != addressLocationLat) && (null != addressLocationLong))
            {
                var latlon = new VELatLong(addressLocationLat, addressLocationLong);
            
                var pin;
        	
                pin = new VEPushpin('centerpoint', latlon, 'img/marker.png', null, null, null);

                mapControl.AddPushpin(pin);
                //resultPushPins.push(pin);
            }
        }
    }
    catch(e)
    {
        return 1;
    }
}

//refresh all bubbles
function RefreshAllBubbles()
{	
	//refresh bubbles
	RefreshHomeBubble();	
	RefreshAmenityBubble();
	RefreshSchoolBubble();
}

//refresh map view
function RefreshMapView(arg)
{
	//UpdateButtons();
	
	RefreshAllBubbles();
	
	//reset apply button in we are within zoom limit and not birdseye
	if(mapControl != null 
		&& ((mapControl.GetZoomLevel() >= minZoomRequired 
		    && mapControl.GetMapStyle() != VEMapStyle.Birdseye)
		    || mapControl.GetMapStyle() == VEMapStyle.Birdseye))
	{
		// Commented by MM
		UpdateNeighborhood(); 
	}
}

function StartZoom(arg)
{
	TempHideDetails(arg);
}

function EndZoom(arg)
{
    tempHide = false;
    
    SetSliderValue(mapControl.GetZoomLevel())
}

//hide detail view temporarily while changing the map
function TempHideDetails(arg)
{
	tempHide = true;
	
	HideAll();
}

function HideAll()
{	
	if(homeBubble != null)
	{	
		homeBubble.style.display = "none";
	}
	if(amenityBubble != null)
	{	
		amenityBubble.style.display = "none";
	}
	if(schoolBubble != null)
	{	
		schoolBubble.style.display = "none";
	}
}

///////////////////////
// Map Nav Controls
///////////////////////

//pan map north
function moveMapUp()
{
	if(mapControl != null)
	{
		mapControl.Pan(0, -panDelta);
		RefreshMapView();
	}
}

//pan map south
function moveMapDown()
{
	if(mapControl != null)
	{
		mapControl.Pan(0, panDelta);
		RefreshMapView();
	}
}

//pan map west
function moveMapLeft()
{
	if(mapControl != null)
	{
		mapControl.Pan(-panDelta, 0);
		RefreshMapView();
	}
}

//pan map east
function moveMapRight()
{
	if(mapControl != null)
	{
		mapControl.Pan(panDelta, 0);
		RefreshMapView();
	}
}

///////////////////////
//Map Rotate Controls
///////////////////////
//rotate map
var origSrc;
function mapRotateSwap(direction)
{
    var img = document.getElementById("mapRotatorImgSelected");
    var imgName
    var urlArray = new Array();
    urlArray = origSrc.split('/');
    imgName = urlArray[urlArray.length - 1];

    if (imgName == 'compass-north.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-east.gif';
	        rotateEast();
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-south.gif';
	        rotateSouth();
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-west.gif';
	        rotateWest();
	    }
	}
	if (imgName == 'compass-east.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-south.gif';
	        rotateSouth();
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-west.gif';
	        rotateWest();
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-north.gif';
	        rotateNorth();
	    }
	}
	if (imgName == 'compass-south.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-west.gif';
	        rotateWest();
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-north.gif';
	        rotateNorth();
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-east.gif';
	        rotateEast();
	    }
	}
	if (imgName == 'compass-west.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-north.gif';
	        rotateNorth();
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-east.gif';
	        rotateEast();
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-south.gif';
	        rotateSouth();
	    }
	}
	
	origSrc = img.src;

}

function mapRotateImgSwap(direction)
{
    var img = document.getElementById("mapRotatorImgSelected");
    var imgName
    origSrc = img.src;
    
    var urlArray = new Array();
    urlArray = origSrc.split('/');
    imgName = urlArray[urlArray.length - 1];

    if (imgName == 'compass-north.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-north-east.gif';
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-north-south.gif';
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-north-west.gif';
	    }
	}
	if (imgName == 'compass-east.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-east-south.gif';
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-east-west.gif';
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-east-north.gif';
	    }
	}
	if (imgName == 'compass-south.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-south-west.gif';
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-south-north.gif';
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-south-east.gif';
	    }
	}
    if (imgName == 'compass-west.gif') {
        if ('east' == direction) {
	        img.src = '/img/compass-west-north.gif';
	    }
	    if ('south' == direction) {
	        img.src = '/img/compass-west-east.gif';
	    }
	    if ('west' == direction) {
	        img.src = '/img/compass-west-south.gif';
	    }
	}
}

function mapRotateImgReplace()
{
    var img = document.getElementById("mapRotatorImgSelected");
    img.src = origSrc;
}

//rotate map north
function rotateNorth()
{
	if(mapControl != null)
	{
		mapControl.SetBirdseyeOrientation(VEOrientation.North);
		RefreshMapView();
	}
}

//rotate map south
function rotateSouth()
{
	if(mapControl != null)
	{
		mapControl.SetBirdseyeOrientation(VEOrientation.South);
		RefreshMapView();
	}
}

//rotate map west
function rotateWest()
{
	if(mapControl != null)
	{
		mapControl.SetBirdseyeOrientation(VEOrientation.West);
		RefreshMapView();
	}
}

//rotate map east
function rotateEast()
{
	if(mapControl != null)
	{
		mapControl.SetBirdseyeOrientation(VEOrientation.East);
		RefreshMapView();
	}
}
///////////////////////
//Slider Control
///////////////////////
function SetSliderValue(val)
{
    var ajaxSlider = $find('sliderBehavior');
    
    if (ajaxSlider 
        && mapControl
        && mapControl.GetMapStyle() != VEMapStyle.Birdseye) 
    {
    
        if (val >= ajaxSlider.get_Maximum())
        {
            val = ajaxSlider.get_Maximum();
        }

        ajaxSlider.set_Value(val);
        ajaxSlider._setHandleOffset(val, false);
    }
    
    UpdateButtons();
}

function InitSlider()
{
	sliderControl = $find('sliderBehavior');
	
    var ajaxSlider = $find('sliderBehavior');
    if (ajaxSlider) {
        ajaxSlider.add_valueChanged(zoomMap);
    }
}

function zoomMap(sender, e) 
{
    if (mapControl
        && mapControl.GetMapStyle() != VEMapStyle.Birdseye) 
    {
        var minSliderValue = 1;
        var maxSliderValue = 17;
        var currentZoom = mapControl.GetZoomLevel();
        var sliderValue = sliderControl.get_Value();
        
        if (sliderValue == maxSliderValue)
        {
            sliderValue = ++currentZoom;
        }
        
        if (sliderValue == minSliderValue)
        {
            sliderValue = --currentZoom;
        }
        
        if (sliderValue != sliderControl.get_Value())
        {
            SetSliderValue(sliderValue);
        }
        
        if (sliderValue != currentZoom)
        {
            mapControl.SetZoomLevel(sliderValue);
        }
    }
}

function SetMapStyle(style)
{
    var currentStyle = mapControl.GetMapStyle();

    if (currentStyle == style) return;
    
    mapControl.SetMapStyle(style);
    
    UpdateButtons();

	mapControl.HideDashboard();
}

//change map view to type defined by argument (show be of type VEMapStyle)
function changeMapView(type)
{
	if(mapControl != null)
	{
		//mapControl.SetMapStyle(type);
		SetMapStyle(type);
		
		RefreshAllBubbles();	
	}
}

//open home detail page for a given id
/*
function ViewHomeDetails(hpID, resultNumber)
{
	var hpidField = FindHPControl('hpid');
	var resulNumberField = FindHPControl('resultnumber');
	hpidField.value = hpID;
	resulNumberField.value = resultNumber;
	
	var viewDetailsSubmitButton = FindHPControl('viewDetailsSubmit');
	viewDetailsSubmitButton.click();
}

function ViewHomeDetails(hpID)
{
	var inputButtons = document.getElementsByTagName("input");
	
	for(var i = 0; i < inputButtons.length; i++)
	{
		var inputHPID = inputButtons[i].getAttribute("hpid");
		
		if(hpID == inputHPID)
		{
			inputButtons[i].click();
			return;
		}
	}
}
*/

//buffers the map from a selected location to a buffer width and buffer height
//used in order to allow room for a map bubble to be displayed
function BufferView(selectedLatLong, bufferWidth, bufferHeight, mapWidth)
{
	if(mapControl != null)
	{
		var latlon = new VELatLong(selectedLatLong.getLatitude(), selectedLatLong.getLongitude());
		
		var currentLocationPoint = mapControl.LatLongToPixel(latlon);
		var newX = currentLocationPoint.x + bufferWidth;
		var newY = currentLocationPoint.y - bufferHeight;
				
		var deltaX = null;
		var deltaY = null;
		if(newX > mapWidth)
		{
			deltaX = newX - mapWidth;
		}
		if(newY < 0)
		{
			deltaY = newY;
		}
		
		if(deltaX != null || deltaY != null)
		{
			if(deltaX == null)
			{
				deltaX = 0
			}
			else
			{
				deltaX = deltaX+10;
			}
			
			if(deltaY == null)
			{
				deltaY = 0
			}
			else
			{
				deltaY = deltaY-10;
			}			
			
			var centerLatLonPixel = mapControl.LatLongToPixel(mapControl.GetCenter());
			newX = centerLatLonPixel.x+deltaX;
			newY = centerLatLonPixel.y+deltaY;
			
			var newLatLon = mapControl.PixelToLatLong(newX, newY);
			mapControl.PanToLatLong(newLatLon);
		}
	}
}

//refresh Neighborhood Data
function RefreshNeighborhoodData()
{
	RefreshAmenityData();
	RefreshSchoolData();
}

//Update the neighborhood data on map
function UpdateNeighborhood()
{
	if(mapControl != null 
		//&& mapControl.GetZoomLevel() >= minZoomRequired 
		//&& mapControl.GetMapStyle() != VEMapStyle.Birdseye
		)
	{	
		var mapView = mapControl.GetMapView();
		var mapCenter = mapControl.GetCenter();
				
		//initialize controls
		var neighborhoodFilter = document.getElementById("Input.AmenitiesOn"); //FindHPControl("neighborhoodFilter");
		var centerLat = FindHPControl("centerLat");
		var centerLon = FindHPControl("centerLon");
		
		var leftEdge = FindHPControl("leftEdge");
		var topEdge = FindHPControl("topEdge");
		var bottomEdge = FindHPControl("bottomEdge");
		var rightEdge = FindHPControl("rightEdge");
				
		//set values
		centerLat.value = mapCenter.Latitude; 
		centerLon.value = mapCenter.Longitude;
		leftEdge.value = mapView.TopLeftLatLong.Longitude;
		topEdge.value = mapView.TopLeftLatLong.Latitude;
		bottomEdge.value = mapView.BottomRightLatLong.Latitude;
		rightEdge.value = mapView.BottomRightLatLong.Longitude;
		
		//submit form
		var neighborhoodSubmit = FindHPControl("neighborhoodSubmit");
		
		if (neighborhoodFilter 
		    && (neighborhoodFilter.value.trim() != "" 
		        || isAmenitySelected))
		{
		    //alert ("Posting UpdateNeighborhood [" + neighborhoodFilter + "] '" + neighborhoodFilter.value + "'");
		    var prm = Sys.WebForms.PageRequestManager.getInstance();
		    if (prm.get_isInAsyncPostBack())
		    {
		        prm.abortPostBack();
		    }
		    
		    __doPostBack(neighborhoodSubmit.name, '');
		}
		
	}
}

//Find the HP Control on the page
function FindHPControl(hpcontrolID)
{
	var inputElements = document.getElementsByTagName("input");
	for(var i = 0 ; i < inputElements.length; i++)
	{
		var inputElement = inputElements[i];
		if(inputElement.getAttribute("hpcontrol") == hpcontrolID)
		{
			return inputElements[i];
		}
	}
	
	return null;
}


