<?php
defined('PRODUCT_NAME') or die;
class DirectoryGoogleMap extends ModuleInstance
{
	public function __construct()
	{
		parent::__construct();
		$this->enable_jquery = true;
	}

	function render()
	{
		$this->load->model("directory_company");

		$page_id				= $this->setting("page_id");
		$category_id			= $this->setting("category_id");
		$address				= rawurlencode($this->setting("address"));
		$zoom					= $this->setting("zoom");
		$latitude				= $this->setting("latitude");
		$longitude				= $this->setting("longitude");
		$sv_heading				= $this->setting("sv_heading");
		$sv_pitch				= $this->setting("sv_pitch");
		$sv_zoom				= $this->setting("sv_zoom");
		$initial_view			= $this->setting("initial_view");
		$bubble_text			= $this->setting("bubble_text");
		$title 					= $this->setting("title");
		$title_heading_level 	= $this->setting("title_heading_level");
		$module_class 			= $this->setting("module_class");

		$page = new Page();
		$page->Load($page_id);

		$page_link = "/" . $page->url;
		$companies = $this->directory_company->LoadByCategoryID($category_id, Mainframe::site()->site_id);
		?>
		<div id="module_<?php echo($this->module_instance_id); ?>" class="module directory-map-module <?php echo($module_class); ?>">
			<?php
			if($title && $title_heading_level)
			{
				?><<?php echo($title_heading_level); ?> class="module-title"><?php echo($title); ?></<?php echo($title_heading_level); ?>><?php
			}
			?>
			<script>
				var directionsService;
				var directionsDisplay;
				var map;
				var geocoder;

				var points = Array(<?php echo count($companies) +1;?>);
				var markers = Array(<?php echo count($companies) +1;?>);
				var infos = Array(<?php echo count($companies) +1;?>);
				var headings = Array(<?php echo count($companies) +1;?>);
				var pitches = Array(<?php echo count($companies) +1;?>);
				var zooms = Array(<?php echo count($companies) +1;?>);

				function display_sv_position()
				{
					var pano = map.getStreetView();
					var pov = pano.getPov();
					var obj = document.getElementById("sv_position");
					var position = pano.getPosition();

					obj.innerHTML = "Latitude: " + position.lat() + "<br />Longitude: " + position.lng() + "<br />Heading: " + pov.heading + "<br />Pitch: " + pov.pitch + "<br />Zoom: " + pov.zoom;
				}

				function initialize()
				{
					//directionsService = new google.maps.DirectionsService();
					//directionsDisplay = new google.maps.DirectionsRenderer();
					geocoder = new google.maps.Geocoder();

					var myOptions =
			    	{
			      		zoom: <?php echo $zoom?>,
			      		//center: points[0],
			      		mapTypeId: google.maps.MapTypeId.ROADMAP,
			      		streetViewControl: true
			    	};

			    	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			    	//directionsDisplay.setMap(map);
			    	//directionsDisplay.setPanel(document.getElementById("directionsPanel"));

			    	map_companies();

					//remove our loading image so that it doesn't bleed through while moving the map around
					//document.getElementById("map_canvas").style.background = "none";
				}

				function map_companies()
				{
					<?php
			        //include("ssi/icons.php");
			        $count = 0;
			        ?>

			        points[<?php echo $count?>] = new google.maps.LatLng(<?php echo $latitude?>, <?php echo $longitude?>);

	                markers[<?php echo $count?>] = new google.maps.Marker({
					      position: points[<?php echo $count?>],
					      map: map,
					      title:"<?php echo $bubble_text?>",
					      zIndex: 0
					});


	            	infos[<?php echo $count?>] = new google.maps.InfoWindow({
					    content: "<?php echo $bubble_text?>"
					});

	            	google.maps.event.addListener(markers[<?php echo $count?>], 'mouseover', function()
					{
						clear_infos();
						infos[<?php echo $count?>].open(map,markers[<?php echo $count?>]);
					});

	                headings[<?php echo $count?>] = <?php echo ($sv_heading ? $sv_heading : "0");?>;
		            pitches[<?php echo $count?>] = <?php echo ($sv_pitch ? $sv_pitch : "0");?>;
		            zooms[<?php echo $count?>] = <?php echo ($sv_zoom ? $sv_zoom : "1");?>;

		            map.setCenter(points[0]);
		            infos[0].open(map,markers[0]);

	                <?php
			        foreach($companies as $company)
			        {
			        	$count++;

			            $info = "";
			            $link = $page_link . "/" . $company->url;

			            $info .= addslashes("<div style=\"width: 300px;\"><h3><a style='font-weight: normal; font-style: normal;' href=\"$link\">" . $company->company . "</a></h3>" .
			                                "<div>" . $company->address . "<br />" . $company->city . ", " . $company->province . "&nbsp;&nbsp;" . (is_null($company->postalcode) ? "" : $company->postalcode) . "</div>");
			            	/*<b>Address:</b><br />" . $event->address .
			            	"<br />" . $event->city . ", " . $event->province . " " . $event->postalcode .
			            	*/
			            	$info .= addslashes("<br />" .
			            	"<a href=\"$link\">View Company Profile</a> | <a href=\"#\" onclick=\"street_view($count); return false;\">Street View</a><br /></div>");

			            	//($event->phone ? "<br /><br /><b>Phone:</b> " . $event->phone : "") .
			            	//($event->email ? "<br /><b>E-mail:</b> <a href=\"mailto: " . $event->email . "\">" . $event->email . "</a>" : "") .
			            	//($event->website ? "<br /><b>Website:</b> <a href=\"" . $event->website . "\" target=\"_blank\">" . $event->website . "</a><br />" : "") .
			            	//($mapit ? "<br /><a href='javascript:get_directions(\"" . ($event->latitude && $event->longitude ? $event->latitude . ", " . $event->longitude : $event->city . ", " . $event->province . " " . $event->postalcode) . "\");'>directions</a>" : "") .
			            	//"<br />");


			            $info = str_replace("\\n", "", $info);

			            if($company->latitude && $company->longitude)// && $mapit)
			            {
			            	//we already have the longitude and latitude
			                ?>
			                points[<?php echo $count?>] = new google.maps.LatLng(<?php echo $company->latitude?>, <?php echo $company->longitude?>);

			                markers[<?php echo $count?>] = new google.maps.Marker({
							      position: points[<?php echo $count?>],
							      map: map,
							      title:"<?php echo addslashes($company->company)?>"
							});


			            	infos[<?php echo $count?>] = new google.maps.InfoWindow({
							    content: "<?php echo $info?>"
							});

			            	google.maps.event.addListener(markers[<?php echo $count?>], 'mouseover', function()
							{
								clear_infos();
								infos[<?php echo $count?>].open(map,markers[<?php echo $count?>]);
								//get_directions("<?php echo ($company->latitude && $company->longitude ? $company->latitude . ", " . $company->longitude : $company->city . ", " . $company->province . " " . $company->postalcode)?>", google.maps.DirectionsTravelMode.DRIVING);
			                });
			                <?php
			            }
			            else
			            {
			            	//Note that we MUST duplicate the Javascript required to plot the point because the geocode function is async
			            	?>
			            	geocoder.geocode( { 'address': "<?php echo($company->address . ', ' . $company->city . ', ' . $company->province . ', ' . (is_null($company->postalcode) ? "" : $company->postalcode));?>"}, function(results, status)
					    	{
					      		if (status == google.maps.GeocoderStatus.OK)
					      		{
					      			//update our database with lat/lng values
					      			jQuery.post(
										"/admin/update_directory_latlng",
										{
											company_id: <?php echo($company->company_id); ?>,
											latitude: results[0].geometry.location.lat(),
											longitude: results[0].geometry.location.lng()
										},
										function(data)
										{
										}
									);

					        		points[<?php echo $count?>] = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());

					        		markers[<?php echo $count?>] = new google.maps.Marker({
									      position: points[<?php echo $count?>],
									      map: map,
									      title:"<?php echo addslashes($company->company)?>"
									});


					            	infos[<?php echo $count?>] = new google.maps.InfoWindow({
									    content: "<?php echo $info?>"
									});

					            	google.maps.event.addListener(markers[<?php echo $count?>], 'click', function()
									{
										clear_infos();
										infos[<?php echo $count?>].open(map,markers[<?php echo $count?>]);
										//get_directions("<?php echo ($company->latitude && $company->longitude ? $company->latitude . ", " . $company->longitude : $company->city . ", " . $company->province . " " . $company->postalcode)?>", google.maps.DirectionsTravelMode.DRIVING);
					                });
					         	}
					         	else
					         	{
					         		console.log("Error geocoding: " + status);
					         	}
					      	});
					      	<?php
			            }
			            ?>

			            headings[<?php echo $count?>] = <?php echo ($company->sv_heading ? $company->sv_heading : "0");?>;
			            pitches[<?php echo $count?>] = <?php echo ($company->sv_pitch ? $company->sv_pitch : "0");?>;
			            zooms[<?php echo $count?>] = <?php echo ($company->sv_zoom ? $company->sv_zoom : "1");?>;
			            <?php
			        }
			        ?>
				}

