var container = document.createElement('div');
var street_view_on = false;

function adjustMapBounds()
{
	var b = bufferBounds(map.getBounds(), -25);
	var z = map.getBoundsZoomLevel(b);
	map.setCenter(b.getCenter(), z);
}

function bufferBounds(b, p)
{
	var n = b.getNorthEast().lat();
	var e = b.getNorthEast().lng();
	var s = b.getSouthWest().lat();
	var w = b.getSouthWest().lng();
	return new GLatLngBounds(
		new GLatLng(s - ( (n - s) * (p / 100) ), w - ( (e - w) / (p * 100) )), 
		new GLatLng(n + ( (n - s) / (p * 100) ), e + ( (e - w) / (p * 100) ))
	);
}

function direction(address)
{
	clear_direction();
	directions.load(address);
}

function clear_direction()
{
	directions.clear();
}

function TextualZoomControl() { }

function TextualMapTypeControl() { }

// At some point we should let the iamges change
function zoom_control(zoom,street)
{
	if (zoom || street)
	{
		map.enableScrollWheelZoom();
	
		///////////////////////////////
		// ZOOM CONTROLS
		///////////////////////////////
		TextualZoomControl.prototype = new GControl();
		TextualZoomControl.prototype.initialize = function(map) {
			// div container
			var container = document.createElement('div');
			
        if (zoom)
        {
			// custom zoom in button
			var zoomInDiv = document.createElement('div');
			zoomInDiv.style.backgroundImage='url(/content/mls/images/zoom_in_icon.png)';
			zoomInDiv.style.width = '24px';
			zoomInDiv.style.height = '23px';
			zoomInDiv.style.cursor = 'pointer';
			container.appendChild(zoomInDiv);
			GEvent.addDomListener(zoomInDiv, 'click', function() {
				map.zoomIn();
			});
			GEvent.addDomListener(zoomInDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/zoom_in_hover_icon.png)';
			});
			GEvent.addDomListener(zoomInDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/zoom_in_icon.png)';
			});
			
			// custom zoom out button
			var zoomOutDiv = document.createElement('div');
			zoomOutDiv.style.backgroundImage='url(/content/mls/images/zoom_out_icon.png)';
			zoomOutDiv.style.width = '24px';
			zoomOutDiv.style.height = '26px';
			zoomOutDiv.style.cursor = 'pointer';
			container.appendChild(zoomOutDiv);
			GEvent.addDomListener(zoomOutDiv, 'click', function() {
				map.zoomOut();
			});
			GEvent.addDomListener(zoomOutDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/zoom_out_hover_icon.png)';
			});
			GEvent.addDomListener(zoomOutDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/zoom_out_icon.png)';
			});
			
        }
		
        if (street)
        {
            // custom Street View button
			var zoomOutDiv = document.createElement('div');
			zoomOutDiv.style.backgroundImage='url(/content/mls/images/b_street_view_internal_on.png)';
			zoomOutDiv.style.width = '24px';
			zoomOutDiv.style.height = '24px';
			zoomOutDiv.style.cursor = 'pointer';
			zoomOutDiv.style.marginTop = '4px';
			container.appendChild(zoomOutDiv);
			GEvent.addDomListener(zoomOutDiv, 'click', function() {
				 $('toggle_street_view').fireEvent('click'); 
			});
			GEvent.addDomListener(zoomOutDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/b_street_view_internal.png)';
			});
			GEvent.addDomListener(zoomOutDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/b_street_view_internal_on.png)';
			});
        }
			
			map.getContainer().appendChild(container);
			return container;
		}
	
		TextualZoomControl.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
		}
		map.addControl(new TextualZoomControl());
	}
}

