<?php

/*

  osCommRes, Services Oline 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare

Released under the GNU General Public License 
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
    require('includes/application_top.php'); 
    tep_get_last_access_file();    
	require(DIR_WS_CLASSES.'split_page_results_event.php');
    require(DIR_WS_FUNCTIONS . 'events_tree.php');
    //require(DIR_WS_CATALOG_LANGUAGES . 'english/events_check_in.php');
    define(BOX_WIDTH1,'125');
  	set_time_limit(25);
    $current_date=getServerDate();
	$action=isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action']:'';
	$command=isset($HTTP_GET_VARS['command'])?$HTTP_GET_VARS['command']:'';
	$disp_reserve=isset($HTTP_POST_VARS['disp_reserve'])?$HTTP_POST_VARS['disp_reserve']:'';
	$event_attend=isset($HTTP_POST_VARS['event_attend'])? $HTTP_POST_VARS['event_attend'] : 0;
	$sid=isset($HTTP_POST_VARS['sid'])? (int)$HTTP_POST_VARS['sid'] : '';
	$cid=isset($HTTP_POST_VARS['cid'])? (int)$HTTP_POST_VARS['cid'] : '';
	
	if (isset($HTTP_GET_VARS["return"]) && isset($HTTP_SESSION_VARS["rep_params"]))
		$input_params=&$HTTP_SESSION_VARS["rep_params"];
	else {
		$input_params=&$HTTP_POST_VARS;
		tep_set_session_value("rep_params",$HTTP_POST_VARS);
	}	 
	$search_mode=isset($input_params['mode'])? $input_params['mode'] : 1; // Attendees or reserved customers
	$event=isset($input_params['sel_event'])?(int)$input_params['sel_event']:-1;
	$session=isset($input_params['sel_session'])?(int)$input_params['sel_session']:-1;
	$instructor=isset($input_params['sel_instructor'])?$input_params['sel_instructor']:-1;
	$view=isset($input_params['sel_view'])?$input_params['sel_view']:1;
	$page = isset($HTTP_GET_VARS['page'])?(int)$HTTP_GET_VARS['page']:1;
	$overbook=isset($input_params['chk_overbook'])?$input_params['chk_overbook']:'';
	$override=isset($input_params['chk_override'])?$input_params['chk_override']:'';
	$found_results=false;
	// build the output if needed
		
	if($event_attend!="")
		tep_db_query("delete from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " where customers_id='" . (int)$cid . "' and sessions_id='" . (int)$sid . "'");
				
	if($view==2) 
		$sql =  "select date_add(start_date, interval -(dayofweek(start_date)-1) day) begin, date_add(start_date, interval (7-dayofweek(start_date)) day) end from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . (int)$session . "'";
	else if($view==3) 
		$sql =  "select date_add(start_date, interval -(dayofmonth(start_date)-1) day) begin, date_add(start_date, interval (30-dayofmonth(start_date)) day) end  from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . (int)$session . "'";
	else if($view==1)
		$sql =  "select start_date as begin, start_date as end  from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . (int)$session . "'";
	
	$sql_result = tep_db_query($sql);
	if (tep_db_num_rows($sql_result)>0){
		$row = tep_db_fetch_array($sql_result);
		$date_begin = $row["begin"];
		$date_end = $row["end"];
	} else
		$date_begin=$date_end=$current_date;	
	$instructors_array = array();
	$events_array = array();
	$session_array = array();
	$result_array=array();
	$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'");
							
							while($result_reservation=tep_db_fetch_array($get_reservation_query))
								$result_array[]=array('id'=>"," . $result_reservation['admin_groups_id'] . ",");

	// get instructor names			
	$sql_ins = "select a.admin_id admin_id, admin_firstname, admin_lastname  from events_instructors ei, admin a where ei.admin_id=a.admin_id order by admin_firstname,admin_lastname";
	$sql_result = tep_db_query($sql_ins);
	$num_rows = tep_db_num_rows($sql_result);
	$instructors_array[]=array("id"=>-1,'text'=>TEXT_ALL_INSTRUCTORS);
	while($row=tep_db_fetch_array($sql_result)) {
		$instructors_array[]=array("id"=>$row["admin_id"],"text"=>$row["admin_firstname"]." ".$row["admin_lastname"]);
	}
	mysql_free_result($sql_result);

	// get all the events
	$events_option="";
	if ($login_groups_type==TEXT_INSTRUCTOR_ENTRY) $events_option=" and e.events_instructor='" . (int)$login_id . "'";
	$sql_query = "select e.events_id,ed.events_name,es.sessions_id,es.start_date  from events e, events_description ed," . TABLE_EVENTS_SESSIONS . " es where e.events_id = ed.events_id and es.events_id=e.events_id and ed.language_id='" . (int)$languages_id ."' " . EVENTS_CONDITION_STATUS . $events_option . " group by e.events_id order by ed.events_name";
	$sql_result = tep_db_query($sql_query);
	while($row=tep_db_fetch_array($sql_result)) {
		$events_array[]=array("id"=>$row["events_id"],"text"=>$row["events_name"]);
	}
	mysql_free_result($sql_result);
	
	// get all the session date 
	$where = " ";
	// fetch results
	if ($event<=0) $event=$events_array[0]['id'];
	if($event>0){
			$date_query=tep_db_query("SELECT s.start_date,s.sessions_id,e.events_id from " . TABLE_EVENTS_SESSIONS . " s," .
					TABLE_EVENTS . " e where s.events_id=e.events_id and e.events_id='" . (int)$event .  "'" . EVENTS_CONDITION_STATUS  . " order by e.events_id,s.start_date");
		while($date_result=tep_db_fetch_array($date_query)) {
			$date_array[]=array("id"=> $date_result["sessions_id"] ,"text"=>format_date($date_result["start_date"]));
			if($session<=0 && $date_result["start_date"]==$current_date)
				$session=$date_result["sessions_id"];
		}
	}	
		
		if($instructor!="-1") {
			$where.= "and e.events_instructor='".$instructor."' ";
		} 
		if($event!="-1") {
			$where.= "and e.events_id='".$event."' ";
		}
		$cus_query=tep_db_query("SELECT customers_id from " . TABLE_EVENTS_ATTENDEES_CONFIRM  . " where events_id='$event' and sessions_id='$session'") ;

		$subscription_ids=tep_get_linked_subscription($event);
		
		$sub_query=tep_db_query("SELECT o.orders_id from " . TABLE_ORDERS  . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_SUBSCRIPTIONS . " su where su.subscription_id=op.products_id and op.products_type='S' and op.products_id in($subscription_ids) and DATE_ADD(o.date_purchased,INTERVAL su.subscription_period DAY) >='" . $current_date. "'") ;
		while($sub_result=tep_db_fetch_array($sub_query)){
			$subs_order_ids.=$sub_result['orders_id'] . ',';
		}
		if($subs_order_ids!="")
			$subs_order_ids=substr($subs_order_ids,0,-1);
		else
			$subs_order_ids='0';

		
		if ($search_mode==1){
				$sql = "select s.start_date,s.sessions_id,e.events_renewal_start,e.events_renewal_end,e.events_wait_list,e.events_id,op.events_type,et.customers_id,op.orders_id,op.products_type,et.customers_firstname,et.attendees_type,et.customers_lastname,o.customers_email_address,s.start_date from " . TABLE_EVENTS_SESSIONS . " s, "  . TABLE_EVENTS_ATTENDEES_CONFIRM . " et, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS . " e " . 
						" LEFT JOIN	" . TABLE_ADMIN . " a on a.admin_id=e.events_instructor where s.sessions_id = et.sessions_id  and ((op.products_id=et.sessions_id and op.products_type='E') or (op.products_id in ($subscription_ids) and op.products_type='S' and o.orders_id in($subs_order_ids))) and et.customers_id=o.customers_id and e.events_id=et.events_id and o.orders_id=op.orders_id " .
						" and  (s.start_date>='$date_begin' and s.start_date<='$date_end')" . $where . $events_option ."  order by s.start_date,et.customers_firstname,et.customers_lastname";
		} else {
				while($cus_result=tep_db_fetch_array($cus_query)){
					$customer_ids.=$cus_result['customers_id'] . ',';
				}
				if($customer_ids!="")
					$customer_ids=substr($customer_ids,0,-1);
				else
					$customer_ids='0';
		
			$sql = "select s.start_date,s.sessions_id,e.events_wait_list,e.events_renewal_start,e.events_renewal_end,e.events_id,op.events_type,op.products_id,op.products_type,c.customers_id,o.orders_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,s.start_date from " . 
					TABLE_EVENTS_SESSIONS . " s, "  . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_CUSTOMERS . " c, " . TABLE_ORDERS . " o," . TABLE_EVENTS . " e " .
					" LEFT JOIN	" . TABLE_ADMIN . " a on a.admin_id=e.events_instructor where  s.events_id=e.events_id " .
					" and o.orders_id=op.orders_id and c.customers_id=o.customers_id and ((op.products_type='E' and s.sessions_id = op.products_id) or (op.products_id in ($subscription_ids) and op.products_type='S' and o.customers_id in($customer_ids) and o.orders_id in($subs_order_ids))) " .
					" and (s.start_date>='$date_begin' and s.start_date<='$date_end') " . $where . $events_option . "  group by o.customers_id  order by s.start_date,o.customers_name";
		}
	// split the report
//MAX_DISPLAY_SEARCH_RESULTS
		// split the report to multiple pages
	$temp_sql=tep_db_query($sql);
	while($row=tep_db_fetch_array($temp_sql))
		$printed_customers.=$row["customers_id"] . ",";
	if($printed_customers!="")
		$printed_customers=substr($printed_customers,0,-1);
	else
		$printed_customers='0';
	$non_order_query=tep_db_query("SELECT * from " . TABLE_EVENTS_ATTENDEES_CONFIRM  . " where events_id='$event' and sessions_id='$session' and customers_id not in (" . $printed_customers . ")") ;
	$non_order_count=tep_db_num_rows($non_order_query);
	
	 $max_display_count=MAX_DISPLAY_SEARCH_RESULTS;	
	 $query_split = new splitPageResultsEvent($page, $max_display_count, $sql, $query_split_numrows,false);
	 $sql_result=tep_db_query($sql);
	 $detail_result=tep_db_query($sql);
	 

	 $query_split_numrows+=$non_order_count;
	 $num_rows=tep_db_num_rows($sql_result);
	 if ($num_rows>0) $found_results=true;
	 if(tep_db_num_rows($cus_query)>0) $found_results=true;
	 
	 $query = tep_db_query("select customers_id, customers_firstname, customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " ORDER BY customers_firstname asc");
	 $result = $query;

	 $selected_name="";	
	 if (tep_db_num_rows($result) > 0)
	 {
		// Query Successful
		$SelectCustomerBox = "<select name='select_order' size=10 onClick=\"javascript:setListboxText(0);toggleList(0);\" onFocus=\"javascript:toggleList(1);\" onBlur=\"javascript:toggleList(0);\" class='customerSelect'>\n";
		while($db_Row = tep_db_fetch_array($result)){ 
			$SelectCustomerBox .= "<option value='" . $db_Row["customers_id"] . "'";
			if($db_Row["customers_id"]==$customers_id){
				$SelectCustomerBox .= " SELECTED ";
				$selected_name=$db_Row["customers_firstname"] . ' ' . $db_Row["customers_lastname"] . ", " . $db_Row["customers_email_address"];
			}
			$SelectCustomerBox .= ">" . $db_Row["customers_firstname"] . ' ' .  $db_Row["customers_lastname"] . ", " . $db_Row["customers_email_address"] . " (" . $db_Row["customers_id"]. ") </option>\n";
		}
		$SelectCustomerBox .= "</select>\n";
    }
    // select events_attendees confirm sessions
    $attend_details=array();
	$attend_query=tep_db_query("SELECT et.customers_id,et.sessions_id from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " et, " . TABLE_EVENTS_SESSIONS . " s where s.start_date>='" . $date_begin . "' and s.start_date<='" . $date_end . "' and s.sessions_id=et.sessions_id order by et.customers_id,et.sessions_id");
	while($attend_result=tep_db_fetch_array($attend_query)){
		$attend_details[$attend_result["customers_id"]][$attend_result["sessions_id"]]=1;
	}	  
  if($command!=""){
	/*if($command=="fetch_sub_details")
	{
		$order_id=isset($HTTP_GET_VARS["order_id"])?(int)$HTTP_GET_VARS["order_id"]:-1;
		$event_id=isset($HTTP_GET_VARS["event_id"])?(int)$HTTP_GET_VARS["event_id"]:-1;
		 if ($order_id<=0) {
			echo '<span class="main">' . TEXT_NO_DETAILS . '</span>';
			exit;
		}
		$subs_sql="select o.date_purchased,count(op.orders_id) as del_count,'E' as d_type from " . TABLE_ORDERS ." o,". TABLE_ORDERS_PRODUCTS . " op where op.orders_id=o.orders_id and op.products_type='E' and o.orders_id='" . $order_id. "'  group by op.orders_id";
  		$subs_query=tep_db_query($subs_sql);
		if(tep_db_num_rows($subs_query)<=0)
		   $subs_sql="select o.date_purchased,su.deliveries,su.deliveries_perday,su.subscription_period,su.subscription_type as d_type from " . TABLE_ORDERS ." o,". TABLE_ORDERS_PRODUCTS . " op," . TABLE_SUBSCRIPTIONS . " su where op.orders_id=o.orders_id and su.subscription_id=op.products_id and op.products_type='S' and o.orders_id='" . $order_id. "'  group by op.orders_id";
  		$subs_query=tep_db_query($subs_sql);
    	if (tep_db_num_rows($subs_query)<=0) {
			echo '<span class="main">' . TEXT_NO_DETAILS . '</span>';
			exit;
		}
		$subs_result=tep_db_fetch_array($subs_query);
		$content='<table border="0" width="100%" cellpadding="2" cellspacing="0">
						<tr><td class="dashPopTitle" align="left">';
		if($subs_result["d_type"]=="E")
			$content.=' Reservation';
		elseif($subs_result["d_type"]=="S")
			$content.=' Season Ticket';
		elseif($subs_result["d_type"]=="C")
			$content.=' Casual Individual';
		$content.=' </td></tr><tr>
							<td class="dashPopSubTitle" align="left">Purchase Date :'. format_date($subs_result["date_purchased"]) .'</td>
					</tr><tr><td class="smallText" align="left">';
		if($subs_result["d_type"]=="E")
		{
			 $content.=$subs_result["del_count"] .' - session</td></tr></table>';
		}
		elseif($subs_result["d_type"]=="S")
		{
			 $content.=$subs_result['deliveries'] . ' deliveries to be used in ' . $subs_result["subscription_period"] . ' days</td></tr></table>';
		}
		elseif($subs_result["d_type"]=="C")
		{
			 $content.=$subs_result['deliveries'] . ' deliveries per ' . $subs_result['deliveries_perday'] . ' days to be used in ' . $subs_result["subscription_period"] . ' days</td></tr></table>';
		}
		echo $content;
		exit;
	}else */
	if($command=="fetch_date_details"){
		$event=isset($HTTP_GET_VARS["sel_event"])?(int)$HTTP_GET_VARS["sel_event"]:-1;
		$date_query=tep_db_query("SELECT s.start_date,s.sessions_id,e.events_id from " . TABLE_EVENTS_SESSIONS . " s," .
					TABLE_EVENTS . " e where s.events_id=e.events_id and e.events_id='" . (int)$event .  "'" . EVENTS_CONDITION_STATUS  . " order by e.events_id,s.start_date");
		while($date_result=tep_db_fetch_array($date_query))
			$content.= $date_result["sessions_id"] . ':' . format_date($date_result["start_date"]) . '#';
		echo $content;
	}else if($command=='add_scustomer'){		
		$select_order=$HTTP_POST_VARS["select_order"];
		$sessions_id=$HTTP_POST_VARS["sel_session"];
		$events_id=$HTTP_POST_VARS["sel_event"];
		$override=$HTTP_GET_VARS["override"];
		$overbook=$HTTP_POST_VARS["chk_overbook"];		
		$check_query=tep_db_query("select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " e where e.sessions_id='" . (int)$sessions_id . "' and e.events_id='" . (int)$events_id ."' and e.customers_id='" . (int)$select_order . "'");
		$check=tep_db_fetch_array($check_query);
		if($check['cnt']<=0)
		{
			if($override)
			{
				$customer_query=tep_db_query("SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone from " .TABLE_CUSTOMERS . " c where  c.customers_id='" . (int)$select_order . "'");
				$customer_result=tep_db_fetch_array($customer_query);
				$customer_result["customers_paid"]="Y";
				$customer_result["events_id"]=$events_id;
				$customer_result["sessions_id"]=$sessions_id;
				$customer_result["attendees_type"]="E";
				$customer_result["customers_paid_type"]='';
				tep_db_perform(TABLE_EVENTS_ATTENDEES_CONFIRM,$customer_result);
				response_display('success',$select_order);
			} else {
				//---check for the present of event---
				  $type='E';
				  $customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone,op.final_price,o.payment_method as customers_paid_type,o.orders_id from " .
											TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_CUSTOMERS . " c where " . 
											" o.orders_id=op.orders_id and o.customers_id=c.customers_id and op.products_type='E' and op.events_type='R' and o.customers_id='" . (int)$select_order . "' and op.products_id='" . (int)$sessions_id . "'");
				 if(tep_db_num_rows($customer_query)<=0)
				 {
				 	//---check for the presence of subscription--
					$subscription_ids=tep_get_linked_subscription($events_id);
				    $customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone,op.final_price,o.payment_method as customers_paid_type,o.orders_id from " .
					TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_CUSTOMERS . " c," . TABLE_SUBSCRIPTIONS . " su where " . 
					" o.orders_id=op.orders_id and su.subscription_id=op.products_id and o.customers_id=c.customers_id and op.products_type='S'  and o.customers_id='" . (int)$select_order . "' and op.products_id in(" . $subscription_ids . ") and DATE_ADD(o.date_purchased,INTERVAL su.subscription_period DAY) >='" . $current_date. "'");
					$type='S';
				 }
				 if(tep_db_num_rows($customer_query)>0)  //valid customer
				 {
				 	if(tep_check_attendees_checkin_count($events_id,$sessions_id,$type,$overbook))
					{
						$customer_result=tep_db_fetch_array($customer_query);
						if($type=='S')
						{
							$res_check=tep_check_subscription_delivery_count($events_id,$customer_result['orders_id'],$sessions_id);
							if($res_check==2)
								response_display('notvalidsession',$select_order);
							elseif($res_check==0)
								response_display('nosession',$select_order);
						}
						
						$status_query=tep_db_query("SELECT orders_status_id from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id='" . (int)$orders_id . "'");
						$status=tep_db_fetch_array($status_query);
						$add_customer=array("customers_id"=>$customer_result["customers_id"],
											"customers_firstname"=>$customer_result["customers_firstname"],
											"customers_lastname"=>$customer_result["customers_lastname"],
											"customers_telephone"=>$customer_result["customers_telephone"],
											"final_price"=>$customer_result["final_price"],
											"customers_paid_type"=>$customer_result["payment_method"],
											"customers_paid"=>((int)$status["order_status_id"]>1)?"Y":"N",
											"events_id"=>$events_id,
											"sessions_id"=>$sessions_id,
											"attendees_type"=>$type);
						tep_db_perform(TABLE_EVENTS_ATTENDEES_CONFIRM,$add_customer);
						response_display('success',$select_order);
					}else
						response_display('notvalid',$select_order);
				 }
				 else response_display('notvalid',$select_order);
			}								
		}
		else
		response_display('duplicate',$select_order);
	}else if($command=='add_bcustomer'){		
		$select_order=$HTTP_POST_VARS["barcode_name"];
		$order_splt=split("-",$select_order);
		$orders_id=$order_splt[0];
		$customer_id=$order_splt[1];
		$sessions_id=$HTTP_POST_VARS["sel_session"];
		$events_id=$HTTP_POST_VARS["sel_event"];
		$type='E';
		$overbook=$HTTP_POST_VARS["chk_overbook"];
 	    
		$customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone,op.final_price,o.payment_method as customers_paid_type from " .
								TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_CUSTOMERS . " c where " . 
								" o.orders_id=op.orders_id and o.customers_id=c.customers_id and op.products_type='E' and op.events_type='R'  and o.orders_id='" . (int)$orders_id . "' and o.customers_id='". (int)$customer_id. "' and op.products_id='" . (int)$sessions_id . "'");
		if(tep_db_num_rows($customer_query)<=0)
		{
			$subscription_ids=tep_get_linked_subscription($events_id);
		    $customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone,op.final_price,o.payment_method as customers_paid_type from " .
			TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_CUSTOMERS . " c," . TABLE_SUBSCRIPTIONS . " su where " . 
			" o.orders_id=op.orders_id and su.subscription_id=op.products_id and o.customers_id=c.customers_id and op.products_type='S'  and o.customers_id='" . (int)$customer_id . "' and op.products_id in(" . $subscription_ids . ") and DATE_ADD(o.date_purchased,INTERVAL su.subscription_period DAY) >='" . $current_date. "' and o.orders_id='" . (int)$orders_id . "'");
			$type='S';
		}
		if(tep_db_num_rows($customer_query)>0)
		{
			$check_query=tep_db_query("select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " e," . TABLE_ORDERS ." o where e.sessions_id='" . (int)$sessions_id . "' and e.events_id='" . (int)$events_id ."' and e.customers_id=o.customers_id and o.orders_id='" . (int)$orders_id . "'");
			$check=tep_db_fetch_array($check_query);
			if($check['cnt']<=0)
			{
				if(!tep_check_attendees_checkin_count($events_id,$sessions_id,$type,$overbook))
					response_display('error',$customer_id);
				if($type=='S')
				{
					$res_check=tep_check_subscription_delivery_count($events_id,$orders_id,$sessions_id);
					if($res_check==2)
						response_display('notvalidsession',$customer_id);						
					elseif($res_check==0)
						response_display('nosession',$customer_id);
				}
				$customer_result=tep_db_fetch_array($customer_query);
				$status_query=tep_db_query("SELECT orders_status_id from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id='" . (int)$orders_id . "'");
				$status=tep_db_fetch_array($status_query);
				$customer_result["customers_paid"]=((int)$status["order_status_id"]>1)?"Y":"N";
				$customer_result["events_id"]=$events_id;
				$customer_result["sessions_id"]=$sessions_id;
				$customer_result["attendees_type"]=$type;
				tep_db_perform(TABLE_EVENTS_ATTENDEES_CONFIRM,$customer_result);
				response_display('success',$customer_id);				
			}
			else response_display('duplicate',$customer_id);
		}
		else response_display('notvalid',$customer_id);
				
	}else if($command=='search') {
		table_write();
		
	}	
	else if($command=='add_customers'){
		$list=$HTTP_POST_VARS["select_order_attendees"];
		if (count($list)>0){
			for ($icnt=0;$icnt<count($list);$icnt++){
				$list_splt=split("-",$list[$icnt]);

				$orders_id=$list_splt[0];
				$sessions_id=$list_splt[1];
				$events_id=$list_splt[2];
				$customer_query=tep_db_query(	"SELECT c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_telephone,op.products_id as sessions_id,op.final_price,o.payment_method as customers_paid_type from " .
												TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," . TABLE_CUSTOMERS . " c where " . 
												" o.orders_id=op.orders_id and o.customers_id=c.customers_id and op.products_type='E' and op.events_type='R' and op.products_id='" . (int)$sessions_id . "' and o.orders_id='" . (int)$orders_id . "'");
				$customer_result=tep_db_fetch_array($customer_query);
				$status_query=tep_db_query("SELECT orders_status_id from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id='" . (int)$orders_id . "'");
				$status=tep_db_fetch_array($status_query);
				$customer_result["customers_paid"]=((int)$status["order_status_id"]>1)?"Y":"N";
				$customer_result["events_id"]=$events_id;
				tep_db_perform(TABLE_EVENTS_ATTENDEES_CONFIRM,$customer_result);				
			}
		}
		response_display('success');		
	}
	exit;
  }
