<?
$page_start=microtime(true);
#ini_set('display_errors', -1);
#ini_set('error_reporting', -1);
if( headers_sent() ){
    	$encoding = false;
}elseif( strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false ){
    	$encoding = 'x-gzip';
}elseif( strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false ){
    	$encoding = 'gzip';
}else{
    	$encoding = false;
}

if( $encoding ){
	ob_start("ob_gzhandler");
}

session_start();

if (isset($_POST['torqueid'])) {
	$_SESSION['id'] = md5($_POST['torqueid']);
	// name, value, expire, path // default path is current!
	setcookie('lastid', $_POST['torqueid'], time()+(60*60*24*365), "/");
}

$body ="<body>\n";

$db_user = "torqueuser";
$db_pass = "torquepass";
$db_name = "torque";
$db_table = "raw_logs";

$link = mysql_connect('localhost', $db_user, $db_pass);
$db = mysql_select_db($db_name);

// make sure we've got historical data for the user's torque id (which is passed into torque.php by the app as the md5 of what's given to the user.)
$session_check = mysql_num_rows(my_sql_query("select distinct(session) from $db_table where id = \"".$_SESSION['id']."\""));
$dum = my_sql_query("delete from $db_table where kff1006 = 0 and kff1005 = 0");
print mysql_error();
if ($session_check == 0) {
	if(isset($_COOKIE['lastid'])) {
		$_SESSION['id'] = md5($_COOKIE['lastid']);
		$session_check = mysql_num_rows(my_sql_query("select distinct(session) from $db_table where id = \"".$_SESSION['id']."\""));
	}
	if ($session_check == 0) {
		header("Location: /");
		exit;
	}
}

if ( $_GET['delete'] ){
	$d = my_sql_query("update $db_table set deleted = 1 where id = \"".$_SESSION['id']."\" and session = \"".mysql_real_escape_string($_GET['delete'])."\"");
	mysql_result($d);
}

$nocache=$_GET['devel'];
$nocache="true";
if (isset($_GET['view'])) {
	// check if the cache exists and send them that, valid for 1 hour?
	$cache_file="cache/".$_SESSION['id']."-".md5($_GET['view']).".cache";
	if (file_exists($cache_file) && (empty($nocache))) {
		if (date("U")-filemtime($cache_file) < 900 ) {
			print file_get_contents($cache_file);
			print "Cached ".(date("U")-filemtime($cache_file))." sec ago (".date ("F d Y H:i:s.", filemtime($cache_file)).")";
			exit;
		}
	}
}

# get all the user sessions and dump them into an array
$req = my_sql_query("select distinct(session) from $db_table where id = \"".$_SESSION['id']."\" and deleted <> 1 order by session DESC");
while ($data = mysql_fetch_row($req)) {
	$sessions[] = $data[0];
}

