﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />
/// <reference path="jquery.accordian.js" />
/// <reference path="VeJavaScriptIntellisenseHelper.js" />

function MapContext(name) {
    this.Name = name;
    this.IsIndoor = false;
    this.IndoorMapImageUrl = null;
    this.Layers = {};
    this.IsActive = false;
    this.VirtualEarthMap = null;
    this.SelectedFaceId = null;

    MapContext.prototype.Display = function() {
        if (!this.IsIndoor) {
            //Handle Virtual Earth Logic
            if (this.VirtualEarthMap != null) {
                for (var key in this.Layers) {
                    var layer = this.Layers[key];
                    if (layer != null && layer.Show != undefined) {
                        layer.Show();
                    }
                }
                var shapeCount = GetShapeCount();
                if (shapeCount > 0) {
                    vemap.SetMapView(GetOptimalViewForAllLayers());
                }
                DisplayShapeCount();
            }
            if (this.SelectedFaceId != null) {
                ShowFaceDetail(this.SelectedFaceId);
            }
            else {
                HideFaceDetail();
            }

            ShowOutdoorMap();
        }
        else {
            //Handle InDoor Logic
            //add back indoor shapes - Dead Code - should be removed at future date.
            var fn = function() {
                var activeMapContext = mapContextManager.GetActiveMapContext();
                for (var layerId in activeMapContext.Layers) {
                    var layer = activeMapContext.Layers[layerId];
                    for (var siteId in layer) {
                        var site = layer[siteId];
                        if (site.Latitude != null &&
                            site.Longitude != null) {
                            site.Marker = addIndoorMapMarker(site.Latitude, site.Longitude, site.Id, layerId, site.IconUrl);
                        }
                        else {
                            break;
                        }
                    }
                }
            }
            ShowIndoorMap(this.IndoorMapImageUrl);
            if (this.SelectedFaceId != null) {
                ShowFaceDetail(this.SelectedFaceId);
            }
            else {
                HideFaceDetail();
            }
        }
    }

    MapContext.prototype.Hide = function() {
        if (!this.IsIndoor) {
            //Handle Virtual Earth Logic
            if (this.VirtualEarthMap != null) {
                for (var key in this.Layers) {
                    var layer = this.Layers[key];
                    if (layer != null && layer.Hide != undefined) {
                        layer.Hide();
                    }
                }
                HideFaceDetail();
                DisplayShapeCount();
            }
        }
    }

    MapContext.prototype.Clear = function() {
        this.IsIndoor = false;
        this.Layers = {};
        this.IsActive = false;
        this.SelectedFaceId = null;
    }

    MapContext.prototype.RemoveLayers = function() {
        if (!this.IsIndoor) {
            if (this.VirtualEarthMap !== null) {
                for (var key in this.Layers) {
                    var layer = this.Layers[key];
                    if (layer != null && layer instanceof VEShapeLayer) {
                        this.VirtualEarthMap.DeleteShapeLayer(layer);
                        this.Layers[key] = null;
                        layer = null;
                    }
                }
                this.Layers = {};
                HideFaceDetail();
                DisplayShapeCount();
            }
        }
        else {
            $("#indoor-map #map-markers").empty();
            for (var key in this.Layers) {
                var layer = this.Layers[key];
                if (layer != null) {
                    this.Layers[key] = null;
                    layer = null;
                }
            }
            this.Layers = {};
            HideFaceDetail();
            DisplayShapeCount();
        }
    }

    MapContext.prototype.LoadGeocodedSearchResults = function(msg) {
        if (!this.IsIndoor) {
            if (this.VirtualEarthMap) {
                var layer = this.Layers["LiveSearchResults"];
                if (layer == undefined) {
                    var layer = new VEShapeLayer();
                    this.Layers["LiveSearchResults"] = layer;
                    this.VirtualEarthMap.AddShapeLayer(layer);
                }
                var shapeCount = layer.GetShapeCount();
                if (msg.d.Results != null) {
                    for (var i = 0; i < msg.d.Results.length; i++) {
                        var result = msg.d.Results[i];

                        //Add to map
                        var shapeLocation = new VELatLong(result.Locations[0].Latitude, result.Locations[0].Longitude, 0, VEAltitudeMode.RelativeToGround);
                        var shape = new VEShape(VEShapeType.Pushpin, shapeLocation);

                        var markerNumber = shapeCount + i + 1;

                        shape.IsLiveSearchResult = false;
                        shape.SetTitle(result.DisplayName);

                        var iconUrl = "Common/Images/Markers/Stock/RedCircle" + markerNumber + ".gif";
                        shape.SetCustomIcon(iconUrl);
                        layer.AddShape(shape);
                        $("#LiveSearchResults").append("<div id=\"LiveSearchResult-" + markerNumber + "\" class=\"LiveSearchResult\"><span class=\"LiveSearchResult-MarkerNumber\">" + markerNumber + "</span><span class=\"LiveSearchResult-BusinessName\">" + result.DisplayName + "<br /><br /></span></div>");
                        //wire up the livesearchresult in the control panel with a closure that will show the shape's InfoBox in the map.
                        $("#LiveSearchResults #LiveSearchResult-" + markerNumber).click(
                            function(map, shape) {
                                return function() {
                                    map.HideInfoBox();
                                    map.SetCenterAndZoom(shape.GetPoints()[0], 15);
                                    window.setTimeout(function() { map.ShowInfoBox(shape); }, 750);
                                    window.setTimeout(function() { map.ShowInfoBox(shape); }, 2000);
                                }
                            } (this.VirtualEarthMap, shape)
                        );
                    }
                }
                DisplayShapeCount();
            }
        }
    }

    MapContext.prototype.LoadLiveSearchResults = function(msg) {
        if (!this.IsIndoor) {
            if (this.VirtualEarthMap) {
                var layer = this.Layers["LiveSearchResults"];

                if (layer == undefined) {
                    var layer = new VEShapeLayer();
                    this.Layers["LiveSearchResults"] = layer;
                    this.VirtualEarthMap.AddShapeLayer(layer);
                }

                var shapeCount = layer.GetShapeCount();

                if (msg.d.PhoneBookResults != null) {
                    for (var i = 0; i < msg.d.PhoneBookResults.length; i++) {
                        var result = msg.d.PhoneBookResults[i];

                        //Add to map
                        var shapeLocation = new VELatLong(result.Latitude, result.Longitude, 0, VEAltitudeMode.RelativeToGround);
                        var shape = new VEShape(VEShapeType.Pushpin, shapeLocation);

                        var markerNumber = shapeCount + i + 1;

                        shape.IsLiveSearchResult = true;
                        shape.LiveSearchMarkerNumber = markerNumber;
                        shape.SetTitle("<a href=\"" + result.DisplayUrl + "\" target=\"_blank\">" + result.Business + "</a>");
                        shape.SetDescription(result.Address);

                        var iconUrl = "Common/Images/Markers/Stock/RedCircle" + markerNumber + ".gif";

                        shape.SetCustomIcon(iconUrl);
                        layer.AddShape(shape);
                        
                        $("#LiveSearchResults").append("<div id=\"LiveSearchResult-" + markerNumber + "\" class=\"LiveSearchResult\"><span class=\"LiveSearchResult-MarkerNumber\">" + markerNumber + "</span><span class=\"LiveSearchResult-BusinessName\">" + result.Business + "</span><span class=\"LiveSearchResult-Address\">" + result.Address + "<br/>" + result.City + ", " + result.StateOrProvince + " " + result.CountryOrRegion + "</span><span class=\"LiveSearchResult-PhoneNumber\">" + result.PhoneNumber + "</span></div>");
                        //wire up the livesearchresult in the control panel with a closure that will show the shape's InfoBox in the map.
                        $("#LiveSearchResults #LiveSearchResult-" + markerNumber).click(
                            function(map, shape) {
                                return function() {
                                    map.HideInfoBox();
                                    map.SetCenterAndZoom(shape.GetPoints()[0], 15);
                                    window.setTimeout(function() { map.ShowInfoBox(shape); }, 750);
                                    window.setTimeout(function() { map.ShowInfoBox(shape); }, 2000);
                                }
                            } (this.VirtualEarthMap, shape)
                        );
                    }
                }
                DisplayShapeCount();
            }
        }
    }

    MapContext.prototype.LoadLayer = function(id, msg) {
        if (!this.IsIndoor) {
            if (this.VirtualEarthMap) {
                //Load into VE
                //check to see if we already have a layer with this id
                var layer = this.Layers[id];

                if (layer == null) {
                    layer = new VEShapeLayer();
                    this.Layers[id] = layer;
                    this.VirtualEarthMap.AddShapeLayer(layer);
                }
                layer.Hide();
                layer.DeleteAllShapes();

                if (msg.d.length > 0 && 1 == 2) { // 1 == 2 - Robert : Disabled Clustering
                    var options = new VEClusteringOptions();
                    var iconSpec = new VECustomIconSpecification();
                    iconSpec.Image = msg.d[0].IconUrl;
                    options.Icon = iconSpec;
                    options.Callback = function(clusters) {
                        //first pass to calculate relative sizing
                        var maxClusterSize = 0;
                        for (var i = 0; i < clusters.length; i++) {
                            var cluster = clusters[i];
                            if (cluster.Shapes.length > maxClusterSize) {
                                maxClusterSize = cluster.Shapes.length;
                            }
                        }
                        for (var i = 0; i < clusters.length; i++) {
                            var cluster = clusters[i];
                            var clusterShape = cluster.GetClusterShape();

                            var sizeWeighting = cluster.Shapes.length / maxClusterSize;
                            var dimension = sizeWeighting * 50; //max size of 25 pixels;

                            clusterShape.SetTitle(SiteClusterBegin + cluster.Shapes.length + SiteClusterEnd);
                            clusterShape.IsCluster = true;
                        }
                    };
                    layer.SetClusteringConfiguration(VEClusteringType.Grid, options);
                }
                for (var i = 0; i < msg.d.length; i++) {
                    var site = msg.d[i];
                    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(site.Latitude, site.Longitude, 0, VEAltitudeMode.RelativeToGround));
                    shape.SetTitle(site.Id);
                    shape.SetDescription(site.Address);
                    shape.SetCustomIcon(site.IconUrl);
                    layer.AddShape(shape);
                }
                layer.Show();
                if (msg.d.length > 0)
                    this.VirtualEarthMap.SetMapView(GetOptimalViewForAllLayers());
                else
                    alert(NoResults);
                DisplayShapeCount();
            }
        }
        else {
            //Load into Indoor Map
            var layer = this.Layers[id];
            if (layer == null) {
                layer = {};
                this.Layers[id] = layer;
            }
            for (var i = 0; i < msg.d.length; i++) {
                var site = msg.d[i];
                var marker = addIndoorMapMarker(site.Latitude, site.Longitude, site.Id, id, site.IconUrl);
                site.Marker = marker;
                layer[site.Id] = site;
            }
        }
    }

    MapContext.prototype.RemoveLayer = function(id) {
        if (!this.IsIndoor) {
            if (this.VirtualEarthMap) {
                var layer = this.Layers[id];
                if (layer != null) {
                    this.Layers[id] = null;
                    vemap.DeleteShapeLayer(layer);
                    layer = null;
                }
                var shapeCount = GetShapeCount();
                if (shapeCount > 0) {
                    //this.VirtualEarthMap.SetMapView(GetOptimalViewForAllLayers());
                }
                else {
                    HideFaceDetail();
                }
                DisplayShapeCount();
            }
        }
        else {
            var layer = this.Layers[id];
            if (layer != null) {
                for (var i in layer) {
                    var site = layer[i];
                    $(site.Marker).remove();
                    layer[i] = null;
                }
                this.Layers[id] = {};
            }
        }
    }
}

