
var map;
var geocoder;
var directionsService;
var directionsDisplay;

var openInfowindow;
var fluster;
var mapPoints = [];
var mapHTMLS = [];

var zoomLevel = 8;

var infoWindowOffset;
	
var iconImageUrl;
var iconSize;
var iconPosition;
var iconHotSpotOffset;


jQuery(document).ready(function () {

	var searchString = 'Address, Intersection or ZIP code';
	var losAngelesCenter = new google.maps.LatLng(34.053797, -118.238983);
	
	directionsService	= new google.maps.DirectionsService();

	var mapOptions = {
		zoom: zoomLevel,
		center: losAngelesCenter,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
	    mapTypeControl: true,
	    mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
	    navigationControl: false,
	    scaleControl: false,
	    scrollwheel: false
	};
	
	map					= new google.maps.Map(document.getElementById("mapInteractive"), mapOptions);
	fluster				= new Fluster2(map);
    geocoder			= new google.maps.Geocoder();
    directionsDisplay	= new google.maps.DirectionsRenderer();

	processMap();

    directionsDisplay.setMap(map);
    
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));

	fluster.styles = {
		0: { image: '/images/m1.png', textColor: '#000000', width: 52, height: 52 },
		10: { image: '/images/m2.png', textColor: '#000000', width: 56, height: 56 },
		20: { image: '/images/m3.png', textColor: '#000000', width: 66, height: 66 }
	};
	
	fluster.initialize();
	

	$('#mapZoomIn').click( function()  { zoomLevel = map.getZoom(); map.setZoom(++zoomLevel); });
	$('#mapZoomOut').click( function() { zoomLevel = map.getZoom(); map.setZoom(--zoomLevel); });


	$('.advertSpace').addClass('ui-corner-all');
	$('.advertSpace').click( function() { location.href = '/advertising.php'; });

	if ($("#mapInteractive").attr("region").length) { $("#regionSelect").val($("#mapInteractive").attr("region")); }

	$('#regionSelect').change( function() { location.href = '/doctors-' + $('#regionSelect option:selected').val() + '.php'; });

	$('#mapLinks div').addClass('ui-corner-left');

	$("#mapLinks div").hover(
		function() { $(this).css({'background-color' : '#e5ffd6'}); },
		function() { $(this).css({'background-color' : '#fbfff5'}); }
	);
	
	
	$('#addressEntered').val(searchString);
	$('#addressEntered').focus( function() { if ($(this).val() == searchString) { $(this).val("") } });
	$('#addressEntered').keyup( function(event) { if(event.keyCode == 13) { $('#addressSearchButton').click() } });
	$('#addressSearchButton').click( function() { if ($('#addressEntered').val() != searchString && $('#addressEntered').val() != '') { geocode() } else { $('#addressEntered').effect("highlight", {}, 3000).focus() } return false; });

});


