/* ALSO REQUIRES COOKIEMANAGER.JS */

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

// Sale Locator Map Display Variables

var lastPoint;

var loaded = false;

jQuery.fn.jumpTo = function() {
	var pos = $(this).offset();
	window.scrollTo(pos.left, pos.top);
	return;
}
$(document).ready(function() {
	if (typeof(window.cityinfo) == 'undefined') { // We're NOT on a city-specific landing page
		// priority: postal code submitted via query string, THEN postal code from cookie, THEN default search page
		if(window.location.href.indexOf('postal_code=') != -1) {
			var radius = '25';
			var pcode_param = window.location.href.match(/(\?|\&)postal_code=([a-z][0-9][a-z] ?[0-9][a-z][0-9])/i);
			if(pcode_param.length > 0) {
				var address = pcode_param[2];
				zoomPostalCode({
					'address': address,
					'radius': radius,
					'date_start': $('#params_date_start'),
					'date_end': $('#params_date_end')
				});
				$('#params_postal_code').val(address);
				$('#params_radius').val(radius);
			}
		}
		else if(getCookie('postalcode')) {
			var radius = getCookie('radius');
			var address = trim(getCookie('postalcode'));
			zoomPostalCode();
			$('#params_postal_code').val(address);
			$('#params_radius').val(radius);
		}
		
		$('#postal_code').bind('keyup', function() {
			if ($(this).val().match(/[a-z]\d[a-z][\s-]*\d[a-z]\d/i)) {
				zoomPostalCode();
				$('#params_postal_code').val($('#postal_code').val());
			}
		});
	}

	$('#city').change(function() {
		if ($(this).val() != 'none') {
			window.location = 'http://www.redflagdeals.com/garagesales/in/' + $(this).val() + '/';
		}
		return 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.');
	}
}
/*
function showAddress(address)
{
	var geocoder = new GClientGeocoder();
	var address = "90210";
	geocoder.getLatLng(address,
	function(point) {
		if (!point) {
			alert(address + " not found");
		} else {
			map.setCenter(point, 13);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			marker.openInfoWindowHtml(address);
		}
	}
	)
};
*/

// postal code zoom in on gmap
function zoomPostalCode(opt) {
	opt = opt || {};

	$('#splash').hide();
	$('#mapbody').show();

	// set cookie information for future quick-reloads if necessary
	if (opt.address) {
		var radius = opt.radius;
		var date_start = opt.date_start;
		var date_end = opt.date_end;
		var address = trim(opt.address);
	} else if (loaded || !getCookie('postalcode')) {
		expiry = new Date();
		expiry.setFullYear(new Date().getFullYear() + 1);

		var radius = $('#radius').val();
		var date_start = $('#date_start').val();
		var date_end = $('#date_end').val();
		var address = trim($('#postal_code').val());
		
		setCookie('postalcode', address, expiry);
		setCookie('radius', radius, expiry);
		setCookie('date_start', date_start, expiry);
		setCookie('date_end', date_end, expiry);
	} else {
		var radius = getCookie('radius');
		var date_start = $('#date_start').val();
		var date_end = $('#date_end').val();
		var address = trim(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');
		$('#mapbody').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() - 2).height(mapbody.height() - 2);
	drape.css({
		'position': 'absolute',
		'background': '#fff',
		//'left': (mapbody.offset().left + 1) + 'px',
		//'top': (mapbody.offset().top + 1) + 'px',
		'left': '1px',
		'top': '1px',
		'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(8);
				break;
				
				case '50':
					map.setZoom(9);
				break;
				
				case '25':
				case '20':
				case '15':
					map.setZoom(10);
				break;
				
				case '10':
					map.setZoom(11);
				break;
				
				case '5':
				default:
					map.setZoom(12);
				break;
			}

		}
	}
	)

	return true;

}

// province zoom in on gmap
function zoomProvince(index)
{
	// alert(index);
	map.closeInfoWindow();	
	
	var zoomForm = document.getElementById('salelocator_form');
	
	/*
	var zoomValue = zoomForm.province.options[zoomForm.province.selectedIndex].value;
	*/
	// var zoomValue = zoomForm.province.options[index].value;

	zoomForm.postalcode.value = '';

	var zoomValue = index;
	
	var lat  =  60.0000;
	var lng  = -97.0000;
	var zoom =  3;

	switch(zoomValue)
	{

		/*
		case 'AB':
		lat = '55.00';
		lng = '-114.000';
		zoom = 5;
		break;
		
		case 'BC':
		lat = '55.00';
		lng = '-127.000';
		zoom = 5;
		break;

		case 'MB':
		lat = '55.00';
		lng = '-97.000';
		zoom = 5;
		break;

		case 'NB':
		lat = '46.34';
		lng = '-66.000';
		zoom = 7;
		break;

		case 'NL':
		lat = '52.61';
		lng = '-60.000';
		zoom = 5;
		break;

		case 'NT':
		lat = '67.407';
		lng = '-117.246';
		zoom = 4;
		break;

		case 'NS':
		lat = '45.259';
		lng = '-63.017';
		zoom = 7;
		break;

		case 'NU':
		lat = '68.334';
		lng = '-98.349';
		zoom = 4;
		break;

		case 'ON':
		lat = '45.000';
		lng = '-73.825';
		zoom = 5;
		break;		

		case 'PE':
		lat = '46.649';
		lng = '-63.182';
		zoom = 7;
		break;

		case 'QC':
		lat = '54.367';
		lng = '-66.708';
		zoom = 4;
		break;

		case 'SK':
		lat = '55.00';
		lng = '-105.000';
		zoom = 5;
		break;

		case 'YT':
		lat = '64.923';
		lng = '-132.143';
		zoom = 5;
		break;		
		*/
	
		case 'AB':
		lat = '50.972265';
		lng = '-116.060059';
		zoom = 5;
		break;

		case 'BC':
		lat = '49.181703';
		lng = '-123.354492';
		zoom = 5;
		break;
		
		case 'MB':
		lat = '49.894634';
		lng = '-97.185059';
		zoom = 5;
		break;

		case 'NB':
		lat = '46.34';
		lng = '-66.000';
		zoom = 7;
		break;

		case 'NL':
		lat = '52.61';
		lng = '-60.000';
		zoom = 5;
		break;

		case 'NT':
		lat = '67.407';
		lng = '-117.246';
		zoom = 4;
		break;

		case 'NS':
		lat = '44.668653';
		lng = '-63.621826';
		zoom = 7;
		break;

		case 'NU':
		lat = '68.334';
		lng = '-98.349';
		zoom = 4;
		break;

		case 'ON':
		lat = '45.000';
		lng = '-73.825';
		zoom = 5;
		break;		

		case 'PE':
		lat = '46.649';
		lng = '-63.182';
		zoom = 7;
		break;
		
		case 'QC':
		lat = '45.675482';
		lng = '-73.564453';
		zoom = 5;
		break;

		case 'SK':
		lat = '51.862924';
		lng = '-105.996094';
		zoom = 5;
		break;

		case 'YT':
		lat = '64.923';
		lng = '-132.143';
		zoom = 5;
		break;

		default:
		lat  =  60.0000;
		lng  = -97.0000;
		zoom =  3;
		break;
	}

	window.setTimeout(function() {map.panTo(new GLatLng(lat, lng));}, 1000);
	selectedZoom = zoom;
	map.setZoom(zoom);
}

function setView(view)
{
	// Reset previous selected type
	changeClass("view_" + selectedView, 'sortingUnselect');

	switch (view)
	{
		case 'upcoming':
			changeClass('view_upcoming', 'sortingSelect');
			selectedView = 'upcoming';
		break

		case 'current':
			changeClass('view_current', 'sortingSelect');
			selectedView = 'current';
		break;
		
		case 'all':
		default:
			changeClass('view_all', 'sortingSelect');
			selectedView = 'all';
		break;		

	}

	updateMap();
};

function setCategory(cat)
{
	selectedCat = cat;
	updateMap();
}

function setType(type)
{

	// Reset previous selected type
	changeClass("type_" + selectedType, 'sortingUnselect');

	switch (type)
	{
		case "warehouse":
		changeClass('type_warehouse', 'sortingSelect');
		selectedType = 'warehouse';
		document.salelocator_form.category.disabled = 0;
		break;

		case "outlet":
		changeClass('type_outlet', 'sortingSelect');
		selectedType = 'outlet';
		document.salelocator_form.category.disabled = 0;
		break;

		case "garage":
		changeClass('type_garage', 'sortingSelect');
		selectedType = 'garage';

		// Reset Previously Selected Category
		selectedCat = 0;

		// Reset & Disable Category Select
		document.salelocator_form.category.selectedIndex = 0;
		document.salelocator_form.category.disabled = 1;
		break;

		case 'all':
		default:
		changeClass('type_all', 'sortingSelect');
		selectedType = 'all';
		document.salelocator_form.category.disabled = 0;
	}

	updateMap();
};

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

	// 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!");
	
	var dealTemplate = $('#entry_template').html();
	var dealTxt = '';
	
	if (locations.length < 1) {
	    $('#drape').hide();
	    $('#weblog_entries').hide()
	    if (typeof(window.cityinfo) == 'undefined') { // We're NOT on a city-specific landing page
			alert('Sorry, we did not find any garage sales within ' + $('#radius').val() + ' KM of your postal code.');
		} else {
			//alert('Sorry, we did not find any garage sales in ' + cityinfo.name + ', ' + cityinfo.province);
			$('#mapmsg').html('Sorry, we did not find any garage sales in ' + window.cityinfo.name + ', ' + window.cityinfo.province + '. Would you like to <a href="/deals/main.php/garagesales/entryform/">add a sale?</a>');
			$('#mapmsg').show();
			$('#drape').show();
		}
		//$('#mapbody').hide();
	}
	else {
		// Loop and populate City Select Form
		for (var i = 0 ; i < locations.length ; i++)
		{
			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
			*/
			markerTxt = '<strong>Where:</strong><br />' + address + '<br /><br /><strong>When:</strong><br />' + date_start + ' - ' + date_end;
			if (typeof(window.cityinfo) == 'undefined') {
				markerTxt += '<br /><br /><strong>Distance:</strong><br />' + distance + ' KM<br /><br /><a href="#' + entry_id + '">More details</a>';
			}
			marker = createMarker(point, markerTxt, garagePin);
			mgr.addMarker(marker, zoom_min);
			
			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(window.cityinfo) != 'undefined' && window.cityinfo.name) {
			dealTxt = '<h1>Garage Sales in ' + window.cityinfo.name + ', ' + window.cityinfo.province + '</h1><br />' + dealTxt;
			$('#weblog_entries').show().html(dealTxt);
		} else 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_txt').show();
		$('#drape').hide();
	}
	
	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);
	
	if (typeof(window.cityinfo) == 'undefined') {
		marker = createMarker(lastPoint, 'Your Location:<br />' + $('#postal_code').val().toUpperCase(), sourcePin);
		mgr.addMarker(marker, 5);
	} else {
		marker = createMarker(lastPoint, null, 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').val(), '#000099', 1, 0.5, '#000099', 0.1);
	map.addOverlay(circle);
};

var handleFailure = function(o)
{
	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>");
	}
};