//ending fetch details	

?>
<!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">
<style type="text/css">
	#pup {position:absolute; visibility:hidden; z-index:200; width:130; }
	.dashPopSubTitle{
	font-family:Arial, Verdana,  sans-serif;
	font-size:10px;
	font-weight:normal;
}
.dashPopTitle{
	font-family:Arial,Verdana,  sans-serif;
	font-size:11px;
	font-weight:bold;
}
.dashPopBoxTop{
	border-top:1px solid #898D7A;
	background-color:#dddddd;
}
.dashPopBoxRight{
	border-right:1px solid #898D7A;
	background-color:#dddddd;
}
.dashPopBoxContent{
	background-color:#dddddd;
}
.dashPopBoxBottom{
	border-bottom:1px solid #898D7A;
	background-color:#dddddd;
}
.dashPopBoxTopRight{
	border-top:1px solid #898D7A;
	border-right:1px solid #898D7A;
	background-color:#dddddd;
}
.dashPopBoxBottomRight{
	border-right:1px solid #898D7A;
	border-bottom:1px solid #898D7A;
	background-color:#dddddd;
}

</style> 
</head>
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script language="JavaScript" src="includes/date-picker.js"></script>
<script language="javascript" src="includes/http.js"></script>
<script language="JavaScript">

	var cEvent="";
	var baby=new Array();
	baby[1]="";
	var openpopup=0;
	var prev_x=-1;
	var prev_y=-1;
	var last_y=-1;
	var enter_cnt=0;
	scrollDashAmount=30;
	
	  var prevID;
	  var timerID;
	  var cEvent;

		
 function pop_config(e,row,id){
	if (row.edit) return;
	prevID=id;
	cEvent=e;
	row.pop_on=true;
	show_description(id);
  }
  function close_config(row,id){
  	if (!row.pop_on || row.edit) return;
	prevID=false;
  	kill();
  }
