var currentShape=null;
var detailPage;
var shapes = new Array();
var shapeLayer;
var dragListing=null;
var dragShape=null;
var moving=false;
var forceMap=0;
var endPanTimer = null;
var nagCount = 0;
var END_PAN_TIMER_DELAY = 900;

function MapView(latmin,latmax,lonmin,lonmax){this.lmin=latmin;this.lmax=latmax;this.lomin=lonmin;this.lomax=lonmax;}
function GetMapView(vemap) {
	var mv;
	if ((vemap.GetMapStyle() == VEMapStyle.Birdseye || vemap.GetMapStyle() == VEMapStyle.BirdseyeHybrid) && vemap.IsBirdseyeAvailable()) {
		var birdseyeScene = vemap.GetBirdseyeScene();
		mv = birdseyeScene.GetBoundingRectangle(); 
	}
	else {
		mv = vemap.GetMapView();
	}
	var ul = mv.TopLeftLatLong;
	var br = mv.BottomRightLatLong;
	return new MapView(br.Latitude, ul.Latitude, ul.Longitude, br.Longitude);	
}
function GetMapStyle(vemap) {
	var style;
	switch(vemap.GetMapStyle())
	{
		case VEMapStyle.Hybrid:style='hybrid';break;
		case VEMapStyle.Road:style='road';break;
		case VEMapStyle.Birdseye:style='birdseye';break;
		case VEMapStyle.BirdseyeHybrid:style='birdseyeh';break;
		default: style='hybrid';break;
	}
	return style;
}
function GetIconCode(type) {
	var url = 'http://content.2viewrealestate.com/icons/map/';
	switch(type) {
		case 'Land':url+='land';break;
		case 'Residential':url+='res';break;
		case 'Multi-Family':url+='res';break;
		case 'Commercial':url+='bus';break;
		case 'Mobile':url+='mob';break;
		default: url+='res';break;
	}
	return url+'.png';
}
function GetCenterLatLong(vemap) {
	if ((vemap.GetMapStyle() == VEMapStyle.Birdseye || vemap.GetMapStyle() == VEMapStyle.BirdseyeHybrid) && vemap.IsBirdseyeAvailable()) {
		var birdseyeScene = vemap.GetBirdseyeScene();
		var rect = birdseyeScene.GetBoundingRectangle(); ;
		var lon = rect.TopLeftLatLong.Longitude + (rect.BottomRightLatLong.Longitude - rect.TopLeftLatLong.Longitude) / 2.22;
		var lat = rect.TopLeftLatLong.Latitude + (rect.BottomRightLatLong.Latitude - rect.TopLeftLatLong.Latitude) / 2.22;
		
		return new VELatLong(lat,lon);
	}
	else {
		return vemap.GetCenter(); 
	}
} 

function MSMap(container,lat,lon,zoom,mapStyle,loadBox) {
	this.loadr = $(loadBox);
	this.vemap = new VEMap(container);
	this.searchLayer = new VEShapeLayer();	
	//this.vemap.SetDashboardSize(VEDashboardSize.Small);
	this.vemap.LoadMap(new VELatLong(lat,lon), zoom , mapStyle, false);
	
	var self = this;
	this.vemap.AttachEvent("onobliqueenter",function(e) { self.EndContinuousPanRequest(); });
	this.vemap.AttachEvent("onendpan",function(e) { self.EndContinuousPanRequest(); });
	this.vemap.AttachEvent("onendzoom",function(e) { forceMap = 0; self.EndContinuousPanRequest(); });
	this.vemap.AttachEvent("onmousemove",function(e) { self.MoveListing(e); });
	this.vemap.AttachEvent("onmouseover",function(e) { self.GetListingInfo(e); });
	this.vemap.AttachEvent("onmouseout",function(e) { self.LeaveShape(e); });
	this.vemap.AttachEvent("ondoubleclick",function(e) { self.OpenDetails(e); if (detailPage != null)return true; });
}

MSMap.prototype.EndContinuousPanRequest = function() {
   //If the timer is set, clear it and reset it
   if (endPanTimer != null) {
      window.clearTimeout(endPanTimer);
   }

   endPanTimer = window.setTimeout(map.MakeRequest, END_PAN_TIMER_DELAY);   
}

