var oldPoly = [];
var presetLat = "";
var presetLong = "";
var presetZoom = "";

if(presetLat == "")
{
    presetLat = 53.5;
}

if(presetLong == "")
{
    presetLong = -8.2;
}

if(presetZoom == "")
{
    presetZoom = 6;
}

var presetBounds = "((50.80593472676908, -15.88623046875), (56.03522578369872, -0.50537109375))";

google.load("maps", "2");

var map;
var pins = [];
var circles = [];
var radius = [];
var markers;
var refreshTimer;
var refreshRetryTimer;
var refreshInProgress = false;
var refreshRetryCount = 0;
var mapDataXml;
var autoPanned = false;
var propertyID;
var geoMarker;
var markerManager;
var latlng;
var firstRefresh = true;
var	suppressRefresh = false;
var dontLoadMap = false;

function loadMap()
{
	try
	{
		window.onunload=GUnload();
	}
	catch( exception ) {}

  if (google.maps.BrowserIsCompatible())
  {
    map = new google.maps.Map2( document.getElementById( "map" ) );

    map.enableScrollWheelZoom();
    map.onmousewheel = wheelevent;
    G_NORMAL_MAP.getMinimumResolution = function() { return 6; }
	G_NORMAL_MAP.getMaximumResolution = function() { return 17; }
    geocoder = new google.maps.ClientGeocoder();

    CreatePncZoomControl();
    map.addControl(new PncZoomControl());
  	map.addControl(new google.maps.MapTypeControl());

    google.maps.Event.addDomListener(map, "DOMMouseScroll", wheelevent);
    google.maps.Event.addListener(map, "moveend", checkRefreshStatus );
    google.maps.Event.addListener(map, "movestart", HideInfoWindow );
    google.maps.Event.addListener(map, "infowindowopen", infoWindowOpened);

    markerManager = new PncMarkerManager();

    if (!map.getInfoWindow().isHidden())
    {
    	map.getInfoWindow().hide();
    }

    refreshViewPort();
  }
}

//----- Stop page scrolling if wheel over map ----
function wheelevent(e)
{
    if (!e) e = window.event;
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;
}

function addDragEndListener(marker,pinID)
{
	        google.mapsEvent.addListener(marker, 'dragend', function(){
	       	updateRadius(pinID);
        })
}
function updateRadius(pinID)
{
        	var latlng = pins[pinID].getLatLng();
        	map.removeOverlay(circles[pinID]);
        	circles[pinID] = drawCircle(latlng, radius[pinID], 80, '#FF0000', 1, 0.8, '#FF0000', 0.2);
}

function infoWindowOpened()
{
		if(refreshRetryTimer) clearTimeout(refreshRetryTimer);
		if(refreshTimer) clearTimeout(refreshTimer);
}


function infoWindowClosed()
{
	if (autoPanned)
	{
		if(refreshTimer) clearTimeout(refreshTimer);
		refreshRetryTimer = setTimeout( "checkRefreshStatus()", "200" );
	}
}

function updateMarkerCount()
{
	try
	{
		if ( markerManager.total > markerManager.count )
		{
			document.getElementById( "number-properties-returned" ).innerHTML = "<p>Showing <strong>"+markerManager.count+"</strong> of <strong>"+OutputFormattedNumber( markerManager.total )+"</strong> properties found, zoom in or refine to view all properties.</p>";
		}
		else
		{
			document.getElementById("number-properties-returned").innerHTML = "<p>Showing all <strong>"+OutputFormattedNumber( markerManager.total )+"</strong> properties found, zoom out to view more properties.</p>";
		}
	}

	catch(err)
	{

	}
}

function checkRefreshStatus( force )
{
	if (suppressRefresh)
	{
		suppressRefresh = false;
		return;
	}

	if ( !force && !map.getInfoWindow().isHidden())
	{
		autoPanned = true;
		return;
	}
	else
	{
	    if ( !map.getInfoWindow().isHidden())
		{
			map.getInfoWindow().hide();
		}
	}

	if (refreshInProgress)
	{
		refreshRetryCount++;
		if (refreshRetryCount < 20)
		{
			refreshRetryTimer = setTimeout( "checkRefreshStatus()", "1000" );
		}
		else
		{
			alert("Failed to update");
		}
	}
	else
	{
		refreshRetryCount = 0;
		if(refreshRetryTimer) clearTimeout(refreshRetryTimer);
		if(refreshTimer) clearTimeout(refreshTimer);
		refreshTimer = setTimeout( "refreshViewPort()", "1000" );
	}
}

var noBounds = false;

function refreshViewPort()
{
	if ( refreshInProgress )
	{
		return;
	}

	if ( dontLoadMap )
	{
		return;
	}

  HideInfoWindow();

  mapUpdating(true);

	markerManager.colorBy = "none";

    if ( noBounds )
    {
        bounds = "bounds=" + presetBounds + "&";
        noBounds = false;
    }
    else
    {
	    bounds = "bounds=" + map.getBounds() + "&";
    }

    filters = ReadMapFilters();

    if( typeof( filters ) == "undefined" )
    {
		filters = "";
    }

  google.maps.DownloadUrl("/ajax/map-data.php?" + bounds + filters + "&r=" + Math.random(), function(data)
  {
        if (refreshRetryCount > 0)
        {
            refreshInProgress = false;
            return;
        }

        if (!map.getInfoWindow().isHidden())
        {
            autoPanned = true;
            mapUpdating(false);
            return;
        }

        map.clearOverlays();
        dataRecieved = eval('(' + data + ')');

        markerManager.markers = dataRecieved.markers;
        markerManager.closeMarkers = [];
        markerManager.count = dataRecieved.count;
        markerManager.total = dataRecieved.total;

        var currentHash = location.hash.replace( "#", "" );

        PlacePins();
    });
}

function mapUpdating(inProgress)
{
	refreshInProgress = inProgress;
	refreshDialog = document.getElementById("refresh-dialog");
	if (refreshInProgress)
	{
		refreshDialog.style.display = 'block';
	}
	else
	{
		refreshDialog.style.display = 'none';
	}
}

function OutputFormattedNumber(number)
{
  str = number.toString();
  i = str.indexOf(".");
  if ( i < 1 )
  {
    i = str.length;
  }
  while ( i > 3 )
  {
    i-=3;
    j = str.charAt( i-1 );
    if ( j>="0" && j<="9" )
    {
      str = str.substr( 0,i ) + "," + str.substr( i );
    }
  }

  return str;
}

