<?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)
	  {
 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	
        {
		    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;
		   		}
			}
 	    }


	 if($multiple)
	 {
	        
	       	echo '<form action="index.php?'. SID .'" method="post" target="_self">';
	        for($j = 0; $j <= $count; $j++) 
			{         
               		
	 		        echo '<br><h2>Airport '.$j.' : </h2>';
					$form = null;
					$text = 'radio';
					for($i = 1; $i <= $nrows[$j]; $i++) 
					{
					    $row = mysqli_fetch_assoc($result[$j]);
          				$input = createInput($text."destin".$j,$row['iata'],$text,$i==1);
						$form .= $input;
						
						 $form .= '<b>'. ucwords(strtolower( $row['name'])) . ' (' . $row['iata'] .')' .  '</b> airport at <b>' 
							  . ucwords(strtolower( $row['city'])) . '-'  .
							    ucwords(strtolower( $row['country'])) . '</b>' ."</label><br /> \n";
						
						
					}		
					echo $form;
			}
					echo '<br><input name="calculate" type="submit" value="calculate emissions" />';
					echo '</form>';	
					return;	
       }//end of multiple
	   // Report starts from this line. 
	   echo '<br/><h2> Emission Offset </h2>';
		        
			  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
						{
						//later on use the origin to calculate the results. make a new table for ground locations is a good idea.
						
						}
						
						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 );
					   //different calculation for ground total
					    $ground_total = ground_emission($ground_dist) ;
						//echo  round($total) . " kilograms<br>";
						$cton += round($total/1000,3);
						$ground_cton = round($ground_total/1000,3);
						//echo $cton . " tonne<br>";
						$totaldist += floor($dist);
						$emission += round($total);
						$ground_emission += round($ground_total);
						echo 'Flight 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 'Ground Distance: <b>' .  floor($ground_dist) . ' </b>kilometers per leg,&nbsp;&nbsp;&nbsp;Emissions per passenger: <b>' . round($ground_total) . ' </b>kilograms of CO2e per leg.<br/><br/>';          
				    
		}
		
		
		echo '<hr>';
		//DEBUG
		echo '<h3>DEBUG</h3>';
        echo 'Total ground trip distance:<b> '  . $ground_dist * $rout  . '</b> km/passenger. <br/> ';
		echo 'Total ground trip emissions:<b> '  .number_format($rout * $ground_cton, 2, '.', '') . '</b> tonne/passenger. <br/> ';
    	echo 'Total flight trip distance:<b> '  . $totaldist * $rout  . '</b> km/passenger. <br/> ';
		echo 'Total flight trip emissions:<b> '  .number_format($rout * $cton, 2, '.', '') . '</b> tonne/passenger. <br/> ';
		//DEBUG	
        $total_dist = ($ground_dist +  $totaldist) * $rout ;
		$total_emissions = $rout * ( $cton + $ground_cton);
		echo '<hr>';
		echo '<h3>Emission, Distance, and Cost Summary:</h3>';
		echo 'Total trip distance:<b> '  . $total_dist  . '</b> km/passenger. <br/> ';
		echo 'Total trip emissions:<b> '  .number_format($total_emissions, 2, '.', '') . '</b> tonne/passenger. <br/> ';
		$number = $rout * $passengers * $cton * 20 ;
		echo 'DEBUG: <strong><Flight></strong> Total offset cost for<b> '  .$passengers  . '</b> passenger(s) climate friendly  
		      is only: <b>$' .number_format($number, 2, '.', '').' </b>(CDN)<br/>';
		$ground_number = total_offset_ground($rout,$passengers,$ground_cton);	  
		echo 'DEBUG: <strong><Ground></strong> Total offset cost for<b> '  .$passengers  . '</b> passenger(s) climate friendly  
		      is only: <b>$' .number_format($ground_number, 2, '.', '').' </b>(CDN)<br/>';	  
		//only for debuging
		//total_offset
		$total_offset = $number + $ground_number;
		echo 'Total offset cost for<b> '  .$passengers  . '</b> passenger(s) climate friendly  
		      is only: <b>$' .number_format($total_offset, 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
//$rout * $passengers * $cton * 20 (dollar per tonn)
function total_offset_ground($rout,$passengers,$cton) 
{ 
	if($_SESSION['mode'] == "bus")
	{	
	   $offset = $rout * $passengers * $cton * 20 ;
	}
	else
	{
	   $offset = $rout * 1 * $cton * 20 ;
	}
	return $offset;
}


 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.2124;
	echo '<br/>DEBUG: You are using <b> Car/Station Wagon </b> and Emissions for Gasoline Modes
         is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "van")
  {
      $haul = 0.27376; 
	  echo '<br/>DEBUG: You are using <b> Van </b> and Emissions for Gasoline Modes
         is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "sport")
  {
      $haul = 0.30208; 
	   echo '<br/>DEBUG: You are using <b> SUV </b> and Emissions for Gasoline Modes
         is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "truck")
  {
      $haul = 0.32804; 
	    echo '<br/>DEBUG: You are using <b> Truck </b> and Emissions for Gasoline Modes
         is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "hcar")
  {
      $haul = 0.130221; 
	  echo '<br/>DEBUG: You are using <b> Hybrid Car </b> and Emissions for Diesel Modes
 is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "hsuv")
  {
      $haul = 0.204295; 
	  echo '<br/>DEBUG: You are using <b> Hybrid SUV </b> and Emissions for Diesel Modes
 is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "cab")
  {
      $haul = 0.2457; 
	  echo '<br/>DEBUG: You are using <b> Cab </b> and Emissions for Diesel Modes
 is <b>' . $haul . '</b>.<br/>';
  }    
  if($_SESSION['mode'] == "limo")
  {
      $haul = 0.47194875; 
	 echo '<br/>DEBUG: You are using <b> LIMO </b> and Emissions for Diesel Modes
 is <b>' . $haul . '</b>.<br/>';
  }
  if($_SESSION['mode'] == "bus")
  {
      $haul = 0.0565; 
	  echo '<br/>DEBUG: You are using <b> BUS </b> and Emissions for Diesel Modes
 is <b>' . $haul . '</b>.<br/>';
 }
   $emission = $dist * $haul; 
   return $emission;
}




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






























