$(document).ready(function() {
	if(GBrowserIsCompatible()) {
		JHoodMap.loadMap();
		JHoodMap.viewMap();
		JHoodMap.startHashPolling();
	}
});

$(document).unload(function() {GUnload();});

JHoodMap = function() {};

JHoodMap.mapName = 'storesmapbig';

JHoodMap.expectedHash = '';

JHoodMap.currentStoreId = 0;

JHoodMap.map = null;

JHoodMap.storeInfo = new Object();
JHoodMap.storeBounds = new GLatLngBounds();

JHoodMap.latLngStores = new Object();
JHoodMap.storeLatLngs = new Object();
JHoodMap.storeMarkers = new Object();
JHoodMap.storeScrollers = new Object();
JHoodMap.markerNum = 1;

JHoodMap.baseIcon = new GIcon();
JHoodMap.baseIcon.iconSize = new GSize(20, 34);
JHoodMap.baseIcon.iconAnchor = new GPoint(10, 34);
JHoodMap.baseIcon.infoWindowAnchor = new GPoint(10, 1);
JHoodMap.baseIcon.imageMap = [9,0,6,0,5,1,2,3,1,5,0,7,0,12,1,14,2,16,4,17,6,19,8,21,8,33,11,33,11,21,13,19,15,17,17,16,18,14,19,12,19,7,18,5,17,3,14,1,6,0,12,0,10,0];
JHoodMap.baseIcon.transparent = "/images/maps/marker_gray_xparent.png";

JHoodMap.blueIcon =  new GIcon(JHoodMap.baseIcon);
JHoodMap.blueIcon.image = "/images/maps/png/marker_blue.png";
JHoodMap.blueIcon.printImage = "/images/maps/gif/marker_blue.gif";
JHoodMap.blueIcon.mozPrintImage = "/images/maps/gifmoz/marker_blue.gif";

JHoodMap.windowOptions = new Object();
JHoodMap.windowOptions.maxWidth = 275;


//This functions loads the map in the div for the first time
JHoodMap.loadMap = 
function() {
	JHoodMap.map = new GMap2(document.getElementById(JHoodMap.mapName));
	if(!JHoodMap.map) {
		return;
	}
	JHoodMap.map.addControl(new GSmallZoomControl());
};


/*
This helper function performs a modulus
on floating point numbers
*/
JHoodMap.modulus = 
function(y, x) {
	var z = y - x * Math.floor((y / x));
	return z;
};


/*
This function returns an array of latitude/longitude pairs,
that lie in circle of radius r (in meters) around the given
latitude/longitude pair
*/
JHoodMap.calcPointsAroundLatLng = 
function(lat, lng, radius, numPoints) {
	//had problems with lat being a string, so this is a crude way of forcing it to be a number
	lat = lat * 1;
	lng = lng * 1;
	var latRad = lat * (Math.PI / 180);
	var lngRad = lng * (Math.PI / 180);
	var radiusEarth = 6378.160 * 1000;
	var distanceRad = radius / radiusEarth;
	var degree = 0;
	var degreeRad = 0;
	var degreInterval = 360 / numPoints;
	var points = Array();

	for(var point = 0; point < numPoints; point++) {
		degree = point * degreInterval;
		degreeRad = degree * (Math.PI / 180);
		lat2Rad = Math.asin(Math.sin(latRad) * Math.cos(distanceRad) + Math.cos(latRad) * Math.sin(distanceRad) * Math.cos(degreeRad));
		if(Math.cos(lat2Rad) == 0) {
			lng2Rad = lngRad;
		}
		else {
			lng2Rad = JHoodMap.modulus(lngRad + Math.asin(Math.sin(degreeRad) * Math.sin(distanceRad) / Math.cos(latRad)) + Math.PI, 2 * Math.PI) - Math.PI;
		}
		lat2 = lat2Rad * (180 / Math.PI);
		lng2 = lng2Rad * (180 / Math.PI);
		points.push(new Array(lat2, lng2));
	}
	return points;
};