var lastLocationHash = "";
var currentMapHash = "";
var searchID = "";

// Gets the map geometry in a form that can be propogated in the URL
function GetMapGeometry()
{
	var coords = map.getCenter()+ "";
	coords = coords.replace( "(", "" ).replace( ")", "" ).replace( " ", "" ).split(",");
	var newCoord = coords[0] + "," + coords[1] + "," + map.getZoom() + "," + markerManager.colorBy;

	return Base64.encode( newCoord );
}

function TestMapGeometry()
{
	var coords = map.getCenter()+ "";
	coords = coords.replace( "(", "" ).replace( ")", "" ).replace( " ", "" ).split(",");
	var newCoord = coords[0] + "," + coords[1] + "," + map.getZoom();

	alert( newCoord );

	location.href = "#" + GetMapGeometry();
}

var propertyDetails = new Array();

function CreatePropertyHtmlFromMarker( marker )
{
	var currencySymbol = (marker.Currency == "EUR") ? "&euro;" : "&pound;";
	var formattedPrice;

	if ( marker.AskingPrice == '0')
	{
		formattedPrice = 'POA';
	}
	else
	{
		formattedPrice = currencySymbol + OutputFormattedNumber( marker.AskingPrice );
	}

	var bedrooms;
	var receptions;

	if ( marker.Bedrooms != 0 )
	{
		bedrooms = marker.Bedrooms + " Bedroom ";
	}
	else
	{
		bedrooms = '';
	}

	if ( marker.ReceptionRooms != 0 )
	{
		receptions = marker.ReceptionRooms + " Reception";
	}
	else
	{
		receptions = ''
	}

	var vp = GetMapGeometry();

	var brochureLink = "/brochure.php?s=" + searchID + "&p=" + marker.PropertyID + "&rt=map&vp=" + vp;

	var colour = markerManager.GetColor(marker);
	var icon = '';

	if ( colour != 'red' )
	{
		icon = '<img src="/images/map/map-house-icon-' + colour + '.gif" /> &nbsp;';
	}

	var infoWindowHtml = "<h3 class='accordion_toggle'>"
		  						+ icon + marker.FullAddress +
		  					"</h3>" +
		  					"<div class='map-info-item accordion_content'>" +
		  						"<div class='map-info-body'>" +
		  							"<div class='arrow'></div>" +
		  							"<a href='" + brochureLink + "'><img src='http://app2.propertynews.com/images/result/" + marker.MediaID + ".jpg'  class='floatleft standard' /></a>" +
									"<h4 class='price no-marg'>" + formattedPrice + "</h4>" +
									"<h4 class='details'><strong>" + marker.PropertyType + "</strong><br />" + bedrooms + receptions + "<br />" + marker.Status + "</h4>" +
									"<div class='clear-floats'></div>" +
								"</div>" +
								"<div class='options'><div class='propOptions'><ul><li class='propInfo'><a href='" + brochureLink + "'>View Details</a></li>" +
								"</ul><div class='clear-floats'></div></div></div>" +
							"</div>";

	return infoWindowHtml;
}

function ShowInfoWindow()
{
	document.getElementById( 'map-info-container' ).style.display = 'block';
}

function HideInfoWindow()
{
	document.getElementById( 'map-info-container' ).style.display = 'none';
}

var lastOverPropertyId;

function PinMouseOver( latlng )
{
	var pixelPoint = map.fromLatLngToDivPixel(latlng);
	var pixelPointKey = Math.floor(pixelPoint.x / markerManager.gridResolution) + "x" + Math.floor(pixelPoint.y / markerManager.gridResolution);

	var properties = markerManager.closeMarkers[pixelPointKey];

	if (!properties)
	{
		return;
	}

	if ( properties.length < 1 )
	{
		return;
	}

	var firstProperty = properties[0];
	var propertyId = firstProperty.PropertyID;

	if ( $(propertyId) )
	{
		$(propertyId).style.background = '#EEE';
		lastOverPropertyId = propertyId;
	}
}

function PinMouseOut( latlng )
{
	if ($(lastOverPropertyId))
	{
		$(lastOverPropertyId).style.background = '#FFF';
	}
}

function PinClicked( latlng )
{
	var pixelPoint = map.fromLatLngToDivPixel( latlng );
	var createAt = map.fromLatLngToContainerPixel( latlng );

	if ( createAt.x < 0 || createAt.y < 0 || createAt.x > 700 || createAt.y > 400 )
	{
		return;
	}

	var pixelPointKey = Math.floor( pixelPoint.x / markerManager.gridResolution ) + "x" + Math.floor( pixelPoint.y / markerManager.gridResolution );

	var properties = markerManager.closeMarkers[ pixelPointKey ];
	propertyHtml = "<img src='/images/map/close-map-window.png' border='0' style='position: absolute; cursor: pointer; right: -8px; top: -8px;' onclick='HideInfoWindow();'/>";

    for( var j = 0; j < properties.length; j++ )
	{
		var property = properties[j];
		propertyHtml += CreatePropertyHtmlFromMarker( property );

		if ( j == 7 )
		{
			break;
		}
	}

	CreateWindow( propertyHtml, createAt );
}

function CreateWindow( windowHtml, createAt )
{
	left = createAt.x + 8;
	var mclass = 'left';

    if ( createAt.x > 350 )
	{
		left = createAt.x - 326;
		mclass = 'right';
	}

	var outputWindow = "<div id='map-info' class='" + mclass + "' style='position: absolute; margin-left: " + left + "px; margin-top: " + ( createAt.y - 45 ) + "px'>";
	outputWindow += windowHtml;
	outputWindow += "</div>";

	document.getElementById( 'map-info-container' ).innerHTML = outputWindow;

	verticalAccordion = new accordion('map-info');
	verticalAccordion.activate($$('#map-info .accordion_toggle')[0]);

	ShowInfoWindow();
}

