<?php

// D1 daily-images — use D1 for all cameras, fallback to files.txt on failure
@include_once('/home/subdomains/livetimelapse/public_html/php/api/daily-images-helper.php');

if (!function_exists('_getFileListForDay')) {
    function _getFileListForDay($cam, $year, $month, $day, $fallbackPath) {
        if (function_exists('dailyImagesGetFileList')) {
            $d1Name = str_replace('_', '-', $cam);
            $d1Date = "$year-$month-$day";
            $d1Result = dailyImagesGetFileList($d1Name, $d1Date, 'web');
            if ($d1Result !== false) {
                $ftResult = @file("$fallbackPath", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                if ($ftResult !== false && count($ftResult) > count($d1Result) + 5) {
                    return $ftResult;
                }
                return $d1Result;
            }
        }
        return @file("$fallbackPath");
    }
}
/////////////////////////////////////////////////////////////////////////
//////////////   QUERY STRING VARIABLES   ///////////////////////////////
/////////////////////////////////////////////////////////////////////////

ini_set('display_errors', '0');

// How many thumbnails displayed per page?
$per_page = $_GET['pp'];

// Which page is being displayed?
$page_number = $_GET['pn'];

// Has the latest image been requested?
$latest_image = $_GET['latest_image'];

// Get daily and project variables
$last2hours = $_GET['last2hours'];
$today = $_GET['today'];
$yesterday = $_GET['yesterday'];

//Get custom time period variables if they exist
$start_year = $_GET['s1y'];
$start_month = $_GET['s1m'];
$start_day = check_month_days($start_month, $_GET['s1d']);
$start_time = $_GET['s1t'];

$stop_year = $_GET['s2y'];    
$stop_month = $_GET['s2m'];    
$stop_day = check_month_days($stop_month, $_GET['s2d']);
$stop_time = $_GET['s2t'];

// Are we saving a timelapse sequence?
$save_timelapse = $_GET['save_timelapse'];

// Get users IP address
$ip_address = $_SERVER['REMOTE_ADDR'];
$remote_ip = file_get_contents("/home/subdomains/livetimelapse/public_html/remote_ip.txt");

// Defaults if not set above
if (!$per_page) { $per_page = '20'; }
if (!$page_number) { $page_number = '1'; }

/////////////////////////////////////////////////////////////////////////
//////////////   ASSORED VARIABLES   ////////////////////////////////////
/////////////////////////////////////////////////////////////////////////

$cache = rand(0,10000);
$timeLapseImageSize = '980x655';
$displayImageSize = '980x655';
  
if ($cam == 'sec_surfair_sec1')
  {
  $timeLapseImageSize = '.jpg';
  $displayImageSize = '980x655';
  $last2hours = "on";
  $newS3 = TRUE;
  date_default_timezone_set("Australia/Brisbane");
  }
  
if ($cam == 'tlc_cityofgoldcoast_palmbeach')
  {
  $timeLapseImageSize = '.jpg';
  $displayImageSize = '980x655';
  $last2hours = "on";
  $newS3 = TRUE;
  date_default_timezone_set("Australia/Brisbane");
  }
  
////////////////////////////////////////////////////////////////////////
//////////////   FUNCTION LIST            ///////////////////////////////
/////////////////////////////////////////////////////////////////////////

function get_images($cam, $date, $start_time_unix, $stop_time_unix)
  {
  global $basedir;
  global $basedir_archive;
  global $archived_images_thumbs;
  global $archived_images_full;

  global $project_start_date;
  global $project_start_hour;
  global $project_start_min;
  global $project_start_ampm;
  
  global $project_stop_hour;
  global $project_stop_min;
  global $project_stop_ampm;
  
  global $last2hours;
  global $today;
  global $yesterday;
  global $project;
  
  global $timeLapseImageSize;
  
  if ($cam == 'tlc_wilson_park_zoom') { $cam = 'tlc_wilson_park'; }

  $start_date = date('Ymd', $start_time_unix);
  $stop_date = date('Ymd', $stop_time_unix);

  $directories = Array();  
  $a = 0;
  $working_date = $start_date;

  while ($working_date <= $stop_date)
    {
    $directories[$a] = "{$basedir_archive}/{$cam}/".substr($working_date,0,4)."/".substr($working_date,4,2)."/".substr($working_date,6,2)."";
    $dates[$a] = $working_date; // Add to master dates array
    $working_date = date('Ymd', (strtotime($working_date) + 86400));
    $a++;
    if ($a == 1000) { break; }
    }

  $c = 0;
  
  
  for ($b = 0; $b < sizeof($directories); $b++)
    {
    if ($last2hours == 'on')
      {      
      // If no start and stop details exist in the query string, use a default as below   
      $current_time = time();
      $current_date = date('Ymd');
      $relative_project_start = strtotime("$current_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
      $relative_project_stop = strtotime("$current_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");  
  
      // If outside of the cameras operating hours, display the last hour of images
      if (($current_time > $relative_project_stop || $current_time < $relative_project_start))
        {
        if ($current_time > $relative_project_stop)
          {
          $start_hour = $relative_project_stop - 7200;
          $stop_hour = $relative_project_stop;
          }
        else
          {
          $start_hour =  $relative_project_stop - 93600;
          $stop_hour =  $relative_project_stop - 86400;
          }      
        }
      else
        {
        $start_hour = $start_time_unix;;
        $stop_hour = $stop_time_unix;
        }
      }
    elseif ($today == 'on' || $yesterday == 'on' || $project == 'on')
      {
      $start_hour = strtotime("{$dates[$b]}, {$project_start_hour}:{$project_start_min}$project_start_ampm");
      $stop_hour = strtotime("{$dates[$b]}, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
      }
    else
      {
      $days = sizeof($directories);
      $current_time = time();
      $current_date = date('Ymd');
      $relative_project_start = strtotime("$current_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
      $relative_project_stop = strtotime("$current_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
      
      // For single day sequences             
      if ($days == 1) 
        {
        // Use the start and stop time selected
        $start_hour = $start_time_unix;
        $stop_hour = $stop_time_unix;
        }
      // For sequences spanning multiple days
      else
        {
        // If day 1 of the squence
        if ($b == 0)
          {
          // Honour the start time selected.  Use project relative stop time
          $start_hour = $start_time_unix;
          $stop_hour = strtotime("{$dates[$b]}, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
          }
        // If it's the last day in the sequence
        elseif ($b == ($days-1))
          {
          // Use project relative start but honour the selected stop hour
          $start_hour = strtotime("{$dates[$b]}, {$project_start_hour}:{$project_start_min}$project_start_ampm");  
          $stop_hour = $stop_time_unix;
          }
        // For all other days
        else
          {
          // Use project relative start and stop hours
          $start_hour = strtotime("{$dates[$b]}, {$project_start_hour}:{$project_start_min}$project_start_ampm");  
          $stop_hour = strtotime("{$dates[$b]}, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");          
          }
        }
      }   
        
    $current_year = substr($dates[$b], 0, 4);
    $current_month = substr($dates[$b], 4, 2);
    $current_day = substr($dates[$b], 6, 2);    
        
    $current_file_list = _getFileListForDay($cam, $current_year, $current_month, $current_day, "{$basedir_archive}/$cam/$current_year/$current_month/$current_day/files.txt");
        
    if ($_GET['ben'] == 'yes') print_r($directories);
    for ($c = 0; $c < sizeof($current_file_list); $c++)
      {         
      $current_file_list[$c] = trim($current_file_list[$c]);
      
      
      
      if (strstr($current_file_list[$c], $timeLapseImageSize))
        {
        $check = str_replace("{$timeLapseImageSize}_", '', $current_file_list[$c]);
        $check = str_replace("{$dates[$b]}_", '', $current_file_list[$c]);
        $check = str_replace('.jpg', '', $check);            
        $current_image_time = strtotime("{$dates[$b]}, $check");

        if ($current_image_time > $start_hour && $current_image_time < $stop_hour)
          {
          $archived_images[] = "$current_year/$current_month/$current_day/".trim($current_file_list[$c]);
          } 
        }
      }    
    }
      
  if ($cam == 'tlc_total_construction_chippendalea') {
    for ($a = 0; $a < sizeof($archived_images); $a = $a + 6) {
      $newArchived[] = $archived_images[$a];
    } 
    $archived_images = $newArchived;
  }  
      
  @sort($archived_images);

return $archived_images;

}

function get_project_images($cam)
  {
  global $archivedir;
  global $basedir_archive;
  global $basedir;

  global $project_start_time_unix;
  global $project_stop_time_unix;
  
  global $project_start_hour;
  global $project_start_min;
  global $project_start_ampm;
  
  global $project_stop_hour;
  global $project_stop_min;
  global $project_stop_ampm;
  
  global $project_images_per_day;
  global $project_limit_start_hour;
  global $project_limit_start_min;
  global $project_limit_start_ampm;
  global $project_limit_stop_hour;
  global $project_limit_stop_min;
  global $project_limit_stop_ampm;
  
  global $timeLapseImageSize;
  
  if ($cam == 'tlc_wilson_park_zoom') { $cam = 'tlc_wilson_park'; }

  $start_date = date('Ymd', $project_start_time_unix);
  $stop_date = date('Ymd', $project_stop_time_unix);
  $current_date = date('Ymd', time()+86400);
  $current_date_unix = time();
  
  $directories = Array();  
  $a = 0;
  $working_date = $project_start_time_unix;

  while (($working_date <= $project_stop_time_unix) && ($working_date < $current_date_unix))
    {
    $directories[$a] = "{$basedir_archive}/{$cam}/".date("Y", $working_date)."/".date("m", $working_date)."/".date("d", $working_date);
    $dates[$a] = date("Ymd", $working_date); // Add to master dates array
    $working_date = $working_date + 86400;
    $a++;
    if ($a == 1000) { break; }
    }
    
  //if ($cam == 'tlc_wilson_park') { print_r($directories); }
 
 $pacificFairFilter = Array(
  'test',
  '20140125',
  '20140203',
  '20140214',
  '20140215',
  '20140222',
  '20140303',
  '20140317',
  '20140318',
  '20140319',
  '20140320',
  '20140321',
  '20140322',
  '20140323',
  '20140324',
  '20140325',
  '20140326',
  '20140327',
  '20140328',
  '20140329',
  '20140330',
  '20140331',
  '20140401',
  '20140402',
  '20140403',
  '20140404',
  '20140405',
  '20140531',
  '20140605',
  '20140613',
  '20140614', 
  '20140715',
  '20140716',    
  '20140726', 
  '20140816',
  '20140822',
  '20140823',
  '20140907',
  '20140908',
  '20141002',
  '20141009',
  '20141018',
  '20141101',
  '20141102',
  '20141103',
  '20141113',
  '20141116',
  '20141118',
  '20141119',
  '20140125'
 );
 
  for ($b = 0; $b < sizeof($directories); $b++)
    {
    if ($project_limit_start_hour) {
      $start_hour = strtotime("{$dates[$b]}, {$project_limit_start_hour}:{$project_limit_start_min}$project_limit_start_ampm");
      $stop_hour = strtotime("{$dates[$b]}, {$project_limit_stop_hour}:{$project_limit_stop_min}$project_limit_stop_ampm");      
    } else {      
      $start_hour = strtotime("{$dates[$b]}, {$project_start_hour}:{$project_start_min}$project_start_ampm");
      $stop_hour = strtotime("{$dates[$b]}, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
    }
   
    $current_year = substr($dates[$b], 0, 4);
    $current_month = substr($dates[$b], 4, 2);
    $current_day = substr($dates[$b], 6, 2);    
    
    $current_list = _getFileListForDay($cam, $current_year, $current_month, $current_day, "{$directories[$b]}/files.txt");

    // Filter the file list.  We only want 640x480 images between the project start and stop times
    for ($a = 0; $a < sizeof($current_list); $a++)
      {
      if (strstr($current_list[$a], $timeLapseImageSize))
        {
        $check = str_replace("{$timeLapseImageSize}_", '', $current_list[$a]);
        $check = str_replace('.jpg', '', $check);            
        $current_image_time = strtotime("{$dates[$b]}, $check");

        if (($current_image_time > $start_hour) && ($current_image_time < $stop_hour))
          {
          if (!array_search("$current_year$current_month$current_day", $pacificFairFilter)) {
            $filtered_list[$b][] = "{$cam}/$current_year/$current_month/$current_day/".trim($current_list[$a]);
          }
          }
        }
      }          

    $forward_skip = round(sizeof($filtered_list[$b]) / $project_images_per_day);
    if ($forward_skip <= 0) { $forward_skip = 1; }

    if ($forward_skip > 0)
      {
      $a = 0;
      while ($filtered_list[$b][$a])
        {
        $final_list[] = $filtered_list[$b][$a];
        $a = $a + $forward_skip;
        }
      }

    }   


 sort($final_list);

return $final_list;

}

function check_month_days($month, $day)
  {
  if ($month == 'jan' && $day > 31) { return 31; }
  if ($month == 'feb' && $day > 28) { return 28; }
  if ($month == 'mar' && $day > 31) { return 31; }
  if ($month == 'apr' && $day > 30) { return 30; }
  if ($month == 'may' && $day > 31) { return 31; }
  if ($month == 'jun' && $day > 30) { return 30; }
  if ($month == 'jul' && $day > 31) { return 31; }
  if ($month == 'aug' && $day > 31) { return 31; }
  if ($month == 'sep' && $day > 30) { return 30; }
  if ($month == 'oct' && $day > 31) { return 31; }
  if ($month == 'nov' && $day > 30) { return 30; }
  if ($month == 'dec' && $day > 31) { return 31; }
  else { return $day; }
  }
  
function round_time($time, $mode, $nearest)
  {
  if ($mode == 'up')
    {
    if ($nearest == 10)
      {
      $time_values = '|00|,|10|,|20|,|30|,|40|,|50|';
      
      $a = 0;
      $current_minutes = date("i", $time);
      while (strstr($time_values, "|$current_minutes|") == FALSE)
        {
        $current_minutes = date("i", $time);
        $time = $time+30;
        $a++;
        if ($a == 20) { break; }
        }      
      }  
    }
 if ($mode == 'down')
    {
    if ($nearest == 10)
      {
      $time_values = '|00|,|10|,|20|,|30|,|40|,|50|';
      
      $a = 0;
      $current_minutes = date("i", $time);
      while (strstr($time_values, "|$current_minutes|") == FALSE)
        {
        $current_minutes = date("i", $time);
        $time = $time-30;
        $a++;
        if ($a == 20) { break; }
        }      
      }  
    }
  return $time;
}

/////////////////////////////////////////////////////////////////////////
//////////////   BEGIN MAIN SCRIPT        ///////////////////////////////
/////////////////////////////////////////////////////////////////////////

if ($last2hours == 'on' || $today == 'on' || $yesterday == 'on' || $project == 'on')
  {    
  ///////////////////////////////
  // PRE-DEFINED TIME PERIODS ///
  ///////////////////////////////
  
  if ($last2hours == 'on')
    {   
    $loop_speed = '120';
    $start_time_unix = time()-7200;
    $stop_time_unix = time();

    // If no start and stop details exist in the query string, use a default as below   
    $current_time = time();
    $current_date = date("Ymd");
    $yesterdays_date = date("Ymd",time()-86400);
    $relative_project_start = strtotime("$current_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
    $relative_project_stop = strtotime("$current_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
    
    // If outside of the cameras operating hours, display the last hour of images
    if (($current_time > $relative_project_stop || $current_time < $relative_project_start))
      {
      if ($current_time > $relative_project_stop)
        {
        $relative_project_start = strtotime("$current_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
        $relative_project_stop = strtotime("$current_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");  
        $start_time_unix = $relative_project_stop - 7200;
        $stop_time_unix = $relative_project_stop;
        }
      else
        {
        $relative_project_start = strtotime("$yesterdays_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
        $relative_project_stop = strtotime("$yesterdays_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");  
        $start_time_unix =  $relative_project_stop - 3600;
        $stop_time_unix =  $relative_project_stop;
        }      
      }
      
    // If the start time is before the actual start time of the project for the current day
    if ($start_time_unix < $relative_project_start) { $start_time_unix = $relative_project_start; }
    }  
  elseif ($today == 'on')
    {
    $loop_speed = '120';
    $today_date = date("Ymd");      
    $start_time_unix = strtotime("$today_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
    $stop_time_unix = strtotime("$today_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
    }
  elseif ($yesterday == 'on')
    {
    $loop_speed = '120';
    $yesterday_date = date("Ymd", time()-86400);      
    $start_time_unix = strtotime("$yesterday_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
    $stop_time_unix = strtotime("$yesterday_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
    }
  elseif ($project == 'on')
    {
    $loop_speed = '120';
    $today_date = date("Ymd");      
    $start_time_unix = strtotime("$project_start_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
    $stop_time_unix = strtotime("$today_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");
    }
    
  $animation = 'yes';
  
  // We still need these variables to have the time options selected
  $start_time_unix = round_time($start_time_unix, 'down', '10');
  $start_year = date("Y", $start_time_unix);
  $start_month = strtolower(date("M", $start_time_unix));
  $start_day = date("d", $start_time_unix);
  $start_time = date("Hi", $start_time_unix);
  
  $stop_time_unix = round_time($stop_time_unix, 'up', '10');
  $stop_year = date("Y", $stop_time_unix);
  $stop_month = strtolower(date("M", $stop_time_unix));
  $stop_day = date("d", $stop_time_unix);
  $stop_time = date("Hi", $stop_time_unix);
  }
elseif ($_GET['s1y'] && $_GET['s2y'])
  {  

  ///////////////////////////////
  // CUSTOM TIME PERIOD       ///
  ///////////////////////////////
  
  // Assorted Variables
  $loop_speed = '120';
    $animation = 'yes';
    
  //If the start and stop details exist from the query string, use them
  if ($start_year && $stop_year)
    {
    $start_time_unix = strtotime("$start_month $start_day,$start_year, $start_time");    
    $stop_time_unix = strtotime("$stop_month $stop_day, $stop_year, $stop_time");
    }
  else
    {
    // If no start and stop details exist in the query string, use a default as below   
    $current_time = time(); 
    $current_date = date("Ymd");
    $relative_project_start = strtotime("$current_date, {$project_start_hour}:{$project_start_min}$project_start_ampm");
    $relative_project_stop = strtotime("$current_date, {$project_stop_hour}:{$project_stop_min}$project_stop_ampm");  
  
    // If outside of the cameras operating hours, display the last hour of images
    if (($current_time > $relative_project_stop || $current_time < $relative_project_start))
      {
      if ($current_time > $relative_project_stop)
        {
        $start_time_unix = $relative_project_stop - 3600;
        $stop_time_unix = $relative_project_stop;
        }
      else
        {
        $start_time_unix =  $relative_project_stop - 90000;
        $stop_time_unix =  $relative_project_stop - 86400;
        }      
      }
    // Otherwise, default to the previous hours worth of images
    else
      {
      $start_time_unix = time()-3600;
      $stop_time_unix = time();
      }  
    }    
  
  // We still need these variables to have the time options selected
  $start_time_unix = round_time($start_time_unix, 'down', '10');
  $start_year = date("Y", $start_time_unix);
  $start_month = strtolower(date("M", $start_time_unix));
  $start_day = date("d", $start_time_unix);
  $start_time = date("Hi", $start_time_unix);
  
  $stop_time_unix = round_time($stop_time_unix, 'up', '10');
  $stop_year = date("Y", $stop_time_unix);
  $stop_month = strtolower(date("M", $stop_time_unix));
  $stop_day = date("d", $stop_time_unix);
  $stop_time = date("Hi", $stop_time_unix);
  
  }
else
  {
  // This is to show a default time selection for the custom time period
  $start_time_unix = round_time($start_time_unix, 'down', '10');
  $start_time_unix = time()-3600;
  $start_year = date("Y", $start_time_unix);
  $start_month = strtolower(date("M", $start_time_unix));
  $start_day = date("d", $start_time_unix);
  $start_time = date("Hi", $start_time_unix);
  
  $stop_time_unix = round_time($stop_time_unix, 'up', '10');
  $stop_time_unix = time();
  $stop_year = date("Y", $stop_time_unix);
  $stop_month = strtolower(date("M", $stop_time_unix));
  $stop_day = date("d", $stop_time_unix);
  $stop_time = date("Hi", $stop_time_unix);  
  
  }

// Creat the archived image list
if ($start_time_unix > $stop_time_unix)
  {
  $error = 'yes';
  }
elseif ($project == 'on')
  {
  $image_list = get_project_images($cam);
  }
else
  {
  $image_list = get_images($cam, $date, $start_time_unix, $stop_time_unix);
  }
  
  
$total_images = sizeof($image_list);
$animation_start_screen = date("g:ia, F j", $start_time_unix);
$animation_stop_screen = date("g:ia, F j", $stop_time_unix);


/////////////////////////////////////////////////////////////////////////
//////////////   START BROWSER OUTPUT       /////////////////////////////
/////////////////////////////////////////////////////////////////////////
   
?>

<script type="text/javascript"> 

<?php

$basedir_archive_www ='https://legacy.livetimelapse.com.au/www/archive_timelapse';

if ($animation == 'yes')
  {
    
  if ($newS3) {
    $bucketName = str_replace("_", "-", $cam);
  } else {
    $bucketName = $cam;
  }
  
  echo '
  webcam_images = new Array();
  webcam_images_display = new Array();
  image_status = new Array();
  ';
  
  for ($a = 0; $a < sizeof($image_list); $a++)
    {
    if (strstr($cam, 'sec')) {
      echo "webcam_images[$a] = \"https://s3.amazonaws.com/$bucketName/{$image_list[$a]}\";\r\n";
    } else {
      echo "webcam_images[$a] = \"https://s3.amazonaws.com/$bucketName/$cam/{$image_list[$a]}\";\r\n";
    }
    }
      
  echo "\r\n";
  
  $nimages = sizeof($image_list);
  $scrollbarimages = sizeof($image_list);
     
  echo "nImages = $nimages;\r\n";
  }

?>

function loop_mode_decide()
  {
  if (play_status == 'play')
    {
    stop();
    }
  else if (play_status == 'stop')
    {
    fwd();
    }  
  }
  
function nav()
   {
   var w = document.webcams.cams.selectedIndex;
   var url_add = document.webcams.cams.options[w].value;
   window.location.href = url_add;
   }
   
function select_event()
   {
   var w = document.custom_time_period.events.selectedIndex;
   var url_add = document.custom_time_period.events.options[w].value;
   window.location.href = url_add;
   }
  
</script>
<script>
  
<!--
 
<!-- IDR.loop.v02b.html --> 
<!-- html for Radar Loops plus cursor Pointer & Origin code.--> 
<!-- It assumes the appropriate JavaScript has already been loaded.--> 
<!-- v01 001208 Clive Edington, new layout. c.f. IDR.loop.v01.js --> 
<!-- Thanks to Alf West and the Radar Section for the original code.--> 
<!-- ASW version by Michael Bath and Ben Quinn 20010112 (severeweather.asn.au) --> 
<!-- Chops Version modified by chops (Michael Fewings) 20031121 (radar.strikeone.net.au) --> 
<!-- Modified by Ben Quinn 20060515 (bsch.au.com) --> 
<!-- Further modified by Ben Quinn 200110615 for the Australian Weathercam Network (webcams.bsch.com.au) --> 

  isMS = false; 
  isNN = false; 
  isNN6 = false; 
  isCursor = false; 
  var d = window.document; 
  if (navigator.appName.indexOf("Microsoft") != -1) { 
    if (parseFloat(navigator.appVersion) >= 4.) isMS = true; 
  }   
  if (navigator.appName.indexOf("Netscape") != -1) { 
    // Netscape 6 reports v5 !!! 
    if  ( (parseFloat(navigator.appVersion) >= 4.) && (parseFloat(navigator.appVersion) < 5.) ) isNN = true; 
    if  ( (parseFloat(navigator.appVersion) >= 5.) && (parseFloat(navigator.appVersion) < 6.) ) isNN6 = true; 
  }   

if (nImages>0) { 
  var doc; // Holds a pointer to MS or NN document (see launch). 
  
// Now the general Looping code. 
// 
//============================================================ 
//                >> jsImagePlayer 1.0 << 
//            for Netscape3.0+, September 1996 
//============================================================ 
//                  by (c)BASTaRT 1996 
//             Praha, Czech Republic, Europe 
// 
// feel free to copy and use as long as the credits are given 
//          by having this header in the code 
// 
//          contact: xholecko@sgi.felk.cvut.cz 
//          http://sgi.felk.cvut.cz/~xholecko 
// 
//============================================================ 
// Thanx to Karel & Martin for beta testing and suggestions! 
//============================================================ 
// 
//     modified by D. Watson and A. Earnhart (CIRA/CSU), 7/30/97 
//     and Greg Thompson (NCAR/RAP) Dec. 11 1997 

// First image 
first_image = 0; 

// Last image 
last_image = nImages-1; 

// Global Variables
webcam_number = 1; 
nDl = 100; 
dL = nDl;         //dL between frames in 1/100 seconds 
dMx = 600; 
dMn = 20; 
dSt = 25; 
sSt = 25; 
dSt = Math.floor((dMx - dMn )/ sSt); 
tCs = sSt-Math.floor(dL/dSt); 
dwm = 3; 
dws = 1; 
eDM   = 6; 
sDM = dwm - 1; 
current_image = first_image;     //number of the current image 
timeID = null; 
loop_status = 0;                      // 0-stopped, 1-playing 
play_mode = 'normal';                   // 0-normal, 1-loop, 2-sweep 
size_valid = 0; 
doc = document; 

var preload_counter = 0;
var total_images = nImages;

  // If the browser is netscape navigator 
  if (isNN) doc = document.animationlayer.document;
  
}  // (end of if there are images to loop) 
 
 
function preload_monitor()
  {
  
  var still_loading = false;

  for (b = 0; b < nImages; b++)
    {
    if (image_status[b] !== 'complete')
      {
      if (webcam_images[b].search(".jpg"))
        {
        still_loading = true;
        if (webcam_images_display[b].complete == true)
          {
          image_status[b] = 'complete';
          preload_counter++;
          percentage = preload_counter / total_images * 100;
          percentage = Math.round(percentage);
          document.getElementById("progress_text").innerHTML = "Downloading Image " + preload_counter + " of " + total_images + " (" + percentage + "%)";
          document.getElementById('progress_bar').style.width = percentage+'%';
          }
        }
      else
        {
        // Not an image so mark it as complete so it doesn't stall the preloader
        image_status[b] = 'complete';
        }
      }
    }

 
  if (still_loading === true)
    {
    preload_monitor_id = setTimeout("preload_monitor()", 5);
    }
  else
    {
    document.getElementById("progress_text").style.color = '#000000';
    final_text = document.getElementById("finished_text").value;
    document.getElementById("progress_text").innerHTML = final_text;
    document.getElementById("progress_text").style.color = 'white';
    }  

}
  
  
function empty()
{

}

// Load and initialize everything once page is downloaded (called from 'onLoad' in <BODY>) 
function launch() 
  { 
  
  // If there are no images to display, cancel the launch 
  if (nImages==0)  return; 
  
  doc = document; 
  
  // If the browser is netscape navigator 
  if (isNN) doc = document.animationlayer.document; 
  
  // Set the image counter to 0 
  current_image = 0; 
  
  // Cycle through the webcams and initiate the images from each camera (this initiates all images)
  for (image_number = 0; image_number < nImages; image_number++)
    {
    webcam_images_display[image_number] = new Image(); 
    webcam_images_display[image_number].src = webcam_images[image_number];        
    image_status[image_number] = 'loading';
    } 
    
  // Now display them   
  display_current_image(); 
  
  // If there's only one image there's no need to continue the script
  if (nImages==1) 
    {
    return;
    }
  
  // Reset the current_image counter to the first image 
  current_image = first_image; 
  
  // This needs to be done to set the right mode when the page is manually reloaded 
  change_mode('loop');
  play_status = 'play'; 
  fwd();
  preload_monitor(); 
} 
  
  
function display_slider() 
{ 
    stop(); 
    current_image = document.control_form.frame_nr.value-1; 
    display_current_image(); 
} 



function display_current_image() 
  { 

  // Display the webcam images onto screen - cycle through the webcam_images_display array
  if (document.getElementById('timelapseimage').src != webcam_images_display[current_image].src) { 
  
    document.getElementById('timelapseimage').src = webcam_images_display[current_image].src;
  
    if (document.getElementById('deleteImage')) {
      document.getElementById('deleteImage').href = 'https://php.livetimelapse.com.au/delete.photo.php?photo=' + webcam_images_display[current_image].src;
    }
  } 

  current_image_actual = current_image+1;
  //document.getElementById("current_sequence_time").innerHTML = main_times_array[current_image];

  //if (current_image_actual == 1) { document.getElementById("time_slider_position").style.left = '0%'; }
  //else if (current_image_actual == nImages) { document.getElementById("time_slider_position").style.left = '99%'; }
  //else { document.getElementById("time_slider_position").style.left = Math.round(current_image_actual/nImages*100)+'%'; }

  //document.getElementById(webcamname + '_image_time').innerHTML = webcam_images_times[webcam_number][current_image];
  //document.getElementById(webcamname + '_full_resolution').href = webcam_images_display[webcam_number][current_image].src.replace('thumbs/185x138_', '');

} 
  
// Stop the animation 
function stop() 
  { 
  // Cancel animation (timeID holds the expression which calls the fwd or bkwd function) 
  if (loop_status == 1) { 
    clearTimeout (timeID); 
  } 
  loop_status = 0;
  play_status = 'stop';
  return; 
} 

// Display animation in fwd direction in either loop or sweep mode 
function animate_fwd() 
  { 
  // If there's only 1 image or less, do nothing.  The return here terminates the function. 
  if (nImages<=1) return; 
  
  // Otherwise, increment the current_image counter 
  current_image++; 

  // Check if current image has exceeded loop bound 
  if (current_image > last_image) 
    { 
    if (play_mode == 'loop') 
      { 
      // Fwd loop mode - skip to first image 
      current_image = first_image; 
      } 
    if (play_mode == 'sweep') 
      { 
      //sweep mode - change directions (go bkwd) 
      current_image = last_image; 
      animate_rev(); 
      return; 
      } 
    } 
    
  // Display the current image on screen
  if (check_next_image_status())
    {
    display_current_image();
    } 
    
  delay_timeout = dL; 
  
  if (current_image == first_image) { delay_timeout = sDM*dL; } 
  if (current_image == last_image) { delay_timeout =   eDM*dL; } 
  
  // call "animate_fwd()" again after a set time (delay_timeout) has elapsed == 
  timeID = setTimeout("animate_fwd()", delay_timeout);
  
    play_stutus = 'play'; 
}
                                                                                                                                                                            
function check_next_image_status()     
  {

  var test;

  if (webcam_images_display[current_image].complete === false) 
    {
    test = true;
    } 
    
  if (test == true)
    {
    current_image++;
    if (current_image > last_image) 
      { 
      if (play_mode == 'loop') 
        { 
        current_image = first_image; 
        } 
      if (play_mode == 'sweep') 
        { 
        current_image = last_image; 
        animate_rev(); 
        return; 
        } 
      }
    }
  else
    {
    //image_status[b][current_image] = true; 
    return true;
    }      
} 
    

function check_previous_image_status()     
  {
  var test;

  if (webcam_images_display[current_image].complete == false) 
    {
    test = true;
    } 
    
  if (test == true)
    {
    current_image--;
    if (current_image > first_image) 
      { 
      if (play_mode == 'normal') 
        { 
        current_image = last_image; 
        } 
      if (play_mode == 'sweep') 
        { 
        current_image = last_image; 
        animate_rev(); 
        return; 
        } 
      }
    }
  else
    {
    //image_status[b][current_image] = true; 
    return true;
    }      
} 
    
// Display animation in reverse direction 
function animate_rev() 
  { 
  // If there's only 1 or less images, do nothing.  The return here terminates the function. 
  if (nImages<=1) return; 
  
  // Otherwise, decrement the current_image_counter 
  current_image--; 
  
  // Check if image number is before lower loop bound == 
  if (current_image < first_image) 
    { 
    if (play_mode == 'normal') 
      { 
      // Rev loop mode - skip to last image 
      current_image = last_image; 
      } 
    if (play_mode == 'sweep') 
      { 
      //sweep mode - change directions (go fwd) 
      current_image = first_image; 
      animate_fwd(); 
      return; 
      } 
    } 
  
  // Now, the idea is to display the webcam images for a set time on screen (all at the same time) 
  // To do that the images from each webcam (at time x) need to have been downloaded and ready 
  // to display on screen.  For current_image, cycle though the webcam image array to see if all images 
  // are ready for display - if they are, display them.  If they're not, increment current_image to see 
  // if the next set of images are ready and continue this pattern indefinitely. 
  
   if (check_previous_image_status())
    {
    display_current_image();
    } 
  
  delay_timeout = dL; 
  
  if (current_image == first_image)  delay_timeout = sDM*dL; 
  if (current_image == last_image)   delay_timeout =   eDM*dL; 
  
  // Call "animate_rev()" again after a set amount of time (delay_timeout) has elapsed 
  timeID = setTimeout("animate_rev()", delay_timeout); 
} 



// Changes playing speed by adding to or substracting from the dL between fra
 
function change_speed(dv) {
  dL+=dv; 
  // check to ensure max and min dL constraints have not been crossed == 
  if(dL > dMx) dL = dMx; 
  if(dL < dMn) dL = dMn; 
  tCs = sSt-Math.floor(dL/dSt); 
} 
  
  
// functions that changed the dwell rates. 
function change_end_dwell(dv) { 
  eDM+=dv; 
  if ( eDM < 1 ) eDM = 0; 
} 
  
  
function change_start_dwell(dv) { 
  sDM+=dv; 
  if ( sDM < 1 ) sDM = 0; 
} 
  
  
// Increment to next image 
function incrementImage() 
  { 
  // If there is 1 or fewer images in the animation, do nothing.  The return here terminates the function. 
  if (nImages<=1) return; 
  
  // To step through the images we must first stop the animation 
  stop(); 
  
  // Next image in the animation 
  current_image++; 
  
  //== if image is last in loop, increment to first image == 
  if (current_image > last_image) 
    { 
    current_image = first_image; 
    } 
    
  //== check to ensure that image has not been deselected from loop == 
   if (check_next_image_status())
    {
    display_current_image();
    }   
} 
  
// Decrement to next image 
function decrementImage() 
  { 
  // If there are 1 or fewer images in the loop, do nothing. The return here terminates the function 
  if (nImages<=1) return; 
  
  // To step through the images we must first stop the animation 
  stop(); 
  
  // Next image in the animation 
  current_image--; 
  
  //== if image is last in loop, increment to first image == 
  if (current_image < first_image) 
    { 
    current_image = last_image; 
    } 
    
  //== check to ensure that image has not been deselected from loop == 
   if (check_previous_image_status())
    {
    display_current_image();
    } 
} 

  
// captures a key stroke of forwards and backwards and moves the animation forwards or backwards 
function stepThrough(ev) 
{ 
    if (!document) { 
  return false; 
 } 
    if (!(ev.ctrlKey || ev.altKey)) { 
        switch (ev.keyCode) { 
            case 37: // KEY left 
                decrementImage(); 
            break; 
            case 39: // KEY right 
                incrementImage(); 
            break; 
            case 190: // KEY '.' or '>' 
                change_speed(-dSt); 
            break; 
            case 188: // KEY ',' or '<' 
                change_speed(dSt); 
            break; 
            default: 
            return true; 
        } 
    } 
} 

// "Play forward" 
function fwd() 
{ 
  stop(); 
  loop_status = 1; 
  play_mode = 'loop';
  play_status = 'play';
  animate_fwd(); 
} 
  
// "Play reverse" 
function rrev() 
{ 
  stop(); 
  loop_status = 1; 
  play_mode = 'loop'; 
  animate_rev(); 
} 

// "play sweep" 
function sweep() { 
  stop(); 
  loop_status = 1; 
  play_mode = 'sweep'; 
  animate_fwd(); 
} 
  
// Change play mode (normal, loop, swing) 
function change_mode(mode) 
{ 
   play_mode = mode; 
} 
  
// Check selection status of image in animation loop 
function checkImage(loop_status,i) 
{ 
  //if (loop_status == true) 
    //image_status[i] = false; 
  //else 
  //image_status[i] = true; 
} 
  
// Empty function - used to deal with image buttons rather than HTML buttons 
function func() 
{ 
} 

function addEvent(el, evname, func) { 
    if (el.attachEvent) { // IE 
        el.attachEvent("on" + evname, func); 
    } else if (el.addEventListener) { // Gecko / W3C 
        el.addEventListener(evname, func, true); 
    } else { 
        el["on" + evname] = func; 
    } 
} 

addEvent(document, "keydown", stepThrough); 

-->
  
</script>

<style tyle="text/css">

body
  {
  margin-top:0px;
  background-color:white;
  color: black;
  /* background: #EEEEEE url('http://www.weatherzone.com.au/images/widgets/bg_body_new.gif') repeat-y 50% 0; */
  }
  
.gradient
  {
  /* fallback (Opera) */
  background: #c3cde8;
  /* Mozilla: */
  background: -moz-linear-gradient(left, #c3cde8, #FFFFFF);
  /* Chrome, Safari:*/
  background: -webkit-gradient(linear, left top, right top, from(#c3cde8), to(#FFFFFF));
  /* MSIE */
  filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#c3cde8', EndColorStr='#FFFFFF', GradientType=1);
  }

table,td,tr
  {
  font-family:"Helvetica", "Arial", sans-serif;
  font-size: 11pt;
  }

.heading
  {
  color: #002352;
  font-weight:bold;
  letter-spacing:1px;
  }

.text
  {
  color: #012c5a;
  }
 
.time
  {
  width:70px;
  }
 
.link
  {
  color: #002352;
  font-weight:bold;
  padding-top:10px;
  padding-bottom:10px;
  }

.camera_menu
  {
  width:220px;
  }
 
A:LINK, A:VISITED, A:ACTIVE
  {
  text-decoration: none;
  letter-spacing:1px;
  color: #002352;
  }
  
A:HOVER
  {
  text-decoration: none;
  color: red;
  }
  
.buttona
  {    
  font: Verdana, Geneva, Arial, Helvetica, sans-serif;    
  background-color: #D7E5F2;    
  color: #102132;
  padding:10px;
  padding-top:5px;
  padding-bottom:5px;
  
  } 
  
.button {
 background-color: #b9caf7;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px;
 -moz-box-shadow: 2px 2px 1px #999;
 -webkit-box-shadow: 2px 2px 1px #999;
 border: solid 1px #CCC;
font-size:14px;
 color: #000000;
 text-shadow: 2px 2px 5px #000000;
 }
 
 .button:hover {
 background-color: #05b3ff;
 }

  
  
#progress_bar_container
  {
  width:100%;
  padding-left:0px;
  padding-right:0px;
  padding-top:0px;
  }
  
#progress_wrapper
  {
  position:relative;
  width:100%;
  height:30px;
  padding-top:0px;
  padding-bottom:0px;
  align:center;
  border:solid 1px #595858;
  }
  
.progress_bar
  {
  z-index:0;
  position:absolute;
  top:0px;
  left:0px;
  width:1px;
  height:28px;
  padding:0px;
  border-right:solid 1px #595858;
  background-color:#064273;
  color: white;
  text-align:left;  
  }

.progress_text
  {
  z-index:1;
  position:absolute;
  top:5px;
  left:0px;
  height: 100%;
  width: 100%;
  padding:0px;
  padding-top:0px;
  text-align:middle;
  color: #a2a0a0;
  }  

</style>
<title>Time Lapse Pty Ltd - <?php echo $html_title; ?></title>
</head>
<?php

if ($animation == 'yes') { echo "<body onLoad=\"launch()\">"; } 

?>
            <table width="980" border="0">
              <tr>


            <?php
            
            $cache = rand(0,20000);
            
            if ($animation == 'yes' && $total_images == 0)
              {
              echo "<td style=\"\" align=\"center\" valign=\"middle\"><font style=\"font-size:150%;\">Sorry, there are no images for the time period you've selected.</font></td>";
              }
            elseif ($animation == 'yes' && $error != 'yes')
              {
              echo "

            <td style=\"background-color:#dbdfe5;\" align=\"center\">
            
            <div style=\"padding:3px 0px 3px 0px;\">
            <div id=\"progress_bar_container\" align=\"center\">
              <div id=\"progress_wrapper\">
                <div id=\"progress_text\" class=\"progress_text\">&nbsp;</div>
                <div id=\"progress_bar\" class=\"progress_bar\">&nbsp;</div>
              </div>
            </div>  
            
            <input type=\"hidden\" id=\"finished_text\" value=\"Displaying <b>$total_images</b> images between $animation_start_screen and $animation_stop_screen\">
            <ilayer name=\"animationlayer\" left=\"1\" top=\"1\" id=\"animationlayer\">
            <img style=\"border: solid 1px #C1C1C1;\" src=\"\" name=animation id=\"timelapseimage\" border=\"0\" width=\"980\">
            </ilayer>
            </div>
            ";
            
            echo "           
            </td>
              ";
              }
            else
              {
              if ($error != 'yes')
                {
                if ($cam == 'tlc_wilson_park_zoom') {
                  echo "
                  <td style=\"background-color:#dbdfe5;\" align=\"center\" valign=\"top\">
                  <div style=\"padding-top:5px;padding-bottom:5px;padding-left:5px;padding-right:5px;\"><img src=\"https://legacy.livetimelapse.com.au/www/tlc_wilson_park/{$displayImageSize}.jpg?c={$cache}\"></div>
                  </td>
                  "; 
                } else {
                  echo "
                  <td style=\"background-color:#dbdfe5;\" align=\"center\" valign=\"top\">
                  <div style=\"padding-top:5px;padding-bottom:5px;padding-left:5px;padding-right:5px;\"><img src=\"https://legacy.livetimelapse.com.au/www/{$cam}/{$displayImageSize}.jpg?c={$cache}\"></div>
                  </td>
                  ";
                }
                }
              else
                {
                echo "<td style=\"background-color:#dbdfe5;\" align=\"center\" valign=\"middle\"><font style=\"font-size:150%;\">Sorry, you have chosen an invalid start and stop time.</font></td>";
                }
              }
              
              ?>
            
            </td>
          </tr>
        </table>


<form method="post" name="control_form">
<input type="hidden" name="frame_nr" size="2" readonly>
</form>

<div align="center" id="fullsize" style="visibility:hidden;">
<a href="" style="color:black;"></a>
</div>

</body>
</html>
