
//##################################################################
//## Object References
//##################################################################

var oMap; // object reference to mapping
var oPropertyTrackerManager = ( typeof EstateWeb_Objects_TrackerManager != "undefined" ? new EstateWeb_Objects_TrackerManager() : null );
var aProperties = new Array(); // array to hold properties in search result
var _map_center_latitude = 0;
var _map_center_longitude = 0;
var _map_minheight = 400;
var __searchResultMapping_isInitialised = false;
var _map_callback_function = null;
var omarkermanager = null;
var omarkers = new Array();
var _map_initialheight = 0;
var _map_event = null;

var _map_icons_letting_available = "images/controls/map/propertypinletting.png";
var _map_icons_sales_available = "images/controls/map/propertypin.png";
var _map_icons_letting_status = "images/controls/map/propertypin.png";
var _map_icons_sales_status = "images/controls/map/propertypin.png";
var _map_icons_commercial = "images/controls/map/propertypinCommercial.png";

//##################################################################
//## Object extension
//##################################################################

EstateWeb_Objects_Property.prototype.DrawMarker = SearchResultMapping_Property_DrawMarker;
EstateWeb_Objects_Property.prototype.Marker = null;
EstateWeb_Objects_Property.prototype.MarkerBubble = null;

var _initialviewtype = 0; // map

function SearchResultMapping_Initialise(){
	//this must be called first, this will initialise the map using the correct view
	//if they have a cached view then use that
	//if ( HttpManager.Request.Cookies.Get("EstateWeb_Mapping_SearchResults_Viewtype") ){
	//	_initialviewtype = parseInt( HttpManager.Request.Cookies.Get("EstateWeb_Mapping_SearchResults_Viewtype") );
	//}else{
	//	//if the page number is greater than 1 or listview param passed then default to list view
	//	if ( HttpManager.Request.QueryString("page") ){
	//		if ( parseInt( HttpManager.Request.QueryString("page") ) > 0 ){ _initialviewtype = 1 }
	//	}
	//	if ( HttpManager.Request.QueryString("lv") ){
	//		_initialviewtype = 1;
	//	}
	//} centerSearchpnlLoading
	HttpManager.Document.GetObject("pnlGoogleMap").style.height = HttpManager.Document.GetObject("leftSearch").offsetHeight +"px";
	HttpManager.Document.GetObject("pnlLoading").style.height = HttpManager.Document.GetObject("leftSearch").offsetHeight + "px";
	_map_initialheight = parseInt(HttpManager.Document.GetObject("pnlGoogleMap").offsetHeight);
	SearchResultMapping_OnLoad();
}


function SearchResultMapping_OnLoad(forceviewtype){
	if ( typeof forceviewtype != "undefined" ){
		_initialviewtype = forceviewtype;
	}
	SearchResultMapping_ToggleView( _initialviewtype );
	if ( _initialviewtype == 0 & !__searchResultMapping_isInitialised ){
		if ( location.href.toLowerCase().indexOf("search.aspx") > 0 ){
			var ilistingtype = HttpManager.Request.QueryString("ListingType");
			var iminimumprice = HttpManager.Request.QueryString("minprice");
			var imaximumprice = HttpManager.Request.QueryString("maxprice");
			var sarea = HttpManager.Request.QueryString("area")
			var ibedrooms = HttpManager.Request.QueryString("bedrooms");
			var squicksearch = HttpManager.Request.QueryString("quicksearch");
			var irentperiod = HttpManager.Request.QueryString("rentperiod");
			var ipage = ( HttpManager.Request.QueryString("page").length > 0 ? HttpManager.Request.QueryString("page") : 1 );
			var iperpage = ( HttpManager.Request.QueryString("pp").length >0 ? HttpManager.Request.QueryString("pp") : 10 );
			var category = 1
			if (window.location.href.indexOf("commercial") > 0){
			    category = 2
			}
			Advanced.GetSearchData(ilistingtype,iminimumprice,imaximumprice,sarea,ibedrooms,squicksearch,irentperiod,iperpage,ipage,category, SearchResultMapping_OnInit);	
		}else{
			PropertyCartManager.PropertyInformation(SearchResultMapping_OnInit);
		}	
	}
	
}

__searchResultMapping_isInitialised = false;

function SearchResultMapping_CallbackFunction(){
	if ( _map_callback_function ){
		eval(_map_callback_function);
		_map_callback_function = null;
	}
}

