<?require ("global.php");?>
<?php

$stageID = 0;
if (isset($_POST['stageID'])) { $stageID = $_POST['stageID']; }

$segmentID = 0;
if (isset($_POST['segmentID'])) { $segmentID = $_POST['segmentID']; }

if ($stageID != 0)
{
  $query = "DELETE FROM maps_coords WHERE stageID = " . $stageID;
  $result = mysql_query($query, $db);
	
  $query = "SELECT * FROM segments WHERE stageID = $stageID";
  $result = mysql_query($query, $db);
  if ($result)
  {
    while ($r = mysql_fetch_array($result))
    {
      $segment = "segment" . $r['ID'];
      if (isset($_POST[$segment]) && $_POST[$segment] != "")
      {
	$coords = split(":", $_POST[$segment]);
	for ($i=0; $i < count($coords) - 1; $i++)
	{
	  list($lat, $lon) = split(",", $coords[$i]);
	  $query2 = "INSERT INTO maps_coords (stageID, segmentID, sequence, latitude, longitude) VALUES (" 
	    . "'" . $stageID . "',"
	    . "'" . $r['ID'] . "',"
	    . "'" . $i . "',"
	    . "'" . $lat . "'," 
	    . "'" . $lon . "')";
	  $result2 = mysql_query($query2, $db) or mysql_error($result2);
	}
      }

      $distance_mi = "distance_mi" . $r['ID'];
      $distance_km = "distance_km" . $r['ID'];
      if (isset($_POST[$distance_mi]) && $_POST[$distance_mi] != "")
      {
	$query2 = "UPDATE segments SET "
	  . "distance_mi = '" . $_POST[$distance_mi] . "', "
	  . "distance_km = '" . $_POST[$distance_km] . "' "
	  . "WHERE ID = " . $r['ID'];
	$result2 = mysql_query($query2, $db) or mysql_error($result2);
      }

    }
    mysql_free_result($result);
  }

  if ($segmentID == 0)
    {
      $query = "INSERT INTO segments (stageID, color, name) VALUES (" 
	. "'" . $stageID . "', "
	. "'" . $_POST['color'] . "', "
	. "'" . myaddslashes($_POST['name']) . "')";
      $result = mysql_query($query, $db) or mysql_error($result);
    }
}

header("Location: /tick/maps_courses.php");

?>
