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

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});
		//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()
{
	$('#splash').hide();
	$('#mapbody').show();
	loadMap();
	var postalcode = $('#postal_code').val();
	
	var address = trim(postalcode);

	if (postalcode == '') {
		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(postalcode)) {
		// incorrect postalcode format
		alert('Invalid Postal Code');
		return false;
	}

	var geocoder = new GClientGeocoder();

	geocoder.getLatLng(address,
	function(point) {
		if (!point) {
			alert(address + " not found");
		} else {
			$('#results_txt').hide();
			$('#indicator').show();
			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;

}

// 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;;
		$('#indicator').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) {
		alert('Sorry, we did not find any locations close to your postal code.');
		$('#mapbody').hide();
		$('#mapbody').hide();
		$('#indicator').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 desc = location.getElementsByTagName("desc")[0].firstChild.nodeValue;
			var img = location.getElementsByTagName("img")[0].firstChild.nodeValue;
			var zoom_min = location.getElementsByTagName("zoom_min")[0].firstChild.nodeValue;
			var zoom_max = location.getElementsByTagName("zoom_max")[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 icon = new GIcon();
			icon.image = img;
			icon.iconSize = new GSize(17, 24);
			icon.iconAnchor = new GPoint(9, 34);
			icon.infoWindowAnchor = new GPoint(9, 2);
			icon.infoShadowAnchor = new GPoint(18, 25);
		
	
			// icon.shadowSize = new GSize(37, 34);
	
			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, desc, icon);
			mgr.addMarker(marker, zoom_min);
			
			var temp = dealTemplate;
			temp = temp.replace('%%WAREHOUSE_IMAGE%%', location.getElementsByTagName("warehouseimage")[0].firstChild.nodeValue);
			temp = temp.replace('%%ENTRY_DATE%%', location.getElementsByTagName("entry_date")[0].firstChild.nodeValue);
			temp = temp.replace('%%STARTS%%', location.getElementsByTagName("starts")[0].firstChild.nodeValue);
			temp = temp.replace('%%EXPIRES%%', location.getElementsByTagName("expires")[0].firstChild.nodeValue);
			temp = temp.replace('%%TITLE%%', location.getElementsByTagName("title")[0].firstChild.nodeValue);
			temp = temp.replace('%%BODY%%', location.getElementsByTagName("body")[0].firstChild.nodeValue);
			temp = temp.replace('%%ADDRESS%%', location.getElementsByTagName("addr")[0].firstChild.nodeValue);
			temp = temp.replace('%%DIRECTIONS%%', encodeURIComponent($('#postal_code').val() + ' to ' + lat + ',' + lng + ' (' + location.getElementsByTagName("nicetitle")[0].firstChild.nodeValue + ')'));
			temp = temp.replace('%%SOURCE%%', location.getElementsByTagName("source")[0].firstChild.nodeValue);
			temp = temp.replace(/%%URL_TITLE%%/g, location.getElementsByTagName("url_title")[0].firstChild.nodeValue);
			temp = temp.replace(/%%ENTRY_ID%%/g, location.getElementsByTagName("entry_id")[0].firstChild.nodeValue);
			
			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>Sales within ' + $('#radius').val() + ' KM of ' + $('#postal_code').val().toUpperCase() + ' (by distance)</h1>' + dealTxt;
			$('#weblog_entries').show().html(dealTxt);
		}
		
		$('#num_results').html(locations.length);
		$('#results_txt').show();
		$('#indicator').hide();
	}
	
	//var point = new GLatLng(lat, lng, false);
	marker = createMarker(lastPoint, 'Your Location:<br />' + $('#postal_code').val().toUpperCase());
	mgr.addMarker(marker, 5);
};

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/getxml',
		data : 'type=' + selectedType + '&view=' + selectedView + '&cat_id=' + selectedCat + '&point=' + encodeURI(point) + '&radius=' + $('#radius').val() + '&type=' + $('#type').val(),
		success : handleSuccess,
		error : function(response, text) { $('#indicator').hide(); alert('Error fetching sales: ' + response); }
	});
}


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

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

/**
 *	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);
	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;
};