/// <reference path="BMBuyerPortal/VEJS/VeJavaScriptIntellisenseHelper.js" />

var _map = null;
var _mapLatLong = null; // VELatLong object
var _shapeSelectedShapes = new Array(); // array of VEShape objects
var _drawLayer = new VEShapeLayer();
var _geoRssLayer = new VEShapeLayer();
var _searchValue = "";
var _notebookCookie = null;

// Variables used for searching functions
var _searchPinId = 12;
var _displayListingSearchWarning = true;

// ###################################
// ########## Map Functions ##########

function mapFindCallback(a,b,c,d,e) {
     if(IsNullOrEmpty(DefaultSearchId) || DefaultSearchId==0 || IsNullOrEmpty(DefaultSearchName)) {
        //alert('run search1');
        GetListings();
    }
}
function SetMap(lat,lon)
{
    _map = new VEMap("divMap"); 
    var LL = new VELatLong(lat,lon);
    var zoom = 10;
    var style = VEMapStyle.Road;
    var fixed = false;
    var mode = VEMapMode.Mode2D;
    var showSwitch = false;
    if(IsNullOrEmpty(lat)||lat=="0"||IsNullOrEmpty(lon)||lon=="0") {
        try
         {
            _map.LoadMap(LL,zoom,style,fixed,mode,showSwitch);
            _map.Find(null, $('MapReferenceCity').value, null, null, null, null, null, null, null, null, mapFindCallback);

         }
         catch(e)
         {
            //alert(e.message);
         }
    }
    else {
        _map.LoadMap(LL,zoom,style,fixed,mode,showSwitch);    
        _map.SetCenterAndZoom(LL, zoom);

        if(IsNullOrEmpty(DefaultSearchId) || DefaultSearchId==0 || IsNullOrEmpty(DefaultSearchName)) {
            //alert('run search2');
            GetListings();
        }
    }

    _map.ClearInfoBoxStyles();
    
    // Disable point/polygon merge
    _map.EnableShapeDisplayThreshold(false);

    // Set map events
    _map.AttachEvent("onclick", OnMouseClick);
 	_map.AttachEvent("onchangeview", OnMapViewChanged); 

    // Set layer titles
    _drawLayer.SetTitle("Draw");
    _geoRssLayer.SetTitle("Boundaries");
    
    // Add layers
    _map.AddShapeLayer(_drawLayer);
    _map.AddShapeLayer(_geoRssLayer);
    
    _map.AttachEvent("onmousemove", MapMouseMove);
    
    //setTimeout("clearAll()",500);  //causes blue screen on list view
}

//############################ Hover Method for ajax hover box  ##################################################
function MapMouseMove(e)
{ 
    if (e.elementID != null)
    {          
        var shape = _map.GetShapeByID(e.elementID);
        var layer = shape.GetShapeLayer(); //temp
        if (shape.GetTitle().indexOf("LOAD:") != -1)
        {
            var divHover; 
            if (IsNullOrEmpty(shape.GetDescription()))
            {
                divHover = document.getElementById('divPreviewHover'); 
                document.getElementById('divShapeHoverText').innerHTML = '';
            }
            else
            {
	            divHover = document.getElementById('divShapeHover'); 
                document.getElementById('divShapeHoverText').innerHTML = shape.GetDescription();
            }
            var pixel = _map.LatLongToPixel(new VELatLong(shape.Latitude,shape.Longitude));
            divHover.style.display="block";
            divHover.style.top=pixel.y+'px';
            divHover.style.left=pixel.x+5+'px';
        }
    }
    else
    {
        document.getElementById('divPreviewHover').style.display='none';
        document.getElementById('divShapeHover').style.display='none';
    }
}
function closeHover(){
    document.getElementById('divListingHoverText').innerHTML = '';
    document.getElementById('divListingHover').style.display='none';
    document.getElementById('divMainHover').style.display='none';
    document.getElementById('divShapeHoverText').innerHTML='';
    document.getElementById('divShapeHover').style.display='none';
    }
