<?php
defined('PRODUCT_NAME') or die;
class DirectoryModule extends ModuleInstance
{
	var $page_link;

	public function __construct()
	{
		parent::__construct();
		$this->enable_jquery = true;

		$this->load->model("page");
		$pages = $this->page->get();
		$parray = array();
		$count = 1;

		foreach($pages as $page)
		{
			$parray[$count]["key"] = $page->page_id;
			$parray[$count]["value"] = $page->title;
			$count++;
		}
		$this->cache_config->user         = true;
		$this->cache_config->url          = true;
		$this->cache_config->query_string = true;
	}

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

		$page_id				= $this->setting("page_id");
		$allow_export 			= $this->setting("allow_export");
		$category_id			= $this->input->get_post("category_id");
		$company_id				= $this->input->get_post("company_id");
		$task					= $this->input->get_post("task");
		$q 						= $this->input->get_post("q" . $this->module_instance_id);
		$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);

		$this->page_link = "/" . $page->url;

		/**
		 * To handle URLs, we're going to check company first, then category.
		 * This means if a category has the same URL as a company for some reason, the company will win the argument.
		 */
		$url_parts = uri_string();
		$url_parts = explode("/", $url_parts);

		if(count($url_parts) == 2)
		{
			$url = $url_parts[1];
		}

		if(isset($url))
		{
			$company = new Directory_Company();
			$company->LoadByURL(Mainframe::site()->site_id, $url);

			if($company->company_id > 0)
			{
				//we successfully loaded a company
				$company_id = $company->company_id;
				$task = "showCompany";
			}
			else
			{
				//try loading a category
				$category = new Directory_Category();
				$category->LoadByURL(Mainframe::site()->site_id, $url);

				if($category->category_id > 0)
				{
					//we successfully loaded a category
					$category_id = $category->category_id;
					$task = "showCategory";
				}
			}
		}

		?>
		<div id="module_<?php echo($this->module_instance_id); ?>" class="module directory-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
			}
			?>
			<form name="search" id="search-form" method="post" action="<?php echo $this->page_link?>">
				<?php
				csrf();
				FeralHidden("task", "search");
				?>

				<div class="row-row">
					<div class="<?php echo(LABEL_COL); ?>"><label>Search</label></div>

					<div class="<?php echo(FIELD_COL); ?>">
						<?php
						$wgt = new FeralTextWidget("q" . $this->module_instance_id, $q, "form-control");
						$wgt->SetAttribute("required", "required");
						$wgt->Create();
						?>
						<button type="search" class="btn btn-primary"><em class="fas fa-search" aria-hidden="true"></em> Search</button>
						<a href="<?php echo($this->page_link); ?>" class="btn btn-secondary"><em class="fas fa-magic" aria-hidden="true"></em> Reset</a>
						<?php if($allow_export) { ?><a href="<?php echo($this->page_link); ?>?task=export" class="btn btn-success" target="_blank"><em class="fas fa-file-pdf" aria-hidden="true"></em> Export PDF</a><?php } ?>
					</div>
				</div>
			</form>
			<?php
			/*if($title && $title_heading_level)
			{
				?><h2 class="directory_title"><?php echo $title?></h2><?php
			}*/

			switch($task)
			{
				case "showCategory":
				{
					$this->showCategory($category_id);

					break;
				}

				case "showCompany":
				{
					$this->showCompany($company_id);

					break;
				}

				// case "addCompany":
				// {
				// 	$this->addCompany();

				// 	break;
				// }

				case "saveCompany":
				{
					$this->saveCompany();

					break;
				}

				case "search":
				{
					$this->search($q);

					break;
				}

				case "export":
				{
					$this->export();

					break;
				}

				default:
				{
					$this->showCategory(0);

					break;
				}
			}
			?>
		</div>
		<?php
	}

	function showCategory($id)
	{
		$q 			= $this->input->get_post("q" . $this->module_instance_id);

		$i = 0;	//intentional offset
		$max_width	= $this->setting("max_width");
		$max_height	= $this->setting("max_height");
		$title		= $this->setting("title");
		$display	= $this->setting("display");

		if($id)
		{
			$category = new Directory_Category();
			$category->Load($id);
		}

		$categories = $this->directory_category->LoadByParentID($id);

		if($id)
		{
			$companies = $this->directory_company->LoadByCategoryID($id, Mainframe::site()->site_id, ($display == "normal" ? "c.company" : "c.contact"));
		}
		else
		{
			$companies = $this->directory_company->LoadByKeyword($q, Mainframe::site()->site_id, ($display == "normal" ? "c.company" : "c.contact"));
			// $companies = array();

			$category = new Directory_Category();
			$category->category_name = $title;

			?><h3>Please Choose a Category</h3><?php
		}

		//die($companies->settings->source);
		?>
		<h2 class="directory-category-name"><?php echo $category->category_name?></h2>

		<div class="directory-category-description">
			<?php echo $category->description?>
		</div>

		<div class="row directory-subcategory-list">
			<?php
			foreach($categories as $c)
			{
				?><div class="<?php echo(TWO_COL); ?>"><h2 class="directory-category-name"><a href="<?php echo $this->page_link?>/<?php echo($c->url ? $c->url : $c->category_id); ?>"><?php echo $c->category_name?></a></h2></div><?php
			}
			?>
		</div>
		<div class="clear"></div>

		<?php
		if(is_array($companies) && count($companies) > 0)
		{
			?>
			<div class="alert alert-success text-center"><?php echo(number_format(count($companies), 0)); ?> Businesses Were Found</div>

			<div class="row directory-category-list">
				<?php
				$count = 0;

				foreach($companies as $company)
				{
					?><div class="<?php echo(TWO_COL); ?>"><?php

					$this->showCompanyVCard($company);

					?></div><?php
				}
				?>
			</div>
			<?php
		}
		else if($id)
		{
			?><div class="alert alert-danger text-center">No Businesses Were Found</div><?php
		}
	}

	function search($q, $user=NULL)
	{
		$display 	= $this->setting("display");
		$companies 	= $this->directory_company->LoadByKeyword($q, Mainframe::site()->site_id, ($display == "normal" ? "c.company" : "c.contact"));

		?><h2>Business Directory Search Results</h2><?php

		if(is_array($companies) && count($companies) > 0)
		{
			?>
			<div class="alert alert-success text-center"><?php echo(number_format(count($companies), 0)); ?> Businesses Were Found</div>

			<div class="row directory-category-list">
				<?php
				$count = 0;

				foreach($companies as $company)
				{
					?><div class="<?php echo(TWO_COL); ?>"><?php

					$this->showCompanyVCard($company);

					?></div><?php
				}
				?>
			</div>
			<?php
		}
		else
		{
			?><div class="alert alert-danger text-center">No Businesses Were Found</div><?php
		}
	}

	function showCompanyVCard($company)
	{
		$i = 2;	//intentional offset
		$max_width		= $this->setting("max_width");
		$max_height		= $this->setting("max_height");
		$display		= $this->setting("display");
		$custom_fields	= explode("\n", ($this->setting("custom_fields") ? $this->setting("custom_fields") : ""));

		if(!$company->contact)
		{
			$company->contact = $company->company;
		}
		?>
		<div class="directory-vcard" itemscope itemtype="http://data-vocabulary.org/Organization">
			<?php
			if($display == "normal")
			{
				?>
				<h2 class="directory-company-name"><a href="<?php echo $this->page_link?>/<?php echo($company->url ? $company->url : $company->company_id); ?>" itemprop="name"><?php echo $company->company?></a></h2>
				<?php
				if($company->contact != $company->company && $company->contact != "")
				{
					?><div class="directory-contact-name">Contact: <?php echo $company->contact?></a></div><?php
				}
			}
			else if($display == "reverse")
			{
				?>
				<h2 class="directory-company-name"><a href="<?php echo $this->page_link?>/<?php echo($company->url ? $company->url : $company->company_id); ?>" itemprop="name"><?php echo $company->contact?></a></h2>
				<?php
				if($company->company && $company->contact != "")
				{
					?><div class="directory-contact-name">Company: <?php echo $company->company?></a></div><?php
				}
			}

			foreach($custom_fields as $value)
			{
				$split 	= explode("=", $value);
				$key 	= $split[0];
				$value 	= $split[1];

				if(isset($company->{$key}))
				{
					?><div class="directory-company-custom"><?php echo($value); ?>: <?php echo($company->{$key})?></a></div><?php
				}
			}
			?>
			<div class="directory-company-address" itemprop="address" itemscope itemtype="http://data-vocabulary.org/Address">
				<span class="directory-company-street" itemprop="address"><?php echo $company->address?><br /></span>
				<?php if($company->city) { ?><span class="directory-company-city" itemprop="locality"><?php echo $company->city?></span>,<?php } ?>
				<span class="directory-company-province" itemprop="region"><?php echo $company->province?></span>
				<span class="directory-company-postalcode" itemprop="postal-code"><?php echo ($company->postalcode != 'NULL' ? substr($company->postalcode, 0, 3) . " " . substr($company->postalcode, 3, 6) : "")?></span>
				<div class="directory-more-info"><a href="<?php echo $this->page_link?>/<?php echo($company->url ? $company->url : $company->company_id); ?>">More Info</a></div>
			</div>
			<?php if($company->phone) { ?><div class="d-none" itemprop="tel"><?php echo $company->phone?></div><?php } ?>
			<?php if($company->website) { ?><div class="d-none" itemprop="url"><?php echo $company->website?></div><?php } ?>
			<div class="d-none" itemprop="role"><?php echo(COMPANY_NAME); ?> Member</div>
		</div>
		<?php
	}

	function showCompany($id)
	{
		$site = Mainframe::site();
		$page = Mainframe::page();

		if(!$id)
		{
			return false;
		}

		$i = 4;	//intentional offset
		$max_width		= $this->setting("max_width");
		$max_height		= $this->setting("max_height");
		$api_key		= $this->setting("google_api_key");
		$display		= $this->setting("display");
		$custom_fields	= explode("\n", ($this->setting("custom_fields") ? $this->setting("custom_fields") : ""));

		$company = new Directory_Company();
		$company->Load($id);

		$companies = array($company);	//a lazy way to be able to fully recycle the main map code

		if(!$company->contact)
		{
			$company->contact = $company->company;
		}

		$newtitle = $company->company . " | " . $page->title . " | " . $site->title;
		?>
		<script>
			document.getElementsByTagName("title")[0].innerHTML = "<?php echo $newtitle?>";

			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: 15,
		      		//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();

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

				//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 = -1;

		        foreach($companies as $company)
		        {
		        	$count++;

		            $info = "";

		            $info .= addslashes("<div style=\"width: 300px;\"><h3>" . $company->company . "</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=\"#\" 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
		            	?>
		            	console.log("geocoding <?php echo($company->address . ', ' . $company->city . ', ' . $company->province . ', ' . (is_null($company->postalcode) ? "" : $company->postalcode));?>");

		            	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="directory-company" itemscope itemtype="http://data-vocabulary.org/Organization">
			<?php
			if($company->logo && file_exists(ABSOLUTE_PATH . "/images/directory/logos/$company->logo"))
			{
				$file 		= ABSOLUTE_PATH . "/images/directory/logos/$company->logo";
				$thumbnail 	= Mainframe::thumbnail($file, $max_width, $max_height, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
				$size 		= @getimagesize(ABSOLUTE_PATH . $thumbnail);

				?><img class="directory-company-logo" src="<?php echo str_replace(ABSOLUTE_PATH, LIVE_SITE, $thumbnail); ?>" width="<?php echo($size[0]); ?>" /><?php
			}

			if($display == "normal")
			{
				?>
				<h2 class="directory-company-name" itemprop="name"><?php echo $company->company?></h2>
				<?php
				if($company->contact != $company->company && $company->contact != "")
				{
					?><div class="directory-contact-name">Contact: <?php echo $company->contact?></a></div><?php
				}
			}
			else if($display == "reverse")
			{
				?>
				<h2 class="directory-company-name" itemprop="name"><?php echo $company->contact?></a></h2>
				<?php
				if($company->company && $company->contact != "")
				{
					?><div class="directory-contact-name">Company: <?php echo $company->company?></a></div><?php
				}
			}

			foreach($custom_fields as $value)
			{
				$split 	= explode("=", $value);
				$key 	= $split[0];
				$value 	= $split[1];

				if(isset($company->{$key}))
				{
					?><div class="directory-company-custom"><?php echo($value); ?>: <?php echo($company->{$key})?></a></div><?php
				}
			}
			?>

			<div class="directory-company-address" itemprop="address" itemscope itemtype="http://data-vocabulary.org/Address">
				<span class="directory-company-street" itemprop="address"><?php echo $company->address?></span><br />
				<?php if($company->city) { ?><span class="directory-company-city" itemprop="locality"><?php echo $company->city?></span>,<?php } ?>
				<span class="directory-company-province" itemprop="region"><?php echo $company->province?></span>
				<span class="directory-company-postalcode" itemprop="postal-code"><?php echo ($company->postalcode != 'NULL' ? substr($company->postalcode, 0, 3) . " " . substr($company->postalcode, 3, 6) : "")?></span>
			</div>
			<?php if($company->phone) { ?><div class="directory-company-phone">Phone: <span itemprop="tel"><?php echo $company->phone?></span></div><?php } ?>
			<?php if($company->fax) { ?><div class="directory-company-phone">Fax: <?php echo $company->fax?></div><?php } ?>
			<?php if($company->email) { ?><div class="directory-company-email">E-mail: <?php $this->emailLink($company->email);?></div><?php } ?>
			<?php if($company->website) { ?><div class="directory-company-website">Website: <a href="<?php echo $company->website?>" target="_blank" itemprop="url"><?php echo $company->website?></a></div><?php } ?>
			<div class="d-none" itemprop="role"><?php echo(COMPANY_NAME); ?> Member</div>

			<div class="directory-company-description"><?php echo nl2br(strip_tags($company->description))?></div>

			<?php
			if($company->photo && file_exists(ABSOLUTE_PATH . "/images/directory/companies/$company->photo"))
			{
				$file 		= ABSOLUTE_PATH . "/images/directory/companies/$company->photo";
				$thumbnail 	= Mainframe::thumbnail($file, $max_width, $max_height, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
				$size 		= @getimagesize(ABSOLUTE_PATH . $thumbnail);

				?><div class="directory-company-photo"><img class="directory-company-photo" src="<?php echo str_replace(ABSOLUTE_PATH, LIVE_SITE, $thumbnail); ?>" width="<?php echo($size[0]); ?>" border="0" /></div><?php
			}

			if($api_key)
			{
				?>
				<div class="directory-company-map">
					<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>
					<?php
					$address 	= rawurlencode($company->address) . ", " . rawurlencode($company->city) . " " . $company->province . " " . rawurlencode($company->postalcode);
					?>
					<!-- <iframe src="https://www.google.com/maps/embed/v1/place?key=<?php echo($api_key); ?>&q=<?php echo($address); ?>&zoom=15" width="100%" height="450" frameborder="0" style="border:0"></iframe> -->
				</div>
				<?php
			}
			?>
		</div>
		<?php
	}

	function emailLink($email)
	{
		?>
		<a class="email" href="mailto: <?php echo $email?>"><?php echo $email?></a>
		<?php
		return;

		$display = str_replace(array("@", "."), array(" {at} ", " {dot} "), $email);

		$first = substr($email, 0, stripos($email, "@"));
		$last = substr($email, strlen($first)+1);
		?>
		<script>
		var email = "<?php echo $first?>" + "@" + "<?php echo $last?>";
		var mailto = "mailto:" + email;
		</script>

		<a class="email" href="#" onmouseover="this.href=mailto;this.innerHTML=email;" onmouseout="this.href='#';this.innerHTML='<?php echo $display?>';"><?php echo $display?></a>
		<?php
	}

	function export()
	{
		$display = $this->setting("display");
		$custom_fields	= explode("\n", ($this->setting("custom_fields") ? $this->setting("custom_fields") : ""));
		$allow_export 	= $this->setting("allow_export");

		if(!$allow_export)
		{
			echo("Export is diabled");
			return;
		}

		$this->load->model("directory_company");

		$companies = $this->directory_company->LoadBySiteID(Mainframe::site()->site_id, 100000, false, ($display == "normal" ? "c.company" : "c.contact"));

		ob_start();

		foreach($companies as $company)
		{
			?>!!!START!!!<?php

			if($display == "normal")
			{
				?>
				<h2><?php echo $company->company?></h2>
				<?php
				if($company->contact != $company->company && $company->contact != "")
				{
					?><p><b>Contact:</b> <?php echo $company->contact?></a></p><?php
				}
			}
			else if($display == "reverse")
			{
				?>
				<h2><?php echo $company->contact?></a></h2>
				<?php
				if($company->company && $company->contact != "")
				{
					?><p><b>Company:</b> <?php echo $company->company?></a></p><?php
				}
			}

			foreach($custom_fields as $value)
			{
				$split 	= explode("=", $value);
				$key 	= $split[0];
				$value 	= $split[1];

				if(isset($company->{$key}))
				{
					?><p><b><?php echo($value); ?>:</b> <?php echo($company->{$key})?></a></p><?php
				}
			}
			?>

			<p>
				<?php echo $company->address?><br />
				<?php if($company->city) { ?><?php echo $company->city?>,<?php } ?>
				<?php echo $company->province?>
				<?php echo ($company->postalcode != 'NULL' ? substr($company->postalcode, 0, 3) . " " . substr($company->postalcode, 3, 6) : "")?><br />
			</p>

			<?php if($company->phone) { ?><b>Phone:</b> <?php echo $company->phone?><br /><?php } ?>
			<?php if($company->fax) { ?><b>Fax:</b> <?php echo $company->fax?><br /><?php } ?>
			<?php if($company->email) { ?><b>E-mail:</b> <?php $this->emailLink($company->email);?><br /><?php } ?>
			<?php if($company->website) { ?><b>Website:</b> <a href="<?php echo $company->website?>" target="_blank"><?php echo $company->website?></a><br /><?php } ?>

			<?php
			$company->description = trim(nl2br(strip_tags($company->description)));

			if($company->description)
			{
				echo("<br />");
				echo($company->description);
				echo("<br />");
			}
			?>
			<br />
			!!!END!!!
			<?php
		}

		$html = ob_get_contents();
		@ob_end_clean();

		$title = COMPANY_NAME . " Directory Export";
		require_once(APPLICATION_PATH . "/controllers/Latex.php");
		$latex = Latex::latex_data($title, $title, $html, true, "directory.tex");
		$latex = str_replace(array("!!!START!!!", "!!!END!!!"), array('\begin{samepage}\begin{minipage}[t]{\textwidth}', '\end{minipage}\end{samepage}'), $latex);
		Latex::latex_pdf($title, $title, $latex, false, true, $title, null);
		die();
	}
}
?>