function MapContextManager() {
    var _contexts = {};
    var _activeMapContext = null;

    MapContextManager.prototype.GetMapContextByName = function(name) {
        return _contexts[name];
    }

    MapContextManager.prototype.AddMapContext = function(mapContext) {
        _contexts[mapContext.Name] = mapContext;
    }

    MapContextManager.prototype.GetActiveMapContext = function() {
        return _activeMapContext;
    }

    MapContextManager.prototype.Activate = function(name) {
        for (var key in _contexts) { // Have to hide all first.
            var mapContext = _contexts[key];
            mapContext.Hide();
        }
        for (var key in _contexts) {
            var mapContext = _contexts[key];

            if (key == name) {
                if (_activeMapContext != mapContext) {
                    _activeMapContext = mapContext;
                    mapContext.Display();
                }
            }
        }
    }

    MapContextManager.prototype.DeactivateAll = function() {
        for (var key in _contexts) {
            var mapContext = _contexts[key];
            if (mapContext.Hide != undefined) {
                mapContext.Hide();
            }
        }
    }

    MapContextManager.prototype.Display = function(name) {
        var mapContext = _contexts[name];
        mapContext.Display();
    }

    MapContextManager.prototype.Clear = function() {
        //clear the contexts
        for (var key in _contexts) {
            var mapContext = _contexts[key];
            if (mapContext.Clear != undefined) {
                mapContext.Clear();
            }
        }
    }

}

//Add some new fields to the VEShape class
VEShape.prototype.Guid = null;
VEShape.prototype.FirstFaceId = null;
VEShape.prototype.FaceCount = 0;
VEShape.prototype.IsCluster = false;
VEShape.prototype.IsLiveSearchResult = false;
VEShape.prototype.LiveSearchMarkerNumber = -1;

// Initialize some global variables
var vemap = null;
var mapContextManager = null;
var siteSearchServiceCallouts = 0;

function OnObliqueEnterHandler() {
    if (vemap.IsBirdseyeAvailable()) {
        $("#MSVE_navAction_ObliqueMapStyle").css("display", "block");
    }
}

function OnObliqueLeaveHandler() {
    if (!vemap.IsBirdseyeAvailable()) {
        $("#MSVE_navAction_ObliqueMapStyle").css("display", "none");
    }
}