function PlacePins()
{
	var autoClickLatLng;
	updateMarkerCount();

	if ( markerManager.markers || markerManager.circles )
	{
		propertyDetails = new Array();

    	if ( firstRefresh )
  		{
  			markerManager.ResetMaxMin();
  		}

			if ( markerManager.markers )
			{
	  			for (x = 0; x < markerManager.markers.length; x++)
	  			{
	  				marker = markerManager.markers[x];

	  				if ( firstRefresh )
	  				{
	  					markerManager.UpdateMaxMin( parseFloat( marker.Latitude ), parseFloat( marker.Longitude ) );
	  				}
				}
			}

			if( firstRefresh )
  		{
  			suppressRefresh = true;
  			markerManager.AutoCenterAndZoom();
    		firstRefresh = false;
  		}

  		if ( markerManager.markers )
  		{

  			markerManager.closeMarkers = new Array();

	      for (x = 0; x < markerManager.markers.length; x++)
  			{
  				marker = markerManager.markers[x];

  				if ( marker )
  				{

					var latlng = new google.maps.LatLng( parseFloat( marker.Latitude ), parseFloat( marker.Longitude ) );

					pixelPoint = map.fromLatLngToDivPixel(latlng);
					pixelPointKey = Math.floor( pixelPoint.x / markerManager.gridResolution ) + "x" + Math.floor( pixelPoint.y / markerManager.gridResolution );

					if ( markerManager.closeMarkers[ pixelPointKey ] )
					{
						markerManager.closeMarkers[ pixelPointKey ][ markerManager.closeMarkers[ pixelPointKey ].length ] = marker;
					}
					else
					{
						markerManager.closeMarkers[ pixelPointKey ] = [ marker ];
					}
				}
			}


			for( var key in markerManager.closeMarkers )
			{
				var markers = markerManager.closeMarkers[ key ];

				if ( typeof( markers ) != "object" )
				{
					continue;
				}

        		// Setup the marker Icon
				houseIcon = new google.maps.Icon();
				houseIcon.iconSize = new google.maps.Size(14, 13);

				var toolTip = "";

				var marker = markers[0];

				houseIcon.iconSize = new google.maps.Size(14, 13);
				houseIcon.image = '/images/map/map-house-icon-'+ markerManager.GetColor(marker) + '.gif';
				houseIcon.iconAnchor = new google.maps.Point(13, 7);

				var latlng;

				if ( markers.length == 1 )
				{
					var marker = markers[0];
					latlng = new google.maps.LatLng(parseFloat(marker.Latitude), parseFloat(marker.Longitude));
					toolTip = marker.FullAddress;
				}
				else
				{
          			houseIcon.iconSize = new google.maps.Size(17, 19);
					houseIcon.image = '/images/map/map-house-icon-plus.gif';

					var coords = key.split( 'x' );
					var point = new GPoint( coords[ 0 ] * markerManager.gridResolution, coords[ 1 ] * markerManager.gridResolution );
					latlng = map.fromDivPixelToLatLng( point );

					var marker = markers[0];
					toolTip = marker.FullAddress + " (plus " + ( markers.length - 1 ) + " more)";
				}

				var opts =
				{
					title: toolTip,
					icon: houseIcon
				};

				var pin = new google.maps.Marker( latlng, opts );
				GEvent.addListener(pin, "click", PinClicked);
				GEvent.addListener(pin, "mouseover", PinMouseOver);
				GEvent.addListener(pin, "mouseout", PinMouseOut);
				map.addOverlay(pin);

			}
		}
	}

	mapUpdating( false );
	autoPanned = false;

	if ( autoClickLatLng )
	{
		PinClicked( autoClickLatLng );
	}
}

function PncMarkerManager()
{
	this.markers = [];
	this.circles = [];
	this.closeMarkers = [];
	this.count = 0;
	this.total = 0;
	this.Add = Add;
	this.Remove = Remove;
	this.Tidy = Tidy;
	this.Colorize = Colorize;
	this.GetColor = GetColor;
	this.ResetMaxMin = ResetMaxMin;
	this.UpdateMaxMin = UpdateMaxMin;
	this.AutoCenterAndZoom = AutoCenterAndZoom;
	this.colorBy = "none";
	this.colorTable = [];
	this.nextColor = 0;
	this.maxLong;
	this.minLong;
	this.maxLat;
	this.minLat;
	this.gridResolution = 10;

	this.colors = ["red","blue","green","purple","orange","grey"];

	// pass an instance of PncMarker to add to the manager and if appropriate palce on the map


	function Add(pncMarker)
	{
		if (!markers[pncMarker.propertyID])
		{
			markers[pncMarker.propertyID] = pncMarker;
			this.markers[propertyID].Place();
			return true;
		}
		return false;
	}

	// Removes Marker by PropertyID
	function Remove(propertyID)
	{
		if (this.markers[propertyID])
		{
			this.markers[propertyID].Remove();
			delete this.markers[propertyID];
			return true;
		}
		else
		{
			return false;
		}
	}

	function ResetMaxMin()
	{
		this.maxLong = 0;
		this.minLong = 0;
		this.maxLat = 0;
		this.minLat = 0;
	}

	function AutoCenterAndZoom()
	{
		centerLat = this.minLat + ((this.maxLat - this.minLat)/2);
		centerLong = this.minLong + ((this.maxLong - this.minLong)/2);
		latlng = new google.maps.LatLng(centerLat, centerLong)
	    pinBounds = new google.maps.LatLngBounds(new google.maps.LatLng(this.minLat, this.minLong),new google.maps.LatLng(this.maxLat, this.maxLong));
	    zoomLevel = map.getBoundsZoomLevel(pinBounds);

	    if ( zoomLevel > 14 )
	    {
	    	zoomLevel = 14;
		}

	    map.setCenter(latlng, zoomLevel);
	}

	function UpdateMaxMin(testLat, testLong)
	{
		if( this.maxLong == 0 || this.maxLong < testLong)
		{
			this.maxLong = testLong;
		}
		if( this.minLong == 0 || this.minLong > testLong)
		{
			this.minLong = testLong;
		}
		if( this.maxLat == 0 || this.maxLat < testLat)
		{
			this.maxLat = testLat;
		}
		if( this.minLat == 0 || this.minLat > testLat)
		{
			this.minLat = testLat;
		}
	}

	// Gets the Bounds of the map and other search settings and removes pins which are nolonger visible, or appropriate
	function Tidy(marker)
	{

	}

	function Colorize(colorBy)
	{
		if ( suppressRefresh )
		{
			return;
		}

		this.colorBy = colorBy;
		this.colorTable = [];
		refreshViewPort();
	}

	function GetColor(marker)
	{
		colorByValue = eval("marker."+this.colorBy);

		// process the value
		switch(this.colorBy)
		{

			case "AskingPrice":

				if ( sector == "sale" )
				{

					if(colorByValue <= 100000)
					{
						return "blue";
						break;
					}

					if(colorByValue <= 150000 )
					{
						return "green";
						break;
					}

					if(colorByValue <= 200000 )
					{
						return "purple";
						break;
					}

					if(colorByValue <= 250000 )
					{
						return "orange";
						break;
					}

					if(colorByValue <= 350000 )
					{
						return "grey";
						break;
					}

					if(colorByValue <= 500000 )
					{
						return "yellow";
						break;
					}

                    if(colorByValue <= 1000000 )
					{
						return "teal";
						break;
					}

					return "black";
				}
				else
				{
					if(colorByValue <= 300)
					{
						return "blue";
						break;
					}

					if(colorByValue <= 400 )
					{
						return "green";
						break;
					}

					if(colorByValue <= 500 )
					{
						return "purple";
						break;
					}

					if(colorByValue <= 600 )
					{
						return "orange";
						break;
					}

					if(colorByValue <= 700 )
					{
						return "grey";
						break;
					}

					if(colorByValue <= 800 )
					{
						return "yellow";
						break;
					}

                    if(colorByValue <= 900 )
					{
						return "teal";
						break;
					}

                    if(colorByValue > 900 )
					{
						return "black";
						break;
					}
				}

				break;

			case "Bedrooms":

				switch ( colorByValue )
				{
					case "2":
						return "blue";
						break;
					case "3":
						return "green";
						break;
					case "4":
						return "purple";
						break;
					case "5":
						return "orange";
						break;
					case "6":
						return "grey";
						break;
					default:
						return "yellow";
						break;
				}
				break;

			case "PropertyType":
				switch (colorByValue)
				{
					case "Apartment":
					case "Business":
					case "Flat":
						return "blue";
						break;

					case "Bungalow":
					case "Detached Bungalow":
					case "Detached":
					case "Villa":
					case "Car Park":
						return "green";
						break;

					case "Semi-Detached Bungalow":
					case "Semi-Detached":
					case "Hotel / Guest House / B&B":
						return "purple";
						break;

					case "Terrace":
					case "Townhouse":
					case "End Terrace":
					case "Lock-up/Garage":
						return "orange";
						break;

					case "Cottage":
					case "Office":
						return "grey";
						break;

					case "Site":
					case "Land":

						return "yellow";
						break;

                    case "Pub":

						return "teal";
						break;

                    case "Restaurant/Cafe":

						return "black";
						break;
				}
		}
		return "red";
	}

}

