<?php

include "../Database.class";
include "../Functions.php";

	list($usec, $sec) = explode(" ",microtime()); 
  $TimeStartTotal = ((float)$usec + (float)$sec); 

//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
  
  if(isset($_GET["output"]) == TRUE)
  {
    $Output = $_GET["output"];
  }
  else
  {
    $Output = "json";
  }
  
  if(isset($_GET["app"]) == TRUE)
  {
    $App = $_GET["app"];
  }
  else
  {
    $App = "free";
  }
  
  if(isset($_GET["spots"]) == TRUE)
  {
    $Spots = $_GET["spots"];
  }
  else
  {
    $Spots = "";
  }
  
  if(isset($_GET["lon"]) == TRUE)
  {
    $Longitude = $_GET["lon"];
  }
  else
  {
    $Longitude = "";
  }
  
  if(isset($_GET["lat"]) == TRUE)
  {
    $Latitude = $_GET["lat"];
  }
  else
  {
    $Latitude = "";
  }
  
  if(isset($_GET["max"]) == TRUE)
  {
    $Max = $_GET["max"];
  }
  else
  {
    $Max = 10;
  }
  
  if(isset($_GET["when"]) == TRUE)
  {
    $When = $_GET["when"];
  }
  else
  {
    $When = "now";
  }
  
  if(isset($_GET["activity"]) == TRUE)
  {
    $IDActivity = $_GET["activity"];
  }
  else
  {
    $IDActivity = 0;
  }
/*
  $ShowMeteo = True;
  if(isset($_GET["meteo"]) == TRUE)
  {
    if ($_GET["meteo"] == "no")
    {
    	$ShowMeteo = False;
    }
  }
  
  $ShowAstro = False;
  if(isset($_GET["astro"]) == TRUE)
  {
    if ($_GET["astro"] == "yes")
    {
    	$ShowAstro = True;
    }
  }
*/
  $ShowAstro = True;
  
  
  /*
  if(isset($_GET["string"]) == TRUE)
  {
    if ($_GET["string"] == "yes")
    {
    	$String = True;
    }
    else
    {
    	$String = False;
    }
  }
  else
  {
    $String = False;
  }
  */
  $String = True;
  
  //$App = "free";
  //echo "Output=".$Output.$CR;
  //print_r($TabSpots);
  //exit();
  
//---------------------------------------------------------------------------------------------------------------- 
// INIT
//----------------------------------------------------------------------------------------------------------------  

  $Db = FN_DbOpen();

  $IDLog = Log_Insert($Db, $CR, "getmeteogeo", $_SERVER);
  //echo "IDLog=".$IDLog.$CR;

//---------------------------------------------------------------------------------------------------------------- 
// Check EMAIL
//----------------------------------------------------------------------------------------------------------------  

  //$_POST["email"] = "fishwolf@gmail.com";
  if(isset($_POST["email"]) == TRUE)
  {
    $Query  = "SELECT * FROM profiles WHERE email='".$_POST["email"]."'";
    //echo "Query=".$Query.$CR;
    $Result = $Db->Exec($Query);
    $TotRec = $Db->Numrows($Result);
    //echo "TotRec=".$TotRec.$CR;
    
    $Record = $Db->Fetch($Result, 0);
    $IDProfile = $Record["id"];
  }
  else
  {
    $IDProfile = 0;
  }
  //echo "IDProfile=".$IDProfile.$CR;

//---------------------------------------------------------------------------------------------------------------- 
// Find SPOTS
//----------------------------------------------------------------------------------------------------------------  

	if (strlen($Latitude) > 0 && strlen($Longitude) > 0)	
	{
		$Query  = "SELECT * FROM spots WHERE enable=1 ";
    $Query .= "AND latitude > ".intval($Latitude - 2)." AND latitude < ".intval($Latitude + 2)." ";
    $Query .= "AND longitude > ".intval($Longitude - 2)." AND longitude < ".intval($Longitude + 2)." ";
  	$Query .= "ORDER BY name";
  	//echo "Query=".$Query.$CR; 
  	$Result = $Db->Exec($Query);  
  	$TotRec = $Db->Numrows($Result);
  	//echo "TotRec=".$TotRec.$CR;
  
  	$TabGeo = array();
  
  	$Unit = "Km";
    
  	for ($Rec=0;$Rec<$TotRec; $Rec++)
  	{
  		//echo "Rec=".$Rec.$CR;
  		
    	$Record = $Db->Fetch($Result, $Rec);
	
    	$Show = FALSE;
	
			if (strlen($Latitude) > 0 && strlen($Longitude) > 0)
			{
		  	$Distance = CalculateDistance($Latitude, $Longitude, $Record["latitude"], $Record["longitude"], $Unit);
		 
		  	$Show = TRUE;
			}
			else
			{
		  	$Distance = "???";
		  	$Show = TRUE;
			}
			//echo "Distance=".$Distance."-".$Unit.$CR;
		
			//$Distance = intval($Distance);
		
			if ($Show == TRUE)
    	{
    		$IndGeo = count($TabGeo);
  	    $TabGeo[$IndGeo]["id"]        = $Record["id"];
	      $TabGeo[$IndGeo]["distance"]  = $Distance;
	  	}
 		}	
 
  	if (count($TabGeo) > 0)
  	{
    	$TabGeo = FN_SortTable($TabGeo, "distance", "ASC", "num");
  	}
  
  	//print_r($TabGeo);
  	//exit();
  	
  	if (count($TabGeo) < $Max)
  	{
  		$Max = count($TabGeo);
  	}
  
  	$TabSpots = array();
  	for ($IndGeo=0; $IndGeo<$Max; $IndGeo++)
  	{
  		$TabSpots[] = $TabGeo[$IndGeo]["id"];
  	}
  }
  //print_r($TabSpots);
  //exit();
  