function OnChangeMapStyleHandler(e) {
    if (e.mapStyle == 'b') { // Bird's Eye 'b'
        $("#MSVE_navAction_Clockwise").css("display", "block");
        $("#MSVE_navAction_CounterClockwise").css("display", "block");
    }
    else {
        $("#MSVE_navAction_Clockwise").css("display", "none");
        $("#MSVE_navAction_CounterClockwise").css("display", "none");
    }
}

$(window).ready(function() {
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

    //Set the dimensions for the DIV that will contain the map
    $("#outdoor-map").width($("#page").width());
    $("#outdoor-map").height($("#page").height() - 51);

    //Set up the virtual earth map
    vemap = new VEMap("outdoor-map");
    vemap.SetDashboardSize(VEDashboardSize.Small);

    var options = new VEMapOptions();
    options.LoadBaseTiles = true;
    options.EnableBirdseye = true;

    vemap.onLoadMap = function() { MapLoadedHandler(); };
    vemap.SetClientToken(token);
    vemap.LoadMap(new VELatLong(60, -100, 1000, VEAltitudeMode.RelativeToGround),
                  4,
                  VEMapStyle.Road,
                  false,
                  VEMapMode.Mode2D,
                  false,
                  5,
                  options);

    mapContextManager = new MapContextManager();

    mapContextManager.AddMapContext(new MapContext("SiteSearch"));
    mapContextManager.AddMapContext(new MapContext("FaceSearch"));
    mapContextManager.AddMapContext(new MapContext("FaceAddressSearch"));
    mapContextManager.AddMapContext(new MapContext("Favorites"));

    mapContextManager.GetMapContextByName("SiteSearch").VirtualEarthMap = vemap;
    mapContextManager.GetMapContextByName("FaceSearch").VirtualEarthMap = vemap;
    mapContextManager.GetMapContextByName("FaceAddressSearch").VirtualEarthMap = vemap;

    vemap.SetMouseWheelZoomToCenter(false);

    vemap.AttachEvent("onobliqueenter", OnObliqueEnterHandler);
    vemap.AttachEvent("onobliqueleave", OnObliqueLeaveHandler);
    vemap.AttachEvent("onchangemapstyle", OnChangeMapStyleHandler);

    //When the window resizes, we resize the map.
    $(window).resize(function() { ResizeMap(); });

    //Show the control panel after a delay
    $("dl.accordian").accordion({ animated: 'easeslide', header: 'dt' });
    $("dl.accordian").bind("change.ui-accordion", AccordionChangeHandler);

    window.setTimeout('$("#controlPanel").show("slow", function() { });', 1500);

    vemap.AttachEvent("onclick", ShapeClickedHandler);
    vemap.AttachEvent("onmouseover", ShapeMouseOverHandler);
    vemap.AttachEvent("onmouseout", ShapeMouseOutHandler);

    var faceCode = RequestQueryString("facecode");
    if (faceCode != "")
        mapContextManager.Activate("FaceSearch");
    else
        mapContextManager.Activate("SiteSearch");
});

function AccordionChangeHandler(event, ui) {
    var selectedIndex = -1;
    if (ui == undefined) {
        return;
    }
    for (var i = 0; i < ui.options.headers.length; i++) {
        var a = ui.newHeader.text();
        var b = ui.options.headers[i].innerText;    
        if (a == b) {
            selectedIndex = i;
            break;
        }
    }
    var activeMapContext = mapContextManager.GetActiveMapContext();
    HideSearchHelp();
    
    if (selectedIndex == 0) { //Site Search
        if (activeMapContext.Name != "SiteSearch")
            mapContextManager.Activate("SiteSearch");
        ShowSaveSearch();
    }
    else if (selectedIndex == 1) { //Live Search
        if (activeMapContext.Name != "SiteSearch")
            mapContextManager.Activate("SiteSearch");
        HideSaveSearch();
    }
    else if (selectedIndex == 2) {
        FaceSearchSelectedChanged();
        HideSaveSearch();
    }
    else if (selectedIndex == 3) { //Favorites mode
        HideFaceDetail();
        HideSaveSearch();
    }
}

function FaceSearchSelectedChanged() {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    // Check the Radio button to see active Face Search context
    var selectedFaceSearchValue = GetSelectedFaceSearchValue();
    if (selectedFaceSearchValue == 'address') {
        if (activeMapContext.Name != "FaceAddressSearch")
            mapContextManager.Activate("FaceAddressSearch");
    }
    else {
        if (activeMapContext.Name != "FaceSearch") {
            mapContextManager.Activate("FaceSearch");
        }
    }
    return true;
}

function GetSelectedFaceSearchValue() {
    var faceSearchRadioButtonList = document.getElementById(FaceSearchTypeRadioButtonListId);
    var inputs = faceSearchRadioButtonList.getElementsByTagName("input");
    var selectedValue = null;
    for (var i = 0; i < inputs.length; i++)
    {
        if (inputs[i].checked)
        {
            selectedValue = inputs[i].value;
            break;
        }
    }
    return selectedValue;
}


function ShowSaveSearch() {
    var selectedMediaProducts = document.getElementById(selectedMediaProductsFieldId);
    if (selectedMediaProducts.value != "") {
        document.getElementById('MSVE_navAction_SaveSearch').style.display = "block";
    }
    else {
        HideSaveSearch();
    }
}

function HideSaveSearch() {
    HideSaveSearchDialog(); // Hide the Save search dialogue before hiding button so that animation makes sense.
    document.getElementById('MSVE_navAction_SaveSearch').style.display = "none";
}

function ShowSaveSearchDialog() {
    var selectedMediaProducts = document.getElementById(selectedMediaProductsFieldId);
    if (selectedMediaProducts.value != "" && document.getElementById('SaveSearchDiv').style.display == "none") {
        $("#SaveSearchDiv").slideDown("slow");
    }
    else {
        HideSaveSearchDialog();
    }
}

function HideSaveSearchDialog() {
    $("#SaveSearchDiv").slideUp("slow");
}

function ShowSearchHelp() {
    if (document.getElementById('HelpDiv').style.display == "none") {
        $("#HelpDiv").show("slow");
    }
    else {
        HideSearchHelp();
    }
}

function HideSearchHelp() {
    $("#HelpDiv").hide("slow");
}

function WriteMapStatus(message) {
    $("#mapStatus").html(message);
}

function BeginRequestHandler(sender, args) {
    $("input").attr("disabled", true);
    $("select").attr("disabled", true);
}

function EndRequestHandler(sender, args) {
    if (args.get_error() != undefined) {
        alert(args.get_error().message);
        args.set_errorHandled(true);
    }
    $("input").attr("disabled", false);
    $("select").attr("disabled", false);
}

function ResizeMap() {
    if (vemap != null) {
        var width = $("#page").width();
        var height = $("#page").height() - 51;
        vemap.Resize(width, height);
    }
}