function SearchResultMapping_OnInit(oproperties){
	if ( GBrowserIsCompatible() ){
		if ( !__searchResultMapping_isInitialised ){
			if ( oproperties.value ){
				oMap = new GMap2(HttpManager.Document.GetObject("pnlGoogleMap"));
				//events
				GEvent.addListener( oMap, 'dragend', function(){ SearchResultMapping_Map_Pointer_OnDragEnd() } );
				GEvent.addListener( oMap, 'zoomend', function(){ SearchResultMapping_Map_Pointer_OnZoomEnd() } );
				oMap.addControl(new GSmallMapControl());
				oMap.addControl(new GMapTypeControl());
				oMap.setCenter(new GLatLng(-2.0015, 53.4967),11);
				oMap.checkResize();
				//get properties
					for ( var i = 0; i < oproperties.value.length; i ++ ){
						var oitem = oproperties.value[i];
						if ( oitem[1] && oitem[2] ){
							var oProperty = new EstateWeb_Objects_Property();
							oProperty.PropertyListingType = oitem[3];
							oProperty.PropertyReference = oitem[0];
							oProperty.PropertyLatitude =  parseFloat(oitem[1])
							oProperty.PropertyLongitude = parseFloat(oitem[2])
							oProperty.PropertyStatusDisplay = (oitem[4] ? oitem[4] : "");
							oProperty.PropertyFormattedPrice = oitem[5];
							oProperty.PropertyAddress = oitem[6];
							oProperty.PropertyCategory = oitem[7];
							aProperties[aProperties.length] = oProperty;
						}
					}
				if ( aProperties.length > 0 ) {
					//now work out the max bounds of the map
					var nlat;
					//get max lat
					aProperties.sort(sortLatitudeDESC);
					nlat = aProperties[0].PropertyLatitude;
					var slat;
					//get min lat
					aProperties.sort(sortLatitudeASC);
					slat = aProperties[0].PropertyLatitude;
					var elon;
					//get max lon
					aProperties.sort(sortLongitudeDESC);
					elon = aProperties[0].PropertyLongitude;
					var wlon;
					//get min lon
					aProperties.sort(sortLongitudeASC);
					wlon = aProperties[0].PropertyLongitude;
					//
					_map_center_latitude = ((nlat+slat)/2);
					_map_center_longitude = ((elon+wlon)/2);
					oMap.setCenter(new GLatLng(_map_center_latitude, _map_center_longitude),5);
					var obound1 = new GLatLng(nlat,wlon);
					var obound2 = new GLatLng(slat,elon);
					
					oMap.setZoom(oMap.getBoundsZoomLevel(new GLatLngBounds(obound1,obound2))); 
					
					var obounds = oMap.getBounds();
					oMap.savePosition();
					omarkermanager = new GMarkerManager(oMap);
					SearchResultMapping_Map_DrawMarkers();
				}else{
					//notihng to load
					SearchResultMapping_Map_Loaded();
				}
			}else{
				SearchResultMapping_Map_NoProperties();
			}
			__searchResultMapping_isInitialised = true;
		}
	}
}

var __searchResultMapping_Map_DrawMarkers_Position = 0;

function SearchResultMapping_Map_Loaded(){
	setTimeout("HttpManager.Document.GetObject(\"pnlLoading\").style.display = \"none\";", 800);
	SearchResultMapping_CallbackFunction();
	//show last looked at property if we have that
	if ( HttpManager.Request.Cookies.Get("EstateWeb_SearchResults_Mapping_LastProperty") ){
		SearchResultMapping_Property_ShowMarker( HttpManager.Request.Cookies.Get("EstateWeb_SearchResults_Mapping_LastProperty") );	
	}
}


function SearchResultMapping_Map_NoProperties(){
	HttpManager.Document.GetObject("pnlLoading").style.display = "none";
	if ( HttpManager.Document.GetObject("tdMapView") ){
		HttpManager.Document.GetObject("tdMapView").style.display = "none";
	}
	SearchResultMapping_ToggleView(1);
}

