// Aaron Spaulding
// Aaron@sachimp.com
// http://sachimp.com
// This code demonstrates that well crafted
//   JavaScript code can be run as PHP under
//   certain conditions.

// This idea was inspired by work done
//   by Billy (Acidus) Hoffman

// http://www.memestreams.net/users/Acidus
// http://en.wikipedia.org/wiki/Billy_Hoffman
// http://www.youtube.com/watch?v=KN6iuS0u9U4
// bhoffman@spidynamics.com

// test to see which environment we are in
function get_environment() {
	if(document) {
		return "JavaScript";
	} else {
		return "PHP";
	}
}

// an output function
function output($text) {
	if (get_environment() == "PHP") {
		eval("print(\"<b>From PHP:</b>  $text\");");
	} else {
		eval("document.write(\"<b>From Javascript:</b>" + $text + "\");");
	}
}

// wrap trig functions for compatibility with php
// unfortunately this function will make
//   your code resemble RPN, I'm so sorry. :P

function hide_math ($val, $func) {
	// for this to work we need hide the
	//   environment specific details
	//   in side of an eval()
	
	// in PHP we want
	//   "return sin(3.14);"
	// in JS we want
	//   "Math.sin(3.14);"

	$base = "";
	if(get_environment() == "PHP") {
		$base = "return $func($val);";
	} else {
		// PHP will interpret this as addition but thats ok
		$base = "Math." + $func + "(" + $val + ");";
	}
	
	return eval($base);
}

// same as above but with two variables

function hide_math_2($top, $bottom, $func) {
	$base = "";
	if(get_environment() == "PHP") {
		$base = "return $func($top, $bottom);";
	} else {
		// PHP will interpret this as addition but thats ok
		$base = "Math." + $func + "(" + $top + "," + $bottom + ");";
	}
	
	return eval($base);
}

function deg_to_rad($theta) {
	$PI = 3.14159265;
	return ($theta / 180) * $PI;
}

function great_circle_distance($start_lat, $start_lng, $end_lat, $end_lng) {
	// from http://en.wikipedia.org/wiki/Great-circle_distance
	$radius = 6371.01; //km
	$delta_lambda = deg_to_rad($start_lng) - deg_to_rad($end_lng);// the change in the longitude
	$start_phi = deg_to_rad($start_lat);
	$end_phi = deg_to_rad($end_lat);
	
	$devisor_part_1 = hide_math_2(hide_math($end_phi,"cos") * hide_math($delta_lambda,"sin"),2, "pow");
	$devisor_part_2 = hide_math_2((hide_math($start_phi,"cos") * hide_math($end_phi,"sin")) - (hide_math($start_phi,"sin") * hide_math($end_phi,"cos") * hide_math($delta_lambda,"cos")),2, "pow");
	$devisor = hide_math( $devisor_part_1 + $devisor_part_2, "sqrt"); // finish me
	
	$denom = (hide_math($start_phi,"sin") * hide_math($end_phi,"sin")) + (hide_math($start_phi,"cos") * hide_math($end_phi,"cos") * hide_math($delta_lambda,"cos"));
	
	$angle  = hide_math_2($devisor, $denom, "atan2");

	return $angle * $radius;
}


output(great_circle_distance(36.12, 86.67, 33.94, 118.40));