function UpdateColorLegend( colorBy )
{
	color = [ "red","blue","green","purple","orange","grey", "yellow", "teal", "black" ];

	switch( colorBy )
	{
		case "AskingPrice":
			document.getElementById( "price-legend" ).style.display = "block";
			if( document.getElementById( "filterPrice" ).style.display != "block" )
			{
				elem = document.getElementById( "filterPrice" );
  				vis = elem.style;
				vis.display = "block";
				elem.parentNode.className = ( vis.display == 'block' ) ? "primary-filter-li minus" : "primary-filter-li plus";
			}
			UncolorLegend( "filterBedrooms" );
			UncolorLegend( "filterType" );
			break;

		case "PropertyType":
			if( document.getElementById( "filterType" ).style.display != "block" )
			{
				elem = document.getElementById( "filterType" );
  				vis = elem.style;
				vis.display = "block";
				elem.parentNode.className = ( vis.display == 'block' ) ? "primary-filter-li minus" : "primary-filter-li plus";
			}
			document.getElementById("price-legend").style.display = "none";
			ColorLegend( "filterType" );
			UncolorLegend( "filterBedrooms" );
			break;

		case "Bedrooms":
			if( document.getElementById( "filterBedrooms" ).style.display != "block" )
			{
				elem = document.getElementById( "filterBedrooms" );
  				vis = elem.style;
				vis.display = "block";
				elem.parentNode.className = ( vis.display == 'block' ) ? "primary-filter-li minus" : "primary-filter-li plus";
			}
			document.getElementById("price-legend").style.display = "none";
			ColorLegend( "filterBedrooms" );
			UncolorLegend( "filterType" );
			break;

		case "none":
			document.getElementById("price-legend").style.display = "none";
			UncolorLegend( "filterBedrooms" );
			UncolorLegend( "filterType" );
			break;

		default:
			UncolorLegend( "filterBedrooms" );
			document.getElementById("price-legend").style.display = "none";
			UncolorLegend( "filterType" );
			break;

	}

}

function ColorLegend( element )
{
	ul = document.getElementById( element ).childNodes;
	var j = 1;
	for( i = 0; i < ul.length; i++ )
	{
		if( ul[i].tagName == "LI" )
		{
			ul[i].className = color[j]+"-legend";
			j++;
		}
	}
}

function UncolorLegend ( element )
{
	if ( !document.getElementById( element ) )
	{
		return;
	}

	ul = document.getElementById( element ).childNodes;
	var j = 0;
	for( i = 0; i < ul.length; i++ )
	{
		if( ul[i].tagName == "LI" )
		{
			ul[i].className = "no-legend";
			j++;
		}
	}
}

function PncServiceMarker()
{
	this.longitude;
	this.latitude;
	this.title;
	this.description;

	this.Place = Place;
	this.Remove = Remove;


	function Place()
	{

	}

	function Remove()
	{

	}
}

function PncMarker()
{
	this.longitude;
	this.latitude;
	this.askingPrice;
	this.houseType;
	this.bedrooms;
	this.receptions;
	this.color;
	this.SetColor = SetColor;
	this.Place = Place;
	this.Remove = Remove;


	function Place()
	{

	}

	function Remove()
	{

	}
	function SetColor(color)
	{

	}
}

function writeDebug(message)
{
	debugWin = document.getElementById("debugWindow");
	debugWin.value += message + "\r\n";
}

//////////////////////////////////////////
// Custom Zoom Controls
//////////////////////////////////////////


// We define the function first
function PncZoomControl() {
}

function CreatePncZoomControl()
{
	// To "subclass" the GControl, we set the prototype object to
	// an instance of the GControl object
	PncZoomControl.prototype = new GControl();

	// Creates a one DIV for each of the buttons and places them in a container
	// DIV which is returned as our control element. We add the control to
	// to the map container and return the element for the map class to
	// position properly.
	PncZoomControl.prototype.initialize = function(map)
	{
	  var container = document.createElement("div");
	  container.style.width = "45px";
	  var zoomInImg = document.createElement("img");
	  zoomInImg.src = "/images/map/zoom-in.png";
	  zoomInImg.alt = "Zoom In";
	  this.setButtonStyle_(zoomInImg);
	  container.appendChild(zoomInImg);
	  GEvent.addDomListener(zoomInImg, "click", function() {
	    map.zoomIn();
	  });

	  var zoomOutImg = document.createElement("img");
	  zoomOutImg.src = "/images/map/zoom-out.png";
	  zoomOutImg.alt = "Zoom Out";
	  zoomOutImg.style.marginLeft = "10px";
	  this.setButtonStyle_(zoomOutImg);
	  container.appendChild(zoomOutImg);
	  GEvent.addDomListener(zoomOutImg, "click", function() {
	    map.zoomOut();
	  });

	  map.getContainer().appendChild(container);
	  return container;
	}

	// By default, the control will appear in the top left corner of the
	// map with 7 pixels of padding.
	PncZoomControl.prototype.getDefaultPosition = function()
	{
	  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
	}

	// Sets the proper CSS for the given button element.
	PncZoomControl.prototype.setButtonStyle_ = function(button)
	{
	  button.style.padding = "2px";
	  button.style.marginBottom = "3px";
	  button.style.cursor = "pointer";
	}
}