function MapLoadedHandler() {
    $("#MSVE_navAction_mapStyleCell").append("<div id=\"MSVE_navAction_ObliqueMapStyle\" style=\"display:none;\" class=\"MSVE_MapStyle\">" + BirdsEye + "</div>");
    $("#MSVE_navAction_mapStyleCell").append("<div id=\"MSVE_navAction_Clockwise\" style=\"display:none;width:30px;vertical-align:bottom;\" class=\"MSVE_MapStyle\"><img src=\"Common\\images\\arrow_RIGHT.png\"></div>");
    $("#MSVE_navAction_mapStyleCell").append("<div id=\"MSVE_navAction_CounterClockwise\" style=\"display:none;width:30px;vertical-align:bottom;\" class=\"MSVE_MapStyle\"><img src=\"Common\\images\\arrow_LEFT.png\"></div>");
    $("#MSVE_navAction_mapStyleCell").append("<div id=\"MSVE_navAction_SaveSearch\" style=\"display:none;\" class=\"MSVE_MapStyle\">" + SaveSearch + "</div>");

    $("#MSVE_navAction_Clockwise").hover(
        function() { /* hover over */$(this).addClass("ms_pseudoHover"); },
        function() { /* hover out */$(this).removeClass("ms_pseudoHover"); }
    );

    $("#MSVE_navAction_CounterClockwise").hover(
        function() { /* hover over */$(this).addClass("ms_pseudoHover"); },
        function() { /* hover out */$(this).removeClass("ms_pseudoHover"); }
    );
    
    $("#MSVE_navAction_ObliqueMapStyle").hover(
        function() { /* hover over */$(this).addClass("ms_pseudoHover"); },
        function() { /* hover out */$(this).removeClass("ms_pseudoHover"); }
    );

    $("#MSVE_navAction_SaveSearch").hover(
        function() { /* hover over */$(this).addClass("ms_pseudoHover"); },
        function() { /* hover out */$(this).removeClass("ms_pseudoHover"); }
    );

    $("#MSVE_navAction_SaveSearch").click(function() {
        ShowSaveSearchDialog();
    });
    
    $("#MSVE_navAction_ObliqueMapStyle").click(function() {
        var activeMapContext = mapContextManager.GetActiveMapContext();
        if (activeMapContext.VirtualEarthMap != null && activeMapContext.VirtualEarthMap.IsBirdseyeAvailable()) {
            $("#MSVE_navAction_mapStyleCell").attr("class", "MSVE_ObliqueMapStyle");
            activeMapContext.VirtualEarthMap.SetBirdseyeScene();
        }
        else {
            alert(BirdsEyeNotAvailable);
        }
    });

    $("#MSVE_navAction_Clockwise").click(function() {
        var activeMapContext = mapContextManager.GetActiveMapContext();
        if (activeMapContext.VirtualEarthMap.IsBirdseyeAvailable()) {
            var birdsEye = activeMapContext.VirtualEarthMap.GetBirdseyeScene();
            switch (birdsEye.GetOrientation()) {
                case VEOrientation.North:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.East);
                    break;
                case VEOrientation.East:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.South);
                    break;
                case VEOrientation.South:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.West);
                    break;
                case VEOrientation.West:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.North);
                    break;
            }
        }
        else {
            alert(BirdsEyeNotAvailable);
        }
    });
    
    $("#MSVE_navAction_CounterClockwise").click(function() {
        var activeMapContext = mapContextManager.GetActiveMapContext();
        if (activeMapContext.VirtualEarthMap.IsBirdseyeAvailable()) {
            var birdsEye = activeMapContext.VirtualEarthMap.GetBirdseyeScene();
            switch (birdsEye.GetOrientation()) {
                case VEOrientation.North:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.West);
                    break;
                case VEOrientation.West:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.South);
                    break;
                case VEOrientation.South:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.East);
                    break;
                case VEOrientation.East:
                    activeMapContext.VirtualEarthMap.SetBirdseyeOrientation(VEOrientation.North);
                    break;
            }
        }
        else {
            alert(BirdsEyeNotAvailable);
        }
    });
    WriteMapStatus(MapLoaded);
    ResizeMap();
}

function GetOptimalViewForLayer(layer)
{
    var shapeCount = layer.GetShapeCount();
    var topLeftLat = null;
    var topLeftLon = null;
    var bottomRightLat = null;
    var bottomRightLon = null;
    if (shapeCount > 0) {
        if (layer.IsVisible()) {
            var boundingRectangle = layer.GetBoundingRectangle();
            if (topLeftLat == null) {
                topLeftLat = boundingRectangle.TopLeftLatLong.Latitude;
                topLeftLon = boundingRectangle.TopLeftLatLong.Longitude;
                bottomRightLat = boundingRectangle.BottomRightLatLong.Latitude;
                bottomRightLon = boundingRectangle.BottomRightLatLong.Longitude;
            }
            else {
                //top-left
                if (boundingRectangle.TopLeftLatLong.Latitude > topLeftLat) {
                    topLeftLat = boundingRectangle.TopLeftLatLong.Latitude;
                }
                if (boundingRectangle.TopLeftLatLong.Longitude < topLeftLon) {
                    topLeftLon = boundingRectangle.TopLeftLatLong.Longitude;
                }
                //bottom-right
                if (boundingRectangle.BottomRightLatLong.Latitude < bottomRightLat) {
                    bottomRightLat = boundingRectangle.BottomRightLatLong.Latitude;
                }
                if (boundingRectangle.BottomRightLatLong.Longitude > bottomRightLon) {
                    bottomRightLon = boundingRectangle.BottomRightLatLong.Longitude;
                }
            }
        }
    }
    return new VELatLongRectangle(new VELatLong(topLeftLat, topLeftLon + .02, 0, VEAltitudeMode.Default), new VELatLong(bottomRightLat, bottomRightLon - .02, 0, VEAltitudeMode.Default), null, null);
}

function GetOptimalViewForAllLayers() {
    var optimalBoundingRectangle = null;
    var activeMapContext = mapContextManager.GetActiveMapContext();
    var layerCount = activeMapContext.VirtualEarthMap.GetShapeLayerCount();
    var topLeftLat = null;
    var topLeftLon = null;
    var bottomRightLat = null;
    var bottomRightLon = null;
    for (var i = 0; i < layerCount; i++) {
        var layer = activeMapContext.VirtualEarthMap.GetShapeLayerByIndex(i);
        var shapeCount = layer.GetShapeCount();
        if (shapeCount > 0) {
            if (layer.IsVisible()) {
                var boundingRectangle = layer.GetBoundingRectangle();
                if (topLeftLat == null) {
                    topLeftLat = boundingRectangle.TopLeftLatLong.Latitude;
                    topLeftLon = boundingRectangle.TopLeftLatLong.Longitude;
                    bottomRightLat = boundingRectangle.BottomRightLatLong.Latitude;
                    bottomRightLon = boundingRectangle.BottomRightLatLong.Longitude;
                }
                else {
                    //top-left
                    if (boundingRectangle.TopLeftLatLong.Latitude > topLeftLat) {
                        topLeftLat = boundingRectangle.TopLeftLatLong.Latitude;
                    }
                    if (boundingRectangle.TopLeftLatLong.Longitude < topLeftLon) {
                        topLeftLon = boundingRectangle.TopLeftLatLong.Longitude;
                    }
                    //bottom-right
                    if (boundingRectangle.BottomRightLatLong.Latitude < bottomRightLat) {
                        bottomRightLat = boundingRectangle.BottomRightLatLong.Latitude;
                    }
                    if (boundingRectangle.BottomRightLatLong.Longitude > bottomRightLon) {
                        bottomRightLon = boundingRectangle.BottomRightLatLong.Longitude;
                    }
                }
            }
        }
    }
    return new VELatLongRectangle(new VELatLong(topLeftLat, topLeftLon + .02, 0, VEAltitudeMode.Default), new VELatLong(bottomRightLat, bottomRightLon - .02, 0, VEAltitudeMode.Default), null, null);
}