MSMap.prototype.MakeRequest = function() {
    endPanTimer = null;
	var self = map;
	if ((self.vemap.GetMapStyle() != VEMapStyle.Birdseye && self.vemap.GetMapStyle() != VEMapStyle.BirdseyeHybrid) || self.vemap.IsBirdseyeAvailable())
	{
		if ($("statusBox") != null)
		   $("statusBox").innerHTML="Loading...";
		   
		if ($("shareBox") != null)
		   $("shareBox").style.display="none";
		   
		var criteria = '';
		if($('hForm')) criteria += ajax.serialize($('hForm'));	
		if(keywords){criteria+='&keywords='+keywords;}
		else if($('sForm')){criteria+='&'+ajax.serialize($('sForm'));}
		if(area) criteria+='&area='+area;
		if(burb) criteria+='&suburb='+burb;
		
		var gc = GetMapView(self.vemap);
		criteria += '&latmin='+gc.lmin+'&latmax='+gc.lmax+'&lonmin='+gc.lomin+'&lonmax='+gc.lomax;

		if (forceMap == 1){ 
			criteria+="&forcemap="+forceMap; 
		}
		
		self.loadr.style.display = 'block';        
			
		ajax.post('/modules/mapsearch.aspx',function(r) { self.HandleResponse(r); },criteria);
	}
		
}
MSMap.prototype.HandleResponse = function(r) {
	eval(r);	
	
	this.vemap.DeleteAllShapeLayers();
	if (shapes.length != 0)
	{	
		shapeLayer = new VEShapeLayer();
		this.vemap.AddShapeLayer(shapeLayer);

		shapeLayer.AddShape(shapes); // bulk loading shapes
		shapes = new Array();	  
	}
	this.loadr.style.display = 'none';
}

MSMap.prototype.GetListingInfo = function(e) {

	var parms="";
	
	if (e.elementID) {
	   currentShape = this.vemap.GetShapeByID(e.elementID);	   
	   if (currentShape) {
		   var title = currentShape.GetTitle();
		   
		   if(title.indexOf("load:") != -1) {
          parms = "mlsId=" + title.substring(5);
		      parms += "&action=info";
          parms += "&pid=" + pid;
          parms += "&pinId=" + e.elementID;
          detailPage = detailPagePrefix + title.substring(5) + detailPageSuffix;
       
          var self = this;		      
          currentShape.SetTitle('<p><img src="http://content.2viewrealestate.com/images/loading.gif" /></p>');		         
       
          ajax.post('/modules/listingservice.aspx',function(r) { self.HandleListingResponse(r); },parms);
		   }
	   }
	}
}

MSMap.prototype.HandleListingResponse = function(r) {	
	if (currentShape) {	  
	  var descIdx = r.indexOf("desc:");
	  var title = r.substring(6, descIdx-1);
	  var description = r.substring(descIdx + 5);
	  
	  currentShape.SetTitle(title);
	  currentShape.SetDescription(description);
	  this.vemap.ShowInfoBox(currentShape);  
	  nagCount++;
	  
	  if (forcedSignup == "NAG" && nagCount >= 10) {
		jQuery("#detailNag").show();
		jQuery("#nagBody").fadeIn(800);
		nagCount = 0;
	  }
	}
}

MSMap.prototype.OpenDetails = function(e) {	
	if (e.elementID) {
	    currentShape = this.vemap.GetShapeByID(e.elementID);	   
	    if (currentShape && detailPage){
	        window.open(detailPage, '_blank');
		    detailPage='';
	    }
	}
}

MSMap.prototype.LeaveShape = function(e) {	
	if (e.elementID) {
	   currentShape = this.vemap.GetShapeByID(e.elementID);	   
	   if (currentShape)  { detailPage = null; }
	}
}
	   
// New method to improve performance
MSMap.prototype.AddItem = function(lat,lon,title,type,sold) {	
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
	if (sold=="1")
		shape.SetCustomIcon("http://content.2viewrealestate.com/icons/map/sold.gif");
	else
		shape.SetCustomIcon(GetIconCode(type));
		
    shape.SetTitle(title);
	shapes.push(shape);	
}

MSMap.prototype.GetCurrentLocation = function() {
	   
	var currentUrl;
	   
	if (location.href.lastIndexOf("/") != -1)
	   currentUrl = location.href.substring(0,location.href.lastIndexOf("/")) + "/";
	else
	   currentUrl = location.href;
	   
	var criteria = currentUrl + "&";
	
	if($('sForm')){criteria+=ajax.serialize($('sForm'));}
	//if(keywords){criteria+='&keywords='+keywords.replace(/ /g, "+");}	
	
	//if(area) criteria+='&area='+area;
	//if(burb) criteria+='&suburb='+burb;
	
	//if (location.href.indexOf("lat") == -1)
	  criteria += '&lat='+GetCenterLatLong(this.vemap).Latitude+'&lon='+GetCenterLatLong(this.vemap).Longitude + '&zoom=' + this.vemap.GetZoomLevel() + '&style=' + GetMapStyle(this.vemap);

	return criteria;
}

