﻿var gMap = null;
var gMapInitialized = false;
var gCreateMap = false;
var gZoomLevel = 6;
var gThrowJavascriptExceptions = true;
var gIsMapLoaded = true;

var RETRY_FAILURE_COUNT = 10;
var BALOON_POPUP_HEIGHT = 0;
 
if(typeof(Sys) !== "undefined") 
{
  Sys.Application.add_load(CreateMap);
}
	
//delays function to be run on window load.
function addLoadEvent(func) 
{ 
  var oldonload = window.onload; 

  if (typeof window.onload != 'function') 
  { 
    window.onload = func; 
  } 
  else 
  { 
    window.onload = function() { oldonload(); func(); } 
  }
}
	
function CreateMap()
{
  try
  {
    gMap = null;
    var retries = 0;

    while(!gMap)
    {
      try
      {	                
        gMap = new VEMap('mapDiv');
				gMap.LoadMap(new VELatLong(53.120405283106564, -3.383789062500008), gZoomLevel);
        
        if(gMap)
        {
          //Success, get out of the loop
          break;
        }		            
      }
      catch(er)
      {
        //we don't want to do anything
        gMap = null;
      }					

      //Advance the counter
      retries++;

      //Check if we have reached the threshold
      if(retries > RETRY_FAILURE_COUNT)
      {
        // too many retries, exist the loop
        gMap = null;
        break;
      }            
    }
    
    if(gMap)
    {
			if((typeof(myMapLocation) !== "undefined") && myMapLocation.length > 0)
			{
				gMap.Find(null, myMapLocation);
			}
			
      AddPinsInRectangle();

      return true;
    }
    else
    {
      // can't create map for any reason
      gMap = null;
      alert("Can't create map. Most likely your browser is not compatible with Microsoft Virtual Earth or it was blocked by your firewall.");
      return false;
    }
  }
  catch(ex)       
  {
    LogErrorMessage("CreateMap: ", ex);
  }
}

function LogErrorMessage(message, exception, rethrowOnly)
{
  if(exception && exception.message)
  {
    message = message + exception.message;

    if(rethrowOnly)
    {
      exception.message = message;
      throw exception;
    }

    UKuBid.Web.Services.MapService.LogClientException(message);   

    if(gThrowJavascriptExceptions)
    {
      throw exception;
    }
  }
}

function AttachEvents()
{
  try
  {
    gMap.AttachEvent("onchangeview", OnViewChanged);
  }
  catch(ex)
  {
    LogErrorMessage("AttachEvents: ", ex, true);
  }
}
	
function DetachEvents()
{
  try
  {
    gMap.DetachEvent("onchangeview", OnViewChanged);
  }
  catch(ex)
  {
    LogErrorMessage("DetachEvents: ", ex, true);
  }
}

function OnViewChanged(e)
{
  try
  {
    RemoveBaloons();

    DetachEvents();
    
    AddPinsInRectangle();
  }
  catch(ex)
  {
    LogErrorMessage("OnViewChanged: ", ex);
  }
}

function AddPinsInRectangle()
{
  try
  {
    GetPinsByLatLong(GetMapCoordinates());
  }
  catch(ex)
  {
    LogErrorMessage("AddPinsInRectangle: ", ex, true);
  }    
}
	
function GetPinsByLatLong(latLong)
{
  try
  {
    UKuBid.Web.Services.MapService.GetPOIByLatLong(
        latLong.TopLeftLatLong.Latitude,
        latLong.BottomRightLatLong.Latitude,
        latLong.TopLeftLatLong.Longitude,
        latLong.BottomRightLatLong.Longitude,
        GetPinsByLatLong_Continue
        );
  }
	catch(ex)
	{
    LogErrorMessage("GetPinsByLatLong: ", ex);
	} 
}