function DisplayShapeCount() {
    var shapeCount = GetShapeCount();
    WriteMapStatus(ShowingSiteBegin + shapeCount + ShowingSiteEnd);
}

function GetShapeCount() {
    var layerCount = vemap.GetShapeLayerCount();
    var shapeCount = 0;
    var visibleLayerCount = 0;
    for (var i = 0; i < layerCount; i++) {
        var layer = vemap.GetShapeLayerByIndex(i);
        if (layer.IsVisible()) {
            visibleLayerCount = visibleLayerCount + 1;
            shapeCount += layer.GetShapeCount();
        }
    }
    visibleLayerCount = visibleLayerCount - 1;
    return shapeCount;
}

function ShapeMouseOverHandler(mapEvent) {
    ShapeClickedHandler(mapEvent);
    return true;  //suppress VE behavior for this event
}

function ShapeMouseOutHandler(mapEvent) {
    return false; //true suppress VE behavior for this event
}

function addIndoorMapMarker(offsetTop, offsetLeft, siteId, layerId, markerIconUrl) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    var markerId = "indoor-map-marker-" + layerId + "-" + siteId;
    $("#indoor-map #map-markers").append("<div id=\"" + markerId + "\" class=\"map-marker\"><img src=\"" + markerIconUrl + "\" /></div>");
    $("#" + markerId).css("margin-left", offsetLeft + "px");
    $("#" + markerId).css("margin-top", offsetTop + "px");
    $("#" + markerId).bt("Loading...<br/><img src=\"Common/Images/ajax-loader.gif\">",
        {   trigger: 'none',
            //width: 250,
            positions: ['right', 'left', 'top', 'bottom'],
            closeWhenOthersOpen: true,
            padding: 15,
            cornerRadius: 0,
            fill: '#FFF',
            strokeStyle: '#ABABAB',
            strokeWidth: 1
        });

    $("#" + markerId).hover(function() {
        IndoorMarkerHoverOverHandler($(this), siteId);
    },
    function() {
        IndoorMarkerHoverOutHandler($(this), siteId);
    });

    return $("#" + markerId);
}

function IndoorMarkerHoverOverHandler(marker, siteId) {
    $(marker).btOn();
    var hasSiteDetail = $(marker).attr("hasSiteDetail");
    if (!hasSiteDetail) {
        //Call to get detail
        $.ajax({
            type: "POST",
            url: "InventoryService.asmx/GetSiteDetail",
            data: "{siteId: \"" + siteId + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) { IndoorDetailReceivedHandler(msg, marker); }
        });
    }
}

function IndoorDetailReceivedHandler(msg, marker) {
    var description = "";
    for (var i = 0; i < msg.d.Faces.length; i++) {
        var face = msg.d.Faces[i];
        var link = "<a href=\"javascript:ShowFaceDetail('" + face.Id + "');\">" + face.Name;
        if (face.FacingDirection != null) {
            link += " - " + face.FacingDirection
        }
        link += "</a><br />";
        description += link;
    }

    $(marker).btOff();
    $(marker).bt(description,
        {   trigger: 'none',
            width: 250,
            positions: ['right', 'left', 'top', 'bottom'],
            closeWhenOthersOpen: true,
            padding: 10,
            cornerRadius: 0,
            fill: '#FFF',
            strokeStyle: '#ABABAB',
            strokeWidth: 1
        });
    $(marker).btOn();
}

function IndoorMarkerHoverOutHandler(marker, siteId) { }

function ShapeClickedHandler(mapEvent) {
    if (mapEvent.elementID != null) {
        var shape = vemap.GetShapeByID(mapEvent.elementID);
        if (shape != null) {
            if (!shape.IsCluster && !shape.IsLiveSearchResult) {
                if (shape.Guid == null) {
                    shape.Guid = shape.GetTitle();
                    shape.SetTitle(LoadingSiteDetails);
                    shape.SetDescription("<img src=\"Common/Images/ajax-loader.gif\" />");
                    var selectedMediaProducts = document.getElementById(selectedMediaProductsFieldId);
                    var activeMapContext = mapContextManager.GetActiveMapContext();

                    if (activeMapContext.Name != "FaceAddressSearch") {
                        //make ajax call to get site details for info box
                        $.ajax({
                            type: "POST",
                            url: "InventoryService.asmx/GetSiteDetailByMediaProduct",
                            data: "{siteId: \"" + shape.Guid + "\", mediaProductIds:\"" + selectedMediaProducts.value + "\"}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(msg) { ShapeDetailReceivedHandler(msg, mapEvent.elementID); }
                        });
                    }
                    else { 
                        //make ajax call to get site details for info box
                        $.ajax({
                            type: "POST",
                            url: "InventoryService.asmx/GetSiteDetail",
                            data: "{siteId: \"" + shape.Guid + "\"}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(msg) { ShapeDetailReceivedHandler(msg, mapEvent.elementID); }
                        });
                    }
                }
            }
            if (shape.IsLiveSearchResult) {
                var liveSearchResultName = "#LiveSearchResults #LiveSearchResult-" + shape.LiveSearchMarkerNumber;
                $(liveSearchResultName)[0].scrollIntoView();
            }
            vemap.ShowInfoBox(shape);
        }
    }
    return false;  //allow VE to do whatever it does by default for this event
}