function buttons(map_button, satellite, terrain, search)
{
	TextualMapTypeControl.prototype = new GControl();
	TextualMapTypeControl.prototype.initialize = function(map) {
	
		// div container
		var container = document.createElement('div');
	
		if (map_button)
		{
			// custom map button
			var mapDiv = document.createElement('div');
			mapDiv.style.backgroundImage='url(/content/mls/images/map_icon.png)';
			mapDiv.style.width = '43px';
			mapDiv.style.height = '26px';
			mapDiv.style.cssFloat = 'left';
			mapDiv.style.styleFloat = 'left';
			mapDiv.style.cursor = 'pointer';
			container.appendChild(mapDiv);
			GEvent.addDomListener(mapDiv, 'click', function() {
				map.setMapType(G_NORMAL_MAP);
			});
			GEvent.addDomListener(mapDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/map_hover_icon.png)';
			});
			GEvent.addDomListener(mapDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/map_icon.png)';
			});
		}
	
		if (satellite)
		{
			// custom satellite button
			var satelliteDiv = document.createElement('div');
			satelliteDiv.style.backgroundImage='url(/content/mls/images/satellite_icon.png)';
			satelliteDiv.style.width = '58px';
			satelliteDiv.style.height = '26px';
			satelliteDiv.style.cssFloat = 'left';
			satelliteDiv.style.styleFloat = 'left';
			satelliteDiv.style.cursor = 'pointer';
			container.appendChild(satelliteDiv);
			GEvent.addDomListener(satelliteDiv, 'click', function() {
				map.setMapType(G_HYBRID_MAP);
			});
			GEvent.addDomListener(satelliteDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/satellite_hover_icon.png)';
			});
			GEvent.addDomListener(satelliteDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/satellite_icon.png)';
			});
		}
	
		if (terrain)
		{	
			// custom terrain button
			var terrainDiv = document.createElement('div');
			terrainDiv.style.backgroundImage='url(/content/mls/images/terrain_icon.png)';
			terrainDiv.style.width = '55px';
			terrainDiv.style.height = '26px';
			terrainDiv.style.cssFloat = 'left';
			terrainDiv.style.styleFloat = 'left';
			terrainDiv.style.cursor = 'pointer';
			container.appendChild(terrainDiv);
			GEvent.addDomListener(terrainDiv, 'click', function() {
				map.setMapType(G_PHYSICAL_MAP);
			});
			GEvent.addDomListener(terrainDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/terrain_hover_icon.png)';
			});
			GEvent.addDomListener(terrainDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/terrain_icon.png)';
			});
		}
	
		if (search)
		{
			// search by map button
			var searchDiv = document.createElement('div');
			searchDiv.style.backgroundImage='url(/content/mls/images/search_map_icon.png)';
			searchDiv.style.width = '139px';
			searchDiv.style.height = '29px';
			searchDiv.style.cursor = 'pointer';
			searchDiv.style.clear = 'both';
			searchDiv.style.marginLeft = '15px';
			container.appendChild(searchDiv);
			GEvent.addDomListener(searchDiv, 'click', function() {
				var latitude_min = (map.getBounds().getSouthWest().lat()).toPrecision(9);
				var latitude_max = (map.getBounds().getNorthEast().lat()).toPrecision(9);
				var longitude_min = (map.getBounds().getSouthWest().lng()).toPrecision(9);
				var longitude_max = (map.getBounds().getNorthEast().lng()).toPrecision(9);
		
				var loc = '/mls/home/?';
				if ($('property_search_form'))
				{
					var form_el = $('property_search_form').elements;
					for (var i = 0; i < form_el.length; i++)
					{
						if (form_el[i].type == 'checkbox')
						{
							if (form_el[i].checked)
							{
								if (form_el[i].value == 'on')
									form_el[i].value = '1';
								
								loc += form_el[i].name + '=' + form_el[i].value + '&';
							}
						}
						else
						{
							if (form_el[i].name != 'location')
								loc += form_el[i].name + '=' + form_el[i].value + '&';
						}
					}
				}
				else
				{
					loc += 'property_search=1&';
				}
		
				loc += 'latitude_min=' + latitude_min + '&latitude_max=' + latitude_max + '&longitude_min=' + longitude_min + '&longitude_max=' + longitude_max;
		
				var vars = window.location.href.split('&');
				for (var i = 0; i < vars.length; i++)
				{
					var parts = vars[i].split('=');
					if (parts[0] == 'view')
					{
						loc += '&view='+parts[1];
						break;
					}
				}
		
				window.location = loc;
			});
			
			GEvent.addDomListener(searchDiv, 'mouseover', function() {
				this.style.backgroundImage='url(/content/mls/images/search_map_hover_icon.png)';
			});
			GEvent.addDomListener(searchDiv, 'mouseout', function() {
				this.style.backgroundImage='url(/content/mls/images/search_map_icon.png)';
			});
		}
	
		map.getContainer().appendChild(container);
		return container;
	}
	
	TextualMapTypeControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
	}
	map.addControl(new TextualMapTypeControl());
}