function OnMouseClick(e)
{
    // Display current position
    SetMapLatLong(e.mapX, e.mapY);

    // Check to see if user clicked on a shape
    if (e.elementID)
    {      // alert(e.elementID + "\n \n" + _map.GetShapeByID(e.elementID).Title);
          //  return;
        var shape = _map.GetShapeByID(e.elementID);
        var layer = shape.GetShapeLayer();
        if (layer != _drawLayer && layer != _geoRssLayer) {
            if (shape.GetTitle().indexOf("LOAD:") != -1)
            {
                var id = parseInt(shape.GetTitle().substring(5));
                var entityId = shape.GetTitle().split(",")[1];
                var pixel = _map.LatLongToPixel(new VELatLong(shape.Latitude,shape.Longitude));
	            var obj =document.getElementById('divListingHover'); 
                obj.style.display="block";
                obj.style.top=pixel.y-48+'px';
                if(pixel.x<290) {
                    obj.style.left=pixel.x+5+'px';
                    document.getElementById('divListingHoverLeft').innerHTML="<img src=\"../App_Themes/Default/Images/Map/flag_left_large.png\" height=\"100\" width=\"11\" />";
                    document.getElementById('divListingHoverRight').innerHTML="<img src=\"../App_Themes/Default/Images/Map/flag_left_close_large.png\" height=\"100\" width=\"2\" />";
                    }
                else {
                    obj.style.left=pixel.x-275+'px';
                    document.getElementById('divListingHoverLeft').innerHTML="<img src=\"../App_Themes/Default/Images/Map/flag_right_close_large.png\" height=\"100\" width=\"2\" />";
                    document.getElementById('divListingHoverRight').innerHTML="<img src=\"../App_Themes/Default/Images/Map/flag_right_large.png\" height=\"100\" width=\"11\" />";
                    }
                launchHoverBox(id,entityId);
            }
            else {
                var id = parseInt(shape.GetTitle());
                var pixel = _map.LatLongToPixel(new VELatLong(shape.Latitude,shape.Longitude));
	            var obj =document.getElementById('divMainHover'); 
                obj.style.display="block";
                obj.style.top=pixel.y-110+'px';
                obj.style.left=pixel.x+5+'px';
                document.getElementById('divMainHoverText').innerHTML = "<span style=\"float:right;margin-top:2px;margin-right:2px;\"><a href=\"javascript:closeHover();\"><img src=\"../App_Themes/Default/Images/Map/square_X.png\" border=\"0\"></a></span>"
                                                                      + "<b>"+shape.GetTitle()+"</b><br />"+shape.GetDescription();
            }
        }
        
        if (layer == _geoRssLayer) {
            document.getElementById('activeBoundary').style.display = 'block';
            document.getElementById('activeBoundary').innerHTML = _map.GetShapeByID(e.elementID).Title;
        }
        
        if (layer == _drawLayer || layer == _geoRssLayer)
        {
            // Get status of other pressed keys
            var shiftKeyPressed = GetKeyStatus("shift", e);
            var ctrlKeyPressed = GetKeyStatus("ctrl", e);

            // Check for click modifier keys
            if (shiftKeyPressed)
            {
                SelectShape(shape);
            }
            else if (ctrlKeyPressed)
            {
                // Check to see if item is already selected
                if (IsSelected(shape))
                {
                    DeselectShape(shape);
                }
                else
                {
                    SelectShape(shape);
                }
            }
            else
            {
                // Loop through all layers
                var layerCount = _map.GetShapeLayerCount();
                for(var layerCounter = 1 ; layerCounter < layerCount; layerCounter++)
                {
                    DeselectAllShapes(_map.GetShapeLayerByIndex(layerCounter));
                }

                SelectShape(shape);
            }
            //alert('get listings 1');
            GetListings();
        }
    }
}

var t;
function OnMapViewChanged(e)
{
    // Display info in status bar
    self.status = ("Zoom: " + _map.GetZoomLevel());
    setMapView();
    
    if($('searchMode').value=='Map') {
            try
            {   
                if($('chkAutoSearch').checked)
                {
                    if( _search.Criteria == "Basic" ||  _search.Criteria == "Advanced") {
                        t=setTimeout("DoUpdate()",1000);
                    }
                }
            }
            catch(e)
            {
                $("divSearching").innerHTML = e.description;
            }
    }
    closeHover();
}

function DoUpdate()
{	
            //HideListingSearchWarning();
            clearTimeout(t);
            GetListings();
}