function ShapeDetailReceivedHandler(msg, shapeId) {
    var shape = vemap.GetShapeByID(shapeId);
    if (shape != null) {
        shape.SetTitle(msg.d.Address);
        var DefaultCameraLatitude, DefaultCameraLongitude, DefaultCameraPitch, DefaultCameraYaw;

        var longitude = 0;
        var latitude = 0;
        if (msg.d.Faces[0] != null) {
            latitude = msg.d.Faces[0].CameraLatitude;
            longitude = msg.d.Faces[0].CameraLongitude;
        }

        var gviewPoint = new GLatLng(latitude, longitude);
        var gviewClient = new GStreetviewClient();
        gviewClient.getNearestPanorama(gviewPoint,
        function(gviewData) {
            DefaultCameraLatitude = latitude;
            DefaultCameraLongitude = longitude;
            var description = "";
            description += "<table width='100%' cellpadding='2'>";
            for (var i = 0; i < msg.d.Faces.length; i++) {
                var face = msg.d.Faces[i];
                var link = "<tr><td><img src='MediaProductIcon.ashx?id=" + face.MediaProductId + "' /></td><td><a href=\"javascript:ShowFaceDetail('" + face.Id + "');\">" + face.Name + " - " + face.FacingDirection + "</a></td><td height='22'>"
                if (gviewData.code == 200) {
                    link += "<a href='javascript:SetStreetViewLink(" + face.CameraLatitude + ", " + face.CameraLongitude + ", " + face.CameraPitch + ", " + face.CameraYaw + ", " + DefaultCameraLatitude + ", " + DefaultCameraLongitude + ");'><img src='Common/Images/StreetViewIconTransparentSmall.png'></a>";
                }
                link += "</td></tr>";
                description += link;
            }
            description += "</table>";

            shape.FaceCount = msg.d.Faces.length;
            shape.SetDescription(description);
            vemap.ShowInfoBox(shape);
            if (msg.d.Faces.Length > 0)
                shape.FirstFaceId = msg.d.Faces[0].Id;
        });
    }
}

function SetStreetViewLink(CameraLatitude, CameraLongitude, CameraPitch, CameraYaw, DefaultCameraLatitude, DefaultCameraLongitude) {
    var gviewPoint = new GLatLng(CameraLatitude, CameraLongitude);
    var gviewClient = new GStreetviewClient();
    gviewClient.getNearestPanorama(gviewPoint,
    function(gviewData) {
        if (gviewData.code == 200) {
            ShowPanoramaWithView(CameraLatitude, CameraLongitude, CameraPitch, CameraYaw);
        }
        else{
            ShowPanoramaWithView(DefaultCameraLatitude, DefaultCameraLongitude, CameraPitch, CameraYaw);
        }
    });
}

function findNearestStreetView(latitude, longitude) {
    var gviewPoint = new GLatLng(latitude, longitude);
    var gviewClient = new GStreetviewClient();
    gviewClient.getNearestPanorama(gviewPoint, setStreetViewLink);
}

function setStreetViewLink(gviewData) {
    if (gviewData.code != 200) {
        $("#ShowPanoramaLinkDiv").html("");
    }
}

function setStreetViewLinkWithDivId(gviewData, divIdentity) {
    if (gviewData.code != 200) {
        $(divIdentity).html("");
    }
}

function FaceSearchShowResults(faceId, siteId, latitude, longitude, iconUrl) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (activeMapContext.IsIndoor) {
        activeMapContext.RemoveLayers();
        var layer = {};
        activeMapContext.Layers["FaceSearch"] = layer;
        var site = { Id: siteId, Latitude: latitude, Longitude: longitude, IconUrl: iconUrl };
        site.Marker = addIndoorMapMarker(latitude, longitude, siteId, "FaceSearch", iconUrl);
        layer[siteId] = site;
        ShowFaceDetail(faceId);
    }
    else {
        var layer = activeMapContext.Layers["FaceSearch"];
        if (layer == undefined || layer.AddShape == null) {
            var layer = new VEShapeLayer();
            activeMapContext.Layers["FaceSearch"] = layer;
            activeMapContext.VirtualEarthMap.AddShapeLayer(layer);
        }
        else if (layer.Show != null) {
            layer.DeleteAllShapes();
            layer.Show();
        }
        ShowFaceDetail(faceId);
        var point = new VELatLong(latitude, longitude, 0, VEAltitudeMode.RelativeToGround);
        var pin = new VEShape(VEShapeType.Pushpin, point);
        pin.IsLiveSearchResult = false;
        pin.SetCustomIcon(iconUrl);
        pin.SetTitle(siteId);
        layer.AddShape(pin);
        activeMapContext.VirtualEarthMap.SetMapView(GetOptimalViewForAllLayers());
        DisplayShapeCount();
    }
}

function ShowFaceDetail(faceId) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    activeMapContext.SelectedFaceId = faceId;
    $("#faceDetailPanel").hide("slow", function() {
        $.ajax({
            type: "GET",
            url: "FaceDetails.ashx",
            data: "faceId=" + faceId,
            contentType: "text/html",
            dataType: "html",
            success: function(msg) { FaceDetailReceivedHandler(msg); }
        });
    });
}

function HideFaceDetail() {
    $("#faceDetailPanel").hide("slow", function() { });
}

function FaceDetailReceivedHandler(msg) {
    $("#faceDetailInner").html(msg);
    $("#faceDetailPanel").show("slow");
}

function ShowVideo(url) {
    $("#modalVideoPage").click(function(event) {
        $("#silverlightVideoPlayerHost").attr("style", "display:none");
        $("#silverlightVideoPlayerHost").html("");
        $(".modalVideo").slideUp("slow", function() { $("#modalVideoPage").attr("style", "display:none;"); });
        $("#modalVideoPage").unbind();
    });
    $("#modalVideoPage").attr("style", "display:block;");
    $(".modalVideo").slideDown("slow", function() { $("#silverlightVideoPlayerHost").attr("style", "display:block;"); });
    var objectCode = "<object id=\"mediaPlayer\" data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"640\" height=\"480\"><param name=\"source\" value=\"ClientBin/VideoPlayerM.xap\" /><param name=\"background\" value=\"transparent\" /><param name=\"initParams\" value=\"m=" + url + ",autostart=true\" /><param name=\"minruntimeversion\" value=\"2.0.31005.0\" /><a href=\"http://go.microsoft.com/fwlink/?LinkId=124807\" style=\"text-decoration: none;\"><img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Get Microsoft Silverlight\" style=\"border-style: none\" /></a></object>";
    $("#silverlightVideoPlayerHost").html(objectCode);
}

function ShowPanorama(Lat, Long) {
    ShowPanoramaWithView(Lat, Long, 0, 0);
}

function ShowPanoramaWithView(Lat, Long, Pitch, Yaw) {
    $("#streetViewPanoramaDiv").click(function(event) {
        $("#modalStreetView").slideUp("slow", function() { $("#streetViewPanoramaDiv").attr("style", "display:none;"); });
        $("#panorama").html("");
    });
    $("#modalStreetView").click(function(event) { return false; });
    $("#streetViewPanoramaDiv").attr("style", "display:block;");
    $("#modalStreetView").slideDown("slow", function() { $("#panorama").attr("style", "display:block;"); });
    ShowStreetView(Lat, Long, Pitch, Yaw);
}

function ResetMapView() {
    vemap.SetCenterAndZoom(new VELatLong(60, -100, 1000, VEAltitudeMode.RelativeToGround), 4);
}

function ClearSiteSearch() {
    //RemoveLayers();
    var activeMapContext = mapContextManager.GetActiveMapContext();
    for (var layerId in activeMapContext.Layers) {
        if (layerId != "LiveSearchResults") {
            activeMapContext.RemoveLayer(layerId);
        }
    }
    HideFaceDetail();
    DisplayShapeCount();
    ResetMapView();
}

function ClearFaceSearch() {
    RemoveLayers();
    ResetMapView();
}