function handleNoFlash(errorCode)
{
	if (errorCode == 603)
	{
		$(street_id).innerHTML = '"<div class="streetViewError">Flash doesn\'t appear to be supported by your browser, or you do not have flash installed. <a href="http://get.adobe.com/flashplayer/" target="_blank">Click Here to Download</a></div>';
		return;
	}
	
	else if (errorCode == 600)
	{
		$(street_id).innerHTML = '<div class="streetViewError">Sorry, Street View is unavailable for this address. This usually happens when a property is situated a considerable distance from the main road, preventing accurate detection of the best street location.</div>';
		return;
	}
}

function handleErrors(errorCode)
{
	$('print_direction').innerHTML = '';
	if (directions.getStatus().code == 602) {
		$('route_info').innerHTML = "<div class='directionError'>No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.</div>";
		return;
	}
	else if (directions.getStatus().code == 500) {
		$('route_info').innerHTML = "<div class='directionError'>A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.</div>";
		return;
	}
	else if (directions.getStatus().code == 601) {
		$('route_info').innerHTML = "<div class='directionError'>The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.</div>";
		return;
	}
	else if (directions.getStatus().code == 610) {
		$('route_info').innerHTML = "<div class='directionError'>The given key is either invalid or does not match the domain for which it was given.</div>";
		return;
	}
	else if (directions.getStatus().code == 400) {
		$('route_info').innerHTML = "<div class='directionError'>A directions request could not be successfully parsed.</div>";
		return;
	}
	else {
		$('route_info').innerHTML = "<div class='directionError'>An unknown error occurred.</div>";
		return;
	}
}

	
function setMarkers()
{
	if(typeof(properties) != 'undefined' && properties.length > 0)
	{
		var bounds = new GLatLngBounds();
		mgr = new MarkerManager(map);
		var markers = [];
		for (var a=0; a<properties.length; a++)
		{
			var property = properties[a];
			var pos = new GLatLng(property[1], property[2]);
			bounds.extend(pos);
			var marker = createMarker(pos, property[6], icons[property[3]][property[4]], property[5], property[0]);
			markers.push(marker);
			all_markers.push(marker);
		}
		var zoom = map.getBoundsZoomLevel(bounds);
		
		if(zoom > zoom_min)
			zoom = zoom_min;
			
		map.setCenter(bounds.getCenter(), zoom);
		mgr.addMarkers(markers, 1, 17);
		mgr.refresh();
			
		adjustMapBounds();
	}
}

function createMarker(pos, title, icon, html, id)
{
	var marker = new GMarker(pos, {title: title, icon: icon });
	
	if (list_page)
	{
		// Tack this on by accessing the custom_infowindow cssID
		var scroll = new Fx.Scroll2('mls_list', {
			wait: false,
			duration: 1000,
			transition: Fx.Transitions.Quad.easeInOut
		});
	
		GEvent.addListener(marker, 'mouseover', function() { 
			marker.openExtInfoWindow(map, 'custom_infowindow', html, {beakOffset: 8, paddingX: 100, paddingY: 45});
			scroll.toElement(id);
	
			var tr_array = $('mls_list').getElementsByTagName('tr');
			for (var i = 0; i < tr_array.length; i++)
			{
				if ($(tr_array[i]).hasClass('map_list_background_sel'))
					$(tr_array[i]).removeClass('map_list_background_sel');
			}
			$(id).addClass('map_list_background_sel');
		});
	}
	GEvent.addListener(marker, 'click', function() {
		marker.openExtInfoWindow(map, 'custom_infowindow', html, {beakOffset: 8, paddingX: 100, paddingY: 45});
	});
	
	return marker;
}
	