function SetMapLatLong(mapX, mapY)
{
    // Get the pixel coordinates of where the map was clicked
    var pixel = new VEPixel(mapX, mapY);
    _mapLatLong = _map.PixelToLatLong(pixel);
    
    // Display info in status bar
    self.status = ("Latitude: " + _mapLatLong.Latitude + " Longitude: " + _mapLatLong.Longitude + " Zoom: " + _map.GetZoomLevel());
}
function zoomIn(task)
{
	var zoom = _map.GetZoomLevel() + 2;	
	var center = _map.GetCenter();
	_map.SetCenterAndZoom(center, zoom);	//zoom map in to correct level
    if(!(task===undefined)) {eval(task);}
}
function GetKeyStatus(keyName, e)
{
    // NOTE: Assumes browser is newer than Netscape 4!!!
    var evt = navigator.appName=="Netscape" ? e:event;
    switch (keyName)
    {
        case "shift":
            return evt.shiftKey;
            
        case "alt":
            return evt.altKey;
            
        case "ctrl":
            return evt.ctrlKey;
    }
}

function SetPointer(strPtr)
{
	var mapDiv = document.getElementById("divMap");
	mapDiv.style.cursor = strPtr;
}

function FindNear(what, where)
{   
	try
	{  
		if (where != null && where != "")
		{
		    // VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
		    // http://msdn.microsoft.com/en-us/library/bb429645.aspx
			_map.Find(what, where);
		}
		else
		{
		    alert("No 'where' provided for FindNear map search.");
		}
	}
	catch(err)
	{
		alert(err.description);
	}   
}

function ShowPin(pinID)
{  
    var pin = _map.GetShapeByID(pinID);  

    if (pin != null)
    {
        _map.ShowInfoBox(pin);
    }
}

// http://blogs.msdn.com/virtualearth/archive/2008/04/08/geocoding-with-virtual-earth.aspx
function GetCoordinates(layer, resultsArray, places, hasMore, veErrorMessage)
{
    if (places != null)
    {
        findPlaceResults = places[0].LatLong;
        var myShape = new VEShape(VEShapeType.Pushpin, findPlaceResults);
        myShape.SetDescription(_searchValue + "<br/>" + findPlaceResults.toString());
        _map.AddShape(myShape);
    }
} 

//function ClearMap()
//{ 
//    // Clear map
//    _map.Clear()
//    
//    // Reinitialize array
//    //_shapeSelectedShapes = new Array();

//    // Delete all shapes from all layers
//    //_map.DeleteAllShapes();

//    // Clear number of matching shapes
//    //document.getElementById('divSearching').innerHTML = "";
//    
//    // Reset drop down lists
//    if (document.getElementById("lstBoundaries"))
//    {
//        //document.getElementById("lstBoundaries").options[0].selected = true;
//        //UpdateShapeList();
//    }
//}

function clearAll()
{	 
	deletePoi();
	deleteListings();
	deleteSolds();
	deleteSchools();
	clearShapeLayers();
	clearGrid();
	//_map.Clear();  //causes sporadic errors with shape boundaries
}

function deletePoi() {
	if(typeof _poiLayer != 'undefined') {
		_poiLayer.DeleteAllShapes();
		}
    document.getElementById('poiResults').innerHTML='';
}

function deleteListings() {
	if(typeof _listingLayer != 'undefined') {
		_listingLayer.DeleteAllShapes();
		}
	clearGrid();
	clearSummary();
	clearList();
}

function deleteSolds() {
	if(typeof _soldLayer != 'undefined') {
		_soldLayer.DeleteAllShapes();
		}
}
function deleteSchools() {
	if(typeof _schoolLayer != 'undefined') {
		_schoolLayer.DeleteAllShapes();
		}
}
function clearShapeLayers() {

	if(typeof _drawLayer != 'undefined') {
		_drawLayer.DeleteAllShapes();
		}
	if(typeof _geoRssLayer != 'undefined') {
		_geoRssLayer.DeleteAllShapes();
		}
		
   // Create layers
   _drawLayer = new VEShapeLayer();
   _geoRssLayer = new VEShapeLayer();
    
    if (_map != null)
    {
        // Add layer to map
        _map.AddShapeLayer(_geoRssLayer);
        _map.AddShapeLayer(_drawLayer);
    }

	// Reinitialize array
    _shapeSelectedShapes = new Array();
    
	document.getElementById('activeBoundary').style.display='none';
    // Reset drop down lists    
    //document.getElementById("lstBoundaries").options[0].selected = true;
    UpdateShapeList();
}