function ClearMap() {
    RemoveLayers();
    HideFaceDetail();
    ClearLiveSearch();
    ResetMapView();
}

function HideOutdoorMap() {
    $("#outdoor-map").hide("slow");
}

function SwitchAccordion(sectionName, activateMapContext, callback) {
    var activateMap = true;
    if (activateMapContext != null && !activateMapContext)
        activateMap = false;

    switch (sectionName) {
        case 'Site Search':
            if (activateMap)
                mapContextManager.Activate("SiteSearch");
            $("dl.accordian").accordion('activate', 0);
            break;
        case 'Live Search':
            if (activateMap)
                mapContextManager.Activate("SiteSearch");
            $("dl.accordian").accordion('activate', 1);
            break;
        case 'Face Search':
            if (activateMap) {
                if (mapContextManager == null)
                    window.setTimeout(WaitForMapContextManagerToCallSwitch, 4000);
                else {
                    mapContextManager.Activate("FaceSearch");
                    $("dl.accordian").accordion('activate', 2);
                }
            }
            else
                $("dl.accordian").accordion('activate', 2);
            break;
        case 'Favorites':
            $("dl.accordian").accordion('activate', 3);
            break;
    }
    if (callback) {
        if (mapContextManager == null)
            window.setTimeout(callback, 4000);
        else
            callback();
    }
    return true;
}

function WaitForMapContextManagerToCallSwitch() {
    var i = 0;
    while (mapContextManager == null) // Fix for IE7 French, this method is called before Window Load method is finished.
        i += 1;
    mapContextManager.Activate("FaceSearch");
    $("dl.accordian").accordion('activate', 2);
}

function SubmitButton(ButtonName) {
    var button = document.getElementById(ButtonName);
    if (button != null)
        button.click();
}

function ShowOutdoorMap() {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (activeMapContext != null) {
        activeMapContext.IsIndoor = false;
    }
    $("#indoor-map").hide("slow",
        function() { $("#outdoor-map").show("slow"); });
    return true;
}

function HideIndoorMap() {
    $("#indoor-map").hide("slow");
}

function ShowIndoorMap(mapImageUrl, callback) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (!activeMapContext.IsIndoor)
        activeMapContext.IsIndoor = true;
    if (activeMapContext.IndoorMapImageUrl == null || activeMapContext.IndoorMapImageUrl == '') {
        activeMapContext.IndoorMapImageUrl = mapImageUrl;
        $("#outdoor-map").hide("slow", function() {
            $("#indoor-map").hide("slow", function() {
                $("#indoor-map").css("visibility", "hidden");
                $("#indoor-map").css("display", "block");
                $("#indoor-map").html("<div id=\"map-image\"></div><div id=\"map-markers\"></div>");
                var mapImage = new Image();
                $("#indoor-map #map-image").append(mapImage);
                $(mapImage).load(function() {
                    var imgWidth = $(this).width();
                    var imgHeight = $(this).height();
                    $("#indoor-map").css("height", imgHeight + "px");
                    $("#indoor-map").css("width", imgWidth + "px");
                    $("#indoor-map").css("margin-top", "-" + imgHeight / 2 + "px");
                    //$("#indoor-map").css("margin-left", "-" + (imgWidth - 230) / 2 + "px");
                    $("#indoor-map").css("margin-left", "-" + imgWidth / 2 + "px");
                    $("#indoor-map").css("display", "none");
                    $("#indoor-map").css("visibility", "visible");
                    if (callback) {
                        $("#outdoor-map").hide("slow", function() { $("#indoor-map").show("slow", callback); });
                    }
                    else {
                        $("#outdoor-map").hide("slow", function() {$("#indoor-map").show("slow"); });
                    }
                })
                $(mapImage).attr("src", mapImageUrl);
            });
        });
    }
    else if (activeMapContext.IndoorMapImageUrl != mapImageUrl) {
        activeMapContext.IndoorMapImageUrl = mapImageUrl;
        $("#outdoor-map").hide("slow",
            function() { $("#indoor-map").hide("slow", function() {
                $("#indoor-map").css("visibility", "hidden");
                $("#indoor-map").css("display", "block");
                var mapImage = new Image();
                $("#indoor-map #map-image").html(mapImage);
                $(mapImage).load(function() {
                    var imgWidth = $(this).width();
                    var imgHeight = $(this).height();
                    $("#indoor-map").css("height", imgHeight + "px");
                    $("#indoor-map").css("width", imgWidth + "px");
                    $("#indoor-map").css("margin-top", "-" + imgHeight / 2 + "px");
                    //$("#indoor-map").css("margin-left", "-" + (imgWidth - 230) / 2 + "px");
                    $("#indoor-map").css("margin-left", "-" + imgWidth / 2 + "px");
                    $("#indoor-map").css("display", "none");
                    $("#indoor-map").css("visibility", "visible");
                    if (callback) {
                        $("#outdoor-map").hide("slow", function() {$("#indoor-map").show("slow", callback); });
                    }
                    else {
                        $("#outdoor-map").hide("slow", function() {$("#indoor-map").show("slow"); });
                    }
                })
                $(mapImage).attr("src", mapImageUrl);
            }); 
        });
    }
    else {
        if (callback) {
            $("#outdoor-map").hide("slow", function() { $("#indoor-map").show("slow", callback); });
        }
        else {
            $("#outdoor-map").hide("slow", function() { $("#indoor-map").show("slow"); });
        }
    }
    return true;
}

function LoadSitesResultsLayer(id, partialAddress, serviceUrl) {
    ClearFaceSearch();
    $.ajax({
        url: serviceUrl,
        type: "POST",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{marketId: '" + id + "', partialAddress: '" + partialAddress + "'}",
        success: function(msg, status) { LoadSitesResultsLayerSuccessHandler(id, msg); },
        error: function(xhr, textStatus, errorThrown) { alert(ErrorRetreivingSiteDate); }
    });
}

function LoadSitesResultsLayerSuccessHandler(id, msg) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (activeMapContext.IsIndoor) {
        ShowOutdoorMap();
    }
    var activeMapContext = mapContextManager.GetActiveMapContext();
    activeMapContext.LoadLayer(id, msg);
}

function LoadLayer(id, areas, mediaProducts, serviceUrl) {
    ShowProgressBarWithDisabledScreen();
    siteSearchServiceCallouts += 1;
    var areasJson = Sys.Serialization.JavaScriptSerializer.serialize(areas);
    var mediaProductsJson = Sys.Serialization.JavaScriptSerializer.serialize(mediaProducts);

    $.ajax({
        url: serviceUrl,
        type: "POST",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{areas: " + areasJson + ", mediaProducts: " + mediaProductsJson + "}",
        success: function(msg, status) { LoadLayerSuccessHandler(id, msg); },
        error: function(xhr, textStatus, errorThrown) { siteSearchServiceCallouts -= 1; alert(ErrorRetreivingSiteDate); }
    });
}