function SearchResultMapping_Map_DrawMarkers(){
	var imax = parseInt(HttpManager.Document.GetObject("pnlBarContainer").style.width.replace("px",""));
	
	//draws all markers on the map
	if ( aProperties[__searchResultMapping_Map_DrawMarkers_Position].Marker == null ){
		aProperties[__searchResultMapping_Map_DrawMarkers_Position].DrawMarker();
		

		var iinterval = imax/(aProperties.length+1);
		HttpManager.Document.GetObject("pnlBar").style.width = ( (__searchResultMapping_Map_DrawMarkers_Position+1) * iinterval)+"px";

		__searchResultMapping_Map_DrawMarkers_Position ++;
		if ( __searchResultMapping_Map_DrawMarkers_Position <= (aProperties.length-1)){
			setTimeout("SearchResultMapping_Map_DrawMarkers();", 5);
		}else{
			HttpManager.Document.GetObject("pnlBar").style.width = imax+"px";
			omarkermanager.addMarkers( omarkers,1,17 );
			omarkermanager.refresh();
			SearchResultMapping_Map_Loaded();
		}
	}
}

function SearchResultMapping_Map_Pointer_OnClick(oMarker){
	//store last looked at property
	HttpManager.Request.Cookies.Add("EstateWeb_SearchResults_Mapping_LastProperty", oMarker.Property.PropertyReference);
	//load brief property details
	if ( oMarker.Property.MarkerBubble == null ){
		var response;
		if ( location.href.toLowerCase().indexOf("search.aspx") >= 0 ){
			response = GoogleMappingSearchResults.GetPointerDetails( oMarker.Property.PropertyReference );
		}else{
			response = GoogleMappingSearchResults.GetPointerBriefDetails( oMarker.Property.PropertyReference );
		}
		oMarker.Property.MarkerBubble = response.value;
	}
	oMap.openInfoWindowHtml( new GLatLng( oMarker.Property.PropertyLatitude, oMarker.Property.PropertyLongitude ), oMarker.Property.MarkerBubble );
	///oMarker.openInfoWindowHtml( oMarker.Property.MarkerBubble );

}

function SearchResultMapping_Map_Pointer_ViewProperty_OnClick(PropertyReference){
	//SearchResultMapping_Map_ViewProperty_OnView(PropertyReference);
	//location.href = "Viewproperty.aspx?adid="+PropertyReference;
	//if ( oPropertyTrackerManager ){
	//	oPropertyTrackerManager.Add(PropertyReference);
	//	//instruct the recentproperties tabbing control to refresh itself
	//	RecentProperties_Refresh(PropertyReference);	
	//}
}

function SearchResultMapping_Map_ViewProperty_OnView(PropertyReference){
	/*if (enableHeaders.length > 0){
	}*/
	//create a div with an IFRAME to display the property details
	SearchResultMapping_ToggleView(1);
	if ( HttpManager.Document.GetObject("pnlPropertyFullDetails").childNodes.length > 0 ){
		for ( var i = 0; i < HttpManager.Document.GetObject("pnlPropertyFullDetails").childNodes.length; i ++ ){
			HttpManager.Document.GetObject("pnlPropertyFullDetails").removeChild( HttpManager.Document.GetObject("pnlPropertyFullDetails").childNodes[i] );
		}
	}
	var ocontainer = document.createElement("div");
	var oframe = document.createElement("iframe");
	oframe.name = "frmFullDetails";
	oframe.id = "frmFullDetails";
	oframe.width = "100%";
	oframe.height = 712;
	oframe.scrolling = "no";
	oframe.frameBorder = "0";
	oframe.src = "viewproperty.aspx?adid=" + PropertyReference +"&eh=1";
	
	ocontainer.appendChild( oframe );
	HttpManager.Document.GetObject("pnlPropertyFullDetails").appendChild( ocontainer );
	Map_ViewProperty_ToggleView(1);
	SearchResultMapping_Map_TrackProperty(PropertyReference);
	window.scrollTo(0,0);
}

function SearchResultMapping_Map_ViewProperty_OnLoad(doc){
	var inewheight = parseInt(doc.getElementById("pnlmarker").offsetTop);
	//make sure height isn't less than map height
	if ( inewheight < _map_initialheight ){
		inewheight = _map_initialheight;
	}
	document.getElementById("frmFullDetails").height = inewheight + "px";
	//HttpManager.Document.GetObject("pnlGoogleMap").style.height = inewheight + "px";
}

function SearchResultMapping_Map_TrackProperty(propertyreference){
	if ( oPropertyTrackerManager ){
		oPropertyTrackerManager.Add(propertyreference);
		//instruct the recentproperties tabbing control to refresh itself
		RecentProperties_Refresh(propertyreference);	
	}
}

