<?php

$g_include_level_up = 0;
$g_public_page = true;

include('./ladybug_include/generic_include.php');

# Check for ajax
if (isset($_POST['_action_id'])) {
	$id = ((isset($_POST['id'])) ? $_POST['id'] : null);

	switch ($_POST['_action_id']) {
		case "check_deleted":
			$query_check = "SELECT 1 FROM wes_Photo WHERE photo_id IN ({$_POST['id']}) AND deleted IS TRUE";
			$result_check = db_query($query_check);
			if (db_num_rows($result_check) == 0) {
				print "false";
			} else {
				print "true";
			}
			break;
	}

	exit();
}

$g_page_title = "Uploads";

# Get images to show - look for email_id not null

$output = "";
$query_images = "SELECT photo_id, image_filename "
	. "FROM (SELECT photo_id, image_filename FROM wes_Photo WHERE album_name = 'email-upload' AND deleted IS FALSE ORDER BY times_used LIMIT 20) AS rarely_used "
	. "ORDER BY rand() LIMIT 10 ";
$result_images = db_query($query_images);
$images = db_num_rows($result_images);
if ($images == 0) {
	$output .= "<script>\n";
	$output .= "$(function() {\n";
	$output .= "    $('html').css('width', '100%').css('height', '100%');\n";
	$output .= "    $('body').css('width', '100%').css('height', '100%').css('background-color', 'black');\n";
	$output .= "});\n";
	$output .= "</script>\n";
	$output .= "<div style=\"background: url(default.jpg) no-repeat center center; height: 100%; width: 100%;\"></div>";
	$g_page_include_default_stylesheets = false;
} else {
	$output .= "<script>\n";
	$output .= "$(function() {\n";
	$output .= "    $.supersized({\n";
	$output .= "        slides : [\n";
	$index = 0;
	while ($row_images = db_fetch_assoc($result_images)) {
		$photo_id[] = $row_images['photo_id'];
		$output .= "            { image : './image/{$row_images['image_filename']}' }";
		if ($index < ($images - 1)) {
			$output .= ",";
		}
		$output .= "\n";
	}
	$photo_string = implode(',', $photo_id);
	$output .= "        ]\n";
	$output .= "    });\n";
	$output .= "});\n";
	
	# Regular update - every two minutes reload whole page
	$output .= "setTimeout(reloadPage, 1000 * 60);\n";
	$output .= "function reloadPage() {\n";
	$output .= "api.playToggle();\n";
	$output .= "if (vars.is_paused) { window.location.href = window.location.href; } else { setTimeout(reloadPage, 1000); }\n";
	$output .= "}\n";
	
	# Check for deleted images every 5 seconds
	$output .= "setInterval(checkDeleted, 1000 * 5);\n";
	$output .= "function checkDeleted() {\n";
	$output .= "$.ajax( { type: 'POST', data: { '_action_id': 'check_deleted', 'id': '$photo_string' }, success: function(data, textStatus, jqXHR) {\n";
	$output .= "if (data == 'true') { reloadPage(); } } });\n";
	$output .= "}\n";

	$output .= "</script>\n";
	
	# Update images to indicate another view
	$query_update = "UPDATE wes_Photo SET times_used = times_used + 1 WHERE photo_id IN ($photo_string)";
	$result_update = db_query($query_update);
}

include('./ladybug_include/header_include.php');

print $output;

include('./ladybug_include/footer_include.php');
?>