<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );

	require('includes/application_top.php');
	include(DIR_WS_CLASSES . 'order.php');
	include(DIR_WS_CLASSES . 'currencies.php');
	include(DIR_WS_FUNCTIONS . 'events_sessions.php');

	$currencies=new currencies();
	$step=isset($HTTP_POST_VARS['step'])?$HTTP_POST_VARS['step']:2;
	$oId=isset($HTTP_GET_VARS['oID'])?(int)$HTTP_GET_VARS['oID']:0;
	$eId=isset($HTTP_GET_VARS['eId'])?(int)$HTTP_GET_VARS['eId']:0;
	$id=isset($HTTP_GET_VARS['id'])?(int)$HTTP_GET_VARS['id']:0;
	$mode=isset($HTTP_GET_VARS['mode'])?$HTTP_GET_VARS['mode']:'';

	// fetch the event_id if id is provided
	if ($id>0){
		$event_id_query=tep_db_query("SELECT events_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_products_id='" . (int)$id . "' and op.products_type='E' and op.products_id=s.sessions_id");
		$event_id_result=tep_db_fetch_array($event_id_query);
		$eId=(int)$event_id_result["events_id"];
		
	}
	$edit_cart=new editOrderCart($oId);

	$page_params="oID=" . $oId;
	$edit_mode=false;	

	$events_id=isset($HTTP_POST_VARS['events_name'])?(int)$HTTP_POST_VARS['events_name']:0;
	$start_date=isset($HTTP_POST_VARS['start_date'])?$HTTP_POST_VARS['start_date']:'';
	$sessions_id=isset($HTTP_POST_VARS['sessions_id'])?(int)$HTTP_POST_VARS['sessions_id']:0;
	$no_attendees=isset($HTTP_POST_VARS["no_attendees"])?(int)$HTTP_POST_VARS['no_attendees']:0;

	
	if (isset($HTTP_GET_VARS["check"])){
		$events_id=isset($HTTP_GET_VARS['param_1'])?(int)$HTTP_GET_VARS['param_1']:0;
		$sessions_id=isset($HTTP_GET_VARS['param_2'])?(int)$HTTP_GET_VARS['param_2']:0;
		$step=3;
	}
	if(isset($HTTP_GET_VARS['opID']) && $HTTP_GET_VARS['opID']>0){
		tep_db_query("delete from ".TABLE_ORDERS_EDIT_PRODUCTS." where orders_products_id='".$HTTP_GET_VARS['opID']."'");
	}
	// check if events id is present and mode is edit
	if ($eId>0 && $mode=="edit"){
		$events_id=$eId;
		// get the dates of selected event to edit
		$check_dates_query=tep_db_query("SELECT s.start_date,s.sessions_id,op.events_type,op.waitlist_type from " . TABLE_ORDERS_EDIT_PRODUCTS .
										" op," . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . (int)$events_id . "' and op.orders_id='" . (int)$oId . "'  and s.sessions_id=op.products_id order by s.start_date");
		if (tep_db_num_rows($check_dates_query)<=0) tep_redirect("orders.php");
		$edit_dates=array();
		while($check_dates_result=tep_db_fetch_array($check_dates_query)){
			$edit_dates[$check_dates_result["sessions_id"]]=array('id'=>$check_dates_result["sessions_id"],"date"=>$check_dates_result["start_date"],
																	'type'=>$check_dates_result["events_type"],'waitlist_type'=>$check_dates_result["waitlist_type"]);
		}
		$step=3;
		$page_params.="&mode=update";
		$edit_mode=true;
	}
	if ($step>4){
		// update the selected event
		$session_array=&$HTTP_POST_VARS['select_dates']; // get selected dates to update
		$select_ids=&$HTTP_POST_VARS["sessions_id"]; // get selected session_ids
		$reserve_type=(isset($HTTP_POST_VARS['reserve_type'])?$HTTP_POST_VARS['reserve_type']:"M"); // identify if order contains only products or only events or both
			$no_attendees=isset($HTTP_POST_VARS["no_attendees"])?(int)$HTTP_POST_VARS['no_attendees']:0;

		if ($sessions_id>0 || is_array($select_ids)==true){
			// select event details
			$result=tep_db_query("SELECT e.events_id,e.events_tax_class_id,e.events_fees,ed.events_name,e.events_location,e.events_start_time,e.waitfee_vip,e.waitfee_custom,e.waitfee_firstcome,e.session_style FROM " . TABLE_EVENTS . " e," . TABLE_EVENTS_DESCRIPTION. " ed  where e.events_id=". (int)$events_id." and e.events_id=ed.events_id and ed.language_id='" . (int)$languages_id . "'");
			
			$Order = tep_db_fetch_array($result);
			
			$sInfo=new objectInfo($Order);
			
			$event_location=tep_get_locations_name($sInfo->events_location);
			$product_name=tep_get_events_display_text($sInfo->events_name,"","");
			$product_tax=tep_get_tax_rate($sInfo->events_tax_class_id);
			$product_quantity=1;
			$product_type='E';
			$events_type="";
			$waitlist_style=false;
			
			$order_detail=new order($oID);
			$CountryID = tep_get_country_id($order_detail->billing["country"]);
			$ZoneID = tep_get_zone_id($CountryID, $order_detail->billing["state"]);
			$product_tax = tep_get_tax_rate($sInfo->events_tax_class_id, $CountryID, $ZoneID); 
			
			// check the current sessions are already added
			$check_ids=array();
			if ($mode!="update"){
				$check_query=tep_db_query("SELECT products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oId . "'");
				while($check_result=tep_db_fetch_array($check_query)){
					$check_ids[$check_result["products_id"]]=1;
				} 
			} else {
				// delete the current event dates if the mode is edit
				$get_ids_query=tep_db_query("SELECT op.orders_products_id from " . TABLE_ORDERS_EDIT_PRODUCTS .
										" op," . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . (int)$events_id . "' and op.orders_id='" . (int)$oId . "' and s.sessions_id=op.products_id");
				$delete_ids="";
				while($get_ids_result=tep_db_fetch_array($get_ids_query)){
					$delete_ids.=$get_ids_result["orders_products_id"] . ",";
				}
				if (strlen($delete_ids)>1){
					$delete_ids=substr($delete_ids,0,-1);
					tep_db_query("DELETE from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_products_id in(" . $delete_ids . ")");
				}
			}
			// iterate with seleected dates
			for ($icnt=0;$icnt<sizeof($select_ids);$icnt++){
				if (isset($session_array[$select_ids[$icnt]]) && !isset($check_ids[$select_ids[$icnt]])){
					$session=&$session_array[$select_ids[$icnt]];
					$product_price=0;
					$original_fees=0;
					if ($reserve_type=="W") $session["type"]="W";
					//if the session type is reserve calculate amount from events fees
					if ($session['type']=="R"){
						$product_price=$sInfo->events_fees-tep_get_discount_price($sInfo->events_id,$sInfo->events_fees,$session_date_array[$icnt]);
						$original_fees=$product_price;
					} else {
						// if session waiting list style is Event then waitlist fee is for all the selected sessions
						if ($sInfo->session_style=='S' || ($sInfo->session_style=='E' && $waitlist_style==false)){
							switch($session['group']){
								case 'V':
									$product_price=$sInfo->waitfee_vip;
									break;
								case 'F':
									$product_price=$sInfo->waitfee_firstcome;
									break;
								case 'C':
									$product_price=$sInfo->waitfee_custom;
							}
							if ($sInfo->session_style=='E') $waitlist_style=true;
						}
						$original_fees=$sInfo->events_fees;
					}
					if ($session['type']=="R") $session["group"]="";
					$sql_data_array=array(
										'orders_id' => $oId,
										'products_id' => $select_ids[$icnt],
										'date_added'=>'now()',
										'products_name' => $product_name,
										'products_model'=>$session['date'],
										'products_price' => $product_price,
										'final_price' => $product_price,
										'products_type' => $product_type,
										'products_quantity'=>$no_attendees,
										'products_tax' =>$product_tax,
										'events_type' =>$session['type'],
										'waitlist_type' =>$session['group'],
										'events_fees'=>$original_fees,
										'waitlist_orders_id'=>0
										);
									//	print_r($sql_data_array);
					tep_db_perform(TABLE_ORDERS_EDIT_PRODUCTS,$sql_data_array);
					$orders_products_id=tep_db_insert_id();
			//	echo $orders_products_id.'<br>';
					$check_ids[$select_ids[$icnt]]=1;
				}
			}
			//update question answer for the selected event
			if (isset($HTTP_POST_VARS["question_type"])){
				$question_type=$HTTP_POST_VARS["question_type"];
				$question_value_data=tep_db_prepare_input($HTTP_POST_VARS["question_value_data"]);
				
				$check_query=tep_db_query("SELECT orders_id from " . TABLE_ORDERS_EVENTS_ANSWERS . " where orders_id='" . (int)$oId . "' and events_id='" . (int)$events_id ."'");
				$total_rows=tep_db_num_rows($check_query);
				if ($total_rows==0)
					tep_db_query("INSERT into " . TABLE_ORDERS_EVENTS_ANSWERS . "(orders_id,events_id,answer_type,answer_value) values('" . $oId . "','" . $events_id . "','" . $question_type . "','" . $question_value_data . "')");
				else
					tep_db_query("UPDATE " . TABLE_ORDERS_EVENTS_ANSWERS . " set answer_type='" . $question_type . "',answer_value='" . $question_value_data . "' where orders_id='" . (int)$oId . "' and events_id='" . (int)$events_id ."'");
				
			}
			if (USE_CACHE == 'true') {
				tep_reset_cache_block(TABLE_ORDERS_EDIT_PRODUCTS_ATTRIBUTES);
				tep_reset_cache_block(TABLE_ORDERS_EDIT_PRODUCTS);
			} 
		}

		if($no_attendees>1){
		   tep_redirect(tep_href_link(FILENAME_CHECKOUT_ATTENDEES, 'oID=' . $oId . '&customer_id=' . $customer_id .'&no_attendees='. ($no_attendees-1).'&opID='.$orders_products_id));
		} else {
		tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, 'oID=' . $oId . '&step=2'));
		}
	}
	$override=(isset($HTTP_POST_VARS["override_reserve"])?true:false);
	$overbook=(isset($HTTP_POST_VARS["overbook_reserve"])?true:false);
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script language="JavaScript">
	function selectEventItem(boxname,id,index){
		var element=document.getElementById(boxname+id);
		var field=document.select_event.elements[boxname+"_index"];
		field.value=index;
		field=document.select_event.elements[boxname];
		if (field.value!=''){
			document.getElementById(boxname+field.value).style.backgroundColor="#FFFFFF";
		}
		field.value=id;
		element.style.backgroundColor="#D8EDFB";
	}
	function selectSessionItem(boxname,id,index){
		var element=document.getElementById(boxname+id);
		var session_type=document.select_session.session_type.value;
		var bgcolor="#FFFFFF";
		var pindex=0;
		var index_field;

		field=document.select_session.elements[boxname+"_index"];
		if (field.value!="") pindex=parseInt(field.value);
		field.value=index;
		if (session_type!="S")
			field=document.select_session.elements[boxname+"_field"];
		else
			field=document.select_session.elements[boxname+"[]"];
		
		if (field.value!=''){
			if (sessions[pindex][3]==0) bgcolor="#F5F5F5";
			document.getElementById(boxname+field.value).style.backgroundColor=bgcolor;
		}
		element.style.backgroundColor="#D8EDFB";
		field.value=id;
		//document.select_session.sessions_count.selectedIndex=0;
		//displaySessionsCountFixed(index);
	}
	function setElementPos(){
		var boxnames=Array("events_name","sessions_id");
		var ids=Array("<?php echo $events_id;?>","<?php echo $sessions_id;?>");
		var box;
		var element;
		for (icnt=0;icnt<boxnames.length;icnt++){
			box=document.getElementById(boxnames[icnt]+"_box");
			element=document.getElementById(boxnames[icnt]+ids[icnt]);
			if (box!=null && element!=null)
				box.scrollTop=element.offsetTop;
		}
	}
	
	function sel_attendees(){
	  var val="<?php echo sizeof($edit_cart->attendees);?>";
	  var no_atten=document.select_event_attendees.no_attendees.value;
	  if(val>0){
	   if(val!=no_atten){
	    alert("Already has an event with " + val + " attendees." + " " + "Number of Attendees for this event must be equal to" + " " + no_atten );
		return false;
	   }else {
	    return true;
	   }
	  }else { 
	   return true;
	  }
	}
