<?php session_start();  ?>
<br/> 
<a href="http://www.whistler.com/">
<img src="http://www.whistler.com/images/common/whistler.gif" border="0" /></a>
<br/>
<?php 


	  if(isset($_POST['calculate']))
	  {
              $calculate = false;  
	      $passengers = $_SESSION['pass'] ;
	  	  $rout = $_SESSION['rout'] ;
		  $count =  $_SESSION['count'];
		 // $origin = $_POST["radioorigin"];
		   for($i = 0; $i <= $count ; $i++ )
		  {
		  	   $destination[$i] = $_POST["radiodestin" . $i];
		  }
		 
	  }
	  else
	  {
	       $calculate = true;  
	      $count = $_POST["destination"] ;
  	      $_SESSION['count'] = $count;
		  $passengers = (int)$_POST["passengers"] ;
		  $flymode = $_POST["FlyMode"];
		  $mode = $_POST["mode"];
		  $_SESSION['mode'] = $mode;
		  $_SESSION['flymode'] = $flymode;
		  $_SESSION['pass'] = $passengers;
		  if( $_POST["Routing"] == "return" )
	  	  {
	        $rout = 2; //return
		    $_SESSION['rout'] = $rout;
			$_SESSION['flight'] = 'round';
	 	  }
		  else 
	 	  {
	        $rout = 1;  //single
	        $_SESSION['rout'] = $rout;
			$_SESSION['flight'] = 'One-way';
		  }
	      
		  for($i = 0; $i <= $count ; $i++ )
		  {
		  	   $destination[$i] = $_POST["destination". $i];
		  }
	  }
	  
	
 
	  if ($passengers == '0')
	  {
	      echo "Passengers entry is not a valid number. Please change the input.<br>";
		  return;
	  }
	  
	  /* Connection to MySQL Database*/
	  $host="mysql103.mysite4now.com";
      $user="external";
      $password="ocns";
	  $database="ocns_calculator";
	  $table="airports";
	  //Connection
	  $cxn = mysqli_connect($host,$user,$password,$database);
	  $multiple = false; 
      if($calculate)
	  {
         if($_SESSION['flymode'] != "ground")
	    {
			for($i = 0; $i <= $count ;$i++ )
			{
	       
		   if(empty($destination[$i])) 
		   {
		         echo "<h3> Please enter inputs. </h3>";
		  		 return; //set a flag here to write the error. 
		   }
		   if($i == 1)
		   {
				if($_SESSION['flymode']!='ground')
				{
					$destination[$i] = $_SESSION['flymode'];
				}
		   }
		   
		   $query="SELECT * FROM ".$table." WHERE city=\"". $destination[$i] ."\"". " OR iata=\"". $destination[$i] ."\"";
	       
		   $result [$i] = mysqli_query($cxn,$query);
		   if($result[$i] == false )
		   {
						echo "<h4>Error: ".mysqli_error($cxn)."</h4>";
						return;
		   }
 		   
		   $nrows[$i] = mysqli_num_rows($result[$i]);
		   if($nrows[$i] == 0)
		   {
						echo "<h4>Query completed.
						No results for origin City or Destination City, check the inputs please.</h4>";
						return;
			}

		   if($nrows[$i]!=1) 
		         $multiple = true;
				
		   
			}
		}
	} //if they press calculate so there is only one destination to calculate
		else	
        {
		    if($_SESSION['flymode'] != "ground")
	        {
			for($i = 0; $i <= $count ; $i++ )
	  	    {
				$query="SELECT * FROM ".$table." WHERE iata=\"". $destination[$i] ."\"";
	       		$result [$i] = mysqli_query($cxn,$query);
		   		if($result[$i] == false )
		   		{
						echo "<h4>Error: ".mysqli_error($cxn)."</h4>";
						return;
		   		}
			}
			}
 	    }
       // Report starts from this line. 
	   echo '<br/><h2> Emission Offset </h2>';
		 if($_SESSION['flymode'] != "ground")
	   {
	           
			  for($j = 0; $j <= $count; $j++) 
			  {
			      	$row[$j] = mysqli_fetch_assoc($result[$j]);
			  
			  }
		   
		} 
		  
		    for($j = 0; $j < $count; $j++) 
			{         
				
					    $orglat =  ( $row[$j]['latdegree'] + ( $row[$j]['latmin'] * 1/60) + ( $row[$j]['latsec'] * 1/60 * 1/60)); 
						if ($row[$j]['latdirection']== "N")
						{
				             $orglat = $orglat * -1;
							
						}
						 $orglong =  $row[$j]['longdeg'] + ( $row[$j]['longmin'] * 1/60) + ($row[$j]['longsec'] * 1/60 * 1/60);
						if ( $row[$j]['longdir'] == "E")
						{
						    $orglong = $orglong * -1;
						   
						}
   					 $deslat = ($row[$j+1]['latdegree'] + ( $row[$j+1]['latmin'] * 1/60) + ($row[$j+1]['latsec']*1/60*1/60));
						if ($row[$j+1]['latdirection']== "N" )
						{
	    		    		$deslat = $deslat * -1;					
						}
					
	                  $deslong = $row[$j+1]['longdeg'] + ( $row[$j+1]['longmin'] * 1/60 ) + ($row[$j+1]['longsec']*1/60*1/60);				
						if ($row[$j+1]['longdir'] == "E")
						{
	      		           $deslong = $deslong  * -1 ;
      						   
						}
						
						
						echo '<br/>';
						//echo $_SESSION['flymode'];
						echo '<br/>';
						
						if ($_SESSION['flymode'] != 'ground')
						{
							
							echo 'Place of origin:<strong>' . ucwords(strtolower( $row[$j]['name'])) . ' (' . $row[$j]['iata'] .')' .  '</strong> airport at <strong>' 
								  . ucwords(strtolower( $row[$j]['city'])) . '-'  .
								    ucwords(strtolower( $row[$j]['country'])) .'</strong>';  
		   					
							echo   '<br/>Number of travellers:'.'<strong>'. $passengers.'</strong>' .' <br><strong>' .  $_SESSION['flight'] . ' </strong>trip ';					
							
							
							
							//if the flymode is not ground show the other flight thing
						    echo  'to  <b>' . ucwords(strtolower($row[$j+1]['name'])) .  ' (' . $row[$j+1]['iata'] .')'  . 
									   '</b> airport at <b>' .  ucwords(strtolower($row[$j+1]['city'])) . '-' . 
								 ucwords(strtolower($row[$j+1]['country'])) .'</b>' ;
							echo '<br/>';
							//if there are no flight mode, only show the origin city name and to whistler, or the to whistler and the mode 
							//can be default.
							//Show the driving mode and calculate the origin to whistler if the ground is chosen, 
						}
						else
						{
						    if(empty($destination[0])) 
		                    {
								echo "<h3> Please enter origin city. </h3>";
								return; //set a flag here to write the error. 
							}
							echo 'Ground transport from <strong>' . $destination[0] . '</strong>'. ' to Whistler ';
							echo '<br/>';
							 
							$query="SELECT * FROM ground WHERE city=\"". $destination[0] ."\"";
	       					$result = mysqli_query($cxn,$query);
							$row = mysqli_fetch_assoc($result);
							echo 'Place of origin:<strong>' . ucwords(strtolower( $row['City'])) .  '</strong> with distance <strong>' 
								  . ucwords(strtolower( $row['Distance'])).  '</strong><br/>';
						
						$ground_dist=$row['Distance'];
						$dist = distance($orglat,$orglong,$deslat,$deslong, "k") ;
						//echo floor($dist)* $rout . " kilometers<br>";
						$total =  emission( $dist ) +  ground_emission($ground_dist) ;
						//echo  round($total) . " kilograms<br>";
						$cton += round($total/1000,3);
						echo $cton . " tonne<br>";
						$totaldist += floor($dist);
						$emission += round($total);
							
						}
						
						echo 'Mode of ground transport to Whistler: '.'<strong>'. $_SESSION['mode'] . '</strong>';
						echo '<br/>';
						
						if($_SESSION['flymode'] =='yvr')
						{
						$ground_dist= 122;
						//and one table for car modes too.
						}
						else if($_SESSION['flymode'] =='sea')
						{
						$ground_dist=354;
						}
						
						$dist = distance($orglat,$orglong,$deslat,$deslong, "k") ;
						//echo floor($dist)* $rout . " kilometers<br>";
						$total =  emission( $dist ) +  ground_emission($ground_dist) ;
						//echo  round($total) . " kilograms<br>";
						$cton += round($total/1000,3);
						//echo $cton . " tonne<br>";
						$totaldist += floor($dist);
						$emission += round($total);
						echo 'Distance: <b>' .  floor($dist) . ' </b>kilometers per leg,&nbsp;&nbsp;&nbsp;Emissions per passenger: <b>' . round($total) . ' </b>kilograms of CO2e per leg.<br/><br/>'; 
						         
				    
		}
		
		
		echo '<hr>';
			echo '<h3> Emission, Distance, and Cost Summary:</h3>';
		echo 'Total trip distance:<b> '  . $totaldist * $rout  . '</b> km/passenger. <br/> ';
		echo 'Total trip emissions:<b> '  .number_format($rout * $cton, 1, '.', '') . '</b> tonne/passenger. <br/> ';
		$number = $rout * $passengers * $cton * 20 ;
		echo 'Total offset cost for<b> '  .$passengers  . '</b> passenger(s) climate friendly  
		      is only: <b>$' .number_format($number, 2, '.', '').' </b>(CDN)<br/>';
		
 ?>