/*	function showpopup(o_id,e_id,y,x)
	{
			// check if popup has already opened
		if (prev_x==x && prev_y==y) return;
		var content;
		content='<table border="0"  width="100%" cellpadding="0" cellspacing="0">'+
					'<tr><td valign="top"><table border="0" width="100%" cellpadding="0" cellspacing="0" height="100%">'+
					'<tr>'+
						'<td class="dashPopBoxTop" valign="top" width="6" style="height:5px"><img src="images/pixel_trans.gif" width="1" height="22"></td>'+
						'<td valign="top" id="popContent" rowspan="2" class="dashPopBoxTop" nowrap style="height:100%">';
		// if type is session then display message loading
		if (prev_y!=y){
			content+="<table border='0' cellpadding='0' cellspacing='0' height='150' width='100%'><tr><td valign='middle' align='center' class='main'><?php echo TEXT_LOADING;?></td></tr></table>";
		} else {
			content+=document.getElementById("cacheContent").innerHTML;
		}

		content+=		'</td><td class="dashPopBoxTopRight" width="6" valign="top" style="height:5px"><img src="images/pixel_trans.gif" width="1" height="22"></td></tr>'+
					'<tr><td class="dashPopBoxContent" width="6">&nbsp;</td><td class="dashPopBoxRight" width="6">&nbsp;</td></tr>'+
							'<tr height="3">'+
								'<td class="dashPopBoxBottom" width="6"><img src="images/pixel_trans.gif" width="1" height="3"></td>'+
								'<td class="dashPopBoxBottom"><img src="images/pixel_trans.gif" width="1" height="3"></td>'+
								'<td class="dashPopBoxBottomRight" width="6"><img src="images/pixel_trans.gif" width="1" height="3"></td></tr></table></td></tr></table>';

		baby[1]=content;
		last_y=y;

		popwidth=150;

		prev_x=x;
		
		if (baby[1]!="") popup("1","");
		// if needed to get the contents using ajax
	
		if (prev_y!=y){
			var action_type=document.getElementById("action_type");
			if(action_type) action_type.value='';	
			command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN,'command=fetch_sub_details');?>&order_id="+o_id+"&event_id="+e_id;
			do_get_command(command);
		}
	} */
	function do_result(result){
		var customer=new Array;
		var action_type=document.getElementById("action_type");	
		if(result.indexOf('^')>=0)
		{
			temp=result.split('^');
			for(i=0;i<temp.length-1;i++)
			{
				content=temp[i];
				temp2=content.split(':');
				customer[i]=new Array(2);
				customer[i][0]=temp2[0];
				customer[i][1]=temp2[1];
			}
			Loadcustomer(customer);
		}
		else if(result.indexOf('#')>=0)
		{
			temp=result.split('#');
			for(i=0;i<temp.length-1;i++)
			{
				content=temp[i];
				temp2=content.split(':');
				dates[i]=new Array(2);
				dates[i][0]=temp2[0];
				dates[i][1]=temp2[1];
			}
			fill_date(dates);
			getcustomers();
		}
		//else if(result!="") 
			//do_result_popup(result);		
		if(action_type && action_type.value!='' && document.getElementById("search_details"))  {
			document.getElementById("search_details").innerHTML=result;
			//document.getElementById("search_details").style.zIndex="1";
		}	
	}

	function do_result_popup(result){
		// assign the result content
		element=document.getElementById("popContent");
		if (element) element.innerHTML=result;
		prev_y=last_y;
		document.getElementById("cacheContent").innerHTML=result;
	}

	function closepopup(){
		do_close();
		prev_x=-1;
		kill();
	}