function changeMarker(title, icon, class_name)
{
	for (var i = 0; i < all_markers.length; i++)
	{
		if (all_markers[i].getTitle() == title)
		{
			if (icon == 'favorite')
			{
				properties[i][5] = properties[i][5].replace(/favorites_map_add/i, 'favorites_map_added');
				properties[i][5] = properties[i][5].replace(/<a href=\"javascript\:void\(0\);\" onClick\=\"mls_add_favorite\(\'[^']*\', \'[^']*\', \'[^']*\', \'[^']*\', \'[^']*\', \'[^']*\', \'[^']*\', \w*\);\">Favorites<\/a>/i, '<b>Favorite</b>');
			}
			
			var new_marker = createMarker(all_markers[i].getPoint(), all_markers[i].getTitle(), icons[icon][class_name], properties[i][5]);
			mgr.removeMarker(all_markers[i]);
			mgr.addMarker(new_marker, 1, 17);
			mgr.refresh();
			all_markers[i] = new_marker;
			break;
		}
	}
}
	
function removeMarker(title)
{
	for (var i = 0; i < all_markers.length; i++)
	{
		if (all_markers[i].getTitle() == title)
		{
			all_markers[i].hide();
			all_markers.splice(i, 1);
			properties.splice(i, 1);
		}
	}
}

function mls_add_favorite(mls_service, mls_class, listing_id, mls_type, obj, address, class_standard, compact)
{
	// change marker to favorite
	changeMarker(address, 'favorite', class_standard);

	if ($('mls_favorites_'+obj))
	{
		if (compact)
			$('mls_favorites_'+obj).innerHTML = '<b>Favorite</b>';
		else
			$('mls_favorites_'+obj).innerHTML = '<b>Added to Favorites</b>';
		
		$('mls_favorites_'+obj).addClass('favorites_added');
	}
	if ($('mls_map_favorites_'+obj))
	{
		$('mls_map_favorites_'+obj).innerHTML = '<b>Favorite</b>';
		$('mls_map_favorites_'+obj).addClass('favorites_map_added');
	}
	if ($(mls_service+'_'+listing_id+'_img'))
		$(mls_service+'_'+listing_id+'_img').innerHTML = '<img src=\"/content/mls/images/property_icons/favorite/'+class_standard+'.png\" />';
	
	var req = new Request({
		method: 'get',
		url: '/mls/home/?mls_action=add_favorite&favorite_service='+mls_service+'&favorite_class='+mls_class+'&favorite_listing_id='+listing_id+'&favorite_type='+mls_type,
		data: { 'do' : '1' },
		onComplete: function(response) { },
		onSuccess: function() {	}
	}).send();
}
	
function mls_list_highlight(id)
{
	var tr_array = $('mls_list').getElementsByTagName('tr');
	
	for (var i = 0; i < tr_array.length; i++)
	{
		if ($(tr_array[i]).hasClass('map_list_background_sel'))
			$(tr_array[i]).removeClass('map_list_background_sel');
	}
	
	$(id).addClass('map_list_background_sel');
	
	for (var i = 0; i < properties.length; i++)
	{
		if (properties[i][0] == id)
			GEvent.trigger(all_markers[i], 'click');
	}
}

function preload_map_icons()
{
	img = new Image(); 
	img.src = '/content/mls/images/zoom_in_hover_icon.png';
	img = new Image(); 
	img.src = '/content/mls/images/zoom_out_hover_icon.png';
	img = new Image(); 
	img.src = '/content/mls/images/map_hover_icon.png';
	img = new Image(); 
	img.src = '/content/mls/images/satellite_hover_icon.png';	
	img = new Image(); 
	img.src = '/content/mls/images/terrain_hover_icon.png';
	img = new Image(); 
	img.src = '/content/mls/images/search_map_hover_icon.png';
	img = new Image(); 
	img.src = '/content/mls/images/b_street_view_internal.png';
	img = new Image(); 
	img.src = '/content/mls/images/b_street_view_internal_on.png';
	img = new Image(); 
	img.src = '/content/mls/images/print_directions_icon.png';
	img = new Image(); 
	img.src = '/content/properties/images/map_route_on.png';
	img = new Image(); 
	img.src = '/content/properties/images/map_route.png';
	
	
}