</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onLoad="setElementPos();">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

	<!-- body //-->
	<table border="0" width="100%" cellspacing="2" cellpadding="2">
		<tr>
 
	<!-- body_text //-->
	<?php 	$customer_find=tep_db_query("select customers_id from " . TABLE_ORDERS . " where orders_id='" . (int)$oID . "'");
			$customer_result=tep_db_fetch_array($customer_find);
			$customer_id=(int)$customer_result['customers_id'];

			if (isset($HTTP_POST_VARS['change_start_date']))
				$change_start_date=$HTTP_POST_VARS['change_start_date'];
			else 
				$change_start_date='N';
	?>

    	<td width="100%" valign="top">
			<table border="0" width="100%" cellspacing="0" cellpadding="0">
    			<tr>
					<td><table border="0" width=60% cellspacing=0 cellpadding=0 ?>
						<tr>
							<!--<td class="pageHeading"><?php //echo ($mode=="edit"?HEADING_TITLE_EDIT:HEADING_TITLE); ?> #<?php //echo $oID; ?></td>!-->
							<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', 1, HEADING_IMAGE_HEIGHT); ?></td>
							<td class="pageHeading" align="right"><?php echo '<a href="' . tep_href_link(FILENAME_EDIT_ORDERS, "oID=$oId&step=2") . '">' . tep_image_button('button_back.gif', IMAGE_BACK) . '</a>'; ?></td>
						</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '5'); ?></td>
				</tr>
				<tr>
					<td>
						<table border="0" width=100% cellspacing="0" cellpadding="1">
							<?php echo tep_draw_form("select_event",FILENAME_ADD_EVENTS,$page_params);?>
							<tr class="attributes-odd" valign="middle">
								<td class="dataTableContent" align=left height="20"><b><?php echo EVENT_STEP1; ?></b></td>
							</tr>
							  <tr>
								<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
							  </tr>
							<tr class="attributes-even">
								<td>
								<table border="0" cellpadding="2" cellspacing="0">
									<tr>
										<td class="dataTableContent" width="100"><?php echo TEXT_EVENT_NAME;?></td>
										<?php  // if the mode is not edit then displa the event select box
										if (!$edit_mode) {?>
										<td class="dataTableContent" align=left valign="middle" width="550">
											<?php $events_array=tep_get_events_info_tree($customer_id);
												  customEventListBox('events_name',$events_array,$events_id,"100%","100px");
											?>
										</td>
										<td align="center" class="main" valign="bottom">
										<table border="0" cellpadding="5" cellspacing="0">
											<?php $get_reservation_query=tep_db_query("select admin_groups_id from admin_files where admin_files_name=' override reservation' or admin_files_name=' overbook reservation'");
												  $result_array=array();
												  while($result_reservation=tep_db_fetch_array($get_reservation_query)){
												    $result_array[]=array('id'=>"," . $result_reservation['admin_groups_id'] . ",");
												  }
											 if (strpos($result_array[0]['id'],"," . $login_groups_id . ",")!==false) { ?>
												<tr>
													<td class="main" nowrap><?php echo tep_draw_checkbox_field('override_reserve','Y',$override) . TEXT_OVERRIDE_RESERVE;?></td>
												</tr>
											<?php } 
											if(strpos($result_array[1]['id'],"," .$login_groups_id .",")!==false){?>
												<tr>
													<td class="main" nowrap><?php echo tep_draw_checkbox_field('overbook_reserve','Y',$overbook) . TEXT_OVERBOOK_RESERVE;?></td>
												</tr>
											<?php }?>
												<tr>
													<td class="main" nowrap><?php echo tep_image_submit("button_select.gif",IMAGE_SELECT_EVENT);?></td>
												</tr>
										<?php } else {?>
												<td class="main" nowrap><b>
													<?php 
														echo tep_get_events_name($events_id);
													?></b>
												</td>
													<input type="hidden" name="events_name" value="<?php echo $events_id;?>">
										<?php } ?>
										</table>
									</tr>
								</table>
								</td>
							</tr>
							<input type='hidden' name='step' value='3'>
							</form>
				<?php $multiple_attendees=false;
						if ($events_id>0){
							$events_query=tep_db_query("select events_id,sessions_select_count,sessions_select_interval,sessions_date_count,events_forward_period,events_forward_length,events_max_reserve,events_overbook_reserve,waitsize_vip,waitsize_firstcome,
															waitsize_custom,priority_question,events_tax_class_id,session_style,events_fees,waitfee_vip,waitfee_firstcome,waitfee_custom,events_pending_period,session_style,session_reduction,session_gaps,events_wait_list,events_renewal_start,events_renewal_end,events_group_bookings,events_group_min,events_group_max from " . TABLE_EVENTS . " where events_id='" . (int)$events_id . "'");
							$events_result=tep_db_fetch_array($events_query);
							//echo $events_result['events_overbook_reserve'];
							//multiple attendees
							if($events_result['events_group_bookings'] =='Y')
								$multiple_attendees=true;
							
							
							}
						?>
					  <tr>
						<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
					  </tr>
						<?php 
						if ($step>2 ){
							if($multiple_attendees){
								for($icnt=$events_result['events_group_min'];$icnt<=$events_result['events_group_max'];$icnt++)
								  if($icnt) $attendees_array[]=array('id' =>$icnt,'text' =>$icnt);
							echo tep_draw_form("select_event_attendees",FILENAME_ADD_EVENTS,$page_params,'post','onsubmit="javascript:return sel_attendees();"');//onsubmit="javascript:return sel_attendees();"
							?>
							<tr class="attributes-odd" valign="middle">
								<td class="dataTableContent" align=left height="20"><b><?php echo EVENT_STEP2; ?></b></td>
							</tr>
							  <tr>
								<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
							  </tr>
							<tr>
								<td>
								<table border="0" cellpadding="0" cellspacing="0">
								<input type="hidden" name="events_name" value="<?php echo $events_id;?>">	
								<tr class="attributes-even">
									<td valign="middle" class="main">
										<?php 
											echo TEXT_MULTIPLE_ATTENDEES . '&nbsp;&nbsp;' . tep_draw_pull_down_menu('no_attendees',$attendees_array) .'&nbsp;';
										?>
									</td>
									<td class="main" valign="middle">
										<?php
											echo tep_image_submit("button_select.gif",IMAGE_SELECT_EVENT,'valign="middle"');
										?>
									</td>
								</tr>
								  <tr>
									<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
								  </tr>
								</table>
								</td>
							</tr>
							<input type='hidden' name='step' value='4'>
							</form>
				<?php 	
							} else {
								$step=4;
							}
				?>
				<?php 
						}
						if($step >3 && $events_id>0){
							$cnt=0;
							$no_attendees=$no_attendees+1;
							// fetch event details

								// fetch question details for the current event if present
								$question_query=tep_db_query("SELECT q.question_title,q.question_description,q.answer_type,q.question_id from " . TABLE_EVENTS . " e, " . TABLE_POP_QUESTIONS .  " q where e.events_id='" . (int)$events_id . "' and q.question_id=e.priority_question");
								$question_count=tep_db_num_rows($question_query);
								$question_confirm="";
								if ($question_count>0){
									$question_result=tep_db_fetch_array($question_query);
									$question_result_error=sprintf(ERR_INVALID_ANSWER,$question_result["question_title"]);
									

									// found already this user had answered the question
									$answer_query=tep_db_query("SELECT oa.answer_value,oa.answer_type from " . TABLE_EVENTS . " e," . TABLE_ORDERS_EVENTS_ANSWERS . " oa " . 
																" where oa.orders_id='" . (int)$oId . "' and oa.events_id=e.events_id and e.priority_question='" . (int)$question_result["question_id"] .
																"' limit 1"
																);
																
									if (tep_db_num_rows($answer_query)>0){
										$answer_result=tep_db_fetch_array($answer_query);
										if ($answer_result["answer_type"]=="D") {
											$question_confirm=date("F|d|Y",strtotime($answer_result["answer_value"]));
										} else {
											$question_confirm=$answer_result["answer_value"];
										}
									}
								}
							
							// get session details
							$session_type=tep_get_session_type((int)$events_id);
							$session_array = array();
								
							$add_option="";
							if ($events_result['events_forward_period']=='Y'){
								$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$events_result['events_forward_length']));
								$add_option=" and start_date<='" . $check_date . "' ";
							}
							// check for overbook function 
							$lock_date=false;
							$dates_array=array();
							// get the previous two day results
							if ($session_type=='S') {
								$start_option=" and start_date>curdate() ";
							} else {
								$start_option=" and start_date>curdate() ";
								$two_dates_query=tep_db_query("SELECT start_date,sessions_id,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS . " where events_id='" . (int)$events_id . "' and start_date<=curdate() and sessions_type!='' order by start_date desc limit 2");

								$icnt=tep_db_num_rows($two_dates_query)-1;
								while($two_dates_result=tep_db_fetch_array($two_dates_query)){
									// if the mode is "edit" check for placing the already added date
									if ($edit_mode && isset($edit_dates[$two_dates_result["sessions_id"]])){
										$selected_mode=true;
										$temp_date=$edit_dates[$two_dates_result["sessions_id"]];
										$status=$temp_date["type"];
										$group=$temp_date["waitlist_type"];
									} else {
										$selected_mode=false;
										$status='E';
										if ($status=='E' && tep_check_session_free($two_dates_result,$events_result,'R',$customer_id,$override,$overbook,$no_attendees)) {
											$status='R';
										}
	
	
										$group=tep_find_waitlist_group($events_id,$two_dates_result['sessions_id'],$customer_id,$events_result,$no_attendees);
										if ($group=='E') $group="";
										else if ($status=='E') $status="W";
									}	
									//echo $status.'<br>';								
										$dates_array[$icnt] = array(	'id' => $two_dates_result['sessions_id'],
																		'date'=> $two_dates_result['start_date'],
																		'group'=>$group,
																		'locked'=>$lock_date,
																		'bgcolor'=>0,
																		'selected'=>$selected_mode,
																		'recursive_id'=>$two_dates_result['recursive_sessions_id'],
																		'type'=> $status);
									$icnt--;
								}
							}
							
							$tax_rate=tep_get_tax_rate($events_result['events_tax_class_id']);

							// get other dates
								$date_query=tep_db_query("SELECT start_date,sessions_id,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS  .  " where events_id='" . (int)$events_id . "'" . $start_option . $add_option . " and sessions_type!='' order by start_date");
								while($date_result = tep_db_fetch_array($date_query))
								{
									$status='E';
									$group='';
									if ($edit_mode && isset($edit_dates[$date_result["sessions_id"]])){
										$selected_mode=1;
										$temp_date=$edit_dates[$date_result["sessions_id"]];
										$status=$temp_date["type"];
										$group=$temp_date["waitlist_type"];
									} else {
										$selected_mode=0;
										//check for reservation seats
										if ($status=='E' && tep_check_session_free($date_result,$events_result,'R',$customer_id,$override,$overbook,$no_attendees)) {
									//	echo 'hai';
											$status='R';
										}
										// check for waitlist seats
										$group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result,$no_attendees);
										if ($group=='E') $group="";
										else if ($status=='E') $status="W";	
										
										if ($status!='E' && $sessions_id==0) $sessions_id=$date_result['sessions_id'];
									}
								//	echo $status.'<br>';
									$dates_array[] = array(	'id' => $date_result['sessions_id'],
															'date'=> $date_result['start_date'],
															'recursive_id'=>$date_result['recursive_sessions_id'],
															'locked'=>$lock_date,
															'selected'=>$selected_mode,
															'bgcolor'=>1,
															'type'=> $status,
															'group'=>$group);
								}
								// get the recursive ids
								$cnt=0;
								$recursive_array=array();
								$prev_recursive=0;
								for ($icnt=0;$icnt<sizeof($dates_array);$icnt++){
									$color="#FF0000";
									if ($dates_array[$icnt]['locked']) $color="#668DE3";
									else if ($dates_array[$icnt]['type']=='R') $color="#000000";
									else if ($dates_array[$icnt]['type']=='W') $color="FFA715";
									$session_array[] = array('id' => $dates_array[$icnt]['id'],
															'date'=> $dates_array[$icnt]['date'],
															'type'=> $dates_array[$icnt]['type'],
															'group'=> $dates_array[$icnt]['group'],
															'selected'=>$dates_array[$icnt]['selected'],
															'bgcolor'=>$dates_array[$icnt]['bgcolor'],
															'text' => sprintf("<font color=\"%s\">%s</font>",$color,format_date($dates_array[$icnt]['date']))
															);
									$cnt++;
									if ($session_type=='R' && $prev_recursive!=$dates_array[$icnt]['recursive_id']){
										$prev_recursive=$dates_array[$icnt]['recursive_id'];
										$recursive_array[]=$prev_recursive;
									}
								}
								
							if($sessions_id > 0){
								$session_query=tep_db_query("SELECT start_date FROM " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . (int)$sessions_id . "'");
								$session_result = tep_db_fetch_array($session_query);
								$start_date=$session_result['start_date'];
								$events_result['start_date']=$start_date;
							}
							// get the gap dates
							if ($session_type=='R' && sizeof($recursive_array)>0){
									$result_array=get_gap_dates_array($recursive_array);
									if (sizeof($result_array)>0){
										for ($icnt=0;$icnt<sizeof($result_array);$icnt++){
											$session_array[]=array('date'=>$result_array[$icnt],'selected'=>0,'type'=>'H','group'=>'','text'=>sprintf("<font color=\"%s\">%s</font>","#000000",format_date($result_array[$icnt]) . '&nbsp;&nbsp;' . TEXT_NOTIFY_HOLIDAY));
										}
										usort($session_array,"user_compare");
									}
								
							}
							$sessions_count=isset($HTTP_POST_VARS["sessions_count"])?(int)$HTTP_POST_VARS["sessions_count"]:0;
							//draw the script elements to form
						//	print_r($dates_array);
							?>
							<script language="JavaScript">
									var sessions=Array();
									var choiceAmount1;
									var choiceAmount2;
									var choiceDays1;
									var choiceDays2;
									var selectedSession=0;
									var selectedCount=<?php echo $sessions_count;?>;
									var fees_reserve=<?php echo tep_add_tax($events_result["events_fees"],$tax_rate);?>;
									var fees_vip=<?php echo tep_add_tax($events_result["waitfee_vip"],$tax_rate);?>;
									var fees_firstcome=<?php echo tep_add_tax($events_result["waitfee_firstcome"],$tax_rate);?>;
									var fees_custom=<?php echo tep_add_tax($events_result["waitfee_custom"],$tax_rate);?>;
									var validIndexes=Array();
									var auto_select=false;
									
									<?php 	$jcnt=0;
										for ($icnt=0;$icnt<sizeof($dates_array);$icnt++) { 
											//if ($dates_array[$icnt]['type']=='R' || $dates_array[$icnt]['type']=='W') {
									?>
											sessions[<?php echo $jcnt;?>]=Array();
											sessions[<?php echo $jcnt;?>][0]=<?php echo isset($dates_array[$icnt]['id'])?$dates_array[$icnt]['id']:0;?>;
											sessions[<?php echo $jcnt;?>][1]="<?php echo $dates_array[$icnt]['type'];?>";
											sessions[<?php echo $jcnt;?>][2]=<?php echo tep_get_events_price($events_result,$dates_array[$icnt]['type'],'',$dates_array[$icnt]['date'],true);?>;
											sessions[<?php echo $jcnt;?>][3]=<?php echo $dates_array[$icnt]['bgcolor'];?>;
									<?php 	
											if ($dates_array[$icnt]['id']==$sessions_id){ ?>
												selectedSession=<?php echo $jcnt;?>;
									<?php	}	
											$jcnt++;
											//}	
										}	?>
									function displayCurrency(num){
										var commaDelimiter="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['thousands_point']:',');?>";
										var symbolLeft="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['symbol_left']:'$');?>";
										var symbolRight="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['symbol_right']:',');?>";
										var output=FormatNumber(new String(num),2,commaDelimiter,".");
										return symbolLeft+output+symbolRight;
									}
									function displaySessionsCountFixed(sIndex){
										var row=document.getElementById("sessions_count_row");
										var select_count=parseInt(document.select_session.select_count.value);
										var select_interval=parseInt(document.select_session.select_interval.value);
										var session_style=document.select_session.session_style.value;
										//var session_type=document.select_session.session_type.value;
										var amount_r=0;
										var amount_w=0;
										var total_fee_r=0;
										var total_fee_w=0;
										var total_days_r=0;
										var total_days_w=0;
										var total_days=0;
										var option;
										//var choice=document.select_session.sessions_count;
										var currentIndex=1;
										var waitlist_amount=0;
										var event_type="";
										//clearChoice(choice);
										if (select_interval==0) select_interval=1;
									
										choiceDays1[choiceDays1.length]=total_days_r;
										choiceDays2[choiceDays2.length]=total_days_w;
										choiceAmount1[choiceAmount1.length]=total_fee_r;
										choiceAmount2[choiceAmount2.length]=total_fee_w;
										//choice.options[choice.options.length]=new Option("",0);
										for (icnt=sIndex;icnt<sessions.length;icnt++){
											amount_r=0;
											amount_w=0;
											if (sessions[icnt][1]=="R" || sessions[icnt][1]=="W") {
												if (sessions[icnt][1]=="R"){//reserve user
													amount_r=sessions[icnt][2];
													amount_w=0;
													total_days_r+=1;
												} else if (sessions[icnt][1]=="W") {
													amount_w=0;
													amount_r=0;
													if (session_style=='S' || event_type==''){
														amount_w=fees_vip;
														event_type='W';
													} else {
														amount_w=0;
													}
													total_days_w+=1;
												}
												total_fee_r+=amount_r;
												total_fee_w+=amount_w;
												if (currentIndex % select_interval==0){
													choiceDays1[choiceDays1.length]=total_days_r;
													choiceDays2[choiceDays2.length]=total_days_w;
													choiceAmount1[choiceAmount1.length]=total_fee_r;
													choiceAmount2[choiceAmount2.length]=total_fee_w;
													if (choiceAmount1.length>=select_count) break;
												}
												currentIndex+=1;
											}
										}
										total_days=total_days_r+total_days_w;
										if (total_days<select_interval && choiceAmount1.length==0){
											//choice.options[choice.options.length]=new Option(total_days+"<?php echo TEXT_FOR;?>"+displayCurrency(total_fee_r+total_fee_w),select_interval);
											choice.options[choice.options.length]=new Option(total_days,select_interval);
											if (selectedCount==select_interval)
												choice.options[choice.options.length-1].selected=true;
										}
										for (icnt=1;icnt<choiceAmount1.length;icnt++){
											currentIndex=choiceDays1[icnt]+choiceDays2[icnt];
											//choice.options[choice.options.length]=new Option(currentIndex+"<?php echo TEXT_FOR;?>"+displayCurrency(choiceAmount1[icnt]+choiceAmount2[icnt]),currentIndex);
											choice.options[choice.options.length]=new Option(currentIndex,currentIndex);
											if (selectedCount==currentIndex)
												choice.options[choice.options.length-1].selected=true;
									
										}
										/*if (session_style=="E" && event_type=="W"){
											document.getElementById("event_style").innerHTML="<?php echo TEXT_WAITLIST_AMOUNT;?>"+waitlist_amount;
											document.getElementById("event_style").style.display="block";
										}*/
										if (!row) return;
										row.style.display="block";
										calculateSelectedDate(1);
									}
									function calculateSelectedDate(selectMode){
										var icnt=0;
										var jcnt=0;
										var checkbox_field;
										var event_type="";
										var amount_r=0;
										var amount_w=0;
										var total_fee_r=0;
										var total_fee_w=0;
										var total_days_r=0;
										var total_days_w=0;
										var total_fee=0;
										var total_days=0;
										var sIndex=0;
										var eIndex=sessions.length-1;
										//var length_field=document.select_session.sessions_count;
										var select_interval=parseInt(document.select_session.select_interval.value);
										var session_style=document.select_session.session_style.value;
										var session_type=document.select_session.session_type.value;
										var reserve_type=document.select_session.reserve_type.value;
										var length_index=0;
										var length_remind=0;
										var cnt=0;
										var slotNo=0;
										var checkFlag;
										var prevIndex=0;
										var session_map=Array();
										var current_interval=0;
									
										// if selecting from combo box
										//if (length_field.selectedIndex<=0 && selectMode==1) return;
										document.getElementById("amount_notify_r").style.visibility="hidden";
										document.getElementById("amount_notify_w").style.visibility="hidden";
										document.getElementById("amount_notify_t").style.visibility="hidden";
									
										if (session_type=='S') return;
										
										checkbox_field=document.select_session.elements['sessions_id[]'];
									
										// session length is one
										if (sessions.length==1){
											if (checkbox_field.checked) {
												if (sessions[0][1]=="R") {
													$total_fee_r=sessions[icnt][2];
													total_days_r=1;
												} else if (sessions[0][1]=="W")  {
													$total_fee_w=fees_vip;
													total_days_w=1;
												}
											}
										}
										
										// session length is more than one
										if (sessions.length>1){
											reserve_type="R";
											//set the session map amount
											if (session_style!=''){
												jcnt=0;
												for (icnt=0;icnt<sessions.length;icnt++){
													if (checkbox_field[icnt].checked && sessions[icnt][1]!='E') {
														if (sessions[icnt][1]=="W") reserve_type="W";
														jcnt++;
														if (jcnt%select_interval==0) {
															session_map[current_interval]=reserve_type;
															current_interval++;
															reserve_type='R';
														}
													}
												}
												if (jcnt%select_interval!=0){
													session_map[current_interval]=reserve_type;
												}
											}
											cnt=0;
											current_interval=0;
											reserve_type="";
											
											for (icnt=sIndex;icnt<=eIndex;icnt++){
												amount_r=0;
												amount_w=0;
												if (sessions[icnt][1]!='E' && checkbox_field[icnt].checked) {
													if (session_style!='E'){
														if (sessions[icnt][1]=="R"){
															amount_r=sessions[icnt][2];
															total_days_r+=1;
														} else if (sessions[icnt][1]=="W") {
															amount_w=fees_vip;
															total_days_w+=1;
														}
													} else {
														if (session_map[current_interval]=='R'){
															amount_r=sessions[icnt][2];
															total_days_r+=1;
														} else {
															if (reserve_type=="") {
																amount_w=fees_vip;
																reserve_type="W";
															}
															total_days_w+=1;
														}
													}
													cnt++;
													if (session_style!=""){
														if (cnt%select_interval==0) {
															reserve_type="";
															current_interval++;
														}
													}
													total_fee_r+=amount_r;
													total_fee_w+=amount_w;
												}
											}
										}
										
										total_days=total_days_r+total_days_w;
										if (total_fee_r>0){
											document.getElementById("amount_notify_r").innerHTML="<?php echo RESERVE_FEE;?>"+displayCurrency(total_fee_r)+" ("+total_days_r+" <?php echo TEXT_DAYS;?>"+")";
											document.getElementById("amount_notify_r").style.visibility="visible";
										}
										if (total_fee_w>0) {
											document.getElementById("amount_notify_w").innerHTML="<?php echo WAITLIST_FEE;?>"+displayCurrency(total_fee_w)+" ("+total_days_w+" <?php echo TEXT_DAYS;?>"+")";
											document.getElementById("amount_notify_w").style.visibility="visible";
										}
										total_fee=total_fee_r+total_fee_w;
										total_days=total_days_r+total_days_w;
										if (total_fee>0) {
											document.getElementById("amount_notify_t").innerHTML="<?php echo TOTAL_FEE;?>"+displayCurrency(total_fee)+" ("+total_days+" <?php echo TEXT_DAYS;?>"+")";
											document.getElementById("amount_notify_t").style.visibility="visible";
										}
										document.getElementById("no_sessions").innerHTML=total_days;
									}
									function selectValidDates(index){
										var select_interval=parseInt(document.select_session.select_interval.value);
										var session_style=document.select_session.session_style.value;
										var session_type=document.select_session.session_type.value;
										var session_gaps=document.select_session.session_gaps.value;
										var session_reduction=document.select_session.session_reduction.value;
										var validIndexs=0;
										var validIndexe=0;
										var no_reserve=0;
										var no_waitlist=0;
										var checkbox_field;
										var selectSlotType=""; // check type category the selected group falls full reserve,waitlist,mixed;
										var error="";
										var no_sessions=0;
										var reserve_type="";
										var selection_mode='fixed' // 'fixed'=>fixed selection. 'reserve'=>select only reservation if possible if not change to fixed reservation
										
										
										// if single session or sessions.lengh <2 or  index is invalid exit
										checkbox_field=document.select_session.elements['sessions_id[]'];
										if (session_type=='S' || sessions.length<2 || index<0 || index>=sessions.length){
											calculateSelectedDate(0);
											return;
										}
										// if auto select just select the sessions and exit
										if (auto_select){
											auto_select=false;
											if (sessions.length>1) checkbox_field[index].checked=true;
											else checkbox_field.checked=true;
										}
										//if select _interval is less than 2 exit
										if (select_interval<2 || sessions.length<2){
											calculateSelectedDate(0);
										} 
										// checkbox is being selected or unselected
										checkFlag=checkbox_field[index].checked;
										if (checkFlag){
											validIndexs=index;
											checkbox_field[index].checked=false;
											reserve_type='R';
											selectSlotType="";
											// if sessions gaps is allowed and selected is reserved just change selection mode reserve
											if (session_gaps=='Y' && sessions[index][1]=="R") selection_mode='reserve';
									
											// iterate first by taking "reserve mode" and then work for fixed
											for (var kcnt=1;kcnt<=2;kcnt++){
												jcnt=0;
												// if selected box is reserved
												if (selection_mode=='reserve'){
													// iterate upto the sessions count & automatically checke the sessions upto select "interval" count or until a session is selected
													for (icnt=index;icnt<sessions.length;icnt++){
														if (checkbox_field[icnt].checked) break;
														validIndexe=icnt;
														if (sessions[icnt][1]=='R') {
															jcnt++;
															if (jcnt>=select_interval) break;
														}
													}
												} else { // if selected is waitlist
													// iterate and select "interval" no of sessions if valid
													for (icnt=index;icnt<sessions.length;icnt++){
													
														if (checkbox_field[icnt].checked) break;
														// mark the slot type to waitlist or mixed or reserved
														if (sessions[icnt][1]!='E'){
															if (sessions[icnt][1]=='W' && selectSlotType!="W"){
																if (selectSlotType=="") selectSlotType="W";
																else selectSlotType="M";
															}
															if (sessions[icnt][1]=='R' && selectSlotType!="R"){
																if (selectSlotType=="") selectSlotType="R";
																else selectSlotType="M";
															}
														}
														// if there is a empty in slot and session_gaps is not allowed pop the error message
														if (sessions[icnt][1]=='E' && session_gaps!='Y'){
															error="<?php echo addslashes(stripslashes(ERR_SESSION_GAPS));?>";
															break;
														} 
														// store the last index 
														validIndexe=icnt;
														if (sessions[icnt][1]!='E') {
															jcnt++;
															if (jcnt>=select_interval) break;
														}
													}
												}
												// if selection mode is reserve and "no sessions" exceeds just exit
												if (selection_mode=="reserve"){
													if (jcnt>=select_interval) {
														selectSlotType="R";
														break;
													}
													selection_mode="fixed";
												}
											}
											// if selection mode is fixed and no sessions is less than expected interval and "session reduction" is off just error
											if (error=="" && selection_mode=="fixed"){ 
												if (jcnt<select_interval && sessions.length>select_interval && session_reduction!='Y'){
													error="<?php echo addslashes(stripslashes(ERR_SESSION_REDUCTIONS));?>";
												}
											}
											if (error!=""){
												alert(error);
												return;
											}
											// check above selected session to find any waitlist is present and slottype is other than waitlist
											for (icnt=0;icnt<validIndexs;icnt++){
												if (checkbox_field[icnt].checked){
													if (sessions[icnt][1]=='W' && selectSlotType!='W') {
														error="<?php echo addslashes(stripslashes(ERR_SESSION_WAITLIST_ABOVE));?>";
														break;
													}
												}
											}
											if (error!=""){
												alert(error);
												return;
											}
											jcnt=0;
											reserve_type='R';
											//check below selected sessions for any reservations is present and slottype is other than reserve
											for (icnt=validIndexe+1;icnt<sessions.length;icnt++){
												if (checkbox_field[icnt].checked && sessions[icnt][1]!='E'){
													if (sessions[icnt][1]=='W') reserve_type='W';
													jcnt++;
													if (jcnt%select_interval==0){
														if (reserve_type=='R' && selectSlotType!='R') {
															error="<?php echo addslashes(stripslashes(ERR_SESSION_RESERVE_BELOW));?>";
															break;
														}
														reserve_type="R";
													}
												}
											}
											if (jcnt%select_interval!=0){
												if (reserve_type=='R' && selectSlotType!='R') {
													error="<?php echo addslashes(stripslashes(ERR_SESSION_RESERVE_BELOW));?>";
												}
											}
											if (error!=""){
												alert(error);
												return;
											}
											// if there is no error select the possible session dates
											for (icnt=validIndexs;icnt<=validIndexe;icnt++){
												if (sessions[icnt][1]!='E') {
													if ((selection_mode=="reserve" && sessions[icnt][1]=='R') || selection_mode!="reserve")
													checkbox_field[icnt].checked=true;
												}
											}
											if (session_reduction!='Y')
												validIndexes[validIndexes.length]=validIndexs+","+validIndexe;
										} else if (session_reduction!='Y') {
											var tempStr="";
											var delIndex=-1;
											for (icnt=0;icnt<validIndexes.length;icnt++){
												tempStr=validIndexes[icnt].split(",");
												validIndexs=parseInt(tempStr[0]);
												validIndexe=parseInt(tempStr[1]);
												if (index>=validIndexs && index<=validIndexe){
													validIndexes[icnt]="";
													delIndex=icnt;
													break;
												}
											}
											if (delIndex>=0) {
												for (icnt=validIndexs;icnt<=validIndexe;icnt++){
													if (sessions[icnt][1]!='E') {
														checkbox_field[icnt].checked=false;
													}
												}
												deleteStoredIndex(delIndex);
											}
										}
										calculateSelectedDate(0);
									}
									function deleteStoredIndex(delIndex){
										if (delIndex<0 || delIndex>=validIndexes.length) return;
										for (var jcnt=delIndex; jcnt<validIndexes.length-1; jcnt++)
											validIndexes[jcnt] = validIndexes[jcnt+1];
										validIndexes.length = validIndexes.length-1;
									}
									function clearChoice(choice){
										if (choice.options==null) return;
										while(choice.options.length>0){
											choice.options[0]=null;
										}
										choice.selectedIndex=-1;
										choiceAmount1=Array();
										choiceAmount2=Array();
										choiceDays1=Array();
										choiceDays2=Array();
									}
									function validateForm(frm){
										var error="";
										var icnt=0;
										var check_field=frm.elements["sessions_id[]"];
										var session_type=frm.session_type.value;
										var session_style=frm.session_style.value;
										var session_gaps=frm.session_gaps.value;
										var session_reduction=frm.session_reduction.value;
										//var sessions_count=parseInt(frm.sessions_count.value);
									
										if (session_type=='S') return true;
										if (sessions.length>1){
											error="<?php echo addslashes(stripslashes(ERR_SELECT_SESSION_DATE));?>";
											for (icnt=0;icnt<check_field.length;icnt++){
												if (check_field[icnt].checked) {
													error="";
													break;
												}
											}
										} else {
											if (check_field.checked==false){
												error="<?php echo addslashes(stripslashes(ERR_SELECT_SESSION_DATE));?>";
											}
										}
										if (error=="" && frm.question_type){
											if (frm.question_type.value=="D"){
												if (isDate(frm.question_month.value+"/"+frm.question_day.value+"/"+frm.question_year.value)==false){
													error="<?php echo addslashes(stripslashes($question_result_error));?>";
												} else {
													frm.question_value_data.value=frm.question_year.value + "-" + frm.question_month.value + "-" + frm.question_day.value;
												}
											} else if (frm.question_type.value=="T" && frm.question_value_data.value==""){
													error="<?php echo addslashes(stripslashes($question_result_error));?>";
											} else if (frm.question_type.value=="N" && isNaN(parseInt(frm.question_value_data.value))){
													error="<?php echo addslashes(stripslashes($question_result_error));?>";
											}
										}
										if (error!=""){
											alert(error);
											return false;
										}
									
										if (sessions.length<=1 || session_style!='E' || session_type=='S') return true;
										// check for event based waiting lists that reservations exist before selected waitlist
										var no_reserve=0; // selected reserve count
										var no_waitlist=0;
										var gap_on=false;
										session_store_type="M";
										for (icnt=0;icnt<sessions.length;icnt++){
											if (sessions[icnt][1]=='W' && check_field[icnt].checked) {
												session_store_type='W';
											}
											if (sessions[icnt][1]=='R' && check_field[icnt].checked) no_reserve+=1;
											/*if (check_field[icnt].checked){
												if (sessions[icnt][1]=='W') {
													if (no_reserve>0) {
														error="<?php echo ERR_RESERVATION_TO_BE_FILLED;?>";
														break;
													}
													session_store_type='W';
													no_waitlist+=1;
												} else if (sessions[icnt][1]=='E'){
													if (session_store_type=='W' && no_waitlist<select_interval){
														error="<?php echo ERR_WAITLIST_LESS_SEATS;?>";
														break;
													}
												}
											}*/
										}
										/*if (session_gaps!='Y' && gap_on) { // checking for continuous session
											error="<?php echo ERR_SESSION_GAPS;?>";
										}
										if (error!=""){
											alert(error);
											return false;
										}*/
										return true;
									}
									function isDate(dateStr) {
									
									  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
									  var matchArray = dateStr.match(datePat); // is format OK?
									
									  if (matchArray == null) {
										return false;
									  }
									
									  // parse date into variables
									  month = matchArray[1];
									  day = matchArray[3];
									  year = matchArray[5];
									
									  if (month < 1 || month > 12) { // check month range
										return false;
									  }
									
									  if (day < 1 || day > 31) {
										return false;
									  }
									
									  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
										return false;
									  }
									
									  if (month == 2) { // check for february 29th
										var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
										if (day > 29 || (day==29 && !isleap)) {
										  return false;
										}
									  }
									  return true;  // date is valid
}							</script>
						<?php  
						echo tep_draw_form("select_session",FILENAME_ADD_EVENTS,$page_params,'post','onSubmit="javascript:return validateForm(this);"');?>
							<tr class="attributes-odd" valign=middle height="20">
								<td class="dataTableContent" align=left><b><?php
								if($multiple_attendees)
									 echo EVENT_STEP3;
								else 
									echo EVENT_STEP2;
							?></b></td>
							</tr>
							  <tr>
								<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
							  </tr>
							<?php if ($cnt >0) {?>
								<tr class="attributes-even">
									<td>
									<table border="0" cellpadding="2" cellspacing="0">
										<tr valign=middle>
											<td class="dataTableContent" width="100"><?php echo TEXT_START_DATE;?></td>
											<td class="dataTableContent" align="left" width="320"><?php customSessionListBox('sessions_id',$session_array,$sessions_id,"100%","220px"); ?></td>
											<td class="dataTableContent" align="left">
												<table border="0" cellpadding="3" cellspacing="0">
													<tr class="attributes-even" id="sessions_count_row" valign="middle">
														<td class="dataTableContent" width="100"><?php echo TEXT_NO_OF_SESSIONS;?></td>
														<td class="dataTableContent" align="left" width="50"><span id="no_sessions">&nbsp;</span></td>
														<td class="dataTableContent" align="left"><?php echo tep_image_submit("button_select.gif",IMAGE_SELECT_SESSION);?></td>
													</tr>
													<tr>
														<td colspan="3" class="dataTableContent" align="left">
															<div id="amount_notify_r" style="visibility:hidden;"><?php echo RESERVE_FEE;?></div>
															<div id="amount_notify_w" style="visibility:hidden"><?php echo WAITLIST_FEE;?></div><p>
															<div id="amount_notify_t" style="visibility:hidden"><?php echo TOTAL_FEE;?></div>
														</td>
													</tr>
												</table>
											</td>
										</tr>
									</table>
									<?php
											for ($icnt=0;$icnt<sizeof($session_array);$icnt++){
												if ($session_array[$icnt]['type']=='W' || $session_array[$icnt]['type']=='R'){
													echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][type]" value="' . $session_array[$icnt]['type'] . '">';
													echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][date]" value="' . $session_array[$icnt]['date'] . '">'; 
													echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][group]" value="' . $session_array[$icnt]['group'] . '">';
												}
											}
											if ($multiple_attendees){
												echo '<input type="hidden" name="no_attendees" value="' . $no_attendees . '">';
											} else {
												echo '<input type="hidden" name="no_attendees" value="1">';
											}
									?>
									<input type='hidden' name='step' value='5'>
									<input type="hidden" name="events_name" value="<?php echo $events_id;?>">
									<input type='hidden' name="session_type" value="<?php echo $session_type;?>">
									<input type='hidden' name="reserve_type" value="M">
									<?php if ($session_type=='R') { ?>
										<input type="hidden" name="select_interval" value="<?php echo $events_result['sessions_select_interval'];?>">
										<input type="hidden" name="select_count" value="<?php echo $events_result['sessions_select_count'];?>">
										<input type="hidden" name="session_style" value="<?php echo $events_result['session_style'];?>">
									<?php } else {?>
										<input type="hidden" name="select_interval" value="1">
										<input type="hidden" name="select_count" value="1">
										<input type="hidden" name="session_style" value="S">
									<?php }?>
										<input type="hidden" name="session_gaps" value="<?php echo $events_result['session_gaps'];?>">
										<input type="hidden" name="session_reduction" value="<?php echo $events_result['session_reduction'];?>">
									</td>
								</tr>
								<?php if ($question_count>0) { // output question area 
										echo '<input type="hidden" name="question_type" value="' . $question_result["answer_type"] . '">';
								?>
											<tr valign=middle height="20">
												<td class="dataTableContent" align=left><b><?php echo $question_result["question_title"];?></b></td>
											</tr>
											<tr class="attributes-even" valign="middle">
												<td>
												<table border="0" cellpadding="2" cellspacing="0">
													<tr valign=middle>
														<td class="main" valign="center">
														<?php echo $question_result["question_description"];?>
														</td>
														<?php echo tep_get_question_input_table($question_result["answer_type"]);?>
													</tr>
													<?php if ($question_confirm!="") { ?>
													<tr valign=middle>
														<td class="smallText" valign="center"><?php echo TEXT_ANSWER_INFO;?></td>
														<?php 
															if ($question_result["answer_type"]=="D") {
																$answer_splt=split("\|",$question_confirm);
																for ($icnt=0;$icnt<sizeof($answer_splt);$icnt++){
																	echo '<td class="smallText" valign="top">' . $answer_splt[$icnt] . '</td>';
																}
															} else {
																echo  '<td class="smallText" valign="top">' . $question_confirm . '</td>';
															}
														?>
													</tr>
													<?php }?>
												</table>
												</td>
											</tr>
								
								<?php  } // question_count
										if (isset($HTTP_GET_VARS["check"])) {
								?>
									<script language="JavaScript">
										auto_select=true;
										selectValidDates(selectedSession)
									</script>
								<?php }
							 } else {	?>
								<tr "attributes-even" valign=middle>
									<td class="dataTableContent" height="20" align="center"><?php echo TEXT_NO_SESSIONS; ?></td>
								</tr>
							<?php  } ?>
						  <tr>
							<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
						  </tr>
						<tr class="attributes-odd">
							<td>&nbsp;</td>
						</tr>
							</form>
				<?php } ?>
					</table>
					</td>
				</tr>
			</table>
		<!-- body_eof //-->
		</tr>
	</table>