</script>
<script language="JavaScript">
	var dates=Array();
	var dates_text=Array();
	var command="";	
	function init_page(mode)
	{
		if(mode!="") {
			if(mode==1)
				document.f.disp_reserve.checked=false;
			else if(mode==2)	
				document.f.disp_reserve.checked=true;
		}
	}
	function getaction() {
		check_mode=document.f.disp_reserve.checked;
		if(check_mode==false)
			doaction(1); // display attendees
		else if(check_mode==true)
			doaction(2); // display reservation & attendees
	} 
	function add_customer(id)
	{
		var error=false;	
		var action_type=document.getElementById("action_type");	
		if(document.f.select_order.selectedIndex>=0)
			selected=true;	
		if (selected){
			document.f.post_action.value="screen";
			if(id==2){
				command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN,'command=add_scustomer&override=1');?>";
				if(action_type) action_type.value='add_scustomer';
			}else{
				command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN ,'command=add_scustomer');?>";						
				if(action_type) action_type.value='add_scustomer';
			}
		}else if(id==2){
			alert("<?php echo ERR_NOTVALID_CUSTOMERS;?>");
			error=true;
		}else{
			alert("<?php echo ERR_SELECT_CUSTOMERS;?>");
			error=true;
		}
		if(command!="" && !error) {
			do_post_command('f',command);
			if(document.getElementById("search_details")) document.getElementById("search_details").innerHTML="<img src='images/24-1.gif' alt='Loading...' title='Loading...'>";
		}
	}
	function dooverbook(cus_id)
	{
		if(confirm("Are you sure to Override this customer?"))
		{
			with(document.f)
			{
				
				for(i=0;i<select_order.length;i++)
				{
					if(select_order.options[i].value==cus_id)
					{
						select_order.options[i].selected=true;
						break;
					}
				}
			}
			add_customer(2);
		}
	}

	function add_barcustomer()
	{
		bvalue=document.f.barcode_name.value;
		var action_type=document.getElementById("action_type");
		selected=true;
		if(bvalue=="" || bvalue.indexOf('-')<0)
			selected=false;
		if(selected && bvalue.indexOf('-')>=0)
		{
			tarr=bvalue.split('-');
			if(tarr.length==2)
			{
				if(isNaN(tarr[0]) || isNaN(tarr[1]))				
					selected=false;				
			}else selected=false;			
		}
		if (selected){			
			command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN ,'command=add_bcustomer');?>";			
			if(action_type) action_type.value='add_bcustomer';	
		}else {
			alert("<?php echo ERR_ENTER_BARCODE;?>");	
			return;
		}
		if(command!=""){
		 do_post_command('f',command);
		 if(document.getElementById("search_details")) document.getElementById("search_details").innerHTML="<img src='images/24-1.gif' alt='Loading...' title='Loading...'>";
	    }
	}

	function doaction(mode) {
		document.f.mode.value=mode;
		var action_type=document.getElementById("action_type");
		command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN,'command=search');?>";		
		if(action_type) action_type.value='search';	
		if(command!=""){
		 do_post_command('f',command);
		 if(document.getElementById("search_details")) document.getElementById("search_details").innerHTML="<img src='images/24-1.gif' alt='Loading...' title='Loading...'>";
		} 	
	}
	
	function move_reserve(sid, cid) {
		document.f.sid.value=sid;
		document.f.cid.value=cid;
		document.f.event_attend.value=1;
		document.f.submit();
	}	
	
</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<script language="javascript" src="includes/popup.js"></script>
<script language="javascript">
function Loadcustomer(cus)
{
	with (document.f) {
		for(i=select_order.options.length;i>=0;i--) {
			select_order.options[i]=null;
		}
		var opn=new Option('<?php echo TEXT_SELECT_CUSTOMER;?>','-1');
		select_order.options[0]=opn;
		select_order.options[0].selected=true;

		for(i=0; i < cus.length; i++){
				var opn=new Option(cus[i][1],cus[i][0]);
				select_order.options[select_order.options.length] = opn;
		}
	}
}

 function getcustomers()
	{
		event_id=document.f.sel_event.value;
		instructor=document.f.sel_instructor.value;
		session=document.f.sel_session.value;
		//command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN);?>?action=select_customer&command=fetch_customer_details&sel_event="+event_id+"&sel_instructor="+instructor+"&sel_session="+session;
		//do_get_command(command);
	}
	function getdates()
	{
		var action_type=document.getElementById("action_type");
		if(action_type) action_type.value='';	
		event_id=document.f.sel_event.value;
		command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN, 'command=fetch_date_details');?>&sel_event="+event_id;
		do_get_command(command);
		
	}
	 function fill_date(dates){
			with (document.f) {	
				for(i=sel_session.options.length;i>=0;i--) {
					sel_session.options[i]=null;
				}
				for(i=0; i < dates.length; i++){
						var opn=new Option(dates[i][1],dates[i][0]);
						sel_session.options[sel_session.options.length] = opn;
						if(dates[i][1]=='<?php echo format_date($current_date);?>')
							sel_session.options[sel_session.options.length-1].selected=true;
				}
				if (dates.length>1 && sel_session.selectedIndex<0) sel_session.selectedIndex=0;
			}
	}