//---------------------------------------------------------------------------------------------------------------- 
// Check SPOTS
//----------------------------------------------------------------------------------------------------------------  

	if (strlen($Spots) > 0)
	{
  	$TabSpots = explode(",", $Spots);
  }
  
  $TabData = array();
	$TabSpot = array();
	  
  for ($IndSpot=0; $IndSpot<count($TabSpots); $IndSpot++)
  {                                   
  	$IDSpot = $TabSpots[$IndSpot];
  	
    $Query  = "SELECT * FROM spots WHERE id=".$IDSpot." AND enable=1";
    //echo "Query=".$Query.$CR;
    $Result = $Db->Exec($Query);
    $TotRec = $Db->Numrows($Result);
    //echo "TotRec=".$TotRec.$CR;
    
    if ($TotRec == 0) 
    {
     	$TabJson["Result"]["code"]    = -1;
    	$TabJson["Result"]["details"] = "spot not found(".$IDSpot.")";
    	$Json = json_encode($TabJson);
      echo $Json;
      
      Log_SetRisposta($Db, $CR, $IDLog, $Json);
      exit();
    }
    
    $Record = $Db->Fetch($Result, 0);
    
    $TypeSpot = $Record["type"];
    //echo "TypeSpot=".$TypeSpot.$CR;
    
    
    // Spot DATA
    $TabData[$IndSpot]["id"]   = $IDSpot;
    $TabData[$IndSpot]["name"] = $Record["name"];
    if (strlen($Record["locality"]) > 0)
    {
    	$TabData[$IndSpot]["loc"]  = $Record["locality"].", ".$Record["zone"].", ".$Record["country"];
    }
    else
    {
    	$TabData[$IndSpot]["loc"]  = $Record["zone"].", ".$Record["country"];
    }
    $TabData[$IndSpot]["lat"]  = $Record["latitude"];
    $TabData[$IndSpot]["lon"]  = $Record["longitude"];
    $TabData[$IndSpot]["type"] = $Record["type"];
    
    
    /*
    $TabSpot[$IDSpot]["name"] = $Record["name"];
    if (strlen($Record["locality"]) > 0)
    {
    	$TabSpot[$IDSpot]["loc"]  = $Record["locality"].", ".$Record["zone"].", ".$Record["country"];
    }
    else
    {
    	$TabSpot[$IDSpot]["loc"]  = $Record["zone"].", ".$Record["country"];
    }
    $TabSpot[$IDSpot]["lat"]  = $Record["latitude"];
    $TabSpot[$IDSpot]["lon"]  = $Record["longitude"];
    $TabSpot[$IDSpot]["type"] = $Record["type"];
    */
    
    
    $Day   = date("d");
    $Month = date("m");
    $Year  = date("Y");
    
    switch($When)
    {
    case "now":
    case "today":
      $Split = 0;
      break;
    case "next1":  
    case "next":  
      $Split = 1;
      break;
    case "next2":  
      $Split = 2;
      break;
    case "next3":  
      $Split = 3;
      break;
    case "next4":  
      $Split = 4;
      break;
    case "next5":  
      $Split = 5;
      break;
    case "next6":  
      $Split = 6;
      break;
     
    default:
      $TabJson["Result"]["code"]    = -1;
    	$TabJson["Result"]["details"] = "parameter when wrong";
    	$Json = json_encode($TabJson);
      echo $Json;
      
      Log_SetRisposta($Db, $CR, $IDLog, $Json);
      exit();
    }
      
    $TimeStamp = mktime(0, 0, 0, $Month, $Day + $Split, $Year);
      
    $DateMeteo = Date("Y-m-d", $TimeStamp);
    
    $TimeNow = date("H:i:s");
    
    //echo "DateMeteo=".$DateMeteo.$CR;
    //exit();
    
//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
      
    $Query  = "SELECT * FROM meteo2 WHERE id_spot=".$IDSpot." ";
    if ($When == "now")
    {  
      $Query .= "AND datetime<='".$DateMeteo." ".$TimeNow."' ";
		  $Query .= "ORDER BY datetime DESC LIMIT 1";
		}
		else
		{
			if ($When == "next")
      {  
        $TimeStamp = mktime(0, 0, 0, $Month, $Day + 6, $Year);
        $DateMeteoEnd= Date("Y-m-d", $TimeStamp);
        
        $Query .= "AND datetime>='".$DateMeteo." 00:00:00' AND datetime<='".$DateMeteoEnd." 23:59:59' ";
      }
      else
      {  
        $Query .= "AND datetime>='".$DateMeteo." 00:00:00' AND datetime<='".$DateMeteo." 23:59:59' ";
      }
		  $Query .= "ORDER BY datetime ASC";
    }
    //echo "Query=".$Query.$CR;
    $Result = $Db->Exec($Query);
    $TotRec = $Db->Numrows($Result);
    //echo "TotRec=".$TotRec.$CR;
    
    
    $IndDate = -1;
    $IndTime = -1;
    $MeteoDatePrec = "";  
    $MeteoTimePrec = "";  
    for ($Rec=0;$Rec<$TotRec; $Rec++)
    {
      $Record = $Db->Fetch($Result, $Rec);
      
      $MeteoDate = substr($Record["datetime"], 0, 10);
    	$MeteoTime = substr($Record["datetime"], 11, 5);	
    	
    	if ($MeteoDate != $MeteoDatePrec)
    	{
    		$MeteoDatePrec = $MeteoDate;
    		$IndDate++;
				$IndTime = -1;
    	}
    	$IndTime++;
		
    	$TabData[$IndSpot]["meteo"][$IndDate]["id"]                  = $Record["id"];
    	$TabData[$IndSpot]["meteo"][$IndDate]["lastupdate"]          = $Record["lastupdate"];
    	$TabData[$IndSpot]["meteo"][$IndDate]["date"]                = substr($Record["datetime"], 0, 10);
    	
    	$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["time"]                = substr($Record["datetime"], 11, 5);	
			
			$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["world_code"]          = OpenwheatermapCode2WorldweathernlineCode($Record["weather_code"]);
			$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["open_code"]           = $Record["weather_code"];
			$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["open_main"]           = $Record["weather_main"];
			$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["open_description"]    = $Record["weather_description"];
			
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["cloudcover_code"]     = $Record["cloudcover_code"];
		  //$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["visibility_code"]     = $Record["visibility_code"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["visibility_code"]     = "0";
                                                     
    	$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["temperature"]         = $Record["temperature"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["humidity"]            = $Record["humidity"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["rainfall"]            = $Record["rainfall"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["pressure"]            = $Record["pressure"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_code"]           = $Record["wind_code"];
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_descr"]          = WindCode2Descr ($Record["wind_code"]);
		  $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_degree"]         = $Record["wind_degree"];
		  //$TabData[$IDSpot][$Rec]["wind_speed"]          = $Record["wind_speed"]; // Kh
		  //$TabData[$IDSpot][$Rec]["wind_speed"]          = intval($Record["wind_speed"] / 1.852); // Convertito in nodi
		  if ($String == True)                           
		  {                                              
		  	$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_speed"]          = (string)intval($Record["wind_speed"]); // E' già in nodi
		  }
		  else
		  {
		  	$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_speed"]        = intval($Record["wind_speed"]); // E' già in nodi
		  }
		  
		  if ($TypeSpot == CONFIG_TYPES_MARINE)
		  {
		  	$TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["wind_speed_wwo"]    = AdjustValue($Record["wind_speed_wwo"]);
		    $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["swell_degree"]      = AdjustValue($Record["swell_degree"]);
		    $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["swell_height"]      = AdjustValue($Record["swell_height"]);
		    $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["swell_period"]      = AdjustValue($Record["swell_period"]);
		    $TabData[$IndSpot]["meteo"][$IndDate]["times"][$IndTime]["water_temperature"] = AdjustValue($Record["water_temperature"]);
		    //$TabData[$IndSpot]["meteo"][$Rec]["tide_height"]       = $Record["tide_height"];
		    
				if ($ShowAstro == True)
				{
					if (strlen($Record["tides"]) == 0)
					{
						$TabData[$IndSpot]["meteo"][$IndDate]["tides"] 			= array();
					}
					else
					{
  	  			$TabData[$IndSpot]["meteo"][$IndDate]["tides"] 			= json_decode($Record["tides"]);
  	  		}
  	  		$TabData[$IndSpot]["meteo"][$IndDate]["astronomy"] 	= json_decode($Record["astronomy"]);
    		}
		  }
		  
		  //echo "TypeSpot=".$TypeSpot."/".CONFIG_TYPES_SKY.$CR;
		  if ($TypeSpot == CONFIG_TYPES_SKY)
		  {
		    $TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_depthmin"]     = $Record["snow_depthmin"];
		    $TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_depthmed"]     = $Record["snow_depthmed"];   
		    $TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_depthmax"]     = $Record["snow_depthmax"]; 
		    $TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_tracksopen"]   = $Record["snow_tracksopen"]; 
		    $TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_trackstotal"]  = $Record["snow_trackstotal"]; 
		  }
		  //print_r($TabData);
			//exit();
			//echo json_encode($TabData);
			//exit();
		}
		
		//print_r($TabData);
		//echo json_encode($TabData);  
		//exit();

//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
  
    if ($When == "now")
    {
      //echo "TypeStation=".$TypeStation."<br>";
      
    	if ($IDSpot == 1) // Bracciano
    	{
    		if ($String == True)
			  {
        	$TabData[$IndSpot]["meteo"][0]["ms_station"] = "1";
        }
        else
        {
        	$TabData[$IndSpot]["meteo"][0]["ms_station"] = 1;
        }
      }
      else
      {
      	if ($String == True)
			  {
        	$TabData[$IndSpot]["meteo"][0]["ms_station"] = "0";
        }
        else
        {
        	$TabData[$IndSpot]["meteo"][0]["ms_station"] = 0;
        }
      }
      	
      
      if ($TypeSpot == CONFIG_TYPES_MARINE)
      {
      	$TabData[$IndSpot]["meteo"][0]["icons"][0]         = "vela_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][1]         = "kitesurf_disabled";  
        $TabData[$IndSpot]["meteo"][0]["icons"][2]         = "surf_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][3]         = "windsurf_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][4]         = "paddling_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][5]         = "pescasubacquea_disabled";  
        
        $TabData[$IndSpot]["meteo"][0]["icons"][0] = SetIcon($Db, $CR, $IDProfile, 6,  $TabData[$IndSpot]["meteo"][$IndDate], "vela", "vela_disabled"); // Vela
        $TabData[$IndSpot]["meteo"][0]["icons"][1] = SetIcon($Db, $CR, $IDProfile, 8,  $TabData[$IndSpot]["meteo"][$IndDate], "kitesurf", "kitesurf_disabled"); // Kitesurf
        $TabData[$IndSpot]["meteo"][0]["icons"][2] = SetIcon($Db, $CR, $IDProfile, 5,  $TabData[$IndSpot]["meteo"][$IndDate], "surf", "surf_disabled"); // surf
        $TabData[$IndSpot]["meteo"][0]["icons"][3] = SetIcon($Db, $CR, $IDProfile, 4,  $TabData[$IndSpot]["meteo"][$IndDate], "windsurf", "windsurf_disabled"); // windsurf
        $TabData[$IndSpot]["meteo"][0]["icons"][4] = SetIcon($Db, $CR, $IDProfile, 16, $TabData[$IndSpot]["meteo"][$IndDate], "paddling", "paddling_disabled"); // Padding
        $TabData[$IndSpot]["meteo"][0]["icons"][5] = SetIcon($Db, $CR, $IDProfile, 17, $TabData[$IndSpot]["meteo"][$IndDate], "pescasubacquea", "pescasubacquea_disabled"); // pescasubacquea
        //exit();
      }

      if ($TypeSpot == CONFIG_TYPES_SKY)
      {
      	$TabData[$IndSpot]["meteo"][0]["icons"][0]         = "snowboard_disabled";
      	$TabData[$IndSpot]["meteo"][0]["icons"][1]         = "arrampicata_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][2]         = "parapendio_disabled";
      	$TabData[$IndSpot]["meteo"][0]["icons"][3]         = "sci_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][4]         = "scifondo_disabled";  
        $TabData[$IndSpot]["meteo"][0]["icons"][5]         = "mountainbike_disabled";  
        
        $TabData[$IndSpot]["meteo"][0]["icons"][0] = SetIcon($Db, $CR, $IDProfile, 13,  $TabData[$IndSpot]["meteo"][$IndDate], "snowboard", "snowboard_disabled"); 
        $TabData[$IndSpot]["meteo"][0]["icons"][1] = SetIcon($Db, $CR, $IDProfile, 14,  $TabData[$IndSpot]["meteo"][$IndDate], "arrampicata", "arrampicata_disabled"); 
        $TabData[$IndSpot]["meteo"][0]["icons"][2] = SetIcon($Db, $CR, $IDProfile, 11,  $TabData[$IndSpot]["meteo"][$IndDate], "parapendio", "parapendio_disabled"); 
        $TabData[$IndSpot]["meteo"][0]["icons"][3] = SetIcon($Db, $CR, $IDProfile, 12,  $TabData[$IndSpot]["meteo"][$IndDate], "sci", "sci_disabled"); 
        $TabData[$IndSpot]["meteo"][0]["icons"][4] = SetIcon($Db, $CR, $IDProfile, 18,  $TabData[$IndSpot]["meteo"][$IndDate], "scifondo", "scifondo_disabled"); 
        $TabData[$IndSpot]["meteo"][0]["icons"][5] = SetIcon($Db, $CR, $IDProfile, 10,  $TabData[$IndSpot]["meteo"][$IndDate], "mountainbike", "mountainbike_disabled"); 
      }
      
      if ($TypeSpot == CONFIG_TYPES_LAKE)
      {
      	$TabData[$IndSpot]["meteo"][0]["icons"][0]         = "vela_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][1]         = "paddling_disabled";  
        $TabData[$IndSpot]["meteo"][0]["icons"][2]         = "windsurf_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][3]         = "canottaggio_disabled";
        $TabData[$IndSpot]["meteo"][0]["icons"][4]         = "kitesurf_disabled"; 
        //$TabData[$IDSpot]["meteo"][0]["icons"][5]         = "pescasubacquea_disabled"; // ??? PESCA
        
        $TabData[$IndSpot]["meteo"][0]["icons"][0] = SetIcon($Db, $CR, $IDProfile, 6,  $TabData[$IndSpot]["meteo"][$IndDate], "vela", "vela_disabled"); // Vela
        $TabData[$IndSpot]["meteo"][0]["icons"][1] = SetIcon($Db, $CR, $IDProfile, 16, $TabData[$IndSpot]["meteo"][$IndDate], "paddling", "paddling_disabled"); // Padding
        $TabData[$IndSpot]["meteo"][0]["icons"][2] = SetIcon($Db, $CR, $IDProfile, 4,  $TabData[$IndSpot]["meteo"][$IndDate], "windsurf", "windsurf_disabled"); // windsurf
        $TabData[$IndSpot]["meteo"][0]["icons"][3] = SetIcon($Db, $CR, $IDProfile, 15, $TabData[$IndSpot]["meteo"][$IndDate], "canottaggio", "canottaggio_disabled"); // canottaggio
        $TabData[$IndSpot]["meteo"][0]["icons"][4] = SetIcon($Db, $CR, $IDProfile, 8,  $TabData[$IndSpot]["meteo"][$IndDate], "kitesurf", "kitesurf_disabled"); // Kitesurf
      }
    }
    //unset($TabData[$IndSpot]["meteo"][$IndDate]["sky"]["snow_depthmed"]);
	}

//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
  
  $TabJson = array();
  
  $TabJson["Result"]["code"]    = 0;
  $TabJson["Result"]["details"] = "OK";
  
  $TabJson["spots"] = $TabData;
  
  //print_r($TabJson);
  //echo "Output=".$Output.$CR;
  
  if ($Output == "array")
  {
    $Json = print_r($TabJson, TRUE);
  }
  else
  {
    $Json = json_encode($TabJson);
  }
  
  echo $Json;
   
//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
  
  //echo "IDLog=".$IDLog.$CR;
  Log_SetRisposta($Db, $CR, $IDLog, $Json, $TimeStartTotal);
  
  $Db->Close();
  
  exit();
  
  

function SetIcon($Db, $CR, $IDProfile, $IDActivity, $TabMeteo, $IconEnable, $IconDisable)
{
	$Rc = CheckCondition($Db, $CR, $IDProfile, $IDActivity, $TabMeteo);
	
	if ($Rc == True)
	{
		//echo "TRUE".$CR;
		$Icon = $IconEnable;
	}
	else
	{
		//echo "FALSE".$CR;
		$Icon = $IconDisable;
	}
	//echo "Icon=".$Icon.$CR;
		
	//exit();
	
	return $Icon;
	
}

function CheckCondition($Db, $CR, $IDProfile, $IDActivity, $TabMeteo)
{
/*
	echo $CR;
	echo "IDProfile=".$IDProfile.$CR;
	echo "IDActivity=".$IDActivity.$CR;
	echo "TabMeteo=";
	echo print_r($TabMeteo);
	echo $CR;
	exit();
*/
	
	$Condition = "";
	
	if ($IDProfile > 0)
	{
	  $Query = "SELECT * FROM profiles_activities WHERE id_profile=".$IDProfile." AND id_activity=".$IDActivity;
	  //echo "Query=".$Query.$CR;
	  $Result = $Db->Exec($Query);
	  $TotRec =$Db->NumRows($Result);
	  //echo "TotRec=".$TotRec.$CR;
	  
	  if ($TotRec > 0)
	  {
		  $Record = $Db->Fetch($Result, 0);
		
		  $IDLevel = $Record["id_level"];
		  //echo "IDLevel=".$IDLevel.$CR;
		  
		  $Query = "SELECT * FROM activities_levels WHERE id=".$IDLevel;
		  //echo "Query=".$Query.$CR;
	    $Result = $Db->Exec($Query);
	  
		  $Record = $Db->Fetch($Result, 0);
		   
		  $Condition = $Record["condition"];
		}
	}
	//echo "Condition=".$Condition."-".$CR;
	
	if (strlen($Condition) == 0)
	{
	  $Query = "SELECT * FROM activities WHERE id=".$IDActivity;
	  //echo "Query=".$Query.$CR;
	  $Result = $Db->Exec($Query);
	  $Record = $Db->Fetch($Result, 0);
		
	  $Condition = $Record["condition"];
	}
	//echo "Condition=".$Condition."-".$CR;
	//$Condition = "\$wind_speed>=3 AND \$wind_speed<=8";
	
	//echo $CR;
	//$Condition = "\$rainfall==0 && \$water_temperature>15";
	//$Condition = "\$rainfall==0";
	//echo "Condition=".$Condition.$CR;
	//exit();
	
  $rainfall          = $TabMeteo["times"][0]["rainfall"];
  $wind_speed        = $TabMeteo["times"][0]["wind_speed"];
  $temperature       = $TabMeteo["times"][0]["temperature"];
  
  if (isset($TabMeteo["sky"]["snow_tracksopen"]) == True)
  {
  	$snow_tracksopen   = $TabMeteo["sky"]["snow_tracksopen"];
  }
  if (isset($TabMeteo["sky"]["snow_depthmed"]) == True)
  {
  	$snow_depthmed   = $TabMeteo["sky"]["snow_depthmed"];
  }
  if (isset($TabMeteo["times"][0]["swell_height"]) == True)
  {
  	$swell_height      = $TabMeteo["times"][0]["swell_height"];
  }
  if (isset($TabMeteo["times"][0]["water_temperature"]) == True)
  {
  	$water_temperature = $TabMeteo["times"][0]["water_temperature"];
  }

/*
  //$wind_speed = 15;
  echo "rainfall=".$rainfall.$CR;
  echo "wind_speed=".$wind_speed.$CR;
  echo "temperature=".$temperature.$CR;
  echo "snow_tracksopen=".$snow_tracksopen.$CR;
  echo "snow_depthmed=".$snow_depthmed.$CR;
  echo "swell_height=".$swell_height.$CR;
  echo "water_temperature=".$water_temperature.$CR;
  exit();
*/

	$Rc = False;
	$Command = "if (".$Condition.") { \$Rc = True; }";
	//echo "Command=".$Command.$CR;
	eval ($Command);

/*	
	if ($Rc == True)
	{
		echo "TRUE<br>";
	}
	else
	{
		echo "FALSE<br>";
	}
	exit();
*/
	
	return $Rc;
	
}


function AdjustValue ($ValueIn)
{
	if ($ValueIn < 0)
	{
		$ValueOut = 0;
	}
	else
	{
		$ValueOut = $ValueIn;
	}
	
	return ($ValueOut);
	
}
	
function WindCode2Descr ($Code)
{
   switch($Code)
   {
   case "N":
     $Descr = "Tramontana";
     break;
   
   case "NNE":
     $Descr = "Tramontana/Grecale";
     break;
   
   case "NE":
     $Descr = "Grecale";
     break;
     
   case "ENE":
     $Descr = "Grecale/Levante";
     break;
   
   case "E":
     $Descr = "Levante";
     break;
   
   case "ESE":
     $Descr = "Levante/Scirocco";
     break;
   
   case "SE":
     $Descr = "Scirocco";
     break;
     
   case "SSE":
     $Descr = "Scirocco/Ostro";
     break;
     
   case "S":
     $Descr = "Ostro";
     break;
   
   case "SSW":
     $Descr = "Ostro/Libeccio";
     break;
   
   case "SW":
     $Descr = "Libeccio";
     break;
     
   case "WSW":
     $Descr = "Libeccio/Ponente";
     break;  
   
   	case "W":
     $Descr = "Ponente";
     break;
   
   case "WNW":
     $Descr = "Ponente/Maestrale";
     break;
   
   case "NW":
     $Descr = "Maestrale";
     break;
     
   case "NNW":
     $Descr = "Maestrale/Tramontana";
     break;  
    
   default:
     $Descr = "???";
     break;
   }
   
   return $Descr;
   
 }
 
function OpenwheatermapCode2WorldweathernlineCode($CodeIn)
{
$TabCode = array();

$TabCode[200]["descr"] = "thunderstorm with light rain";
$TabCode[200]["image"] = "11d.png"; 
$TabCode[200]["code"]  = "263";

$TabCode[201]["descr"] = "thunderstorm with rain";   
$TabCode[201]["image"] = "11d.png";
$TabCode[201]["code"]  = "266";  

$TabCode[202]["descr"] = "thunderstorm with heavy rain";
$TabCode[202]["image"] = "11d.png";
$TabCode[202]["code"]  = "293";  

$TabCode[210]["descr"] = "light thunderstorm";   
$TabCode[210]["image"] = "11d.png";
$TabCode[210]["code"]  = "263";  

$TabCode[211]["descr"] = "thunderstorm";   
$TabCode[211]["image"] = "11d.png";
$TabCode[211]["code"]  = "386";  

$TabCode[212]["descr"] = "heavy thunderstorm";
$TabCode[212]["image"] = "11d.png";
$TabCode[212]["code"]  = "389";  
   
$TabCode[221]["descr"] = "ragged thunderstorm";
$TabCode[221]["image"] = "11d.png";
$TabCode[221]["code"]  = "389";  
   
$TabCode[230]["descr"] = "thunderstorm with light drizzle"; 
$TabCode[230]["image"] = "11d.png";
$TabCode[230]["code"]  = "200";  
  
$TabCode[231]["descr"] = "thunderstorm with drizzle";   
$TabCode[231]["image"] = "11d.png";
$TabCode[231]["code"]  = "386";  

$TabCode[232]["descr"] = "thunderstorm with heavy drizzle";
$TabCode[232]["image"] = "11d.png";
$TabCode[232]["code"]  = "389";  



$TabCode[300]["descr"] = "light intensity drizzle";
$TabCode[300]["image"] = "09d.png";
$TabCode[300]["code"]  = "263";  

$TabCode[301]["descr"] = "drizzle";
$TabCode[301]["image"] = "09d.png";
$TabCode[301]["code"]  = "266";  

$TabCode[302]["descr"] = "heavy intensity drizzle";
$TabCode[302]["image"] = "09d.png";
$TabCode[302]["code"]  = "293";  

$TabCode[310]["descr"] = "light intensity drizzle rain";
$TabCode[310]["image"] = "09d.png";
$TabCode[310]["code"]  = "296";  

$TabCode[311]["descr"] = "drizzle rain";
$TabCode[311]["image"] = "09d.png";
$TabCode[311]["code"]  = "302";  

$TabCode[312]["descr"] = "heavy intensity drizzle rain";
$TabCode[312]["image"] = "09d.png";
$TabCode[312]["code"]  = "305";  

$TabCode[313]["descr"] = "shower rain and drizzle";
$TabCode[313]["image"] = "09d.png";
$TabCode[313]["code"]  = "317";  

$TabCode[314]["descr"] = "heavy shower rain and drizzle";
$TabCode[314]["image"] = "09d.png";
$TabCode[314]["code"]  = "320";  

$TabCode[321]["descr"] = "shower drizzle";
$TabCode[321]["image"] = "09d.png";
$TabCode[321]["code"]  = "338";  



$TabCode[500]["descr"] = "light rain";
$TabCode[500]["image"] = "10d.png";
$TabCode[500]["code"]  = "263";  

$TabCode[501]["descr"] = "moderate rain";  
$TabCode[501]["image"] = "10d.png";    
$TabCode[501]["code"]  = "176";  

$TabCode[502]["descr"] = "heavy intensity rain"; 
$TabCode[502]["image"] = "10d.png";    
$TabCode[502]["code"]  = "266";  

$TabCode[503]["descr"] = "very heavy rain"; 
$TabCode[503]["image"] = "10d.png";    
$TabCode[503]["code"]  = "293";  

$TabCode[504]["descr"] = "extreme rain"; 
$TabCode[504]["image"] = "10d.png";    
$TabCode[504]["code"]  = "308";  

$TabCode[511]["descr"] = "freezing rain"; 
$TabCode[511]["image"] = "10d.png";    
$TabCode[511]["code"]  = "281";  

$TabCode[520]["descr"] = "light intensity shower rain"; 
$TabCode[520]["image"] = "10d.png";    
$TabCode[520]["code"]  = "263";  

$TabCode[521]["descr"] = "shower rain"; 
$TabCode[521]["image"] = "10d.png";    
$TabCode[521]["code"]  = "266";  

$TabCode[522]["descr"] = "heavy intensity shower rain"; 
$TabCode[522]["image"] = "10d.png";    
$TabCode[522]["code"]  = "293";  

$TabCode[531]["descr"] = "ragged shower rain"; 
$TabCode[531]["image"] = "10d.png";    
$TabCode[531]["code"]  = "296";  


$TabCode[600]["descr"] = "light snow";
$TabCode[600]["image"] = "13d.png";
$TabCode[600]["code"]  = "323";  

$TabCode[601]["descr"] = "snow";
$TabCode[601]["image"] = "13d.png";  
$TabCode[601]["code"]  = "326";  

$TabCode[602]["descr"] = "heavy snowv";
$TabCode[602]["image"] = "13d.png";  
$TabCode[602]["code"]  = "332";  

$TabCode[611]["descr"] = "sleet";
$TabCode[611]["image"] = "13d.png";  
$TabCode[611]["code"]  = "317";  

$TabCode[612]["descr"] = "shower sleet";
$TabCode[612]["image"] = "13d.png";  
$TabCode[612]["code"]  = "320";  

$TabCode[615]["descr"] = "light rain and snow";
$TabCode[615]["image"] = "13d.png";  
$TabCode[615]["code"]  = "362";  

$TabCode[616]["descr"] = "rain and snow";       
$TabCode[616]["image"] = "13d.png";  
$TabCode[616]["code"]  = "365";  

$TabCode[620]["descr"] = "light shower snow";
$TabCode[620]["image"] = "13d.png";  
$TabCode[620]["code"]  = "368";  

$TabCode[621]["descr"] = "shower snow";
$TabCode[621]["image"] = "13d.png";  
$TabCode[621]["code"]  = "332";  

$TabCode[622]["descr"] = "heavy shower snow";
$TabCode[622]["image"] = "13d.png";  
$TabCode[622]["code"]  = "338";  




$TabCode[701]["descr"] = "mist";
$TabCode[701]["image"] = "50d.png";  
$TabCode[701]["code"]  = "200";  

$TabCode[711]["descr"] = "smoke";
$TabCode[711]["image"] = "50d.png";
$TabCode[711]["code"]  = "248";    

$TabCode[721]["descr"] = "haze";
$TabCode[721]["image"] = "50d.png";  
$TabCode[721]["code"]  = "143";  

$TabCode[731]["descr"] = "Sand/Dust Whirls";
$TabCode[731]["image"] = "50d.png";  
$TabCode[731]["code"]  = "143";  

$TabCode[741]["descr"] = "Fog";
$TabCode[741]["image"] = "50d.png"; 
$TabCode[741]["code"]  = "248";   

$TabCode[751]["descr"] = "sand";
$TabCode[751]["image"] = "50d.png"; 
$TabCode[751]["code"]  = "143";  

$TabCode[761]["descr"] = "dust";
$TabCode[761]["image"] = "50d.png"; 
$TabCode[761]["code"]  = "143";  

$TabCode[762]["descr"] = "VOLCANIC ASH";
$TabCode[762]["image"] = "50d.png"; 
$TabCode[762]["code"]  = "";  

$TabCode[771]["descr"] = "SQUALLS";
$TabCode[771]["image"] = "50d.png"; 
$TabCode[771]["code"]  = "389";  

$TabCode[781]["descr"] = "TORNADO";
$TabCode[781]["image"] = "50d.png"; 
$TabCode[781]["code"]  = "";  




$TabCode[800]["descr"] = "sky is clear";  // 01n.png 
$TabCode[800]["image"] = "01d.png"; 
$TabCode[800]["code"]  = "113";  

$TabCode[801]["descr"] = "few clouds";  // 02n.png
$TabCode[801]["image"] = "02d.png"; 
$TabCode[801]["code"]  = "116";  

$TabCode[802]["descr"] = "scattered clouds";  // 03d.png
$TabCode[802]["image"] = "03d.png"; 
$TabCode[802]["code"]  = "119";  

$TabCode[803]["descr"] = "broken clouds";  // 03d.png
$TabCode[803]["image"] = "04d.png"; 
$TabCode[803]["code"]  = "119";  

$TabCode[804]["descr"] = "overcast clouds";  // 04d.png
$TabCode[804]["image"] = "04d.png"; 
$TabCode[804]["code"]  = "122";  



$TabCode[900]["descr"] = "tornado";
$TabCode[900]["image"] = "";   
$TabCode[900]["code"]  = "";  

$TabCode[901]["descr"] = "tropical storm";
$TabCode[901]["image"] = "";
$TabCode[901]["code"]  = "";  

$TabCode[902]["descr"] = "hurricane";
$TabCode[902]["image"] = "";
$TabCode[902]["code"]  = "";  

$TabCode[903]["descr"] = "cold";
$TabCode[903]["image"] = "";     
$TabCode[903]["code"]  = "";   

$TabCode[904]["descr"] = "hot";
$TabCode[904]["image"] = "";
$TabCode[904]["code"]  = "";  

$TabCode[905]["descr"] = "windy";
$TabCode[905]["image"] = "";
$TabCode[905]["code"]  = "";  

$TabCode[906]["descr"] = "hail";
$TabCode[906]["image"] = "";
$TabCode[906]["code"]  = "";  



$TabCode[950]["descr"] = "Setting";
$TabCode[950]["image"] = "";   
$TabCode[950]["code"]  = "";  

$TabCode[951]["descr"] = "Calm";
$TabCode[951]["image"] = "";   
$TabCode[951]["code"]  = "";  

$TabCode[952]["descr"] = "Light breeze";
$TabCode[952]["image"] = "";   
$TabCode[952]["code"]  = "";  

$TabCode[953]["descr"] = "Gentle Breeze";
$TabCode[953]["image"] = "";   
$TabCode[953]["code"]  = "";  

$TabCode[954]["descr"] = "Moderate breeze";
$TabCode[954]["image"] = "";   
$TabCode[954]["code"]  = "";  

$TabCode[955]["descr"] = "Fresh Breeze";
$TabCode[955]["image"] = "";   
$TabCode[955]["code"]  = "";  

$TabCode[956]["descr"] = "Strong breeze";
$TabCode[956]["image"] = "";   
$TabCode[956]["code"]  = "";                                  

$TabCode[957]["descr"] = "High wind, near gale";
$TabCode[957]["image"] = "";   
$TabCode[957]["code"]  = "";  

$TabCode[958]["descr"] = "Gale";
$TabCode[958]["image"] = "";  
$TabCode[958]["code"]  = "";   

$TabCode[959]["descr"] = "Severe Gale";
$TabCode[959]["image"] = "";  
$TabCode[959]["code"]  = "";   

$TabCode[960]["descr"] = "Storm";
$TabCode[960]["image"] = ""; 
$TabCode[960]["code"]  = "";    

$TabCode[961]["descr"] = "Violent Storm";
$TabCode[961]["image"] = "";   
$TabCode[961]["code"]  = "";  

$TabCode[962]["descr"] = "Hurricane"; 
$TabCode[962]["image"] = ""; 
$TabCode[962]["code"]  = "";    

  //$CodeIn = 999999;
  if (isset($TabCode[$CodeIn]["code"]) == True)
  {
		$CodeOut = $TabCode[$CodeIn]["code"];
	}
	else
	{
		$CodeOut = "???";
		
		$to       = "fishwolf@gmail.com";
  	$subject  = "Codice Errato";
  	$message  = "Codice=".$CodeIn;
  	$headers  = 'From:  noreplay@meteospot.it' . "\r\n" .
   	            'Reply-To: noreplay@meteospot.it' . "\r\n" .
    	          'X-Mailer: PHP/' . phpversion();
  	mail($to, $subject, $message, $headers);
	}
	
	//echo "CodeOut=".$CodeOut.$CR;
	
	return $CodeOut;
}

//---------------------------------------------------------------------------------------------------------------- 
//
//----------------------------------------------------------------------------------------------------------------  

function CalculateDistance($lat1, $lon1, $lat2, $lon2, $Unit)
{
  //echo "lat=".$lat1."<br>";
  //echo "lon1=".$lon1."<br>";
  //echo "lat2=".$lat2."<br>";
  //echo "lon2=".$lon2."<br>";
  // Formula for calculating distances
  // from latitude and longitude.
  $dist   = acos(sin(deg2rad($lat1))
            * sin(deg2rad($lat2))
            + cos(deg2rad($lat1))
            * cos(deg2rad($lat2))
            * cos(deg2rad($lon1 - $lon2)));

  $dist   = rad2deg($dist);
     
  $miles  = (float) $dist * 69;

  // To get kilometers, multiply miles by 1.61
  $km     = (float) $miles * 1.61;

  // This is all displaying functionality
  //$display  = sprintf("%0.2f",$miles).' miles' ;
  //$display .= ' ('.sprintf("%0.2f",$km).' kilometers)' ;
 
  $Distance = 0;
  if ($Unit == "Km")
  {
    $Distance = sprintf("%0.1f",$km);
  } 
  if ($Unit == "Miles")
  {
    $Distance = sprintf("%0.2f",$miles);
  }
  
  //echo "Distance=".$Distance."<br>";
  //exit();
  return $Distance ;
}       
 
?>