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

$(document).ready(function() {
	if(CookieManager.getCookie('postalcode')) {
		var address = trim(CookieManager.getCookie('postalcode'));
		$('#postal_code').val(address);
		$('#postal_code_reset').val(address);
	}
	$('#show_locations').submit(function() {
		$('#postal_code_reset').val($('#postal_code').val());
		showLocations();
        return false;
	});
	$('#reset_locations').submit(function() {
		showLocations();
        return false;
	});
	$('#radius_reset').change(function() {
		showLocations();
        return false;
	});
    $('#changeMapSizeButton').click(function() {
        changeMapSize();
        return false;
    });
	$('#date_start_reset, #date_end_reset').datepicker({
		speed: 'fast',
		showOn: 'both',
		buttonImage: '/images/icons/calendar.png',
		buttonImageOnly: true
	});
});

// Sale Locator Map Display Variables

var lastPoint;
var loaded = false;

function loadMap(point) {
	if (loaded) return;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		//map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		if (typeof point != 'undefined') {
			map.setCenter(point);
		}
		else {
			map.setCenter(new GLatLng(60.0000, -97.0000), 3);
		}
		mgr = new MarkerManager(map, {trackMarkers:true});
		//updateMap();
		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();

	// set cookie information for future quick-reloads if necessary
	// if map is loaded OR if there's no cookie OR if cookie does not match the postal code requested, create new cookie
	if (loaded || !CookieManager.getCookie('postalcode') || CookieManager.getCookie('postalcode') != trim($('#postal_code_reset').val())) {
		expiry = new Date();
		expiry.setFullYear(new Date().getFullYear() + 1);

		CookieManager.setCookie('postalcode', trim($('#postal_code_reset').val()), expiry);
		// WESLEY - commented out radius cookie, related to the auto-reload functionality (06-11-2009)
		// CookieManager.setCookie('radius', radius, expiry);
	}
	var radius = $('#radius_reset').val();
	var date_start = $('#date_start_reset').val();
	var date_end = $('#date_end_reset').val();
	var address = trim($('#postal_code_reset').val());
	
	/* WESLEY - commented out the auto-reload functionality, deemed too confusing for Scarlett users? (06-11-2009)
	else {
		var radius = CookieManager.getCookie('radius');
		var date_start = $('#date_start_reset').val();
		var date_end = $('#date_end_reset').val();
		var address = trim(CookieManager.getCookie('postalcode'));
	}
	*/

	if (address == '') {
		alert("Please enter a postal code");
		$('#postal_code')[0].focus();
		return false;
	}
	
	var postalcode_regex = /^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i;

	if (!postalcode_regex.test(address)) {
		// incorrect postalcode format
		alert('Invalid Postal Code');
		return false;
	}

	// ajax indicator
	var mapbody = $('#mapbody');
	var drape = null;
	if($('#drape').length > 0) {
		drape = $('#drape');
	} else {
		drape = $(document.createElement('div')).attr('id','drape');
		$('body').append(drape);
		indicator = $(document.createElement('img')).attr('src','http://images.redflagdeals.com/redesign/indicatorBar.gif');
		indicator.css({
			'position': 'absolute',
			'top': '50%',
			'left': '50%',
			'margin': '-10px 0 0 -110px'
		});
		drape.append(indicator);
	}
	drape.width(mapbody.width()).height(mapbody.height());
	drape.css({
		'position': 'absolute',
		'background': '#fff',
		'left': mapbody.offset().left + 'px',
		'top': mapbody.offset().top + 'px',
		'z-index': 6000,
		'opacity': 0.8,
		'filter': 'alpha(filter=80)'
	});
	drape.hide();
	
	var geocoder = new GClientGeocoder();

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

		}
	});
	
	return true;
}