function processMap() {

	var bounds = new google.maps.LatLngBounds();

	infoWindowOffset	= new google.maps.Size(14, 20);
	
	iconImageUrl		= './images/doctor-map-icon.png';
	iconSize			= new google.maps.Size(38, 32);
	iconPosition		= new google.maps.Point(0, 0);
	iconHotSpotOffset	= new google.maps.Point(19, 16);

	var	markerImage = new google.maps.MarkerImage(iconImageUrl, iconSize, iconPosition, iconHotSpotOffset);

	
	$("#mapLinks").children().each( function() {

		var listing_lat	= parseFloat($(this).attr('lat'));
		var listing_lng	= parseFloat($(this).attr('lng'));
	
		var listing_tag		= $(this).attr('tag');
		var listing_name	= $(this).attr('name');
		var listing_address	= $(this).attr('address');
		var listing_phone	= $(this).attr('phone');
		var listing_hours	= $(this).attr('hours');
		var listing_href	= $(this).attr('href');


		if (listing_lat && listing_lng) {

			var point = new google.maps.LatLng(listing_lat, listing_lng);
	
			var html = '<h3 style="margin-top: 0; cursor: pointer;" onClick="location.href=\'show-' + listing_tag + '.php\';">' + listing_name + '</h3>';
	
			if (listing_address) {
				html += '<p>' + listing_address + '</p>';
			}
			
			if (listing_phone) {
				html += '<p><img src="/images/telephone.png" style="float: left; margin: 2px 4px 0 2px; width: 16px; height: 16px;" alt="Dispensary Phone Number">' + listing_phone + '</p>';
			}
			
			if (listing_hours) {
				html += '<p><img src="/images/clock.png" style="float: left; margin: 2px 4px 0 2px; width: 16px; height: 16px;" alt="Dispensary Hours">' + listing_hours + '</p>';
			}
					
			html += '<p><a href="show-' + listing_tag + '.php"><img src="/images/view-listing.png" style="float: left; margin: 4px 4px 0 2px; width: 16px; height: 16px;" alt="View Listing">View Listing Details and Ratings</a></p>';
			html += '<p><img src="/images/map_magnify.png" style="float: left; margin: 2px 4px 0 2px; width: 16px; height: 16px;" alt="Get Direction">Get Directions from <input type="text" id="directionsFrom" onKeyUp="checkForSearch()" value="" /><input type="hidden" id="directionsTo" value="' + listing_address + '" /><span class="directionsSearchButton" onClick="calcRoute();">Go!</span></p>';

			html += '<p><a href="javaScript:zoomTo(' + listing_lat + ',' + listing_lng + ')"><img src="/images/magnifier.png" style="float: left; margin: 2px 4px 0 2px; width: 16px; height: 16px;" alt="Zoom Here">Zoom Here</a></p>';
		
			var marker = new google.maps.Marker({
				title: listing_name,
				icon: markerImage,
				position: point,
				flat: true
			});
	
			google.maps.event.addListener(marker, "click", function() {
				var infowindow = new google.maps.InfoWindow({ content: html, pixelOffset: infoWindowOffset });
				setInfowindow(infowindow);
				infowindow.open(map, marker);
			});

			fluster.addMarker(marker);
			mapPoints.push(point);
			mapHTMLS.push(html);
			bounds.extend(point);
		}
	});

	map.fitBounds(bounds);
}


function listingClicked(markerNum) {
	
	var infowindow = new google.maps.InfoWindow({ content: mapHTMLS[markerNum] });
		infowindow.setPosition(mapPoints[markerNum]);
		infowindow.open(map);

	map.setCenter(mapPoints[markerNum]);
	map.setZoom(16);

	setInfowindow(infowindow);
}

function zoomTo(lat, lng) {
	var point = new google.maps.LatLng(lat, lng);
	map.setCenter(point);
	map.setZoom(16);
}

function setInfowindow(newInfowindow) {
	if (openInfowindow != undefined) { openInfowindow.close(); }
	openInfowindow = newInfowindow;
}

function checkForSearch() {
	$('#directionsFrom').keyup( function(event) {
		if(event.keyCode == 13) {
			$('#directionsFrom').unbind('keyup');
			calcRoute();
			$('#directionsFrom').bind('keyup', function() { checkForSearch(); });
		};
	});
	return false;
}

function calcRoute() {

	var start	= $("#directionsFrom").val();
	var end		= $("#directionsTo").val();
	
	if ((start.length >= 2) && (end.length >= 2)) {
	
		var request = {
			origin: start, 
			destination: end,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		directionsService.route(request, function(response, status) {
		
			if (status == google.maps.DirectionsStatus.OK) {

				if (openInfowindow != undefined) {
					openInfowindow.close();
				}
				
				$("#directionsPanel").html("");
				directionsDisplay.setDirections(response);
				$("#directionsPanel").prepend('<h3>How to Get to ' + end + '</h3><p style="font-style: italic;">...and please mention you found them using MMJshopping.com!</p>');
				$("#directionsPanel").delay(600).slideDown(800);
			}
		});
	} else {
		$("#directionsFrom").effect("highlight", {}, 3000).focus();
	}
	
	return false;
}

function geocode() {
	var address = $("#addressEntered").val();
	geocoder.geocode({ 'address': address, 'partialmatch': true}, geocodeResult);
}

function geocodeResult(results, status) {
	if (status == 'OK' && results.length > 0) {
		map.fitBounds(results[0].geometry.viewport);
	} else {
		alert("I can't find that address because: " + status);
	}
}
