<?php
$optres ['css'][] = $module_css_path . "amodules/booking_search/css/find_hotels.css";

$book_title = '';
$book_text = '';
$aff_code = 'BOOKING000000002';
$hotel_aff_location = 'Limassol';

$destinations = array();
$regions = array();

$q = "SELECT * FROM `booking_destinations` where country_code='cy' order by full_name asc;";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) > 0) {
	while ($row = mysql_fetch_assoc($r)) {
		$destinations [] = array_map('stripslashes', $row);
	}
}

$q = "SELECT * FROM `booking_regions` where country_code='cy' order by region_name asc;";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) > 0) {
	while ($row = mysql_fetch_assoc($r)) {
		$regions [] = array_map('stripslashes', $row);
	}
}

?>

<div id="booking-search-container">
	<?php
	/*
	<h2 class="wb_h2"><?php echo $book_title;?></h2>
	*/
	if($book_title != "") {
		echo '<span class="book_title">' . $book_title . '</span><br/>';
	}
	
	if($book_text != "") {
		echo '<span class="book_text">' . $book_text . '<br/></span>';
	}
	?>
	<form id="booking-search" action="">
		<?php
		$def_checkin = date("d/m/Y", strtotime("+1 day"));
		$def_checkout = date("d/m/Y", strtotime("+2 day"));
		$def_rooms = 1;
		$def_adults = 2;
		$def_children = 0;
		$min_checkout_date = date("d/m/Y", strtotime("+2 day"));
		$max_checkout_date = date("d/m/Y", strtotime("+29 day"));
		if(isset($_SESSION['hotel_search']) && isset($_SESSION['hotel_search']['checkin']) && trim($_SESSION['hotel_search']['checkin']) != ""){
			$def_checkin = $_SESSION['hotel_search']['checkin'];
			$dt = DateTime::createFromFormat('d/m/Y', $def_checkin);
			$dt_reg = strtotime($dt->format('Y-m-d'));
			$min_checkout_date = date("d/m/Y", strtotime('+1 day', $dt_reg));
			$max_checkout_date = date("d/m/Y", strtotime('+28 day', $dt_reg));
			
		}
		if(isset($_SESSION['hotel_search']) && isset($_SESSION['hotel_search']['checkout']) && trim($_SESSION['hotel_search']['checkout']) != ""){
			$def_checkout = $_SESSION['hotel_search']['checkout'];
		}
		if(isset($_SESSION['hotel_search']['adults']) && intval($_SESSION['hotel_search']['adults']) >0){
			$def_adults = intval($_SESSION['hotel_search']['adults']);
		}
		?>
		<div class="checkinout">
			<h1 class="book-header fldst first">Cyprus Hotels<small>Find Hotels In Cyprus</small></h1>
			<span class="fldst  first region">
				<label class="dest" for="checkin">Resort Area</label>
				<select id="ck-dest" class="text ck-dest" name="ck_dest">
					<option value="" selected="selected">-</option>
					<optgroup label="Regions">
						<?php
						foreach ($regions as $i=>$data) {
							echo '<option value="', $data['region_name'], '">', $data['region_name'], '</option>';
						}
						?>
					</optgroup>
					<optgroup label="Destinations">
						<?php
						foreach ($destinations as $i=>$data) {
							echo '<option value="', $data['full_name'], '">', $data['full_name'], '</option>';
						}
						?>
					</optgroup>
				</select>
			</span>
		</div>
		<div class="checkinout">
			
			<span class="fldst first last">
				<label id="lbl_checkIn" for="checkin">Check In</label>
				<input type="text" id="checkin" value="<?php echo $def_checkin;?>" class="sprite-calendar-ylw text datepicker checkin" name="checkin"/>
			</span>
			<span class="fldst last chk-out cal ">
				<label id="lbl_checkOut" for="checkout">Check Out</label>
				<input type="text" id="checkout" value="<?php echo $def_checkout;?>" class="sprite-calendar-ylw text datepicker checkout" name="checkout"/>
			</span>
			<div id="book-details">
				<span class="fldst last rooms">
					<label for="rooms">Rooms</label> 
					<select id="main_rooms" name="rooms" onchange="">
					<?php
					$rooms_array = array(1,2,3,4,5,6,7,8,9,10);
					
					foreach ($rooms_array as $rooms_cnt) {
						$selected = '';
						if($def_rooms == $rooms_cnt) {
							$selected = 'selected="selected"';
						}
						echo '<option value="'.$rooms_cnt.'" '.$selected.'>'.$rooms_cnt.'</option>';
					}
					?>
					</select>
				</span>
				<span class="fldst last adults">
					<label for="adults">Adults</label> 
					<select id="main_adults" name="adults" onchange="">
					<?php
					$adults_array = array(1,2,3,4);
					
					foreach ($adults_array as $adults_cnt) {
						$selected = '';
						if($def_adults == $adults_cnt) {
							$selected = 'selected="selected"';
						}
						echo '<option value="'.$adults_cnt.'" '.$selected.'>'.$adults_cnt.'</option>';
					}
					?>
					</select>
				</span>
				<span class="fldst last children">
					<label for="children">Children</label> 
					<select id="main_children" name="children" onchange="">
					<?php
					$children_array = array(0,1,2,3,4,5,6,7,8,9,10);
					
					foreach ($children_array as $children_cnt) {
						$selected = '';
						if($def_children == $children_cnt) {
							$selected = 'selected="selected"';
						}
						echo '<option value="'.$children_cnt.'" '.$selected.'>'.$children_cnt.'</option>';
					}
					?>
					</select>
				</span>
			</div>
			<div class="aff_providers_container">
				<div class="aff-partner-button">
					<div class="find-hotels" rel="<?php echo $aff_code;?>">
						Search
					</div>
				</div>
			</div>
		</div>
		<div class="extra" id="extra-rooms">
			<span class="fldst last children">
					<label for="children">Children</label> 
					<select id="children" name="children" onchange="">
					<?php
					$children_array = array(0,1,2,3,4,5,6,7,8,9,10);
					
					foreach ($children_array as $children_cnt) {
						$selected = '';
						if($def_children == $children_cnt) {
							$selected = 'selected="selected"';
						}
						echo '<option value="'.$children_cnt.'" '.$selected.'>'.$children_cnt.'</option>';
					}
					?>
					</select>
				</span>
		</div>
		
		<div style="clear: both;"></div>
	</form>