function DragZoomControl(a,b,c){this.globals={draggingOn:false,cornerTopDiv:null,cornerRightDiv:null,cornerBottomDiv:null,cornerLeftDiv:null,mapPosition:null,outlineDiv:null,mapWidth:0,mapHeight:0,mapRatio:0,startX:0,startY:0,borderCorrection:0};this.globals.style={opacity:.2,fillColor:"#000",border:"2px solid blue"};var d=this.globals.style;for(var s in a){d[s]=a[s]}var e=d.border.split(' ');d.outlineWidth=parseInt(e[0].replace(/\D/g,''));d.outlineColor=e[2];d.alphaIE='alpha(opacity='+(d.opacity*100)+')';this.globals.backStack=[];this.globals.options={buttonHTML:'',buttonStartingStyle:{padding:'1px',marginLeft:'8px'},backButtonHTML:'zoom back',backButtonStyle:{background:'#FFF',display:'none'},buttonZoomingHTML:'Drag a <br />region on <br />the map',buttonZoomingStyle:{background:'#FFF'},overlayRemoveTime:6000,backButtonEnabled:false,stickyZoomEnabled:false};for(var s in b){this.globals.options[s]=b[s]}if(c==null){c={}}this.globals.callbacks=c}

var DragZoomUtil={};