</script>
<div id="spiffycalendar" class="text"></div>
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->
<table id="holetable" border="0" width="100%" cellspacing="2" cellpadding="2">
<tr>
	<td align=left valign="top" id="formtable" width="100%">
		<table border="0" cellspacing="0" cellpadding="2" width="100%">
		<form name="f" action="events_check_in.php">
			<?php
						echo tep_draw_hidden_field("mode",$search_mode);
						echo tep_draw_hidden_field('event_attend',$event_attend);
						echo tep_draw_hidden_field('sid',$sid);
						echo tep_draw_hidden_field('cid',$cid);
						echo tep_draw_hidden_field("post_action");
						echo tep_draw_hidden_field("action_type");					
			?>
			<tr class="cell_bg_report_header">
				<td>
					<table border="0" cellspacing="3" cellpadding="2"  width="100%" class="searchArea">
					<tr>
						<td class="main">
							<table cellpadding="0" cellspacing="0" border="0" width="100%" >
								<tr>
								<?php
									$all_events_array=array();
									$all_events_array = tep_get_events_array_single();
									if(sizeof($all_events_array)<=0) echo '<td colspan="2">Events are not Available</td>';
									else { ?> 
										<td align="left" class="main"><?php echo TEXT_EVENT . '&nbsp;&nbsp;';?><?php echo tep_draw_event_select_menu('sel_event',$all_events_array,$event,' id="sel_event" onchange="javascript:getdates();"') . '&nbsp;&nbsp;';?> </td>
									<?php }?>	
										<td align="right"  class="main"><?php echo TEXT_INSTRUCTOR . '&nbsp;&nbsp;';?><?php echo tep_draw_pull_down_menu("sel_instructor",$instructors_array,$instructor,'onchange="javascript:getcustomers()"') . '&nbsp;&nbsp;' ; ?></td>
										<td align="right"  class="main"><?php echo TEXT_SESSION . '&nbsp;&nbsp;';?><?php echo  tep_draw_pull_down_menu("sel_session",$date_array,$session,'onchange="javascript:getcustomers()"')  ;?></td>						 
									</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td class="main"><table cellpadding="2" cellspacing="0" width="100%" border="0">
							<tr>
								<Td class="main" colspan="2"><?php echo TEXT_ADD_BY_NAME?></Td>
								<td class="main" colspan="2"><?php echo TEXT_ADD_BY_BARCODE?></td>
							</tr>
							<tr>
								<div id="customer_list" style="position:absolute;display:none;width:100px;">
									<?php //echo tep_draw_pull_down_menu('select_order',$customer_array,'','"style=width:100px" size=5 class="customerSelect" multiple onClick="javascript:setListboxText(0);toggleList(0);" onFocus="javascript:toggleList(1);" onBlur="javascript:toggleList(0);"');
									echo $SelectCustomerBox;?>
								</div>
								<td class="main" valign=top width="80" nowrap>
								  <?php echo tep_draw_input_field('customer_name','','size="20"  onFocus="javascript:toggleText(1);" onBlur="javascript:toggleText(0);" style="width:400px;valign:top"') ; ?>
								  </td>
								  <td>
								  <a href='javascript:add_customer(1);'><?php echo tep_image_button('button_add.gif',IMAGE_ADD_CUSTOMER,'align=absmiddle');?></a>
								</td>

								<td class="main" valign="top" nowrap>
								<?php echo tep_draw_input_field('barcode_name','','size="20"  style="width:220px;"') ; ?>
								</td>
								<td align="right">
								<a href='javascript:add_barcustomer();'><?php echo tep_image_button('button_add.gif',IMAGE_ADD_CUSTOMER,'align=absmiddle');?></a>
								</td>
							</tr>
						</table></td>	
					</tr>
					<tr>
						<td class="main">
							<table cellpadding="0" cellspacing="0" width="100%">
							<tr>
								<td class="main">
								 <?php 
										if(strpos($result_array[1]['id'],"," .$login_groups_id .",")!==false)
										  echo tep_draw_checkbox_field('chk_overbook','1',$overbook,'') . ' ' . TEXT_OVERBOOK_RESERVATIONS . '&nbsp;&nbsp;&nbsp;';
									?>
								</td>
								<td  class="main"><?php echo tep_draw_checkbox_field('disp_reserve', $disp_reserve ,'','') . '&nbsp;' . TEXT_DISPLAY_RESERVATIONS ; ?></td>
								<td class="main" align="right">
									 <?php echo tep_image_button('button_report_search.gif','','onClick=getaction(); style=cursor:hand;cursor:pointer;');?>
								</td>	
							</tr>
							</table>
						</td>
					</tr>
				</table>
				</td>
			</tr>	
			<tr>
				<td align="left" width="100%">
					<div id="search_details" style="position:absolute;"></div>
				</td>
			</tr>
		</form>
		</table>
	</td>
</tr>				
<tr>
	<td><?php echo tep_draw_separator('pixel_trans.gif');?></td>
