var map; // GoogleMap Instance
var mgr; // GoogleMap Marker Manager Instance

$(document).ready(function() {
	$('#show_locations').submit(function() {
		showLocations();
        return false;
	});
    $('#changeMapSizeButton').click(function() {
        changeMapSize();
        return false;
    });
});

// Sale Locator Map Display Variables

var lastPoint;
var loaded = false;

function loadMap() {
	if (loaded) return;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById('map'));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(60.0000, -97.0000), 3);
		mgr = new MarkerManager(map, {trackMarkers:true});
		loaded = true;
	}
	else {
		alert('Your browser is not compatible with this page. Please upgrade to a more recent version.')
	}
}

// postal code zoom in on gmap
function showLocations() {
	$('#splash').hide();
	$('#mapbody').show();
	
	loadMap();
	
	var postal_code = $('#postal_code').val();
	var address = $.trim(postal_code);
	var postal_code_regex = /^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i
	
	if (postal_code == '') {
		alert("Please enter a postal code");
		$('#postal_code')[0].focus();
		return false;
	} else if (!postal_code_regex.test(postal_code)) { // Invalid postal code
		alert('Invalid Postal Code');
		$('#postal_code')[0].focus();
		return false;
	}

	var geocoder = new GClientGeocoder();

	geocoder.getLatLng(address, function(point) {
		if (!point) {
			alert(address + ' not found');
		} else {
			updateMap(point); // To get sales close to location
			window.setTimeout(function() {map.panTo(point);}, 1000);
			
			switch ($('#radius').val()) {
				case '5':				map.setZoom(12);	break;
				case '10':				map.setZoom(11);	break;
				case '50':				map.setZoom(9);		break;
				case '100':				map.setZoom(8);		break;
				case '25':	default:	map.setZoom(10);	break;
			}
		}
	});

	return true;
}

function handleSuccess(response) {
	$('#results').html(response);
	
	var icon = new GIcon();
	icon.image = 'http://scarlett.redflagdeals.com/images/pin_actual.png';
	icon.iconSize = new GSize(17, 24);
	icon.iconAnchor = new GPoint(9, 34);
	icon.infoWindowAnchor = new GPoint(9, 2);
	icon.infoShadowAnchor = new GPoint(18, 25);

	marker = createMarker(lastPoint, 'Your Location:<br />' + $('#postal_code').val().toUpperCase(), icon);
	mgr.addMarker(marker, 5);
	
	$('#show_locations_wait').hide();
};

function handleFailure(o) {
	$('#show_locations_wait').hide();
	if (o.responseText !== undefined) {
		alert("Unable to fufill request. Please try again later.<br /><li>Transaction id: " + o.tId + "</li><li>HTTP status: " + o.status + "</li><li>Status code message: " + o.statusText + "</li>");
	}
};

function updateMap(point) {
	lastPoint = point;
	
	// Clear Markers from GoogleMap MarkerManager
	mgr.clearMarkers();
	
	// Clear Overlays from GoogleMap
	map.clearOverlays();
	
	$('#show_locations_wait').show();
	// Build and Perform AJAX Request
	$.ajax({
		type : 'POST',
		url : '/sale-locator/ajax-results/',
		data : 'postal_code=' + $('#postal_code').val() + '&point=' + encodeURI(point) + '&radius=' + $('#radius').val() + '&type=' + $('#type').val(),
		success : handleSuccess,
		error : function(response, text) { $('#indicator').hide(); alert('Error fetching sales: ' + response); }
	});
}

function changeMapSize() {
	var mapdiv = $('#map');
	var button = $('#changeMapSizeButton');
	
	if (mapdiv.css('height') == "300px")
	{
		// SHRINK MAP
		mapdiv.css('height', 500 + "px");
		button.html("<span>SHRINK MAP</span>");
	} else {
		// EXPAND MAP
		mapdiv.css('height', 300 + "px");
		button.html("<span>EXPAND MAP</span>");
	}
}

// Creates GMarker with HTML Info Box and Custom Icon (GIcon)
function createMarker(point,html, icon) {
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}