//For internal use only
JHoodMap.updateHash = 
function() {
	var hash = '#';
	if(JHoodMap.currentStoreId != 0) {
		hash += 's=' +encodeURIComponent(JHoodMap.currentStoreId.toString());
	}
	
	//cant get this to work in safari, anyway I try it
	if(navigator.userAgent.indexOf('Safari') == -1) {
		window.location.hash = hash;
		JHoodMap.expectedHash = hash;
	}
};


//For internal use only
JHoodMap.startHashPolling = 
function() {
	//cant get this to work in safari, anyway I try it
	if(navigator.userAgent.indexOf('Safari') == -1) {
			x= window.setInterval(
			function() {
			var winLocHash = window.location.hash;
			var expectedHash = JHoodMap.expectedHash.slice(1);
			if(window.location.hash.charAt(0) == '#') {
				winLocHash = window.location.hash.slice(1);
			}
			if(expectedHash != winLocHash) {
				JHoodMap.viewMap();
			}
		}, 200);
	}
};

//Should only be called when class is beign initialized
JHoodMap.addStoreInfo = 
function(storeId, latitude, longitude) {
	var x = Object();
	var point = null;
	var icon = null;
	var marker = null;

	x['storeId'] = storeId;
	x['latitude'] = latitude;
	x['longitude'] = longitude;
	JHoodMap.storeInfo[storeId] = x;
	JHoodMap.storeBounds.extend(new GLatLng(latitude, longitude));
};


//For internal use only
JHoodMap.addLatLngStore = 
function(latitude, longitude, storeId) {
	if(typeof(JHoodMap.latLngStores[latitude]) == 'undefined') {
		JHoodMap.latLngStores[latitude] = new Object();
	}
	if(typeof(JHoodMap.latLngStores[latitude][longitude]) == 'undefined') {
		JHoodMap.latLngStores[latitude][longitude] = new Array();
	}
	JHoodMap.latLngStores[latitude][longitude].push(storeId);
};


//For internal use only
JHoodMap.createStoreMarker =
function(latitude, longitude, storeId) {
	var store = JHoodMap.storeInfo[storeId];
	var point = new GLatLng(latitude, longitude);
	var storeIcon =  new GIcon(JHoodMap.baseIcon);
	var markerOptions = new Object();

	if(JHoodMap.markerNum < 131) {
		iconSuffix = '_' + JHoodMap.markerNum;
		JHoodMap.markerNum++;
	}
	else {
		iconSuffix = '_gray';
	}

	storeIcon.image = "/images/maps/png/marker" + iconSuffix + ".png";
	storeIcon.printImage = "/images/maps/gif/marker" + iconSuffix + ".gif";
	storeIcon.mozPrintImage = "/images/maps/gifmoz/marker" + iconSuffix + ".gif";
	markerOptions.icon = storeIcon;
	markerOptions.clickable = true;
	markerOptions.title = $('#storebubbledesc'+storeId+' h3').html();

	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", 
	function() {
		var infoTabs = new Array();

		$('#storebubbledesc'+storeId+' .photo').attr('src', $('#storebubbledesc'+storeId+' .imageSrc').html());
		html = $('#storebubbledesc'+storeId).html();
		infoTabs.push(new GInfoWindowTab('Description','<div class="storesmapbubbexcerpt">'+html+'</div>'));

		html = $('#storebubbledetails'+storeId).html();
		infoTabs.push(new GInfoWindowTab('Details', html));

		offset = $('#storesmapstoresbig').offset();
		topHeight = offset.top;

		$('#storesmapstoresbig').animate({scrollTop: JHoodMap.storeScrollers[storeId] - topHeight}, 1000, "easeOutExpo");
		
		marker.openInfoWindowTabsHtml(infoTabs, JHoodMap.windowOptions);

		JHoodMap.currentStoreId = storeId;

		JHoodMap.updateHash();

		window.scrollTo(0, 0);
	});

	return marker;
};


//Here we zoom in on a store from any other state
JHoodMap.viewStore = 
function(storeId) {
	var store = JHoodMap.storeInfo[storeId];
	if(typeof(JHoodMap.storeInfo[storeId]) == 'undefined') {
		return;
	}
	
	if(JHoodMap.currentStoreId == 0) {
		JHoodMap.viewStores(false);
	}

	GEvent.trigger(JHoodMap.storeMarkers[storeId], "click");
};