function validateValues() {
  var msg=null;
    if((_search.PriceMin!=null) && isNaN(_search.PriceMin)){msg='Minimum price must be numeric';}
    if ((_search.PriceMax != null) && isNaN(_search.PriceMax)) { msg = 'Maximum price must be numeric'; }
    if ( isMinLarger( _search.PriceMin, _search.PriceMax)) {msg='Invalid price range';}
    if ( isMinLarger( _search.BedMin, _search.BedMax)){msg='Invalid bedrooms range';}
    if ( isMinLarger(_search.BathMin, _search.BatMax)) { msg = 'Invalid bathrooms range'; }
    if ( isMinLarger(_search.AcresMin, _search.AcresMax)) { msg = 'Invalid acres range'; }
    if ( isMinLarger(_search.UnitsMin, _search.UnitsMax)) { msg = 'Invalid units range'; }
    if ( isMinLarger(_search.SqFtMin, _search.SqFtMax)) { msg = 'Invalid SqFt range'; }
    if ( isMinLarger(_search.YearBuiltMin, _search.YearBuiltMax)) { msg = 'Invalid Year-Built range'; }
    return msg == null? 'success': ErrorCls.CreateHtmlErrorMessage(msg); 
}

function isMinLarger(min, max) {
    return min = null || max == null? false: ( parseInt(min) > parseInt(max) ? true : false);
}

function clearList() {
    $('divList').innerHTML = '';
}

function launchSaveSearch() {
    if (_search.ListingTypeId == null) {
        alert("Please select a property type\nbefore saving your search.");
        return;
    }

    var str='';
    if(_search.SearchID != null) { //show update OR new search
        str += "<div style=\"height:80px;width:155px;text-align:center;border:1px solid #dedede;float:left;\">Update Saved Search:"
        + "<span>"
        + "<input type=\"text\" id=\"existingSavedSearchName\" value=\""+_search.SearchName+"\" disabled/>"
        + "<input type=\"hidden\" id=\"existingSavedSearchId\" value=\""+_search.SearchID+"\"/>"
        + "</span>"
        + "<br /><br />"
        + "<a href=\"javascript:hideSavedSearchPopUp();updateExistingSavedSearch()\"><img src=\"../App_Themes/Default/Images/button_Save_green.png\"></a>"
        + "</div>"
        + "<div style=\"height:80px;width:35px;float:left;\"><div style=\"margin-top:30px;font-size:1.4em;font-weight:bold;\">&nbsp;OR&nbsp;</div></div>"
        + "<div style=\"height:80px;width:155px;text-align:center;border:1px solid #dedede;float:left;\">Create New Saved Search:"
        + "<span><input type=\"text\" id=\"newSavedSearchName\" /></span>"
        + "<br /><br />"
        + "<a href=\"javascript:hideSavedSearchPopUp();newSavedSearch()\"><img src=\"../App_Themes/Default/Images/button_Save_green.png\"></a>"
        + "</div>";
    }
    else {  //show NEW search only
        str += "<div style=\"margin:top:25px;margin-left:25px;\">New Saved Search: <input type=\"text\" id=\"newSavedSearchName\" />"
            + "<a href=\"javascript:hideSavedSearchPopUp();newSavedSearch()\"><img style=\"position:relative;top:2px;margin-left:5px;\" src=\"../App_Themes/Default/Images/button_Save_green.png\"></a>"
            + "</div>";
    }
    //show checkboxes
    str += "<div style=\"clear:both;\">"
    + "<br /><input type=\"checkbox\" id=\"chkQuickAlert\" checked /> <span>Receive Quick Alert<sup>TM</sup> emails regarding new listings.</span>"
    + "<br /><input type=\"checkbox\" id=\"chkMapBoundingBox\" checked /> <span>Save current map view</span>"
    + "<br /><br />"
    + "<input class=\"wireframe_popup_closebtn\" type=\"image\" src=\"/App_Themes/Default/Images/registration_buttonclose.png\" onclick=\"hideSavedSearchPopUp();return false;\" />"
    + "</div>";
    $("divPromptSaveSearchInner").innerHTML=str;
    $("divPromptSaveSearch").style.display="block";
}

function runCurrentSearch(update) {
   _search.Criteria='Basic';
   _search.ShowSearchCriteria();
   if (  update )
       _advancedSearch.CollectAllValues();
   else
       _advancedSearch.DisplayLeftSideLinks();
   GetListings();    
}
