<?php
header( "Cache-Control: no-cache, must-revalidate" );
header( "Pragma: no-cache" );



include("functions.php");

//this function determines what should be displayed the given cell, representing a day of the month.
//it is called for each day of the month further down.
//$result is a php mymsql_result which is a list of reservations for this month +/-1 month
//$shownames is set based on whether or not we are a guest.
function getCellData($result, $month, $d, $year, $shownames)
{
	include("boats.php");

	$i=0;
	$num=mysql_numrows($result);
	$cellContents="";
	while ($i < $num)
	{
		$resid = mysql_result($result,$i,"id");
		$rFrom = datetime(mysql_result($result,$i,"reservefrom"));
		$rTo = datetime(mysql_result($result,$i,"reserveto"));


		if($shownames)
		{
			$lname = "&nbsp;";
		}
		else
		{
			$lastname=mysql_result($result,$i,"last");

			$lenLname = strlen($lastname);
			$maxlen = 7;
			if($lenLname > $maxlen)
				$lastname = substr($lastname, 0, $maxlen - 2) . "...";

			$lname = "<a href=\"reservationinfo.php?resid=".$resid."\">" . $lastname . "</a>";
		}

		$phone = mysql_result($result,$i,"phone1");
		$destination = mysql_result($result,$i,"destination");
		$boatname = mysql_result($result,$i,"name");
		$todayM = mktime(0,0,0,$month,$d,$year);
		$tomorrowM = mktime(0,0,0,$month,$d + 1,$year);
		$todayA = mktime(12,0,0,$month,$d,$year);

		if($rFrom >= $todayM && $rFrom < $todayA)
		{
			if($rTo >= $todayM && $rTo < $todayA)
			{
				//starts this morning, ends this morning
				for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
				{
					if($boatname==$fleetboatnames[$k])
					{
						$morning[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
					}
				}
			}
			else
			{
				//starts this morning, goes into the afternoon (or beyond)
				for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
				{
					if($boatname==$fleetboatnames[$k])
					{
						$morning[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
						$afternoon[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
					}
				}
			}
		}
		else if($rFrom >= $todayA && $rFrom < $tomorrowM)
		{
			//starts this afternoon (doesnt matter if it goes beyond)
			for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
			{
				if($boatname==$fleetboatnames[$k])
				{
					$afternoon[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
				}
			}
		}
		else if($rTo >= $todayM && $rTo < $todayA)
		{
			//ends this morning.
			for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
			{
				if($boatname==$fleetboatnames[$k])
				{
					$morning[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
				}
			}
		}
		else if($rTo >= $todayA && $rTo < $tomorrowM)
		{
			//ends this afternoon, and includes this morning
			for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
			{
				if($boatname==$fleetboatnames[$k])
				{
					$morning[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
					$afternoon[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
				}
			}
		}
		else if($rFrom <= $todayM && $rTo > $todayA)
		{
			//starts before today, ends this afternoon or later
			for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
			{
				if($boatname==$fleetboatnames[$k])
				{
					$morning[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
					$afternoon[] = "<td style=\"font-size: 10pt; width: 25%; height: 25%; background:". $fleetboatcolors[$k]."\">" . $lname . "</td>";
				}
			}
		}

		$i++;
	}
	$cellContents = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 100%;\">";
	for($q=0;$q<sizeof($fleetboatnames);$q=$q+1)
	{
		if(!$morning[$q] || $morning[$q]=="")
			$morning[$q]="<td style=\"width: 25%; height: 25%;\">&nbsp;</td>";
		if(!$afternoon[$q] || $afternoon[$q]=="")
			$afternoon[$q]="<td style=\"width: 25%; height: 25%;\">&nbsp;</td>";
		$rowData = "<tr>".$morning[$q].$afternoon[$q]."</tr>";
		$cellContents = $cellContents . $rowData;
	}
	$cellContents = $cellContents . "</table>";

	return $cellContents;
}

#$mosConfig_locale_debug = 0;
#$mosConfig_locale_use_gettext = 0;

//uncomment these lines to hide errors - there shouldn't be any errors so we leave them commented!
#error_reporting('0');
#ini_set('display_errors', '0');


//define the location and size of the floating reservation window.
$fw_top=100;
$fw_left=100;
$fw_height=400;
$fw_width=420;

// connect to the mysql database

$dbhost = 'db.washingtonyachtclub.org';
$dbuser = 'wyc';
$dbpass = 'WYC#Sail!Pass';
$database = 'production';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
@mysql_select_db($database) or die( "Unable to select database");

//check to see if the user has the login cookie. if not the send to login page
if(!isset($_COOKIE['ID_wycnumber']))
{
	header("Location: login.php");
	exit();
}
else
{
	$is_guest=0;
	$proceed=0;


	$wycnumber = $_COOKIE['ID_wycnumber'];
	$password = $_COOKIE['Key_site'];
	if($wycnumber=="guest")
	{
		$defaultPhoneNumber = "Guest Phone";
		$first = "";
		$last = "Guest Acount";

		$is_guest=1;
		$proceed=1;
	}
	else
	{
		$query = "SELECT * FROM WYCDatabase WHERE wycnumber = '$wycnumber' and password = PASSWORD('$password')";
		$check = mysql_query($query)or die(mysql_error());

		$check2 = mysql_num_rows($check);
		//if the username/password is wrong, then we won't have any matches in the db. if there are no matching rows, send them to the login page
		if ($check2 == 0)
		{
			header("Location: login.php");
			mysql_free_result($check2);
			mysql_free_result($check);
			mysql_close();
		}
		$defaultPhoneNumber = mysql_result($check,0,"phone1");
		$first = mysql_result($check,0,"first");
		$last = mysql_result($check,0,"last");
		mysql_free_result($check);

		$hour = time() + 3600;
		setcookie(ID_wycnumber, $_COOKIE['ID_wycnumber'], $hour);
		setcookie(Key_site, $_COOKIE['Key_site'], $hour);

		$proceed=1;
	}
	//we proceed either if we are a guest, or if we have been logged in successfully
	if($proceed)
	{
		$check4 = getAllowReservations($_SERVER['REMOTE_ADDR']);
		
		//don't allow members without a KB rating to check out a boat
		$ratingQuery= "SELECT * FROM wyc_ratings JOIN ratings ON rating = ratings._index WHERE member = '$wycnumber' and is_kb = 1";
		$ratingMySQL = mysql_query($ratingQuery)or die(mysql_error());
		$hasRating = mysql_num_rows($ratingMySQL);
		if (($check4 == 0 | $is_guest) | $hasRating == 0)
			$allowReservation=0;
		else
			$allowReservation=1;


		// look at the month we are requesting from the query string

		if(!isset($_REQUEST['monthyear']))
		{
			$date = mktime(0,0,0,date('m'), 1, date('Y'));
		}
		else
		{
			$date = $_REQUEST['monthyear'];
		}

		$month = date('m', $date);
		$year = date('Y', $date);

		// Get the first second of the month
		$month_start = mktime(0,0,0,$month, 1, $year);

		// the date() function is our friend!
		$month_name = date('F', $month_start);

		// Figure out which day of the week, again using the date() function
		$month_start_day = date('D', $month_start);


		//get an offset into the start of the month
		switch($month_start_day){
			case "Sun": $offset = 0; break;
			case "Mon": $offset = 1; break;
			case "Tue": $offset = 2; break;
			case "Wed": $offset = 3; break;
			case "Thu": $offset = 4; break;
			case "Fri": $offset = 5; break;
			case "Sat": $offset = 6; break;
		}

		//cal_days_in_month() is our friend here
		// determine how many days are in the last month.
		if($month == 1){
			$num_days_last = cal_days_in_month(0, 12, ($year -1));
		} else {
			$num_days_last = cal_days_in_month(0, ($month -1), $year);
		}

		// determine how many days are in the current month.
		$num_days_current = cal_days_in_month(0, $month, $year);

		// Build an array for the number of days
		// in last month
		for($i = 1; $i <= $num_days_last; $i++){
			$num_days_last_array[] = $i;
		}

		// Build an array for the current days
		// in the month
		for($i = 1; $i <= $num_days_current; $i++){
			$num_days_array[] = $i;
		}


		if($offset > 0)
		{
			$offset_correction = array_slice($num_days_last_array, -$offset, $offset);
			$new_count = array_merge($offset_correction, $num_days_array);

			$offset_count = count($offset_correction);
		}
		// The else statement is to prevent building the $offset array.
		else
		{
			$new_count = $num_days_array;
			$offset_count = 0;
		}


		// count how many days we have with the two
		// previous arrays merged together
		$current_num = count($new_count);


		// Since we will have 5 HTML table rows (TR)
		// with 7 table data entries (TD)
		// we need to fill in 35 TDs
		// so, we will have to figure out
		// how many days to appened to the end
		// of the final array to make it 35 days.


		if($current_num > 35)
		{
			$num_weeks = 6;
			$outset = (42 - $current_num);
		}
		elseif($current_num < 35)
		{
			$num_weeks = 5;
			$outset = (35 - $current_num);
		}

		if($current_num == 35)
		{
			$num_weeks = 5;
			$outset = 0;
		}

		// Outset Correction
		for($i = 1; $i <= $outset; $i++)
		{
			$new_count[] = $i;
		}

		// Now lets "chunk" the $new_count array into weeks. Each week has 7 days
		// so we will array_chunk it into 7 days.
		$weeks = array_chunk($new_count, 7);

		$previous_link = "<a href=\"".$_SERVER['PHP_SELF']."?monthyear=";
		if($month == 1){
		   $previous_link .= mktime(0,0,0,12,1,($year -1));
		} else {
		   $previous_link .= mktime(0,0,0,($month -1),1,$year);
		}
		$previous_link .= "\"><img src=\"images/btn_prev.gif\" alt=\"Previous\"></a>";

		$next_link = "<a href=\"".$_SERVER['PHP_SELF']."?monthyear=";
		if($month == 12){
		   $next_link .= mktime(0,0,0,1,1,($year + 1));
		} else {
		   $next_link .= mktime(0,0,0,($month +1),1,$year);
		}
		$next_link .= "\"><img src=\"images/btn_next.gif\" alt=\"Next\"></a>";


		?>
		<html>
			<head>
				<title>Washington Yacht Club Calendar</title>
				<link rel="stylesheet" type="text/css" href="css/wyc.css">
				<link rel="stylesheet" href="css/floating-window.css" media="screen" type="text/css">
				<script type="text/javascript" src="js/ajax.js"></script>
				<script type="text/javascript" src="js/floating-window.js"></script>
			</head>
			<body>


		<table id="tblCal" border="1" cellpadding="2" cellspacing="0" class="calendar">
			<tr>
				<td colspan="7" class="calendarHeader" style="width:100%;">
					<table border="0" cellpadding="0" cellspacing="0" style="width:100%" >
						<tr>
							<td style="vertical-align:top; text-align:left; width:155px">
								<a href="http://www.washingtonyachtclub.org"><img src="images/burgee_purple.gif" alt="burgee_purple" /></a>
							</td>
							<td style="vertical-align:top">
								<span style="font-size:30">Washington Yacht Club</span>
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
								<span style="font-size:18">Keelboat availability</span>
								<br />
								<span style="font-size:9pt">
									<?php
										if($allowReservation)
											echo "You may use this calendar to reserve a boat. Happy sailing!";
										else
											echo "To reserve a boat, you must login (not as a guest) using the computer in the sail locker.";
									?>
								</span>
							</td>
							<td style="vertical-align:top; text-align:right">
								<b>Remember to <a href="logout.php">Logout</a></b>
								<br/>
								<br/>
								<table style="border: solid 1px black"><tr><td style="font-size:9pt" colspan="2">2</td></tr>
								<?php
									include("boats.php");
									for($k=0;$k<sizeof($fleetboatnames);$k=$k+1)
									{
 										echo "<tr><td style=\"background: ". $fleetboatcolors[$k]. "; font-size:9p\">" . $fleetboatnames[$k] . " Morning</td>";
 										echo "<td style=\"background: ". $fleetboatcolors[$k] . "; font-size:9p\">" . $fleetboatnames[$k] . " Afternoon</td></tr>";
									}
								?>
								</table>
							</td>
						</tr>
						<tr>
							<td colspan="3">
								<center><span style="background: #dddddd">
								<?php
									if(!$is_guest && $allowReservation)
										echo "<a href=\"#\" onclick=\"customFunctionCreateWindow(false,$fw_width,$fw_height,$fw_left,$fw_top,".$_COOKIE['ID_wycnumber'].",".date('m').",".date('d').",".date('Y').",'".$defaultPhoneNumber."');return false\">Make a reservation</a>"
								?><br />
								You are logged in as <?php echo $first . " " . $last; ?>. <a href="logout.php">Logout</a> when you are finished!
								</span></center>
							</td>

						</tr>
						<tr>
							<td style="height:20px" colspan="2">
								<?php echo $previous_link . " " . $next_link . " <b>" . $month_name .
								" " . $year . "</b>" ?>
							</td>
							<td style="text-align:right">
								<a href="cal.php">Today</a>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td class="columnHeader">S</td>
				<td class="columnHeader">M</td>
				<td class="columnHeader">T</td>
				<td class="columnHeader">W</td>
				<td class="columnHeader">T</td>
				<td class="columnHeader">F</td>
				<td class="columnHeader">S</td>
			</tr>


		<?php


		//select all the reservations that we might need to show for the selected month.
		//first do some adjustments in case we are in december/january
		$bmonth=$month-1;
		$byear=$year;
		if($bmonth==0)
		{
			$bmonth=12;
			$byear=$byear-1;
		}
		$tmonth=$month+1;
		$tyear=$year;
		if($tmonth==13)
		{
			$bmonth=1;
			$tyear=$tyear+1;
		}
		$query="select id, name, wycnumber, reservefrom, reserveto, destination, numberofcrew, comments, first, last, phone1, phone2
		from calendartable, WYCDatabase, calendarboats
		where memberwycnumber=wycnumber
		and calendartable.cboatid=calendarboats.cboatid
		and ((reservefrom >= '".$byear."-".($bmonth)."-01 00:00:00' and reservefrom <= '".$tyear."-".($tmonth)."-31 11:59:59') or (reserveto >= '".$byear."-".($bmonth)."-01 00:00:00' and reserveto <= '".$tyear."-".($tmonth)."-31 11:59:59'));";
		$result=mysql_query($query) or die(mysql_error());


		// Now we break each key of the array into a week and create a new table row for each
		// week with the days of that week in the table data

		$i = 0;
		foreach($weeks AS $week)
		{
			echo "<tr>\n";
			foreach($week as $d)
			{

				// last months greyed out days
				if($i < $offset_count)
				{
					if($allowReservation)
					{
						if($month==1)
						{
							$monthmone=12;
							$adjyear=$year-1;
						}
						else
						{
							$monthmone=$month-1;
							$adjyear=$year;
						}
						if(mktime(0,0,0,date('m'), date('d'), date('Y')) <= mktime(0,0,0,$monthmone,$d,$adjyear) && mktime(0,0,0,date('m'), date('d'), date('Y')+1) > mktime(0,0,0,$monthmone,$d,$adjyear))
							$day_link = "<a href=\"#\" onclick=\"customFunctionCreateWindow(false,$fw_width,$fw_height,$fw_left,$fw_top,".$_COOKIE['ID_wycnumber'].",".$monthmone.",".$d.",".$adjyear.",'".$defaultPhoneNumber."');return false\">$d</a><br>";
						else
							$day_link = "$d";
					}
					else
						$day_link = "$d";

					echo "<td class=\"nonmonthdays\">$day_link\n";
					$cellData = getCellData($result, $month - 1, $d, $year, $is_guest);
					if($cellData=="")
						echo "<div><br /><br /><br /><br /></div>";
					else
						echo $cellData;
					echo "\n</td>\n";
				}
				// this months days
				if(($i >= $offset_count) && ($i < ($num_weeks * 7) - $outset))
				{
					if(mktime(0,0,0,date('m'), date('d'), date('Y')) == mktime(0,0,0,$month,$d,$year))
						echo "<td class=\"today\">\n";
					else
						echo "<td class=\"monthdays\">\n";

					if($allowReservation && mktime(0,0,0,date('m'), date('d'), date('Y')) <= mktime(0,0,0,$month,$d,$year) && mktime(0,0,0,date('m'), date('d'), date('Y')+1) > mktime(0,0,0,$month,$d,$year))
						//echo "<a href=\"reserve.php?date=".mktime(0,0,0,$month,$d,$year)."\">$d</a><br />\n";
						echo "<a href=\"#\" onclick=\"customFunctionCreateWindow(false,$fw_width,$fw_height,$fw_left,$fw_top,".$_COOKIE['ID_wycnumber'].",".$month.",".$d.",".$year.",'".$defaultPhoneNumber."');return false\">$d</a><br>";
					else
						echo "$d";


					$cellData = getCellData($result, $month, $d, $year, $is_guest);
					if($cellData=="")
						echo "<div><br /><br /><br /><br /></div>";
					else
						echo $cellData;
					echo "\n</td>\n";
				}
				// next months greyed out days
				elseif($i >= ($num_weeks * 7) - $outset)
				{
					if($allowReservation)
					{
						if($month==12)
						{
							$monthpone=1;
							$adjyear=$year+1;
						}
						else
						{
							$monthpone=$month+1;
							$adjyear=$year;
						}
						if($allowReservation && mktime(0,0,0,date('m'), date('d'), date('Y')) <= mktime(0,0,0,$monthpone,$d,$adjyear) && mktime(0,0,0,date('m'), date('d'), date('Y')+1) > mktime(0,0,0,$monthpone,$d,$adjyear))
							$day_link = "<a href=\"#\" onclick=\"customFunctionCreateWindow(false,$fw_width,$fw_height,$fw_left,$fw_top,".$_COOKIE['ID_wycnumber'].",".$monthpone.",".$d.",".$adjyear.",'".$defaultPhoneNumber."');return false\">$d</a><br>";
						else
							$day_link = "$d";
					}
					else
						$day_link = "$d";

					echo "<td class=\"nonmonthdays\">$day_link\n";
					$cellData = getCellData($result, $month + 1, $d, $year, $is_guest);
					if($cellData=="")
						echo "<div><br /><br /><br /><br /></div>";
					else
						echo $cellData;
					echo "\n</td>\n";
				}
				$i++;
			}

			echo "</tr>\n";
		}


		// terminate the mysql connection
		mysql_close();
	}
}

?>

<tr><td colspan="7" class="days"> </td></tr>
</table>

</body>
</html>