function CreateDragZoomControl()
{
	DragZoomControl.prototype=new GControl();
	DragZoomControl.prototype.saveMapContext=function(a){if(this.globals.options.backButtonEnabled){this.saveBackContext_(a,true);this.globals.backButtonDiv.style.display='block'}};
	DragZoomControl.prototype.initiateZoom=function(){this.buttonclick_()};
	DragZoomControl.prototype.initiateZoomBack=function(){if(this.globals.options.backButtonEnabled)this.backbuttonclick_()};
	DragZoomControl.prototype.initButton_=function(a){var G=this.globals;var b=document.createElement('div');b.innerHTML=G.options.buttonHTML;b.id='gzoom-control';DragZoomUtil.style([b],{cursor:'pointer',zIndex:200});DragZoomUtil.style([b],G.options.buttonStartingStyle);DragZoomUtil.style([b],G.options.buttonStyle);a.appendChild(b);return b};
	DragZoomControl.prototype.initBackButton_=function(a){var G=this.globals;var b=document.createElement('div');b.innerHTML=G.options.backButtonHTML;b.id='gzoom-back';DragZoomUtil.style([b],{cursor:'pointer',zIndex:200});DragZoomUtil.style([b],G.options.buttonStartingStyle);DragZoomUtil.style([b],G.options.backButtonStyle);a.appendChild(b);return b};
	DragZoomControl.prototype.setButtonMode_=function(a){var G=this.globals;if(a=='zooming'){G.buttonDiv.innerHTML=G.options.buttonZoomingHTML;DragZoomUtil.style([G.buttonDiv],G.options.buttonStartingStyle);DragZoomUtil.style([G.buttonDiv],G.options.buttonZoomingStyle)}else{G.buttonDiv.innerHTML=G.options.buttonHTML;DragZoomUtil.style([G.buttonDiv],G.options.buttonStartingStyle);DragZoomUtil.style([G.buttonDiv],G.options.buttonStyle)}};
	DragZoomControl.prototype.initialize=function(a){var G=this.globals;var b=this;var c=a.getContainer();var d=document.createElement("div");DragZoomUtil.style([d],{cursor:'pointer',zIndex:150});var f=this.initButton_(d);var g=this.initBackButton_(d);c.appendChild(d);var h=document.createElement("div");h.id='gzoom-map-cover';h.innerHTML='<div id="gzoom-outline" style="position:absolute;display:none;"></div><div id="gzoom-cornerTopDiv" style="position:absolute;display:none;"></div><div id="gzoom-cornerLeftDiv" style="position:absolute;display:none;"></div><div id="gzoom-cornerRightDiv" style="position:absolute;display:none;"></div><div id="gzoom-cornerBottomDiv" style="position:absolute;display:none;"></div>';DragZoomUtil.style([h],{position:'absolute',display:'none',overflow:'hidden',cursor:'crosshair',zIndex:101});c.appendChild(h);GEvent.addDomListener(f,'click',function(e){b.buttonclick_(e)});GEvent.addDomListener(g,'click',function(e){b.backbuttonclick_(e)});GEvent.addDomListener(h,'mousedown',function(e){b.coverMousedown_(e)});GEvent.addDomListener(document,'mousemove',function(e){b.drag_(e)});GEvent.addDomListener(document,'mouseup',function(e){b.mouseup_(e)});G.mapPosition=DragZoomUtil.getElementPosition(c);G.outlineDiv=DragZoomUtil.gE("gzoom-outline");G.buttonDiv=DragZoomUtil.gE("gzoom-control");G.backButtonDiv=DragZoomUtil.gE("gzoom-back");G.mapCover=DragZoomUtil.gE("gzoom-map-cover");G.cornerTopDiv=DragZoomUtil.gE("gzoom-cornerTopDiv");G.cornerRightDiv=DragZoomUtil.gE("gzoom-cornerRightDiv");G.cornerBottomDiv=DragZoomUtil.gE("gzoom-cornerBottomDiv");G.cornerLeftDiv=DragZoomUtil.gE("gzoom-cornerLeftDiv");G.map=a;G.borderCorrection=G.style.outlineWidth*2;this.setDimensions_();this.initStyles_();G.mapCover.onselectstart=function(){return false};return d};
	DragZoomControl.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(3,120))};
	DragZoomControl.prototype.coverMousedown_=function(e){var G=this.globals;var a=this.getRelPos_(e);G.startX=a.left;G.startY=a.top;DragZoomUtil.style([G.mapCover],{background:'transparent',opacity:1,filter:'alpha(opacity=100)'});DragZoomUtil.style([G.outlineDiv],{left:G.startX+'px',top:G.startY+'px',display:'block',width:'1px',height:'1px'});G.draggingOn=true;G.cornerTopDiv.style.top=(G.startY-G.mapHeight)+'px';G.cornerTopDiv.style.display='block';G.cornerLeftDiv.style.left=(G.startX-G.mapWidth)+'px';G.cornerLeftDiv.style.top=G.startY+'px';G.cornerLeftDiv.style.display='block';G.cornerRightDiv.style.left=G.startX+'px';G.cornerRightDiv.style.top=G.startY+'px';G.cornerRightDiv.style.display='block';G.cornerBottomDiv.style.left=G.startX+'px';G.cornerBottomDiv.style.top=G.startY+'px';G.cornerBottomDiv.style.width='0px';G.cornerBottomDiv.style.display='block';if(G.callbacks.dragstart!=null){G.callbacks.dragstart(G.startX,G.startY)}return false};
	DragZoomControl.prototype.drag_=function(e){var G=this.globals;if(G.draggingOn){var a=this.getRelPos_(e);rect=this.getRectangle_(G.startX,G.startY,a,G.mapRatio);if(rect.left){addX=-rect.width}else{addX=0}if(rect.top){addY=-rect.height}else{addY=0}DragZoomUtil.style([G.outlineDiv],{left:G.startX+addX+'px',top:G.startY+addY+'px',display:'block',width:'1px',height:'1px'});G.outlineDiv.style.width=rect.width+"px";G.outlineDiv.style.height=rect.height+"px";G.cornerTopDiv.style.height=((G.startY+addY)-(G.startY-G.mapHeight))+'px';G.cornerLeftDiv.style.top=(G.startY+addY)+'px';G.cornerLeftDiv.style.width=((G.startX+addX)-(G.startX-G.mapWidth))+'px';G.cornerRightDiv.style.top=G.cornerLeftDiv.style.top;G.cornerRightDiv.style.left=(G.startX+addX+rect.width+G.borderCorrection)+'px';G.cornerBottomDiv.style.top=(G.startY+addY+rect.height+G.borderCorrection)+'px';G.cornerBottomDiv.style.left=(G.startX-G.mapWidth+((G.startX+addX)-(G.startX-G.mapWidth)))+'px';G.cornerBottomDiv.style.width=(rect.width+G.borderCorrection)+'px';if(G.callbacks.dragging!=null){G.callbacks.dragging(G.startX,G.startY,rect.endX,rect.endY)}return false}};
	DragZoomControl.prototype.mouseup_=function(e){var G=this.globals;if(G.draggingOn){var a=this.getRelPos_(e);G.draggingOn=false;var b=this.getRectangle_(G.startX,G.startY,a,G.mapRatio);if(b.left)b.endX=b.startX-b.width;if(b.top)b.endY=b.startY-b.height;this.resetDragZoom_();var c=new GPoint(b.startX,b.startY);var d=new GPoint(b.endX,b.startY);var f=new GPoint(b.endX,b.endY);var g=new GPoint(b.startX,b.endY);var h=G.map.fromContainerPixelToLatLng(c);var i=G.map.fromContainerPixelToLatLng(d);var j=G.map.fromContainerPixelToLatLng(f);var k=G.map.fromContainerPixelToLatLng(g);var l=new GPolyline([h,i,j,k,h],G.style.outlineColor,G.style.outlineWidth+1,.4);try{G.map.addOverlay(l);setTimeout(function(){G.map.removeOverlay(l)},G.options.overlayRemoveTime)}catch(e){}polyBounds=l.getBounds();var i=polyBounds.getNorthEast();var k=polyBounds.getSouthWest();var j=new GLatLng(k.lat(),i.lng());var h=new GLatLng(i.lat(),k.lng());zoomLevel=G.map.getBoundsZoomLevel(polyBounds);center=polyBounds.getCenter();G.map.setCenter(center,zoomLevel);if(G.callbacks.dragend!=null){G.callbacks.dragend(h,i,j,k,c,d,f,g)}if(G.options.stickyZoomEnabled){this.initCover_();if(G.options.backButtonEnabled)this.saveBackContext_(G.options.backButtonHTML,false);G.backButtonDiv.style.display='none'}}};
	DragZoomControl.prototype.setDimensions_=function(){var G=this.globals;var a=G.map.getSize();G.mapWidth=a.width;G.mapHeight=a.height;G.mapRatio=G.mapHeight/G.mapWidth;DragZoomUtil.style([G.mapCover,G.cornerTopDiv,G.cornerRightDiv,G.cornerBottomDiv,G.cornerLeftDiv],{left:'0px',top:'0px',width:G.mapWidth+'px',height:G.mapHeight+'px'})};
	DragZoomControl.prototype.initStyles_=function(){var G=this.globals;DragZoomUtil.style([G.mapCover,G.cornerTopDiv,G.cornerRightDiv,G.cornerBottomDiv,G.cornerLeftDiv],{filter:G.style.alphaIE,opacity:G.style.opacity,background:G.style.fillColor});G.outlineDiv.style.border=G.style.border};
	DragZoomControl.prototype.buttonclick_=function(){var G=this.globals;G.backButtonDiv.style.display='none';if(G.mapCover.style.display=='block'){this.resetDragZoom_();if(G.options.backButtonEnabled){this.restoreBackContext_();if(G.backStack.length==0)G.backButtonDiv.style.display='none'}}else{this.initCover_();if(G.options.backButtonEnabled)this.saveBackContext_(G.options.backButtonHTML,false)}};
	DragZoomControl.prototype.backbuttonclick_=function(){var G=this.globals;if(G.options.backButtonEnabled&&G.backStack.length>0){this.restoreBackContext_();if(G.callbacks['backbuttonclick']!=null){G.callbacks.backbuttonclick(G.methodCall)}}};
	DragZoomControl.prototype.saveBackContext_=function(a,b){var G=this.globals;var c={};c["center"]=G.map.getCenter();c["zoom"]=G.map.getZoom();c["maptype"]=G.map.getCurrentMapType();c["text"]=G.backButtonDiv.innerHTML;c["methodCall"]=b;G.backStack.push(c);G.backButtonDiv.innerHTML=a};
	DragZoomControl.prototype.restoreBackContext_=function(){var G=this.globals;var a=G.backStack.pop();G.map.setCenter(a["center"],a["zoom"],a["maptype"]);G.backButtonDiv.innerHTML=a["text"];G.methodCall=a["methodCall"];if(G.backStack.length==0)G.backButtonDiv.style.display='none'};
	DragZoomControl.prototype.initCover_=function(){var G=this.globals;G.mapPosition=DragZoomUtil.getElementPosition(G.map.getContainer());this.setDimensions_();this.setButtonMode_('zooming');DragZoomUtil.style([G.mapCover],{display:'block',background:G.style.fillColor});DragZoomUtil.style([G.outlineDiv],{width:'0px',height:'0px'});if(G.callbacks['buttonclick']!=null){G.callbacks.buttonclick()}};
	DragZoomControl.prototype.getRelPos_=function(e){var a=DragZoomUtil.getMousePosition(e);var G=this.globals;return{top:(a.top-G.mapPosition.top),left:(a.left-G.mapPosition.left)}};
	DragZoomControl.prototype.getRectangle_=function(a,b,c,d){var e=false;var f=false;var g=c.left-a;var h=c.top-b;if(g<0){g=g*-1;e=true}if(h<0){h=h*-1;f=true}delta=g>h?g:h;return{startX:a,startY:b,endX:a+delta,endY:b+parseInt(delta*d),width:delta,height:parseInt(delta*d),left:e,top:f}};
	DragZoomControl.prototype.resetDragZoom_=function(){var G=this.globals;DragZoomUtil.style([G.mapCover,G.cornerTopDiv,G.cornerRightDiv,G.cornerBottomDiv,G.cornerLeftDiv],{display:'none',opacity:G.style.opacity,filter:G.style.alphaIE});G.outlineDiv.style.display='none';this.setButtonMode_('normal');if(G.options.backButtonEnabled&&(G.backStack.length>0))G.backButtonDiv.style.display='block'};
	DragZoomUtil.gE=function(a){return document.getElementById(a)}
	DragZoomUtil.getMousePosition=function(e){var a=0;var b=0;if(!e)var e=window.event;if(e.pageX||e.pageY){a=e.pageX;b=e.pageY}else if(e.clientX||e.clientY){a=e.clientX+(document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft);b=e.clientY+(document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop)}return{left:a,top:b}};
