<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

	require "../_container/container_top.php";
	require_once ('business/ReservationMgr.php');
	require_once ('business/PaymentMgr.php');
	require_once ('business/TenantMgr.php');
	require_once ('business/TenancyMgr.php');
	require_once ("config/Tagger.php");

	$reservationMgr = new ReservationMgr();
	$paymentMgr = new PaymentMgr();
	$tenantMgr = new TenantMgr();
	$tenancyMgr = new TenancyMgr();
	$tagger = new Tagger();

	$action = getPost('action');

	if (empty($action)) $action = "Add";
	$add = ($action == "Add") ? true : false;

	$reservationid = getPost('id');

	$arrReservation = $reservationMgr->getReservation($reservationid);
	$arrPayment = $paymentMgr->getPaymentByReservation($reservationid);

	$arrAllTenants = $tenantMgr->getTenants();
	$arrTenancy = $tenancyMgr->getTenancys();

	if (empty($arrReservation)) $arrReservation = array(new ReservationVo());
	$reservclosed = ($arrReservation[0]->status == ReservationMgr::RESERV_CLOSED);
	if ($config['allow_edit_paid_reserv']) $reservclosed = false;

	// print_r($arrReservation);

?>

	<div>
		<ul class="breadcrumb">
			<li><a href="./"><?php echo $tr->translate("menuHome"); ?></a> <span class="divider">/</span></li>
			<li><a href="reservation.php"><?php echo $tr->translate("menuReservations"); ?></a> <span class="divider">/</span></li>
			<li class="active"><?php echo $tr->translate($action); ?></li>
		</ul>
	</div>

	<?php if (empty($arrTenancy)) { ?>
		<div class="alert alert-error">
			<h1><small><?php echo $tr->translate("msgNoTenancy"); ?></small></h1>
			<p><?php echo $tr->translate("msgAddTenancy"); ?></p>
			<p class="">
				<a href="tenancyDetail.php" class="btn btn-large btn-primary"><i class="icon-chevron-left icon-white"></i> <?php echo $tr->translate("AddTenancy"); ?></a>
			</p>
			<div class="clearfix"></div>
		</div>

	<?php }else{ ?>

	<div class="sortable row-fluid">
		<a data-rel="tooltip" title="<?php echo $tr->translate('AddReserv'); ?>" class="well span2 top-block btn-action" href="#" name="newReservation" id="newReservation" _page="reservationDetail.php" _action="Add">
			<i class="icon-red icon-user"></i>
			<div><?php echo $tr->translate("AddReserv"); ?></div>
			<div></div>
		</a>
		<a data-rel="tooltip" title="<?php echo $tr->translate("AddPayment"); ?>" class="well span2 top-block btn-action" href="#" name="newPayment" id="newPayment" _page="paymentDetail.php" _action="Add">
			<i class="icon-cog"></i>
			<div><?php echo $tr->translate("AddPayment"); ?></div>
			<div></div>
		</a>
	</div>
	<div class="row-fluid sortable ui-sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title="">
				<h2><i class="icon-th"></i> <?php echo $tr->translate("Reservation"); ?></h2>
			</div>
			<div class="box-content">
				<?php if ($reservclosed) {
					$msgType = "error";
					$msg = $tr->translate("msgReservPreventChange");
					echo '<div class="alert alert-'.$msgType . '">
						<strong>' . $msg . '</strong>
						</div>';
				} ?>

			<?php if (!$add) { ?>
				<h6>[id: <?php echo $arrReservation[0]->reservation_id; ?>] // [recorddate: <?php echo $arrReservation[0]->recorddate; ?>]</h6> 
			<?php } ?>
				<form class="form-horizontal" method="post" name="reservationForm" id="reservationForm" action="reservation.php">
					<input type="hidden" name="action" id="action" value="" />
					<input type="hidden" name="start_date" id="start_date" value="" />
					<input type="hidden" name="end_date" id="end_date" value="" />
					<input type="hidden" name="reservationid" id="reservationid" value="<?php echo $reservationid; ?>" />
					<input type="hidden" name="lease_date" id="lease_date" value="" />
					<input type="hidden" name="tenancyid" id="tenancyid" value="" />

			<?php if (!$add) { ?>
			<h3><?php echo $tr->translate("Status"); ?></h3>
				<div class="row-fluid" name="statusReserv" id="statusReserv">
					<div class="span12">
						<div class="control-group">
							<div class="controls">
								<span class="tracking">
									<a name="<?php echo ReservationMgr::RESERV_OPTION; ?>" title="<?php echo $tr->translate("Tracking1"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($arrReservation[0]->status >= ReservationMgr::RESERV_OPTION) echo "current"; ?>"><i class="badge icon-question-sign icon-large"></i></a>
									<a name="<?php echo ReservationMgr::RESERV_LEASE_SENT; ?>" title="<?php echo $tr->translate("Tracking2"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($arrReservation[0]->status >= ReservationMgr::RESERV_LEASE_SENT) echo "current"; ?>"><i class="badge icon-envelope icon-large"></i></a>
									<a name="<?php echo ReservationMgr::RESERV_VALIDATE; ?>" title="<?php echo $tr->translate("Tracking3"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($arrReservation[0]->status >= ReservationMgr::RESERV_VALIDATE) echo "current"; ?>"><i class="badge icon-ok icon-large"></i></a>
									<a name="<?php echo ReservationMgr::RESERV_CLOSED; ?>" title="<?php echo $tr->translate("Tracking4"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($arrReservation[0]->status >= ReservationMgr::RESERV_CLOSED) echo "current"; ?>"><i class="badge icon-usd icon-large"></i></a>
								</span>
							</div>
						</div>
					</div>
				</div>
				<h3><?php echo $tr->translate("Lease"); ?></h3>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<?php if (isset($arrReservation[0]->lease_date)) { ?>
								<label class="control-label" for="inputTitle"><?php echo $tr->translate("LeaseDate"); ?></label>
							<?php }else{ ?>
								<label class="control-label" for="inputTitle"><?php echo $tr->translate("LeaseNotSent"); ?></label>
							<?php } ?>
							<div class="controls">
								<?php if (isset($arrReservation[0]->lease_date)) { ?>
								<input type="text" class="" id="inputLease" name="inputLease" value="<?php echo date($config['date_format'], strtotime($arrReservation[0]->lease_date)); ?>" disabled>
									<?php if ($arrReservation[0]->status < ReservationMgr::RESERV_VALIDATE) { ?>

									<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipClearLeaseDate"); ?>" data-rel="tooltip" href="#" onclick="goAction('CLEAR_LEASE_DATE');">
										<i class="icon-trash"></i>
									</a>
									<?php } ?>
										<?php
											$tagger->setReservationId($arrReservation[0]->reservation_id);
											if (file_exists(LEASE_PATH . "/" . $tagger->tag($config['lease_filename']) . '.pdf')){ ?>
												<a id="leasePreview" name="leasePreview" class="btn btn-info btn-mini" title="<?php echo $tr->translate("tipFileView"); ?>" data-rel="tooltip" href="#" _id="<?php echo LEASE_PATH . "/" . $tagger->tag($config['lease_filename']) . '.pdf'; ?>">
												<?php echo $tr->translate("btnLeasePreview"); ?></a>
										<?php }else{
											echo $tr->translate("msgLeaseNotFound");
										} ?>
									<?php }else{ ?>
								<div class="input-append"><input type="text" class="datepicker input-medium" name="leaseDate" id="leaseDate" value="<?php
									echo date($config['date_format']);
									?>"><span class="add-on"><i class="icon-calendar"></i></span>

								</div>
									<a class="btn btn-primary btn-mini" title="<?php echo $tr->translate("tipSetLeaseDate"); ?>" data-rel="tooltip" href="#" onclick="goAction('SET_LEASE_DATE');">
										<i class="icon-ok"></i>
									</a>
									<button type="button" name="previewLease" id="previewLease" class="btn btn-info btn-mini" onclick="goAction('PREVIEW_LEASE')" data-rel="tooltip" title="<?php echo $tr->translate("tipReservLeasePreview"); ?>"><i class="icon-search"></i></button>

									<?php } ?>
								<?php if ($arrReservation[0]->tenant_email && !$reservclosed) { ?>
								<div class="control-group">
									<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo UPLOAD_FILE_SIZE; ?>" />
									<input type="file" id="uploadfile_Path" name="uploadfile_Path" size="24" title="<?php echo $tr->translate("ChooseFileTitle"); ?>" />
									<button type="button" name="uploadfile" id="uploadfile" class="btn btn-warning btn-mini"><?php echo $tr->translate("btnSendLease"); ?></button>
								</div>
								<?php } ?>
							</div>
						</div>
					</div>
				</div>

				<div class="progress">
				  <div class="bar" style="width: 100%"></div>
				</div>
			<?php } ?>
			<?php if (!$add) { ?>
			<?php if (empty($arrReservation[0]->tenant_email)) {
						$msgType = "error";
						$msg = $tr->translate("msgErrorTenantMailNotExist");
						echo '<div class="alert alert-' . $msgType . '">
							<strong>' . $msg . '</strong>
							</div>';
			} ?>
			<?php } ?>
				<h3><?php echo $tr->translate("Tenant"); ?></h3>
				<div class="row-fluid" <?php if (!$add) echo "style='display: none;'"; ?>>
					<div class="span12">
						<div class="control-group">
							<label class="control-label"><?php echo $tr->translate("KnownTenant"); ?></label>
							<div class="controls">
								<label class="radio inline"><?php echo $tr->translate("Yes"); ?>
								<input class="tenantRadio" type="radio" name="radioTenant" id="radioTenant2" value="yes" <?php if (!$add) echo " checked"; ?>>
								</label>
								<label class="radio inline"><?php echo $tr->translate("No"); ?>
								<input class="tenantRadio" type="radio" name="radioTenant" id="radioTenant1" value="no" <?php if ($add) echo " checked"; ?>>
								</label>
							</div>
						</div>
					</div>
				</div>

				<div class="row-fluid" name="knownTenant" id="knownTenant">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="selectTenant"><?php echo $tr->translate("Name"); ?></label>
							<div class="controls">
								<select class="chosen" id="selectTenant" name="selectTenant" data-rel="chosen" <?php if (!$add) echo "disabled "; ?>>
									<option value="0"><?php echo $tr->translate("SelectTenant"); ?></option>
									<?php foreach ($arrAllTenants as $tenant) {
										echo "<option";
										echo " value='" . $tenant->tenant_id . "'";
										if (($arrReservation[0]->tenant_id == $tenant->tenant_id) && ($arrReservation[0]->tenant_lastname == $tenant->lastname)) {
											echo " selected";
										}
										echo ">" . $tenant->lastname . " " . $tenant->name . "</option>";
									} ?>
								</select>
								<button type="button" name="editTenant" id="editTenant" class="btn btn-info btn-mini"><?php echo $tr->translate("btnEdit"); ?></button>
							</div>
						</div>
					</div>
				</div>

				<div name="newTenant" id="newTenant" <?php if (!$add) echo "style='display: none;'"; ?>>
				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputTitle"><?php echo $tr->translate("thTenantTitle"); ?></label>
							<div class="controls">
								<select id="inputTitle" name="inputTitle">
									<option></option>
									<?php $arrTitle = $tr->translate("thUserformTitles");
										foreach($arrTitle as $title) { ?>
											<option value="<?php echo $title; ?>"><?php echo $title; ?></option>
									<?php } ?>
								</select>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputLastname"><?php echo $tr->translate("thTenantLastName"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputLastname" name="inputLastname" value="">
							</div>
						</div> 				
						<div class="control-group">
							<label class="control-label" for="inputName"><?php echo $tr->translate("thTenantName"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputName" name="inputName" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputReference"><?php echo $tr->translate("thTenantRefer"); ?></label>
							<div class="controls">
								<select id="inputReference" name="inputReference">
									<option></option>
									<?php $arrRef = explode(",", $config['tenant_reference']);
										foreach($arrRef as $ref) { ?>
											<option value="<?php echo $ref; ?>"><?php echo $ref; ?></option>
									<?php } ?>
								</select>
								<button type="button" name="editTenantReference" id="editTenantReference" class="btn btn-info btn-mini"><?php echo $tr->translate("btnEdit"); ?></button>
							</div>
						</div>
					</div>
					<div class="span6">
						<div class="control-group">
						<label class="control-label" for="inputAddress1"><?php echo $tr->translate("thTenantAddress1"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputAddress1" name="inputAddress1" value="">
							</div>
						</div>
						<div class="control-group">
						<label class="control-label" for="inputAddress2"><?php echo $tr->translate("thTenantAddress2"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputAddress2" name="inputAddress2" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputZipcode"><?php echo $tr->translate("thTenantZipCode"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputZipcode" name="inputZipcode" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCity"><?php echo $tr->translate("thTenantCity"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputCity" name="inputCity" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCountry"><?php echo $tr->translate("thTenantCountry"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputCountry" name="inputCountry" value="">
							</div>
						</div>
					</div>
					</div>
					<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputPhone"><?php echo $tr->translate("thTenantPhone"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputPhone" name="inputPhone" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCellphone"><?php echo $tr->translate("thTenantMobile"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputCellphone" name="inputCellphone" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputFax"><?php echo $tr->translate("thTenantFax"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputFax" name="inputFax" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputEmail"><?php echo $tr->translate("thTenantEmail"); ?></label>
							<div class="controls">
								<input type="text" class="input-medium" id="inputEmail" name="inputEmail" value="">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputNewsletter"><?php echo $tr->translate("thTenantNewsletter"); ?></label>
							<div class="controls">
								<input type="checkbox" id="inputNewsletter" name="inputNewsletter">
							</div>
						</div>
					</div>
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputLanguage"><?php echo $tr->translate("thTenantLanguage"); ?></label>
							<div class="controls">
								<select id="inputLanguage" name="inputLanguage">
									<option></option>
									<?php $arrLang = $tr->translate("thTenantLanguageNames");
										foreach($arrLang as $lng) { ?>
											<option value="<?php echo $lng; ?>"><?php echo $lng; ?></option>
									<?php } ?>
								</select>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="inputComment"><?php echo $tr->translate("thTenantComment"); ?></label>
							<div class="controls">
								<textarea class="span6" id="inputComment" name="inputComment" rows="6"></textarea>
							</div>
						</div>
					</div>
				</div>

				</div>

				<div class="progress">
				  <div class="bar" style="width: 100%"></div>
				</div>

				<h3><?php echo $tr->translate("Tenancy"); ?></h3>			
				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="selectTenancy"><?php echo $tr->translate("Name"); ?></label>
							<div class="controls">
								<select class="chosen" id="selectTenancy" name="selectTenancy" data-rel="chosen" <?php if ($reservclosed) echo "disabled"; ?>>
									<option value="0"><?php echo $tr->translate("SelectTenancy"); ?></option>
									<?php foreach ($arrTenancy as $tenancy) {
										echo "<option";
										echo " value='" . $tenancy->tenancy_id . "'";
										if ($arrReservation[0]->tenancy_name == $tenancy->name) {
											echo " selected";
										}
										echo ">" . $tenancy->name . "</option>";
									} ?>
								</select>
								<button type="button" name="editTenancy" id="editTenancy" class="btn btn-info btn-mini"><?php echo $tr->translate("btnEdit"); ?></button>
								<img id="tenancyLoading" name="tenancyLoading" class="hide" src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/ajax-loaders/ajax-loader.gif" />
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputTitle"><?php echo $tr->translate("thReservFrom"); ?></label>
							<div class="controls">
								<div class="input-append"><input type="text" class="datepicker input-medium"  name="startDate" id="startDate" value="<?php
									if (!empty($arrReservation[0]->arrival_date)) {
										echo date($config['date_format'], strtotime($arrReservation[0]->arrival_date));
									}else{
										echo date($config['date_format']);
									}
									?>" <?php if ($reservclosed) echo "disabled"; ?>><span class="add-on"><i class="icon-calendar"></i></span>
								</div>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputTitle"><?php echo $tr->translate("thReservTo"); ?></label>
							<div class="controls">
								<div class="input-append"><input type="text" class="datepicker input-medium"  name="endDate" id="endDate" value="<?php
									if (!empty($arrReservation[0]->departure_date)) {
										echo date($config['date_format'], strtotime($arrReservation[0]->departure_date));
									}else{
										echo date($config['date_format'], strtotime('+7 day'));
									}
									?>"  <?php if ($reservclosed) echo "disabled"; ?>><span class="add-on"><i class="icon-calendar"></i></span>
								</div>
								<button type="button" name="checkDate" id="checkDate" class="btn btn-warning btn-mini" onclick="goAction('check_date')" value="<?php echo $tr->translate("btnCheckDate"); ?>" <?php if ($reservclosed) echo "disabled"; ?>><?php echo $tr->translate("btnCheckDate"); ?></button>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="inputPriceTotal"><?php echo $tr->translate("thReservPrice"); ?></label>
							<div class="controls">
								<div class="input-append">
									<input type="text" class="input-mini" id="inputPriceTotal" name="inputPriceTotal" value="<?php echo ($arrReservation[0]->price) ? $arrReservation[0]->price : 0; ?>" <?php if ($reservclosed) echo "disabled"; ?>><span class="add-on"><i><?php echo $config['currency_symbol']; ?></i></span>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputAdults"><?php echo $tr->translate("thReservAdults"); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign <?php if (!$reservclosed) echo "qtyminus"; ?>" data-field="inputAdults"></span></a><input type="text" class="input-mini" id="inputAdults" name="inputAdults" value="<?php echo (empty($arrReservation[0]->adults_nb)) ? 0 : $arrReservation[0]->adults_nb; ?>" <?php if ($reservclosed) echo " disabled"; ?>><a href="#"><span class="add-on icon-plus-sign <?php if (!$reservclosed) echo "qtyplus"; ?>" data-field="inputAdults"></span></a>
								</div>
							</div>
						</div>
					</div>
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputDisabled"><?php echo $tr->translate("thReservDisabled"); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<input type="checkbox" id="inputDisabled" name="inputDisabled"<?php if ($reservclosed) echo " disabled"; if (!empty($arrReservation[0]->disabled)) echo " checked";?>>
									</select>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputChilds"><?php echo $tr->translate("thReservChilds"); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign <?php if (!$reservclosed) echo "qtyminus"; ?>" data-field="inputChilds"></span></a><input type="text" class="input-mini" id="inputChilds" name="inputChilds" value="<?php echo (empty($arrReservation[0]->childs_nb)) ? 0 : $arrReservation[0]->childs_nb; ?>" <?php if ($reservclosed) echo " disabled"; ?>><a href="#"><span class="add-on icon-plus-sign <?php if (!$reservclosed) echo "qtyplus"; ?>" data-field="inputChilds"></span></a>
								</div>
							</div>
						</div>
					</div>
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputBaby"><?php echo $tr->translate("thReservBabys"); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign <?php if (!$reservclosed) echo "qtyminus"; ?>" data-field="inputBaby"></span></a><input type="text" class="input-mini" id="inputBaby" name="inputBaby" value="<?php echo (empty($arrReservation[0]->baby_nb)) ? 0 : $arrReservation[0]->baby_nb; ?>" <?php if ($reservclosed) echo " disabled"; ?>><a href="#"><span class="add-on icon-plus-sign <?php if (!$reservclosed) echo "qtyplus"; ?>" data-field="inputBaby"></span></a>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="inputReferenceResa"><?php echo $tr->translate("thReservRefer"); ?></label>
							<div class="controls">
								<select id="inputReferenceResa" name="inputReferenceResa" <?php if ($reservclosed) echo "disabled"; ?>>
									<option></option>
									<?php $arrRef = explode(",", $config['reserv_reference']);
										foreach($arrRef as $ref) { ?>
											<option value="<?php echo $ref; ?>" <?php if ($ref == $arrReservation[0]->reference) echo " selected"; ?>><?php echo $ref; ?></option>
									<?php } ?>
								</select>
								<button type="button" name="editResaReference" id="editResaReference" class="btn btn-info btn-mini"><?php echo $tr->translate("btnEdit"); ?></button>
							</div>
						</div> 				
					</div>
				</div> 				
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="inputCommentReserv"><?php echo $tr->translate("thReservComment"); ?></label>
							<div class="controls">
							<textarea class="span6" id="inputCommentReserv" name="inputCommentReserv" rows="6" <?php if ($reservclosed) echo "disabled"; ?>><?php echo $arrReservation[0]->comment; ?></textarea>
							</div>
						</div>
					</div>
				</div>
				<div class="progress">
				  <div class="bar" style="width: 100%"></div>
				</div>

				<h3><?php echo $tr->translate("thReservResume"); ?></h3>
				<div class="row-fluid">
					<div class="span4">
						<div class="row-fluid">
							<div class="control-group">
								<label class="control-label" for="labelDays"><?php echo $tr->translate("Days"); ?></label>
								<div class="controls" id="labelDays" name="labelDays">
									<h3>15<small> <?php echo $tr->translate("thReservDays"); ?></small></h3>
								</div>
							</div>
						</div>
					</div>
					<div class="span4">
						<div class="row-fluid">
							<div class="control-group">
								<label class="control-label" for="labelPrice"><?php echo $tr->translate("Price"); ?></label>
								<div class="controls" id="labelPrice" name="labelPrice">
									<h3>0<small>.00 <?php echo $config['currency_symbol']; ?></small></h3>
								</div>
							</div>
						</div>
					</div>
				</div>
				<hr>
				<div class="row-fluid">
					<div class="span12">
						<div class="row-fluid">
							<div class="control-group">
								<label class="control-label" for="labelTotal"><?php echo $tr->translate("Total"); ?></label>
								<div class="controls" id="labelTotal" name="labelTotal">
									<h1>0<small>.00 <?php echo $config['currency_symbol']; ?></small></h1>
								</div>
							</div>
						</div>
					</div>
				</div>

				<?php if (!$add) { ?>
				<div class="progress">
				  <div class="bar" style="width: 100%"></div>
				</div>

	<?php } ?>
				<div class="row-fluid">
					<div class="span12">
						<fieldset>
						<div class="control-group">
						<div class="form-actions">
						<?php if ($add) { ?>
							<button type="btn" name="ADD_RESERV" id="add" class="btn btn-primary"><?php echo $tr->translate("btnAdd"); ?></button>
						<?php }else{ ?>
						<?php if (!$reservclosed) { ?>
							<button type="btn" name="UPDATE_RESERV" id="update" class="btn btn-primary"><?php echo $tr->translate("btnSave"); ?></button>
						<?php } ?>
							<button type="button" name="delete" id="delete" class="btn btn-danger" onclick="goAction('DELETE_RESERV');"><?php echo $tr->translate("btnDelete"); ?></button>
						<?php } ?>
						</div>
						</div>
					</fieldset>
					</div>
				</div>
			</form>
			</div>
		</div><!--/span-->
	</div>
	<?php if (!$add) { ?>
	<div class="row-fluid sortable">
		<div class="box span6">
			<div class="box-header well" data-original-title>
				<h2><?php echo $tr->translate("Payments"); ?></h2>
			</div>
			<div class="box-content">
			<div class="table-responsive">
				<table id="tableReservPayments" name="tableReservPayments" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
							<th><?php echo $tr->translate("thPaymentDate"); ?></th>
							<th><?php echo $tr->translate("thPaymentType"); ?></th>
							<th><?php echo $tr->translate("thPaymentMethod"); ?></th>
							<th><?php echo $tr->translate("thPaymentAmount"); ?></th>
						</tr>
					</thead>   
					<tbody>
					<?php
						$totalPrice = 0;
						foreach ($arrPayment as $payment) {
							$totalPrice += $payment->amount;
					?>
						<tr>
							<td><?php echo date($config['date_format'], strtotime($payment->payment_date)); ?></td>
							<td><?php echo $payment->type; ?></td>
							<td><?php echo $payment->method; ?></td>
							<td class="center"><?php echo $payment->amount . " " . $config['currency_symbol']; ?></td>
						</tr>
					<?php } ?>
					</tbody>
					<tfoot>
						<tr>
							<th><?php echo $tr->translate("thPaymentTotal"); ?></th>
							<th></th>
							<th></th>
							<th><?php echo $totalPrice . " " . $config['currency_symbol']; ?></th>
						</tr>
					</tfoot>
				</table>
				</div>
			</div>
		</div>
	</div>
	<?php } ?>
	<?php } ?>

<?php require "../_container/container_bottom.php"; ?> 
<script>

	$(document).ready(function() {
	// var startDate = moment("<?php echo ((empty($arrReservation[0]->arrival_date)) ? date("Y-m-d H:i") : $arrReservation[0]->arrival_date) ?>");
	// var endDate = moment("<?php echo ((empty($arrReservation[0]->departure_date)) ? date("Y-m-d H:i", strtotime("+14 day")) : $arrReservation[0]->departure_date) ?>");
	var startDate = moment("<?php echo ((empty($arrReservation[0]->arrival_date)) ? roundDate(date("Y-m-d H:i"), $config['reserv_hour_increment']) : $arrReservation[0]->arrival_date) ?>").format("<?php echo $config['date_format_js_moment']; ?>");
	var endDate = moment("<?php echo ((empty($arrReservation[0]->departure_date)) ? roundDate(date("Y-m-d H:i", strtotime("+7 day")), $config['reserv_hour_increment']) : $arrReservation[0]->departure_date) ?>").format("<?php echo $config['date_format_js_moment']; ?>");

	$('#startDate').val(startDate);
	$('#endDate').val(endDate);
// JS Round function
// var coeff = 1000 * 60 * 5;
// var date = new Date();  //or use any other date
// var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
// alert(rounded);

		// $('#reportRange span').html("[" + moment(endDate).diff(startDate, 'days') + "j] " + moment(startDate).format("<?php echo $config['date_format_js_moment']; ?>") + ' - ' + moment(endDate).format("<?php echo $config['date_format_js_moment']; ?>"));

		$("#reservationForm").validate({
			rules: {
				selectTenant:{required: true, min:1},
				inputName: {required: true},
				inputLastname: {required: true},
				startDate: {required: true},
				endDate: {required: true},
				inputAdults: {required: true, number: true, min:1},
				inputChilds: {required: true, number: true},
				inputBaby: {required: true, number: true},
				inputPriceTotal: {number: true}
				
			},
			errorPlacement: function(error, element) {
				error.appendTo($(element).parent());
			},
			messages: {
				selectTenant: {
					// min:"Please select a Tenant"
				},
				inputAdults: {
					min:"<?php echo $tr->translate("msgUserformSelectAdult"); ?>"
				}
			}
		});
		<?php if (!$add) { ?>
			$('#knownTenant').show();
			$('#newTenant').hide();
		<?php }else{ ?>
			$('#knownTenant').hide();
			$('#newTenant').show();
		<?php } ?>
		priceCalc();
	});

	$("#add, #update").click(function(e){
		// e.preventDefault();
		if (($("input[name='radioTenant']:checked").val() == "yes") && ($('#selectTenant').val() == 0 || $('#selectTenant').val() == null)){
			$('#selectTenant').validate();
			alert("<?php echo $tr->translate("SelectTenant"); ?>");
			return false;
		}
		if ($('#selectTenancy').val() == 0 || $('#selectTenancy').val() == null){
			alert("<?php echo $tr->translate("SelectTenancy"); ?>");
			return false;
		}
		if ($('#startDate').val() != '' && $('#endDate').val() != '') {
			var start = moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");
			var end = moment($('#endDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");

			if (!(moment(start).isValid())){
				alert("<?php echo $tr->translate("msgUserformInvalidStartDate"); ?>");
				return false;
			}
			if (!(moment(end).isValid())){
				alert("<?php echo $tr->translate("msgUserformInvalidEndDate"); ?>");
				return false;
			}

			if (moment(end).isBefore(start)) {
				alert("<?php echo $tr->translate("msgUserformEndBeforeStart"); ?>");
				return false;
			}
			if (moment(end).isSame(start)) {
				alert("<?php echo $tr->translate("msgUserformSameDate"); ?>");
				return false;
			}
			var isvalidate = $("#reservationForm").valid();
			if(isvalidate){
				$('#start_date').val(start);
				$('#end_date').val(end);

				$("#reservationForm").attr("action", "reservation.php");
				$("#action").val($(this).attr("name"));
				blockUI();
			}else{
				e.preventDefault();
				return false;
			}
		}
	});

	$(".tenantRadio").click(function(){
		switch($(this).val()) {
			case "yes":
				$('#newTenant').hide();
				$('#knownTenant').show();
				break;
			case "no":
				$('#knownTenant').hide();
				$('#newTenant').show();
				break;
			default:
				$('#knownTenant').hide();
				$('#newTenant').show();
				break;
		}
	});
	function goAction(action) {
		if (action == "PREVIEW_LEASE") {
			$("#reservationForm").attr("action", "leasePreview.php");
			// $("#action").val("preview");
			// $("#selectTenancy").val("0");
			reservationForm.submit();
			$("#reservationForm").attr("action", "reservation.php");
		}
		if (action == "DELETE_RESERV") {
			$("#action").val(action);
			// $('#content').slideUp("slow");
			blockUI();
			reservationForm.submit();
		}
		if (action == "SET_LEASE_DATE") {
			$("#reservationForm").attr("action", "index.php");
			$("#action").val(action);

			// var lease_date = moment($("#leaseDate").val()).format("YYYY-MM-DD HH:mm:ss");
			var lease_date = moment($('#leaseDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");
			if (!(moment(lease_date).isValid())){
				alert("<?php echo $tr->translate("msgInvalidDate"); ?>");
				return false;
			}
			$("#lease_date").val(lease_date);
			// $('#content').slideUp("slow");
			blockUI();
			reservationForm.submit();
		}
		if (action == "CLEAR_LEASE_DATE") {
			$("#reservationForm").attr("action", "index.php");
			$("#action").val(action);
			// $('#content').slideUp("slow");
			blockUI();
			reservationForm.submit();
		}
		if (action == "check_date") {
			
		}
	}

$('#editTenant').click(function(){
	if($('#selectTenant').val() > 0){
		blockUI();
		$().redirect(
			"tenantDetail.php",
			{
				'id': $('#selectTenant').val(),
				'action': "Edit"
			},
			'POST'
		);
		return false;
	}else{
		alert("<?php echo $tr->translate("SelectTenant"); ?>");
		return false;
	}
});
$('#editTenancy').click(function(){
	if($('#selectTenancy').val() > 0){
		blockUI();
		$().redirect(
			"tenancyDetail.php",
			{
				'id': $('#selectTenancy').val(),
				'action': "Edit"
			},
			'POST'
		);
		return false;
	}else{
		alert("<?php echo $tr->translate("SelectTenancy"); ?>");
		return false;
	}
});
$('#editResaReference, #editTenantReference').click(function(){
	blockUI();
	$().redirect(
		"config.php",
		{
		},
		''
	);
	return false;
});

$('#selectTenancy').change(function(){
	$("#dateresult").remove();
	$("#checkDate").removeClass("btn-success").removeClass("btn-danger").addClass("btn-warning");
	$.ajax({ url: 'ajaxFnc.php',
			beforeSend: function(){
				$("#tenancyLoading").removeClass("hide").show();
			},
			 data: {
				func: 'getTenancy',
				tenancyid: $('#selectTenancy').val()
			},
			type: 'POST',
			success: function(output) {
				var obj = eval('(' + output + ')');
				$.each($.parseJSON(output), function(idx, resa){
					$("#inputVat").val(resa.vat);
				});
				$("#tenancyLoading").hide();
			},
			error:function(xhr, ajaxOptions, thrownError){
			}
		});

});
$('#endDate').change(function(){
	$("#dateresult").remove();
	$("#checkDate").removeClass("btn-success").removeClass("btn-danger").addClass("btn-warning");
	priceCalc();
});
$('#startDate').change(function(){
	$("#dateresult").remove();
	$("#checkDate").removeClass("btn-success").removeClass("btn-danger").addClass("btn-warning");
	newDate = moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>").add('days', 7).format("<?php echo $config['date_format_js_moment']; ?>");
	$('#endDate').val(newDate);
	priceCalc();
});

$("#uploadfile").click(function(e){
	e.preventDefault();
	if ($("#uploadfile_Path").val() != '') {
		$('#reservationForm').attr("enctype", "multipart/form-data");
		$("#action").val("SEND_LEASE_FILE");
		reservationForm.submit();
	}else{
		alert("<?php echo $tr->translate("ChooseFileTitle"); ?>");
		return false;
	}
});
$("#checkDate").click(function(e){
	var ori = $(this).html();
	$("#dateresult").remove();
	$("#checkDate").removeClass("btn-success").removeClass("btn-danger").addClass("btn-warning");

	$(this).html('<img src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/ajax-loaders/ajax-loader.gif" />');
	
	$.ajax({ url: 'ajaxFnc.php',
			 data: {
				func: 'isReservationAvailable',
				start_date: moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss"),
				end_date: moment($('#endDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss"),
				// start_date: moment(startDate).format("YYYY-MM-DD HH:mm:ss"),
				// end_date: moment(endDate).format("YYYY-MM-DD HH:mm:ss"),
				tenancyid: $('#selectTenancy').val(),
				reservationid: <?php if (isset($arrReservation[0]->reservation_id)) {echo $arrReservation[0]->reservation_id;}else{echo "0";} ?>
			},
			type: 'POST',
			success: function(output) {
				var res = "";
				var obj = eval('(' + output + ')');
				var objCount = 0;
				for(_obj in obj) objCount++;
				if (objCount == 0) {
					$("#checkDate").html(ori);
					$("#checkDate").removeClass("btn-warning").addClass("btn-success");
				}else{
				res += '<div class="box-content">'+
				'<div>'+
				'<table id="tableReservAvailability" name="tableReservAvailability" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">'+
				  '<thead>'+
					  '<tr>'+
						  '<th><?php echo $tr->translate("ID"); ?></th>'+
						  '<th><?php echo $tr->translate("thReservTenancy"); ?></th>'+
						  '<th><?php echo $tr->translate("thReservLastName"); ?></th>'+
						  '<th><?php echo $tr->translate("thReservName"); ?></th>'+
						  '<th><?php echo $tr->translate("thReservFrom"); ?></th>'+
						  '<th><?php echo $tr->translate("thReservTo"); ?></th>'+
						  '<th><?php echo $tr->translate("Days"); ?></th>'+
						  '<th><?php echo $tr->translate("Price"); ?></th>'+
						  '<th><?php echo $tr->translate("Status"); ?></th>'+
					  '</tr>'+
				  '</thead>'+
				  '<tbody>';
					$.each($.parseJSON(output), function(idx, resa){
					res += '<tr id="' + resa.reservation_id + '">'+
						'<td>' + resa.reservation_id + '</td>'+
						'<td>' + resa.tenancy_name + '</td>'+
						'<td>' + resa.tenant_lastname + '</td>'+
						'<td>' + resa.tenant_name + '</td>'+
						'<td>' + moment(resa.arrival_date).format("<?php echo $config['date_format_js_moment']; ?>") + '</td>'+
						'<td>' + moment(resa.departure_date).format("<?php echo $config['date_format_js_moment']; ?>") + '</td>'+
						'<td>' + moment(resa.departure_date).diff(resa.arrival_date, 'days') + '</td>'+
						'<td>' + resa.price + '</td>'+
						'<td>' + resa.status + '</td>'+
					'</tr>';

						// res += "<br>ID: " + resa.reservation_id + "<br>";
						// res += "<?php echo $tr->translate("thReservLastName"); ?>: " + resa.tenant_lastname + " " + resa.tenant_name + "<br>";
						// res += "<?php echo $tr->translate("thReservFrom"); ?>/<?php echo $tr->translate("thReservTo"); ?>: " + moment(resa.arrival_date).format("<?php echo $config['date_format_js_moment']; ?>") + " ==> " + moment(resa.departure_date).format("<?php echo $config['date_format_js_moment']; ?>") + "<br>";
						// res += "<?php echo $tr->translate("thReservStatus"); ?>: " + resa.status + "<br>";
					});
					res += '</tbody>'+
			  '</table>'+
			  '</div>';

					$("#checkDate").html(ori).after("<span id='dateresult'>"+res+"</span>");
					$("#checkDate").removeClass("btn-warning").addClass("btn-danger");
				}
			},
			error:function(xhr, ajaxOptions, thrownError){
				$("#checkDate").html(ori).after("<span id='dateresult'><br><?php echo $tr->translate("msgErrorCheckDate"); ?><br>"+ajaxOptions+": "+thrownError+"</span>");
			}
	});
});

$("#leasePreview").click(function(){
	$().redirect(
		"filePreview.php",
		{
			'id': $(this).attr("_id")
		},
		'POST'
	);
	return false;
});

$('#inputPriceTotal').on('input', priceCalc);

function priceCalc() {
	var totalPrice = 0;
	var totalTotal = 0;
	var substr;
	if ($("#inputPriceTotal").val()) {
		totalPrice = parseFloat($("#inputPriceTotal").val());
	}

	totalPrice = totalPrice.toFixed(2);
	substr = totalPrice.toString().split('.');
	$("#labelPrice").html("<h3>" + substr[0] + "<small>." + substr[1] +" <?php echo $config['currency_symbol']; ?></small></h3>");

	totalTotal = parseFloat(totalPrice);
	totalTotal = totalTotal.toFixed(2);
	substr = totalTotal.toString().split('.');
	$('#labelTotal').html("<h1>" + substr[0] + "<small>." + substr[1] +" <?php echo $config['currency_symbol']; ?></small></h1>");

	var start = moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>");
	var end = moment($('#endDate').val(),"<?php echo $config['date_format_js_moment']; ?>");
	if (start && end) {
		nbdays = end.diff(start, 'days');
	}else{
		nbdays = 0;
	}
	$('#labelDays').html("<h3>" + nbdays + "<small> <?php echo $tr->translate("thReservDays"); ?></small></h3>");
}

</script>