</tr>
	<?php if ($search_mode=="1" || $found_results) {
	?>
	<script language="JavaScript">
			function add_selected(){
				var choice_box=document.f.elements["select_order_attendees[]"];
				var selected=false;
				if (choice_box.length) { // multiple box
					for (icnt=0;icnt<choice_box.length;icnt++){
						if(choice_box[icnt].checked){
							selected=true;
							break;
						}
					}
				} else {
					if(choice_box.checked){
						selected=true;
					}
				}
				if (selected){
					document.f.action="<?php echo FILENAME_EVENT_CHECKIN . '?action=add_customers';?>";
					document.f.submit();
					return;
				}
				alert("<?php echo ERR_SELECT_CUSTOMERS;?>");
			}
			function select_all_boxes(){
				var all_box=document.f.select_all;
				var choice_box=document.f.elements["select_order_attendees[]"];
				if(!choice_box) return "";
				if (choice_box[0]) { // multiple box
					for (icnt=0;icnt<choice_box.length;icnt++){
						choice_box[icnt].checked=all_box.checked;
					}
				} else {
					choice_box.checked=all_box.checked;
				}
			}
		
		</script>
	<?php 
?>
<tr>
	<td id="cacheContent" style="display:none"></td>
</tr>
	<script language="JavaScript">
		getcustomers();
		var iex=(document.all);//ie
		var na6=(window.sidebar);//netscape 6.2
		if(na6) document.f.customer_name.addEventListener("keyup",selectList,true);
		if(iex) document.f.customer_name.onkeyup=selectList;
		if(na6) document.f.customer_name.addEventListener("keydown",scrollList,true);
		if(iex) document.f.customer_name.onkeydown=scrollList;
		function page_navigation(arg1,arg2,arg3,arg4){
			var page="&page=1";
			if(document.getElementById("action_type")) document.getElementById("action_type").value='search';
			var obj=document.getElementById("page_1");
			if(arg2 && obj){
 			   if(arg4=='prev' && obj.selectedIndex>0) page="&page="+parseInt(obj.selectedIndex);
			   else if(arg4=='next') page="&page="+(parseInt(obj.selectedIndex)+2);
			   else if(arg4=='select') page="&page="+parseInt(obj.options[obj.selectedIndex].value);
			}	
			if(page!=""){
			  command="<?php echo tep_href_link(FILENAME_EVENT_CHECKIN, 'command=search');?>"+page;
			  do_post_command('f',command);
			}
		}
		function resize(){
			document.getElementById('customer_list').style.visibility="hidden";
			document.f.customer_name.blur();
		}
		var lastposition=0;
		var currentField="";
		var intervalId;
			function checkdropDown(){
				if (currentField==""){
					clearInterval(intervalId);
					hideList();
					intervalId="";
				}
			}
			function toggleText(mode){ 
				if (mode==1) {
					currentField="Text";
					showList();
					if (intervalId) clearInterval(intervalId);
					intervalId=setInterval("checkdropDown()",300);
				} else {
					currentField="";
				}
			}
			function toggleList(mode){
				if (mode==1){
					currentField="drop";
				} else {
					currentField="";
				}
			}
			function showList(){
				var listbox=document.getElementById("customer_list");
				var textbox=document.f.customer_name;
				listbox.style.visibility="visible";
				listbox.style.display="";
				var left = getPageOffsetLeft(textbox);
				var top =getPageOffsetTop(textbox);

				if(window.scrollMaxX >0)listbox.style.left=left;
				else listbox.style.left=left;
				listbox.style.top=top+17;
				
			}
			function hideList(){
				var listbox=document.getElementById("customer_list");
				var textbox=document.f.customer_name;
				setListboxText(1);
				listbox.style.display="none";
			}
			function scrollList(e){
				var listbox=document.f.select_order;

				if (iex) keyCode=window.event.keyCode;
				if (na6) keyCode=e.which;

				if (keyCode==40 || keyCode==38){
					if (keyCode==40 && listbox.selectedIndex>=0 && listbox.selectedIndex<listbox.options.length-1){
						listbox.selectedIndex+=1;
					} else if (keyCode==38 && listbox.selectedIndex>0 && listbox.selectedIndex<=listbox.options.length-1){
						listbox.selectedIndex-=1;
					}

					setListboxText(0);
					if (iex) window.event.returnValue=0;
					if (na6) e.returnValue=0;
					return;

				}
			}
			function selectList(e){
				var listbox=document.f.select_order;
				var search_word=document.f.customer_name.value;
				var text_length;
				var found=-1;
				var listbox_word;
				var eventObject;
				var keyCode=0;
				var fromPos=0;
				var toPos=0;
				if (!listbox.options || listbox.options.length<=0) return;
				if (search_word!="") {
					search_word=search_word.toLowerCase();
					found=binaryFind(listbox,search_word,0,listbox.options.length-1);
					if (found>=0)
						listbox.selectedIndex=found;
				}

			}
			function setListboxText(mode){
				var listbox=document.f.select_order;
				if (!listbox.options || listbox.options.length<=0 || listbox.selectedIndex<0) return;
				var textbox_name=document.f.customer_name;
				textbox_name.value=""
				textbox_name.value=listbox.options[listbox.options.selectedIndex].text;
				
				//document.f.submit();
			}
			function binaryFind(listBox,fWord,sPos,ePos){
				var listElement;
				var tWord;
				var mPos;
				if (sPos>ePos) return -1;
				mPos=sPos+Math.ceil((ePos-sPos)/2);
				
				if (mPos<0 || mPos>=listBox.options.length) return -1;
				listElement=listBox.options[mPos].innerHTML.toLowerCase();
				tWord=listElement.substr(0,fWord.length);

				if (tWord==fWord) return mPos;
				if (mPos<=0 || mPos>=listBox.options.length) return -1;
				
				if (fWord<tWord) return binaryFind(listBox,fWord,mPos+1,ePos);
				else return binaryFind(listBox,fWord,sPos,mPos-1);
			}
			
		</script>				<?php 
					if ($search_mode==1 && $view==1) {  //customer list box 
					// first select customer_id from events_attendees_confirm table
					
					$attend_ids="";
					$add_option="";
					$attend_query=tep_db_query("SELECT customers_id from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " where sessions_id='" . $session . "'");
					while($attend_result=tep_db_fetch_array($attend_query)){
						$attend_ids.=$attend_result["customers_id"] . "','";
					}
					if ($attend_ids!=""){
						$add_option=" and customers_id not in('" . substr($attend_ids,0,-2) . ") ";
					}
					
				?>
				<?php
					}
				}else { // if found_results
				?>
				<tr class='main'><Td align='center'><?php echo NO_RESULTS_FOUND; ?></td></tr>

				<?php }  // found results ?>
				<script>
					init_page('<?php echo $input_params['mode']; ?>');
				</script>
</table>
	<!-- footer //-->
	<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
	<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
 <script>
 var baby=new Array();
	baby[1]="";
	content_value=""; 
	function show_description(code){
		content_value = code;		
		content='<table class="tableArea" cellspacing="0" cellpadding="2" width="100%" ><tr><td class="dashPopBoxContent"><table cellpadding="2" cellspacing="0" width="100%"><tr><td class="main"><small>';
		content+=content_value;
		content+='</small></td></tr></table></td></tr></table>';
		popwidth=170;						
			baby[1]=content; 				
			if (baby[1]!=""){			
			popup("1","#D6F0F9");					
				//setTimeout('popup("1","#D6F0F9")',2500);
				//clearTimeout();										
			}							
    }
	</script>
 <?php
 function tep_get_session_last_date($ord_id)
{
 $session_query=tep_db_query("SELECT max(e.start_date) as session_last from " . TABLE_ORDERS_PRODUCTS . " op," . TABLE_EVENTS_SESSIONS . " e where e.sessions_id=op.products_id and op.orders_id='" . (int)$ord_id . "' and op.products_type='E' ");
 $session=tep_db_fetch_array($session_query);
 return $session['session_last'];

}
function tep_get_session_left($ord_id,$s_date)
{
 $count_query=tep_db_query("SELECT count(op.orders_id) as cnt from " . TABLE_ORDERS_PRODUCTS . " op," . TABLE_EVENTS_SESSIONS . " e where e.sessions_id=op.products_id and op.orders_id='" . (int)$ord_id . "' and op.products_type='E' and e.start_date>='" . $s_date . "'");
 $count=tep_db_fetch_array($count_query);
 return $count['cnt'];

} 

function tep_check_attendees_checkin_count($events_id,$sessions_id,$type,$overbook)
{
	$sql="select events_max_reserve,events_overbook_reserve,subscription_overbook_reserve from " . TABLE_EVENTS . " where events_id='" . (int)$events_id . "'";
	$event_query=tep_db_query($sql);
	$event=tep_db_fetch_array($event_query);
	$sql="select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " where events_id='" . (int)$events_id . "' and sessions_id='" . (int)$sessions_id . "'";
	$count_query=tep_db_query($sql);
	$e_count=tep_db_fetch_array($count_query);
	$add_reserve=0;
	if($overbook)
	{
		if($type=='E')
			$add_reserve=$event['events_overbook_reserve'];
		else
			$add_reserve=$event['subscription_overbook_reserve'];
	}
	if(($event['events_max_reserve'] + $add_reserve)>$e_count['cnt'])
		return true;
	else
     return false;
}
function tep_get_linked_subscription($events_id)
{
	$sub_query=tep_db_query("SELECT subscription_id from " . TABLE_EVENTS_TO_SUBSCRIPTIONS  . " where events_id='". (int)$events_id . "'") ;
	while($sub_result=tep_db_fetch_array($sub_query)){
		$subscription_ids.=$sub_result['subscription_id'] . ',';
	}
	if($subscription_ids!="")
		$subscription_ids=substr($subscription_ids,0,-1);
	else
		$subscription_ids='0';
	return $subscription_ids;
}
function tep_check_subscription_delivery_count($events_id,$orders_id,$sessions_id)
{
	$sql="select su.subscription_id,su.subscription_type,su.subscription_period,su.deliveries,su.deliveries_perday,o.date_purchased,o.customers_id from " . TABLE_SUBSCRIPTIONS . " su," . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op where op.orders_id=o.orders_id and op.products_id=su.subscription_id and op.products_type='S' and o.orders_id=" . (int)$orders_id;
	$sql_result=tep_db_query($sql);
	$datas=tep_db_fetch_array($sql_result);
	$session_date=tep_get_session_start_date($events_id,$sessions_id);
	$start_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($datas['date_purchased'])),(strftime("%d",strtotime($datas['date_purchased']))),strftime("%Y",strtotime($datas['date_purchased']))));
	$end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($start_date)),(strftime("%d",strtotime($start_date))+$datas['subscription_period']),strftime("%Y",strtotime($start_date))));
    if(!($session_date>=$start_date && $session_date<=$end_date))
      return 2;
    $count_sql="";	
	switch($datas['subscription_type'])
	{
		case "C":  //casual
			$no_of_slots=$datas['deliveries_perday'];
			$temp_start_date=$start_date;
			$temp_end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_start_date)),(strftime("%d",strtotime($temp_start_date))+$no_of_slots-1),strftime("%Y",strtotime($temp_start_date))));
			while(!($session_date>=$temp_start_date && $session_date<=$temp_end_date))
			{
				$temp_start_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_end_date)),(strftime("%d",strtotime($temp_end_date))+1),strftime("%Y",strtotime($temp_end_date))));
				$temp_end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_start_date)),(strftime("%d",strtotime($temp_start_date))+$no_of_slots-1),strftime("%Y",strtotime($temp_start_date))));
			}
			$count_sql="select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " ec," . TABLE_EVENTS_SESSIONS . " s where ec.sessions_id=s.sessions_id and ec.events_id=s.events_id and ec.events_id='" . (int)$events_id . "' and ec.customers_id='" . (int)$datas['customers_id'] . "' and s.start_date>='" . $temp_start_date . "' and s.start_date<='" . $temp_end_date . "'";
			break;
		case "S" ://seasonal
			$count_sql="select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " ec," . TABLE_EVENTS_SESSIONS . " s where ec.sessions_id=s.sessions_id and ec.events_id=s.events_id and ec.events_id='" . (int)$events_id . "' and ec.customers_id='" . (int)$datas['customers_id'] . "' and s.start_date>='" . $start_date . "' and s.start_date<='" . $end_date . "'";
			break;
	}
	if($count_sql!="")
	{
		$count_query=tep_db_query($count_sql);
		$count_data=tep_db_fetch_array($count_query);
		if($count_data['cnt']<$datas['deliveries'])
			return 1;
		else 
			return 0;
	}	
}
function tep_get_session_start_date($events_id,$sessions_id)
{
	$sql_ses="select start_date from " . TABLE_EVENTS_SESSIONS . "  where events_id='" . (int)$events_id . "' and sessions_id='" . (int)$sessions_id. "'";
	$sql_ses_result=tep_db_query($sql_ses);
	$datas_ses=tep_db_fetch_array($sql_ses_result);
	$session_date=$datas_ses['start_date'];
	return $session_date;
}
function get_subscription_details($events_id,$orders_id,$sessions_id)
{
	$sql="select su.subscription_id,su.subscription_type,su.subscription_period,su.deliveries,su.deliveries_perday,o.date_purchased,o.customers_id from " . TABLE_SUBSCRIPTIONS . " su," . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op where op.orders_id=o.orders_id and op.products_id=su.subscription_id and op.products_type='S' and o.orders_id=" . (int)$orders_id;
	$sql_result=tep_db_query($sql);
	$datas=tep_db_fetch_array($sql_result);
	$session_date=tep_get_session_start_date($events_id,$sessions_id);
	$start_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($datas['date_purchased'])),(strftime("%d",strtotime($datas['date_purchased']))),strftime("%Y",strtotime($datas['date_purchased']))));
	$end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($start_date)),(strftime("%d",strtotime($start_date))+$datas['subscription_period']),strftime("%Y",strtotime($start_date))));
    if(!($session_date>=$start_date && $session_date<=$end_date))
      return "";
    $count_sql="";
	switch($datas['subscription_type'])
	{
		case "C":  //casual
			$no_of_slots=$datas['deliveries_perday'];
			$temp_start_date=$start_date;
			$temp_end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_start_date)),(strftime("%d",strtotime($temp_start_date))+$no_of_slots-1),strftime("%Y",strtotime($temp_start_date))));
			while(!($session_date>=$temp_start_date && $session_date<=$temp_end_date))
			{
				$temp_start_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_end_date)),(strftime("%d",strtotime($temp_end_date))+1),strftime("%Y",strtotime($temp_end_date))));
				$temp_end_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($temp_start_date)),(strftime("%d",strtotime($temp_start_date))+$no_of_slots-1),strftime("%Y",strtotime($temp_start_date))));
			}
			$swhere="ec.sessions_id=s.sessions_id and ec.events_id=s.events_id and ec.events_id='" . (int)$events_id . "' and ec.customers_id='" . (int)$datas['customers_id'] . "' and s.start_date>='" . $temp_start_date . "' and s.start_date<='" . $temp_end_date . "'";
			$count_sql="select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " ec," . TABLE_EVENTS_SESSIONS . " s where ec.sessions_id=s.sessions_id and ec.events_id=s.events_id and " . $swhere;
			break;
		case "S" ://seasonal
			$swhere="ec.sessions_id=s.sessions_id and ec.events_id=s.events_id and ec.events_id='" . (int)$events_id . "' and ec.customers_id='" . (int)$datas['customers_id'] . "' and s.start_date>='" . $start_date . "' and s.start_date<='" . $end_date . "'";
			$count_sql="select count(*) as cnt from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " ec," . TABLE_EVENTS_SESSIONS . " s where " . $swhere ;
			break;
	}
	if($count_sql!="")
	{
		//echo $count_sql;
		$count_query=tep_db_query($count_sql);
		$count_data=tep_db_fetch_array($count_query);
		$remaining=$datas['deliveries']-$count_data['cnt'];
		 
		$date_sql=tep_db_query("select max(s.start_date) as end_date from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " ec," . TABLE_EVENTS_SESSIONS . " s where " . $swhere); 
		$date_field=tep_db_fetch_array($date_sql);
		
		return $datas['subscription_type']. '#' . $remaining . '#' . $date_field['end_date'] ;
	}
}