</div>
<script type="text/javascript">

	var guests = {
		'rooms':1,
		'adults': 2,
		'children':0,
		'rep': [
				{
					'adults':2,
					'children':0
				}
			]
		,
		'children_age': []
	};

	var roomStr = 'Rooms';

	function open_popup(url, win, specs) {
		var new_win = window.open(url, win, specs + "menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes");
	}

	$(document).ready(function(){
		
		var roomRowHtml = '<tr class="roomRow"><td valign="top" class="roomNum">'+roomStr+' 0</td><td valign="top"><select name="group_adults"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select></td><td valign="top"><select name="group_children"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select></td><td valign="top" class="childrenAge"></td></tr>';
		var childrenInput = '<input name="age" value="" /> ';
		var selectMainRooms = $("select#main_rooms");
		var selectMainAdults = $("select#main_adults");
		var selectMainChildren = $("select#main_children");
		var roomContainer = $('#hotel_form_rooms_infos');
			$("#hotel_form_rooms_infos_container .button").click( function() {
			$("#hotel_form_rooms_infos_container").hide(100);
		});
		selectMainRooms.change(function () {
			var numRooms = $('#hotel_form_rooms_infos tr.roomRow').length;
			var rooms = selectMainRooms.val();
			var adults = selectMainAdults.val();
			var children = selectMainChildren.val();
			var myregexp = new RegExp(eval('/'+roomStr+' [0-9]{1,2}/'));
			var total = 0;
			if ( rooms > numRooms ) {
			for (i=numRooms; i<rooms; i++) {
			roomRowHtml = roomRowHtml.replace(myregexp, roomStr+" " + parseInt(i+1));
			roomContainer.append(roomRowHtml);
			}
			}
			else{
			while ( rooms < numRooms ) {
			roomContainer.find("tr.roomRow").last().remove();
			numRooms = $('#hotel_form_rooms_infos tr.roomRow').length;
			}
			}
			var selectGroupAdults = $("select[name=group_adults]");
			var selectGroupChildren = $("select[name=group_children]");
			selectMainAdults.change(function () {
			adults = selectMainAdults.val();
			adultsPerRoom = Math.floor(adults / rooms);
			selectGroupAdults.val(adultsPerRoom);
			adultsPerRoomRest = adults % rooms;
			selectGroupAdults.each(function() {
			if ( adultsPerRoomRest > 0 ) {
			$(this).val(parseInt($(this).val())+1);
			adultsPerRoomRest--;
			}
			});
			showRoomsInfos();
			});
			selectMainAdults.trigger("change");
			selectGroupAdults.off("change");
			selectGroupAdults.on("change", function() {
			adults = 0;
			selectGroupAdults.each(function() {
			adults += parseInt($(this).val());
			});
			selectMainAdults.val(adults);
			showRoomsInfos();
			});
			selectGroupChildren.off("change");
			selectGroupChildren.on("change", function() {
			total = 0;
			selectGroupChildren.each(function() {
			total += parseInt($(this).val());
			});
			selectMainChildren.val(total);
			updateChildAge($(this));
			showRoomsInfos();
			});
			selectMainChildren.off("change");
			selectMainChildren.on("change", function() {
			children = selectMainChildren.val();
			childrenPerRoom = Math.floor(children / rooms);
			selectGroupChildren.val(childrenPerRoom);
			childrenPerRoomRest = children % rooms;
			selectGroupChildren.each(function() {
			if ( childrenPerRoomRest > 0 ) {
			$(this).val(parseInt($(this).val())+1);
			childrenPerRoomRest--;
			}
			updateChildAge($(this));
			});
			showRoomsInfos();
			});
			selectMainChildren.trigger("change");
			showRoomsInfos();
			function showRoomsInfos() {
			var rooms = selectMainRooms.val();
			var adults = selectMainAdults.val();
			var children = selectMainChildren.val();
			if ( ( children > 0 ) || ( rooms > 1 && adults > 4)){
			$("#hotel_form_rooms_infos_container").show(100);
			}else
			{
			$("#hotel_form_rooms_infos_container").hide(100);
			}
			}
			function updateChildAge(childrenSelect) {
			var numChildren = $("td.childrenAge input",childrenSelect.parent().parent()).length;
			var children = childrenSelect.val();
			if ( children > numChildren ) {
			for (i=numChildren; i<children; i++) {
			$("td.childrenAge",childrenSelect.parent().parent()).append(childrenInput);
			}
			}
			else{
			while ( children < numChildren ) {
			$("td.childrenAge input",childrenSelect.parent().parent()).last().remove();
			numChildren = $("td.childrenAge input",childrenSelect.parent().parent()).length;
			}
			}
			}
		});
		selectMainChildren.off("change");
		selectMainChildren.on("change", function() {
		selectMainRooms.trigger("change");
		});
		selectMainRooms.trigger("change");
		});
		$(document).ready( function(){
		$('nav li.parent').each(function() {
		var $this = $(this);
		var $a = $this.find('a:first');
		var $ul = $this.find('ul');
		if ($a.is(':visible'))
		$ul.hide();
		if (Modernizr.touch) {
		$a.on('click touchstart', function(event) {
		event.stopImmediatePropagation();
		event.preventDefault();
		if ($a.is(':visible')) {
		if($ul.is(':visible'))
		$ul.hide();
		else {
		$('nav li.parent a:visible + ul').not($ul).hide();
		$ul.show();
		}
		}
		return false;
		});
		$ul.find('a').on('click', function(event) {
		$ul.hide();
		});
		}
		else {
		$this.bindDelayed('mouseenter', function(event) {
		if ($a.is(':visible')) {
		$ul.slideDown(50);
		}
		}, 0, 'mouseleave');
		$this.bindDelayed('mouseleave', function(event) {
		if ($a.is(':visible')) {
		$ul.slideUp(50);
		}
		}, 200, 'mouseenter');
		}
		$(window).on('resize', function(event) {
		if (!$a.is(':visible')) {
		$ul.show();
		}
		});
		});
		if(Modernizr.touch) {
		$('nav li.parent ul a').on('touchstart' , function(event) {
		event.stopPropagation();
		});
		$(document).on('touchstart',function(event) {
		$('nav li.parent a:visible + ul').hide();
		});
		}
		
		
		/*
		$('#children').change(function(){
			var kids = parseInt($(this).val(), 10);
			console.log(kids);
			if(kids > 0) {
				
				guests.children = kids;
				
				$('#extra-rooms').show();
			}
			else {
				$('#extra-rooms').hide();
			}
		});
		*/
		
		
		// Dates
		$( "#checkin" ).datepicker({
			//defaultDate: "+1w",
			minDate: '<?php echo (isset($_SESSION['hotel_search']['checkin'])) ? $_SESSION['hotel_search']['checkin'] : date("d/m/Y", strtotime("+1 day"));?>',
			changeMonth: true,
			numberOfMonths: 2,
			dateFormat: 'dd/mm/yy',
			onClose: function( selectedDate, dtp ) {
				$("#checkin, #checkout").css({'z-index': '1'});
			},
			onSelect: function( selectedDate, dtp ) {
				$(this).css({'z-index': '9999'});
				var curDate = $(this).datepicker( "getDate" );
				var chekout_min_date = new Date();
				var chekout_max_date = new Date();
				chekout_min_date.setTime(curDate.getTime()+ 1 * 24 * 60 * 60 * 1000);
				chekout_max_date.setTime(curDate.getTime()+ 28 * 24 * 60 * 60 * 1000);
				
				setTimeout(function(){
		            $( "#checkout" ).datepicker("show");
		        }, 16); 
				
				/*
				console.log(selectedDate);
				console.log(curDate);
				console.log(chekout_min_date);
				console.log(chekout_max_date);
				*/
				
				$( "#checkout" ).datepicker( "option", "minDate", chekout_min_date );
				$( "#checkout" ).datepicker( "option", "maxDate", chekout_max_date );
			}
		});
		$( "#checkout" ).datepicker({
			//defaultDate: "+1w",
			minDate: '<?php echo (isset($_SESSION['hotel_search']['checkin'])) ? $min_checkout_date : date("d/m/Y", strtotime("+2 day"));?>',
			maxDate: '<?php echo (isset($_SESSION['hotel_search']['checkin'])) ? $max_checkout_date : date("d/m/Y", strtotime("+29 day"));?>',
			changeMonth: true,
			numberOfMonths: 2,
			dateFormat: 'dd/mm/yy',
			onClose: function( selectedDate, dtp ) {
				$("#checkin, #checkout" ).css({'z-index': '1'});
			},
			onSelect: function( selectedDate, dtp ) {
				$(this).css({'z-index': '9999'});
				//$( "#checkin" ).datepicker( "option", "maxDate", selectedDate );
			}
		});
		
		$('#ui-datepicker-div').wrap('<div class="booking-search"></div>');
		
		$('.find-hotels').each(function(){
			$(this).click(function(){
			
				var $frm = $('#booking-search');
				var hotel_data = $(this).attr('rel') + '|' + ($('#ck-dest').val());
				$.ajax({
					url: 'http://<?php echo $_SERVER['HTTP_HOST'];?>/amodules/client_stand/aff/aff_jump.php',
					data: $frm.serialize() + '&current_affiliate=' + hotel_data + '&act=find-hotels',
					async: false,
					cache: false,
					dataType: 'json',
					type: 'post',
					success: function(r) {
						if(r != null) {
							open_popup(r.url, r.affiliate, 'left=' + 20 + ',width=' + ($(window).width() -40) + ',height=' + ($(window).height() - 40) + ',top=20,');
						}
					}
				});
			});
		});
	});
</script>