DragZoomUtil.getElementPosition = function(element) {
  var leftPos = element.offsetLeft;          // initialize var to store calculations
  var topPos = element.offsetTop;            // initialize var to store calculations
  var parElement = element.offsetParent;     // identify first offset parent element
  while (parElement != null ) {                // move up through element hierarchy
    leftPos += parElement.offsetLeft;      // appending left offset of each parent
    topPos += parElement.offsetTop;
    parElement = parElement.offsetParent;  // until no more offset parents exist
  }
  return {left: leftPos, top: topPos};
};

//	DragZoomUtil.getElementPosition=function(a){var b=a.offsetLeft;var c=a.offsetTop;var d=a.offsetParent;while(d!=null){b+=d.offsetLeft;c+=d.offsetTop;d=d.offsetParent}return{left:b,top:c}};
	DragZoomUtil.style=function(a,b){if(typeof(a)=='string'){a=DragZoomUtil.getManyElements(a)}for(var i=0;i<a.length;i++){for(var s in b){a[i].style[s]=b[s]}}};
	DragZoomUtil.getManyElements=function(a){var b=a.split(',');var c=[];for(var i=0;i<b.length;i++){c[c.length]=DragZoomUtil.gE(b[i])};return c};
}


///////////////////////////////////////////////////////////
///  +sliderControl TODO: OO this code
///////////////////////////////////////////////////////////

     var currObj;              // stores the current object being manipulated (leftSlider or rightSlider object)
      var leftPos = 0;          // the current left position after mouse is released
      var rightPos = 150;       // the current right position after mouse is released
      var sliderWidth = 7;      // the width of the sliders (includes borders)
      var sliderBarWidth = 150; // the width of the slider bar (does not include borders)
      var mouseStart = -99999   // an arbitrary number used to show that it is the first time we are hitting the moveSlider1 function.
      var pos;                  // position with offset used during the move
      var min = 1;            // minimum value of the data
      var max = 15;            // maximum value of the data

      /* function moveSlider(obj)
           parameter obj - object reference to the calling object
         This function sets the resets the starting mouse position and sets the document
         methods used to watch for mouse events.
      */
      function moveSlider(obj) {
        mouseStart = -99999;   // set the beginning mouse position to an unlikely number.
        currObj = obj;         // set the currObj variable to the object that was clicked
        document.onmousemove = moveSlider1; // set the onmousemove method to the function that moves the slider
        document.onmouseup = moveDone;   // set the onmouseup method to the function that stops listening for the mousemove and reclaculates the data
      }

      /* function moveslider1
         This function is called by the mousemove event
         checks the current mouse position and compares it
         to the mouse position when the move was started.
         uses the difference as an offset from the slider's
         staring position to move the slider with the mouse
      */
      function moveSlider1(e){
        if (!e) var e = window.event;  // if IE, then we need to assign e
        if (e.pageX) posX = e.pageX;   // FF, opera, netscape
        else if (e.clientX) {          // IE
          posX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        }
        if (mouseStart == -99999) mouseStart = posX;  // -99999 is an arbitrary number.  It is unlikely to be hit
        var offset = posX - mouseStart; // determine the difference from where the mouse started to where it is now

        if (currObj.id == "sliderLeft")
        {  // If we are moving the left slider
          pos = leftPos + offset;        // the new position should be the current left position + the offset
          if (pos < 0) pos = 0;          // if this makes the left position less than 0 then use 0
          if (pos > rightPos - sliderWidth) pos = rightPos - sliderWidth; // if the position would put us past the right slider then move up to the right slider

          var newValue;

          if (sector == "rent")
          {
          	newValue = Math.round(pos / sliderBarWidth * (max - min) + min) * 150;
          }
          else
          {
          	newValue = Math.pow(Math.round(pos / sliderBarWidth * (max - min) + min), 2) * 10;
          }

          document.getElementById('SliderMinPrice').value = OutputFormattedNumber( newValue );

          CheckPriceMinMax();
        }
        else
        {
          pos = rightPos + offset   // the new position should be the current right position + the offset
          if (pos < leftPos + sliderWidth) pos = leftPos + sliderWidth;  // if the new position would take us past the left slider then move next to the left slider
          if (pos > sliderBarWidth) pos = sliderBarWidth;  // if the new position is past the end of the bar, position at the end of the bar.

          var newValue;

          if (sector == "rent")
          {
          	newValue = Math.round(pos / sliderBarWidth * (max - min) + min) * 150;
          }
          else
          {
          	newValue = Math.pow(Math.round(pos / sliderBarWidth * (max - min) + min), 2) * 10;
          }

          document.getElementById('SliderMaxPrice').value = OutputFormattedNumber( newValue );

          CheckPriceMinMax();
         }

        currObj.style.left = pos + "px";  // move the slider to the new position
      }

      /* function moveDone()
         sets the current left/right position memory variable.
         clears the mouse monitoring methods.
         Calls the function to recaculate the data
      */
      function moveDone(e) {
        if (currObj.id == "sliderLeft") leftPos = pos;    // set the current left position to the value of pos
        else rightPos = pos;                              // set the current right position to the value of pos
        document.onmousemove = function() {};             // stop listening for a mousemove event
        document.onmouseup = function() {};               // stop listening for a mouseup event
      }

      function updateSliderPos(currObj)
      {
      	val = currObj.value.replace(',', '');

      	if (sector == "sale")
      	{
      		val = Math.round(Math.sqrt(val / 10));
      	}
      	else
      	{
			val = val / 150;
      	}

      	if (currObj.id == "SliderMinPrice")
      	{
      		val -= 1;
      	}

      	if ( val != '0' && ( isNaN(val) || val == '' ) ) return;

      	pos = (val / ((max - min) + min)) * sliderBarWidth;

      	if ( currObj.id == "SliderMinPrice" )
      	{
      		slider = "sliderLeft";

      		if (pos < 0) pos = 0;          // if this makes the left position less than 0 then use 0

      		if (pos > rightPos - sliderWidth) pos = rightPos - sliderWidth;

			leftPos = pos;
      	}
      	else
      	{
      		slider = "sliderRight";

			if (pos < leftPos + sliderWidth) pos = leftPos + sliderWidth;  // if the new position would take us past the left slider then move next to the left slider

			if (pos > sliderBarWidth ) pos = sliderBarWidth ;

			rightPos = pos;
      	}
      	document.getElementById(slider).style.left = pos + "px";
      }