function table_write(){ 
	global  $found_results,$sql_result,$check,$page,$query_split,$query_split_numrows,$max_display_count,$printed_customers,$event,$session; 
?>
	<table border="0" cellspacing="0" cellpadding="2" width="100%">
		<?php 		    
			$display_record_count=0;
			$check=0;
			if($found_results) {
				?>
					<tr  class="dataTableHeadingTitleRow">
						<td class='dataTableHeadingContent' width="30">&nbsp;</td>
						<td class='dataTableHeadingContent' ><?php echo TEXT_FIRST_NAME;?></td>
						<td class='dataTableHeadingContent' ><?php echo TEXT_LAST_NAME;?></td>
						<td class='dataTableHeadingContent'  width="100"><?php echo TEXT_TYPE;?></td>
						<td class='dataTableHeadingContent' width="85"><?php echo TEXT_SESSION_LEFT;?></td>
						<td class='dataTableHeadingContent' width="85"><?php echo TEXT_LAST_SESSION;?></td>
						<td class='dataTableHeadingContent'><?php echo TEXT_R;?></td>
						<td class='dataTableHeadingContent' align="right"></td>
					</tr>
					<?php
						$icnt=0;
						$jcnt=0;
						$detail_array=array();
						$load_details="";
						while($row = tep_db_fetch_array($sql_result)) {
							////
							$content="";
						$order_id=$row['orders_id'];
						$events_id=$row["events_id"];
						 if ($order_id<=0) {
							$content=TEXT_NO_DETAILS ;
						}
						$subs_sql="select o.date_purchased,count(op.orders_id) as del_count,'E' as d_type from " . TABLE_ORDERS ." o,". TABLE_ORDERS_PRODUCTS . " op where op.orders_id=o.orders_id and op.products_type='E' and o.orders_id='" . (int)$order_id. "'  group by op.orders_id";
						$subs_query=tep_db_query($subs_sql);
						if(tep_db_num_rows($subs_query)<=0)
						   $subs_sql="select o.date_purchased,su.deliveries,su.deliveries_perday,su.subscription_period,su.subscription_type as d_type from " . TABLE_ORDERS ." o,". TABLE_ORDERS_PRODUCTS . " op," . TABLE_SUBSCRIPTIONS . " su where op.orders_id=o.orders_id and su.subscription_id=op.products_id and op.products_type='S' and o.orders_id='" . (int)$order_id. "'  group by op.orders_id";
						$subs_query=tep_db_query($subs_sql);
						if (tep_db_num_rows($subs_query)<=0) {
							$content=TEXT_NO_DETAILS;
						}
						$subs_result=tep_db_fetch_array($subs_query);
						if($subs_result["d_type"]=="E")
							$content.='<b>Reservation</b>';
						elseif($subs_result["d_type"]=="S")
							$content.='<b>Season Ticket</b>';
						elseif($subs_result["d_type"]=="C")
							$content.='<b>Casual Individual</b>';
						$content.=' <br>Purchase Date :'. format_date($subs_result["date_purchased"]) . '<br>';

						if($subs_result["d_type"]=="E")
						{
							 $content.=$subs_result["del_count"] .' - session';
						}
						elseif($subs_result["d_type"]=="S")
						{
							 $content.=$subs_result['deliveries'] . ' deliveries to be used in ' . $subs_result["subscription_period"] . ' days';
						}
						elseif($subs_result["d_type"]=="C")
						{
							 $content.=$subs_result['deliveries'] . ' deliveries per ' . $subs_result['deliveries_perday'] . ' days to be used in ' . $subs_result["subscription_period"] . ' days';
						}
						    $rec='<tr  id="defaultSelected"  class="dataTableRow" height="20" onMouseOver="javascript:rowOverEffect(this),pop_config(\'event\',this,\'' . $content . '\');" onMouseOut="javascript:rowOutEffect(this), close_config(this);"' ;
								if(isset($attend_details[$row["customers_id"]][$row["sessions_id"]]) || $search_mode==1)
									$rec.= ' onClick="move_reserve(\'' . $row['sessions_id'] . '\',\'' . $row['customers_id'] . '\')"';								
							$rec.= " >";			
							echo $rec;?>
							<td class='dataTableContent' style="cursor:hand" >
							  <?php
								if ($search_mode==2 && !isset($attend_details[$row["customers_id"]][$row["sessions_id"]])){
									echo tep_draw_checkbox_field('select_order_attendees[]',$row["orders_id"] . '-' . $row["products_id"] . "-" . $event);
									$check++;
								}
							  ?>	
							  </td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $row['customers_firstname']?></td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $row['customers_lastname']?></td>
							  <td class='dataTableContent' style="cursor:hand">
							  <?php 
								   $last_date="";
		      						$renewal="N";
									$session_left=0;
							  		if($row['products_type']!='E')
							  		{
										$var_res=get_subscription_details($row["events_id"],$row['orders_id'],$row["sessions_id"]);
										if($var_res!="")
										{
											$temp_arr=split("#",$var_res);
											if($temp_arr[0]=='C')
												echo 'Casual Individual';
											elseif($temp_arr[0]=='S')
												echo 'Season Ticket';
											$session_left=$temp_arr[1];
											$last_date=$temp_arr[2];
										}
								  }
								  else
								  {
										echo "Reservation";
										$session_left=tep_get_session_left($row['orders_id'],$row['start_date']);
										$last_date= tep_get_session_last_date($row['orders_id']);
								   }?></td>
							  <td class='dataTableContent' style="cursor:hand" align="center">
							  	<?php echo $session_left;?></td>
							  <td class='dataTableContent' style="cursor:hand"><?php 
							  			if($last_date!=""){
											$s_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($last_date)),(strftime("%d",strtotime($last_date))-$row['events_renewal_start']),strftime("%Y",strtotime($last_date))));
											$e_date=date("Y-m-d",mktime(0,0,0,strftime("%m",strtotime($last_date)),(strftime("%d",strtotime($last_date))-$row['events_renewal_end']),strftime("%Y",strtotime($last_date))));
							  				echo format_date($last_date);
											if($current_date<=$e_date && $current_date>=$s_date)
												$renewal="Y";
										}?></td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $renewal;?></td>
					    		<td class='dataTableContent' style="cursor:hand" align="center">
								<?php echo '<a href="' . FILENAME_CUSTOMERS . '?action=edit&return=ec&cID=' . $row['customers_id'] .  '">' . tep_image(DIR_WS_IMAGES . 'template.gif',IMAGE_CUSTOMER) . '</a>';?>
							  <?php echo '<a href="' . FILENAME_ORDERS . '?oId='. $row['orders_id'] . '&return=ec&page=1&action=edit&oID='. $row['orders_id'] . '">' . tep_image(DIR_WS_IMAGES .'reserve_view.gif',IMAGE_ORDERS) . '</a>';?>
							  </td>
						  </tr>
						  
					<?php 
								$display_record_count++;						
						}

						if($display_record_count<$max_display_count)
						{
							$offset=0;
							if($num_rows==0)
							{
							 $prev_count=$query_split_numrows-$non_order_count;
							 $d_remaining=fmod($prev_count,$max_display_count);

							 $c_page_number=$prev_count/$max_display_count;
							 if($d_remaining==0 && $page==$c_page_number+1)
								$offset=0;
							 else
							 	$offset = ($max_display_count * abs(($c_page_number-1)));
								//$offset = ($max_display_count -$d_remaining);
							}
							$limit_query .= " limit " . $offset . ", " . $max_display_count;
							$non_order_query=tep_db_query("SELECT * from " . TABLE_EVENTS_ATTENDEES_CONFIRM  . " where events_id='$event' and sessions_id='$session' and customers_id not in (" . $printed_customers . ") "  . " order by customers_firstname" . $limit_query) ;
							
							while($row=tep_db_fetch_array($non_order_query))
							{
								if($display_record_count>=$max_display_count) break;
								$rec="<tr class='dataTableRow' height='20' " ;
							    $rec.= "onClick=\"move_reserve('" . $row['sessions_id'] . "','" . $row['customers_id'] . "')\" "; 
								$rec.= " >";			
								echo $rec;		?>
							  <td class='dataTableContent' style="cursor:hand" > </td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $row['customers_firstname']?></td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $row['customers_lastname']?></td>
							  <td class='dataTableContent' style="cursor:hand"></td>
							  <td class='dataTableContent' style="cursor:hand" align="center">0</td>
							  <td class='dataTableContent' style="cursor:hand"></td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo 'N';?></td>
					  		<td class='dataTableContent' style="cursor:hand" align="right" nowrap><?php echo '<a href="' . FILENAME_CUSTOMERS . '?action=edit&return=ec&cID=' . $row['customers_id'] .  '">' . tep_image(DIR_WS_IMAGES . 'template.gif',IMAGE_CUSTOMER) . '</a>';?>
						  </tr>
							<?php 
							$display_record_count++;}
						} ?>
				<?php	}else { ?>
						<tr class='main'><Td  colspan='6' align='center'><?php echo NO_RESULTS_FOUND; ?></td></tr>
			  <?php }	?>
				
				<?php if ($check>0){ ?>
					<tr>
						<td colspan="8" align="left" class="smallText">
						<?php echo '<a href="javascript:add_selected();">' . tep_image_button('button_add.gif',IMAGE_ADD_CUSTOMER,'align=absmiddle') . '</a>';?>
						<?php echo tep_draw_checkbox_field("select_all",'','','','onClick="javascript:select_all_boxes();"') . TEXT_SELECT_ALL;?>
						</td>
					</tr>
				<?php 
						}  // if check
				?>
		<?php if ($found_results) {	?>
			<tr>
				<td colspan="8">
				<table border="0"  width="100%" cellspacing="0" cellpadding="2">
				 	<tr>			        
				  		<td class="smallText" width="50%" valign="top"><?php echo $query_split->display_count($query_split_numrows, $max_display_count, $page, TEXT_DISPLAY_NUMBER_OF_EVENTS); ?></td>
						<td class="smallText" width="50%" align="right"><?php echo $query_split->display_script_links($query_split_numrows, $max_display_count, MAX_DISPLAY_PAGE_LINKS, $page,1,'page_navigation(\'\'','1');?>&nbsp;</td>
					</tr>
				</table>
				</td>
				</tr>
		<?php } ?>
		 </table>