function LoadLayerSuccessHandler(id, msg) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    activeMapContext.LoadLayer(id, msg);
    siteSearchServiceCallouts -= 1;
    if (siteSearchServiceCallouts <= 0)
        window.setTimeout(HideNonMSAJAXProgressBar, 1000);
}

function RemoveLayer(id) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    activeMapContext.RemoveLayer(id);
}

function RemoveLayers() {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    activeMapContext.RemoveLayers();
}

function LiveSearch() {
    ShowNonMSAJAXProgressBar();
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (!activeMapContext.IsIndoor) {
        $("#LiveSearchLinkButton").attr("disabled", true);
        $("#ClearLiveSearchLinkButton").attr("disabled", true);
        $("#TextBoxLiveSearch").attr("disabled", true);
        var center = activeMapContext.VirtualEarthMap.GetCenter();
        var query = $("#TextBoxLiveSearch").attr("value");
        ExecuteLiveSearchRecursive(center.Latitude, center.Longitude, 150, query, 25, 0);
    }
    else {
        alert(LiveSearchNotSupported);
    }
}

function LiveSearchSuccessHandler(msg, resetLayer) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (resetLayer) {
        activeMapContext.RemoveLayer("LiveSearchResults");
        $("#LiveSearchResults").empty();
        $("#LiveSearchResults").show("slow");
    }
    activeMapContext.LoadLiveSearchResults(msg);
}

function LiveSearchErrorHandler(xhr, textStatus, errorThrown) {
    HideNonMSAJAXProgressBar();
    alert(LiveSearchError);
    $("#LiveSearchResults").hide("slow");
    $("#LiveSearchLinkButton").attr("disabled", false);
    $("#ClearLiveSearchLinkButton").attr("disabled", false);
    $("#TextBoxLiveSearch").attr("disabled", false);
}

function GeocodedSearchSuccessHandler(msg, resetLayer) {
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (resetLayer) {
        activeMapContext.RemoveLayer("LiveSearchResults");
        $("#LiveSearchResults").empty();
        $("#LiveSearchResults").show("slow");
    }
    activeMapContext.LoadGeocodedSearchResults(msg);
}

function ClearLiveSearch() {
    $("#TextBoxLiveSearch").attr("value", EnterABusinessOrLocation);
    var activeMapContext = mapContextManager.GetActiveMapContext();
    if (activeMapContext.IsIndoor) {
        alert(LiveSearchNotSupported);
    }
    else {
        activeMapContext.RemoveLayer("LiveSearchResults");
        $("#LiveSearchResults").empty();
        $("#LiveSearchResults").hide("slow");
    }
    if (activeMapContext.VirtualEarthMap != null) {
        activeMapContext.VirtualEarthMap.HideInfoBox();
    }
    DisplayShapeCount();
    ResetMapView();
}

function ExecuteLiveSearchRecursive(latitude, longitude, radius, query, pageSize, pageIndex) {
    var resetLayer = false;
    if (pageIndex == 0) {
        resetLayer = true;
    }
    var queryClean = Sys.Serialization.JavaScriptSerializer.serialize(query);
    var SearchSelectionRadioButton = document.getElementsByName('SearchSelectionRadioButton');
    if (SearchSelectionRadioButton[0].checked) // Live Search
    {
        var serviceUrl = "SearchService.asmx/GetLiveSearch";
        //do search
        $.ajax({
            url: serviceUrl,
            type: "POST",
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ latitude: " + latitude + ", longitude: " + longitude + ", radius: " + radius + ", query: " + queryClean + ", pageSize: " + pageSize + ", pageIndex: " + pageIndex + " }",
            success: function(msg, status) {
                LiveSearchSuccessHandler(msg, resetLayer);
                var offset = pageSize * ++pageIndex;
                if ((msg.d.PhoneBookResultsTotal > offset) && (offset < 201)) {
                    ExecuteLiveSearchRecursive(latitude, longitude, radius, query, pageSize, pageIndex, serviceUrl);
                }
                else {
                    $("#LiveSearchLinkButton").attr("disabled", false);
                    $("#ClearLiveSearchLinkButton").attr("disabled", false);
                    $("#TextBoxLiveSearch").attr("disabled", false);
                    DisplayShapeCount();
                }
                HideNonMSAJAXProgressBar();
            },
            error: function(xhr, textStatus, errorThrown) { LiveSearchErrorHandler(xhr, textStatus, errorThrown); }
        });
    }
    else    // Geocode search
    {
        var serviceUrl = "SearchService.asmx/GetGeocodedLocation";
        //do search
        $.ajax({
            url: serviceUrl,
            type: "POST",
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ latitude: " + latitude + ", longitude: " + longitude + ", radius: " + radius + ", query: " + queryClean + ", pageSize: " + pageSize + ", pageIndex: " + pageIndex + " }",
            success: function(msg, status) {
                GeocodedSearchSuccessHandler(msg, resetLayer);
                var offset = pageSize * ++pageIndex;
                if ((msg.d.PhoneBookResultsTotal > offset) && (offset < 201)) {
                    ExecuteLiveSearchRecursive(latitude, longitude, radius, query, pageSize, pageIndex, serviceUrl);
                }
                else {
                    $("#LiveSearchLinkButton").attr("disabled", false);
                    $("#ClearLiveSearchLinkButton").attr("disabled", false);
                    $("#TextBoxLiveSearch").attr("disabled", false);
                    DisplayShapeCount();
                }
                HideNonMSAJAXProgressBar();
            },
            error: function(xhr, textStatus, errorThrown) { LiveSearchErrorHandler(xhr, textStatus, errorThrown); }
        });
    }
}

function WatermarkFocus(TextBoxElement, WatermarkString) {
    if (TextBoxElement.value == WatermarkString) 
        TextBoxElement.value = '';
}

function WatermarkBlur(TextBoxElement, WatermarkString) {
    if (TextBoxElement.value == '')
        TextBoxElement.value = WatermarkString;
}

function SetValueInControl(TextBoxElement, Value) {
    TextBoxElement.value = Value;
}

function SetTextBoxLiveSearchDefaultText(TextBoxElement, Value) {
    var element = document.getElementById('TextBoxLiveSearch');
    element.value = EnterABusinessOrLocation;
}

function HideNonMSAJAXProgressBar() {
    HideLoadingOverlay();
    var progressDiv = document.getElementById('nonMSAJAXProgress');
    progressDiv.style.display = 'none';
}

function ShowNonMSAJAXProgressBar() {
    var progressDiv = document.getElementById('nonMSAJAXProgress');
    progressDiv.style.display = 'block';
}

function ShowProgressBarWithDisabledScreen() {
    ShowLoadingOverlay();
    var progressDiv = document.getElementById('nonMSAJAXProgress');
    progressDiv.style.display = 'block';
}

function Sleep(milliseconds, callback) {
    var startTime = new Date().getTime();
    var currentTime = startTime
    while (currentTime - startTime < milliseconds) {
        currentTime = new Date().getTime();
    }
    if (callback != null)
        callback();
}

function ActivateMapLayer(contextName) {
    mapContextManager.Activate(contextName);
}

function RequestQueryString(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1]; 
}