$head = '<head>
<style type="text/css">
.left {
	font-size:12px;
	float:left;
	height:99%;
	padding-right:10px;
}
.sessions {
	max-height:60%;
	overflow-y:scroll;
	margin-bottom:10px;
	min-width: 110px;
}
.map_holder {
	float:none;
	width: 345px;
	height: 345px;
}
.slink { 
	text-decoration: none;
	color: #000;
}
.slink:hover { background-color: #ff0; }
.dlink:hover { background-color: #f00; }
	
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
';
// create the sessions div down the left side, $body and is build up as what will be the html body, we build html head section a bit below and obviously want head before body on output.
$body .= "<div class=\"left\"><div class=\"sessions\">\n";
if (($_GET['view']+0) > 0 ){
	$all = array();
	$allin = my_sql_query("select * from $db_table where session = ".($_GET['view']+0)." and id = \"".$_SESSION['id']."\" order by time");
	while ($row = mysql_fetch_assoc($allin)) {
	$all[] = $row;
	}
}

foreach ($sessions as $session){
	$o=$c="";
	if ($session == $_GET['view']) {
		$o = "<b>";
		$c = "</b> <a href=index.php?delete=$session class=\"dlink slink\" title=\"Delete\" onclick=\"return confirm('Really Delete?');\">[X]</a>";
	}
		$body .= "$o<a href=\"?view=$session\" class=\"slink\">".date("d/n/y H:i", $session/1000)."</a>$c<br>\n";
	}
	$body .= "</div><div id=\"pids\"></div></div>\n";

	// this is where the map will go, change the width and height of the div in css to adjust the size.
	$body .= "<div class=\"map_holder\" id=\"map_canvas\" style=\"float:left;\"></div>\n<div name='pano' id='pano' style='width: 345px; height: 345px'></div>";

	// dirty but it works and gives links that'll take you directly to the data.
	if ($_GET['view']) {
		for ($i=0;$i<sizeof($all);$i++) {
			$coords[] = array($all[$i]["kff1006"],$all[$i]["kff1005"]);
			$x[] = $all[$i]["kff1006"];
			$y[] = $all[$i]["kff1005"];
		}
		// calculate where the center of the map should be.
		$xd = (max($x)-min($x))/2;
		$cx = min($x)+$xd;
		$yd = (max($y)-min($y))/2;
		$cy = min($y)+$yd;
		// cx and cy (Center X/Y) are used below to set the map center, however moving to api v3 allowed the api to locate center itself.
	}

	// this is where all the google maps api stuff happens
	$gmap .= "<script type=\"text/javascript\"> \n";

	if ($_GET['view'] > 0) {
	    $gmap .= "var myLatlng = new google.maps.LatLng($cx, $cy);";
	} else {
	    // this was here to center in on the o2 arena when as default with no track selected.
	    $gmap .= "var myLatlng = new google.maps.LatLng(51.502999,0.003144);";
	}

	$gmap .= "
	  //function initialize() {
	    var myOptions = {
	      zoom: 14,
	      center: myLatlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
	   var map = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);

	    ";

	if ($_GET['view'] > 0) {
	// this builds the javascript to create the polyline
	$gmap .= "var flightPlanCoordinates = [\n";
	// do the new google.maps.LatLng(37.772323, -122.214897), (no , on last one :()
		foreach ($coords as $points){
		$gmap .= "new google.maps.LatLng(".$points[0].", ".$points[1]."),";
		}
	$gmap .= '];
	  var flightPath = new google.maps.Polyline({
	    path: flightPlanCoordinates,
	    strokeColor: "#0000FF",
	    strokeOpacity: 1.0,
	    strokeWeight: 3
	  });

	  flightPath.setMap(map);
	  var bounds = new google.maps.LatLngBounds ();
	  for (var i = 0, LtLgLen = flightPlanCoordinates.length; i < LtLgLen; i++) {
		bounds.extend (flightPlanCoordinates[i]);
	  }
	  map.fitBounds (bounds);



var panoramaOptions = {
  position: flightPlanCoordinates[0],
  pov: {
    heading: '.$all[0]['kff1007'].',
    pitch: 0,
    zoom: 1
  }
};
var panorama = new  google.maps.StreetViewPanorama(document.getElementById("pano"), panoramaOptions);
pano.setStreetView(panorama);


';
	}
	$gmap .= '</script> 
	  ';

	if ($_GET['view']) {

		$sess = $_GET['view'];
		    #$headers = mysql_fetch_assoc(my_sql_query("select * from $db_table where session = $sess and id = \"".$_SESSION['id']."\" limit 1"));
		    $headers = $all[0];
		    $blacklistkeys=array("kff1005", "kff1006", "kff1007");
		    #$blacklistkeys=array("kff1005", "kff1006", "kff1220", "kff1221" ,"kff1226", "kff1007", "k46", "k2f");
		    /* 
		    * kc as it's RPM and it's normally to high for graphing, needs scaling down.
		    * k46 - ambient air temp - not received.
		    * k2f - fuel level - again not received
		    */

		    // make sure that we've <> 0 data getting returned for each, check min and max.
		    $header=array();
		    foreach ($headers as $key => $value) {
			if ( (preg_match("/^k/", $key)) && (! in_array($key, $blacklistkeys)) ){
				#$chk = mysql_fetch_array(my_sql_query("select min($key)+0,max($key)+0 from $db_table where session = $sess and id = \"".$_SESSION['id']."\" limit 1"));
				$a=array();
				for ($i=0;$i<sizeof($all);$i++) {
					$a[] = $all[$i][$key];
				}
				$chk=array(min($a),max($a));
				if ( ($chk[0] != 0) || ($chk[1] != 0) ) {
					$header[] = $key;
				}
			}
		    }
		   
	$head .= '
	  <script type="text/javascript">
';
		
		$domain = array();
		$direction = array();
		for ($i=0;$i<sizeof($all);$i++) {
			$domain[] = $all[$i]["time"];
			$direction[] = $all[$i]['kff1007'];
		}
	foreach ($header as $key) {

		$range = array();
		for ($i = 0 ; $i < sizeof($all); $i++){
			$row[0] = $all[$i][$key];
			// reduce revs so they fit nicer into < 100
			if ($key == "kc") {
				$range[] = $row[0]/35;
			// convert kph to mph
			} else if ( $key == "k0d" || $key == "kff1001" || $key == "kd") {
					// clip to max speed limit
				if ( $row[0]*0.621371192 > 70 ) { 
					$range[] = 70; 
				} else {
					$range[] = $row[0]*0.621371192;
				}
			} else {
				$range[] = $row[0];
			}
		}
		$json[$key]['id'] = $key;
		$json[$key]['domain'] = $domain;
		$json[$key]['direction'] = $direction;
		$json[$key]['label'] = mysql_fetch_row(my_sql_query("select name from key_name where pid = \"$key\" limit 1"))?:$key;
		if ($key == "kc") {
		 	$json[$key]['label'] = $json[$key]['label'][0]." * 35";
		} else if ( $key == "k0d" || $key == "kff1001" || $key == "kd") {
			$json[$key]['label'] = $json[$key]['label'][0]." [mph]";
		}
		$json[$key]['range'] = $range;
		$json[$key]['axis'] = "value";
		$head .= "\t".$key." = ".json_encode($json[$key])."\n";


		
	}
	$head .= "
	</script>
	  <script type=\"text/javascript\" src=\"/widget/widget.js\"></script>
	  <script type=\"text/javascript\">
	    function onChronoscopeLoaded(chrono) {
	     var data = [".join(",",$header)."];
	pids = document.getElementById('pids');
        var pidsinner='';
        for (var i=0; i<data.length; i++) {
                pidsinner += '<input type=\"checkbox\" name=\"option1\" value=\"'+ data[i].id +'\" checked onclick=\"dostuff();\">'+ data[i].label +'</input><br>';
        }
        //alert(sessiondatainner);
        pids.innerHTML = pidsinner;
	     chronoscope.Chronoscope.setErrorReporting(true);
	     chronoscope.Chronoscope.createTimeseriesChartById(\"chartid\", data, 750, 345, function(view) {
		var ch = view.getChart(), pl = ch.getPlot();
		pl.addHoverHandler(function(e) {
                var timestamp = e.getDomainPoints()[0];
                index = data[0]['domain'].indexOf(timestamp.toString());
                //document.getElementById('SteveDebug').innerHTML = index; 
                //index = window.kff1001.indexOf(timestamp.toString());
                var marker = new google.maps.Marker({
                        position: flightPlanCoordinates[index],
                        icon: '/car.png'
                        });
                marker.setMap(map);
                try {oldmarker.setMap(null);} catch (e) {;}
                oldmarker = marker;
		panoramaOptions = {
		  position: flightPlanCoordinates[index],
		  pov: {
		    heading: parseInt(data[0]['direction'][index]) + 0,
		    pitch: 0,
		    zoom: 1
		  }
		};
		var panorama = new  google.maps.StreetViewPanorama(document.getElementById(\"pano\"), panoramaOptions);
		pano.setStreetView(panorama);

       });
       ch.redraw();
       largeview = view;
	     });
	   }

function dostuff() {
        var inputs = document.getElementsByTagName('input');
        var data = [];
        for(var i=0; i<inputs.length; i++){
		//alert(inputs[i].value.length);
                if(inputs[i].getAttribute('type')=='checkbox'){
                        if ( (inputs[i].checked == 1) && (inputs[i].value != 'on') && (inputs[i].value.length > 0) ){
                                data.push(eval(inputs[i].value));
                        }
                }
        }
        //alert(data[0].id.toString());
	chronoscope.Chronoscope.setErrorReporting(true);
             chronoscope.Chronoscope.createTimeseriesChartById(\"chartid\", data, 750, 345, function(view) {
                var ch = view.getChart(), pl = ch.getPlot();
                pl.addHoverHandler(function(e) {
                var timestamp = e.getDomainPoints()[0];
                index = data[0]['domain'].indexOf(timestamp.toString());
                var marker = new google.maps.Marker({
                        position: flightPlanCoordinates[index],
                        icon: '/car.png'
                        });
                marker.setMap(map);
                try {oldmarker.setMap(null);} catch (e) {;}
                oldmarker = marker;
 
       });
       ch.redraw();
       largeview = view;
             });

 }

function steve_cleanup() {
	alert(document.getElementById('sessions').style.height);
	alert(document.getElementById('left').style.height);
	alert(document.getElementById('pids').style.height);
	return true;
}

	  </script>
	  ";
	$body .= "   <div id=\"chartid\">Loading ...</div>\n";

	} // end chart if

	
if (isset($_GET['view'])) {
	// check if the cache exists and send them that, valid for 1 hour?
	$cache_file="./cache/".$_SESSION['id']."-".md5($_GET['view']).".cache";
	file_put_contents($cache_file, $head."</head>".$body);
}
	print "$head</head>$body\n$gmap";
print "Page loaded in ".number_format(microtime(true)-$page_start, 4)." Seconds.<br><div id=\"debug\"></div>";

function sec2hms ($sec, $padHours = false) 
  {
    // start with a blank string
    $hms = "";
    // do the hours first: there are 3600 seconds in an hour, so if we divide
    // the total number of seconds by 3600 and throw away the remainder, we're
    // left with the number of hours in those seconds
    $hours = intval(intval($sec) / 3600); 
    // add hours to $hms (with a leading 0 if asked for)
    $hms .= ($padHours) 
          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
          : $hours. ":";
    // dividing the total seconds by 60 will give us the number of minutes
    // in total, but we're interested in *minutes past the hour* and to get
    // this, we have to divide by 60 again and then use the remainder
    $minutes = intval(($sec / 60) % 60); 
    // add minutes to $hms (with a leading 0 if needed)
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";
    // seconds past the minute are found by dividing the total number of seconds
    // by 60 and using the remainder
    $seconds = intval($sec % 60); 
    // add seconds to $hms (with a leading 0 if needed)
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
    // done!
    return $hms;
    
  }

function my_sql_query($query) {
#$start = microtime(true);	
$data = mysql_query($query);
#$end = microtime(true);

#$log = number_format(($end-$start),6)."\t$query\n";
#@file_put_contents("../logs/torque.php.sql_debug.csv", $log, FILE_APPEND | LOCK_EX);
return $data;
}