//This shows all the stores in a metro
JHoodMap.viewStores = 
function(shouldUpdateHash) {
	JHoodMap.map.clearOverlays();

	var lat = (JHoodMap.storeBounds.getNorthEast().lat() + JHoodMap.storeBounds.getSouthWest().lat()) / 2;
	var lng = (JHoodMap.storeBounds.getNorthEast().lng() + JHoodMap.storeBounds.getSouthWest().lng())/2;
	var x;
	var y;

	JHoodMap.map.setCenter(new GLatLng(lat,lng));
	JHoodMap.map.setZoom(JHoodMap.map.getBoundsZoomLevel(JHoodMap.storeBounds));

	JHoodMap.latLngStores = new Object();
	JHoodMap.storeLatLngs = new Object();
	JHoodMap.storeMarkers = new Object();
	JHoodMap.storeScrollers = new Object();
	JHoodMap.markerNum = 1;

	for(i in JHoodMap.storeInfo) {
		x = JHoodMap.storeInfo[i];
		JHoodMap.storeLatLngs[x.storeId] = new Array(x.latitude, x.longitude);
		JHoodMap.addLatLngStore(x.latitude, x.longitude, x.storeId);
	}

	for(i in JHoodMap.latLngStores) {
		for(j in JHoodMap.latLngStores[i]) {
			if(JHoodMap.latLngStores[i][j].length > 1) {
				if(JHoodMap.latLngStores[i][j].length < 5) {
					x = JHoodMap.calcPointsAroundLatLng(i, j, 4, JHoodMap.latLngStores[i][j].length);
				}
				else {
					x = JHoodMap.calcPointsAroundLatLng(i, j, 8, JHoodMap.latLngStores[i][j].length);
				}
				for(k in JHoodMap.latLngStores[i][j]) {
					JHoodMap.storeLatLngs[JHoodMap.latLngStores[i][j][k]][0] = x[k][0];
					JHoodMap.storeLatLngs[JHoodMap.latLngStores[i][j][k]][1] = x[k][1];
				}
			}
		}
	}

	for(i in JHoodMap.storeLatLngs) {
		marker = JHoodMap.createStoreMarker(JHoodMap.storeLatLngs[i][0], JHoodMap.storeLatLngs[i][1], i);
		JHoodMap.storeMarkers[i] = marker;
		JHoodMap.map.addOverlay(marker);
	}

	JHoodMap.currentStoreId = 0;

	//Begin Window/Document work
	x = document.getElementById('storesmapstoresbig');
	x.scrollTop = 0;

	for(i in JHoodMap.storeMarkers) {
		x = JHoodMap.storeMarkers[i].getIcon();
		y = document.getElementById('storeMarker' + i);
		if(y) {
			y.src = x.printImage;
			y.width = 20;
			y.height = 34;
			offset = $('#storeMarker'+i).offset();
			JHoodMap.storeScrollers[i] = offset.top;
		}
	}

	if(shouldUpdateHash) {
		JHoodMap.updateHash();
	}

	window.scrollTo(0, 0);
};


//This function looks at the current map URL and decides
//which specific map (city/store) to display
JHoodMap.viewMap = 
function() {
	//cant get this to work right in safari, anyway I try it
	if(navigator.userAgent.indexOf('Safari') == -1) {
		if(window.location.hash.length > 1) {
			var hash = window.location.hash.slice(1);
			var hashParts = hash.split('&');
			var i;
			for(i = 0; i < hashParts.length && i < 2; i++) {
				hashPart = hashParts[i].split('=');
				if(hashPart.length > 1) {
					if(hashPart[0] == 's' && i == 0) {
						JHoodMap.viewStore(hashPart[1]);
					}
				}
			}
		}
	}

	if(JHoodMap.currentStoreId == 0) {
		JHoodMap.viewStores(false);
	}
	if(navigator.userAgent.indexOf('Safari') == -1) {
		JHoodMap.expectedHash = window.location.hash;
	}
};