function GetPinsByLatLong_Continue(poiList)
{
  var poi;

  try
  {
    if(typeof(poiList) != 'undefined' && poiList)
    {
      var icon;
      var latLong;
      var shape;
      var pixel;

      for(var i = 0; i < poiList.length; i++)
      {
        poi = poiList[i];
        latLong = new VELatLong(poi.Latitude, poi.Longitude);
        shape = new VEShape(VEShapeType.Pushpin, latLong);
        pixel = gMap.LatLongToPixel(latLong, gMap.GetZoomLevel());
	    
        icon = "<img propertyId='" + poi.PropertyId + "' latitude='" + poi.Latitude + "' longitude='" + poi.Longitude + "' pixelX='" + pixel.x + "' pixelY='" + pixel.y + "' src='../images/mappin.gif' onclick='javascript:ShowAuctionDetails(this);' title='Click for Auction details' />";
        
        shape.SetCustomIcon(icon);
        
        gMap.AddShape(shape);
      }
    }
    
    AttachEvents();
  }
  catch(ex)
  {
    LogErrorMessage("GetPinsByLatLong_Continue: ", ex);
  } 
}

function ShowAuctionDetails(pinImage)
{
  try
  {
    RemoveBaloons();

    UKuBid.Web.Services.MapService.GetPOIDetail(
      pinImage.getAttribute("propertyId"),
      pinImage.getAttribute("latitude"),
      pinImage.getAttribute("longitude"),
      pinImage.getAttribute("pixelX"),
      pinImage.getAttribute("pixelY"),
      ShowAuctionDetails_Continue
      );    
  }
  catch(ex)
  {
    LogErrorMessage("ShowAuctionDetails: ", ex);
  }
}

function ShowAuctionDetails_Continue(poiDetail)
{
  try
  {
    if(typeof(poiDetail) != 'undefined' && poiDetail)
    {
      var imageHTML = "";
      
      if(typeof(poiDetail.Pictures) != 'undefined' && poiDetail.Pictures && poiDetail.Pictures.length > 0)
      {
        imageHTML = "<a href=\"../Secure/BidPage.aspx?pid=" + poiDetail.PropertyId + "\"><img src=\"../Public/PictureHandler.ashx?s=t&pid=" + poiDetail.Pictures[0].PictureId + "\" alt=\"" + poiDetail.SearchAuction.ShortAddress + "\" /></a>";
      }
      else
      {
        imageHTML = "<a href=\"../Secure/BidPage.aspx?pid=" + poiDetail.PropertyId + "\"><img src=\"../images/defaultNotAvailable_128.gif\" alt=\"" + poiDetail.SearchAuction.ShortAddress + "\" /></a>";
      }
      
        var innerHTML = "<div class=\"mapCallout\">" +
                        "   <div class=\"closeWindow\"><a href=\"#\" onclick=\"RemoveBaloons(); return false;\"><img src=\"../images/closeWindow.gif\" alt=\"close window\" /></a></div>" +
                        "   <table cellpadding=\"0\" cellspacing=\"0\" class=\"callout\">" +
                        "       <tbody>" +
                        "           <tr>" +
                        "               <td class=\"topLeft\"colspan=\"3\"></td>" +
                        "               <td class=\"topRight\"><img class=\"topRight\" src=\"../images/cornerCalloutRedTopRight.gif\" alt=\"\" /></td>" +        
                        "           </tr>" +
                        "           <tr>" +
                        "               <td class=\"centerLeft\"></td>" +
                        "               <td class=\"centerColumnLeft\">" + imageHTML + "<p><a href=\"../Secure/BidPage.aspx?pid=" + poiDetail.PropertyId + "\">Learn more...</a></p>" +
                        "               </td>" +
                        "               <td class=\"centerColumnRight\">" +
                        "                   <p><strong>Address: </strong><br/>" + poiDetail.SearchAuction.ShortAddress + "</p>" +
                        "                   <p><strong>Current Bid: </strong>" + poiDetail.CurrentBid + "</p>" +
                        "                   <p><strong>End Date: </strong>" + poiDetail.EndDate + "</p>" +
                        "                   <p><strong>End Time: </strong>" + poiDetail.EndTime + "</p>" +                
                        "               </td>" +
                        "               <td class=\"centerRight\"></td>" +           
                        "           </tr>" +
                        "           <tr>" +
                        "               <td class=\"centerLeft\"></td>" +
                        "               <td class=\"centerColumnLeft\"></td>" +
                        "               <td class=\"centerColumnRight\">" +
                        "                   <div class=\"buttonContainer\">" +
                        "                       <div class=\"buttonOffset\">" +
                        "                           <a href=\"../Secure/BidPage.aspx?pid=" + poiDetail.PropertyId + "\"><img src=\"../images/btnBidNow.gif\" width=\"104\" height=\"26\" border=\"0\" alt=\"Bid Now!\" /></a>" +
                        "                       </div>" +
                        "                   </div>" +
                        "               </td>" +
                        "               <td class=\"centerRight\"></td>" +           
                        "           </tr>" + 
                        "           <tr class=\"bottom\">" +
                        "               <td class=\"bottomLeft\" colspan=\"3\"></td>" +
                        "               <td class=\"bottomRight\"><img class=\"bottomRight\" src=\"../images/cornerCalloutRedBottomRight.gif\" alt=\"\" /></td>" +          
                        "           </tr>" +       
                        "       </tbody>" +
                        "</table>" +
                        "</div>";

      var balloon = document.getElementById("pinDiv");

      var newdiv = document.createElement("div");
      
      var menudiv = document.getElementById("pageMenu");
      
			newdiv.innerHTML = innerHTML;
			
			newdiv.style.position = "absolute";
			newdiv.style.zIndex = 10;		            

			balloon.appendChild(newdiv);
			menudiv.style.zIndex = "1";

      newdiv.style.top = (poiDetail.PixelY - 170) + "px";
      newdiv.style.left = (poiDetail.PixelX) + "px";
      newdiv.style.display = "block";
    }
  }
  catch(ex)
  {
    LogErrorMessage("ShowAuctionDetails_Continue: ", ex);
  }
}