function MapListing(pinId,title,description,oldLat,oldLon,mlsId,mlsProviderId) { this.pinId=pinId;this.title=title;this.description=description;this.oldLat=oldLat;this.oldLon=oldLon;this.mlsId=mlsId;this.mlsProviderId=mlsProviderId;}

MSMap.prototype.ChangeListingPosition = function(pinId,mlsId,mlsProviderId) {
    if(dragShape == null){
        dragShape = this.vemap.GetShapeByID(pinId);
        dragListing=new MapListing(pinId,dragShape.GetTitle(),dragShape.GetDescription(),dragShape.GetPoints()[0].Latitude,dragShape.GetPoints()[0].Longitude,mlsId,mlsProviderId);
        
        moving=true;
        this.vemap.vemapcontrol.EnableGeoCommunity(true);
        
        dragShape.SetTitle("Draggable listing");
        dragShape.SetDescription("<p>Hold down the left mouse button to drag listing</p><div id=\"r_"+pinId+"\"><a href='#' onclick=\"map.SaveListingPosition('"+pinId+"');\">Save</a>&nbsp;<a href='#' onclick=\"map.CancelListingPositioning('"+pinId+"');\">Cancel</a></div>");
        this.vemap.HideInfoBox(dragShape);
        this.vemap.ShowInfoBox(dragShape);
		
        $("mapContainer").style.cursor="move";
    }
}

MSMap.prototype.SaveListingPosition = function(pinId) {
    var shape=this.vemap.GetShapeByID(pinId);
    if(shape && dragListing){
        shape.SetTitle(dragListing.title);
        shape.SetDescription(dragListing.description);
        
        var self=this;
        var parms="&action=saveposition";
        parms += "&mlsId=" + dragListing.mlsId;
        parms += "&pid=" + dragListing.mlsProviderId;
        parms += "&lat=" + dragShape.GetPoints()[0].Latitude;
        parms += "&lon=" + dragShape.GetPoints()[0].Longitude;
        ajax.post("/modules/listingservice.aspx", function(r){ self.SaveResponse(r); }, parms);
    }
}
MSMap.prototype.SaveResponse = function(r) {
    var targetDiv="r_"+dragListing.pinId;
    $(targetDiv).innerHTML=r;
    
    moving=false;
    this.vemap.vemapcontrol.EnableGeoCommunity(false);
    $("mapContainer").style.cursor="pointer";
    dragShape=null;
    dragListing=null;
}
MSMap.prototype.CancelListingPositioning = function(pinId) {
    var shape=this.vemap.GetShapeByID(pinId);
    if(shape && dragListing){
        shape.SetTitle(dragListing.title);
        shape.SetDescription(dragListing.description);
        shape.SetPoints(new VELatLong(dragListing.oldLat,dragListing.oldLon));
        this.vemap.HideInfoBox(dragShape);
        this.vemap.ShowInfoBox(dragShape);
        
        moving=false;
        this.vemap.vemapcontrol.EnableGeoCommunity(false);
        $("mapContainer").style.cursor="pointer";
        dragShape=null;
        dragListing=null;
    }
}
MSMap.prototype.MoveListing = function(e) {
	if (this.vemap.GetMapStyle() != VEMapStyle.Birdseye && this.vemap.GetMapStyle() != VEMapStyle.BirdseyeHybrid) {
	    var loc = this.vemap.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
	    if(dragShape && moving && e.leftMouseButton){
	        this.vemap.HideInfoBox(dragShape);
	        dragShape.SetPoints(loc);
	    }
	}
}

MSMap.prototype.LocalSearch = function(searches) {
	this.vemap.DeleteShapeLayer(this.searchLayer);
	this.searchLayer = new VEShapeLayer();	
	
	var options = $(searches).getElements("input[type=checkbox]");
	
	if (options.length != 0) {
		for(var i = 0;i < options.length; i++) {
		  if (options[i].checked) {	    
		    if(options[i].id != ''){try{this.vemap.Find(options[i].id,null,VEFindType.Businesses,this.searchLayer);}
		    catch(e){alert(e.message);}
		    }
		  }
		}
		
		this.vemap.AddShapeLayer(this.searchLayer);
	}
}

MSMap.prototype.DisposeMap = function() {
   if(this.vemap) this.vemap.Dispose();
}

function AddVEUsageTracker(map) {
    tileTrackerSpec = new VETileSourceSpecification("VEUsageTracker", "/modules/veusagetracker.ashx?qkey=%4");
    tileTrackerSpec.Opacity = 0;
		
    if (map.GetTileLayerByID("VEUsageTracker") == null)
        map.AddTileLayer(tileTrackerSpec);
}