/////////////////////////////////////////////////////////////////////////
///  +AGENTS AREA MAPPING FUNCTIONS
/////////////////////////////////////////////////////////////////////////

var pinPlaced = false;

function GetLat()
{
	return marker.getLatLng().lat();
}

function GetLong()
{
	return marker.getLatLng().lng();
}


////////////////////////////////////////


////////////////////////////////////////

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function ClearFilters()
{
    filters = $("primary-filter").getElementsByTagName("UL");

    for (x = 0; x < filters.length; x++)
    {
        var filterType = filters[x].id.replace('filter', '');
        var thisFilter = '';
        filterValues = filters[x].getElementsByTagName("INPUT");
        switch (filterType)
        {
            // deal with special filtercases
            case "Bedrooms":
            case "Type":
                for (y = 0; y < filterValues.length; y++)
                {
                    filterValues[y].checked = false;
                }

                break;

            case "Price":
                for (y = 0; y < filterValues.length; y++)
                {
                    if (filterValues[y].name == "SliderMinPrice")
                    {
                        filterValues[y].value = OutputFormattedNumber( defaultMinPrice );
                    }

                    if (filterValues[y].name == "SliderMaxPrice" )
                    {
                        filterValues[y].value = OutputFormattedNumber( defaultMaxPrice );
                    }
                }

                break;


        }
     }

     updateSliderPos(document.getElementById("SliderMinPrice"));
     updateSliderPos(document.getElementById("SliderMaxPrice"));

     CheckPriceMinMax();

     checkRefreshStatus(true);
}

function getQueryParams(qs)
{
	qs = qs.split("+").join(" ");
	var params = {};
	var tokens;
	while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
	    params[decodeURIComponent(tokens[1])]
	        = decodeURIComponent(tokens[2]);
	    qs = qs.replace(tokens[0], '');
	}

	return params;
}

function ReadMapFilters()
{
    if ( !$("primary-filter") )
    {
        return;
    }

	var $_GET = getQueryParams(document.location.search);

    var filterString = "";
    //get each of the filters
    filters = $("primary-filter").getElementsByTagName("UL");

    for ( x = 0; x < filters.length; x++)
    {
        var filterType = filters[ x ].id.replace('filter','');
        var thisFilter = '';
        filterValues = filters[ x ].getElementsByTagName("INPUT");

            switch ( filterType )
            {
                // deal with special filtercases
                case "Bedrooms":
                    for ( y = 0; y < filterValues.length; y++)
                    {
                        if ( filterValues[ y ].checked )
                        {
                            thisFilter += filterValues[ y ].value;
                        }
                    }
                    break;
                case "Price":
                    for (y = 0; y < filterValues.length; y++)
                    {
                        var intPrice = +filterValues[y].value.replace( ",", "" );

                        if ( filterValues[y].name == "SliderMinPrice" )
                        {
                            if ( ( intPrice > defaultMinPrice ) && ( intPrice != 0 ) )
                            {
                                if (sector == "sale")
                                {
                                    intPrice *= 1000;
                                }

                                filterString += "&MinPrice=" + intPrice;
                            }
                            else
                            {
                                filterString += "&MinPrice=";
                            }
                        }


                        if ( filterValues[y].name == "SliderMaxPrice" )
                        {
                            if ( ( intPrice < defaultMaxPrice ) && ( intPrice != 0 ) )
                            {
                                if (sector == "sale")
                                {
                                    intPrice *= 1000;
                                }

                                filterString += "&MaxPrice=" + intPrice;
                            }
                            else
                            {
                                filterString += "&MaxPrice=";
                            }
                        }
                    }
                    break;
                default:
                    for ( y = 0; y < filterValues.length; y++)
                    {
                        if ( filterValues[ y ].checked )
                        {
                            thisFilter += filterValues[ y ].name + "|";
                        }
                    }
                    break;

            }

        if ( thisFilter != '' || filterType == "Type" )
        {
            filterString += "&"+filterType+"="+thisFilter;
        }
    }

    if( 'sector' in $_GET )
    {
    	//alert( $_GET[ 'sector' ] );

    	//alert( filterString );

    	if( $_GET[ 'sector' ] == 'rent' || $_GET[ 'sector' ] == 'sale' )
    	{
			filterString += "&Sector=" + $_GET[ 'sector' ];
    	}

    	//alert( filterString );
    }

    return filterString;
}