function handleSuccess(response) {
	// Load XML Document
	var xml = response;

	// Errors?
	var err_no  = xml.getElementsByTagName('err_no')[0].childNodes[0].nodeValue;

	// Error Check
	if (err_no != 0)
	{
		var err_msg = xml.getElementsByTagName ('err_msg')[0].childNodes[0].nodeValue;
		$('#drape').hide();
		$('#mapbody').hide();
		alert(err_msg);
		return;
	}
		
	// mgr.refresh();	  

	// Add Sales To Map
	var locations = xml.getElementsByTagName('location');
	
	// alert(locations.length + " sales found!");
	
	$('.sale').remove();
	
	if (locations.length < 1) {
	    $('#drape').hide();
	    $('#weblog_entries').hide()
		alert('Sorry, we did not find any garage sales within ' + $('#radius').val() + ' KM of your postal code.');
		//$('#mapbody').hide();
	}
	else {
		// Loop and populate City Select Form
		for (var i = 0 ; i < locations.length ; i++)
		{
			var dealTemplate = $('#sale_template').clone().addClass('sale');
	
			var location = locations[i];
	
			var lat = location.getElementsByTagName("lat")[0].firstChild.nodeValue;
			var lng = location.getElementsByTagName("long")[0].firstChild.nodeValue;
			var entry_id = location.getElementsByTagName("entry_id")[0].firstChild.nodeValue;
			var title = location.getElementsByTagName("title")[0].firstChild.nodeValue;
			var url_title = location.getElementsByTagName("url_title")[0].firstChild.nodeValue;
			var comments = location.getElementsByTagName("comments")[0].firstChild.nodeValue;
			var address = location.getElementsByTagName("addr")[0].firstChild.nodeValue;
			var city = location.getElementsByTagName("city")[0].firstChild.nodeValue;
			var postal_code = location.getElementsByTagName("pcode")[0].firstChild.nodeValue;
			var date_start = location.getElementsByTagName("date_start")[0].firstChild.nodeValue;
			var date_end = location.getElementsByTagName("date_end")[0].firstChild.nodeValue;
			var hours = location.getElementsByTagName("hours")[0].firstChild.nodeValue;
			var desc = location.getElementsByTagName("desc")[0].firstChild.nodeValue;
			var rain_or_shine = location.getElementsByTagName("rain_or_shine")[0].firstChild.nodeValue;
			var distance = location.getElementsByTagName("distance")[0].firstChild.nodeValue;
			var zoom_min = location.getElementsByTagName("zoom_min")[0].firstChild.nodeValue;
			var zoom_max = location.getElementsByTagName("zoom_max")[0].firstChild.nodeValue;
			var saved = location.getElementsByTagName("bookmarked")[0].firstChild.nodeValue;
	
			var point = new GLatLng(lat, lng, false);
	
			// Create Icon
			// See for information about creating icons:
			// http://www.google.com/apis/maps/documentation/#API_Overview
			var garagePin = new GIcon();
			garagePin.image = 'http://images.redflagdeals.com/redesign/pin_garage.png';
			garagePin.shadow = 'http://images.redflagdeals.com/redesign/pinshadow_garage.png';
			garagePin.iconSize = new GSize(20, 30);
			garagePin.iconAnchor = new GPoint(10, 28);
			garagePin.infoWindowAnchor = new GPoint(10, 8);
			garagePin.infoShadowAnchor = new GPoint(22, 18);
			garagePin.shadowSize = new GSize(40, 30);

			var point = new GLatLng(lat, lng, false);
	
			/*
			if they fall within the map's current viewport and the map's zoom level is greater than or equal to
			the specified minZoom. If the maxZoom  was given, the markers are automatically removed
			if the map's zoom is greater than the one specified. (Since 2.67)
	
			1 - nation level
			10 - street level
			*/
			marker = createMarker(point, '<strong>Where:</strong><br />' + address + '<br /><br /><strong>When:</strong><br />' + date_start + ' - ' + date_end + '<br /><br /><strong>Distance:</strong><br />' + distance + ' KM<br /><br /><a href="#' + entry_id + '">More details</a>', garagePin);
			mgr.addMarker(marker, zoom_min);
			
			dealTemplate.attr('id','sale_' + entry_id);
			dealTemplate.find('p.sale_location').html(address);
			dealTemplate.find('span.sale_distance').html(distance);
			dealTemplate.find('a.sale_directions').attr('href','http://maps.google.com/?q=' + encodeURIComponent($('#postal_code_reset').val() + ' to ' + address.replace(/(<br \/>|\n|\r)/g, ' ') + ', ' + city));
			dealTemplate.find('p.sale_dates').html(date_start + (date_start != date_end ? (' &ndash; ' + date_end) : '') + '<br />' + hours);
			dealTemplate.find('h3.sale_title').html(title);
			dealTemplate.find('p.sale_description').html(desc);
			dealTemplate.find('span.sale_postdate').html(distance);
			if ( $.trim(rain_or_shine) == 'Yes') {
                dealTemplate.find('span.sale_weather').show();
			} else {
                dealTemplate.find('span.sale_weather').hide();
			}
			dealTemplate.find('a.sale_permalink').attr('href','/garage-sales/sale-detail/' + url_title + '/?origin=' + encodeURIComponent($('#postal_code_reset').val()));
			dealTemplate.find('a.sale_permalink_comments').attr('href','/garage-sales/sale-detail/' + url_title + '/?origin=' + encodeURIComponent($('#postal_code_reset').val()) + '#comments').html(comments == 1 ? (comments + ' comment') : (comments + ' comments'));
		
			$('#results ul').append(dealTemplate);
			/*
			var temp = dealTemplate;

			if(saved == 1) {
				temp = temp.replace('%%NOT_SAVED%%', 'hidden');
				temp = temp.replace('%%SAVED%%', '');
			} else {
				temp = temp.replace('%%NOT_SAVED%%', '');
				temp = temp.replace('%%SAVED%%', 'hidden');
			}
			
			temp = temp.replace(/%%ENTRY_ID%%/g, entry_id);
			temp = temp.replace('%%TITLE%%', title);
			temp = temp.replace(/%%URL_TITLE%%/g, url_title);
			temp = temp.replace('%%COMMENTS%%', comments);
			temp = temp.replace(/%%ADDRESS%%/g, address);
			temp = temp.replace(/%%CITY%%/g, city);
			temp = temp.replace('%%DISTANCE%%', distance);
			temp = temp.replace('%%MAPADDRESS%%', encodeURIComponent($('#postal_code').val() + ' to ' + address.replace(/(<br \/>|\n|\r)/g, ' ')));
			temp = temp.replace('%%START%%', date_start);
			temp = temp.replace('%%END%%', date_end);
			if(date_start == date_end) {
				temp = temp.replace(/%%DATES%%/g, date_start);
			} else {
				temp = temp.replace(/%%DATES%%/g, date_start + ' &ndash; ' + date_end);
			}
			temp = temp.replace('%%HOURS%%', hours);
			temp = temp.replace('%%DESCRIPTION%%', desc);
			
			if ( $.trim(rain_or_shine) == 'Yes') {
			    var rainorshine = '';
			    rainorshine += '<img src="http://images.redflagdeals.com/redesign/weather_rain.png" width="16" height="16" alt="" style="vertical-align:middle" /> <img src="http://images.redflagdeals.com/redesign/weather_sun.png" width="16" height="16" alt="" style="vertical-align:middle" /> Rain or shine!';
                temp = temp.replace('%%RAIN_OR_SHINE%%', rainorshine);
			} else {
                temp = temp.replace('%%RAIN_OR_SHINE%%', '');
			}

			dealTxt += temp;
			
			/*dealTxt += '<div style="margin:5px 0; border:1px solid #CCCCCC; padding:5px">';
			dealTxt += '<h2>' + location.getElementsByTagName("title")[0].firstChild.nodeValue + '</h2>';
			dealTxt += location.getElementsByTagName("body")[0].firstChild.nodeValue + '<br /><br />';
			dealTxt += '<b>Address:</b><br />' + location.getElementsByTagName("addr")[0].firstChild.nodeValue;
			dealTxt += '</div>';*/
		}
		
		/*
		if (typeof(lastPoint) != 'undefined') {
			dealTxt = '<h1>Garage Sales within ' + $('#radius').val() + ' KM of ' + $('#postal_code').val().toUpperCase() + ' (by distance)</h1><br />' + dealTxt;
			$('#weblog_entries').show().html(dealTxt);
		}
		*/
		
		$('#num_results').html(locations.length);
		$('#results').show();
		$('#display_radius').text($('#radius_reset').val());
		$('#display_postal_code').text($('#postal_code_reset').val());
		$('#drape').hide();
		$('#postmap_text').slideDown();
	}
	
	var sourcePin = new GIcon();
	sourcePin.image = 'http://images.redflagdeals.com/redesign/pin_start.png';
	sourcePin.shadow = 'http://images.redflagdeals.com/redesign/pinshadow_start.png';
	sourcePin.iconSize = new GSize(16, 30);
	sourcePin.iconAnchor = new GPoint(8, 28);
	sourcePin.infoWindowAnchor = new GPoint(8, 8);
	sourcePin.infoShadowAnchor = new GPoint(22, 18);
	sourcePin.shadowSize = new GSize(40, 30);

	//var point = new GLatLng(lat, lng, false);
	marker = createMarker(lastPoint, 'Your Location:<br />' + $('#postal_code').val().toUpperCase(), sourcePin);
	mgr.addMarker(marker, 5);
	
	// circle radius overlay
	// requires gmaps.CircleOverlay.js from http://dawsdesign.com/drupal/google_maps_circle_overlay (modified to take km instead of mi)
	circle = new CircleOverlay(lastPoint, $('#radius_reset').val(), '#000099', 1, 0.5, '#000099', 0.1);
	map.addOverlay(circle);
};
	
	
	
/*	
	$('#drape').hide();
	
	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
	//alert('http://www.redflagdeals.com/deals/main.php/salelocator/getgaragexml?point=' + encodeURI(point) + '&radius=' + $('#radius').val() + '&start=' + encodeURI($('#date_start').val()) + '&end=' + encodeURI($('#date_end').val()));
	$.ajax({
		type : 'GET',
		url : '/external/getGarageXML.php',
		data : 'point=' + encodeURI(point) + '&radius=' + $('#radius_reset').val() + '&start=' + encodeURI($('#date_start_reset').val()) + '&end=' + encodeURI($('#date_end_reset').val()),
		success : handleSuccess,
		error : handleFailure
	});
}

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;
}

// Trims whitespace off of string
function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '')
};