function RemoveBaloons()
{
  try
  {
    var balloon = document.getElementById("pinDiv");

    if ( balloon && balloon.childNodes )
    {
      while ( balloon.childNodes.length > 0 )
      {
        balloon.removeChild(balloon.childNodes[0]);
      }
      var menudiv = document.getElementById("pageMenu");
      menudiv.style.zIndex = "2";
    }
  }
  catch(ex)
  {
    LogErrorMessage("RemoveBaloons: ", ex);
  }
}

function GetMapCoordinates()
{
  try
  {
    var latLongRect;
    
    switch(gMap.GetMapStyle())
    {
			case VEMapStyle.Oblique:
			case VEMapStyle.Birdseye:
			case VEMapStyle.BirdseyeHybrid:
				latLongRect = gMap.GetBirdseyeScene().GetBoundingRectangle();
				break;
			default:
				latLongRect = gMap.GetMapView();
				break;		
    }

    return latLongRect;
  }
	catch(ex)
	{
    LogErrorMessage("GetMapCoordinates: ", ex, true);
	} 
}

function NavigateMap(searchInput)
{
  try
  {
		var location = document.getElementById(searchInput);
		
		if(typeof(location) != 'undefined' && location.value.length > 0 && typeof(gMap) != 'undefined')
		{
			if(location.value.indexOf("UK") < 0)
			{
				location.value += ", UK";
			}
			
			gMap.Find(null, location.value);
		}
		
		return false;
  }
	catch(ex)
	{
    LogErrorMessage("NavigateMap: ", ex, true);
	} 
}

function SearchCriteria_OnEnter(searchInput, e)
{
  try
  {
		var keynum;
		
		if(window.event) // IE
		{
			keynum = e.keyCode;
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which;
		}

		if(keynum == 13)
		{
			var location = document.getElementById(searchInput);

			if(typeof(location) != 'undefined' && location.value.length > 0 && typeof(gMap) != 'undefined')
			{
				if(location.value.indexOf("UK") < 0)
				{
					location.value += ", UK";
				}

				gMap.Find(null, location.value);
			}
			
			return false;
		}
		
		return true;
  }
	catch(ex)
	{
    LogErrorMessage("onEnter: ", ex, true);
	} 
}