function Map_ViewProperty_ToggleView(val){
	switch ( val ){
		case 0:
			//map view
			HttpManager.Document.GetObject("pnlPropertyFullDetails").style.display = "none";
			HttpManager.Document.GetObject("pnlBackToMap").style.display = "none";
			HttpManager.Document.GetObject("pnlGoogleMap").style.height = _map_initialheight+"px";
			HttpManager.Document.GetObject("pnlGoogleMap").style.display = "block";
			break;
		case 1:
			//full details
			HttpManager.Document.GetObject("pnlPropertyFullDetails").style.display = "block";
			HttpManager.Document.GetObject("pnlBackToMap").style.display = "block";
			HttpManager.Document.GetObject("pnlGoogleMap").style.display = "none";
			break;
	}
}

function SearchResultMapping_ToggleView(val){
	//store the view type
	//HttpManager.Request.Cookies.Add("EstateWeb_Mapping_SearchResults_Viewtype", val);
	//switch( val ){
	//	case 0:
	//		if ( HttpManager.Document.GetObject("pnlResults") ) {
	//			HttpManager.Document.GetObject("pnlResults").style.display = "none";
	//		}
	//		if ( HttpManager.Document.GetObject("pnlMap") ) {
	//			HttpManager.Document.GetObject("pnlMap").style.display = "block";
	//		}
	//		if ( HttpManager.Document.GetObject("imgMapView") ){
	//			HttpManager.Document.GetObject("imgMapView").src = "Images/switch-mapview.gif"; //selected
	//		}
	//		if ( HttpManager.Document.GetObject("imgListView") ){
	//			HttpManager.Document.GetObject("imgListView").src = "Images/list-view.gif"; //unselected
	//		}
	//		HttpManager.Document.GetObject("pnlSearchPagingHeader").style.display = "none";
	//		HttpManager.Document.GetObject("pnlSearchPagingFooter").style.display = "none";
	//		Map_ViewProperty_ToggleView(0);
	//		break;
	//	case 1:
	//		if ( HttpManager.Document.GetObject("pnlResults") ){
	//			HttpManager.Document.GetObject("pnlResults").style.display = "block";
	//		}
	//		if ( HttpManager.Document.GetObject("pnlMap") ){
	//			setTimeout("HttpManager.Document.GetObject('pnlMap').style.display = 'none'", 50);
	//		}
	//		if ( HttpManager.Document.GetObject("imgMapView") ){
	//			HttpManager.Document.GetObject("imgMapView").src = "Images/switch-mapview.gif"; //unselected
	//		}
	//		if ( HttpManager.Document.GetObject("imgListView") ){
	//			HttpManager.Document.GetObject("imgListView").src = "Images/list-view.gif"; //selected
	//		}
	//		HttpManager.Document.GetObject("pnlSearchPagingHeader").style.display = "block";
	//		HttpManager.Document.GetObject("pnlSearchPagingFooter").style.display = "block";
	//		Map_ViewProperty_ToggleView(0);
	//		break;
	//}
	//when we toggle if there are no properties avaialble then hide the map view
	//if ( HttpManager.Document.GetObject("_ctl1_CenterRegion__ctl0_txtResultcount").innerHTML.length == 0 ){
	//	if ( HttpManager.Document.GetObject("imgMapView") ){
	//		HttpManager.Document.GetObject("imgMapView").style.display = "none";
	//	}
	//}
}