<?php unset($session_array); ?>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
<?php

function user_compare($a, $b) 
{
    if ($a['date'] == $b['date']) {
        return 0;
    }
    return ($a['date'] < $b['date']) ? -1 : 1;
}
function customEventListBox($name,&$list,$selected,$width,$height){
	$selIndex=0;
	
	echo '<div id="' . $name . '_box" style="border-color: #7b9ebd; border-style: solid; border-width: 1px;overflow:auto;width:' . $width . ';height:' . $height . '">' . "\n";
	echo '<table border="0" cellspacing="0" cellpadding="2" width="100%" valign="middle" align="center" class="BoxTable">' . "\n";
	for ($icnt=0;$icnt<sizeof($list);$icnt++){
		if ($list[$icnt]['mode']=='E') {
			if ($selected==0) $selected=$list[$icnt]['id'];
			echo  '<tr class="attributes-even"><td nowrap bgcolor="' . ($selected==$list[$icnt]['id']?"#D8EDFB":"#FFFFFF") . '" valign="middle" width="100%" id="' . $name . $list[$icnt]['id'] . '" onClick="javascript:selectEventItem(\'' . $name . '\',\'' . $list[$icnt]['id'] .  '\',' . $icnt .')" class="BoxTd">' . "\n";
			echo  $list[$icnt]['text'] .'</td></tr>' ."\n";
			if ($selected==$list[$icnt]['id']) $selIndex=$icnt;
		} else {
			echo  '<tr class="attributes-even"><td nowrap bgcolor="#FFFFFF" valign="middle" width="100%" class="BoxTd">' . "\n";
			echo  $list[$icnt]['text'] .'</td></tr>' ."\n";
		}
	}
	echo '</table></div>' . "\n";
	echo '<input type="hidden" name="' . $name . '" value="' . $selected . '">';
	echo '<input type="hidden" name="' . $name . '_index" value="' . $selIndex . '">';
}
function customSessionListBox($name,&$list,$selected,$width,$height){
	global $session_type;
	$selIndex=0;
	$bgcolor="#FFFFFF";
	$jcnt=0;
	echo '<div id="' . $name . '_box" style="border-color: #7b9ebd; border-style: solid; border-width: 1px;overflow:auto;width:' . $width . ';height:' . $height . '">' . "\n";
	echo '<table border="0" cellspacing="0" cellpadding="1" width="100%" valign="middle" align="center" class="BoxTable">' . "\n";
	for ($icnt=0;$icnt<sizeof($list);$icnt++){
		echo '<tr class="attributes-even" height=20><td class="main" width=50>';
		if ($list[$icnt]['type']=='R' || $list[$icnt]['type']=='W'){
			if ($list[$icnt]['bgcolor']==0) $bgcolor="#F5F5F5";
			else $bgcolor="#FFFFFF";
			if ($selected=="" || $selected==0) $selected=$list[$icnt]['id'];
			if ($selected==$list[$icnt]['id']) $selIndex=$jcnt;
			if ($session_type!='S')
				echo tep_draw_checkbox_field($name . "[]",$list[$icnt]['id'],$list[$icnt]['selected'],'','onClick="javascript:selectValidDates('. $jcnt . ');"');
				echo '</td><td bgcolor="' . ($selected==$list[$icnt]['id']?"#D8EDFB":$bgcolor) . '" valign="middle" width="100%" id="' . $name . $list[$icnt]['id'] . '" onClick="javascript:selectSessionItem(\'' . $name . '\',\'' . $list[$icnt]['id'] .  '\',' . $jcnt .')" class="BoxTd">';
		} else {
			if ($list[$icnt]['type']=='E') echo tep_draw_checkbox_field($name . "[]",$list[$icnt]['id'],false,'','style="visibility:hidden"');
			echo '</td><td bgcolor="#FFFFFF" valign="middle" width="100%" class="BoxTd">';
		}
		if ($list[$icnt]['type']!='H') $jcnt++;
		echo $list[$icnt]['text'] .'</td></tr>';
	}
	echo '</table></div>' . "\n";
	if ($session_type=="S")
		echo '<input type="hidden" name="' . $name . '[]" value="' . $selected . '">';
	else
		echo '<input type="hidden" name="' . $name . '_field" value="' . $selected . '">';
	echo '<input type="hidden" name="' . $name . '_index" value="' . $selIndex . '">';
}

  function tep_get_country_id($country_name) {

    $country_id_query = tep_db_query("select * from " . TABLE_COUNTRIES . " where countries_name = '" . $country_name . "'");

    if (!tep_db_num_rows($country_id_query)) {
      return 0;
    }
    else {
      $country_id_row = tep_db_fetch_array($country_id_query);
      return $country_id_row['countries_id'];
    }
  }
  
  function tep_get_zone_id($country_id, $zone_name) {

    $zone_id_query = tep_db_query("select * from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_name = '" . $zone_name . "'");

    if (!tep_db_num_rows($zone_id_query)) {
      return 0;
    }
    else {
      $zone_id_row = tep_db_fetch_array($zone_id_query);
      return $zone_id_row['zone_id'];
    }
  }
?>