				function clear_infos()
				{
					kill_street_view();

					var i=0;

					for(i=0; i<infos.length; i++)
					{
						try
						{
							infos[i].close();
						}
						catch(e)
						{
							//if geocoding an address fails, it will not have an info window to close
						}
					}
				}

				function street_view(index)
				{
					var panoramaOptions =
					{
			  			position: points[index],
			  			enableCloseButton: true,
			  			pov:
			  			{
			    			heading: headings[index],
						    pitch: pitches[index],
			    			zoom: zooms[index]
			  			}
					};

					var panorama = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);

					map.setStreetView(panorama);

				}

				function kill_street_view()
				{
					panorama = map.getStreetView();
					panorama.setVisible(false);
				}

				function loadScript()
				{
					var script = document.createElement("script");
					script.type = "text/javascript";
					script.src = "https://maps.google.com/maps/api/js?sensor=true&callback=initialize";
					document.body.appendChild(script);
				}

				jQuery(window).on("load", function()
				{
					loadScript();
				});
			</script>

			<div class="map-controls">
				<a href="#" onclick="kill_street_view(); return false;">Map View</a> |
				<a href="#" onclick="street_view(0); return false;">Street View</a>
			</div>

			<div id="map_canvas" class="map_canvas"></div>
		</div>
		<?php
	}
}