<?php }
function response_display($response='',$cid=''){
	global $HTTP_GET_VARS,$login_groups_id,$result_array;	
	 if($cid)
			$disp_customer_name=trim(tep_customers_name($cid));
	 	if($response=="success")
		 {
			$p_class="messageStackSuccess";
			$d_img='success.gif';
			if($disp_customer_name!="")
				$d_text=sprintf(TEXT_SUCCESSFUL_CHECK_IN,$disp_customer_name);
			else
				$d_text=TEXT_SUCCESSFUL_CHECK_IN_ALL;
		}elseif($response=="duplicate"){
			$p_class="messageStackError";
			$d_img='error.gif';
			$d_text=sprintf(TEXT_ALREADY_CHECK_IN,$disp_customer_name);
		}elseif($response=="notvalid"){
			$p_class="messageStackError";
			$d_img='error.gif';
			if($disp_customer_name!="")
				$d_text=sprintf(TEXT_NOTVALID_CHECK_IN,$disp_customer_name);
			else
				$d_text=TEXT_ERROR_CHECK_IN;
		}elseif($response=="error"){
			$p_class="messageStackError";
			$d_img='error.gif';
			$d_text=TEXT_ERROR_CHECK_IN;
		}elseif($response=="nosession"){
			$p_class="messageStackError";
			$d_img='error.gif';
			if($disp_customer_name!="")
				$d_text=sprintf(TEXT_NO_SESSIONS,$disp_customer_name);
			else
				$d_text=TEXT_ERROR_CHECK_IN;
		}elseif($response=="notvalidsession"){
			$p_class="messageStackError";
			$d_img='error.gif';
			$d_text=TEXT_NOT_INCLUDED_SESSIONS;
		}
		if($response!=""){?> 
      	   <table border="0" cellpadding="0" cellspacing="0" width="100%">
			<tr><td> 
				<table class="<?php echo $p_class?>" width="100%">
				<tr><td><?php echo tep_image(DIR_WS_ICONS . $d_img) . '&nbsp;' ;
				echo $d_text;
				if($response=="notvalid" && $disp_customer_name!="")
				{
					if (strpos($result_array[0]['id'],"," . $login_groups_id . ",")!==false)
	 					
						echo " &nbsp;<input type=button name='btn_override' value='Override' onclick=javascript:dooverbook('" . $cid . "');>";
				}
			    ?></td></tr>
				</table>
			</td></tr>
		</table>	
<?php }
  }		
?>