var callback =
{
	success:handleSuccess,
	failure:handleFailure
};

function updateMap(point)
{
	
	lastPoint = point;
	
	// Clear Markers from GoogleMap MarkerManager
	mgr.clearMarkers();
	
	// Clear Overlays from GoogleMap
	map.clearOverlays();
	
	// Build and Perform AJAX Request
	$.ajax({
		type : 'POST',
		url : '/deals/main.php/salelocator/getgaragexml',
		data : 'point=' + encodeURI(point) + '&radius=' + $('#radius').val() + '&start=' + encodeURI($('#date_start').val()) + '&end=' + encodeURI($('#date_end').val()),
		success : handleSuccess,
		error : function(response, text) { $('#drape').hide(); alert('Error fetching sales: ' + response); }
	});
}


function changeClass(elemId, className)
{
	document.getElementById(elemId).className = className;
}

function changeMapSize()
{
	map.savePosition();
	var mapdiv = $('#map');
	var button = $('#changeMapSizeButton');
	
	if (mapdiv.css('height') == "480px")
	{
		// SHRINK MAP
		mapdiv.css('height', 880 + "px");
		button.html("<strong>SHRINK MAP</strong>");
	} else {
		// EXPAND MAP
		mapdiv.css('height', 480 + "px");
		button.html("<strong>EXPAND MAP</strong>");
	}
	
	map.checkResize();
	map.returnToSavedPosition();
	map.disableScrollWheelZoom();
}

/**
 *	HELPER FUNCTIONS
 */

/*
Resets Map Controls and Map itself
*/
function resetMap(index)
{
	setView('current');	
	setType('all');
	setCategory('0');
	
	var zoomForm = document.getElementById('salelocator_form');
	zoomForm.province.selectedIndex = 0;
	zoomForm.category.selectedIndex = 0;	

	zoomProvince('XX');
	
	// var mapdiv = document.getElementById('map');
	var button = document.getElementById('changeMapSizeButton');
	map.style.height = 300 + "px";			
	button.innerHTML = "<strong>EXPAND MAP</strong>";	

}

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

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

// Returns value of xml node provided
function getValueFromXML( oNode )
{
	if (oNode.length == 0)
	{
		return(-9999);
	}
	var val = oNode[0].childNodes[0].nodeValue;
	return val;
};

