<?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
*/
////
// Return true if the events category has subcategories
// TABLES: events_categories

// use condition in all event status checking 

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();

define('EVENTS_CONDITION_STATUS'," and (e.events_status=1 or ( e.events_status=2 and e.sessions_start_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "') or (e.events_status>=3 and e.sessions_end_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "')) and date_format(e.events_date_available,'%Y-%m-%d')<='" . date('Y-m-d H:i:s',getServerDate(false)) . "'");
define('EVENTS_VIEW_CONDITION_STATUS'," and (e.events_status=1 or ( e.events_status=2 and e.sessions_start_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "') or (e.events_status>=3 and e.sessions_end_date>='" . date('Y-m-d H:i:s',getServerDate(false)) . "')) and date_format(e.events_date_available,'%Y-%m-%d')>'" . date('Y-m-d H:i:s',getServerDate(false)) . "'");
define('SUBSCRIPTION_CONDITION_STATUS'," and (su.subscription_status=1) and date_format(su.subscription_date_available,'%Y-%m-%d')<='" . date('Y-m-d H:i:s',getServerDate(false)) . "'");
define('PRODUCTS_CONDITION_STATUS'," and (p.products_status=1) and date_format(p.products_date_available,'%Y-%m-%d')<='" . date('Y-m-d H:i:s',getServerDate(false)) . "'");
define('TEXT_COMPLETE_PAYMENT','Complete Payment');
// check if an category has subcategories
  function tep_has_events_category_subcategories($events_category_id) {
    $child_events_category_query = tep_db_query("select count(*) as count from " . TABLE_EVENTS_CATEGORIES . " where parent_id = '" . (int)$events_category_id . "'");
    $child_events_category = tep_db_fetch_array($child_events_category_query);

    if ($child_events_category['count'] > 0) {
      return true;
    } else {
      return false;
    }
  }
  
  function tep_get_events_subcategories(&$subcategories_array, $parent_id = 0) {
    $subcategories_query = tep_db_query("select events_categories_id from " . TABLE_EVENTS_CATEGORIES . " where parent_id = '" . (int)$parent_id . "'");
    while ($subcategories = tep_db_fetch_array($subcategories_query)) {
      $subcategories_array[sizeof($subcategories_array)] = $subcategories['events_categories_id'];
      if ($subcategories['events_categories_id'] != $parent_id) {
        tep_get_events_subcategories($subcategories_array, $subcategories['events_categories_id']);
      }
    }
  }


////
// Return the number of events in a category
// TABLES: events, events_to_events categories, categories
  function tep_count_events_in_events_category($events_category_id, $include_inactive = false) {
    $events_count = 0;
    if ($include_inactive == true) {
      $events_query = tep_db_query("select count(*) as total from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " e2c where e.events_id = e2c.events_id and e2c.events_categories_id = '" . (int)$events_category_id . "'");
    } else {
      $events_query = tep_db_query("select count(*) as total from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " e2c where e.events_id = e2c.events_id and e.events_status >= 1 and e2c.events_categories_id = '" . (int)$events_category_id . "'");
    }
    $events = tep_db_fetch_array($events_query);
    $events_count += $events['total'];

    $child_events_categories_query = tep_db_query("select events_categories_id from " . TABLE_EVENTS_CATEGORIES . " where parent_id = '" . (int)$events_category_id . "'");
    if (tep_db_num_rows($child_events_categories_query)) {
      while ($child_events_categories = tep_db_fetch_array($child_events_categories_query)) {
        $events_count += tep_count_events_in_events_category($child_events_categories['events_categories_id'], $include_inactive);
      }
    }

    return $events_count;
  }

////
// Parse and secure the ecPath parameter values
  function tep_parse_events_category_path($ecPath) {
// make sure the category IDs are integers
    $ecPath_array = array_map('tep_string_to_int', explode('_', $ecPath));

// make sure no duplicate category IDs exist which could lock the server in a loop
    $tmp_array = array();
    $n = sizeof($ecPath_array);
    for ($i=0; $i<$n; $i++) {
      if (!in_array($ecPath_array[$i], $tmp_array)) {
        $tmp_array[] = $ecPath_array[$i];
      }
    }

    return $tmp_array;
  }

  
////
// Generate a path to events categories
  function tep_get_events_path($current_events_category_id = '') {
    global $ecPath_array;

    if (tep_not_null($current_events_category_id)) {
      $ecp_size = sizeof($ecPath_array);
      if ($ecp_size == 0) {
        $ecPath_new = $current_events_category_id;
      } else {
        $ecPath_new = '';
        $last_events_category_query = tep_db_query("select parent_id from " . TABLE_EVENTS_CATEGORIES . " where events_categories_id = '" . (int)$ecPath_array[($ecp_size-1)] . "'");
        $last_events_category = tep_db_fetch_array($last_events_category_query);

        $current_events_category_query = tep_db_query("select parent_id from " . TABLE_EVENTS_CATEGORIES . " where events_categories_id = '" . (int)$current_events_category_id . "'");
        $current_events_category = tep_db_fetch_array($current_events_category_query);

        if ($last_events_category['parent_id'] == $current_events_category['parent_id']) {
          for ($i=0; $i<($ecp_size-1); $i++) {
            $ecPath_new .= '_' . $ecPath_array[$i];
          }
        } else {
          for ($i=0; $i<$ecp_size; $i++) {
            $ecPath_new .= '_' . $ecPath_array[$i];
          }
        }
        $ecPath_new .= '_' . $current_events_category_id;

        if (substr($ecPath_new, 0, 1) == '_') {
          $ecPath_new = substr($ecPath_new, 1);
        }
      }
    } else {
      $ecPath_new = implode('_', $ecPath_array);
    }

    return 'ecPath=' . $ecPath_new;
  }
  
  	// prepare the events categories path for given category_id
	function tep_find_events_category_path($category_id){
		$query=tep_db_query("SELECT parent_id,events_categories_id from " . TABLE_EVENTS_CATEGORIES . " where events_categories_id='" . $category_id . "'");
		
		if (tep_db_num_rows($query)<=0) return "";
		$result=tep_db_fetch_array($query);
		if ($result["parent_id"]==0){
			return $category_id;
		} else {
			return tep_find_events_category_path($result["parent_id"]) . "_" . $category_id;
		}
	}

  ////
// Return a event's name
// TABLES: events
  function tep_get_events_name($event_id, $language = '') {
    global $languages_id;

    if (empty($language)) $language = $languages_id;

    $event_query = tep_db_query("select events_name from " . TABLE_EVENTS_DESCRIPTION . " where events_id = '" . (int)$event_id . "' and language_id = '" . (int)$language . "'");
    $event = tep_db_fetch_array($event_query);

    return $event['events_name'];
  }

	// Return a instructor name
  function tep_get_instructor_name($id) {
    $instructor_query = tep_db_query("select admin_firstname,admin_lastname from " . TABLE_ADMIN . " where admin_id='" . (int)$id  . "'");
    if ($instructor=tep_db_fetch_array($instructor_query))
        return $instructor['admin_firstname'] . ' ' . $instructor['admin_lastname'];
  }

 // Get the session type single or recursive for an event
 function tep_get_session_type($event_id)
 {
    $check_query=tep_db_query("select count(*) as total from " . TABLE_RECURSIVE_SESSIONS . " where events_id='" . $event_id . "'");
    if ($check_result=tep_db_fetch_array($check_query)){
    if ((int)$check_result['total']>0)
      return 'R';
    $check_query=tep_db_query("select count(*) as total from " . TABLE_EVENTS_SESSIONS . " where events_id='" . $event_id . "' and sessions_type!=''");
    $check_result=tep_db_fetch_array($check_query);
    if ((int)$check_result['total']>0)
      return 'S';
    }
    return '';
 }
 // Get the session date for an session
 function tep_get_session_date($session_id)
 {
    $check_query=tep_db_query("select start_date from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . $session_id . "'");
    $check_result=tep_db_fetch_array($check_query);
    return $check_result["start_date"];
 }
 
 // get the available free_sessions
 function tep_get_free_sessions($start_id,$no_of_sessions,$events_type,$customers=1){
	// get  event details with session id
	global $session_array,$events_result,$customer_id;
	$events_id=(int)$events_result['events_id'];
	$start_date=tep_get_session_date($start_id);
	$max_reserve=((int)$events_result['events_max_reserve']);

	//iterate and find available session
	if ($events_result['events_forward_period']=='Y'){
		$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$events_result['events_forward_length']));
		$check_data=" and start_date<='" . $check_date . "' ";
	}
	$date_sql = "select sessions_id,start_date,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS . " where events_id='" . $events_id . "' and start_date>='" . $start_date . "' and sessions_type!='' and sessions_type!='P' " . $check_data ." order by start_date";
	$date_query=tep_db_query($date_sql);

  //iterate all selected dates and find reserved,waitlist,no seats dates 
   $current_count=1;
	$session_array_temp=array();
	while($date_result=tep_db_fetch_array($date_query)){
		$accept=false;
		$session_type="R";
		if ($events_type=='R' || $events_type=='M'){
		
			// calculate total reservations using no of reserved users, no of renewal users, no of reservations in the cart
			$total_reservations=tep_reserve_count($date_result["sessions_id"],$events_result)+$customers;
			$total_reservations+=tep_get_renewal_users_count($events_result,$date_result['start_date']);
			$total_reservations+=tep_count_cart($date_result["sessions_id"],"R");
	   	// check if total reservations exceed the maximum limits
			
			//echo "total=" .  $total_reservations . "<br>" . "reserve=" . tep_reserve_count($date_result["sessions_id"],$events_result) . "<br>";  
			//echo (($total_reservations) - (tep_reserve_count($date_result["sessions_id"],$events_result))); 
		
			if ($total_reservations<=$max_reserve){  
					$accept=true;
			} else {
				//check group bookings	
				if($events_result['events_group_bookings']=='Y'){
					return $total_reservations . "#" . $max_reserve;
				}
				//check group bookings
				// if session_gaps is not selected, continuous dates need to be selected
				if ($events_result['session_gaps']!='Y' && sizeof($session_array_temp)>0){
					$session_array_temp=array();
					$current_count=1;
				}
			}
		} 
		if  ($accept==false){
			$session_type="W";
			if ($events_type=='W' || $events_type=='M'){
				// find the entry in any of the three waiting list groups
				//$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result);
				$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result,$customers);
		
				if ($find_group!='E'){
					$accept=true;
				} else {
					if ($events_result['session_gaps']!='Y' && sizeof($session_array_temp)>0){
						$session_array_temp=array();
						$current_count=1;
					}
				}
			}
		}
		if ($accept==true){
			// if the found date is not already selected add the temp list
			if (!isset($session_array[$date_result['sessions_id']])){
				$session_array_temp[$date_result['sessions_id']]=array('date'=>$date_result['start_date'],'type'=>$session_type,'group'=>$find_group,'recursive_id'=>$date_result['recursive_sessions_id']);
				$current_count++;
				if ($current_count>$no_of_sessions) break;
			}
		}
	}
	// merge to final output list
	if (sizeof($session_array_temp)>0) $session_array+=$session_array_temp;
}

// get the total no of reserved users
function tep_reserve_count($sessions_id,&$values)
{
	$count=0;
	$pending_option="";
	if ((int)$values['events_pending_period']>0){
		$pending_option=" and (o.orders_status>1 or date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . date('Y-m-d H:i:s',getServerDate(false)) . "') and op.orders_products_status!=5";
	}
	//$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='R' and op.products_id='" . $sessions_id ."' " . $pending_option);
	$query=tep_db_query("select sum(op.products_quantity) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='R' and op.products_id='" . $sessions_id ."' " . $pending_option);
	$result=tep_db_fetch_array($query);
	$count+=(int)$result['total_count'];

	return $count;
}

// get the total no of waitlisted users
function tep_waitlist_count($sessions_id,&$values)
{
	$count=0;
	$pending_option="";
	if ((int)$values['events_pending_period']>0){
	 	$pending_option=" and (o.orders_status>1 or date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . date('Y-m-d H:i:s',getServerDate(false)) . "') and op.orders_products_status!=5";
	}
	//$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.products_id='" . $sessions_id ."' " . $pending_option);
	$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.products_id='" . $sessions_id ."' " . $pending_option);
	$result=tep_db_fetch_array($query);
	$count+=(int)$result['total_count'];
	return $count;
}

// get the total no of users found in the cart
function tep_count_cart($session_id,$events_type,$waitlist_type=""){
	$cart_count=0; //count in shopping cart and edit orders table
	
	// time elapsed of events_order_timeout 
	$expiry=strtotime("-" . ((int)EVENTS_ORDER_TIMEOUT) . " minutes");
	// get cart count by checking records within this expiry time
	$query="SELECT count(*) as total from " . TABLE_CUSTOMERS_BASKET . " cb, " . TABLE_CUSTOMERS_BASKET_SESSIONS . " cs where cs.session_id='" . $session_id . "' and cs.products_id=cb.products_id " . 
							" and UNIX_TIMESTAMP(cb.customers_basket_date_added)>" . $expiry . " and cs.session_type='" . $events_type . "' and cs.session_group='" . $waitlist_type ."' and cb.products_type='E';";
	$result=tep_db_query($query);
	$result_array=tep_db_fetch_array($result);	
	$cart_count+=(int)$result_array["total"];

	//get backend orders edit table count
	$query="SELECT count(*) as total from " . TABLE_ORDERS_EDIT_PRODUCTS . " eo where eo.products_id='" . $session_id .  
							"' and UNIX_TIMESTAMP(eo.date_added)>" . $expiry . " and eo.events_type='" . $events_type . "' and eo.waitlist_type='" . $waitlist_type ."' and eo.products_type='E';";
	$result=tep_db_query($query);
	$result_array=tep_db_fetch_array($result);	
	$cart_count+=(int)$result_array["total"];

	return $cart_count;
}
// get the admin groups name by providing the group id
function tep_get_group_name($group_id){
    $group_query=tep_db_query("SELECT admin_groups_name from " . TABLE_ADMIN_GROUPS . " where admin_groups_id='" . (int)$group_id . "'"); 
    if ($group_result=tep_db_fetch_array($group_query)){
      return $group_result['admin_groups_name'];
    } 
 }
 
 // get the html content for question input from user
 function tep_get_question_input($type){
   $result='';
   $param="size=30 maxlength=100";
   //if the type is text or numeric, create a textbox
    if ($type=='T' || $type=='N'){
		if ($type=='N') $param="size=15 maxlength=10";
       $result.=tep_draw_input_field('question_value_data','',$param);
    } else if ($type=='D'){
		// if the type is a date, create a dropdownlist for month,day,year
		
       $result.=tep_draw_hidden_field('question_value_data','');
       $month=array('','January','February','March','April','May','June','July','August','September','October','November','December');
       $date_query=tep_db_query("SELECT date_format(current_date,'%d') as day, date_format(current_date,'%m') as month, date_format(current_date,'%Y') as year");
       $date_result=tep_db_fetch_array($date_query);
       $month_array=array();
       for($icnt=0;$icnt<=12;$icnt++)
          $month_array[]=array('id'=>$icnt,'text'=>$month[$icnt]);
       $result.=tep_draw_pull_down_menu('question_month',$month_array);
       $day_array=array();
       for($icnt=0;$icnt<=31;$icnt++){
	   	$text=$icnt;
	   	if ($icnt==0) $text='';
          $day_array[]=array('id'=>$icnt,'text'=>$text);
		}  
       $result.='&nbsp;' . tep_draw_pull_down_menu('question_day',$day_array);
       $year_array=array();
       $year_array[]=array('id'=>0,'text'=>'');
       $year_array[]=array('id'=>$date_result['year'],'text'=>$date_result['year']);
       $year_array[]=array('id'=>$date_result['year']+1,'text'=>$date_result['year']+1);
       $result.='&nbsp' . tep_draw_pull_down_menu('question_year',$year_array);
    }
    return $result . '<font color="red">&nbsp;*</font>';
 }
 
 // send single session email
function tep_send_event_email($process_id,$mail_type){
	global $currencies;
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;
	if ((int)$process_id<=0 || $mail_type=='')
		return;

	// fetch data
	$process_query=tep_db_query("select c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_second_email_address,
				  o.customers_street_address,c.customers_email_address,o.customers_suburb,o.customers_postcode,o.customers_city,
				  o.customers_state,o.customers_country,op.final_price,op.products_id,s.start_date,e.events_payment,op.products_tax,op.products_name,
				  e.events_id,e.events_instructor,e.events_renewal_start,e.events_renewal_end,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time,e.events_location,e.events_fees,e.events_tax_class_id,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method,e.service_id,e.link_service from " . 
						   TABLE_CUSTOMERS . " c, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS . " e " . 
				   "where o.orders_id=op.orders_id and o.customers_id=c.customers_id and op.products_id=s.sessions_id and s.events_id=e.events_id and op.orders_products_id='" . $process_id . "'");

	if (tep_db_num_rows($process_query)<=0) return;
	
	$process_result=tep_db_fetch_array($process_query);

	//fetch mail template
	$details=array();
	$details['type']=$mail_type;
	$details['table']=TABLE_EVENTS_MESSAGES;
	$details['events_id']=$process_result['events_id'];

	tep_get_template($details);
	
	if ($details['html_text']=="") return;

	// get the renewal end date of this reservation
	$renewal_array=tep_get_renewal_details($process_result,$process_result["customers_id"],true);
	$renewal_end="";

	if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];
 
	$events_location=tep_get_locations_name($process_result['events_location'],$process_result['link_service'],$process_result['service_id']);
	
	// prepare details for merge details
	$replace_array=array(	TEXT_FN=>$process_result['customers_firstname'],
							TEXT_LN=>$process_result['customers_lastname'],
							TEXT_DF=>format_date($process_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $process_result['customers_email_address'] . '"><u>' . $process_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$process_result['customers_telephone'],
							TEXT_FX=>$process_result['customers_fax'],
							TEXT_SA=>$process_result['customers_street_address'],
							TEXT_SU=>$process_result['customers_suburb'],
							TEXT_PC=>$process_result['customers_postcode'],
							TEXT_CT=>$process_result['customers_city'],
							TEXT_ST=>$process_result['customers_state'],
							TEXT_CY=>$process_result['customers_country'],
                            
							TEXT_EN=>$process_result['products_name'],
							TEXT_SI=>$process_result['events_start_time'],
							TEXT_EI=>$process_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($process_result['events_fees'],tep_get_tax_rate($process_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($process_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_SD=>format_date($process_result['start_date']),
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $process_result['events_id'],'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $process_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&cuID=' . $process_result['customers_id'] . '&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&cuID=' . $process_result['customers_id'] . '&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&cuID=' . $process_result['customers_id'] . '&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $process_result['orders_id'],'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
							TEXT_RE=>format_date($renewal_end),

							TEXT_ON=>$process_result['orders_id'],
							TEXT_OC=>$process_result['orders_comments'],
							TEXT_OD=>format_date($process_result['date_purchased']),
							TEXT_BT=>$process_result['billing_name'],
							TEXT_BA=>$process_result['billing_street_address'],
							TEXT_PY=>$process_result['payment_method'],
							TEXT_TX=>$process_result['products_tax'],
							TEXT_SB=>$currencies->format($process_result['final_price']),
							TEXT_SS=>sprintf(TEXT_FORMAT_SS,$process_result['products_name'],$process_result['events_start_time'],$process_result['events_end_time'],date('l, jS F', strtotime($process_result['start_date'])),$events_location),
							TEXT_SSM=>format_date($process_result['start_date'],true),
							TEXT_TL=>$currencies->format(tep_add_tax($process_result['final_price'],$process_result['products_tax'])));

	// merge content
	tep_replace_template($details,$replace_array);

	tep_strip_html($details);

	// send mails to needed address
	$details['to_name']=$process_result['customers_firstname'] . ' ' . $process_result['customers_lastname'];
	$details['to_email']=$process_result['customers_email_address'];
	$details['from_name']=STORE_OWNER;
	$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
	
	$sql_array=array(	'orders_id'=>$process_result["orders_id"],
						'events_id'=>$process_result["events_id"],
						'customers_id'=>$process_result["customers_id"],
						'message_type'=>$mail_type,
						'message_mode'=>'E',
						'email_address'=>$process_result["customers_email_address"],
						'send_date'=>'now()'
					);
    
	if (tep_send_email($details)){
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
	}
	// if the mail_type is waitist promotion send cc mail to intructor of user registered event
	if ($mail_type=='WPR'){
		$instructor_query=tep_db_query("SELECT admin_firstname,admin_lastname,admin_email_address from " . TABLE_ADMIN . " where admin_id='" . $process_result['events_instructor'] . "'");
		$instructor_result=tep_db_fetch_array($instructor_query);

		$details['to_name']=$instructor_result['admin_firstname'] . ' ' . $instructor_result['admin_lastname'];
		$details['to_email']=$instructor_result['admin_email_address'];
		$details['from_name']=STORE_OWNER;
		$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
        
		tep_send_email($details);
	}
	// if the mail_type is withdraw reservation send cc mail to callmanager 
    if ($mail_type=='WTR'){
		$callmanager_query=tep_db_query("SELECT a.admin_id,a.admin_firstname,a.admin_lastname,a.admin_email_address from " . TABLE_ADMIN . " a, " . TABLE_ADMIN_GROUPS . " ag where a.admin_groups_id=ag.admin_groups_id and ag.admin_groups_name='" . TEXT_CALLMANAGER_ENTRY . "'");
		$callmanager_result=tep_db_fetch_array($callmanager_query);

		$details['to_name']=$callmanager_result['admin_firstname'] . ' ' . $callmanager_result['admin_lastname'];
		$details['to_email']=$callmanager_result['admin_email_address'];
		$details['from_name']=STORE_OWNER;
		$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
		
		tep_send_email($details);
    }
	// send sms to the registered customer 
    if ($process_result['customers_fax']!=''){
       $temp_details['mobile']=$process_result['customers_fax'];
       $temp_details['mail_type']=$mail_type;
       $temp_details['events_id']=$process_result['events_id'];
       $temp_details['country']=$process_result['customers_country'];
       if (tep_send_event_sms_email($replace_array,$temp_details)){
	   	$sql_array["message_mode"]='S';
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
	   }
    }
}

// send event order email
function tep_send_event_order_email($i,$aoemail=''){
	global $currencies,$order,$customer_id,$sessions,$insert_id,$group_members,$order_timestamp;
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;
	// get event details	
	$event_query=tep_db_query("SELECT e.events_id,e.events_instructor,e.events_renewal_start,e.events_renewal_end,time_format(e.events_start_time,'%h:%i%p') as events_start_time,time_format(e.events_end_time,'%h:%i%p') as events_end_time,e.events_location,e.events_fees,e.events_tax_class_id,e.link_service,e.service_id  from " . 
							   TABLE_EVENTS . " e " . " where e.events_id='" . (int)$order->products[$i]['id'] . "'");
	if (tep_db_num_rows($event_query)<=0) return;    
	$event_result=tep_db_fetch_array($event_query);
	// get mail template details
	$details_r=array();
	$details_r['type']='RCF';
	$details_r['table']=TABLE_EVENTS_MESSAGES;
	$details_r['events_id']=$event_result['events_id'];
	tep_get_template($details_r);
	$details_w=array();
	$details_w['type']='WCF';
	$details_w['table']=TABLE_EVENTS_MESSAGES;
	$details_w['events_id']=$event_result['events_id'];
	tep_get_template($details_w);
	if ($details_r['html_text']=="" && $details_w['html_text']=="") return;
	// get the renewal end date of this reservation
	//$renewal_array=tep_get_renewal_details($event_result,$customer_id,true);
	$renewal_end="";

	if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];

	$total_query=tep_db_query("SELECT class,value,title from " . TABLE_ORDERS_TOTAL . " where class in('ot_total','ot_coupon') and orders_id='" . $insert_id ."'");

	$total_array=array(	'ot_total'=>array('value'=>$currencies->format(tep_add_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']),'title'=>''),
						'ot_coupon'=>array('value'=>0,'title'=>'')
						);
	$ot_total=$ot_coupon=-1;
	while($total_result=tep_db_fetch_array($total_query)){
		if ($total_result["class"]=="ot_coupon") {
			$total_array["ot_coupon"]=array("value"=>$total_result["value"],"title"=>$total_result["title"]);
			$ot_coupon=$total_result["value"];
		} else {
			$ot_total=$total_result["value"];
		}
	}
	if ($ot_coupon>0){
		$total_array["ot_total"]["value"]=$currencies->format($ot_total) . ("<br>" . $total_array["ot_coupon"]["title"] . ' ' . $currencies->format($total_array["ot_coupon"]["value"]));
	}
	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_HTTPS_CATALOG:HTTP_SERVER . DIR_WS_HTTP_CATALOG);
	
	// get some customer information 
	$order_query=tep_db_query("SELECT customers_fax,customers_dob from " . TABLE_CUSTOMERS . " where customers_id='" . (int)$customer_id . "'");
	$order_result=tep_db_fetch_array($order_query);
 
	$session_dates=array('long_r'=>'','short_r'=>'','long_w'=>'','short_w'=>'');
	$events_location=tep_get_locations_name($event_result['events_location'],$event_result['link_service'],$event_result['service_id']);
	// get session date details
	reset($sessions);
	$starting_date='';
	while(list($sid,)=each($sessions)){
		if ($starting_date=='') $starting_date=$sessions[$sid]['date'];
		if ($sessions[$sid]['type']=='R' || $sessions[$sid]['type']=='U'){
			$session_dates['short_r'].=format_date($sessions[$sid]['date'],true) . ",";
			$session_dates['long_r'].=(sprintf(TEXT_FORMAT_SS,$order->products[$i]['name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($sessions[$sid]['date'])),$events_location) . '<br>');
		} else {
			$session_dates['short_w'].=format_date($sessions[$sid]['date'],true) . ",";
			$session_dates['long_w'].=(sprintf(TEXT_FORMAT_SS,$order->products[$i]['name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($sessions[$sid]['date'])),$events_location) . '<br>');
		}
	}
		//for direct deposit module
	if($GLOBALS['payment']=='ausbank')
		$direct_deposit=sprintf(TEXT_DIRECT_DEPOSIT,substr(strtolower($order->customer['firstname']),0,3) , substr(strtolower($order->customer['lastname']),0,3) , $order_timestamp );
	else 
		$direct_deposit='';	
	
	$attendee = '';
	if(strpos($order->order_attendees,',')>0) $attendee = '<td align="left" valign="top" nowrap="nowrap"><font face="Arial, Helvetica, sans-serif" size="2" color="#000000"><b>Multiple Attendees</b></font></td>' . 
														'<td align="left"><font face="Arial, Helvetica, sans-serif" size="2" color="#000000">' . $order->order_attendees . '</font></td>';

	$replace_array=array(	TEXT_FN=>$order->customer['firstname'],
							TEXT_LN=>$order->customer['lastname'],
							TEXT_DF=>format_date($order_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $order->customer['email_address'] . '"><u>' . $order->customer['email_address'] .'</u></a>',
							TEXT_TN=>$order->customer['telephone'],
							TEXT_FX=>$order_result['customers_fax'],
							TEXT_SA=>$order->customer['street_address'],
							TEXT_SU=>$order->customer['suburb'],
							TEXT_PC=>$order->customer['postcode'],
							TEXT_CT=>$order->customer['city'],
							TEXT_ST=>$order->customer['state'],
							TEXT_CY=>$order->customer['country']['title'],
							
							TEXT_EN=>$order->products[$i]['name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],tep_get_tax_rate($event_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_SD=>format_date($starting_date),
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $event_result['events_id'],'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_id,'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&cuID=' . $customer_id . '&events_id=' . $event_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&cuID=' . $customer_id . '&events_id=' . $event_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&cuID=' . $customer_id . '&events_id=' . $event_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $insert_id,'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
							TEXT_SL=>'<a href="' . tep_href_link(FILENAME_DEFAULT) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . STORE_OWNER . '</a>',
							TEXT_SP=>'<img src="' . $url_home . DIR_WS_TEMPLATES . TEMPLATE_NAME . '/images/' .COMPANY_LOGO . '" title="' . STORE_NAME . '">',
							TEXT_MA=>$attendee,
							TEXT_RE=>format_date($renewal_end),
							TEXT_ON=>$insert_id,
							TEXT_OC=>$order->info['comments'],
							TEXT_OD=>date(EVENTS_DATE_FORMAT),
							TEXT_BT=>$order->billing['firstname'] . ' ' . $order->billing['lastname'],
							TEXT_BA=>$order->billing['street_address'],
							TEXT_PY=>$order->info['payment_method'],
							TEXT_DD=>$direct_deposit,
							TEXT_TX=>$currencies->format(tep_calculate_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']),
							TEXT_SB=>$currencies->format($order->products[$i]['final_price']*$order->products[$i]['qty']),
							TEXT_TL=>$total_array["ot_total"]["value"],
							TEXT_GB=>$group_members
							);
	//store details
	$sql_array=array(	'orders_id'=>$insert_id,
						'events_id'=>$event_result["events_id"],
						'customers_id'=>(int)$customer_id,
						'message_type'=>$details_r['type'],
						'message_mode'=>'E',
						'email_address'=>tep_db_prepare_input($order->customer['email_address']),
						'send_date'=>'now()',
					);
	// replace content for reserved sessions
	if ($session_dates['short_r']!=''){
		$replace_array[TEXT_SS]=$session_dates['long_r'];
		$replace_array[TEXT_SSM]=substr($session_dates['short_r'],0,-1);
		if ($details_r['html_text']!='') {			
			if ($aoemail!='') $details_r['html_text'].=$details_r['html_text'] . '<a href="' . tep_href_link(CONTENT_ACCOUNT . '.php','type=aofficer') . '">' . TEXT_COMPLETE_PAYMENT . '</a>';
			tep_replace_template($details_r,$replace_array);
			tep_strip_html($details_r);
			// form the address array to send
			$details_r['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
			$details_r['to_email']=($aoemail!='' ? $aoemail :$order->customer['email_address']);
			$details_r['from_name']=STORE_OWNER;
			$details_r['from_email']=STORE_OWNER_EMAIL_ADDRESS;	
			tep_send_email($details_r);
			tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
			if (SEND_EXTRA_ORDER_EMAILS_TO!=''){
			$details_r['to_email'] = SEND_EXTRA_ORDER_EMAILS_TO;
			tep_send_email($details_r);
			}
			// send mail to Store Owner
	/*		if (STORE_OWNER_EMAIL_ADDRESS!="" && $details_r['type']=='RCF') {
				$details_r['to_name']=STORE_OWNER;
				$details_r['to_email']=($aoemail!='' ? $aoemail :STORE_OWNER_EMAIL_ADDRESS);
				$details_r['from_name']=STORE_OWNER;
				$details_r['from_email']=STORE_OWNER_EMAIL_ADDRESS;
				tep_send_email($details_r);
			   }
	*/		   	
		
		}
		
		// send sms	
		if ($order_result['customers_fax']!=''){
			$temp_details['mobile']=$order_result['customers_fax'];
			$temp_details['mail_type']='RCF';
			$temp_details['events_id']=$event_result['events_id'];
			$temp_details['country']=$order->customer['country']['title'];
			if (tep_send_event_sms_email($replace_array,$temp_details)){
				$sql_array['message_type']=$details_r['type'];
				$sql_array['message_mode']='S';
				tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
			}
		}
	} 
	// replace content for waitlisted sessions
	if ($session_dates['short_w']!=''){
		$replace_array[TEXT_SS]=$session_dates['long_w'];
		$replace_array[TEXT_SSM]=substr($session_dates['short_w'],0,-1);
		if ($details_w['html_text']!='') {
			tep_replace_template($details_w,$replace_array);
			tep_strip_html($details_w);
			// form the address array to send
			$details_w['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
			$details_w['to_email']=($aoemail!='' ? $aoemail :$order->customer['email_address']);
			$details_w['from_name']=STORE_OWNER;
			$details_w['from_email']=STORE_OWNER_EMAIL_ADDRESS;
            
			if (tep_send_email($details_w)){
				$sql_array['message_type']=$details_w['type'];
				$sql_array['message_mode']='E';
				tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
			}
		}
		// send sms	
		if ($order_result['customers_fax']!=''){
			$temp_details['mobile']=$order_result['customers_fax'];
			$temp_details['mail_type']='WCF';
			$temp_details['events_id']=$event_result['events_id'];
			$temp_details['country']=$order->customer['country']['title'];
			if (tep_send_event_sms_email($replace_array,$temp_details)){
				$sql_array['message_type']=$details_w['type'];
				$sql_array['message_mode']='S';
				tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
			}
		}
	}
}

// send email to user regarding reserved event by grouping all of the sessions of an order
function tep_send_event_group_email($orders_id,$events_id,$type,$events_type=''){
	global $currencies;
	
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;

	if ((int)$orders_id<=0 || (int)$events_id<=0) return;

	$details=array();
	$details['type']=$type;
	$details['events_id']=$events_id;
	$details['table']=TABLE_EVENTS_MESSAGES;
	tep_get_template($details);

	if ($details['html_text']=='') return;

	$check_option=" and (events_type='R' or events_type='W')";

	if ($type=='WTR') $check_option=" and events_type='" . $events_type . "'";


	$customer_query=tep_db_query("select c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_second_email_address," . 
								" o.customers_street_address,c.customers_email_address,o.customers_suburb,o.customers_postcode,o.customers_city,o.customers_state,o.customers_country, " . 
								" o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method from " . TABLE_ORDERS . " o, " . TABLE_CUSTOMERS . " c where o.orders_id='" . $orders_id . "' and c.customers_id=o.customers_id");
	
	if (tep_db_num_rows($customer_query)<=0) return;

	$customer_result=tep_db_fetch_array($customer_query);
	
	
	$event_query=tep_db_query(	"SELECT e.events_id,e.events_instructor,e.events_renewal_start,e.events_renewal_end,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time," .
								"e.events_location,e.events_tax_class_id,e.events_fees,e.service_id,e.link_service from " . TABLE_EVENTS . " e where e.events_id='" . $events_id . "'");
	
	if (tep_db_num_rows($event_query)<=0) return;
	$event_result=tep_db_fetch_array($event_query);
	
	$date_query=tep_db_query(	"SELECT op.final_price,op.products_id,op.events_type,op.products_tax,op.products_name,s.start_date from " . 
							   		TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_id='" . $orders_id . "' and op.products_type='E' " . $check_option . " and op.products_id=s.sessions_id and s.events_id='" . $events_id . "' order by s.start_date");

		
	if (tep_db_num_rows($date_query)<=0) return;    
	$events_location=tep_get_locations_name($event_result['events_location'],$event_result['link_service'],$event_result['service_id']);	

	// get the renewal end date of this reservation
	$renewal_array=tep_get_renewal_details($event_result,$customer_result["customers_id"],true);
	$renewal_end="";

	if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];

	$starting_date='';
	while($date_result=tep_db_fetch_array($date_query)){
		if ($starting_date=='') $starting_date=$date_result['start_date'];
		$session_dates['short_r'].=format_date($date_result['start_date'],true) . ",";
		$session_dates['long_r'].=sprintf(TEXT_FORMAT_SS,$date_result['products_name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($date_result['start_date'])),$events_location) . '<br>';
		$tax+=tep_calculate_tax($date_result["final_price"],$date_result["products_tax"]);
		$subtotal+=$date_result["final_price"];
	}
	$total=$subtotal+$tax;


	$replace_array=array(	TEXT_FN=>$customer_result['customers_firstname'],
							TEXT_LN=>$customer_result['customers_lastname'],
							TEXT_DF=>format_date($customer_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$customer_result['customers_telephone'],
							TEXT_FX=>$customer_result['customers_fax'],
							TEXT_SA=>$customer_result['customers_street_address'],
							TEXT_SU=>$customer_result['customers_suburb'],
							TEXT_PC=>$customer_result['customers_postcode'],
							TEXT_CT=>$customer_result['customers_city'],
							TEXT_ST=>$customer_result['customers_state'],
							TEXT_CY=>$customer_result['customers_country'],
							TEXT_RE=>format_date($renewal_end),
							TEXT_EN=>$event_result['products_name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],tep_get_tax_rate($event_result['events_tax_class_id']))),
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
							TEXT_SD=>format_date($start_date),
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $events_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&cuID=' . $customer_result['customers_id'] . '&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&cuID=' . $customer_result['customers_id'] . '&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&cuID=' . $customer_result['customers_id'] . '&events_id=' . $events_id,'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $orders_id,'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
							TEXT_SS=>$session_dates['long_r'],
							TEXT_SSM=>substr($session_dates['short_r'],0,-1),
							TEXT_ON=>$customer_result['orders_id'],
							TEXT_OC=>$customer_result['orders_comments'],
							TEXT_OD=>format_date($cusomer_result['date_purchased']),
							TEXT_BT=>$customer_result['billing_name'],
							TEXT_BA=>$customer_result['billing_street_address'],
							TEXT_PY=>$customer_result['payment_method'],
							TEXT_TX=>$currencies->format($tax),
							TEXT_SB=>$currencies->format($subtotal),
							TEXT_TL=>$currencies->format($total)
						);
	//replace content
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);

	$sql_array=array(	'orders_id'=>$orders_id,
						'events_id'=>$events_id,
						'customers_id'=>$customer_result["customers_id"],
						'message_type'=>$type,
						'message_mode'=>'E',
						'email_address'=>$customer_result["customers_email_address"],
						'send_date'=>'now()'
					);

	// get the address to send
    $details['to_name']=$customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'];
	$details['to_email']=$customer_result['customers_email_address'];
	$details['from_name']=STORE_OWNER;
	$details['from_email']=STORE_OWNER_EMAIL_ADDRESS;
    
	if (tep_send_email($details)){
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
	}
	
	if ($customer_result['customers_fax']!=''){
       $temp_details['mobile']=$customer_result['customers_fax'];
       $temp_details['mail_type']=$type;
       $temp_details['events_id']=$events_id;
       $temp_details['country']=$customer_result['customers_country'];
       if (tep_send_event_sms_email($replace_array,$temp_details)){
	   		$sql_array["message_mode"]="S";		
			tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);	
	   }
    }
}

// send invite email to selected friends email address
function tep_send_invite_email(&$send_details){
	global $currencies,$languages_id;
	//if ((int)EMAIL_ACTIVATE!=1) return;
	if (is_array($send_details)==false)
		return;

	// fetch the event details
	$event_query=tep_db_query("select s.start_date,ed.events_name,e.events_instructor,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time,e.events_location,e.events_tax_class_id,e.events_fees,e.service_id,e.link_service from " . 
								TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION .  " ed " .
								"where e.events_id='" . $send_details['events_id'] . "' and s.events_id=e.events_id and e.events_id=ed.events_id and ed.language_id='" . $languages_id . "' order by s.start_date");

	if (tep_db_num_rows($event_query)<=0) return;

	$event_result=tep_db_fetch_array($event_query);

	$tax_rate=tep_get_tax_rate($event_result['events_tax_class_id']);

	// fetch the customer details
	$customer_query=tep_db_query("select customers_firstname,customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " where customers_id='" . $send_details['customers_id'] . "'");
	if (tep_db_num_rows($customer_query)<=0) return;
	$customer_result=tep_db_fetch_array($customer_query);

	$details=array();
	$details['type']=$send_details['mail_type'];
	$details['table']=TABLE_EVENTS_MESSAGES;
	$details['events_id']=$send_details['events_id'];
	
	tep_get_template($details);
	
	$events_location=tep_get_locations_name($event_result['events_location'],$event_result['link_service'],$event_result['service_id']);
	
	// get the corresponding dates of event
	$session_query=tep_db_query("SELECT s.start_date from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . $send_details['events_id'] . "' and op.products_id=s.sessions_id and op.products_type='E' and (op.events_type='R' || op.events_type='W') and o.orders_id=op.orders_id and o.customers_id='" . $send_details['customers_id'] . "' order by s.start_date");
	$session_dates="";
	$session_dates_long="";
	if (tep_db_num_rows($session_query)>0){
		while($session_result=tep_db_fetch_array($session_query)){
			$session_dates_long.=sprintf(TEXT_FORMAT_SS,$event_result['events_name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($session_result['start_date'])),$events_location) . '<br>';
			$session_dates.=format_date($session_result['start_date'],true) . ",";
		}
		$session_dates=substr($session_dates,0,-1);
	}
	$replace_array=array( 	TEXT_EN=>$event_result['events_name'],
							TEXT_SI=>$event_result['events_start_time'],
							TEXT_EI=>$event_result['events_end_time'],
							TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
							TEXT_EL=>$events_location,
						//	TEXT_SD=>format_date($event_result['start_date']),
						//	TEXT_SS=>$session_dates_long,
						//	TEXT_SSM=>$session_dates,
							TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],$tax_rate)),
							TEXT_CF=>$customer_result['customers_firstname'],
							TEXT_CL=>$customer_result['customers_lastname'],
							TEXT_IC=>$send_details['comments'],
							TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
						/*	TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>' */
 
							);

	//replace template
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);

	$email_array=&$send_details["address"];
	$name_array=&$send_details["name"];

	// send email
	$message = new email(array('X-Mailer: osCommerce'));
	for ($icnt=0;$icnt<sizeof($email_array);$icnt++){
		$mes_content=$details['html_text'];
		$mes_text=eregi_replace("%%" . TEXT_FE . "%%",$name_array[$icnt] . "",$mes_content);
		
		$text=strip_tags($mes_text,'<br>');
		$text=str_replace('<br>',chr(13). chr(10),$text);
		$text=str_replace('<BR>',chr(13). chr(10),$text);

		if ($mes_text!='' && $email_array[$icnt]!=''){

			if ($mail_data_result['message_format'] != 'T') {
				$message->add_html($mes_text, $text);
			} else {
				$message->add_text($text);
			}
			$message->build_message();
		
			$message->send($name_array[$icnt], $email_array[$icnt], $customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'], $customer_result['customers_email_address'], $details['subject']);
		}
	}
}

  // send sms to reserved user
  function tep_send_event_sms_email($replace_array,$send_details)
  {
		if ((int)SMS_ACTIVATE!=1) return false;

		// fetch the sms template details
		$sms_query=tep_db_query("SELECT message_text from " . TABLE_EVENTS_SMS_MESSAGES . " where events_id='" . (int)$send_details['events_id'] . "' and message_type='" . $send_details['mail_type'] . "'");
		
		if (tep_db_num_rows($sms_query)<=0) return false;
		
		$sms_result=tep_db_fetch_array($sms_query);
		
		$mes_text=$sms_result['message_text'];
		reset($replace_array);
	
		while (list($key, $value) = each($replace_array))
			$mes_text=eregi_replace("%%" . $key  . "%%",$value  . "",$mes_text);
		
		$text = strip_tags($mes_text,'<br>');
		$text = str_replace('<br>',chr(13) .chr(10),$text);
		$text = str_replace('<BR>',chr(13) .chr(10),$text);
		
		return send_sms($send_details['mobile'],$replace_array[TEXT_FN] . ' ' . $replace_array[TEXT_LN],$text,$send_details['country']);
  }
 
 	// replace the invite email content
	function tep_replace_invite_mail_content($send_details){
	global $currencies;
		if (is_array($send_details)==false)
			return;
		
		// fetch the event details
		$event_query=tep_db_query("select s.start_date,ed.events_name,e.events_instructor,time_format(e.events_start_time,'%h:%i %p') as events_start_time,time_format(e.events_end_time,'%h:%i %p') as events_end_time,e.events_location,e.events_tax_class_id,e.events_fees,e.service_id,e.link_service from " . 
									TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION .  " ed " .
									"where e.events_id='" . $send_details['eID'] . "' and s.events_id=e.events_id and e.events_id=ed.events_id order by s.start_date limit 1");

		if (tep_db_num_rows($event_query)<=0) return;
		$event_result=tep_db_fetch_array($event_query);
	
		// fetch the tax rate
		$tax_rate=tep_get_tax_rate($event_result['events_tax_class_id']);

		// fetch the customer detail
		$customer_query=tep_db_query("select customers_firstname,customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " where customers_id='" . $send_details['cID'] . "'");
		if (tep_db_num_rows($customer_query)<=0) return;
		$customer_result=tep_db_fetch_array($customer_query);

		
		// prepare the merge array
		$events_location=tep_get_locations_name($event_result['events_location'],$event_result['link_service'],$event_result['service_id']);
		$replace_array=array( 	TEXT_EN=>$event_result['events_name'],
								TEXT_SI=>$event_result['events_start_time'],
								TEXT_EI=>$event_result['events_end_time'],
								TEXT_IN=>tep_get_instructor_name($event_result['events_instructor']),
								TEXT_EL=>$events_location,
						//		TEXT_SD=>format_date($event_result['start_date']),
						//		TEXT_SS=>sprintf(TEXT_FORMAT_SS,$event_result['events_name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($event_result['start_date'])),$events_location),
						//		TEXT_SSM=>format_date($event_result['start_date'],true),
								TEXT_EF=>$currencies->format(tep_add_tax($event_result['events_fees'],$tax_rate)),
								TEXT_CF=>$customer_result['customers_firstname'],
								TEXT_CL=>$customer_result['customers_lastname'],
								TEXT_FE=>TEST_MAIL_FE,
								TEXT_IC=>TEST_MAIL_IC,
								TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
						/*	TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $process_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>' */
 
								);

		$mes_content=$send_details['text'];
	
		// replace the merge details
		while (list($key, $value) = each($replace_array))
			$mes_content=eregi_replace("%%" . $key  . "%%",$value . "",$mes_content);
	
		return $mes_content;	
	}

	// replace the test email with default merge details
function tep_replace_test_mail_content($mail_content){
  global $currencies;
      $replace_array=array(TEXT_FN=>TEST_MAIL_FN,
							TEXT_LN=>TEST_MAIL_LN,
							TEXT_DF=>TEST_MAIL_DF,
							TEXT_EM=>TEST_MAIL_EM,
							TEXT_TN=>TEST_MAIL_TN,
							TEXT_FX=>TEST_MAIL_FX,
							TEXT_SA=>TEST_MAIL_SA,
							TEXT_SU=>TEST_MAIL_SU,
							TEXT_PC=>TEST_MAIL_PC,
							TEXT_CT=>TEST_MAIL_CT,
							TEXT_ST=>TEST_MAIL_ST,
							TEXT_CY=>TEST_MAIL_CY,
    
							TEXT_EN=>TEST_MAIL_EN,
							TEXT_SD=>getServerDate(),
							TEXT_SI=>TEST_MAIL_SI,
							TEXT_EI=>TEST_MAIL_EI,
							TEXT_EF=>TEST_MAIL_EF,
							TEXT_IN=>TEST_MAIL_IN,
							TEXT_EL=>TEST_MAIL_EL,
							TEXT_IV=>TEST_MAIL_IV,
							TEXT_IC=>TEST_MAIL_IC,
							TEXT_IF=>TEST_MAIL_IF,
							TEXT_UN=>TEST_MAIL_UN,
							TEXT_RE=>TEST_MAIL_RE,
							TEXT_FE=>TEST_MAIL_FE,
							TEXT_CF=>TEST_MAIL_CF,
							TEXT_CL=>TEST_MAIL_CL,
							TEXT_SS=>sprintf(TEST_MAIL_FORMAT_SS,TEST_MAIL_EN,TEST_MAIL_SI,TEST_MAIL_EI,date('l, jS F'),TEST_MAIL_EL),
							TEXT_SSM=>date(str_replace("/","-",EVENTS_DATE_FORMAT)),
							TEXT_RL=>TEST_MAIL_RL,
							TEXT_RM=>TEST_MAIL_RM,
							TEXT_RV=>TEST_MAIL_RV,
							TEXT_WV=>TEST_MAIL_WV,
							TEXT_FV=>TEST_MAIL_FV,
							
							TEXT_ON=>TEST_MAIL_ON,
							TEXT_OC=>TEST_MAIL_OC,
							TEXT_OD=>TEST_MAIL_OD,
							TEXT_BT=>TEST_MAIL_BT,
							TEXT_BA=>TEST_MAIL_BA,
							TEXT_PY=>TEST_MAIL_PY,
							TEXT_SB=>$currencies->format(TEST_MAIL_SB),
							TEXT_TX=>$currencies->format(TEST_MAIL_TX),
							TEXT_TL=>$currencies->format(TEST_MAIL_TL),
							TEXT_IL=>TEST_MAIL_IL,
			 );
   while (list($key, $value) = each($replace_array))
      $mail_content=eregi_replace("%%" . $key  . "%%",$value . "",$mail_content);

  return $mail_content;
}

//default mail handling function with type,merge_details,send_address details
function tep_send_default_email($type,$merge_details,$send_details){
	$details=array();
	$details['type']=$type;
	$details['table']=TABLE_EMAIL_MESSAGES;
	tep_get_template($details);      	  // get template using type and table   
    if ($details['html_text']=="") {	
	
		if($type!='PRD') return;
		$fp=@fopen(DIR_FS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/images/product_email_template.html","r");
		if (!$fp) return;
		$details['html_text']=fread($fp,filesize(DIR_FS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/images/product_email_template.html"));
		if ($details['html_text']=="") return false;
		$details['text']=strip_tags($details['html_text']);
		$details['format']="B";
    }
	tep_replace_template($details,$merge_details); // replace template content with merge details
 
	tep_strip_html($details); // strip tags;
    //send mails to given addresses
    for ($icnt=0;$icnt<sizeof($send_details);$icnt++){
		$details['to_name']=$send_details[$icnt]['to_name'];
		$details['to_email']=$send_details[$icnt]['to_email'];
		$details['from_name']=$send_details[$icnt]['from_name'];
		$details['from_email']=$send_details[$icnt]['from_email'];
		tep_send_email($details,true); // send email
    }
 }

// find the free waitlist group vip=>V, firstcome=>F, custom(question)=>C
function tep_find_waitlist_group($event_id,$sessions_id,$customer_id=0,$values=array(),$customers=1){

	if (sizeof($values)<=0){
		$value_query=tep_db_query("SELECT " . tep_event_fields_list() . " from " . TABLE_EVENTS . " e where e.events_id='" .$event_id . "'");
		$values=tep_db_fetch_array($value_query);
	}

	// check if event has waiting list feature
	if ($values['events_wait_list']!='Y') return 'E';

 	// prepare waitlist groups according to priority 
	$wait_size['V']=(int)$values['waitsize_vip'];
	$wait_size['F']=(int)$values['waitsize_firstcome'];
	$wait_size['C']=(int)$values['waitsize_custom'];

	$priority_array=array('1'=>'','2'=>'','3'=>'');

	$priority_array['1']='V';
	$priority_array['2']='C';
	$priority_array['3']='F';
	
	// iterate and find a place in free waiting list group
	$find_group='';
	$current_priority=1;
	while($find_group=='')
	{
		// if waitlist size of group has value>0
		if ($wait_size[$priority_array[$current_priority]]>0){
			// check for custom question, the event has question_id assigned
			if (($current_priority=='2' && $values['priority_question']>0) || $current_priority!='2'){
				// find no of users in the particular waitlist group, also find no in shopping cart
				//$group_count=(int)tep_waitlist_group_count($priority_array[$current_priority],$sessions_id,$values);
				$group_count=(int)tep_waitlist_group_count($priority_array[$current_priority],$sessions_id,$values)+$customers;

				$group_count+=tep_count_cart($sessions_id,"W",$priority_array[$current_priority]);

				// check if group count is within the maximum waitlist size
				if ($group_count<=$wait_size[$priority_array[$current_priority]]){
					$find_group=$priority_array[$current_priority];
					// for waitlist group vip, check if customer is vip or not
					if ($find_group=="V" && $customer_id>0){
						$customer_query=tep_db_query("SELECT customers_type from " . TABLE_CUSTOMERS . " where customers_id=" . $customer_id);
						$result=tep_db_fetch_array($customer_query);
						if ($result['customers_type']=='V') break;
					} else if ($find_group=="F" || $find_group=="C") {
							break;
					}
					$find_group='';
				}
			}
		}
		$current_priority=$current_priority+1;
		if ($current_priority>3) break;
	}
	if ($find_group==''){
		$find_group='E';
	}
	return $find_group;
 }

	// get the count of users registered for particular session in particular group
	function tep_waitlist_group_count($current_priority,$sessions_id,&$values)
	{
		$count=0;
		$pending_option="";
		if ($values['events_pending_period']>0){
			$pending_option=" and (o.orders_status>1 or date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . date('Y-m-d H:i:s',getServerDate(false)) . "') and op.orders_products_status!=5";
		}
		if ($current_priority=='V'){
			$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='V' and op.products_id='" . $sessions_id ."' " . $pending_option);
			$result=tep_db_fetch_array($query);
			$count+=(int)$result['total_count'];
			return $count;
		} else if ($current_priority=='F'){
			$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='F' and op.products_id='" . $sessions_id ."' " .  $pending_option);
			$result=tep_db_fetch_array($query);
			$count+=(int)$result['total_count'];
			return $count;
		} else if ($current_priority=='C'){
			$query=tep_db_query("select count(orders_products_id) as total_count from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='C' and op.products_id='" . $sessions_id ."' " . $pending_option);
			$result=tep_db_fetch_array($query);
			$count+=(int)$result['total_count'];
			return $count;
		}
		return 0;
	}

// function to add   to given date
function tep_dateadd($timestamp, $unit, $amount) {
		$rtime=0;
		if($timestamp>0){
			$timestring=date("Y-m-d H:i:s",$timestamp);
			$timestring = preg_replace("#\s#","",$timestring); 
			$timestring = preg_replace("#\:#","",$timestring);
			$timestring = preg_replace("#\.#","",$timestring);
			$timestring = preg_replace("#\/#","",$timestring);
			$timestring = preg_replace("#\-#","",$timestring);
			$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
			$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;
			$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
			$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
			$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
			$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
			$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
			$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);
			$array[$unit]+=$amount;
			$rtime = mktime ($array['hr'],$array['min'],$array['sec'],$array['mon'],$array['day'],$array['yr']); 
		}
	return $rtime;
}

// subtract specified interval to a given date
function tep_datesub($timestamp, $unit, $amount) {
		$timestring=date("Y-m-d H:i:s",$timestamp);
		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;
		$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);

		$array[$unit]-=$amount;
		   $rtime = mktime ($array['hr'],$array['min'],$array['sec'],$array['mon'],$array['day'],$array['yr']);
	return $rtime;
} 

 function tep_get_count($table,$condition){
    $count_query=tep_db_query("select count(*) as total from " . $table . " where " . $condition);
    if($count_result=tep_db_fetch_array($count_query))
       return (int)$count_result['total'];
    return 0;
 }
 
  function tep_get_renewal_users_count_old($events_id,$renewal_end,$check_date="")
  {
     global $customer_id;
     $count=0;
	 return $count;
     if ((int)$renewal_end<=0) return $count;
     if ($customer_id>0)
        $customer_check=" and o.customers_id!='" . $customer_id . "' ";
     
     $user_query=tep_db_query("SELECT o.customers_id,date_add(max(s.start_date),interval '" . $renewal_end ."' day) as valid_end_date,max(s.start_date) as valid_start_date,op.orders_products_status as orders_products_status from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e " .
                               " where e.events_id='" . (int)$events_id . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id " . $customer_check . " and op.products_id=s.sessions_id and s.events_id=e.events_id group by o.customers_id having valid_end_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' and valid_start_date<'" . $check_date . "' and orders_products_status!=5 ");
/*     while($user_result=tep_db_fetch_array($user_query)){
        if (date('Y-m-d')<=$user_result['max_date'] && $user_result['min_date']>$check_date){
	   $count++; 
	}
     }*/
     $count=tep_db_num_rows($user_query);
     return $count;
 }
 	// get the total no of users
	function tep_get_renewal_users_count($events,$check_date="")
	{
		global $customer_id;
		$count=0;

		// if renewal checking is enabled
		if ((int)EVENTS_RENEWAL_CHECK!=1) return $count;
		$renewal_end=(int)$events['events_renewal_end'];
		$renewal_start=$events['events_renewal_start'];
		$renewal_end=$renewal_end-1;

		if ($renewal_end<=0) return $count;
		$curdate="'" . date('Y-m-d H:i:s',getServerDate(false)) . "' ";
		//$curdate="'2005-04-15'";
		if ($customer_id>0)
			$customer_check=" and o.customers_id!='" . $customer_id . "' ";
		// if renewal start is one week before last session or two week before or last session
		if ($renewal_start=='OBS' || $renewal_start=='TBS' || $renewal_start=='FLS') {
			$start_days=0;
			if ($renewal_start=='OBS') $start_days=7;
			if ($renewal_start=='TBS') $start_days=14;
			$end_days=$renewal_end-$start_days;
			// fetch the users count with in the renewal period			
			$user_query=tep_db_query("SELECT o.customers_id,date_add(max(s.start_date),interval '" . $end_days ."' day) as valid_end_date,date_sub(max(s.start_date),interval '" . $start_days ."' day) as valid_start_date,op.orders_products_status as orders_products_status from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
									" where s.events_id='" . (int)$events['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id " . $customer_check . " and op.products_id=s.sessions_id group by o.customers_id having valid_start_date<=" . $curdate . " and valid_end_date>=" . $curdate . " and valid_start_date<='" . $check_date . "' and orders_products_status!=5");
			$count=tep_db_num_rows($user_query);
		} else if ($renewal_start=='SLS' || $renewal_start=='DLS'){
			// get the user session dates
			$user_query=tep_db_query("SELECT o.customers_id,s.start_date,date_add(s.start_date,interval '" . $renewal_end . "'  day) as end_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
									" where s.events_id='" . (int)$events['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id " . $customer_check . " and op.products_id=s.sessions_id and s.start_date<='" . $check_date . "' and op.orders_products_status!=5 order by o.customers_id,s.start_date desc");
			$prev_customer=0;
			$session_position=($renewal_start=='SLS'?2:3);
			$cur_row=1;
			$cur_date=getServerDate();
			//$cur_date='2005-02-20';

			// determine second last session,third last session
			while($user_result=tep_db_fetch_array($user_query)){
				if ($prev_customer!=$user_result['customers_id']){
					$prev_customer=$user_result['customers_id'];
					$cur_row=1;
				}
				if ($cur_row==$session_position){
					if ($user_result['start_date']<=$cur_date && $user_result['end_date']>=$cur_date) $count++;
				}
				$cur_row++;
			}
		}
		return $count;
	}

	// get the list of events to be renewed for the current customerfs
	function tep_get_renewal_events()
	{
		global $customer_id;
		$renewal_array=array();
		$count=0;
		if ((int)$customer_id<=0)
			return $renewal_array;

		// fetch all the events, customer has registered
		$event_query=tep_db_query("SELECT s.events_id,e.events_renewal_start,e.events_renewal_end from " .  TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " .
								TABLE_EVENTS . " e where o.customers_id='" . $customer_id . "' and o.orders_id=op.orders_id and op.products_type='E' and op.events_type='R' and op.products_id=s.sessions_id and s.events_id=e.events_id and op.orders_products_status!=5 group by s.events_id order by events_id");

		$renewal_details=array();
		$icnt=0;
		// check for the renewal status for the event
		while($event_result=tep_db_fetch_array($event_query)){
			$renewal_details=tep_get_renewal_details($event_result,$customer_id);
			if (sizeof($renewal_details)>0 && $renewal_details['status']=='yes'){
				$renewal_array[$icnt]['events_id']=$event_result['events_id'];
				$renewal_array[$icnt]['events_name']=tep_get_events_name($event_result['events_id']);
				$renewal_array[$icnt]['no_days']=tep_count_days($renewal_details['start_date'],$renewal_details['end_date']);
				$icnt++;
			}
		}
     return $renewal_array;
 }

// count the no of days in given start and end date
function tep_count_days($start, $end)
{
   if( $start != '0000-00-00' and $end != '0000-00-00' )
   {
       $timestamp_start = strtotime($start);
       $timestamp_end = strtotime($end);
       if( $timestamp_start >= $timestamp_end ) return 0;
       $start_year = date("Y",$timestamp_start);
       $end_year = date("Y", $timestamp_end);
       $num_days_start = date("z",strtotime($start));
       $num_days_end = date("z", strtotime($end));
       $num_days = 0;
       $i = 0;
       if( $end_year > $start_year )
       {
           while( $i < ( $end_year - $start_year ) )
           {
             $num_days = $num_days + date("z", strtotime(($start_year + $i)."-12-31"));
             $i++;
           }
         }
         return ( $num_days_end + $num_days ) - $num_days_start;
   }
   else
   {
         return 0;
     }
}

// fetch user pending payment regarding order
function tep_get_orders_reminder_details($orders_id,$events_id,$session_style,$all_detail=false){
	$details=array("tax"=>0,"amount"=>0);
	if ((int)$orders_id<=0 || (int)$events_id<=0) return $details;

	// fetch the tax result
	$tax_query=tep_db_query("SELECT op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_id='" . $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and op.orders_products_status!=5 limit 1");
	$tax_result=tep_db_fetch_array($tax_query);
	$details["tax"]=$tax_result["products_tax"];
	
	// determine if all details are required or only amount is required
	if (!$all_detail){
		$details["amount"]=tep_get_orders_reminder_amount($orders_id,$events_id,$session_style);
	} else {
		if ($session_style=='E'){
			// Get Total Order Amount
			$order_total_query=tep_db_query("SELECT sum(op.final_price) as total from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS  . " s where op.orders_id='" .  $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.orders_products_status!=5 group by op.orders_id union " . 
											"SELECT sum(op.events_fees) as total from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS  . " s where op.orders_id='" .  $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and ((op.events_type='R' and op.waitlist_type='P') or op.events_type='C') and op.orders_products_status!=5 group by op.orders_id");
			
			$order_total_result=tep_db_fetch_array($order_total_query);
			$details["order_total"]=(float)$order_total_result["total"];

			$order_total_result=tep_db_fetch_array($order_total_query);
			$details["product_total"]=(float)$order_total_result["total"];

			// Get Confirmed Total,Confirmed Paid amount
			$confirm_query=tep_db_query("SELECT sum(op.events_fees) as confirm_total,sum(op.final_price) as confirm_paid,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.waitlist_orders_id='" . $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.orders_products_status!=5 group by op.orders_id,s.events_id");
			$confirm_result=tep_db_fetch_array($confirm_query);
			$details["confirm_total"]=$confirm_result["confirm_total"];
			$details["confirm_paid"]=$confirm_result["confirm_paid"];
		} else {
			// if session_style is single session
			$order_total_query=tep_db_query("SELECT sum(op.events_fees)-sum(op.final_price) as total,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_id='" . $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and op.orders_products_status!=5 group by op.orders_id,s.events_id");
			$order_total_result=tep_db_fetch_array($order_total_query);
			$details["order_total"]=$order_total_result["total"];
		}
	}
	return $details;
}
// get the remaining amount to be paid for an order
function tep_get_orders_reminder_amount($orders_id,$events_id,$session_style,$tax=false){
	$final_amount=0;
	if ($orders_id<=0 || $events_id<=0) return $final_amount;

	// if session style is event
	if ($session_style=='E'){
		// Get the Total of Order
		$order_total_query=tep_db_query("SELECT sum(op.final_price) as total,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS  . " s where op.orders_id='" .  $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.orders_products_status!=5 group by op.orders_id union " . 
										"SELECT sum(op.events_fees) as total,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS  . " s where op.orders_id='" .  $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and ((op.events_type='R' and op.waitlist_type='P') or op.events_type='C') and op.orders_products_status!=5 group by op.orders_id");
		
		$order_total_result=tep_db_fetch_array($order_total_query);
		$amount_paid=(float)$order_total_result["total"];
		$products_tax=$order_total_result["products_tax"];
		
		$order_total_result=tep_db_fetch_array($order_total_query);
		$amount_total=(float)$order_total_result["total"];
		
		// Get the Confirmed Total,Confirmed Paid amount
		$confirm_query=tep_db_query("SELECT sum(op.events_fees) as confirm_total,sum(op.final_price) as confirm_paid,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.waitlist_orders_id='" . $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.orders_products_status!=5 group by op.orders_id,s.events_id");
		$confirm_result=tep_db_fetch_array($confirm_query);

		// calculate the final amount
		if ($tax)
			$final_amount=tep_add_tax($amount_total,$products_tax)-(tep_add_tax($amount_paid,$products_tax)+tep_add_tax($confirm_result["confirm_paid"],$products_tax));
		else
			$final_amount=$amount_total-($amount_paid+$confirm_result["confirm_paid"]);			
	} else {
		// if session style is session
		$order_total_query=tep_db_query("SELECT sum(op.events_fees)-sum(op.final_price) as total,op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_id='" . $orders_id . "' and s.events_id='" . $events_id . "' and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and op.orders_products_status!=5 group by op.orders_id,s.events_id");
		$order_total_result=tep_db_fetch_array($order_total_query);
		if ($tax)
			$final_amount=tep_add_tax($order_total_result["total"],$order_total_result["products_tax"]);
		else
			$final_amount=$order_total_result["total"];
	}
	if ($final_amount<=0) $final_amount=0;
	return $final_amount;
}

// Get the reminder fees of all event
 function tep_get_all_reminder_fees(){
    global $customer_id,$currencies,$cart;
    $reminder_array=array();
    if ((int)$customer_id==0) return $reminder_array;

    $reminder_query=tep_db_query("SELECT o.orders_id,e.events_id,e.session_style,count(op.products_id) as session_count from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s, " .
                             TABLE_EVENTS . " e where o.customers_id='" . (int)$customer_id . "' and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and op.orders_id=o.orders_id and op.products_id=s.sessions_id and s.events_id=e.events_id and op.orders_products_status!=5 group by o.orders_id,e.events_id");
    $icnt=0;
    while($reminder_result=tep_db_fetch_array($reminder_query)){
       $cart_found=false;
       /*if (isset($cart) & is_object($cart)){
         $cart_found=$cart->check_orders_id($reminder_result['orders_id'],$reminder_result['session_id']);
       }*/
       if ($cart_found==false){
		   $reminder_array[$icnt]['events_id']=$reminder_result['events_id'];
   		   $reminder_array[$icnt]['events_name']=tep_get_events_name($reminder_result['events_id']);
		   $reminder_array[$icnt]['amount']=tep_get_orders_reminder_amount($reminder_result['orders_id'],$reminder_result['events_id'],$reminder_result['session_style'],true);
		   $reminder_array[$icnt]['count']=$reminder_result['session_count'];
		   $reminder_array[$icnt]['orders_id']=$reminder_result['orders_id'];
		   $icnt++;
       }
    }   
    return $reminder_array; 
 }

// Get the reminder fees of given event
	function tep_get_events_reminder_fees($orders_id,$events_id,$session_style){
		global $customer_id,$currencies,$cart;
		$session_array=array("amount"=>0,"session_ids"=>array(),"session_dates"=>array());
		if ((int)$customer_id==0) return $session_array;
		
		$event_check=" and s.events_id='" . (int)$events_id . "' and o.orders_id='" . (int)$orders_id . "'";

		// get total amount for pending order details
		$reminder_query=tep_db_query("SELECT s.start_date,op.products_id from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " . TABLE_EVENTS_SESSIONS . " s " .
								 " where o.customers_id='" . (int)$customer_id . "'" . $event_check . " and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and op.orders_id=o.orders_id and op.products_id=s.sessions_id and op.orders_products_status!=5 order by s.start_date");
		$product_total=0;
		$order_total=0;
		while($reminder_result=tep_db_fetch_array($reminder_query)){
		   $session_array["session_ids"][]=$reminder_result["products_id"];
		   $session_array["session_dates"][]=$reminder_result["start_date"];
		}   
		// Get the remaining amount	
		$session_array["amount"]=tep_get_orders_reminder_amount($orders_id,$events_id,$session_style,true);
		return $session_array; 
	}
	function tep_get_sms_address($mobile){
	return $mobile . '@' . EVENTS_SMS_GATEWAY;
	}

	//  function to check waiting list of particular event_id
	function tep_check_waiting_list($event_id)
	{
		$value_query=tep_db_query("SELECT " . tep_event_fields_list() . " from " . TABLE_EVENTS . " e where e.events_id='" .$event_id . "'");
		$values=tep_db_fetch_array($value_query);
		// if event has no waiting list option just exit
	
		if ($values['events_wait_list']!='Y') return;
	
		// get the ending period of dates to fetch if there is a forward reservation_period
		if ($values['events_forward_period']=='Y'){
			$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$values['events_forward_length']));
			$check_data=" and start_date<='" . $check_date . "' ";
		}	 
	
		// select the sessions_id from events_sessions 
		$event_query=tep_db_query("select sessions_id from " . TABLE_EVENTS_SESSIONS . " where events_id='" . $event_id . "'" . $check_data . " order by start_date");
		$cnt=tep_db_num_rows($event_query);
		while($event_result=tep_db_fetch_array($event_query)){
			tep_process_waiting_list($event_id,$event_result['sessions_id'],$values);
			tep_promote_waiting_list($event_id,$event_result['sessions_id'],$values);
		}
	}

	// function to fetch events field list
	function tep_event_fields_list(){
		$fields_list=" e.events_id,e.events_max_reserve,e.waitsize_vip,e.waitsize_firstcome,e.waitsize_custom,e.priority_vip,e.priority_firstcome,e.priority_custom,e.priority_question,
						e.events_renewal_start,e.events_renewal_end,e.events_wait_list,e.events_pending_period,e.session_gaps,e.session_reduction,e.events_forward_period,e.events_forward_length,
						e.events_fees,e.events_tax_class_id,e.waitfee_vip,e.waitfee_firstcome,e.waitfee_custom,e.sessions_select_count,e.sessions_select_interval,e.sessions_date_count ";
		return $fields_list;
	}

	 // function to forward waitlist users to reserved and promoting waiting lists
	 function tep_process_waiting_list($event_id,$sessions_id,$values=array()){
	 	// get the event field values if not present
		global $customer_id;
		if (sizeof($values)<=0){
			$value_query=tep_db_query("SELECT " . tep_event_fields_list() . " from " . TABLE_EVENTS . " e where e.events_id='" .$event_id . "'");
			$values=tep_db_fetch_array($value_query);
			
			if ($values['events_wait_list']!='Y') return;
		}
		// check if users exist in waiting list group
		$waitlist_count=tep_waitlist_count($sessions_id,$values);
		if ($waitlist_count<=0) return;

		// get the total reservation count
		$reserve_count=tep_reserve_count($sessions_id,$values);
	   
		// fetch the session date from session table
		$date_query=tep_db_query("SELECT start_date from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . $sessions_id . "'");
		$date_result=tep_db_fetch_array($date_query);
     
		$max_reservations=((int)$values['events_max_reserve'])-tep_get_renewal_users_count($values,$date_result['start_date']);
		
		// if reservations reached max limit just return
		if ($reserve_count>=$max_reservations) return;
     
		$question_query=tep_db_query("SELECT answer_type from " . TABLE_POP_QUESTIONS . " where question_id='" . (int)$values['priority_question'] . "'");
		$question=tep_db_fetch_array($question_query);

		// prioity to fetch waiting list
		$priority_array=array('1'=>'','2'=>'','3'=>'');
		
		$priority_array[(int)$values['priority_vip']]='V';
		$priority_array[(int)$values['priority_firstcome']]='F';
		$priority_array[(int)$values['priority_custom']]='C';
		
		// get seats to fill from waiting list to reservation
		$seatsfill=$max_reservations-$reserve_count;
		$current_priority=1;
		while($seatsfill>0)
		{
			$orders_products_id=(int)tep_next_reservation($priority_array[$current_priority],$sessions_id,(int)$question['answer_type']);
			if ($orders_products_id>0){
				// move reservation from waiting list to reservation
				tep_move_reservation($orders_products_id);
				$seatsfill=$seatsfill-1;
			} else {
				$current_priority=$current_priority+1;
				if ($current_priority>3)
					break;
			}
		}
     //get max_reservations and waiting list size
	}  

	// function to promote waitlist users from one group to another group
	function tep_promote_waiting_list($event_id,$sessions_id,$values=array()){
	 	// get the event field values if not present
		if (sizeof($values)<=0){
			$value_query=tep_db_query("SELECT " . tep_event_fields_list() . " from " . TABLE_EVENTS . " e where e.events_id='" .$event_id . "'");
			$values=tep_db_fetch_array($value_query);
			
			if ($values['events_wait_list']!='Y') return;
		}
		// check if users exist in waiting list group
		$waitlist_count=tep_waitlist_count($sessions_id,$values);
		if ($waitlist_count<=0) return;

		$question_query=tep_db_query("SELECT answer_type from " . TABLE_POP_QUESTIONS . " where question_id='" . (int)$values['priority_question'] . "'");
		$question=tep_db_fetch_array($question_query);
		
		// form the priority group
		$wait_size['V']=(int)$values['waitsize_vip'];
		$wait_size['F']=(int)$values['waitsize_firstcome'];
		$wait_size['C']=(int)$values['waitsize_custom'];
	
		$priority_array=array('1'=>'','2'=>'','3'=>'');
		
		$priority_array[(int)$values['priority_vip']]='V';
		$priority_array[(int)$values['priority_firstcome']]='F';
		$priority_array[(int)$values['priority_custom']]='C';
	
		$current_priority=1;
		$move=false;
		$empty_seats['V']=0;
		$empty_seats['F']=0;
		$empty_seats['C']=0;
		$previous_priority=1;
		$move_count=0;
		while(true)
		{
			// find if the group has enough seats
			$waitlist_group_count=tep_waitlist_group_count($priority_array[$current_priority],$sessions_id,$values);
			if ($waitlist_group_count>0){
				for($jcnt=1;$jcnt<=$current_priority-1;$jcnt++){
					for($icnt=1;$icnt<=$empty_seats[$priority_array[$jcnt]];$icnt++){
						// find the appropriate waitlist reservation to be promoted
						$orders_products_id=tep_next_reservation($priority_array[$current_priority],$sessions_id,$question,($priority_array[$jcnt]=='V'?true:false));
						if ($orders_products_id>0){
							tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set waitlist_type='" . $priority_array[$jcnt] . "' where orders_products_id='" . $orders_products_id . "'");
							tep_send_event_email($orders_products_id,'WPL');
							$move_count=$move_count+1;
							$waitlist_group_count=$waitlist_group_count-1;
							if ($waitlist_group_count<=0) break;     
						}	 
					}
					$empty_seats[$priority_array[$jcnt]]=$empty_seats[$priority_array[$jcnt]]-$move_count;
					if ($waitlist_group_count<=0) break;
					$move_count=0;
				}
			}
			$empty_seats[$priority_array[$current_priority]]=$wait_size[$priority_array[$current_priority]]-$waitlist_group_count;
		
			$previous_priority=$current_priority;
	
			$current_priority=$current_priority+1;
			if ($current_priority>3) break;
		}
	}

	// move reservation to confirmed one
	function tep_move_reservation($id)
	{
		tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set events_type='R',waitlist_type='P' where orders_products_id='" . $id . "'");
		//send confirm email
		//'WPR' -> waitlist promotion to reservation;
		tep_send_event_email($id,'WPR');
	}

	// find effective reservation to be confirmed or promoted
	function tep_next_reservation($current_priority,$sessions_id,$question_type,$check_vip=false)
	{
		if ($current_priority=='V'){
			$query=tep_db_query("select orders_products_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='V' and op.orders_products_status!=5 and op.products_id='" . $sessions_id ."' order by o.date_purchased");
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		} else if ($current_priority=='F'){
			if ($check_vip==true)
				$query=tep_db_query("select orders_products_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 c.customers_type='V' and op.products_type='E' and op.events_type='W' and op.waitlist_type='F' and op.orders_products_status!=5 and op.products_id='" . $sessions_id ."' order by o.date_purchased");
			else   
				$query=tep_db_query("select orders_products_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='F' and op.orders_products_status!=5 and op.products_id='" . $sessions_id ."' order by o.date_purchased");
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		}	else if ($current_priority=='C'){
			$order_string='';
			if ($question_type=="D")
				$order_string=" order by question_value_date ";
			else if ($question_type=="T")
				$order_string=" order by question_value_text ";
			else
				$order_string=" order by question_value_number ";
			if ($check_vip==true)
				$query=tep_db_query("select orders_products_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 c.customers_type='V' and op.products_type='E' and op.events_type='W' and op.waitlist_type='C' and op.orders_products_status!=5 and op.products_id='" . $sessions_id . "'" . $order_string);
			else
				$query=tep_db_query("select orders_products_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.products_type='E' and op.events_type='W' and op.waitlist_type='C' and op.orders_products_status!=5 and op.products_id='" . $sessions_id ."'" . $order_string);
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		}
		return 0;
	} 

 // check if session has reservation in orders_products table
 function tep_check_single_reservation($session_id,$customer_id)
 {
    $check_query=tep_db_query("select count(*) as total from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o where o.orders_id=op.orders_id and o.customers_id='" . $customer_id . "' and op.products_id='" . $session_id . "' and op.products_type='E' and (op.events_type='W' or op.events_type='R') and op.orders_products_status!=5");
    if ($result=tep_db_fetch_array($check_query)){
     if (((int)$result['total'])>0) return true;
    }
    return false;
 }

// get the discount price for the event
function tep_get_discount_price($events_id,$fees,$date)
{
  $discount_amount=0;
  
  $discount_query=tep_db_query("SELECT discount_value,discount_type from " . TABLE_EVENTS_DISCOUNTS . " where events_id='" . $events_id . "' and '" . $date . "'>=discount_start_date and '" . $date . "'<=discount_end_date order by discount_start_date");
  if (tep_db_num_rows($discount_query)){
    $discount_result=tep_db_fetch_array($discount_query);
	// P=>Percentage A=>Amount
    if ($discount_result['discount_type']=='P'){
       $discount_amount=$fees*$discount_result['discount_value']/100;
    } else {
       $discount_amount=$discount_result['discount_value'];
    }
  }
  return $discount_amount;   
}

// get the locations name
function tep_get_locations_name($location_id,$link_service='L',$service_id='0') {
	if($link_service=='L'){
    	$location_query = tep_db_query("select location_name from " . TABLE_EVENTS_LOCATIONS . " where location_id = '" . (int)$location_id . "'");
	} else if($link_service=='S'){
		$location_query=tep_db_query("SELECT sl.service_location_name as location_name from " . TABLE_SERVICES." s, ".TABLE_SERVICES_LOCATIONS ." sl where  s.service_location=sl.service_location_id and s.service_id='".(int)$service_id ."'");
	}
    	$location = tep_db_fetch_array($location_query);

    return $location['location_name'];
}  

	// format date according to date setting in configuration
  function format_date($raw_date,$simple=false){
    if ( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '0000-00-00') || ($raw_date == '') ) return false;
	$format=EVENTS_DATE_FORMAT;

	if ($simple) $format=strtolower($format);
    $year = substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);

    if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
      return date($format, mktime($hour, $minute, $second, $month, $day, $year));
    } else {
      return ereg_replace('2037' . '$', $year, date($format, mktime($hour, $minute, $second, $month, $day, 2037)));
    }
  }
	// get events price either reservation,waitlisted amount
	function tep_get_events_price(&$events_result,$events_type,$waitlist_type,$date,$tax=false){
		$final_amount=0;
		if ($events_type=='R')  { // reserved user
			$final_amount=$events_result["events_fees"]-tep_get_discount_price($events_result["events_id"],$events_result["events_fees"],$date);
		} else {
			switch($waitlist_type){
				case "V":
					$final_amount=$events_result["waitfee_vip"];  // vip user
					break;
				case "F":
					$final_amount=$events_result["waitfee_firstcome"]; // firstcome user
					break;
				case "C":
					$final_amount=$events_result["waitfee_custom"]; // custom user
					break;
			}
		}
		if ($tax){
			$tax_rate=tep_get_tax_rate($events_result["events_tax_class_id"]);
			$final_amount=tep_add_tax($final_amount,$tax_rate);
		}
		return $final_amount;
	}
	// get the list of events with atleast one free seat
	function &tep_get_free_events($dates,$type,$exclude){
		global $ecPath;
		$free_list=array();
		$path_split=array();
		$option_waitlist="";
		$option_dates="";
		$option_events="";
		$option_category="";
		// get the category in which the event is located
		if ($ecPath!='') $path_split=split("_",$ecPath);
		if (sizeof($path_split)>0){
			$option_category=" and ecd.events_categories_id='" . $path_split[sizeof($path_split)-1] . "' ";
		}
		//add additonal option if dates is not empty
		if ($dates!='') $option_dates=" and s.start_date in(" . $dates . ")";
		//omit events ids in the list if needs
		if (sizeof($exclude)>0){
			for ($icnt=0;$icnt<sizeof($exclude);$icnt++){
				$option_events.=$exclude[$icnt]['id'] . ",";
			}
			$option_events=" and e.events_id not in(" . substr($option_events,0,-1) . ") ";
		}
		//add additonal option if type is waiting list
		if ($type=='W') $option_waitlist=" and e.events_wait_list='Y'";
		if ($option_category=="")
			$event_query=tep_db_query("SELECT ed.events_name,e.events_max_reserve,e.events_forward_period,e.events_forward_length,e.events_pending_period,e.events_id,(e.waitsize_vip+e.waitsize_firstcome+e.waitsize_custom) as events_max_waitlist,e.events_wait_list from " . TABLE_EVENTS. " e, " . TABLE_EVENTS_DESCRIPTION . " ed, " . TABLE_EVENTS_SESSIONS . " s where e.events_id=ed.events_id " . EVENTS_CONDITION_STATUS . " and s.events_id=e.events_id " . $check_data . $option_waitlist . $option_events . " and s.start_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' and s.sessions_type!='' group by events_id order by events_name");
		else 
			$event_query=tep_db_query("SELECT ed.events_name,e.events_max_reserve,e.events_forward_period,e.events_forward_length,e.events_pending_period,e.events_id,(e.waitsize_vip+e.waitsize_firstcome+e.waitsize_custom) as events_max_waitlist,e.events_wait_list from " . TABLE_EVENTS. " e, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " ecd, " . TABLE_EVENTS_DESCRIPTION . " ed, " . TABLE_EVENTS_SESSIONS . " s where e.events_id=ed.events_id and ecd.events_id=e.events_id " . EVENTS_CONDITION_STATUS . " and s.events_id=e.events_id " . $check_data . $option_waitlist . $option_events . $option_category . " and s.start_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' and s.sessions_type!='' group by events_id order by events_name");

		if (tep_db_num_rows($event_query)<=0) return $free_list;

		// iterate events and find the total count of each event with given dates
		while($event_result=tep_db_fetch_array($event_query)){
			$check_data="";

			if ($event_result['events_forward_period']=='Y'){
				$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$event_result['events_forward_length']));
				$check_data=" and s.start_date<='" . $check_date . "' ";
			}
			$date_query=tep_db_query("SELECT s.sessions_id,s.start_date from " . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . $event_result["events_id"] . "' and s.start_date>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' " . $check_option . " order by s.start_date ");
			
			//$reserve_query=tep_db_query("SELECT count(op.products_id) as total from " . TABLE_EVENTS_SESSIONS . " s left join " . TABLE_ORDERS_PRODUCTS . " op on op.products_id=s.sessions_id and op.products_type='E' and op.events_type='" . $type . "' where s.events_id='" . $event_result["events_id"] . "' " . $check_data . " group by s.sessions_id");
			//accept flag to test all given dates are free
			$accept=false;
			while($date_result=tep_db_fetch_array($date_query)){

				if ($type=='R'){ // if reserved users
					$reserve_count=tep_reserve_count($date_result["sessions_id"],$event_result);
					if ($event_result['events_max_reserve']>$reserve_count){ // if total count is more than available seats exit for this event
						$accept=true;
						break;
					}
				} else if ($type=='W') { // if waitlisted users 
					$waitlist_count=tep_waitlist_count($date_result["sessions_id"],$event_result);
					if ($event_result['events_max_waitlist']>$waitlist_count){ // if total count is more than available waitlist seats exit for this event
						$accept=true;
						break;
					}
				}
			}
			if ($accept){
				$free_list[]=array('id'=>$event_result['events_id'],'name'=>$event_result['events_name']);
			}
		}
		return $free_list;
	}
	// Replace the template content
	function tep_replace_template(&$details,&$replace_array){
		reset($replace_array);
		while(list($key,$value)=each($replace_array)){
			$details['html_text']=eregi_replace("%%" . $key . "%%",$value . "",$details['html_text']);
		}
		$details['html_text']=eregi_replace("%%current_url%%"		,HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/",$details['html_text']);
	}

	// common function to send email
	function tep_send_email(&$details,$default=false){
		$result=false;
		if ($default==false && (int)EMAIL_ACTIVATE!=1) return $result;

		 $message = new email(array('X-Mailer: osCommRes'));
			
		 if ($details['format'] != 'T') {
			 $message->add_html($details['html_text'], $details['text']);
		 } else {
			 $message->add_text($details['text']);
		 }
	     
		 $message->build_message();
		 $result=$message->send($details['to_name'], $details['to_email'], $details['from_name'], $details['from_email'], $details['subject']);
		 
		 unset($message);
		 return $result;
	}

	// function to fetch template content from database table
	function tep_get_template(&$details){
		$details['html_text']='';
		$details['text']='';
		$events_option="";
		if (isset($details['events_id'])){
			$add_option=" and events_id='" . $details['events_id'] . "' ";
		} else if (isset($details['subscription_id'])){
			$add_option=" and subscription_id='" . $details['subscription_id'] . "' ";
		}
		$mail_data_query=tep_db_query("SELECT * from " . $details["table"] . " where message_type='" . $details["type"] . "'" . $add_option);
		if (tep_db_num_rows($mail_data_query)>0){
			$mail_data_result=tep_db_fetch_array($mail_data_query);
			//get message content
			$details['format']=$mail_data_result['message_format'];
			$details['html_text']=$mail_data_result['message_text'];
			$details['subject']=$mail_data_result['message_subject'];
		}
	}
	// strip the html tags
	function tep_strip_html(&$details){
		$details['text']=strip_tags($details['html_text'],'<br>');
		$details['text']=str_replace(array('<br />','<br>','<BR>','<BR />','<br/>','<BR/>'),chr(13). chr(10),$details['text']);
	}
	//common function to send sms 
	function send_sms($to,$from,$text,$country){
		global $sms,$messageStack;

		$to=str_replace(" ","",$to);

		if (!$sms->connecthost()){
			$messageStack->add_session("SMS Error:" . $sms->get_error(), 'error');
			return false;
		}
		if (!$sms->send_sms($to,$from,$text,$country)){
			$messageStack->add_session($sms->get_failed_messages(), 'error');
			return false;
		}
		return true;
	}

	// get rounded amount according to rounding factor in configuration
 function tep_get_rounded_amount($amount){
 	$result=0;
	$round_digit=0;
	$decimal=0;
 	$round_type=EVENTS_ORDER_AMOUNT_ROUND;

	$decimal=floor((($amount-floor($amount))*100)+0.5);
	switch($round_type){
		case "0.01":
			$result=$amount;
			break;
		case "0.05":
			$round_digit=$decimal%10;
			if ($round_digit>7) {
				$decimal=(floor($decimal/10)+1)*10;
			} else if ($round_digit>2) {
				$decimal=(floor($decimal/10)*10)+5;
			} else {
				$decimal=floor($decimal/10)*10;			
			}
			$result=floor($amount)+$decimal/100;
			break;
		case "0.1":
			$decimal=(floor($decimal/10))*10;
			$result=floor($amount)+$decimal/100;
			break;
		case "0":
		default:
			if ($decimal>=50)
				$result=floor($amount)+1;
			else
				$result=floor($amount);
	}
	return $result;
 }
 // function to find given event has to be displayed or not
 function tep_get_event_display_status($events_id){
 	$check_query=tep_db_query("SELECT max(s.start_date) as first_date,min(s.start_date) as last_date,e.events_status from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_SESSIONS .
								" s where e.events_id='" . (int)$events_id . "' and s.events_id=e.events_id and e.events_status>=1");
	$check_result=tep_db_fetch_array($result);
	$status=(int)$check_result["events_status"];
	if ($status<=0 || $check_result["first_date"]=="" || $check_result["last_date"]=="")
		return false;
		
	if ($status==1) return true;
	$curdate=getServerDate();
	if ($status==2) {
		if ($check_status["first_date"]<=$curdate) return false;
		else return true;
	}
	if ($status>2){
		if ($check_status["end_date"]<=$curdate) return false;
		else return true;
	}
 }
 	// function to get renewal details
	function tep_get_renewal_details(&$events,$customer_id,$only_data=false){
		$details=array();
		$renewal_end=(int)$events['events_renewal_end'];
		$renewal_start=$events['events_renewal_start'];
		$renewal_end=$renewal_end-1;
		if ($customer_id<=0 || $renewal_end<=0) return $details;
		$curdate=getServerDate();
		$customer_check=" and o.customers_id='" . $customer_id . "' ";
		// if renewal start is one week before last session,two week before last session or first last session
		if ($renewal_start=='OBS' || $renewal_start=='TBS' || $renewal_start=='FLS') {
			$start_days=0;
			if ($renewal_start=='OBS') $start_days=7;
			if ($renewal_start=='TBS') $start_days=14;
			$end_days=$renewal_end-$start_days;
			$user_check_query=tep_db_query("SELECT date_add(max(s.start_date),interval '" . $end_days ."' day) as valid_end_date,date_sub(max(s.start_date),interval '" . $start_days ."' day) as valid_start_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
									" where s.events_id='" . (int)$events['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id " . $customer_check . " and op.products_id=s.sessions_id and op.orders_products_status!=5");
			if (tep_db_num_rows($user_check_query)>0){
				$user_check=tep_db_fetch_array($user_check_query);
				if ($only_data){
					$details["end_date"]=$user_check["valid_end_date"];
					return $details;
				}
				if ($user_check["valid_start_date"]!="" && $user_check["valid_end_date"]!=""){
					$details["start_date"]=$user_check["valid_start_date"];
					$details["end_date"]=$user_check["valid_end_date"];
					$details["status"]="no";
					if ($user_check["valid_end_date"]>=$curdate) {
						if ($user_check["valid_start_date"]<=$curdate)
							$details["status"]="yes";
						else
							$details=array();
					}
				}
			}
		} else {
			// if the result is second last session,third last session
			$user_check_query=tep_db_query("SELECT o.customers_id,s.start_date,date_add(s.start_date,interval '" . $renewal_end . "'  day) as end_date from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
									" where s.events_id='" . (int)$events['events_id'] . "' and op.products_type='E' and op.events_type='R' and op.orders_id=o.orders_id " . $customer_check . " and op.products_id=s.sessions_id and op.orders_products_status!=5 order by o.customers_id,s.start_date desc");
			$session_position=($renewal_start=='SLS'?2:3);
			$cur_row=1;
			while($user_check=tep_db_fetch_array($user_check_query)){
				if ($cur_row==$session_position){
					if ($only_data){
						$details["end_date"]=$user_check["end_date"];
						return $details;
					}
					$details["start_date"]=$user_check["start_date"];
					$details["end_date"]=$user_check["end_date"];
					$details["status"]="no";
					if ($user_check['end_date']>=$curdate) {
						if ($user_check["start_date"]<=$curdate)
							$details["status"]="yes";
						else
							$details=array();
					}
					break;
				}
				$cur_row++;
			}
		}
		return $details;
	}
 // format may be in format dd mm yyyy in any combinations but length must be equal to this
 function tep_check_date_raw($date,$format,$sep_char="-"){
 	$date_details=array('y'=>0,'m'=>0,'d'=>0);
	$split_arr=split($sep_char,$date);
	$split_format=split($sep_char,$format);
	if (!(sizeof($split_arr)==sizeof($split_format) && sizeof($split_arr)>0 && sizeof($split_arr)<=3)) return false;
	
	for ($icnt=0;$icnt<sizeof($split_arr);$icnt++){
		if (isset($date_details[strtolower($split_format[$icnt])]))
			$date_details[strtolower($split_format[$icnt])]=(int)$split_arr[$icnt];
	}
	return checkdate($date_details['m'],$date_details['d'],$date_details['y']);
 }
 // format may be in format dd mm yyyy in any combinations but length must be equal to this
 function tep_convert_date_raw($date,$format=EVENTS_DATE_FORMAT,$sep_char="-"){
 	$date_details=array('y'=>0,'m'=>0,'d'=>0);
	$split_arr=split($sep_char,$date);
	$split_format=split($sep_char,$format);
	if (!(sizeof($split_arr)==sizeof($split_format) && sizeof($split_arr)>0 && sizeof($split_arr)<=3)) return "";
	
	for ($icnt=0;$icnt<sizeof($split_arr);$icnt++){
		if (isset($date_details[strtolower($split_format[$icnt])]))
			$date_details[strtolower($split_format[$icnt])]=(int)$split_arr[$icnt];
	}
	return $date_details['y'] . '-' . $date_details['m'] . '-' . $date_details['d'];
 }
 // Update events table with session starting and ending date
 function tep_set_event_limit_dates($events_id){
	$events_id=(int)$events_id;
	if ($events_id<=0) return;
	$session_query=tep_db_query("SELECT max(s.start_date) as last_date,min(s.start_date) as first_date from " . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . $events_id . "' and (s.sessions_type='S' or s.sessions_type='R')");
	if (tep_db_num_rows($session_query)>0){
		$session_result=tep_db_fetch_array($session_query);
		tep_db_query("UPDATE " . TABLE_EVENTS . " set sessions_start_date='" . $session_result["first_date"] . "', sessions_end_date='" . $session_result["last_date"] . "' where events_id='" . $events_id . "'");
	}
 }
	// function to get events display text
	function tep_get_events_display_text($events_name,$start_time,$location){
		$bolTest=true;
		if ($bolTest) return $events_name;
		$result=$events_name;
		
		$dayLight=strtolower(date("A",strtotime($start_time)));
		$result.=" - " . ($dayLight=="pm"?"Night":"Day");
		$result.=" - " . $location;
		return $result;
	}

 // get the current server date considering date offset settings
 function getServerDate($date=true){
 	/*$curTime=mktime();
	$offset=(float)EVENTS_SERVER_DATE_OFFSET;
	if ($offset>=-23.5	&& $offset<=23.5) {
		$hour=abs($offset);
		$min=$offset-$hour;
		$delta = @gmmktime($hour,$min,0,1,1,1970);
		if ($offset>0)
			$curTime=$curTime + $delta;
		else
			$curTime=$curTime - $delta;
	}

	if ($date_result){
		return date('Y-m-d',$curTime);
	} else {
		return $curTime;
	}*/
	$offset=(float)EVENTS_SERVER_DATE_OFFSET;
	if($offset>0){
		if(strpos($offset,'.')>0){
			$cur_offset_time = mktime(date('H')+abs($offset),date('i')+30,date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}else{
			$cur_offset_time = mktime(date('H')+abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}
	}else{
		if(strpos($offset,'.')>0){
			$cur_offset_time = mktime(date('H')-abs($offset)+1,date('i')-30,date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}else{
			$cur_offset_time = mktime(date('H')-abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}
	}
 }
 
   ////rmh referral
// Returns an array with sources
// TABLES: sources
  function tep_get_sources($sources_id = '') {
    $sources_array = array();
    if (tep_not_null($sources_id)) {
        $sources = tep_db_query("select sources_name from " . TABLE_SOURCES . " where sources_id = '" . (int)$sources_id . "'");
        $sources_values = tep_db_fetch_array($sources);
        $sources_array = array('sources_name' => $sources_values['sources_name']);
    } else {
      $sources = tep_db_query("select sources_id, sources_name from " . TABLE_SOURCES . " order by sources_name");
      while ($sources_values = tep_db_fetch_array($sources)) {
        $sources_array[] = array('sources_id' => $sources_values['sources_id'],
                                   'sources_name' => $sources_values['sources_name']);
      }
    }

    return $sources_array;
  }

////rmh referral
// Creates a pull-down list of countries
  function tep_get_source_list($name, $selected = '', $parameters = '') {
    $sources_array = array(array('id' => '', 'text' => PULL_DOWN_DEFAULT));
    $sources = tep_get_sources();

    for ($i=0, $n=sizeof($sources); $i<$n; $i++) {
      	$sources_array[] = array('id' => $sources[$i]['sources_id'], 'text' => $sources[$i]['sources_name']);
    }
	if (DISPLAY_REFERRAL_OTHER=='true'){
		$sources_array[] = array('id' => '9999', 'text' => TEXT_REFERRAL_OTHER);
	}

    return tep_draw_pull_down_menu($name, $sources_array, $selected, $parameters);
  }
  
  function tep_get_customer_options($type) {
    $options_array = array();
	$options_array[] = array('id' => '', 'text' => PULL_DOWN_DEFAULT);
    $options = tep_db_query("select options_id, options_name from " . TABLE_CUSTOMER_OPTIONS . " where options_type='". $type  ."' order by options_name");
      while ($options_values = tep_db_fetch_array($options)) {
        $options_array[] = array('id' => $options_values['options_id'],
                                   'text' => $options_values['options_name']);
      }
    return $options_array;
  }

  function tep_draw_hidden($name, $value = '', $parameters = '') {
    $field = '<input type="hidden" name="' . tep_output_string($name) . '"';

      $field .= ' value="' . tep_output_string($value) . '"';

    if (tep_not_null($parameters)) $field .= ' ' . $parameters;

    $field .= '>';

    return $field;
  }

  function tep_get_all_input_params($exclude_array = '') {
    global $HTTP_GET_VARS;

    if (!is_array($exclude_array)) $exclude_array = array();

    $get_url = '';
    if (is_array($HTTP_GET_VARS) && (sizeof($HTTP_GET_VARS) > 0)) {
      reset($HTTP_GET_VARS);
      while (list($key, $value) = each($HTTP_GET_VARS)) {
        if ( (strlen($value) > 0) && ($key != tep_session_name()) && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') ) {
          $get_url .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }
      }
    }

    return $get_url;
  }
  
function tep_payment_installed($module){
		$modules=MODULE_PAYMENT_INSTALLED;

		if ($modules!=""){
			$modules_array=split(";",$modules);
			
			if (array_search($module,$modules_array)===false){
				return false;
			} else {
				return true;
			}
		}
	}
	
  function tep_product_small_image($image,$title,$parameters=""){

	if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
		return tep_image(DIR_WS_IMAGES . "small/" . $image,$title,'','',$parameters);
	} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
		return tep_image(DIR_WS_IMAGES . "big/" . $image,$title,SMALL_IMAGE_WIDTH,'',$parameters);
	} else {
		return tep_image(DIR_WS_IMAGES . $image,$title,SMALL_IMAGE_WIDTH,'',$parameters);

	}
  }	
    function tep_product_email_image($image,$title,$parameters=""){
	if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "small/" . $image . '" width=50 height=50 border="0" ' . $parameters . '>';
	} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "big/" . $image . '" width=50 height=50 border="0" ' . $parameters . '>';
	} else if(file_exists(HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image))  {
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" width=50 height=50 border="0" ' . $parameters . '>';
	} else {
		return tep_image(DIR_WS_IMAGES . 'pixel_trans.gif','', '50','50');
	}	
  }	
    function tep_product_custom_image($image,$title,$parameters="",$width=50,$height=50,$calculate=true){
		$filename=$image;
		if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
			$filename="small/" . $image;
		} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
			$filename="big/" . $image;
		}
		if ($calculate){
		  if ($image_size = @getimagesize(DIR_FS_CATALOG . DIR_WS_IMAGES . $filename)) {
			  if ($image_size[0]>$width){
				  $ratio = $width / $image_size[0];
				  $height = intval($image_size[1] * $ratio);
			  } elseif ($image_size[1]>$height) {
				  $ratio = $height / $image_size[1];
				  $width = intval($image_size[0] * $ratio);
			  } else {
				  $width = $image_size[0];
				  $height = $image_size[1];
			  }
		  }
		}
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $filename . '" width="' .$width . '" height="' . $height. '" border="0" ' . $parameters . '>';
	} 
   //display the subscription page image
      function tep_subscription_custom_image($image,$title,$parameters="",$width=50,$height=50){
	if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "small/" . $image . '" width="' .$width . '" height="' . $height. '" border="0" ' . $parameters . '>';
	} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "big/" . $image . '" width="' . $width . '" height="' . $height . '" border="0" ' . $parameters . '>';
	} else {
		return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" width=50 height=50 border="0" ' . $parameters . '>';
	}
  }

  
  // get the total no of users found in the cart
function tep_attribute_count_cart($product_id){
	$cart_count=0; //count in shopping cart and edit orders table
	global $customer_id;
	
	// time elapsed of events_order_timeout 
	$expiry=strtotime("-" . ((int)EVENTS_ORDER_TIMEOUT) . " minutes");
	// get cart count by checking records within this expiry time
	$query="SELECT sum(cb.customers_basket_quantity) as total from " . TABLE_CUSTOMERS_BASKET . " cb  where cb.products_id='" . $product_id . "' " . 
							" and UNIX_TIMESTAMP(cb.customers_basket_date_added)>" . $expiry . "  and cb.products_type='P' and cb.customers_id != $customer_id;";
						
	$result=tep_db_query($query);
	$result_array=tep_db_fetch_array($result);	
	$cart_count+=(int)$result_array["total"];

	//get backend orders edit table count
	$query="SELECT count(*) as total from " . TABLE_ORDERS_EDIT_PRODUCTS . " eo where eo.products_id='" . $product_id .  
							"' and UNIX_TIMESTAMP(eo.date_added)>" . $expiry . " and eo.products_type='P';";
	$result=tep_db_query($query);
	$result_array=tep_db_fetch_array($result);	
	$cart_count+=(int)$result_array["total"];

	return $cart_count;
}

 function getGMTTime(){
		$timestring=date("Y-m-d H:i:s",mktime());
		$offset=date("O");
		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;

		$array['years']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['months']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['days']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hours']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['minutes']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['seconds']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);

		$hour=(int)substr($offset,1,2);
		$min=(int)substr($offset,3);


		if (substr($offset,0,1)=="-"){
		   $rtime = mktime ( $array['hours']      +     $hour,
							$array['minutes'] +     $min,
							$array['seconds'] +     0,
							$array['months']  +     0,
							$array['days']      +     0,
							$array['years']      +     0);
		} else {
		   $rtime = mktime ( $array['hours']      -     $hour,
							$array['minutes'] -    $min,
							$array['seconds'] -     0,
							$array['months']  -     0,
							$array['days']      -     0,
							$array['years']      -     0);
		}
	return $rtime;
 }
 
	function tep_owd_costs($type='',$value=0){
		$cost_total = 0;
		if($type=='') return;
		
		if($type=="order" && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER')){
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER;
		
		} else if($type=="overweight" && defined('MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE')){
			if (defined("MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD") && MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD>0){
				if($value>MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD) {
					$cost_total = MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE;
				}
			}
		} else if($type=='quantity' && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM')) {
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM*$value;
		
		} else if($type=="packing" && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING') && defined('SHIPPING_MAX_WEIGHT')) {
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING*(ceil($value/SHIPPING_MAX_WEIGHT));
		}
		
		return $cost_total;
	}
	function tep_get_OWD_shipping_type($type=''){
		switch($type){
			case 'usps_Express':
				$shipping="POS.EXP"; 
			break;
			case 'usps_Parcel':
				$shipping="OWD.4th.PARCEL";
			break;
			case 'ups_GND':
				$shipping="UPS.GND";
			break;
			case 'ups_1DA':
				$shipping="UPS.NDA";
			break;
			default:
			$shipping="OWD.1ST.PRIORITY";
		}
		return $shipping; 
	}
	function tep_get_unit_name(){
		if (!defined("SHOP_WEIGHT_UNIT")) return TEXT_KG;
		if (!defined("TEXT_" . SHOP_WEIGHT_UNIT)) return TEXT_KG;
		return constant("TEXT_" . SHOP_WEIGHT_UNIT);
	}
	function tep_get_display_weight($weight){
		return $weight . '&nbsp;' . tep_get_unit_name();
	}		
	  function tep_get_customer_survey_options($type,$other_option=false) {
    $options_array = array();
	$options_array[] = array('id' => '', 'text' => PULL_DOWN_DEFAULT);
    $options = tep_db_query("select options_id, options_name from " . TABLE_CUSTOMER_OPTIONS . " where options_type='". $type  ."' order by options_name");
      while ($options_values = tep_db_fetch_array($options)) {
        $options_array[] = array('id' => $options_values['options_id'],
                                   'text' => $options_values['options_name']);
      }
	 if($other_option) 	$options_array[] = array('id'=>'9999', 'text' => TEXT_REFERRAL_OTHER); 
    return $options_array;
  }
  $nwords = array(    "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
                     "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
                     "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                     "Nineteen", "Twenty", 30 => "Thirty", 40 => "Forty",
                     50 => "Fifty", 60 => "Sixty", 70 => "Seventy", 80 => "Eighty",
                     90 => "Ninety" );

function int_to_words($x)
{
     global $nwords;
     if(!is_numeric($x))
     {
         $w = '#';
     }else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }else{
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }else{
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= '-'. $nwords[$r];
             }
         } else if($x < 1000)
         {
             $w .= $nwords[floor($x/100)] .' Hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' and '. int_to_words($r);
             }
         } else if($x < 1000000)
         {
             $w .= int_to_words(floor($x/1000)) .' Thousand';
             $r = fmod($x, 1000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $w .= 'and ';
                 }
                 $w .= int_to_words($r);
             }
         } else {
             $w .= int_to_words(floor($x/1000000)) .' Million';
             $r = fmod($x, 1000000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $word .= 'and ';
                 }
                 $w .= int_to_words($r);
             }
         }
     }
     return $w; 
	}
	function tep_check_module_status(&$module,$payment_zone,$except_zone_list,$except_country_list){
		global $order;
	  if ( ($module->enabled == true) && (($except_zone_list!='' && substr($except_zone_list,0,1)!='M') || ($except_country_list!='' && substr($except_country_list,0,1)!='M'))) {
	  	$add_option='';
		if ($except_zone_list!='' && substr($except_zone_list,0,1)!='M') $add_option.=" geo_zone_id in(" . $except_zone_list . ") ";
		if ($except_country_list!='' && substr($except_country_list,0,1)!='M') {
			if ($add_option!='') $add_option.=' or ';
			$add_option.=" zone_country_id in(" . $except_country_list . ") ";
		}
		if ($add_option!=""){
			$check_query=tep_db_query("SELECT zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where  (" . $add_option. ") and zone_country_id='" . $order->billing['country']['id'] . "' and (zone_id is null or zone_id = '0' or zone_id ='" . $order->billing['zone_id'] ."');");
			if (tep_db_num_rows($check_query)>0){
				$module->enabled=false;
			}
		}
	  }
      if ( ($module->enabled == true) && ($payment_zone!='') ) {
        $check_flag = false;
		$check_sql = "select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id in(" . $payment_zone . ") and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id";
        $check_query = tep_db_query($check_sql);
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }

        if ($check_flag == false) {
          $module->enabled = false;
        }
      }
	}
	
	function tep_check_shipping_module_status(&$module,$payment_zone,$except_zone_list,$except_country_list){
		global $order;
	  if ( ($module->enabled == true) && (($except_zone_list!='' && substr($except_zone_list,0,1)!='M') || ($except_country_list!='' && substr($except_country_list,0,1)!='M'))) {
	  	$add_option='';
		if ($except_zone_list!='' && substr($except_zone_list,0,1)!='M') $add_option.=" geo_zone_id in(" . $except_zone_list . ") ";
		if ($except_country_list!='' && substr($except_country_list,0,1)!='M') {
			if ($add_option!='') $add_option.=' or ';
			$add_option.=" zone_country_id in(" . $except_country_list . ") ";
		}
		$check_query=tep_db_query("SELECT zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where  (" . $add_option. ") and zone_country_id='" . $order->delivery['country']['id'] . "' and (zone_id is null or zone_id = '0' or zone_id ='" . $order->delivery['zone_id'] ."');");
		if (tep_db_num_rows($check_query)>0){
			$module->enabled=false;
		}
	  }
      if ( ($module->enabled == true) && ($payment_zone!='') ) {
        $check_flag = false;
		$securepay_zone=trim($payment_zone)!=""?$payment_zone:'0';
        $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id in(" . $payment_zone . ") and zone_country_id = '" . $order->delivery['country']['id'] . "' order by zone_id");
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->delivery['zone_id']) {
            $check_flag = true;
            break;
          }
        }

        if ($check_flag == false) {
          $module->enabled = false;
        }
      }
	}
	
	function replace_content(&$replaced_content,&$template_details){
		$ttotal_cols=1;
		while(list($key,$value)=each($template_details)){
			switch(substr($key,0,strpos($key,'_'))){
				case "VALUE":
					$replaced_content=str_replace("{{" . $key . "}}",$value,$replaced_content);
					break;
				case "SECTION":
					if ($value!=1){
						$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/","",$replaced_content);
					} else {
						$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
					}
					break;
				case "REPEAT":
					$start_pos=strpos($replaced_content,"{{" . $key . "_START}}")+strlen("{{" . $key ."_START}}");
					$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
					$repeat_content=substr($replaced_content,$start_pos,$end_pos-$start_pos);
					$merged_total_content='<table cellpadding="0" cellspacing="0" width="100%" border="0">' . "\n";
					$col=0;
					$row=0;
					for ($icnt=0,$n=count($value);$icnt<$n;$icnt++){
						$merged_content='';
						if ($col==0 || $ttotal_cols==1) $merged_content.='<tr>';
						$merged_content.='<td valign="top"' . ($row==0?$tcols_width:''). '>' . $repeat_content;

						reset($value[$icnt]);
						while(list($itemkey,)=each($value[$icnt])){
							$merged_content=str_replace("{{" . $key . "_" . $itemkey . "}}",$value[$icnt][$itemkey],$merged_content);
						}
						$col++;
						if ($col==$ttotal_cols) {
							$col=0;
							$row++;
						}
						$merged_total_content.="\n" . $merged_content;
					}
					$merged_total_content.="</table>";
					//$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/",$merged_total_content,$replaced_content);
					$replaced_content=substr($replaced_content,0,$start_pos) . $merged_total_content . substr($replaced_content,$end_pos);
					$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
					break;
			}
		}
	}
	
		function tep_check_password_strength($pwd)
	{
            $tot_average        = 0.0; 
            $pwdav_len            = 0.0;                 
            $pwdav_caps        = 0.0;                 
            $pwdav_nums        = 0.0;                                         
            $pwdav_small        = 0.0; 
            $pwdav_puncts        = 0.0;                 
            $total_char_used = 0; 
            if (strlen($pwd)>0) 
            { 
                $p_limit = 5; 
                $pwd_len = strlen($pwd); 
                $nums_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (is_numeric($pwd[$i])) 
                        $nums_cnt++; 
                } 
                if ($nums_cnt>0) 
                    $total_char_used += 10; 
					
                $small_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_lower($pwd[$i])) 
                    { 
                        $small_cnt++; 
                    } 
                } 
                if ($small_cnt>0) 
                { 
                    $total_char_used += 26; 
                } 

                $caps_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_upper($pwd[$i])) 
                    { 
                        $caps_cnt++; 
                    } 
                } 
                if ($caps_cnt>0) 
                { 
                    $total_char_used += 26; 
                } 

                $puncts_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_punct($pwd[$i])) 
                    { 
                        $puncts_cnt++; 
                    } 
                } 
                if ($puncts_cnt>0) 
                { 
                    $total_char_used += 31; 
                } 
                // calculation   
				$len_min=ENTRY_PASSWORD_MIN_LENGTH;
				$len_max=16;                                      
                if (($pwd_len>$len_min) and ($pwd_len<$len_max)) 
                { 
                    $pwdav_len += (100 / $p_limit); 
                }                                                         
                // caps 
                $tot_average += $pwdav_len; 
                if (20 <= (($caps_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_caps += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_caps += ($caps_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_caps; 
                // numbers 
                if (10 <= (($nums_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_nums += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_nums += ($nums_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_nums; 
                // small 
                if (30 <= (($small_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_small += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_small += ($small_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_small; 
                // symbols 
                if (10 <= (($puncts_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_puncts += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_puncts += ($puncts_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                 
                $tot_average += $pwdav_puncts;             

                $charSet = $total_char_used; 
            } 

            $tot_average=round($tot_average, 0); 
			echo $tot_average;
			if($tot_average<=40)
				return false;
			else
				return true;
				
	}
	
	function tep_get_events_output_tree($parent_id = '0',&$content,$default,$event_category_id=0) {
    global $languages_id,$selected_name,$login_id,$login_groups_type;

    if (!is_array($events_category_tree_array)) $events_category_tree_array = array();
	// filte to particular instructor
	$login_option="";
	if ($login_groups_type==TEXT_INSTRUCTOR_ENTRY){
		$login_option=" and e.events_instructor=" . $login_id;
	}
	$event_where = '';
	if($event_category_id>0)$event_where = " and ec.events_categories_id='" . $event_category_id . "'";
	// iterate with nested category
	$events_categories_sql = "select ec.events_categories_id, ecd.events_categories_name, ec.parent_id from " . TABLE_EVENTS_CATEGORIES . " ec, " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ec.events_categories_id = ecd.events_categories_id and ecd.language_id = '" . (int)$languages_id . "' and ec.parent_id = '" . (int)$parent_id . "'" . $event_where . " order by ec.sort_order, ecd.events_categories_name";
	//echo $parent_id . ":" . $events_categories_sql;exit;
	$events_categories_query = tep_db_query($events_categories_sql);
	while ($events_categories = tep_db_fetch_array($events_categories_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_events_category_space($events_categories['events_categories_id']) . tep_output_string($events_categories['events_categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of events of particular category
		$events_query=tep_db_query("select ed.events_name,ed.events_id from " . TABLE_EVENTS . ' e, ' . TABLE_EVENTS_DESCRIPTION . " ed, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " ecd where ecd.events_categories_id='" . $events_categories['events_categories_id'] . "' " . $login_option . " and ed.language_id = " . (int)$languages_id . EVENTS_CONDITION_STATUS. " and e.events_id=ecd.events_id and e.events_id=ed.events_id order by ed.events_name");
		while ($events=tep_db_fetch_array($events_query))
		{
			$content .= '<option style="color:#000000" value="' . tep_output_string($events['events_id']) . '"';
			if ($default == $events['events_id']){
				$selected_name=$events['events_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . tep_output_string($events['events_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}    
		tep_get_events_output_tree($events_categories['events_categories_id'], $content,$default);
		$content.='</optgroup>';
	}

}
	function write_events_category_space($category_id){
	    global $languages_id,$selected_name,$login_id,$login_groups_type;
		$sql = "select parent_id,ec.events_categories_id,events_categories_name from " . TABLE_EVENTS_CATEGORIES . " ec," . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ec.events_categories_id=ecd.events_categories_id and ecd.language_id = '" . (int)$languages_id . "' and ec.events_categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_events_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_event_select_menu($name, $values, $default = '', $parameters = '', $required = false,$initial_category_id=0,$need_all=true,$initial_parent_id=0) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_SELECT . '</option>';
	
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		tep_get_events_output_tree($initial_parent_id,$content,$default,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
	function tep_get_events_array_single($first=''){
		global $languages_id;
		$event_array=array();
		$event_query=tep_db_query("SELECT e.events_id,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where e.events_id=ed.events_id " . EVENTS_CONDITION_STATUS . " and language_id='" . $languages_id. "' order by ed.events_name");
		while($event_result=tep_db_fetch_array($event_query)){
			$event_array[]=array('id'=>$event_result['events_id'],'text'=>$event_result['events_name']);
		}
		return $event_array;
	} 
	
	
	// products tree structure
	
function tep_get_products_output_tree($parent_id = '0',&$content,$default,$product_category_id=0) {
    global $languages_id,$selected_name,$login_id,$login_groups_type;

    if (!is_array($products_category_tree_array)) $products_category_tree_array = array();
	// filte to particular instructor
	$product_where = '';
	if($product_category_id>0)$product_where = " and pc.categories_id='" . $product_category_id . "'";
	// iterate with nested category
	$products_categories_sql = "select pc.categories_id, pcd.categories_name, pc.parent_id from " . TABLE_CATEGORIES . " pc, " . TABLE_CATEGORIES_DESCRIPTION . " pcd where pc.categories_id = pcd.categories_id and pcd.language_id = '" . (int)$languages_id . "' and pc.parent_id = '" . (int)$parent_id . "'" . $product_where . " order by pc.sort_order, pcd.categories_name";
	//echo $parent_id . ":" . $events_categories_sql;exit;
	$products_categories_query = tep_db_query($products_categories_sql);
	while ($products_categories = tep_db_fetch_array($products_categories_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_products_category_space($products_categories['categories_id']) . tep_output_string($products_categories['categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of products of particular category
		$products_query=tep_db_query("select pd.products_name,pd.products_id from " . TABLE_PRODUCTS . ' p, ' . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd where pcd.categories_id='" . $products_categories['categories_id'] . "' " .  " and pd.language_id = " . (int)$languages_id . PRODUCTS_CONDITION_STATUS. " and p.products_id=pcd.products_id and p.products_id=pd.products_id order by pd.products_name");
		while ($products=tep_db_fetch_array($products_query))
		{
			$content .= '<option style="color:#000000" value="' . tep_output_string($products['products_id']) . '"';
			if ($default == $products['products_id']){
				$selected_name=$events['products_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . tep_output_string($products['products_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}    
		tep_get_products_output_tree($products_categories['categories_id'], $content,$default);
		$content.='</optgroup>';
	}

}
	function write_products_category_space($category_id){
	    global $languages_id,$selected_name,$login_id,$login_groups_type;
		$sql = "select parent_id,pc.categories_id,categories_name from " . TABLE_CATEGORIES . " pc," . TABLE_CATEGORIES_DESCRIPTION . " pcd where pc.categories_id=pcd.categories_id and pcd.language_id = '" . (int)$languages_id . "' and pc.categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_products_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_product_select_menu($name, $values, $default = '', $parameters = '', $required = false,$initial_category_id=0,$need_all=true,$initial_parent_id=0) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_SELECT . '</option>';
	
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	

		$content="";
		tep_get_products_output_tree($initial_parent_id,$content,$default,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
	function tep_get_products_array_single($first=''){
		global $languages_id;
		$product_array=array();
		$product_query=tep_db_query("SELECT p.products_id,pd.products_name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_id=pd.products_id " . PRODUCTS_CONDITION_STATUS . " and language_id='" . $languages_id. "' order by pd.products_name");
		while($product_result=tep_db_fetch_array($product_query)){
			$product_array[]=array('id'=>$product_result['products_id'],'text'=>$product_result['products_name']);
		}
		return $product_array;
	} 
  function tep_info_image($image, $alt, $width = '', $height = '') {
    if (tep_not_null($image) && (file_exists(DIR_WS_IMAGES . $image)) ) {
      $image = tep_image(DIR_WS_IMAGES . $image, $alt, $width, $height);
    } else {
      $image = $alt;
    }

    return $image;
  }
 function check_restrick(){
   global $customer_id,$HTTP_GET_VARS,$customer_group_id;
    if(!$customer_group_id && $customer_id>0) $customer_group_id=get_customer_group_id();
    $check_restrict_customer="and ((restrict_to_customers='' OR ISNULL(restrict_to_customers)) AND (restrict_to_groups='' OR ISNULL(restrict_to_groups)))";     
    if($customer_id>0) $check_restrict_customer=substr($check_restrict_customer,0,-1)." OR (restrict_to_customers like '%".$customer_id."%' OR restrict_to_groups like '%".$customer_group_id."%'))";    
    $return=false;
    if($HTTP_GET_VARS['products_id'] && $HTTP_GET_VARS['products_id']>0){
		$check_product_query=tep_db_query("select products_id from ".TABLE_PRODUCTS." where products_id='".(int)$HTTP_GET_VARS['products_id']."' ".$check_restrict_customer);		
		
		if(tep_db_num_rows($check_product_query)>0) $return=true;
    }
    return $return;
 }   
 function get_customer_group_id(){
 	global $customer_id;
 	$customer_group_id="";
 	if($customer_id>0){
 		$customer_group_query=tep_db_query("select customers_groups_id from ".TABLE_CUSTOMERS." where customers_id='".(int)$customer_id."'"); 		
 		if(tep_db_num_rows($customer_group_query)>0) {
 			$customer_group=tep_db_fetch_array($customer_group_query);
 			$customer_group_id=$customer_group['customers_groups_id'];			
 		} 		
 	}
 	return $customer_group_id;
 }
 
 function tep_show_products_price($inital_price,$product_info,$select_quantity=true,$quantity_combo=false){
 	global $currencies,$products_price;
 	$output="<b>" . TEXT_PRICE . ": " .$products_price . "</b>";

 	if ($product_info["products_price_break"]!='Y') return $output;

	$breaks_query=tep_db_query("SELECT quantity,discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" .$product_info["products_id"] . " order by quantity");
	

	if(tep_db_num_rows($breaks_query)<=0) return $output;

	$output="";
	$tax=tep_get_tax_rate($product_info['products_tax_class_id']);
	$select_script="";
	if ($select_quantity){
		$select_script="onMouseOver='javascript:rowOverEffect2(this);' onMouseOut='javascript:rowOutEffect2(this);' onClick='javascript:setQuantity(this,%s)'";
		$output.='<script language="javascript">var prev;function setQuantity(object,quan){object.className="moduleRowSelected";document.getElementById("qty").value=quan;if(prev && prev!=object) prev.className="moduleRow";prev=object;load_stock_first('. $product_info["products_id"] .');}function rowOverEffect2(object) { if (object.className == "moduleRow") object.className = "moduleRowOver";}function rowOutEffect2(object) {if (object.className == "moduleRowOver") object.className = "moduleRow";}</script><input type="hidden" name="qty" value=1 id="qty">';
	}

	$output.='<table border="0" cellpadding="2" cellspacing="0" width="100%" id="tablePriceBreaks">
				<tr>
					<td class="smallText" align="right"><b>' . TEXT_QUANTITY  . '</b></td>
					<td class="smallText" align="right"><b>' . TEXT_PRICE . '</b></td>
				</tr>
				<tr class="moduleRow" ' . sprintf($select_script,1) . '>
					<td class="smallText" align="right"><b>1</b></td>
					<td class="smallText" align="right"><b>' .$currencies->format(tep_add_tax($product_info["products_price"], $tax)) . '</b></td>
				</tr>';
				
				
	while ($break_result = tep_db_fetch_array($breaks_query)) {
	    $quantity=$break_result['quantity'];
		$price=$currencies->format(tep_add_tax($product_info["products_price"]-$break_result['discount_per_item'], $tax) * $quantity);
		$output.='<tr class="moduleRow" ' . sprintf($select_script,$quantity) . '>
					<td class="smallText" align="right"><b>' . $quantity  . '</b></td>
					<td class="smallText" align="right"><b>' . $price . '</b></td>
				</tr>';
	}
	if ($quantity_combo){
		$price_breaks=tep_get_products_price_breaks($product_info["products_id"]);
		$output.='<tr height="10"><td></td></tr><tr><td class="main" colspan="2" align="right">' . TEXT_QUANTITY . ': ' . tep_draw_pull_down_menu('qty',$price_breaks,1) .'</td></tr>';
	}
	$output.='</table><script language="javascript">setQuantity(document.getElementById("tablePriceBreaks").rows[1],1)</script>';
	
	return $output;
 }
 
 function tep_get_products_breaks($product_info,$tax_rate){
 	global $currencies;
	
	$breaks_query=tep_db_query("SELECT quantity,discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" .$product_info["products_id"] . " order by quantity");
	if(tep_db_num_rows($breaks_query)<=0) return false;

	$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"]="{enabled:true,prices:{";
	$result=array();
	$icnt=0;
	
	$result[]=array('QUANTITY'=>1,"PRICE"=>$currencies->format(tep_add_tax($product_info["products_price"],$tax_rate)));
	
	$GLOBALS["JS_START"].="setQuantity('','1');\n";
	
	while ($break_result = tep_db_fetch_array($breaks_query)) {
		$price=tep_add_tax($product_info["products_price"]-$break_result['discount_per_item'], $tax_rate) * $break_result['quantity'];
	    $result[]=array('QUANTITY'=>$break_result['quantity'],"PRICE"=>$currencies->format($price));
		$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"].=$break_result['quantity'] .":" . $price . ",";
				

		$icnt++;
	}
	$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"]=substr($GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"],0,-1) . "}}";
	return $result;
 }

 function tep_get_products_price_breaks($products_id){
 	$price_breaks=false;
	$breaks_query=tep_db_query("SELECT quantity from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" . $products_id . " order by quantity");
	if (tep_db_num_rows($breaks_query)>0){
		$price_breaks=array(array('id'=>1,'text'=>1));
		while($breaks_result=tep_db_fetch_array($breaks_query)){
			$price_breaks[]=array('id'=>$breaks_result["quantity"],'text'=>$breaks_result["quantity"]);
		}
	}
	return $price_breaks;
 }

function tep_write_payment_response($order_id,$payment_response){
	tep_db_query("insert into ".TABLE_PAYMENT_RESPONSE." (order_id,payment_response) values('$order_id','" . tep_db_input($payment_response) . "')");
}
function tep_update_payment_response_code($old_id,$order_id){
	tep_db_query("UPDATE ".TABLE_PAYMENT_RESPONSE." set order_id='$order_id' where order_id='" . tep_db_input($old_id) . "'");
}
function tep_join_keys_arr($arr,$sep){
	if (count($arr)<=0) return "";
	$payment_response="";
	reset($arr);
	while( list($key,$value) = each($arr)){
		$payment_response.="$key => " . tep_db_prepare_input($value) . $sep;
	}
	return $payment_response;
}
function tep_get_plain_products_price($products_price){
     global $customer_id;
	  if (!tep_session_is_registered('customer_id')) {
		 $customer_discount = 0;
		 if (defined("GUEST_DISCOUNT")) $customer_discount=(int)GUEST_DISCOUNT;
		 if ($customer_discount >= 0) {
			$products_price = $products_price + $products_price * abs($customer_discount) / 100;
		 } else {
			$products_price = $products_price - $products_price * abs($customer_discount) / 100;
		 }
		 return $products_price;
		 
	  } elseif (tep_session_is_registered('customer_id')) {
		 $query = tep_db_query("select g.customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . $customer_id . "'");
		 $query_result = tep_db_fetch_array($query);
		 $customers_groups_discount = $query_result['customers_groups_discount'];
		 $query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
		 $query_result = tep_db_fetch_array($query);
		 $customer_discount = $query_result['customers_discount'];
		 $customer_discount = $customer_discount + $customers_groups_discount;

		 if ($customer_discount >= 0) {
			$products_price = $products_price + $products_price * abs($customer_discount) / 100;
		 } else {
			$products_price = $products_price - $products_price * abs($customer_discount) / 100;
		 }
		return $products_price;
	  }
}
function tep_check_event_display() {
   global $ecPath,$current_events_category_id;

   $get_events_query=tep_db_query("SELECT e.events_id from " .  TABLE_EVENTS . " e, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES  . " ec " .
								  " where ec.events_categories_id='" .$current_events_category_id . "'  and ec.events_id=e.events_id  " . EVENTS_CONDITION_STATUS);
	if(tep_db_num_rows($get_events_query)==1) {
		$get_events_result=tep_db_fetch_array($get_events_query);
			tep_redirect(tep_href_link(FILENAME_SESSION_DETAILS, ($ecPath ? 'ecPath=' . $ecPath . '&' : '') . 'events_id=' . $get_events_result['events_id']));
	}								  
}

 require("wallet_general.php");
 require("freeway_general.php");
?>