<br/>
<a href="index.php" title="New" accesskey="n" target="_self">New calculation</a>
<br/>
<br/>

  <a href="http://www.offsetters.ca">
<img src="http://www.trekescapes.com/offsetting/images/ofsetters-logo.gif" width="250" height="98" border="0" /></a>

<?php
 function distance($lat1, $lon1, $lat2, $lon2, $unit) { 

 
     $theta = $lon1 - $lon2;

 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

//return emission in kgr
function emission($dist) { 
  $metric = 2;
  //freight allocation
  $freight = 0.10;
  if($dist <= 500)
  {
      $haul = 0.15; 
  }
   if($dist <= 1600 && $dist > 500)
  {
      $haul = 0.12;
  }
   if($dist > 1600)
  {
      $haul = 0.11;
  }
   
   $temission = $dist * $haul;
   //echo $temission."<br>";
   $falloc = $temission * $freight;
   //echo $falloc."<br>";
   $emission = ($temission - $falloc)*$metric;   
   return $emission;
}

//return ground emission in kgr
function ground_emission($dist) { 
	//use $_SESSION['mode'] for each emiision rateand haul.
		
  if($_SESSION['mode'] == "car")
  {
	$haul = 0.2457;
	echo '<br/>DEBUG: You are using <b> Car/Station Wagon </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "van")
  {
      $haul = 0.31668; 
	  echo '<br/>DEBUG: You are using <b> Van </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "sport")
  {
      $haul = 0.34944; 
	  echo '<br/>DEBUG: You are using <b> Sport-Utility Vehicle </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "truck")
  {
      $haul = 0.37947; 
	  echo '<br/>DEBUG: You are using <b> Pickup truck </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "hcar")
  {
      $haul = 0.130221; 
	  echo '<br/>DEBUG: You are using <b> Hybrid Car </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "hsuv")
  {
      $haul = 0.204295; 
	  echo '<br/>DEBUG: You are using <b> Hybrid SUV </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "cab")
  {
      $haul = 0.2457; 
	  echo '<br/>DEBUG: You are using <b> Cab </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }    
  if($_SESSION['mode'] == "limo")
  {
      $haul = 0.47194875; 
	  echo '<br/>DEBUG: You are using <b> Limo </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "bus")
  {
      $haul = 0.0565; 
	  echo '<br/>DEBUG: You are using <b> Bus </b> and the distance is <b>' . $dist . '</b>.<br/>';
  }
  
   
   $emission = $dist * $haul; 
   return $emission;
}




function createInput($name, $value, $type, $checked)
{
	return "<input type=\"{$type}\" name=\"{$name}\" value=\"{$value}\" " . ( $checked ? " checked = \"checked\" " : "" ) . "/>" ;
}
?>
 






