function SearchResultMapping_Property_DrawMarker(){
	if ( this.PropertyLatitude  && this.PropertyLongitude ){
		var oPropertyIcon = new GIcon();
		//####
		if (this.PropertyCategory == 2){
			oPropertyIcon.image = _map_icons_commercial;
		} else{
				oPropertyIcon.image = ( this.PropertyListingType == "5" ? _map_icons_sales_available : _map_icons_letting_available );
		}
		
		//oPropertyIcon.image = ( this.PropertyStatusDisplay.length ? ( this.PropertyListingType == "5" ? _map_icons_sales_status :  _map_icons_letting_status ) : ( this.PropertyListingType == "5" ? _map_icons_sales_available : _map_icons_letting_available ) );
		oPropertyIcon.iconSize = new GSize(34,37);
		//OLD VALUES FOR PINS - oPropertyIcon.iconSize = new GSize(14,25);
		oPropertyIcon.iconAnchor = new GPoint(34,37);
		oPropertyIcon.infoWindowAnchor = new GPoint(0,0);
		//append the icon to the map
		var oPropertyPoint = new GLatLng(this.PropertyLatitude,this.PropertyLongitude);
		var oMarker = new GMarker(oPropertyPoint, oPropertyIcon);
		//var oMarker = new GxMarker(oPropertyPoint, oPropertyIcon);
		//oMarker.setTooltip("<div id=\"pnlTooltip\"><b>"+this.PropertyAddress+" "+this.PropertyFormattedPrice+"</b></div>");
		//oMarker.setOpacity(90);
		oMarker.Property = this;
		GEvent.addListener( oMarker, 'click', function() { SearchResultMapping_Map_Pointer_OnClick(this); } );
		//GEvent.addListener( oMarker, 'mouseover', function(){ HttpManager.Document.GetObject("transDiv"+oMarker.Property.PropertyReference).className="TransDivOver"; } );
		//GEvent.addListener( oMarker, 'mouseout', function(){ HttpManager.Document.GetObject("transDiv"+oMarker.Property.PropertyReference).className="TransDiv"; } );
		GEvent.addListener( oMarker, 'infowindowclose', function(){ SearchResultMapping_Map_Pointer_OnInfoWindowClose(this); } );
		this.Marker = oMarker;
		//oMap.addOverlay( oMarker );
		omarkers.push( oMarker );
	}
}

function SearchResultMapping_Property_ShowMarker(PropertyReference,e){

	if ( !__searchResultMapping_isInitialised ){
		_map_callback_function = "SearchResultMapping_Property_ShowMarker('"+PropertyReference+"')"
		SearchResultMapping_OnLoad(0);
	}else{

		for ( var i = 0; i < aProperties.length; i ++ ){
			if ( aProperties[i].PropertyReference.toLowerCase() == PropertyReference.toLowerCase() ){
				//show bubble
				SearchResultMapping_ToggleView(0);
				SearchResultMapping_Property_ShowMarker_CalculateSourceClickLatLng(aProperties[i]);
				break;
			}
		}	
	}
}

function SearchResultMapping_Property_ShowMarker_CalculateSourceClickLatLng(o){
	if(HttpManager.Document.GetObject("pnlproperty_"+o.PropertyReference)){
		var ipropertytop = HttpManager.Document.GetObject("pnlproperty_"+o.PropertyReference).offsetTop;
		ipropertytop = HttpManager.Document.GetObject("pnlGoogleMap").offsetHeight - ipropertytop;
		var ileft = HttpManager.Document.GetObject("pnlGoogleMap").offsetWidth / 2;
		var opoint = new GPoint( ileft, ipropertytop);

		oMap.closeInfoWindow();
		
		setTimeout( function(){
		
			GEvent.clearListeners( oMap, 'infowindowclose' );
			GEvent.addListener( oMap, 'moveend', function(){
				GEvent.clearListeners( oMap, 'moveend' );
				
				GEvent.addListener( oMap, 'moveend', function(){
					GEvent.clearListeners( oMap, 'moveend' );
					SearchResultMapping_Map_Pointer_OnClick(o.Marker);
				})
				
				oMap.panTo( oMap.fromContainerPixelToLatLng( opoint ), oMap.getZoom() );
			})
				
			oMap.panTo(new GLatLng(o.PropertyLatitude,o.PropertyLongitude), oMap.getZoom());		
		}, 100);
	}

}

function SearchResultMapping_Map_Pointer_OnInfoWindowClose(){
	//when somebody closes an info window, we slide back to the center
	oMap.returnToSavedPosition();
}

function SearchResultMapping_Map_Pointer_OnDragEnd(){
	oMap.savePosition();
}

function SearchResultMapping_Map_Pointer_OnZoomEnd(){
	oMap.savePosition();
}

function sortLatitudeDESC(a,b){
	return (b.PropertyLatitude - a.PropertyLatitude);
}	

function sortLatitudeASC(a,b){
	return (a.PropertyLatitude - b.PropertyLatitude);
}	

function sortLongitudeDESC(a,b){
	return (b.PropertyLongitude - a.PropertyLongitude);
}	

function sortLongitudeASC(a,b){
	return (a.PropertyLongitude - b.PropertyLongitude);
}	