<?php
/*
  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

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

Copyright 2007 ZacWare Pty. Ltd
*/

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die(); 
// begin old format
    
// use condition in all event status checking 
define('EVENTS_CONDITION_STATUS'," and (e.events_status=1 or ( e.events_status=2 and e.sessions_start_date>'" . getServerDate(true) . "') or (e.events_status>=3 and e.sessions_end_date>'" . getServerDate(true) . "')) and date_format(e.events_date_available,'%Y-%m-%d')<='" . getServerDate(true) . "'");
define('SUBSCRIPTION_CONDITION_STATUS'," and (su.subscription_status>=1) and date_format(su.subscription_date_available,'%Y-%m-%d')<='" . getServerDate(true) . "'");

////
//Return files stored in box that can be accessed by user
	/*function tep_get_events_output_tree($parent_id = '0',&$content,$default) {
    global $languages_id,$selected_name,$login_id,$login_groups_type;

    if (!is_array($events_category_tree_array)) $events_category_tree_array = array();
    
	$login_option="";
	if ($login_groups_type==TEXT_INSTRUCTOR_ENTRY){
		$login_option=" and e.events_instructor=" . $login_id;
	}
	// iterate with nested category
	$events_categories_query = tep_db_query("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 . "' order by ec.sort_order, ecd.events_categories_name");
	while ($events_categories = tep_db_fetch_array($events_categories_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . tep_output_string($events_categories['events_categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		tep_get_events_output_tree($events_categories['events_categories_id'], $content,$default);
		$content.='</optgroup>';
	}

	// 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='" . (int)$parent_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>';
    }    
}	*/ 	 

	function tep_get_tax_description($class_id, $country_id, $zone_id) {
    $tax_query = tep_db_query("select tax_description from " . TABLE_TAX_RATES . " tr left join " . TABLE_ZONES_TO_GEO_ZONES . " za on (tr.tax_zone_id = za.geo_zone_id) left join " . TABLE_GEO_ZONES . " tz on (tz.geo_zone_id = tr.tax_zone_id) where (za.zone_country_id is null or za.zone_country_id = '0' or za.zone_country_id = '" . (int)$country_id . "') and (za.zone_id is null or za.zone_id = '0' or za.zone_id = '" . (int)$zone_id . "') and tr.tax_class_id = '" . (int)$class_id . "' order by tr.tax_priority");
    if (tep_db_num_rows($tax_query)) {
      $tax_description = '';
      while ($tax = tep_db_fetch_array($tax_query)) {
        $tax_description .= $tax['tax_description'] . ' + ';
      }
      $tax_description = substr($tax_description, 0, -3);

      return $tax_description;
    } else {
     // return TEXT_UNKNOWN_TAX_RATE;
	 return 'Unknown Tax Rate';
    }
  }

  function tep_display_attributes($products_id=0){
  		global $currencies;
  		$result=""; 
  		//$attribute_query=tep_db_query("select products_options,products_options_values,options_values_price from ".TABLE_ORDERS_PRODUCTS_ATTRIBUTES." where orders_id='".(int)$orders_id."' order by orders_products_id,products_options");
  		$attribute_query=tep_db_query("SELECT pa.options_values_price as options_values_price,po.products_options_name as products_options,pov.products_options_values_name as products_options_values FROM " . TABLE_PRODUCTS_ATTRIBUTES . " pa LEFT JOIN " . TABLE_PRODUCTS_OPTIONS . " po ON po.products_options_id=pa.options_id LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov ON pov.products_options_values_id=pa.options_values_id WHERE products_id='$products_id' and pa.options_id=po.products_options_id and pa.options_values_id=pov.products_options_values_id group by products_options_values_id order by products_options_name");
		 
  		if(tep_db_num_rows($attribute_query)>0){
  		 $result.="<tr><td colspan='9' class='smalltext'><table border='0' cellspacing='0' cellpadding='0' width='60%'>";
  		 while($attributes=tep_db_fetch_array($attribute_query)){
  			$result.="<tr><td width='15%'></td>".
  			"<td width='23%' align='left' class='smalltext' nowrap>".$attributes['products_options']."</td>". 
  			"<td width='20%' align='left' class='smalltext' nowrap>".$attributes['products_options_values']."</td>".
  			"<td width='25%' align='left' class='smalltext' nowrap>".$currencies->format($attributes['options_values_price'])."</td></tr>";  			
  		 } 
  		 $result.="</table></td></tr>";
  		}
  		return $result;
  }
  function tep_admin_name($admin_id) {
    $admin = tep_db_query("select admin_firstname, admin_lastname from " . TABLE_ADMIN . " where admin_id = '" . (int)$admin_id . "'");
    $admin_values = tep_db_fetch_array($admin);

    return $admin_values['admin_firstname'] . ' ' . $admin_values['admin_lastname'];
  }
  
  function tep_create_random_value($length, $type = 'mixed') {
    if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;

    $rand_value = '';
    while (strlen($rand_value) < $length) {
      if ($type == 'digits') {
        $char = tep_rand(0,9);
      } else {
        $char = chr(tep_rand(0,255));
      }
      if ($type == 'mixed') {
        if (eregi('^[a-z0-9]$', $char)) $rand_value .= $char;
      } elseif ($type == 'chars') {
        if (eregi('^[a-z]$', $char)) $rand_value .= $char;
      } elseif ($type == 'digits') {
        if (ereg('^[0-9]$', $char)) $rand_value .= $char;
      }
    }

    return $rand_value;
  }

// count payment modules
  function tep_count_payment_modules() {
    return tep_count_modules(MODULE_PAYMENT_INSTALLED);
  }  

  function tep_count_modules($modules = '') {
    $count = 0;

    if (empty($modules)) {
		return $count;
	}	

    $modules_array = split(';', $modules);

    for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
      $class = substr($modules_array[$i], 0, strrpos($modules_array[$i], '.'));
      if (is_object($GLOBALS[$class])) {
        if ($GLOBALS[$class]->enabled) {
          $count++;
        }
      }	  
    }
    return $count;
  }

  // config function for date formats
  function tep_cfg_date_formats($value,$key='') {
    $format=array(array('id'=>'d-m-Y','text'=>'dd-mm-yyyy'),
	              array('id'=>'m-d-Y','text'=>'mm-dd-yyyy'),
				  array('id'=>'Y-m-d','text'=>'yyyy-mm-dd'));
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_pull_down_menu($name,$format,$value) . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
 // config function for date formats
  function tep_cfg_time_formats($value,$key='') {
    $format=array(array('id'=>'12','text'=>'12 hour'),
	              array('id'=>'24','text'=>'24 hour'));
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_pull_down_menu($name,$format,$value) . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }

  // config function for order amount round factor
  function tep_cfg_pull_down_round_factors($value,$key='') {
    $format=array(array('id'=>'0','text'=>'None'),
	              array('id'=>'0.01','text'=>'0.01'),
	              array('id'=>'0.05','text'=>'0.05'),
				  array('id'=>'0.1','text'=>'0.1'));
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_pull_down_menu($name,$format,$value,'onchange="javascript:save_round_factor()"') . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // config function for activating sms gateway
  function tep_cfg_sms_option($value,$key='') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_radio_field($name,'1',($value==1?true:false)) . '&nbsp;' . TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field($name,'0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // config function for renewal days 
  function tep_cfg_renewal_option($value,$key='') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_radio_field($name,'1',($value==1?true:false)) . '&nbsp;' . TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field($name,'0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // config function for activating email
  function tep_cfg_email_option($value,$key='') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_radio_field($name,'1',($value==1?true:false)) . '&nbsp;' . TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field($name,'0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // config function for report maximum rows
  function tep_cfg_pull_down_report_max_rows($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$result=tep_draw_input_field($name,$value,'size=6 maxlength=5') . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // config function for report maximum links
  function tep_cfg_pull_down_report_max_links($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$result=tep_draw_input_field($name,$value,'size=6 maxlength=5') . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
    // SetTime Limit For E-Mail Sending Process
  function tep_cfg_email_timelimit($value,$key='')
  {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$result=tep_draw_input_field($name,$value,'size=6 maxlength=5') . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
  // date offset popup to display hours offset
  function tep_cfg_pull_down_date_offset($value,$key='') {
    $offset=array(array('id'=>'0','text'=>TEXT_NO_OFFSET));
	for ($icnt=-23.5;$icnt<=23.5;$icnt=$icnt+0.5){
		$offset[]=array('id'=>$icnt,'text'=>sprintf("%+.1f",$icnt));
	}
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');

    $result= date("l dS of F Y h:i:s A") . '<br><br>'  . tep_draw_separator('pixel_trans.gif',20,1);
	$result.=tep_draw_pull_down_menu($name, $offset, $value) . '&nbsp;' . TEXT_OFFSET_HOURS . '&nbsp;';
	//$result.	=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  // to display time options
  /*function tep_cfg_pull_down_msg_times($value,$key='') {
    $times=array(array('id'=>'0','text'=>TEXT_NO_LIMIT));
	for ($icnt=1;$icnt<=23;$icnt++){
		$times[]=array('id'=>$icnt . ':00','text'=>$icnt . ':00');
	}
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
    $name1 = (($key) ? 'configuration1[' . $key . ']' : 'configuration_value1');
	$value_split=split(",",$value);
    $result = TEXT_MES_START . '&nbsp;';
	$result.=tep_draw_pull_down_menu($name, $times, (isset($value_split[0])?$value_split[0]:'')) . '&nbsp;<br><br>' . tep_draw_separator('pixel_trans.gif',20,1);
	$result.=TEXT_MES_END . '&nbsp;';
	$result.=tep_draw_pull_down_menu($name1, $times, (isset($value_split[1])?$value_split[1]:'')) . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }*/
  
  function tep_cfg_pull_down_msg_times($value,$key='') {
    $times=array(array('id'=>'0','text'=>TEXT_NO_LIMIT));
    if(!$value) $value='0,0';
	for ($icnt=1;$icnt<=23;$icnt++){
		$times[]=array('id'=>$icnt . ':00','text'=>$icnt . ':00');
	}
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
    $name1 = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$value_split=split(",",$value);
    $result = TEXT_MES_START . '&nbsp;';
	$result.=tep_draw_pull_down_menu($name, $times, (isset($value_split[0])?$value_split[0]:'')) . '&nbsp;<br><br>' . tep_draw_separator('pixel_trans.gif',20,1);
	$result.=TEXT_MES_END . '&nbsp;';
	$result.=tep_draw_pull_down_menu($name1, $times, (isset($value_split[1])?$value_split[1]:'')) . '&nbsp;';
	//$result.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
  // to set event view style normal,calendar
  function tep_cfg_pull_down_view_style($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$choices=array(array("id"=>"basic","text"=>"Basic"),array("id"=>"calendar","text"=>"calendar"),array("id"=>"view1","text"=>"View1"),array("id"=>"view2","text"=>"View2"),array("id"=>"view3","text"=>"View3"));
	$result.=tep_draw_pull_down_menu($name,$choices,strtolower($value)) . '&nbsp;';
	//$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
  // to set event view calendar style
  function tep_cfg_pull_down_calendar_style($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$choices=array(array("id"=>"day","text"=>"Day"),array("id"=>"week","text"=>"Week"),array("id"=>"month","text"=>"Month"));
	$lock_option="";
	
	$configuration_value_query=tep_db_query('select configuration_value from '.TABLE_CONFIGURATION." where configuration_key = 'EVENTS_VIEW_STYLE' ");
	$configuration_value_array=tep_db_fetch_array($configuration_value_query);
	if($configuration_value_array['configuration_value']!='calendar') $lock_option='disabled=true';
	
	//if (strtolower(EVENTS_VIEW_STYLE)!='calendar') $lock_option='disabled=true';
	$result.=tep_draw_pull_down_menu($name,$choices,strtolower($value),$lock_option)  . '&nbsp;';
	//$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }

  function tep_cfg_pull_down_event_display($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . '][]' : 'configuration_value[]');
  	$choices=array(array("id"=>"E","text"=>"Name"),array("id"=>"EL","text"=>"Name - Location"),
					array("id"=>"ET","text"=>"Name - Time"),array("id"=>"ELT","text"=>"Name - Time - Location"),
					);
	$result.=tep_draw_pull_down_menu($name,$choices,strtolower($value))  . '&nbsp;';
	$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
// get events name by passng event_id
  function tep_get_events_name($event_id, $language_id = 0) {
    global $languages_id;

    if ($language_id == 0) $language_id = $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_id . "'");
    $event = tep_db_fetch_array($event_query);
	
	

    return $event['events_name'];
  } 
  
  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;
 }
// get survey name by passng survey_id
  function tep_get_survey_name($survey_id, $language_id = 0) {

    $event_query = tep_db_query("select survey_name from " . TABLE_EVENTS_SURVEYS . " where survey_id = '" . (int)$survey_id . "'");
    $survey = tep_db_fetch_array($event_query);

    return $survey['survey_name'];
  }  

// get location name by passing location_id
  function tep_get_locations_name($location_id) {
    $location_query = tep_db_query("select location_name from " . TABLE_EVENTS_LOCATIONS . " where location_id = '" . (int)$location_id . "'");
    $location = tep_db_fetch_array($location_query);

    return $location['location_name'];
  }  
// get events description by passing event_id
 function tep_get_events_description($event_id, $language_id=0) {
    $event_query = tep_db_query("select events_description from " . TABLE_EVENTS_DESCRIPTION . " where events_id = '" . (int)$event_id . "' and language_id = '" . (int)$language_id . "'");
    $event = tep_db_fetch_array($event_query);

    return $event['events_description'];
  }

// get sessions description by passing session_id
 function tep_get_sessions_description($session_id, $language_id=0) {
    $session_query = tep_db_query("select sessions_description from " . TABLE_EVENTS_SESSIONS_DESCRIPTION . " where sessions_id = '" . (int)$session_id . "' and language_id = '" . (int)$language_id . "'");
    $session = tep_db_fetch_array($session_query);

    return $session['sessions_description'];
  }

 // get events url by passing event_id
 function tep_get_events_url($event_id, $language_id=0) {
    $event_query = tep_db_query("select events_url from " . TABLE_EVENTS_DESCRIPTION . " where events_id = '" . (int)$event_id . "' and language_id = '" . (int)$language_id . "'");
    $event = tep_db_fetch_array($event_query);

    return $event['events_url'];
  }



 // set event status by passing events_id
  function tep_set_event_status($events_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_EVENTS . " set events_status = 1, events_last_modified = now() where events_id = '" . (int)$events_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_EVENTS . " set events_status = 0, events_last_modified = now() where events_id = '" . (int)$events_id . "'");
    } else {
      return -1;
    }
  }
 // set status by passing subscription_id
  function tep_set_subscription_status($subscription_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_SUBSCRIPTIONS . " set subscription_status = 1, subscription_last_modified = now() where subscription_id = '" . (int)$subscription_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_SUBSCRIPTIONS . " set subscription_status = 0, subscription_last_modified = now() where subscription_id = '" . (int)$subscription_id . "'");
    } else {
      return -1;
    }
  }   
 //set session status by passing session_id
 function tep_set_session_status($session_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_EVENTS_SESSIONS . " set sessions_status = '1', sessions_last_modified = now() where sessions_id = '" . (int)$session_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_EVENTS_SESSIONS . " set sessions_status = '0', sessions_last_modified = now() where sessions_id = '" . (int)$session_id . "'");
    } else {
      return -1;
    }
  }    
 
 
 // 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;
}
 // remove event from database
 function tep_remove_event($event_id) {
 	// fetch image name 
    $event_image_query = tep_db_query("select events_image from " . TABLE_EVENTS . " where events_id = '" . (int)$event_id . "'");
    $event_image = tep_db_fetch_array($event_image_query);

    $duplicate_image_query = tep_db_query("select count(*) as total from " . TABLE_EVENTS . " where events_image = '" . tep_db_input($event_image['events_image']) . "'");
    $duplicate_image = tep_db_fetch_array($duplicate_image_query);

	// delete if there is only one reference for this image
    if ($duplicate_image['total'] < 2) {
      if (file_exists(DIR_FS_CATALOG_IMAGES . $event_image['events_image'])) {
        @unlink(DIR_FS_CATALOG_IMAGES . $event_image['events_image']);
      }
    }
	$event_id=(int)$event_id;
	// delete from events,events_description,events_to_events table
    tep_db_query("delete from " . TABLE_EVENTS . " where events_id = '" . (int)$event_id . "'");
    tep_db_query("delete from " . TABLE_EVENTS_DESCRIPTION . " where events_id = '" . (int)$event_id . "'");
    tep_db_query("delete from " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " where events_id = '" . (int)$event_id . "'");	
	tep_db_query("delete from " . TABLE_EVENTS_MESSAGES . " where events_id='" . (int)$events_id . "'");
	tep_db_query("delete from " . TABLE_EVENTS_SMS_MESSAGES . " where events_id='" . (int)$events_id . "'");
	//delete corresponding sessions;
	tep_db_query("delete from " . TABLE_EVENTS_SESSIONS . " where events_id='" . (int)$event_id . "'");
	tep_db_query("delete from " . TABLE_RECURSIVE_SESSIONS . " where events_id='" . (int)$event_id . "'");
/*	$service_query=tep_db_query("select count(*) from ".TABLE_EVENTS ." where events_id='".(int)$events_id."'");
	if(tep_db_num_rows($service_query)<=0){
		tep_db_query("delete from " . TABLE_EVENTS_TO_SERVICES . " where events_id='" . (int)$events_id ."'");
	}*/
	
	$survey_query=tep_db_query("SELECT survey_id from " . TABLE_EVENTS_SURVEYS . " where events_id='" . $event_id . "'");
	while($survey_result=tep_db_fetch_array($survey_query)){
		tep_delete_survey($survey_result["survey_id"]);
	}
 
  }  
  

  // function remove a survey by passing survey_id
	function tep_delete_survey($delete_id){
		$delete_id=(int)$delete_id;
		$question_query=tep_db_query("SELECT question_id from " . TABLE_EVENTS_SURVEYS_QUESTION . " where survey_id='" . $delete_id . "'");
		$question_ids='';
		while($question_result=tep_db_fetch_array($question_query)){
			if ($question_ids!='') $question_ids .= ',';
			$question_ids .= "'" . $question_result['question_id'] . "'";
		}
		if ($question_ids!=''){
			tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS_CHOICE . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS_QUESTION . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS_ANSWER . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS_TEXT . " where question_id in(" . $question_ids . ")");
		}
		tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS . " where survey_id='" . $delete_id . "'");
		tep_db_query("DELETE from " . TABLE_EVENTS_SURVEYS_FLAG . " where survey_id='" . $delete_id . "'");
	}
// remove a session from by passing the session_id	
 function tep_remove_session($session_id) {

    tep_db_query("delete from " . TABLE_EVENTS_SESSIONS . " where sessions_id = '" . (int)$session_id . "'");
  
  }    
// build url parameter by passing eventid and session_id
  function tep_build_session_parameter($eventid,$sessionid)
  {
     $field=(isset($eventid)?'&eID=' .$eventid:'');
	 $field=$field . (isset($sessionid)?'&sID=' .$sessionid:'');
	 return $field;
  } 
// get events_path url parameter by passing current events_category_id  
  function tep_get_events_path($current_events_category_id = '') {
    global $ecPath_array;

    if ($current_events_category_id == '') {
      $ecPath_new = implode('_', $ecPath_array);
    } else {
      if (sizeof($ecPath_array) == 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[(sizeof($ecPath_array)-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, $n = sizeof($ecPath_array) - 1; $i < $n; $i++) {
            $ecPath_new .= '_' . $ecPath_array[$i];
          }
        } else {
          for ($i = 0, $n = sizeof($ecPath_array); $i < $n; $i++) {
            $ecPath_new .= '_' . $ecPath_array[$i];
          }
        }

        $ecPath_new .= '_' . $current_events_category_id;

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

    return 'ecPath=' . $ecPath_new;
  } 
	// get events category name by passing category_id and language_id
  function tep_get_events_category_name($events_category_id, $language_id) {
    $events_category_query = tep_db_query("select events_categories_name from " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " where events_categories_id = '" . (int)$events_category_id . "' and language_id = '" . (int)$language_id . "'");
    $events_category = tep_db_fetch_array($events_category_query);

    return $events_category['events_categories_name'];
  }

  // get total events count by navigating nested category
  function tep_events_in_events_category_count($events_categories_id, $include_deactivated = false) {
    $events_products_count = 0;

    if ($include_deactivated) {
      $events_products_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_categories_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_categories_id . "'");
    }

    $events = tep_db_fetch_array($events_query);

    $events_count += $events['total'];

    $childs_query = tep_db_query("select events_categories_id from " . TABLE_EVENTS_CATEGORIES . " where parent_id = '" . (int)$events_categories_id . "'");
    if (tep_db_num_rows($childs_query)) {
      while ($childs = tep_db_fetch_array($childs_query)) {
        $events_count += tep_events_in_events_category_count($childs['events_categories_id'], $include_deactivated);
      }
    }

    return $events_count;
  }

  // find total no of child events in a selected category
  function tep_childs_in_events_category_count($events_categories_id) {
    $events_categories_count = 0;

    $events_categories_query = tep_db_query("select events_categories_id from " . TABLE_EVENTS_CATEGORIES . " where parent_id = '" . (int)$events_categories_id . "'");
    while ($events_categories = tep_db_fetch_array($events_categories_query)) {
      $events_categories_count++;
      $events_categories_count += tep_childs_in_events_category_count($events_categories['events_categories_id']);
    }

    return $events_categories_count;
  }
	function tep_sessions_on_events_count($event_id){
		$check_sql = "select count(*) as count from " . TABLE_EVENTS_SESSIONS . " where events_id=" . $event_id;
		$check_query = tep_db_query($check_sql);
		$check_result = tep_db_fetch_array($check_query);
		return $check_result['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 events category path from the current category
  function tep_output_generated_events_category_path($id, $from = 'events_category') {
    $calculated_events_category_path_string = '';
    $calculated_events_category_path = tep_generate_events_category_path($id, $from);
    for ($i=0, $n=sizeof($calculated_events_category_path); $i<$n; $i++) {
      for ($j=0, $k=sizeof($calculated_events_category_path[$i]); $j<$k; $j++) {
        $calculated_events_category_path_string .= $calculated_events_category_path[$i][$j]['text'] . '&nbsp;&gt;&nbsp;';
      }
      $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -16) . '<br>';
    }
    $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -4);

    if (strlen($calculated_events_category_path_string) < 1) $calculated_events_category_path_string = TEXT_TOP;

    return $calculated_events_category_path_string;
  }
  // generate events category path to the current category
  function tep_output_rev_generated_events_category_path($id, $from = 'events_category') {
    $calculated_events_category_path_string = '';
    $calculated_events_category_path = tep_generate_events_category_path($id, $from);
    for ($i=0, $n=sizeof($calculated_events_category_path); $i<$n; $i++) {
      for ($j=0, $k=sizeof($calculated_events_category_path[$i]); $j<$k; $j++) {
        $calculated_events_category_path_string = $calculated_events_category_path[$i][$j]['text'] . '&nbsp;&gt;&nbsp;' . $calculated_events_category_path_string;
      }
      $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -16) . '<br>';
    }
    $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -4);

    if (strlen($calculated_events_category_path_string) < 1) $calculated_events_category_path_string = '';

    return $calculated_events_category_path_string;
  }

  // get the events category path by passing currenct directory
  function tep_get_generated_events_category_path_ids($id, $from = 'events_category') {
    $calculated_events_category_path_string = '';
    $calculated_events_category_path = tep_generate_events_category_path($id, $from);
    for ($i=0, $n=sizeof($calculated_events_category_path); $i<$n; $i++) {
      for ($j=0, $k=sizeof($calculated_events_category_path[$i]); $j<$k; $j++) {
        $calculated_events_category_path_string .= $calculated_events_category_path[$i][$j]['id'] . '_';
      }
      $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -1) . '<br>';
    }
    $calculated_events_category_path_string = substr($calculated_events_category_path_string, 0, -4);

    if (strlen($calculated_events_category_path_string) < 1) $calculated_events_category_path_string = TEXT_TOP;

    return $calculated_events_category_path_string;
  }

  // remove the selected events category
  function tep_remove_events_category($events_category_id) {
    $category_image_query = tep_db_query("select events_categories_image from " . TABLE_EVENTS_CATEGORIES . " where events_categories_id = '" . (int)$events_category_id . "'");
    $category_image = tep_db_fetch_array($category_image_query);

    $duplicate_image_query = tep_db_query("select count(*) as total from " . TABLE_EVENTS_CATEGORIES . " where events_categories_image = '" . tep_db_input($events_category_image['events_categories_image']) . "'");
    $duplicate_image = tep_db_fetch_array($duplicate_image_query);

    if ($duplicate_image['total'] < 2) {
      if (file_exists(DIR_FS_CATALOG_IMAGES . $category_image['events_categories_image'])) {
        @unlink(DIR_FS_CATALOG_IMAGES . $category_image['events_categories_image']);
      }
    }

    tep_db_query("delete from " . TABLE_EVENTS_CATEGORIES . " where events_categories_id = '" . (int)$events_category_id . "'");
    tep_db_query("delete from " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " where events_categories_id = '" . (int)$events_category_id . "'");
    tep_db_query("delete from " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " where events_categories_id = '" . (int)$events_category_id . "'");


  }
  // form the generated events category tree
	function tep_get_events_category_tree($parent_id = '0', $spacing = '', $exclude = '', $events_category_tree_array = '', $include_itself = false) {
		global $languages_id;
		
		if (!is_array($events_category_tree_array)) $events_category_tree_array = array();
		if ( (sizeof($events_category_tree_array) < 1) && ($exclude != '0') ) $events_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);
		if ($include_itself) {
			$events_category_query = tep_db_query("select ecd.events_categories_name from " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ecd.language_id = '" . (int)$languages_id . "' and ecd.events_categories_id = '" . (int)$parent_id . "'");
			$events_category = tep_db_fetch_array($events_category_query);
			$events_category_tree_array[] = array('id' => $parent_id, 'text' => $events_category['events_categories_name']);
		}
		$events_categories_query = tep_db_query("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 . "' order by ec.sort_order, ecd.events_categories_name");
		while ($events_categories = tep_db_fetch_array($events_categories_query)) {
			if ($exclude != $events_categories['events_categories_id']) {
				$events_category_tree_array[] = array('id' => $events_categories['events_categories_id'], 'text' => $spacing . $events_categories['events_categories_name']);
			}
			$events_category_tree_array = tep_get_events_category_tree($events_categories['events_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $events_category_tree_array);
		}
		return $events_category_tree_array;
	}
  // get events category path
  function tep_generate_events_category_path($id, $from = 'events_category', $events_categories_array = '', $index = 0) {
    global $languages_id;

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

    if ($from == 'event') {
      $events_categories_query = tep_db_query("select events_categories_id from " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " where events_id = '" . (int)$id . "'");
      while ($events_categories = tep_db_fetch_array($events_categories_query)) {
        if ($events_categories['events_categories_id'] == '0') {
          $events_categories_array[$index][] = array('id' => '0', 'text' => TEXT_TOP);
        } else {
          $events_category_query = tep_db_query("select ecd.events_categories_name, ec.parent_id from " . TABLE_EVENTS_CATEGORIES . " ec, " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ec.events_categories_id = '" . (int)$events_categories['events_categories_id'] . "' and ec.events_categories_id = ecd.events_categories_id and ecd.language_id = '" . (int)$languages_id . "'");
          $events_category = tep_db_fetch_array($events_category_query);
          $events_categories_array[$index][] = array('id' => $events_categories['events_categories_id'], 'text' => $events_category['events_categories_name']);
          if ( (tep_not_null($events_category['parent_id'])) && ($events_category['parent_id'] != '0') ) $events_categories_array = tep_generate_events_category_path($events_category['parent_id'], 'events_category', $events_categories_array, $index);
          $events_categories_array[$index] = array_reverse($events_categories_array[$index]);
        }
        $index++;
      }
    } elseif ($from == 'events_category') {
      $events_category_query = tep_db_query("select ecd.events_categories_name, ec.parent_id from " . TABLE_EVENTS_CATEGORIES . " ec, " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ec.events_categories_id = '" . (int)$id . "' and ec.events_categories_id = ecd.events_categories_id and ecd.language_id = '" . (int)$languages_id . "'");
      $events_category = tep_db_fetch_array($events_category_query);
      $events_categories_array[$index][] = array('id' => $id, 'text' => $events_category['events_categories_name']);
      if ( (tep_not_null($events_category['parent_id'])) && ($events_category['parent_id'] != '0') ) $events_categories_array = tep_generate_events_category_path($events_category['parent_id'], 'events_category', $events_categories_array, $index++);
    }
    return $events_categories_array;
  }
  //draw the date elements
  function tep_draw_combo_select($types,$selectname,$valueselect)
  {
    $result='';
    if ($types=='weeks') 
	{
      $element=array('1'=>'first','2'=>'second','3'=>'third','4'=>'fourth');
	}
	elseif ($types=='months')
	{
	  $element=array('1'=>'January','2'=>'February','3'=>'March','4'=>'April',
				  '5'=>'May','6'=>'June','7'=>'July','8'=>'August','9'=>'September',
				  '10'=>'October','11'=>'November','12'=>'December');
	}
	else{
	  $element=array('1'=>'Monday','2'=>'Tuesday','3'=>'Wednesday','4'=>'Thursday',
	                 '5'=>'Friday','6'=>'Saturday','7'=>'Sunday');}
	$result='<select name="'. $selectname . '" id="' . $selectname . '" ';
	$result.=' class="inputNormal" onBlur="javascript:toggle_focus(this,1);" onFocus="javascript:toggle_focus(this,2);"';
	$result.='>';
	for($icnt=1,$n=sizeof($element);$icnt<=$n;$icnt++)
	{
	   $result=$result . '<option value="' . ($icnt) . '"';
	   if ($icnt==$valueselect) $result=$result . ' selected';
	   $result=$result . '>' . $element[$icnt] . '</option>';
	}
	$result=$result . '</select>';
	return $result;
  }

  // get the instructor name by passing admin_id
  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 instructor e-mail address by passing admin_id
  function tep_get_instructor_email($id) {
    $instructor_query = tep_db_query("select admin_email_address from " . TABLE_ADMIN . " where admin_id='" . (int)$id  . "'");
    if ($instructor=tep_db_fetch_array($instructor_query))
        return $instructor['admin_email_address'];
  }

  // get the answer type for the given question
  function tep_get_popquestion_type($id) {
    $popquestion_query = tep_db_query("select answer_type from " . TABLE_POP_QUESTIONS . " where question_id='" . (int)$id  . "'");
    if ($popquestion=tep_db_fetch_array($popquestion_query))
        return $popquestion['answer_type'];
  }
  
  // to get the given array of params from $HTTP_GET_VARS
  function tep_all_get_params($include_array = '') {
    global $HTTP_GET_VARS;

    if ($include_array == '') $include_array = array();

    $get_url = '';

    reset($HTTP_GET_VARS);
    while (list($key, $value) = each($HTTP_GET_VARS)) {
      if (($key != tep_session_name()) && ($key != 'error') && (in_array($key, $include_array))) $get_url .= $key . '=' . $value . '&';
    }

    return $get_url;
  }

 // get the session type by passing session_id
 function tep_get_session_type($event_id)
 {
    $check_query=tep_db_query("select count(*) as total from " . TABLE_RECURSIVE_SESSIONS . " where events_id='" . (int)$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='S'");
    if ($check_result=tep_db_fetch_array($check_query)){
    if ((int)$check_result['total']>0)
      return 'S';
      }
    }
    return '';
 }
 // get the session date by passing sessions_id
 function tep_get_session_date($sessions_id)
 {
    $check_query=tep_db_query("select start_date from " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . (int)$sessions_id . "'");
    if ($check_result=tep_db_fetch_array($check_query)){
      return $check_result['start_date'];
    }
 }

 // get total records by passing table name and condition
 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;
 }
 
 // select values by passing tablename,fields and condition
 function tep_get_value($table,$fields,$condition)
 {
   $value_query=tep_db_query("select " . $fields . " from " . $table . " where " . $condition);
   if ($value_result=tep_db_fetch_array($value_query))
      return $value_result;
   return array();      
 }
 
 /*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;
	}*/ 
	// Output a form pull down menu
	/*function tep_draw_event_select_menu($name, $values, $default = '', $parameters = '', $required = false) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		$field .= '<option style="color:#000000" value="-1">' . TEXT_ALL_EVENTS . '</option>';
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		
		$content="";
		tep_get_events_output_tree(0,$content,$default);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}*/
	
	
  // get the list of events as an array
  function tep_get_events_array($first=''){
  	global $login_id,$login_groups_type,$languages_id;
    $event_array=array();
	$login_option="";
	if ($login_groups_type==TEXT_INSTRUCTOR_ENTRY){
		$login_option=" and e.events_instructor=" . $login_id;
	}
    if ($first!='')
       $event_array[]=array('id'=>-2,'text'=>$first);
    $event_query=tep_db_query("SELECT e.events_id,ed.events_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . " ed where 1=1 " . $login_option . " and e.events_id=ed.events_id and ed.language_id='" . $languages_id . "'" . EVENTS_CONDITION_STATUS . "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;
 } 

 // get the list of events with given amount
  function tep_get_price_events_array($amount=0){
    $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 e.events_fees='" . $amount . "' 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;
 }
 
 // find a session has some records in orders products table
 function tep_check_linked_reservation($session_id)
 {
    $check_query=tep_db_query("select count(*) as total from " . TABLE_ORDERS_PRODUCTS . " where products_id='" . $session_id . "' and products_type='E' and (events_type='W' or events_type='R') and orders_products_status!=5");
    if ($result=tep_db_fetch_array($check_query)){
     if (((int)$result['total'])>0) return true;
    }
    return false;
 }
// check if a single reservation exists for the given session_id
 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;
 }
 
 // find total of sessions in an event
 function tep_sessions_in_events_count($events_id) {
    $sessions_count=0;

    $events_sessions_query = tep_db_query("select count(*) as total from " . TABLE_EVENTS_SESSIONS . " e where events_id = '" . (int)$events_id . "'");

    $sessions = tep_db_fetch_array($events_sessions_query);

    $sessions_count=(int)$sessions['total'];

    return $sessions_count;
  } 
  

 //to display text for admin_files permission
 function tep_get_help_text($help_id){
   if ($help_id=='E')
      return TEXT_INFO_EVENTS;
   else if ($help_id=='S')
      return TEXT_INFO_SESSIONS;
   else if ($help_id=='R')
      return TEXT_INFO_RESERVATIONS;
   else if ($help_id=='I')
      return TEXT_INFO_INSTRUCTORS;
   else if ($help_id=='T')
      return TEXT_INFO_REPORTS;
   else if ($help_id=='M')
      return TEXT_INFO_MESSAGES;
   else if ($help_id=='O')
      return TEXT_INFO_EVENT_ORDERS;
   else if ($help_id=='U')
      return TEXT_INFO_SURVEYS;
 }

// send event email by passing session_id and mail_type
function tep_send_event_email($process_id,$mail_type){
	global $currencies;
	
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;

	if ($process_id=="" || $mail_type=='') return;
		
	// get the details from order table
	/*$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,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,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method," .
								"o.customers_state,o.customers_country from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " c, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e " .
								"where op.orders_products_id in('" . $process_id . "') and op.orders_id=o.orders_id and o.customers_id=c.customers_id and op.products_id=s.sessions_id and s.events_id=e.events_id limit 1"); */
	
	$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,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,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method," .
								"o.customers_state,o.customers_country from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " c, ". TABLE_CUSTOMERS_TO_CUSTOMERS ." c2c," . TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e " .
								"where o.customers_id=c2c.group_customer_id and c2c.customer_id=c.customers_id and c2c.orders_id=o.orders_id and op.orders_products_id in('" . $process_id . "') 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");							
							
	if (tep_db_num_rows($process_query)<=0) return;

	// get the session details from orders products
	$date_query=tep_db_query("SELECT op.final_price,op.products_id,s.start_date,op.products_tax,op.products_name from " . 
							   TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s where op.orders_products_id in('" . $process_id . "') and op.products_type='E' and op.products_id=s.sessions_id and op.orders_products_status!=5 order by s.start_date");
	

	if (tep_db_num_rows($date_query)<=0) return;
	
	while($process_result=tep_db_fetch_array($process_query)){
	
	$details=array();
	$details['type']=$mail_type;
	$details['table']=TABLE_EVENTS_MESSAGES;
	$details['events_id']=$process_result['events_id'];

	// get the mail template details
	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']);

	$starting_date='';
	$total=0;
	$subtotal=0;
	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'],$process_result['events_start_time'],$process_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;

	// form the merge fields
	$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_RE=>format_date($renewal_end),
							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($start_date),
							TEXT_IV=>'<a href="' . tep_catalog_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_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $process_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_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_catalog_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_catalog_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_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $process_result['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=>$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_DD=>'',
							TEXT_TX=>$currencies->format($tax),
							TEXT_SB=>$currencies->format($subtotal),
							TEXT_TL=>$currencies->format($total),
						);
	
	//replace the template with merge details
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);

	$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()'
					);

	// get the address to send
   $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;
	// send email to destination address
	if (tep_send_email($details)){
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
	}
	
	// check mail type for waitlist promotion
	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'];
		tep_send_email($details);
	}
	
	// check mail type for withdraw reservation
	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'];
	   tep_send_email($details);
	}

    // send sms if mobile no exists
    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 mail to customer by collecting all 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;

	// get the mail template
	$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 . "'";

	// get the customer details
	/*$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");*/
	$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,".TABLE_CUSTOMERS_TO_CUSTOMERS." c2c where o.customers_id=c2c.group_customer_id and c2c.customer_id=c.customers_id  and c2c.orders_id=o.orders_id and  o.orders_id=" . $orders_id);							
	 
	if (tep_db_num_rows($customer_query)<=0) return;

	while($customer_result=tep_db_fetch_array($customer_query)){
	
	// get the 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_tax_class_id,e.events_fees 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 . "' and op.orders_products_status!=5 order by s.start_date");

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

	// 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;

	// form the merge fields
	$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_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $events_id,'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $customer_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_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_catalog_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_catalog_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_catalog_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_DD=>'',
							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;

	// send email to customer
	if (tep_send_email($details)){
		tep_db_perform(TABLE_EVENTS_MESSAGES_HISTORY,$sql_array);
	}

	// send sms if mobile no exists
	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 friend email address
function tep_send_invite_email($send_details){
  global $currencies;
  
	//if ((int)EMAIL_ACTIVATE!=1) return;
	
  if (is_array($send_details)==false)
     return;

	// get 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 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 order by s.start_date limit 1");


   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']);

	// get 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);

	// get the mail template
   $mail_data_query=tep_db_query("SELECT * from " . TABLE_EVENTS_MESSAGES . " where message_type='" . $send_details['mail_type'] . "' and events_id='" . $send_details['events_id'] . "'");

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

   $mail_data_result=tep_db_fetch_array($mail_data_query);
   $send_details['address']=str_replace(';',',',$send_details['address']);
   $send_details['names']=str_replace(';',',',$send_details['names']);
   
   $email_array=explode(",",$send_details['address']);
   $name_array=explode(",",$send_details['names']);

   $events_location=tep_get_locations_name($event_result['events_location']);
   
   // form the merge fields
   $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_IC=>$send_details['comments'],
			 TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>');

   $mes_content=$mail_data_result['message_text'];

   while (list($key, $value) = each($replace_array))
      $mes_content=eregi_replace("%%" . $key  . "%%",$value,$mes_content);

 	// send email to selected email address  
   for ($icnt=0;$icnt<sizeof($email_array);$icnt++){
    $mes_text=str_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]!=''){
       $message = new email(array('X-Mailer: osCommerce'));

		// send using format html or plain text 
       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'], $mail_data_result['message_subject']);
    }
  }
} 

// function to replace the content for the selected template
function tep_replace_event_email($process_id,$mail_type,$mail_content=''){
  global $currencies;
  if ((int)$process_id<=0 || $mail_type=='')
     return;
	
	// get the customer details
  $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,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method 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 . "' and op.orders_products_status!=5");

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

   $process_result=tep_db_fetch_array($process_query);

	
   if ($mail_content==''){
      $mail_data_query=tep_db_query("SELECT * from " . TABLE_EVENTS_MESSAGES . " where message_type='" . $mail_type . "' and events_id='" . $process_result['events_id'] . "'");
      if (tep_db_num_rows($mail_data_query)<=0) return;
      $mail_data_result=tep_db_fetch_array($mail_data_query);
      $mail_content=$mail_data_result['message_text'];
   }

// 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"];

	// form the merge fields
   $events_location=$process_result['events_location'];
   $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_IV=>'<a href="' . tep_catalog_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_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $process_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
			 TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
			 TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
			 TEXT_RV=>'<a href="' . tep_catalog_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_catalog_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_catalog_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_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $process_result['orders_id'],'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
			 
			 TEXT_EN=>$process_result['products_name'],
                         TEXT_SI=>$process_result['events_start_time'],
			 TEXT_EF=>$currencies->format(tep_add_tax($process_result['final_price'],$process_result['products_tax'])),
                         TEXT_EI=>$process_result['events_end_time'],
                         TEXT_IN=>tep_get_instructor_name($process_result['events_instructor']),
                         TEXT_EL=>$events_location,
                         TEXT_SD=>format_date($process_result['start_date']),
			 TEXT_RE=>format_date($renewal_end),
			 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_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_DD=>'',
                         TEXT_TX=>$currencies->format($process_result['products_tax']),
			 TEXT_SB=>$currencies->format($process_result['final_price']),
			 TEXT_TL=>$currencies->format(tep_add_tax($process_result['final_price'],$process_result['products_tax'])));

   

   while (list($key, $value) = each($replace_array))
      $mail_content=eregi_replace("%%" . $key  . "%%",$value,$mail_content);
   return $mail_content;
}

// to add specified interval to a given date

function tep_dateadd($timestamp, $unit, $amount) { 
  if($amount<0) $amount=1;
  // Possible $units are: "hr", "min", "sec",
  // "mon", "day", or "yr"
  // $amount should be an integer
   	  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;
}

//to add specified interval to a given time
function tep_timeadd($timestamp, $unit, $amount) {
if($amount<0) $amount=1;
// Possible $units are: "hr", "min", "sec",
//          "mon", "day", or "yr"
// $amount should be an integer

	if ($amount==0) return $timestamp;
   $delta_vars = array("hr"=>0, "min"=>0,
   "sec"=>0, "mon"=>1,
   "day"=>1,"yr"=>1);

   $delta_vars[$unit] += $amount;

   $delta = gmmktime($delta_vars["hr"],
   $delta_vars["min"],
   $delta_vars["sec"],
   $delta_vars["mon"],
   $delta_vars["day"],
   $delta_vars["yr"]);
   return $timestamp + $delta;
}
// subtract specified interval to a given date
function tep_datesub($timestamp, $unit, $amount) {
	if($amount<=0) $amount=1;
// Possible $units are: "hr", "min", "sec",
//          "mon", "day", or "yr"
// $amount should be an integer
		$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;
} 
// form the tree of catgories and events for customized list box to select event
function tep_get_events_display_tree($parent_id = '0', $spacing = '', $exclude = '', $events_category_tree_array = '', $include_itself = false) {
    global $languages_id;

    if (!is_array($events_category_tree_array)) $events_category_tree_array = array();
    if ( (sizeof($events_category_tree_array) < 1) && ($exclude != '0') ) $events_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);

	// if the current category is to be included
    if ($include_itself) {
      $events_category_query = tep_db_query("select ecd.events_categories_name from " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ecd.language_id = '" . (int)$languages_id . "' and ecd.events_categories_id = '" . (int)$parent_id . "'");
      $events_category = tep_db_fetch_array($category_query);
      $events_category_tree_array[] = array('id' => $parent_id, 'text' => $events_category['events_categories_name']);
      

           
    }
	// recursively form the tree
    $events_categories_query = tep_db_query("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 . "' order by ec.sort_order, ecd.events_categories_name");
    while ($events_categories = tep_db_fetch_array($events_categories_query)) {
      if ($exclude != $events_categories['events_categories_id']) $events_category_tree_array[] = array('id' => $events_categories['events_categories_id'], 'text' => $spacing . $events_categories['events_categories_name']);
      $events_category_tree_array = tep_get_events_display_tree($events_categories['events_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $events_category_tree_array);
    }

	// select the events for the current 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='" . (int)$parent_id . "' 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))
    {
        $events_category_tree_array[] = array('id' => $events['events_id'], 'text' => $spacing . $events['events_name']);
    }    
    return $events_category_tree_array;
}
// form the tree of catgories and events for customized list box to select event (only for the page addevents)
	function tep_get_events_info_tree($customer_id,$parent_id = '0', $spacing = '', $exclude = '', $events_category_tree_array = '', $include_itself = false) {
		global $languages_id,$currencies;
		
		if (!is_array($events_category_tree_array)) $events_category_tree_array = array();
		if ( (sizeof($events_category_tree_array) < 1) && ($exclude != '0') ) $events_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);
		
		// if the category is to be included
		if ($include_itself) {
			$events_category_query = tep_db_query("select ecd.events_categories_name from " . TABLE_EVENTS_CATEGORIES_DESCRIPTION . " ecd where ecd.language_id = '" . (int)$languages_id . "' and ecd.events_categories_id = '" . (int)$parent_id . "'");
			$events_category = tep_db_fetch_array($category_query);
			$events_category_tree_array[] = array('id' => $parent_id, 'text' => $events_category['events_categories_name'],'mode'=>'C');
		}
		// recursively select the category
		$events_categories_query = tep_db_query("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 . "' order by ec.sort_order, ecd.events_categories_name");
		while ($events_categories = tep_db_fetch_array($events_categories_query)) {
			if ($exclude != $events_categories['events_categories_id']) $events_category_tree_array[] = array('id' => $events_categories['events_categories_id'], 'text' => $spacing . $events_categories['events_categories_name']);
			$events_category_tree_array = tep_get_events_info_tree($customer_id,$events_categories['events_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $events_category_tree_array);
		}
		
		// select the events
		$events_query=tep_db_query("select ed.events_name,e.events_location,e.events_start_time,ed.events_id,e.events_fees,e.events_tax_class_id,e.events_max_reserve,e.events_overbook_reserve,e.waitsize_vip,e.waitsize_firstcome,e.waitsize_custom,e.priority_question,e.events_wait_list,e.events_forward_period,e.events_forward_length,e.events_pending_period,e.events_renewal_start,e.events_renewal_end from " . TABLE_EVENTS . ' e, ' . TABLE_EVENTS_DESCRIPTION . " ed, " . TABLE_EVENTS_TO_EVENTS_CATEGORIES . " ecd where ecd.events_categories_id='" . (int)$parent_id . "' and ecd.events_categories_id>0 and e.events_id=ecd.events_id and e.events_id=ed.events_id  " . EVENTS_CONDITION_STATUS . " and ed.language_id = " . $languages_id . " order by ed.events_name");
		while ($events=tep_db_fetch_array($events_query))
		{
			$events_name=$events["events_name"];

		
			$tax=tep_get_tax_rate($events["events_tax_class_id"]);
			$price=$currencies->display_price($events["events_fees"],$tax);
			$status=&get_event_reserve_status($events,$customer_id);
			$start_date='';
			$discount_info="";
			if ($status['date']!='') {
				$start_date="(" . format_date($status["date"]) . ")&nbsp;";
			}
			if ($status['date']!='' && $status['type']=='R'){
				// get the discount details
				$discount_query=tep_db_query("SELECT discount_value,discount_type,discount_start_date,discount_end_date from " . TABLE_EVENTS_DISCOUNTS . " where events_id='" . $events["events_id"] . "' order by discount_start_date");
				while($discount_result=tep_db_fetch_array($discount_query)){
					// check the session date to come within the range and calculate the fees
					if ($status['date']>=$discount_result["discount_start_date"] && $status['date']<=$discount_result["discount_end_date"]){
						$events_fees=tep_add_tax($events["events_fees"],$tax);
						if ($discount_result["discount_type"]=='P'){
							$discount_amount=$currencies->format($events_fees-($events_fees*$discount_result["discount_value"]/100));
						} else {
							$discount_amount=$currencies->format($events_fees-$discount_result["discount_value"]);
						}
						$discount_info='<font color="#3300FF">' . $discount_amount . '<font>';
						break;
					}
				}
			}
			if ($status['type']=='R')
				$color="#000000";
			else if ($status['type']=='W')
				$color="#FFA715";			
			else 
				$color="#FF0000";
	
			// form the array with events_name,color,price,start_date
			$events_category_tree_array[] = array('id' => $events['events_id'], 'text' => $spacing . $events_name . '&nbsp;<font color=' . $color . '>' . $price . '</font>&nbsp;&nbsp;&nbsp;' . $start_date . $discount_info,'mode'=>'E');
		} 
		
		return $events_category_tree_array;
	}
	// to find whether the event has reserve seats to fill or waitlist seats to fill
	function &get_event_reserve_status($events,$customer_id){
		$status_list=array('type'=>'E','date'=>'');
		$find_list=array('R','W');
		// iterate for two times to find the result start with empty
		$status='E';
		for ($icnt=0;$icnt<=1;$icnt++){
			// if the type is waitlist check for presence of waitling list in the event
			if ($find_list[$icnt]=='W' && $events['events_wait_list']!='Y') break;
			//add option if forward reservation period has been set
			if ($events['events_forward_period']=='Y'){
				$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$events['events_forward_length']));
				$check_data=" and s.start_date<='" . $check_date . "' ";
			}
			// get the sessions count if present in reservation table
			//$reserve_query=tep_db_query("SELECT count(op.products_id) as total,s.start_date from "  . TABLE_EVENTS_SESSIONS . " s left join " . TABLE_ORDERS_PRODUCTS . " op on s.sessions_id=op.products_id and op.products_type='E' and op.events_type='" . $find_list[$icnt] . "' where s.events_id='" . $events['events_id']. "' and s.start_date>curdate() " . $check_data . " and s.sessions_type!='' group by s.sessions_id");
			$session_query=tep_db_query("SELECT s.sessions_id ,s.start_date from "  . TABLE_EVENTS_SESSIONS . " s where s.events_id='" . $events['events_id']. "' and s.start_date>'" . getServerDate(true) . "' " . $check_data . " and s.sessions_type!='' order by s.start_date");
			while($session_result=tep_db_fetch_array($session_query)){
				if (tep_check_session_free($session_result,$events,$find_list[$icnt],$customer_id)==true){
					$status_list['type']=$find_list[$icnt];
					$status_list['date']=$session_result['start_date'];
					$status=$find_list[$icnt];
					break;
				}
			}
			if ($status!='E') break;
		}
		return $status_list;
	}
	//get the session_free_status if needed by passing session,events,type and customer_id
	function tep_check_session_free(&$session,&$events,$type,$customer_id=0,$override=false,$overbook=false,$customers=1){
		global $lock_date;		
		if ($type=='R')
			$reserve_count=tep_reserve_count($session["sessions_id"],$events);
		else
			$reserve_count=tep_waitlist_count($session["sessions_id"],$events,$customer_id);		
		$reserve_count+=tep_count_cart($session["sessions_id"],$type);
		//to check reserved sessions
		if ($type=='R'){
			//$reserve_count+=tep_get_renewal_users_count($events['events_id'],$events['events_renewal_end'],$customer_id,$session['start_date']);
			$lock_date=false;
			$total_seats=$events["events_max_reserve"];
			$renewal_count=0;
			if (!$override)	$renewal_count=tep_get_renewal_users_count($events,$customer_id,$session['start_date']);

			if ($overbook) $total_seats+=$events["events_overbook_reserve"];	
			
					
			
			if ($total_seats>=($reserve_count+$renewal_count+$customers)) return true; // total reservation is within max limit

			//if ($renewal_count>0 && $total_seats>$reserve_count) $lock_date=true;
		} else {
			$total=$events["waitsize_vip"]+$events["waitsize_firstcome"];
			if ($events["priority_question"]!=0)
				$total+=$events["waitsize_custom"]; // if user had added priority question for this event
			if ($total>=$reserve_count+$customers){ // if the total waitlist is within  max limit
				return true;
			}
		}
		return false;
	}
	
	// get session details like no of users in details
	function tep_get_session_details(&$session,&$events,$customer_id=0){
		$details=array('reserved'=>0,'waitlist'=>0,'status'=>'E','renewal'=>0);
		
		$reserve_count=tep_reserve_count($session["sessions_id"],$events);
		$reserve_count+=tep_count_cart($session["sessions_id"],'R');
		$details["renewal"]=tep_get_renewal_users_count($events,$customer_id,$session['start_date']);
		$reserve_count+=$details["renewal"];
		
		
		$waitlist_count+=tep_count_cart($session["sessions_id"],'W');
		$waitlist_count=tep_waitlist_count($session["sessions_id"],$events,$customer_id);	

		//to check reserved sessions
		if ($events["events_max_reserve"]>$reserve_count) {
			$details["reserved"]=$events["events_max_reserve"]-$reserve_count;
			$details["status"]='R';  // total reservation is within max limit
		} else if ($events["events_wait_list"]=='Y') {
			$total=$events["waitsize_vip"]+$events["waitsize_firstcome"];
			if ($events["priority_question"]!=0) $total+=$events["waitsize_custom"]; // if user had added priority question for this event
			if ($total>$waitlist_count) {
				$details["status"]='W';// if the total waitlist is within  max limit
				$details["waitlist"]=$total-$waitlist_count;
			}
		}
		return $details;
	}

	// get the products display tree
  function tep_get_products_display_tree($parent_id = '0', $spacing = '', $exclude = '', $category_tree_array = '', $include_itself = false) {
    global $languages_id;

    if (!is_array($category_tree_array)) $category_tree_array = array();
    if ( (sizeof($category_tree_array) < 1) && ($exclude != '0') ) $category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);

    if ($include_itself) {
      $category_query = tep_db_query("select cd.categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " cd where cd.language_id = '" . (int)$languages_id . "' and cd.categories_id = '" . (int)$parent_id . "'");
      $category = tep_db_fetch_array($category_query);
      $category_tree_array[] = array('id' => $parent_id, 'text' => $category['categories_name']);
    }

    $categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' and c.parent_id = '" . (int)$parent_id . "' order by c.sort_order, cd.categories_name");
    while ($categories = tep_db_fetch_array($categories_query)) {
      if ($exclude != $categories['categories_id']) $category_tree_array[] = array('id' => $categories['categories_id'], 'text' => $spacing . $categories['categories_name']);
      $category_tree_array = tep_get_products_display_tree($categories['categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $category_tree_array);
    }
    $products_query=tep_db_query("select pd.products_name,pd.products_id from " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd where pcd.categories_id='" . (int)$parent_id . "' and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "'");
    while ($products=tep_db_fetch_array($products_query))
    {
        $category_tree_array[] = array('id' => $products['products_id'], 'text' => $spacing . $products['products_name'] . '(product)');
    }
    return $category_tree_array;
  }
  
  

// send email to customer regarding the order
function tep_send_event_order_email($order_id){
	global $currencies,$referenceID;
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;

	if ((int)$order_id<=0)	return;

	// fetch order details
	/*$order_sql = "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.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method,
					  o.customers_state,o.customers_country from " . TABLE_ORDERS . " o, " . TABLE_CUSTOMERS . " c where o.orders_id='" . (int)$order_id . "' and o.customers_id=c.customers_id";*/
					  
	$order_sql = "select o.customers_id,o.customers_street_address,o.customers_suburb,o.customers_postcode,o.customers_city,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method,
					  o.customers_state,o.customers_country from " . TABLE_ORDERS . " o where o.orders_id='" . (int)$order_id . "'";
	
	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_CATALOG:HTTP_SERVER . DIR_WS_CATALOG);
	$order_query=tep_db_query($order_sql);	
	if (tep_db_num_rows($order_query)<=0) return;    
	$order_result=tep_db_fetch_array($order_query);
	$customer_query=tep_db_query("SELECT c.customers_email_address,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_second_email_address from " . TABLE_CUSTOMERS . " c where customers_id='" . $order_result["customers_id"] . "'");

	if (tep_db_num_rows($customer_query)>0){
		$customer_result=tep_db_fetch_array($customer_query);
		$order_result=array_merge($order_result,$customer_result);
	}
	//fetch event added to order
	/*$product_query=tep_db_query("SELECT count(*) as quantity,sum(op.final_price) as total_price,op.final_price,op.products_id,op.products_tax,op.products_name,s.events_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
							 " where o.orders_id='" . $order_id ."' and o.orders_id=op.orders_id and op.products_id=s.sessions_id and op.products_type='E' and op.orders_products_status!=5 group by s.events_id,op.final_price ");*/

	$product_query=tep_db_query("SELECT op.final_price,op.products_tax,op.products_name,op.events_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op ".
							 " where o.orders_id='" . $order_id ."' and o.orders_id=op.orders_id and op.products_type='E' and op.orders_products_status!=5");

	
	$products_result=array();
	while($temp_result=tep_db_fetch_array($product_query)){
		if (!isset($products_result[$temp_result["events_id"]])) $products_result[$temp_result["events_id"]]=array();
		$products_result[$temp_result["events_id"]]["total_price"]+=$temp_result["final_price"];
		$products_result[$temp_result["events_id"]]["products_name"]=$temp_result["products_name"];
		$products_result[$temp_result["events_id"]]["products_tax"]=$temp_result["products_tax"];
	}
	if (count($products_result)<=0) return;
	// get mail template details
	$details_r=array();
	$details_r['type']='RCF';
	$details_r['table']=TABLE_EVENTS_MESSAGES;

	$details_w=array();
	$details_w['type']='WCF';
	$details_w['table']=TABLE_EVENTS_MESSAGES;
	

	//while($product_result=tep_db_fetch_array($product_query))
	reset($products_result);
	while(list($events_id,$product_result)=each($products_result))
	{
		$product_result['events_id']=$events_id;
		$details_r['events_id']=$product_result['events_id'];
		tep_get_template($details_r);
		$details_w['events_id']=$product_result['events_id'];
		tep_get_template($details_w);
		
		//fetch event details
		$event_query=tep_db_query("SELECT e.events_id,e.events_instructor,e.events_renewal_end,e.events_renewal_start,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 from " . TABLE_EVENTS . " e where events_id='" . $product_result['events_id'] . "'");
		$event_result=tep_db_fetch_array($event_query);


		$renewal_array=tep_get_renewal_details($event_result,$order_result["customers_id"],true);
		$renewal_end="";

		if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];
		//fetch session dates        
		/*$date_query=tep_db_query("SELECT s.start_date,op.events_type from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o, " .  TABLE_EVENTS_SESSIONS . " s, " . TABLE_EVENTS . " e " .
							 " where o.orders_id='" . $order_id . "' and s.events_id='" . $product_result['events_id'] . "' and op.orders_id=o.orders_id and op.products_id=s.sessions_id and s.events_id=e.events_id and op.products_type='E' and (op.events_type='R' || op.events_type='W') and op.orders_products_status!=5 order by s.start_date");*/

		$date_query=tep_db_query("SELECT op.products_model as start_date,op.events_type from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o " .
							 " where o.orders_id='" . $order_id . "' and op.events_id='" . $product_result['events_id'] . "' and op.orders_id=o.orders_id and op.products_type='E' and (op.events_type='R' || op.events_type='W') and op.orders_products_status!=5 order by op.products_model");

		$session_dates=array('long_r'=>'','short_r'=>'','long_w'=>'','short_w'=>'');

		$events_location=tep_get_locations_name($event_result['events_location']);

		$starting_date='';
		while($date_result=tep_db_fetch_array($date_query)){
			if ($starting_date=='') $starting_date=$date_result['start_date'];
			if ($date_result['events_type']=='R' || $date_result['events_type']=='U'){
				$session_dates['short_r'].=format_date($date_result['start_date'],true) . ",";
				$session_dates['long_r'].=sprintf(TEXT_FORMAT_SS,$product_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>';
			} else {
				$session_dates['short_w'].=format_date($date_result['start_date'],true) . ",";
				$session_dates['long_w'].=sprintf(TEXT_FORMAT_SS,$product_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>';
			}
		}
		//for direct deposit module
	if($GLOBALS['payment']=='ausbank')
		$direct_deposit=sprintf(TEXT_DIRECT_DEPOSIT, $referenceID );
	else 
		$direct_deposit='';
		
		$attendee='';
		/*$order_attendees = $order_result['customers_firstname']." ".$order_result['customers_lastname'];
		$get_group_customers=tep_db_query("select customer_id from " . TABLE_CUSTOMERS_TO_CUSTOMERS . " where group_customer_id='" . $order_result['customers_id'] . "' and orders_id='" . $order_id . "'");
		if(tep_db_num_rows($get_group_customers)>1){
			$order_attendees="";
			$customers_id_string="";
			while($get_group_customer_id=tep_db_fetch_array($get_group_customers)) $customers_id_string.=$get_group_customer_id['customer_id'].",";
			$customers_id_string=substr($customers_id_string,0,-1);
			$attendees_query =  tep_db_query("select customers_firstname,customers_lastname from " . TABLE_CUSTOMERS . " where customers_id in ($customers_id_string)");
			$attendees_count = tep_db_num_rows($attendees_query);
			$loop_count = 1;
			while($attendees_result = tep_db_fetch_array($attendees_query)){
				$order_attendees .= $attendees_result['customers_firstname'] . " " . $attendees_result['customers_lastname'];
				if($loop_count < $attendees_count)$order_attendees .= ",";
				$loop_count++;
			}							
		}
		$attendee = $order_attendees;
		if(strpos($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_attendees . '</font></td>';*/
		// form the merge fields
		$replace_array=array(	TEXT_FN=>$order_result['customers_firstname'],
								TEXT_LN=>$order_result['customers_lastname'],
								TEXT_DF=>format_date($order_result['customers_dob']),
								TEXT_EM=>'<a href="mailto:' . $order_result['customers_email_address'] . '"><u>' . $order_result['customers_email_address'] .'</u></a>',
								TEXT_TN=>$order_result['customers_telephone'],
								TEXT_FX=>$order_result['customers_fax'],
								TEXT_SA=>$order_result['customers_street_address'],
								TEXT_SU=>$order_result['customers_suburb'],
								TEXT_PC=>$order_result['customers_postcode'],
								TEXT_CT=>$order_result['customers_city'],
								TEXT_ST=>$order_result['customers_state'],
								TEXT_CY=>$order_result['customers_country'],
								TEXT_RE=>format_date($renewal_end),
								TEXT_EN=>$product_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($starting_date),
								TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $product_result['events_id'],'NONSSL',false) . '">' . TEXT_IV . '</a>',
								TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $order_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
								TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
								TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
								TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
								TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
								TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
								TEXT_IL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $order_id,'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
								TEXT_SL=>'<a href="../index.php" 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 . 'admin/images/freeway.png" title="' . STORE_NAME . '">',
								TEXT_MA=>$attendee,
								TEXT_ON=>$order_result['orders_id'],
								TEXT_OC=>$order_result['orders_comments'],
								TEXT_OD=>format_date($order_result['date_purchased']),
								TEXT_BT=>$order_result['billing_name'],
								TEXT_BA=>$order_result['billing_street_address'],
								TEXT_PY=>$order_result['payment_method'],
								TEXT_DD=>$direct_deposit,
								TEXT_TX=>$currencies->format(tep_calculate_tax($product_result['total_price'],$product_result['products_tax'])),
								TEXT_SB=>$currencies->format($product_result['total_price']),
								TEXT_TL=>$currencies->format(tep_add_tax($product_result['total_price'],$product_result['products_tax']))
								
								
								);
								
		$sql_array=array(	'orders_id'=>$order_result["orders_id"],
							'events_id'=>$event_result['events_id'],
							'customers_id'=>$order_result["customers_id"],
							'message_type'=>$details_r['type'],
							'message_mode'=>'E',
							'email_address'=>$order_result["customers_email_address"],
							'send_date'=>'now()'
						);

		// replace template
		if ($session_dates['short_r']!=''){ // send mail by grouping reservation sessions
			$replace_array[TEXT_SS]=$session_dates['long_r'];
			$replace_array[TEXT_SSM]=substr($session_dates['short_r'],0,-1);
			if ($details_r['html_text']!='') {
				tep_replace_template($details_r,$replace_array);
				tep_strip_html($details_r);
				$details_r['to_name']=$order_result['customers_firstname'] . ' ' . $order_result['customers_lastname'];
				$details_r['to_email']=$order_result['customers_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 by grouping reservation sessions to Shop Owner
	 /*			 if (STORE_OWNER_EMAIL_ADDRESS!="" && $details_r['type']=='RCF') { // send mail by grouping reservation sessions to Shop Owner
					$details_r['to_name']=STORE_OWNER;
					$details_r['to_email']=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 to particular customer
			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_result['customers_country'];
			   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);
			   }
			}
		}
		if ($session_dates['short_w']!=''){ // send mail by grouping waitlisted sessions
			$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);
				$details_w['to_name']=$order_result['customers_firstname'] . ' ' . $order_result['customers_lastname'];
				$details_w['to_email']=$order_result['customers_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 mobile no exists
			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_result['customers_country'];
			   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 event order notification email
function tep_send_event_order_notify_email($order_id,$event_id){
	global $currencies;
	
	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;
	if ((int)$order_id<=0 || $event_id<=0)
		return;
	// fetch order details
	$order_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.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method,
					  o.customers_state,o.customers_country from " . TABLE_ORDERS . " o, " . TABLE_CUSTOMERS . " c where o.orders_id='" . (int)$order_id . "' and o.customers_id=c.customers_id");

	if (tep_db_num_rows($order_query)<=0) return;    
	$order_result=tep_db_fetch_array($order_query);

	//fetch event added to order
	$product_query=tep_db_query("SELECT s.start_date,op.final_price,op.products_id,op.products_tax,op.products_name,s.events_id from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s " .
							 " where o.orders_id='" . $order_id ."' and o.orders_id=op.orders_id and op.products_id=s.sessions_id and op.products_type='E' and op.events_type='R' and op.waitlist_type='P' and s.events_id='" . $event_id . "'");

	if (tep_db_num_rows($product_query)<=0) return;  
	// get mail template details
	$details=array();
	$details['type']='WPR';
	$details['events_id']=$event_id;
	$details['table']=TABLE_EVENTS_MESSAGES;
	tep_get_template($details);	
	
	if ($details['html_text']=="") return;

	//fetch 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 from " . TABLE_EVENTS . " e where events_id='" . $event_id . "'");
	$event_result=tep_db_fetch_array($event_query);

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

	if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];
	
	$session_dates=array('long'=>'','short'=>'');
	$events_location=tep_get_locations_name($event_result['events_location']);
	$starting_date="";
	while($product_result=tep_db_fetch_array($product_query))
	{
		if ($starting_date=='') $starting_date=$product_result['start_date'];
		$session_dates['short'].=format_date($product_result['start_date'],true) . ",";
		$session_dates['long'].=sprintf(TEXT_FORMAT_SS,$product_result['products_name'],$event_result['events_start_time'],$event_result['events_end_time'],date('l, jS F', strtotime($product_result['start_date'])),$events_location) . '<br>';
	}

	// form the merge fields
	$replace_array=array(	TEXT_FN=>$order_result['customers_firstname'],
							TEXT_LN=>$order_result['customers_lastname'],
							TEXT_DF=>format_date($order_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $order_result['customers_email_address'] . '"><u>' . $order_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$order_result['customers_telephone'],
							TEXT_FX=>$order_result['customers_fax'],
							TEXT_SA=>$order_result['customers_street_address'],
							TEXT_SU=>$order_result['customers_suburb'],
							TEXT_PC=>$order_result['customers_postcode'],
							TEXT_CT=>$order_result['customers_city'],
							TEXT_ST=>$order_result['customers_state'],
							TEXT_CY=>$order_result['customers_country'],
							TEXT_RE=>format_date($renewal_end),
							TEXT_EN=>$product_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($starting_date),
							TEXT_SS=>$session_dates["long"],
							TEXT_SSM=>substr($session_dates["short"],0,-1),
							TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_INVITE_FRIEND,'R=1&path=ACC&eID=' . $product_result['events_id'],'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_UNSUBSCRIBE,'R=1&cID=' . $order_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=RV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=WV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_EVENTS_SURVEYS_ANSWER,'R=1&type=FV&cuID=' . $order_result['customers_id'] . '&events_id=' . $product_result['events_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_IL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $order_id,'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
							);
		$sql_array=array(	'orders_id'=>$order_id,
							'events_id'=>$event_id,
							'customers_id'=>$order_result["customers_id"],
							'message_type'=>'WPR',
							'message_mode'=>'E',
							'email_address'=>$order_result["customers_email_address"],
							'send_date'=>'now()'
						);

		// replace template
		if ($session_dates['short']!=''){
			$replace_array[TEXT_SS]=substr($session_dates['long'],0,-4);
			$replace_array[TEXT_SSM]=substr($session_dates['short'],0,-1);
			tep_replace_template($details,$replace_array);
			tep_strip_html($details);
			$details['to_name']=$order_result['customers_firstname'] . ' ' . $order_result['customers_lastname'];
			$details['to_email']=$order_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);
			}
			
			// send email to alloted event instructor
			
			$instructor_query=tep_db_query("SELECT admin_firstname,admin_lastname,admin_email_address from " . TABLE_ADMIN . " where admin_id='" . $event_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'];
			tep_send_email($details);
			if ($order_result['customers_fax']!=''){
			   $temp_details['mobile']=$order_result['customers_fax'];
			   $temp_details['mail_type']='WPR';
			   $temp_details['events_id']=$event_id;
			   $temp_details['country']=$order_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);
			   }
			}
		}
	}
	
  // config option to set sms gateways
  function tep_cfg_sms_gateway($value,$key=''){
     $sms_array=array();
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');

     $sms_gateway=explode(";",MODULE_SMS_GATEWAYS_INSTALLED);
     
     for($icnt=0;$icnt<sizeof($sms_gateway);$icnt++){
	 	$module=substr($sms_gateway[$icnt], 0, strrpos($sms_gateway[$icnt], '.'));
        $sms_array[]=array('id'=>$module,'text'=>$module);
	}
     $draw_string=tep_draw_pull_down_menu($name,$sms_array,$value) . '&nbsp';
     
    // $draw_string.=tep_image_submit('button_admin_modify.gif',IMAGE_MODIFY,'align=absmiddle');
     
     return $draw_string;
  }

  // send sms to customer
  function tep_send_event_sms_email($replace_array,$send_details)
  {
  	if ((int)SMS_ACTIVATE!=1) return false;
     $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;
     
     $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=str_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']);
  }

  // send event test email 
  function tep_send_event_test_email($mail_type,$events_id){
  global $currencies;

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

   $mail_data_query=tep_db_query("SELECT * from " . TABLE_EVENTS_MESSAGES . " where message_type='" . $mail_type . "' and events_id='" . (int)$events_id . "'");

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

   $mail_data_result=tep_db_fetch_array($mail_data_query);
     
   $mes_text=tep_replace_test_mail_content($mail_data_result['message_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);
	
     $message = new email(array('X-Mailer: osCommRes'));

     if ($mail_data_result['message_format'] != 'T') {
	 $message->add_html($mes_text, $text);
     } else {
	 $message->add_text($text);
     }
     $message->build_message();

     $message->send(TEST_MAIL_FN . ' ' . TEST_MAIL_LN , EVENTS_TEST_EMAIL_ADDRESS, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $mail_data_result['message_subject']);
}

// send event test sms email
function tep_send_event_test_sms_email($mail_type,$events_id)
{
  if ($mail_type=='' || (int)$events_id<=0)
     return;

   $mail_data_query=tep_db_query("SELECT message_text from " . TABLE_EVENTS_SMS_MESSAGES . " where message_type='" . $mail_type . "' and events_id='" . (int)$events_id . "'");

   if (tep_db_num_rows($mail_data_query)<=0) return;
   
   $mail_data_result=tep_db_fetch_array($mail_data_query);

   $mes_text=tep_replace_test_mail_content($mail_data_result['message_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);
	 
     send_sms(SMS_TEST_PHONE,SMS_FROM_NAME,$text,SMS_TEST_COUNTRY);
}
// send sms function by passing mobileNo,name,message text,country ,automate flag
	function send_sms($to,$to_name,$text,$country,$automate=false){
		global $sms,$messageStack;
		
		//echo 'send me';
		
	//echo "No=" . $to . ": Phone=" . $to_name . "<br>" . "text=" . $text . "<br>country=" . $country . "<br>automate=" . $automate . "<br>";  
	//exit;	
	
		$to=str_replace(" ","",$to);
		$sms->create_log=false;
		if (!$sms->connecthost()){
			if ($automate) echo $to . " - SMS Connect Error:" . $sms->get_error() . "\n";
			else $messageStack->add_session($to . " - SMS Connect Error:" . $sms->get_error(), 'error');
			return false;
		}
		if (!$sms->send_sms($to,$to_name,$text,$country)){
			if ($automate) echo $to . " - SMS Send Error:" . $sms->get_error() . "\n";
			else $messageStack->add_session($to . " - SMS Send Error:" . $sms->get_error(), 'error');
			return false;
		}
		return true;
	}
// replace the test mail content
function tep_replace_test_mail_content($mail_content){
  global $currencies;
    $replace_array=array(TEXT_FN=>TEST_MAIL_FN,
          TEXT_LN=>TEST_MAIL_LN,
		  CUST_CM=>TEST_MAIL_CM,
          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_RL=>TEST_MAIL_RL,
			 TEXT_SSM=>date(str_replace("/","-",EVENTS_DATE_FORMAT)),
			 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_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="' . tep_href_link('images/' .COMPANY_LOGO) . '" title="' . STORE_NAME . '">',
			TEXT_MA=>'<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">' . TEST_MAIL_FN . " " . TEST_MAIL_LN . '</font></td>',
          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_DD=>TEST_MAIL_DD,
			 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,
			 TEXT_SUB_NA=>TEST_MAIL_SUB_NA,
			 TEXT_SUB_CO=>$currencies->format(TEST_MAIL_SUB_CO),
			 TEXT_SUB_PE=>TEST_MAIL_SUB_PE,
			 TEXT_SUB_RL=>TEST_MAIL_SUB_RL,
			 TEXT_WAD=>TEST_MAIL_WAD,
			 TEXT_PT=>TEST_MAIL_PT,
			 TEXT_WCB=>TEST_MAIL_WCB,
			 TEXT_SER_SN=>TEST_MAIL_SER_SN,
			 TEXT_SER_SC=>TEST_MAIL_SER_SC,
			 TEXT_SER_SD=>TEST_MAIL_SER_SD,
			 TEXT_SER_ED=>TEST_MAIL_SER_ED,
			 TEXT_SER_ST=>TEST_MAIL_SER_ST,
			 TEXT_SER_ET=>TEST_MAIL_SER_ET,
			 TEXT_SER_RN=>TEST_MAIL_SER_RN,
			 TEXT_SER_AD=>TEST_MAIL_SER_AD,
			 TEXT_SER_TT=>TEST_MAIL_SER_TT,
			 TEXT_SER_PN=>TEST_MAIL_SER_PN,
			 TEXT_SER_PP=>TEST_MAIL_SER_PP,
			 TEXT_SER_SL=>TEST_MAIL_SER_SL,
			 TEXT_SUB_TY=>TEST_SUB_TY,
			 TEXT_SUB_SD=>TEST_SUB_SD,
			 TEXT_LC=>TEST_LC,
									TEXT_SPL=>TEST_SPL,
									TEXT_DN=>TEST_DOMAIN_NAME,
									TEXT_DE=>TEST_DE,
									TEXT_DU=>TEST_DU,
									TEXT_R=>TEST_R,
									TEXT_TST=>TEST_TST,
									TEXT_PU=>TEST_PU,
									TEXT_SUM=>TEST_SUM
			 
			  );
			  //print_r($replace_array);
	reset($replace_array);
   while (list($key, $value) = each($replace_array))
      $mail_content=eregi_replace("%%" . $key  . "%%",$value,$mail_content);
  return $mail_content;

}

	// send default admin related email 
	function tep_send_default_test_email($type){
		global $currencies;
		$details=array();
		$replace_array="";
		$details["type"]=$type;
		$details["table"]=TABLE_EMAIL_MESSAGES;
		
		tep_get_template($details); // get template of content
	    
		tep_merge_details($replace_array,"test_default");  // get default merge data
		tep_replace_template($details,$replace_array);
		
		$details["to_name"]=TEST_MAIL_FN . ' ' . TEST_MAIL_LN;
		$details["to_email"]=EVENTS_TEST_EMAIL_ADDRESS;
		$details["from_name"]=STORE_OWNER;
		$details["from_email"]=STORE_OWNER_EMAIL_ADDRESS;
		//print_r ($details);
		
		tep_send_email($details,true);
		
	} 

	// get the merge details for test
	function tep_merge_details(&$replace_array,$type)
	{ 
	    global $currencies;
		switch($type){
			case "test_default":  
				$replace_array=array(TEXT_FN=>TEST_MAIL_FN,	TEXT_LN=>TEST_MAIL_LN,
									CUST_CM=>TEST_MAIL_CM,
									TEXT_SM=>TEST_MAIL_SM,	TEXT_SE=>TEST_MAIL_SE,
									TEXT_LE=>TEST_MAIL_LE,	TEXT_LP=>TEST_MAIL_LP,
									TEXT_SN=>TEST_MAIL_SN,	TEXT_AL=>TEST_MAIL_AL,
									TEXT_GR=>TEST_MAIL_GR,
									'Store_Link'=>STORE_NAME,
									'Order_Link'=>'Click Here',
									'Store_Logo'=>tep_image(DIR_WS_IMAGES . COMPANY_LOGO),
									TEXT_PN=>TEST_MAIL_PN, TEXT_PP=>TEST_MAIL_PP,
									TEXT_PA=>TEST_MAIL_PA, TEXT_P_M=>TEST_MAIL_P_M,
									TEXT_P_DA=>TEST_MAIL_P_DA, 		TEXT_P_W=>TEST_MAIL_P_W,
									TEXT_P_A_UP=>TEST_MAIL_P_A_UP, 	TEXT_P_U=>TEST_MAIL_P_U,
									TEXT_P_Q=>TEST_MAIL_P_Q,   		TEXT_SN=>TEST_MAIL_SN,
									TEXT_P_SM=>TEST_MAIL_SM,  		TEXT_SE=>TEST_MAIL_SE,
														
									ORDR_NO=>TEST_ORDR_NO, ORDR_OP=>TEST_ORDR_OP,
									ORDR_OL=>TEST_ORDR_OL, ORDR_OM=>TEST_ORDR_OM,
									ORDR_PO=>TEST_ORDR_PO, ORDR_OT=>TEST_ORDR_OT,
									ORDR_PM=>TEST_ORDR_PM, ORDR_PF=>TEST_ORDR_PF,
									ORDR_DD=>TEST_ORDR_DD, ORDR_PD=>TEST_ORDR_PD,
									
									CUST_CF=>TEST_ORDR_CF, CUST_CL=>TEST_ORDR_CL,
									CUST_CM=>TEST_ORDR_CM, CUST_CT=>TEST_ORDR_CT,
									CUST_CS=>TEST_ORDR_CS, CUST_CC=>TEST_ORDR_CC,
									CUST_CP=>TEST_ORDR_CP, CUST_CE=>TEST_ORDR_CE,
									CUST_CU=>TEST_ORDR_CU, CUST_CO=>TEST_ORDR_CO,
									CUST_CA=>TEST_ORDR_CA, DELI_NA=>TEST_ORDR_CF, 
									
									DELI_CM=>TEST_ORDR_CM, DELI_CT=>TEST_ORDR_CT,
									DELI_CS=>TEST_ORDR_CS, DELI_CC=>TEST_ORDR_CC,
									DELI_CP=>TEST_ORDR_CP, DELI_CE=>TEST_ORDR_CE,
									DELI_CU=>TEST_ORDR_CU, DELI_CO=>TEST_ORDR_CO,
									DELI_CA=>TEST_ORDR_CA, BILL_NA=>TEST_ORDR_CF,
									
									BILL_CM=>TEST_ORDR_CM, BILL_CT=>TEST_ORDR_CT,
									BILL_CS=>TEST_ORDR_CS, BILL_CC=>TEST_ORDR_CC,
									BILL_CP=>TEST_ORDR_CP, BILL_CE=>TEST_ORDR_CE,
									BILL_CU=>TEST_ORDR_CU, BILL_CO=>TEST_ORDR_CO,
									BILL_CA=>TEST_ORDR_CA, 
								
									
									TEXT_AD=>TEST_MAIL_AD,
									TEXT_AU=>TEST_MAIL_AU,
									TEXT_AP=>TEST_MAIL_AP,
									TEXT_FL=>TEST_MAIL_FL,
									
									TEXT_FD=>TEST_MAIL_FD,
									TEXT_FB=>TEST_MAIL_FB,
									TEXT_FI=>TEST_MAIL_FI,
									TEXT_P_STATUS=>TEST_P_STATUS,
									TEXT_LC=>TEST_LC,
									TEXT_SPL=>TEST_SPL,
									TEXT_DN=>TEST_DOMAIN_NAME,
									TEXT_DE=>TEST_DE,
									TEXT_DU=>TEST_DU,
									TEXT_R=>TEST_R,
									TEXT_TST=>TEST_TST,
									TEXT_PU=>TEST_PU,
									TEXT_SUM=>TEST_SUM
									
						);
				//print_r($replace_array);
				break;
		
		}
	}
 // form the mobile address by passing the mobile no
 function tep_get_sms_address($mobile){
    return $mobile . '@' . EVENTS_SMS_GATEWAY;
 }
 
// get the discount price for the given event name,amount,no days regarding session date
 function tep_get_discount_price_days($events_id,$fees,$days)
{
  $discount_amount=0;
  if ($days<=0) return $discount_amount;
  
  $discount_query=tep_db_query("SELECT discount_value,discount_type from " . TABLE_EVENTS_DISCOUNTS . " where events_id='" . $events_id . "' and discount_days<='" . $days . "' order by discount_days desc");
  if (tep_db_num_rows($discount_query)){
    $discount_result=tep_db_fetch_array($discount_query);
    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 discount price for the given event, passing values event name,amount,date
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);
	// if the discount type is percentage or gross 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;   
}

// count the no of days for given start date 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;
     }
}

// set default rights automatically for the selected group
function tep_set_default_group_rights($group_name,$group_id=0){
	if ($group_name=="") return;

	if ($group_id==0){
		$group_query=tep_db_query("SELECT admin_groups_id from " . TABLE_ADMIN_GROUPS . " where admin_groups_name='" . $group_name . "'");
		$group_result=tep_db_fetch_array($group_query);
		$group_id=(int)$group_result['admin_groups_id'];
	}
	if ($group_id<=0) return;
		$file_list=array();
		switch($group_name){
			case TEXT_ADMINISTRATOR_ENTRY:
    		    $file_list=array(FILENAME_ADMIN_ACCOUNT,FILENAME_ADMIN_FILES,FILENAME_ADMIN_MEMBERS,
								FILENAME_CATEGORIES,FILENAME_DEFINE_MAINPAGE,FILENAME_EASYPOPULATE,FILENAME_FEATURED,FILENAME_MANUFACTURERS,FILENAME_PRODUCTS_ATTRIBUTES,
								FILENAME_PRODUCTS_EXPECTED,FILENAME_QUICK_ATTIRBUTES_POPUP,FILENAME_QUICK_PRODUCTS_POPUP,FILENAME_REVIEWS,FILENAME_SALEMAKER,
								FILENAME_SALEMAKER_INFO,FILENAME_SPECIALS,FILENAME_XSELL_PRODUCTS,
								FILENAME_CONFIGURATION,
								FILENAME_CREATE_ACCOUNT,FILENAME_CREATE_ACCOUNT_PROCESS,FILENAME_CREATE_ACCOUNT_SUCCESS,FILENAME_CREATE_ORDER,FILENAME_CREATE_ORDER_PROCESS,
								FILENAME_CUSTOMERS,FILENAME_EDIT_ORDERS,FILENAME_ORDERS,
							
							FILENAME_ADMIN_LETTERS,FILENAME_EVENTS_CATEGORIES,FILENAME_EVENTS_BROWSE,FILENAME_EVENTS_DISCOUNTS,FILENAME_EVENTS_LOCATIONS,
							 	FILENAME_EVENTS_OPTIONS,FILENAME_SEARCH_EVENTS,FILENAME_POP_QUESTIONS,FILENAME_SESSIONS,
								
							FILENAME_EVENTS_COPY_MESSAGES,FILENAME_EVENTS_MESSAGES,FILENAME_EVENTS_MESSAGES_LOG,FILENAME_EVENTS_SMS_MESSAGES,FILENAME_SEND_EMAIL,
								FILENAME_SEND_MESSAGES_SCRIPT,FILENAME_SEND_SMS_EMAIL,

							FILENAME_ADD_EVENTS,FILENAME_CHECKOUT_PAYMENT,FILENAME_CHECKOUT_PROCESS,FILENAME_EDIT_EVENTS,FILENAME_EDIT_ORDERS_CONFIRM,FILENAME_EDIT_ORDERS_PROCESS,
								FILENAME_EDIT_ORDERS_SUCCESS,FILENAME_PENDING_WAITLIST_NEW_ORDER,FILENAME_PENDING_WAITLIST_PAYMENTS,FILENAME_PENDING_WAITLIST_PAYMENTS_CONFIRM,
								FILENAME_PENDING_WAITLIST_PAYMENTS_PROCESS,

							FILENAME_MOVE_RESERVATIONS_CONFIRM,FILENAME_MOVE_RESERVATIONS_PROCESS,FILENAME_REFUND_CONFIRM_RESERVATIONS,FILENAME_REFUND_PROCESS,FILENAME_REFUND_RESERVATIONS,
								FILENAME_REFUND_SUCCESS,FILENAME_SEARCH_RESERVATIONS,FILENAME_SEARCH_RESERVATIONS_DATED,FILENAME_SEARCH_RESERVATIONS_PRINT,FILENAME_SEARCH_RESERVATION_PRINT_DATED,
								FILENAME_SEARCH_RESERVATIONS_PRINT_PDF,FILENAME_WAITLISTS,FILENAME_WITHDRAW_PROCESS,FILENAME_WITHDRAW_RESERVATIONS,
							
							FILENAME_EVENTS_REPORTS_WAITLIST,FILENAME_STATS_RESERVATIONS_COUNT,

							FILENAME_EVENTS_COPY_SURVEYS,FILENAME_EVENTS_REPORTS_SURVEYS,FILENAME_EVENTS_REPORTS_SURVEYS_DETAIL,FILENAME_EVENTS_REPORTS_SURVEYS_FILE,FILENAME_EVENTS_REPORTS_SURVEYS_RELATION,
								FILENAME_EVENTS_REPORTS_SURVEYS_SUMMARY,FILENAME_EVENTS_SURVEYS,FILENAME_EVENTS_SURVEYS_ANSWER,FILENAME_EVENTS_SURVEYS_EDIT,FILENAME_EVENTS_SURVEYS_PROCESS,

							FILENAME_FAQDESK,FILENAME_FAQDESK_REVIEWS,
							FILENAME_FAQDESK_CONFIGURATION,
							FILENAME_COUPON_ADMIN,FILENAME_COUPON_RESTRICT,FILENAME_GV_MAIL,FILENAME_GV_QUEUE,FILENAME_GV_SENT,
							FILENAME_INFOBOX_CONFIGURATION,FILENAME_TEMPLATE_CONFIGURATION,
							FILENAME_CURRENCIES,FILENAME_LANGUAGES,FILENAME_ORDERS_STATUS,FILENAME_MODULES,
							FILENAME_NEWSDESK,FILENAME_NEWSDESK_REVIEWS,
							FILENAME_NEWSDESK_CONFIGURATION,
							FILENAME_PAYPALIPN_TESTS,FILENAME_PAYPALIPN_TRANSACTIONS,
							FILENAME_STATS_CUSTOMERS,FILENAME_STATS_PRODUCTS_PURCHASED,FILENAME_STATS_PRODUCTS_VIEWED,FILENAME_STATS_MONTHLY_SALES,
							FILENAME_COUNTRIES,FILENAME_GEO_ZONES,FILENAME_TAX_CLASSES,FILENAME_TAX_RATES,FILENAME_ZONES,
							FILENAME_BACKUP,FILENAME_BANNER_MANAGER,FILENAME_BANNER_STATISTICS,FILENAME_CACHE,FILENAME_DEFINE_LANGUAGE,FILENAME_FILE_MANAGER,
							FILENAME_MAIL,FILENAME_NEWSLETTERS,FILENAME_SERVER_INFO,FILENAME_WHOS_ONLINE
					);
					$box_list=array('manual_order.php','administrator.php','affiliate.php','configuration.php','catalog.php','event.php','instructor.php','modules.php','customers.php','taxes.php','localization.php','reports.php','tools.php','paypalipn.php','infoboxes.php','newsdesk.php','faqdesk.php','gv_admin.php');
					break;
			case TEXT_CALLMANAGER_ENTRY:
				$file_list=array(FILENAME_REVIEWS,FILENAME_CREATE_ACCOUNT,FILENAME_CREATE_ACCOUNT_PROCESS,FILENAME_CREATE_ACCOUNT_SUCCESS,FILENAME_CREATE_ORDER,
							FILENAME_CREATE_ORDER_PROCESS,FILENAME_CUSTOMERS,FILENAME_EDIT_ORDERS,FILENAME_ORDERS,
							
							FILENAME_ADMIN_LETTERS,FILENAME_EVENTS_BROWSE,
								
							FILENAME_ADD_EVENTS,FILENAME_CHECKOUT_PAYMENT,FILENAME_CHECKOUT_PROCESS,FILENAME_EDIT_ORDERS_CONFIRM,FILENAME_EDIT_ORDERS_PROCESS,FILENAME_EDIT_EVENTS,FILENAME_EDIT_ORDERS_SUCCESS,
							FILENAME_PENDING_WAITLIST_NEW_ORDER,FILENAME_PENDING_WAITLIST_PAYMENTS,FILENAME_PENDING_WAITLIST_PAYMENTS_CONFIRM,FILENAME_PENDING_WAITLIST_PAYMENTS_PROCESS,
							
							FILENAME_SEND_EMAIL,FILENAME_SEND_SMS_EMAIL,
							
							FILENAME_MOVE_RESERVATIONS_CONFIRM,FILENAME_MOVE_RESERVATIONS_PROCESS,FILENAME_REFUND_RESERVATIONS,FILENAME_REFUND_CONFIRM_RESERVATIONS,FILENAME_REFUND_PROCESS,
								FILENAME_REFUND_SUCCESS,FILENAME_SEARCH_RESERVATIONS,FILENAME_SEARCH_RESERVATIONS_DATED,FILENAME_SEARCH_RESERVATION_PRINT,FILENAME_SEARCH_RESERVATION_PRINT_DATED,
								FILENAME_SEARCH_RESERVATION_PRINT_PDF,FILENAME_WAITLISTS,FILENAME_WITHDRAW_PROCESS,FILENAME_WITHDRAW_RESERVATIONS
					);
				$box_list=array('catalog.php','event.php','customers.php');
				break;
			case TEXT_CALLSTAFF_ENTRY:
				$file_list=array(FILENAME_CREATE_ACCOUNT,FILENAME_CREATE_ACCOUNT_PROCESS,FILENAME_CREATE_ACCOUNT_SUCCESS,FILENAME_CREATE_ORDER,
							FILENAME_CREATE_ORDER_PROCESS,FILENAME_CUSTOMERS,FILENAME_EDIT_ORDERS,FILENAME_ORDERS,

							FILENAME_ADMIN_LETTERS,FILENAME_EVENTS_BROWSE,

							FILENAME_ADD_EVENTS,FILENAME_CHECKOUT_PAYMENT,FILENAME_CHECKOUT_PROCESS,FILENAME_EDIT_ORDERS_CONFIRM,
			    				FILENAME_EDIT_ORDERS_PROCESS,FILENAME_EDIT_EVENTS,FILENAME_EDIT_ORDERS_SUCCESS,

							FILENAME_PENDING_WAITLIST_NEW_ORDER,FILENAME_PENDING_WAITLIST_PAYMENTS,FILENAME_PENDING_WAITLIST_PAYMENTS_CONFIRM,
								FILENAME_PENDING_WAITLIST_PAYMENTS_PROCESS,
							
							FILENAME_SEND_EMAIL,
							
							FILENAME_MOVE_RESERVATIONS_CONFIRM,FILENAME_MOVE_RESERVATIONS_PROCESS,FILENAME_REFUND_SUCCESS,FILENAME_SEARCH_RESERVATIONS,
								FILENAME_SEARCH_RESERVATIONS,FILENAME_SEARCH_RESERVATIONS_DATED,FILENAME_SEARCH_RESERVATION_PRINT,FILENAME_SEARCH_RESERVATION_PRINT_DATED,
								FILENAME_SEARCH_RESERVATION_PRINT_PDF,FILENAME_WAITLISTS,FILENAME_WITHDRAW_PROCESS,FILENAME_WITHDRAW_RESERVATIONS
						);
				$box_list=array('event.php','customers.php');
				break;
		    case TEXT_INSTRUCTOR_ENTRY:
    			$file_list=array(FILENAME_SEARCH_RESERVATIONS,FILENAME_SEARCH_RESERVATION_PRINT,
								FILENAME_INSTRUCTORS,FILENAME_EVENTS_ADMIN_MESSAGES,FILENAME_VIEW_RESERVATIONS,FILENAME_INSTRUCTOR_RESERVATIONS,
								FILENAME_EVENTS_PAYMENTS,FILENAME_EVENTS_PAYMENTS_DETAIL
								);
				$box_list=array('event.php','instructor.php');
				break;
			case TEXT_PRODUCTMANAGER_ENTRY:
				$file_list=array(FILENAME_CATEGORIES,FILENAME_DEFINE_MAINPAGE,FILENAME_EASYPOPULATE,FILENAME_FEATURED,FILENAME_MANUFACTURERS,FILENAME_PRODUCTS_ATTRIBUTES,
							FILENAME_PRODUCTS_EXPECTED,FILENAME_QUICK_ATTIRBUTES_POPUP,FILENAME_QUICK_PRODUCTS_POPUP,FILENAME_REVIEWS,FILENAME_SALEMAKER,
							FILENAME_SALEMAKER_INFO,FILENAME_SPECIALS,FILENAME_XSELL_PRODUCTS,
							FILENAME_FAQDESK,FILENAME_FAQDESK_REVIEWS,
							FILENAME_COUPON_ADMIN,FILENAME_COUPON_RESTRICT,FILENAME_GV_MAIL,FILENAME_GV_QUEUE,FILENAME_GV_SENT,
							FILENAME_STATS_CUSTOMERS,FILENAME_STATS_PRODUCTS_PURCHASED,FILENAME_STATS_PRODUCTS_VIEWED,FILENAME_STATS_MONTHLY_SALES
						);
				$box_list=array('catalog.php','reports.php','faqdesk.php','gv_admin.php');
				break;
			case TEXT_RESERVATIONMANAGER_ENTRY:
				$file_list=array(FILENAME_REVIEWS,FILENAME_CREATE_ACCOUNT,FILENAME_CREATE_ACCOUNT_PROCESS,FILENAME_CREATE_ACCOUNT_SUCCESS,FILENAME_CREATE_ORDER,FILENAME_CREATE_ORDER_PROCESS,
							FILENAME_CUSTOMERS,FILENAME_EDIT_ORDERS,FILENAME_ORDERS,
							
							FILENAME_ADMIN_LETTERS,FILENAME_EVENTS_CATEGORIES,FILENAME_EVENTS_DISCOUNTS,FILENAME_EVENTS_LOCATIONS,FILENAME_EVENTS_OPTIONS,FILENAME_SEARCH_EVENTS,
								FILENAME_EVENTS_BROWSE,FILENAME_POP_QUESTIONS,FILENAME_SESSIONS,

						    FILENAME_INSTRUCTORS,FILENAME_INSTRUCTORS_OPTIONS,FILENAME_VIEW_RESERVATIONS,FILENAME_INSTRUCTOR_RESERVATIONS,
							
							FILENAME_ADD_EVENTS,FILENAME_CHECKOUT_PAYMENT,FILENAME_CHECKOUT_PROCESS,FILENAME_EDIT_ORDERS_CONFIRM,FILENAME_EDIT_ORDERS_PROCESS,
							    FILENAME_PENDING_WAITLIST_NEW_ORDER,FILENAME_PENDING_WAITLIST_PAYMENTS,FILENAME_PENDING_WAITLIST_PAYMENTS_CONFIRM,FILENAME_PENDING_WAITLIST_PAYMENTS_PROCESS,
								FILENAME_EDIT_EVENTS,FILENAME_EDIT_ORDERS_SUCCESS,
				
							FILENAME_EVENTS_COPY_MESSAGES,FILENAME_EVENTS_MESSAGES,FILENAME_EVENTS_SMS_MESSAGES,FILENAME_SEND_EMAIL,FILENAME_SEND_SMS_EMAIL,
							FILENAME_EVENTS_MESSAGES_LOG,
							
							FILENAME_MOVE_RESERVATIONS_CONFIRM,FILENAME_MOVE_RESERVATIONS_PROCESS,FILENAME_REFUND_RESERVATIONS,FILENAME_REFUND_CONFIRM_RESERVATIONS,FILENAME_REFUND_PROCESS,
								FILENAME_REFUND_SUCCESS,FILENAME_SEARCH_RESERVATIONS,FILENAME_SEARCH_RESERVATION_PRINT,FILENAME_SEARCH_RESERVATIONS_DATED,FILENAME_SEARCH_RESERVATION_PRINT_DATED,
								FILENAME_SEARCH_RESERVATION_PRINT_PDF,FILENAME_WAITLISTS,FILENAME_WITHDRAW_PROCESS,FILENAME_WITHDRAW_RESERVATIONS,
							    
							FILENAME_EVENTS_REPORTS_WAITLIST,FILENAME_STATS_RESERVATIONS_COUNT,
							FILENAME_FAQDESK,FILENAME_FAQDESK_REVIEWS
							);
							$box_list=array('catalog.php','customers.php','event.php','instructor.php','faqdesk.php');
						}
  if (sizeof($file_list)<=0) return;

  $files_to_modify=implode("','",$file_list);
  $boxes_to_modify=implode("','",$box_list);
  
  $sql="SELECT * from " . TABLE_ADMIN_FILES . " where admin_files_is_boxes='1'";
  $boxes_query=tep_db_query($sql);
  if (tep_db_num_rows($boxes_query)<=0) return;
  while($boxes_result=tep_db_fetch_array($boxes_query)){
    $admin_groups=explode(",",$boxes_result['admin_groups_id']);
   if(in_array($boxes_result['admin_files_name'],$box_list)){
    if (!in_array($group_id,$admin_groups)){
      $admin_groups[]=$group_id;
      sort($admin_groups,SORT_NUMERIC);
      $update_groups=implode(",",$admin_groups);
      tep_db_query("UPDATE " . TABLE_ADMIN_FILES . " set admin_groups_id='" . $update_groups . "' where admin_files_id='" . $boxes_result['admin_files_id'] . "'");
    }
   } else {
     if (in_array($group_id,$admin_groups)){
       $admin_groups=array_diff($admin_groups,array($group_id));
       $update_groups=implode(",",$admin_groups);
       tep_db_query("UPDATE " . TABLE_ADMIN_FILES . " set admin_groups_id='" . $update_groups . "' where admin_files_id='" . $boxes_result['admin_files_id'] . "'");
     }
   }
  }
  
  $sql="SELECT * from " . TABLE_ADMIN_FILES . " where admin_files_is_boxes='0'";
  $files_query=tep_db_query($sql);
  if (tep_db_num_rows($files_query)<=0) return;
  while($files_result=tep_db_fetch_array($files_query)){
    $admin_groups=explode(",",$files_result['admin_groups_id']);
    if(in_array($files_result['admin_files_name'],$file_list)){
     if (!in_array($group_id,$admin_groups)){
      $admin_groups[]=$group_id;
      sort($admin_groups,SORT_NUMERIC);
      $update_groups=implode(",",$admin_groups);
      tep_db_query("UPDATE " . TABLE_ADMIN_FILES . " set admin_groups_id='" . $update_groups . "' where admin_files_id='" . $files_result['admin_files_id'] . "'");
     }
    } else {
     if (in_array($group_id,$admin_groups)){
       $admin_groups=array_diff($admin_groups,array($group_id));
       $update_groups=implode(",",$admin_groups);
       tep_db_query("UPDATE " . TABLE_ADMIN_FILES . " set admin_groups_id='" . $update_groups . "' where admin_files_id='" . $files_result['admin_files_id'] . "'");
     }
    }
  }
}

//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 . "templates/" . DEFAULT_TEMPLATE . "/images/product_email_template.html","r");
		if (!$fp) return;
		$details['html_text']=fread($fp,filesize(DIR_FS_CATALOG . "templates/" . DEFAULT_TEMPLATE . "/images/product_email_template.html"));
		if ($details['html_text']=="") return false;
		
		$details['text']=strip_tags($details['html_text']);
		$details['format']="T";
    }; 
	tep_replace_template($details,$merge_details); // replace template content with merge details
 
	tep_strip_html($details); // strip tags;
	
	//print_r ($send_details);
    //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
    }
 }

  // select event select menu
  function tep_draw_eventselect_menu($name, $values, $selected_vals, $params = '', $required = false) {
    $field = '<select name="' . $name . '"';
    if ($params) $field .= ' ' . $params;
	$field.=' class="inputNormal" onBlur="javascript:toggle_focus(this,1);" onFocus="javascript:toggle_focus(this,2);"';
    $field .= ' >';
    for ($i=0; $i<sizeof($values); $i++) {
	if ($values[$i]['id'])
	{
      	$field .= '<option value="' . $values[$i]['id'] . '"';
	    if ($selected_vals == $values[$i]['id']) $field .= ' SELECTED';
        $field .= '>' . $values[$i]['text'] . '</option>';
	}
    }
    $field .= '</select>';

    if ($required) $field .= TEXT_FIELD_REQUIRED;

    return $field;
  } 
  
  // draw the pull down menu
  function tep_draw_alt_pull_down_menu($name, $values, $default = '', $parameters = '', $required = false) {
    $field = '<select name="' . tep_output_string($name) . '"';

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

    $field .= '>';

    if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);

    for ($i=0, $n=sizeof($values); $i<$n; $i++) {
      $field .= '<option value="' . tep_output_string($values[$i]['id']) . '"';
      if ($default == $values[$i]['text']) {
        $field .= ' SELECTED';
      }

      $field .= '>' . tep_output_string($values[$i]['text'], array('"' => '&quot;', '\'' => '&#039;')) . '</option>';
    }
    $field .= '</select>';

    if ($required == true) $field .= TEXT_FIELD_REQUIRED;

    return $field;
  }

  // format the given date according to configuration setting EVENTS_DATE_FORMAT
  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)));
    }
  }
    // function to calculate instructor rate
	function calculate_instructor_rate($total_amount,$no_student,$session_rate){
		$rate_query=tep_db_query("SELECT rate_type,rate,base_rate from " . TABLE_INSTRUCTOR);
		$rate=tep_db_fetch_array($rate_query);
		switch($rate["rate_type"]){
			case 0:
				$amount=$total_amount*$rate["rate"]/100.0+$rate["base_rate"];
				break;
			case 1:
				$amount=($session_rate*$rate["rate"]/100.0)*$no_student;
				break;
			case 2:
				$amount=$rate["rate"]*$no_student;
				break;
			default:
				$amount=0;
		}
		$amount+=$rate["base_rate"];
		return $amount;
	}
	// mail functions used to send emails and message
	function send_internal_message(&$details){
		$sql_array=array(	"message_from"=>$details["from_name"],
							"message_to"=>$details["to_name"],
							"message_date"=>'now()',
							"message_subject"=>$details['subject'],
							"message_text"=>$details['text']);
		tep_db_perform(TABLE_ADMIN_MESSAGES,$sql_array);
	}
	// replace the template with merge details
	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['text']=eregi_replace("%%" . $key . "%%"," ".$value,$details['text']);
		}
		$details['html_text']=eregi_replace("%%current_url%%",HTTP_SERVER . DIR_WS_CATALOG . "",$details['html_text']);
		$details['text']=eregi_replace("%%current_url%%",HTTP_SERVER . DIR_WS_CATALOG . "",$details['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();		
		 if($details['to_name']!=='' && $details['to_email']!=='' && $details['from_name']!=='' && $details['from_email']!=='' && $details['subject']!=='')
		 {
			 $result=$message->send($details['to_name'], $details['to_email'], $details['from_name'], $details['from_email'], $details['subject']);			 
			 unset($message);
			 return $result;
		 }	 
	}

	// function to fetch 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);
			$details['format']=$mail_data_result['message_format'];
			$details['html_text']=$mail_data_result['message_text'];
			$details['text']=strip_tags($mail_data_result['message_text'],'<br>');
			$details['subject']=$mail_data_result['message_subject'];
			return $details;
		}
		
	}
	// stip the html 
	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']);
	}
	
	// get the events price 
	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 "F":
					$final_amount=$events_result["waitfee_firstcome"]; // firstcome user
					break;
				case "C":
					$final_amount=$events_result["waitfee_custom"]; // custom user
					break;
				case "V":
				default:
					$final_amount=$events_result["waitfee_vip"];  // vip 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 sessions list as an array for the given events_id
	function tep_get_sessions_list($events_id,$session_type,$start_date=''){
		//get the recursive query
		$events_query=tep_db_query("select sessions_select_count,sessions_select_interval,sessions_date_count,events_forward_period,events_forward_length from " . TABLE_EVENTS . " where events_id='" . (int)$events_id . "'");
		$events_result=tep_db_fetch_array($recursive_query);
		$add_option="";
		if ($events_result['events_forward_period']=='Y'){
			$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$events_result['events_forward_length']));
			$date_end_option=" and start_date<='" . $check_date . "' ";
		}
		if ($start_date!=''){
			$date_start_option=" and start_date>='" . $start_date ."' ";
		}
		$cnt=0;
		$session_query=tep_db_query("SELECT start_date,sessions_id from " . TABLE_EVENTS_SESSIONS  .  " where events_id='" . (int)$events_id . "' and start_date>'" . getServerDate(true) . "' " . $date_start_option . $date_end_option . " and sessions_type!='' order by start_date");
		while($session_result = tep_db_fetch_array($session_query))
		{
			$session_array[] = array('id' => $session_result['sessions_id'],'text' => format_date($session_result['start_date']));
			$cnt++;
			if ($session_type=='R'){
				if ($cnt>=(int)$session_result['sessions_date_count']) break;
			}
		}
	}
	
	// redraw the post fields to the page
	function tep_draw_post_fields($fields){
		global $HTTP_POST_VARS;
		reset($fields);
		$result="";
		//reset and iterate all fields in the array
		while(list(,$key)=each($fields)){
			if (isset($HTTP_POST_VARS[$key])){ // if the field value is present
				if (is_array($HTTP_POST_VARS[$key])){ // if its a array
					$value=&$HTTP_POST_VARS[$key];
					for ($icnt=0;$icnt<sizeof($value);$icnt++){
						$result.='<input type="hidden" name="' . $key . '[]" value="' . $value[$icnt] . '">' . "\n";
					}
				} else {
					$result.='<input type="hidden" name="' . $key . '" value="' . tep_output_string($HTTP_POST_VARS[$key]) . '">' . "\n";
				}
			}
		}
		return $result;
	}
	function tep_redirect_post($filename,$params,$values){
		echo '<html><head><title>test</title></head><body>';
		echo '<form name="frmSubmit" method="post" action="' . tep_href_link($filename,$params) . '">';
		echo tep_draw_post_fields($values);
		echo '<input type="hidden" name="add_option" value="none">';
		echo '</form>';
		echo '<script language="javascript">document.frmSubmit.submit();</script>';
		echo '</body></html>';
		require(DIR_WS_INCLUDES . 'application_bottom.php');
		tep_exit_execution();
	}
	function tep_exit_execution(){
    global $logger;
		if (STORE_PAGE_PARSE_TIME == 'true') {
		  if (!is_object($logger)) $logger = new logger;
		  $logger->timer_stop();
		}
	
		exit;
	}
	
/* functions describing event reservation system to find max reseved users,max waitlist users and determine free seats

*/

	//  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);
		}
	}
	// common function to fetch required fields of event table
	function tep_event_fields_list(){
		$fields_list=" e.events_id,e.events_max_reserve,e.events_overbook_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
		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,0,$date_result['start_date']);
		
		if ($reserve_count>=$max_reservations) return;
     
		// 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);
			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
	}

	// promote waiting list by checking the session dates if needed
	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;

		$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)
		{
			$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++){
						$orders_products_id=tep_next_reservation($priority_array[$current_priority],$sessions_id,($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;
		}
	}

	// get the total no of users of particular waiting list 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)>=curdate())";
			$pending_option=" and ((op.orders_products_status>1 and op.orders_products_status<5)  or (op.orders_products_status=1 and (date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . getServerDate(true) . "'))) 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;
	}

	// get the total no of reserved users for the particular session 
	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)>=curdate())";
			$pending_option=" and ((op.orders_products_status>1 and op.orders_products_status<5) or ( op.orders_products_status=1 and (date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . getServerDate(true) . "'))) and op.orders_products_status!=5";
		}
		$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 for the particular session
	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)>=curdate())";
			$pending_option=" and ((op.orders_products_status>1 and op.orders_products_status<5) or ( op.orders_products_status=1 and (date_add(o.date_purchased,interval '" . $values['events_pending_period'] . "' day)>='" . getServerDate(true) . "'))) 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);
		$result=tep_db_fetch_array($query);
		$count+=(int)$result['total_count'];
		return $count;
	}
	
	// calculate the given date
	function tep_date_calculate($timestamp, $unit, $amount, $mode) {
		if($amount<=0) $amount=1;
	// Possible $units are: "hr", "min", "sec",
	//          "mon", "day", or "yr"
	// $amount should be an integer
	   $delta_vars = array("hr"=>0, "min"=>0,
	   "sec"=>0, "mon"=>1,
	   "day"=>1,"yr"=>1970);
	   if ($mode==1)
		   $delta_vars[$unit] += $amount;
		else 
			$delta_vars[$unit] -= $amount;
	   $delta = gmmktime($delta_vars["hr"],
	   $delta_vars["min"],
	   $delta_vars["sec"],
	   $delta_vars["mon"],
	   $delta_vars["day"],
	   $delta_vars["yr"]);
	   return $timestamp - $delta;
	}
	
	// get the total no of renewal users count
	function tep_get_renewal_users_count_old($events_id,$renewal_end,$customer_id=0,$check_date="")
	{
		$count=0;


		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>'" . getServerDate(true) . "' 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 renewal details renewal start date,renewal end date, status
	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();
		//$curdate="2005-10-29";
		$customer_check=" and o.customers_id='" . $customer_id . "' ";
		
		// find the renewal start type last session,one week before last session,two week before 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;

			// find the date with in the given renewal period
			$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 { // 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){
					$details["start_date"]=$user_check["start_date"];
					$details["end_date"]=$user_check["end_date"];
					$details["status"]="no";
					if ($only_data){
						$details["end_date"]=$user_check["end_date"];
						return $details;
					}
					if ($user_check['end_date']>=$curdate) {
						if ($user_check["start_date"]<=$curdate)
							$details["status"]="yes";
						else
							$details=array();
					}
					break;
				}
				$cur_row++;
			}
		}
		return $details;
	}

	// get the total no of users who are in the renewal period using the given renewal settings
	function tep_get_renewal_users_count(&$events,$customer_id=0,$check_date="")
	{
	//version 1
		$count=0;
		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="'" . getServerDate(true) . "' ";
		//$curdate="'2005-10-29'";
		if ($customer_id>0)
			$customer_check=" and o.customers_id!='" . $customer_id . "' ";
		
		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_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'){
			$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();

			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;
	}
   // move the reservation from waiting list to confirmed
	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 the next possible reservation using the given current priority
	function tep_next_reservation($current_priority,$sessions_id,$check_vip=false)
	{
		if ($current_priority=='V'){ // vip group 
			$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.products_id='" . $sessions_id ."' and op.orders_products_status!=5 order by o.date_purchased");
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		} else if ($current_priority=='F'){ // first come group
			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.products_id='" . $sessions_id ."' and op.orders_products_status!=5 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.products_id='" . $sessions_id ."' and op.orders_products_status!=5 order by o.date_purchased");
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		}	else if ($current_priority=='C'){ // custom question group
			// get question ordered 
			//echos("SELECT orders_products_id,case answer_type when 'D' then ADDDATE(answer_value,INTERVAL 0 day) when 'N' then (answer_value+0.0) else answer_value END as result_answer from " . TABLE_ORDERS_EVENTS_ANSWERS . " a, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS  . " o, "  . TABLE_ORDERS_PRODUCTS . " op where s.sessions_id='" . $sessions_id . "' and s.events_id=a.events_id and o.orders_id=a.orders_id and op.products_id=s.sessions_id and 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 order by result_answer limit 1 ");
			$query=tep_db_query("SELECT orders_products_id,case answer_type when 'D' then ADDDATE(answer_value,INTERVAL 0 day) when 'N' then (answer_value+0.0) else answer_value END as result_answer from " . TABLE_ORDERS_EVENTS_ANSWERS . " a, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS  . " o, "  . TABLE_ORDERS_PRODUCTS . " op where s.sessions_id='" . $sessions_id . "' and s.events_id=a.events_id and o.orders_id=a.orders_id and op.products_id=s.sessions_id and 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 order by result_answer limit 1 ");
			$result=tep_db_fetch_array($query);
			return $result['orders_products_id'];
		}
		return 0;
	} 
	
	//used to check the free sessions 
	function tep_get_check_free_sessions($start_id,$no_of_sessions,$events_type,$customer_id=0){
	// get  event details with session id
	global $session_array,$events_result,$oID;
//	print_r($events_result);
	$events_id=(int)$events_result['events_id'];
	$start_date=tep_get_session_date($start_id);
	$max_reserve=((int)$events_result['events_max_reserve']);

	// Limit the sessions date to the events_forward_period if exists
	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 . "' ";
	}
	// check if present in orders_edit_product table
	$products_query=tep_db_query("select products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oID . "' and products_type='E' and (events_type='R' || events_type='W')");
//echo "select products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oID . "' and products_type='E' and (events_type='R' || events_type='W')";
	$check_ids=array();
	while($products_result=tep_db_fetch_array($products_query)){
		$check_ids[$products_result['products_id']]="1";
	}
	$date_query=tep_db_query("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");
//echo "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";
  //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 the given type is to find reserved,waitlist of mixed
		if ($events_type=='R' || $events_type=='M'){
			$total_reservations=tep_reserve_count($date_result["sessions_id"],$events_result)+1;
			$total_reservations+=tep_get_renewal_users_count($events_result,$customer_id,$date_result['start_date']);
			$total_reservations+=tep_count_cart($date_result["sessions_id"],"R");
		//	echo '<br>'. $date_result["start_date"] . ' total_reserve:'.$total_reservations.'max_reserve:'.$max_reserve .'<br>';
			// if the reserved users exceeds the maximum reservations
			if ($total_reservations<=$max_reserve){ 
					$accept=true;
			} else {
				//check group bookings	
				if($events_result['events_group_bookings']=='Y') {
				  return $total_reservations . "#" . $max_reserve;
				}//return;
				//check group bookings
				// check if session gaps is present
				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 appropriate waiting list group
				$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result);
		
				if ($find_group!='E'){
					$accept=true;
				} else {
					// check if session gaps is present
					if ($events_result['session_gaps']!='Y' && sizeof($session_array_temp)>0){
						$session_array_temp=array();
						$current_count=1;
					}
				}
			}
		}
		if ($accept==true){
			// combine the formed dates into final one
			if (!isset($session_array[$date_result['sessions_id']]) && !isset($check_ids[$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;
			}
		}
	}
//	if (sizeof($session_array_temp)>0) $session_array+=$session_array_temp;
}
	
	
	// fetch the sessions list ready for reservation from the given date, no of sessions , type of reservation (confirmed or waitlist) logic 1 not used as current
 function tep_get_free_sessions($start_id,$no_of_sessions,$events_type,$customer_id=0){
	// get  event details with session id
	global $session_array,$events_result,$oID;
	
	$events_id=(int)$events_result['events_id'];
	$start_date=tep_get_session_date($start_id);
	$max_reserve=((int)$events_result['events_max_reserve']);
	// Limit the sessions date to the events_forward_period if exists
	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 . "' ";
	}
	// check if present in orders_edit_product table
	$products_query=tep_db_query("select products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oID . "' and products_type='E' and (events_type='R' || events_type='W')");
//echo "select products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oID . "' and products_type='E' and (events_type='R' || events_type='W')";
	$check_ids=array();
	while($products_result=tep_db_fetch_array($products_query)){
		$check_ids[$products_result['products_id']]="1";
	}
	$date_query=tep_db_query("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");
  //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 the given type is to find reserved,waitlist of mixed
		if ($events_type=='R' || $events_type=='M'){
			$total_reservations=tep_reserve_count($date_result["sessions_id"],$events_result)+1;
			$total_reservations+=tep_get_renewal_users_count($events_result,$customer_id,$date_result['start_date']);
			$total_reservations+=tep_count_cart($date_result["sessions_id"],"R");
			
			// if the reserved users exceeds the maximum reservations
			if ($total_reservations<=$max_reserve){
					$accept=true;
			} else {
				//check group bookings	
				if($events_result['events_group_bookings']=='Y')  return;
				
				//check group bookings
				// check if session gaps is present
				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 appropriate waiting list group
				$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result);
		
				if ($find_group!='E'){
					$accept=true;
				} else {
					// check if session gaps is present
					if ($events_result['session_gaps']!='Y' && sizeof($session_array_temp)>0){
						$session_array_temp=array();
						$current_count=1;
					}
				}
			}
		}
		if ($accept==true){
			// combine the formed dates into final one
			if (!isset($session_array[$date_result['sessions_id']]) && !isset($check_ids[$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;
			}
		}
	}
	if (sizeof($session_array_temp)>0) $session_array+=$session_array_temp;
}
// get free sessions for the backend order creation page
 function tep_get_free_sessions_fixed($start_id,$no_of_sessions,$customer_id=0){
	// get  event details with session id
	global $session_array,$events_result,$oID;
	
	$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 . "' ";
	}

	// check if there in orders_edit_product table
	$products_query=tep_db_query("select products_id from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id='" . (int)$oID . "' and products_type='E' and (events_type='R' || events_type='W')");

	$check_ids=array();
	while($products_result=tep_db_fetch_array($products_query)){
		$check_ids[$products_result['products_id']]="1";
	}
	$date_query=tep_db_query("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");

	//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";
	
		$total_reservations=tep_reserve_count($date_result["sessions_id"],$events_result)+1;
		$total_reservations+=tep_get_renewal_users_count($events_result,$customer_id,$date_result['start_date']);
		$total_reservations+=tep_count_cart($date_result["sessions_id"],"R");
		
		if ($total_reservations<=$max_reserve) $accept=true;

		if  ($accept==false){
			$session_type="W";
			$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result);
			
			if ($find_group!='E')	$accept=true;
		 }

     if ($accept==true){
			if (!isset($session_array[$date_result['sessions_id']]) && !isset($check_ids[$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;
			}
     }
	}
	if (sizeof($session_array_temp)>0){
		$session_array+=$session_array_temp;
	}
}

// get first session of the given event
 function tep_get_first_session(&$events_result){

	$events_id=(int)$events_result['events_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 . "' ";
	}

	

	//iterate all selected dates and find reserved,waitlist,no seats dates 
	
	// first check for the free sessions
	$fetch_types=array('R','W');
	for ($icnt=0;$icnt<count($fetch_types);$icnt++){
		$session_type=$fetch_types[$icnt];
		$date_query=tep_db_query("select sessions_id,start_date,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS . " where events_id='" . $events_id . "' and start_date>'" . getServerDate(true) . "' and sessions_type!='' and sessions_type!='P' " . $check_data ." order by start_date");
		while($date_result=tep_db_fetch_array($date_query)){
			$accept=false;

			if ($session_type=="R"){
				$total_reservations=tep_reserve_count($date_result["sessions_id"],$events_result)+1;
				$total_reservations+=tep_get_renewal_users_count($events_result,$customer_id,$date_result['start_date']);
				$total_reservations+=tep_count_cart($date_result["sessions_id"],"R");
				if ($total_reservations<=$max_reserve) $accept=true;
			} else {
				$find_group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],0,$events_result);
				if ($find_group!='E') $accept=true;
			}
			if ($accept==true){
				if ($session_type=="W"){
					$waitlist_count+=tep_count_cart($date_result['sessions_id'],'W');
					$waitlist_count=tep_waitlist_count($date_result["sessions_id"],$events_result,$customer_id);
			
					$total=$events_result["waitsize_vip"]+$events_result["waitsize_firstcome"];
					if ($events["priority_question"]!=0) $total+=$events["waitsize_custom"]; // if user had added priority question for this event
					$spaces=$total-$waitlist_count;
				} else {
					$spaces=$max_reserve-($total_reservations-1);
				}
				$session_array=array('id'=>$date_result['sessions_id'],'date'=>$date_result['start_date'],'type'=>$session_type,'group'=>$find_group,spaces=>$spaces,'recursive_id'=>$date_result['recursive_sessions_id']);
				break;
			}
		}
		if (count($session_array)>0) break;
	}
	return $session_array;
}

// count the session items present 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");

	$waitlist_option="";
	if ($waitlist_type!='') $waitlist_option=" and cs.session_group='" . $waitlist_type . "'";
	// 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 . "' " . $waitlist_option ." 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;
}

// find the appropriate waitlist group
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);
	}
	if ($values['events_wait_list']!='Y') return 'E';

 	// align the waiting list groups according to present priorities
	$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';
	
	$find_group='';
	$current_priority=1;
	while($find_group=='')
	{
		// waiting list size of given group is >0
		if ($wait_size[$priority_array[$current_priority]]>0){
			if (($current_priority=='2' && $values['priority_question']>0) || $current_priority!='2'){
				// get the waitlist users count
				$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]);
				
				$current_wait_size=$wait_size[$priority_array[$current_priority]];
												
				// if there some seats in current group
				if ($group_count<=$current_wait_size){
					$find_group=$priority_array[$current_priority];
					// check for vip group
					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;
 }

// check if the given event has filled for all sessions
 function tep_check_max_reservations($events_id,$sessions_id,$id=0){
	$customer_query=tep_db_query("SELECT o.customers_id,s.start_date,s.sessions_id from  " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS . " o where s.sessions_id=op.products_id and o.orders_id=op.orders_id and op.orders_products_id='" . (int)$id . "' and op.orders_products_status!=5");
	//echo "SELECT o.customers_id,s.start_date,s.sessions_id from  " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS . " o where s.sessions_id=op.products_id and o.orders_id=op.orders_id and op.orders_products_id='" . (int)$id . "' and op.orders_products_status!=5";
	$customer_result=tep_db_fetch_array($customer_query);
	$customer_id=(int)$customer_result['customers_id'];

	$events_query=tep_db_query("SELECT " . tep_event_fields_list() . " from "  . TABLE_EVENTS . " e where e.events_id='" . $events_id . "'");
	$events_result=tep_db_fetch_array($events_query);
	
	return tep_check_session_free($customer_result,$events_result,'R',$customer_id);
 }

 // get the waitlist name
 function tep_get_waitlist_name($events_id,$sessions_id,$id=0){
	$customer_query=tep_db_query("SELECT o.customers_id,s.start_date,s.sessions_id from  " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_EVENTS_SESSIONS . " s, " . TABLE_ORDERS . " o where s.sessions_id=op.products_id and o.orders_id=op.orders_id and op.orders_products_id='" . (int)$id . "' and op.orders_products_status!=5");
	$customer_result=tep_db_fetch_array($customer_query);
	$customer_id=(int)$customer_result['customers_id'];

	$events_query=tep_db_query("SELECT " . tep_event_fields_list() . " from "  . TABLE_EVENTS . " e where e.events_id='" . $events_id . "'");
	$events_result=tep_db_fetch_array($events_query);
	
	return tep_find_waitlist_group($events_id,$sessions_id,$customer_id,$events_result);
 }

// get the instructor total amount to be paid for given event
 function tep_get_instructor_event_rate(&$events,$sessions_id,$table){
 	//fetch the total amount for the instructor assigned to event
	// GP -Gross Percentage SP -Percentage per student fee MU -Multiple Rate per student FL-Flat rate
	$rate=0.0;	
	if (sizeof($events)<=0) return $rate;
	$rate_type=$events["instructors_rate_type"];
	$count_query=tep_db_query("SELECT count(customers_id) as total,sum(final_price) as total_amount from " . $table . " where sessions_id='" . $sessions_id . "' group by sessions_id");
	$count_result=tep_db_fetch_array($count_query);
	$total_students=(tep_not_null($count_result["total"])?$count_result["total"]:0);
	if ($total_students<=0) return $rate;
	if ($rate_type=="FL") {// flat rate
		$rate=$events["instructors_base_rate"];
		return $rate;
	}
	if ($rate_type=='MU') { // multiple student
		$rate=($events["instructors_rate"]*$total_students)+$events["instructors_base_rate"];
		return $rate;
	}
	if ($rate_type=='GP'){ // gross percentage
		/*$rate_query="SELECT sum(op.final_price) as total_amount from " . TABLE_EVENTS_ATTENDEES_CONFIRM . " where sessions_id='" . $sessions_id . "' and paid='N' group by sessions_id");
		$rate_result=tep_db_fetch_array($rate_query);*/
		$amount=(float)$count_result["total_amount"];
		$rate=$events["instructors_base_rate"]+$amount*$events["instructors_rate"]/100;
	}
	return $rate;
 }
 // update the session start date and end date for the recursive session in the event table. It is used for easy access
 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"])?$session_result["first_date"]:'0000-00-00 00:00:00') . "', sessions_end_date='" . (($session_result["last_date"])?$session_result["last_date"]:'0000-00-00 00:00:00') . "' where events_id='" . $events_id . "'");
	}
 }
 
 // round the given amount according to round factor
 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;
 }

 // utility function to prepare hidden fields
 function tep_prepare_hidden_params($keys,$mode='post',$output='post',$check_array=array()){
 	global $HTTP_POST_VARS,$HTTP_GET_VARS;
	$result="";
	if ($mode=='post'){
		for ($icnt=0;$icnt<sizeof($keys);$icnt++){
			if (isset($HTTP_POST_VARS[$keys[$icnt]])){
				if ($output=='post'){
					$result.= '<input type="hidden" name="' . $keys[$icnt] . '" value="' . htmlspecialchars(stripslashes($HTTP_POST_VARS[$keys[$icnt]])) . '">';
				} else {
					$result.=$keys[$icnt] . "=" . stripslashes($HTTP_POST_VARS[$keys[$icnt]]) . "&";
				}
			}
		}
	} else if ($mode=='get') {
		for ($icnt=0;$icnt<sizeof($keys);$icnt++){
			if (isset($HTTP_GET_VARS[$keys[$icnt]])){
				if ($output=='post'){
					$result.= '<input type="hidden" name="' . $keys[$icnt] . '" value="' . htmlspecialchars(stripslashes($HTTP_GET_VARS[$keys[$icnt]])) . '">';
				} else {
					$result.=$keys[$icnt] . "=" . stripslashes($HTTP_GET_VARS[$keys[$icnt]]) . "&";
				}
			}
		}
	} else {
		for ($icnt=0;$icnt<sizeof($keys);$icnt++){
			if (isset($check_array[$keys[$icnt]])){
				if ($output=='post'){
					$result.= '<input type="hidden" name="' . $keys[$icnt] . '" value="' . htmlspecialchars(stripslashes($check_array[$keys[$icnt]])) . '">';
				} else {
					$result.=$keys[$icnt] . "=" . stripslashes($check_array[$keys[$icnt]]) . "&";
				}
			}
		}
	}
	return $result;
 }
 // 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];
	}
	$date_details['d']=sprintf("%02d",$date_details['d']);
	$date_details['m']=sprintf("%02d",$date_details['m']);
	return $date_details['y'] . '-' . $date_details['m'] . '-' . $date_details['d']; 
 }
 // utility function to get the total no of renewal users count for given date
function tep_get_renewal_users_count_dated(&$events,$customer_id=0,$check_date="",$given_date="")
{
	$count=0;
	$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="'" . getServerDate(true) . "' ";

	$curdate=$given_date;
	if ($customer_id>0)
		$customer_check=" and o.customers_id!='" . $customer_id . "' ";
	
	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_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'){
		$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=$given_date;
		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;
}

// utility function used in presenting customized event selection box.
function tep_get_event_select_header($url,$left_text,$image){
	global $events_id,$selected_name;
	$events_array=tep_get_events_display_tree();
	$result.='<tr><td>' . tep_draw_separator('pixel_trans.gif', '1', '10') . '</td></tr>';
	$result='<tr><td>' . tep_draw_form('select_event',$url) . 
			'<table border="0" cellspacing="0" cellpadding="2">' .
			'<div id="event_list" style="position:absolute;left:242px;top:130px;display:none;width:400px">' .
			tep_draw_event_select_menu('select_id',$events_array,$events_id,'size=10 onClick="javascript:setListboxText(0);" class="customerSelect"') .
			'</div>' .
			'<tr height=20>' .
			'<td class="main" width="100">' . $left_text . '</td>' .
			'<td class="main">' . tep_draw_input_field('select_text',$selected_name,'onFocus="javascript:toggleList(1);" onBlur="javascript:toggleList(0);" style="width:400px"') . '</td>' .
			'<td class="main" valign=center>' . tep_image_submit('button_select.gif',$image,'align=absmiddle size=') . '</td>' .
			'</tr>' .
			'</table></td></tr>' .
			'</form>' .
			'<script language="JavaScript">' .
			'if(na6) document.select_event.select_text.addEventListener("keyup",selectList,true);' .
			'if(iex) document.select_event.select_text.onkeyup=selectList;' .
			'if(na6) document.select_event.select_text.addEventListener("keydown",scrollList,true);' .
			'if(iex) document.select_event.select_text.onkeydown=scrollList;' .
			'</script>';
	$result.='<tr><td>' . tep_draw_separator('pixel_trans.gif', '1', '10') . '</td></tr>';
	return $result;
}

// form the html content for accepting question answer
	 function tep_get_question_input($type){
   $result='';
   $param="size=30 maxlength=100";

     // question type is text or numeric
    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'){ // question type is date
       $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>';
 }
 // form the html content for accepting question answer with html tables
	 function tep_get_question_input_table(&$question_result){
   $result='';
   $param="size=30 maxlength=100";

   $type=$question_result["answer_type"];

	// if the question is text or numeric
    if ($type=='T' || $type=='N'){
		if ($type=='N') $param="size=15 maxlength=10";
       $result.='<td class="main">' . tep_draw_input_field('question_value_data','',$param) . '<font color="red">&nbsp;*</font></td>';
    } else if ($type=='D'){ // if the question is date
       $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.='<td class="main" valign="top">' . tep_draw_pull_down_menu('question_month',$month_array) . '</td>';
		   $day_array=array();
		   for($icnt=0;$icnt<=31;$icnt++){
			$text=$icnt;
			if ($icnt==0) $text='';
			  $day_array[]=array('id'=>$icnt,'text'=>$text);
			}  
	       $result.='<td class="main" valign="top">' . tep_draw_pull_down_menu('question_day',$day_array) . '</td>';
       $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.='<td class="main" valign="top">' . tep_draw_pull_down_menu('question_year',$year_array);
	   $result.='<font color="red">&nbsp;*</font></td>';
    }
    return $result;
 }
 // function for survey type
	function survey()
	{
	   $survey_event=array('RV'=>TEXT_RV,'WV'=>TEXT_WV,'FV'=>TEXT_FV);
	   while(list($value)=each($survey_event)){
       
	   }
	   return $survey_events[$type];	   
	}
 // get the current server date considering date offset settings
 function getServerDate($time=false){
   /*$curTime=mktime();
	$offset=(float)EVENTS_SERVER_DATE_OFFSET;
	if ($offset>=-23.5	&& $offset<=23.5) {
		$hour=abs($offset);
		$min=$offset-$hour;
		$delta = @mktime($hour,$min,0,1,1,1970);
		if ($offset>0)
			$curTime=$curTime + $delta;
		else
			$curTime=$curTime - $delta;
	}
	if ($time){
		return date('Y-m-d H:i:s',$curTime);
	} else {
		return date('Y-m-d',$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($time)
				return date('Y-m-d H:i:s',$cur_offset_time);
			else
				return date('Y-m-d',$cur_offset_time);
		}else{
			$cur_offset_time = mktime(date('H')+abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($time)
				return date('Y-m-d H:i:s',$cur_offset_time);
			else
				return date('Y-m-d',$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($time)
				return date('Y-m-d H:i:s',$cur_offset_time);
			else
				return date('Y-m-d',$cur_offset_time);
		}else{
			$cur_offset_time = mktime(date('H')-abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($time)
				return date('Y-m-d H:i:s',$cur_offset_time);
			else
				return date('Y-m-d',$cur_offset_time);
		}
	}
 }
 
 // remove event related details 
  function tep_remove_order_events($order_id, $restock = false) {
    if ($restock == 'on') {
      $order_query = tep_db_query("select products_id, products_quantity from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . (int)$order_id . "' and products_type='P'");
      while ($order = tep_db_fetch_array($order_query)) {
        tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = products_quantity + " . $order['products_quantity'] . ", products_ordered = products_ordered - " . $order['products_quantity'] . " where products_id = '" . (int)$order['products_id'] . "'");
      }
    }
	/*$customer_query=tep_db_query("select customers_id from ".TABLE_ORDERS." where orders_id='".(int)$order_id."'");
	$customer_result=tep_db_fetch_array($customer_query);
	
	$attendee_query=tep_db_query("select * from ".TABLE_CUSTOMERS_TO_CUSTOMERS." where orders_id='".(int)$order_id."' and customer_id!='".(int)$customer_result['customers_id']."'");
	if(tep_db_num_rows($attendee_query)){
		while($attendee_result=tep_db_fetch_array($attendee_query)){
			$other_attendee=tep_db_query("select * from ".TABLE_CUSTOMERS_TO_CUSTOMERS." where customer_id='".$attendee_result['customer_id']."' and orders_id!='".(int)$order_id."'");
			if(tep_db_num_rows($other_attendee)<=0){
				tep_db_query("delete from " . TABLE_CUSTOMERS." where customers_id='".(int)$attendee_result['customer_id']."'");
				tep_db_query("delete from " . TABLE_ADDRESS_BOOK . " where customers_id='".(int)$attendee_result['customer_id']."'");
			}
		}*/
	tep_db_query("delete from " . TABLE_CUSTOMERS_TO_CUSTOMERS ." where orders_id='".(int)$order_id."'");
 	//}
    tep_db_query("delete from " . TABLE_ORDERS . " where orders_id = '" . (int)$order_id . "'");
    tep_db_query("delete from " . TABLE_ORDERS_EVENTS_ANSWERS . " where orders_id = '" . (int)$order_id . "'");
    tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . (int)$order_id . "'");
    tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_id = '" . (int)$order_id . "'");
    tep_db_query("delete from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id = '" . (int)$order_id . "'");
    tep_db_query("delete from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . (int)$order_id . "'");
	tep_db_query("delete from " . TABLE_WALLET_HISTORY . " where orders_id = '" . (int)$order_id . "'");
	
	//Support Packs
	$order_packs_query=tep_db_query("select support_packs_id from " . TABLE_ORDERS_PRODUCTS_SUPPORT_PACKS . " where orders_id='" . (int)$order_id . "'");
	if(tep_db_num_rows($order_packs_query)>0){
		while($order_packs_result=tep_db_fetch_array($order_packs_query)){
			tep_db_query("delete from " . TABLE_SUPPORT_PACKS_LICENSE . " where support_packs_id='" . $order_packs_result['support_packs_id'] . "'");
			tep_db_query("delete from " . TABLE_SUPPORT_PACKS_ORDER_HISTORY . " where support_pack_id='" . $order_packs_result['support_packs_id'] . "'");
		}
		tep_db_query("delete from " . TABLE_ORDERS_PRODUCTS_SUPPORT_PACKS . " where orders_id='" . (int)$order_id . "'");
	}//Support Packs
  }
	
	// utility function to get the input parameter
	function get_request_param($key,$type="numeric",$default=""){
		$success=true;
		if (!isset($HTTP_GET_VARS[$key])){
			$success=false;
		} else if ($type=="N" && !is_numeric($HTTP_GET_VARS[$key])){
			$success=false;
		}
		if ($success){
			return $HTTP_GET_VARS[$key];
		} else {
			if ($default!="") return $default;
			if ($type=="N") return 0;
			return "";
		}
	}
	// function to get events display title including event name,time,location
	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;
	}
	// write  content to a text file
	function tep_write_text_file($filename,&$content){
		$filename=DIR_FS_CATALOG . '/images/' . $filename;
		if (file_exists($filename)){
			unlink($filename);
		}
		$fp=@fopen($filename,"w");
		if ($fp){
			fwrite($fp,$content,strlen($content));
			fclose($fp);
		}
	}
	function tep_get_report_name($idValue){
		$idValue=strtolower($idValue);
		$name="";
		switch($idValue){
			case "rs":
				$name=FILENAME_REPORTS_SHIPPING;
				break;
			case 'rdc':
				$name=FILENAME_REPORTS_DISCOUNT_COUPON;
				break;
			case "ct":
				$name=FILENAME_CUSTOMER_DETAILS;
				break;
			case "ev":
				$name=FILENAME_EVENTS_ATTENDEES;
				break;
			case "rev":
				$name=FILENAME_REPORTS_VECHICLE;
				break;
			case "bl":
				$name=FILENAME_BIRTHDAY_LIST;
				break;
			case "dr":
				$name=FILENAME_DAILY_RESERVATIONS;
				break;
			case "up":
				$name=FILENAME_UNPAID_PAYMENTS;
				break;
			case "up_sub":
				$name=FILENAME_UNPAID_SUBSCRIPTIONS;
			break;
			case "cl":
				$name=FILENAME_CALL_CENTRE_ORDERS;
				break;
			case "iv":
				$name=FILENAME_INVENTORY;
				break;
			case "en":
				$name=FILENAME_EVENTS_NON_RETURNS;
				break;
			case "at":
				$name=FILENAME_ATTENDANCE_ANALYSIS;
				break;
			case "ps":
				$name=FILENAME_PRODUCTS_SALES;
				break;
			case "ss_sub":
				$name=FILENAME_SUBSCRIPTIONS_SALES;
				break;
			case "es":
				$name=FILENAME_EVENTS_SALES;
				break;
			case "ip":
				$name=FILENAME_INSTRUCTOR_PAYMENTS;
				break;
			case "pp":
				$name=FILENAME_PENDING_PAYMENTS;
				break;
			case "sud":
				$name=FILENAME_SUBSCRIPTION_DETAILS;
				break;
			case "ec":
				$name=FILENAME_EVENT_CHECKIN;
				break;
			case "ret":
				$name=FILENAME_EVENT_TICKET;
				break;
			case "ric":
				$name=FILENAME_EVENTS_REPORT_IDCARDS;
				break;
			case "snr":
				$name=FILENAME_SUBSCRIPTION_NON_RENEWALS;
				break;
			case "sun":
				$name=FILENAME_SUBSCRIPTION_RENEWALS;
				break;
			 case "sr":
			    $name=FILENAME_SEARCH_RESERVATIONS;
				break;
			 case "aop":
			    $name=FILENAME_AO_PAYMENTS;
			    break;
			 case "waup":
			 	$name=FILENAME_REPORTS_WALLET;
				break;
			case "pc":
				$name=FILENAME_REPORTS_PRODUCTS_RECONCILIATION;
				break;
			case "si":
				$name=FILENAME_INSTRUCTOR_RESERVATIONS;
				break;
			case "dd":
				$name=FILENAME_REPORTS_DIRECT_DEPOSIT;
				break;	
			case "rscl":
				$name=FILENAME_SERVICES_CALL_CENTRE_ORDERS;
				break;
			case "rr":
				$name=FILENAME_PRODUCTS_REFUNDS;
				break;
			case "rspo":
				$name=FILENAME_SERVICES_PENDING_ORDERS;
				break;	
			case 'gvq':
				$name=FILENAME_PRODUCTS_SALES;
				break;	
			case 'sdc':
				$name=FILENAME_DISCOUNT_COUPONS;
				break;
		}
		return tep_href_link($name,"return=1");
	}
	function tep_get_report_params(){
		global $input_params;
		$result="";
		$params=$input_params;
		if (sizeof($params)>0){
			reset($params);
			while(list($key,$value)=each($params)){
				if (!is_array($value)){
					if ($key!="post_action" && $key!='new_status' && $key!='X' && $key!='Y' && $key!='page')
						$result.='<input type="hidden" name="' . $key . '" value="' . htmlentities(stripslashes($value)) . '">';
				}
			}
		}
		return $result;
	}
	/*function tep_get_events_display_text($events_id){
		global $languages_id;
		$event_style=EVENTS_NAME_STYLE;
		
		$event_query=tep_db_query("SELECT ed.events_name,e.events_start_time,e.events_location,rs.*,l.location_name from " . TABLE_EVENTS . " e, " . TABLE_EVENTS_DESCRIPTION . 
						" ed LEFT JOIN " . TABLE_RECURSIVE_SESSIONS . " rs on e.events_id=rs.events_id LEFT JOIN " . 
						TABLE_EVENTS_LOCATIONS . " l on l.location_id=e.events_location where e.events_id=ed.events_id and ed.language_id='" . $languages_id . "'" .
						" and e.events_id='" . $events_id . "'");
		
		$event_result=tep_db_fetch_array($event_query);
		
		if (!($event_style=="ET" || $event_style=="EL" || $event_style=="ETL")) return $event_result["events_name"];
		
		$result="";
		$style_splt=preg_split('//', $event_style, -1, PREG_SPLIT_NO_EMPTY);

		 //$days_array=array('1'=>'Sunday','2'=>'Monday','3'=>'Tuesday','4'=>'Wednesday','5'=>'Thursday','6'=>'Friday','7'=>'Saturday');
		$days_array=array('1'=>'Mon','2'=>'Tues','3'=>'Wed','4'=>'Thur','5'=>'Fri','6'=>'Sat','7'=>'Sun');
		$count_array=array('1'=>'first','2'=>'second','3'=>'third','4'=>'fourth');
		$months_array=array('1'=>'Jan','2'=>'Feb','3'=>'Mar','4'=>'Apr','5'=>'May','6'=>'Jun','7'=>'Jul','8'=>'Aug','9'=>'Sep','10'=>'Oct','11'=>'Nov','12'=>'Dec');

		for ($icnt=0;$icnt<sizeof($style_splt);$icnt++){
			switch($style_splt[$icnt]){
				case "E":
					$result[]=$event_result["events_name"];
					break;
				case "T":
					$type=$event_result['sessions_type_option'];
					$result_text="";
					switch($type){
						case 'DD':
							if ($event_result['sessions_type_daily_days']<=1){
								$result_text=TEXT_DAILY_DAY;}
							else
								$result_text=sprintf(TEXT_DAILY_DAYS,$event_result['sessions_type_daily_days']);
							break;
						case 'WW':
							$temp_string=$event_result['sessions_type_weekly_days'];
							$day_string="";
							for ($icnt=0;$icnt<strlen($temp_string);$icnt++){
								if (substr($temp_string,$icnt,1)=='1'){
									if ($day_string!='') $day_string=$day_string . ", ";
										$day_string=$day_string . $days_array[$icnt+1];
									}
								}
							$result_text=$day_string;
							break;
						case 'MD':
							if ($event_result['sessions_type_monthly_months']>1)
								$result_text=sprintf(TEXT_MONTHLY_DAYS,$event_result['sessions_type_monthly_months'],$event_result['sessions_type_monthly_days']);
							else
								$result_text=sprintf(TEXT_MONTHLY_DAY,$event_result['sessions_type_monthly_days']);
							break;
						case 'MM':
							if ($event_result['sessions_type_monthly_weekmonths']>1)
								$result_text=sprintf(TEXT_MONTHLY_WEEKS,$event_result['sessions_type_monthly_weekmonths'],$count_array[$event_result['sessions_type_monthly_weeks']],$days_array[$event_result['sessions_type_monthly_weekdays']]);
							else
								$result_text=sprintf(TEXT_MONTHLY_WEEK,$count_array[$event_result['sessions_type_monthly_weeks']],$days_array[$event_result['sessions_type_monthly_weekdays']]);	  
							break;
						case 'YM':
							$result_text=sprintf(TEXT_YEARLY_MONTHS,$months_array[$event_result['sessions_type_yearly_months']],$event_result['sessions_type_yearly_monthdays']);
							break;
						case 'YY':
							$result_text=sprintf(TEXT_YEARLY_WEEKS,$count_array[$event_result['sessions_type_yearly_weeks']],$days_array[$event_result['sessions_type_yearly_weekdays']],$months_array[$event_result['sessions_type_yearly_weekmonths']]);
							break;
					}// switch $type
					$dayLight=strtolower(date("A",strtotime($event_result["events_start_time"])));
					$result[]=$result_text . ($dayLight=="pm"?" Night":"");
					break;
				case "L":
					$result[]=$event_result["location_name"];
					break;
			} // switch event style
		} // for $icnt
			return join(" - ",$result);
	}*/
	
// finding a current version 
	function tep_check_current_version()
	{
		global $PHP_SELF,$site_version_available;		
		$cur_content=@file_get_contents(DIR_FS_CATALOG."version.txt");
		$cur_content=strtolower($cur_content);
		$start_pos=strpos($cur_content,"<program_version>");
		if ($start_pos===false) return;
		$end_pos=strpos($cur_content,"</program_version>");
		if ($end_pos===false) return;
		$cur_version=substr($cur_content,$start_pos+17,$end_pos-($start_pos+17));		
		//$config_version=split(",",CURRENT_VERSION);				
		$result="";
		$cur_date=date('Y-m-d');
		
		//if ($config_version[0]==0 || ($config_version[0]==1 && $config_version[1]==$cur_date))
		//$site_content=@file_get_contents("http://www.zac-ware.com/fileadmin/freeway/freeway.xml");
		if(!tep_session_is_registered('site_version_available')) {
			$site_content=@file_get_contents("http://www.zac-ware.com/fileadmin/freeway/freeway.xml");
			//$site_content=@file_get_contents(".../freeway.xml");
			$site_content=strtolower($site_content);
			$start_pos=strpos($site_content,"<program_version>");
			if ($start_pos===false) return;
			$end_pos=strpos($site_content,"</program_version>");
			if ($end_pos===false) return;
			$site_version_available=substr($site_content,$start_pos+17,$end_pos-($start_pos+17));
			tep_session_register('site_version_available');
		}
		$cur_version_temp=split("[.]",$cur_version);
		$site_version_temp=split("[.]",$site_version_available);
		$check_version = sizeof($site_version_temp);
		$version_updation = false;
		if(sizeof($site_version_temp)<sizeof($cur_version_temp))
			$check_version = sizeof($cur_version_temp);
		for($i=0;$i<$check_version;$i++){
			if(!$site_version_temp[$i])$site_version_temp[$i]=0;
			if(!$cur_version_temp[$i])$cur_version_temp[$i]=0;
			if($site_version_temp[$i]>$cur_version_temp[$i]){
				$version_updation = true;
				break;
			}else if($site_version_temp[$i]<$cur_version_temp[$i]){
				$version_updation = false;
				break;
			}
		}
		//$cur_version_temp=(int)str_replace(".","",$cur_version);
		//$site_version_temp=(int)str_replace(".","",$site_version);
		//if($cur_version_temp<$site_version_temp)
					
		if ($version_updation) {
			$result.='  <table border="0" cellpadding="0" cellspacing="0" width="95%" height="20" class="cell_bg_versionm" align="center">
							<tr>
								<td valign="top" width="5">' . tep_image(DIR_WS_IMAGES . "/template/cell_bg_versionl.gif","") . '</td>
								<td valign="top" style="padding-top:5px">
								<table border="0" cellpadding="0" cellspacing="0" id="version">
									<tr>
										<td valign="top" class="versionTitle">' . tep_image(DIR_WS_IMAGES . '/template/img_version.gif','','','','align=left') . '&nbsp;' . TEXT_UPDATE_VERSION . '
										</td>
									</tr>
									<tr>
										<td valign="top" class="minText" align="center">' .TEXT_UPDATE_VERSION_INFO . '</td>
									</tr>
								</table>
								</td>
								<td valign="top" width="5">' . tep_image(DIR_WS_IMAGES . "/template/cell_bg_versionr.gif","") . '</td>
							</tr>
						</table>
					 ';
		} else {
			/*$result.='  <table border="0" cellpadding="0" cellspacing="0" width="95%" height="71" class="cell_bg_versionm" align="center">
							<tr>
								<td valign="top" width="5">' . tep_image(DIR_WS_IMAGES . "/template/cell_bg_versionl.gif","") . '</td>
								<td valign="top" style="padding-top:5px" class="versionTitle">' . sprintf(TEXT_FREEWAY_VERSION,$cur_version) . '</td>
								<td valign="top" width="5">' . tep_image(DIR_WS_IMAGES . "/template/cell_bg_versionr.gif","") . '</td>
							</tr>
						</table>
					 ';*/
			$result.=sprintf(TEXT_FREEWAY_VERSION,$cur_version);
		}
		//}
		return $result;
	}
	
function current_version(){
	$cur_content=@file_get_contents(DIR_FS_CATALOG."version.txt");
	$cur_content=strtolower($cur_content);
	$start_pos=strpos($cur_content,"<program_version>");
	if ($start_pos===false) return;
	$end_pos=strpos($cur_content,"</program_version>");
	if ($end_pos===false) return;
	$cur_version=substr($cur_content,$start_pos+17,$end_pos-($start_pos+17));
	return 'Freeway ' . '&nbsp;' . $cur_version;
}
// 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;
  }

// 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_get_customers_groups_id($customer_id) {
    $customers_groups_query = tep_db_query("select customers_groups_id from " . TABLE_CUSTOMERS . " where customers_id =  '" . $customer_id . "'");
    $customers_groups_id = tep_db_fetch_array($customers_groups_query);
    return $customers_groups_id['customers_groups_id'];
  }
  function tep_get_products_special_price($product_id,$customer_id) {
    $customer_groups_id = tep_get_customers_groups_id($customer_id);

	$specials_query = tep_db_query("select specials_new_products_price,customers_id,customers_groups_id from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "' and status = '1'");

    if (tep_db_num_rows($specials_query)) {
      $special = tep_db_fetch_array($specials_query);
	  	if ($customer_id>0 && $customer_id==$special["customers_id"]){
		  $special_price = $special['specials_new_products_price'];
		} else if ($customer_groups_id>0 && $customer_groups_id==$special["customers_groups_id"]){
		  $special_price = $special['specials_new_products_price'];
		} else if ($special["customers_id"]<=0 && $special["customers_groups_id"]<=0){
		  $special_price = $special['specials_new_products_price'];
		} else {
			$special_price=false;
		}
    } else {
	  $special_price = false;
    }
	
	return $special_price;
  }
  //get discount price from products
  function tep_get_products_discount_price($products_price,$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_cfg_hide_from_backend($id,$key='')
	{
	    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
		$hide_backend_array = array(array('id' =>TEXT_PRODUCTS,'text'=>TEXT_PRODUCTS),array('id'=>TEXT_EVENTS,'text'=>TEXT_EVENTS),array('id'=>TEXT_SUBSCRIPTIONS,'text'=>TEXT_SUBSCRIPTIONS),array('id'=>TEXT_SERVICES,'text'=>TEXT_SERVICES),array('id'=>TEXT_INSTRUCTOR,'text'=>TEXT_INSTRUCTOR));
		return tep_draw_pull_down_menu($name, $hide_backend_array, $id);	
	} 
  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_discount_price($products_id,$products_price,$products_tax,$customer_id)
  {  
    $empty=0;
	$result_array=array();
	$count_customer_query=tep_db_query("select customers_groups_id,customers_id,specials_new_products_price from " . TABLE_SPECIALS ."");
	$count_customer_value=tep_db_fetch_array($count_customer_query);
	$ap_customer_id=$count_customer_value['customers_id'];
	$ap_customer_group_id=$count_customer_value['customers_groups_id'];
	$ap_price=$count_customer_value['specials_new_products_price'];
	if($ap_customer_group_id==0 && $ap_customer_id==0 && ($ap_price!='' || $ap_price!=0)){
      $query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id='" . $products_id . "'");
	}else {  
	  $query = tep_db_query("select specials_new_products_price from " . TABLE_CUSTOMERS . " c," . TABLE_SPECIALS . " s where s.products_id='" . $products_id . "' and ((s.customers_id ='" . $customer_id ."' and s.customers_id=c.customers_id) or (c.customers_id='". $customer_id ."' and s.customers_groups_id=c.customers_groups_id))");
	}
	$query_result = tep_db_fetch_array($query);
	$products_special_price = $query_result['specials_new_products_price'];
		if(($ap_customer_group_id!=0 || $ap_customer_id!=0) || ($ap_customer_group_id==0 && $ap_customer_id==0 && $ap_price!=0) ){
		  $result_array=array('id'=>'SP','text'=>tep_add_tax($products_special_price, $products_tax));
	      return  $result_array;
		}else if($ap_price==0 && ($ap_customer_id==0 && $ap_customer_group_id==0)) {
		     $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;
				$result_array=array('id'=>'GD','text'=>$products_price);
			 } else {
				$products_price = $products_price - $products_price * abs($customer_discount) / 100;
			   $result_array=array('id'=>'GD','text'=>$products_price);
			 }
			 return $result_array; 
		}else {
		  return $empty;
		}
  }
  function tep_product_small_image($image,$title,$parameters=""){
	if (file_exists(DIR_FS_CATALOG_IMAGES . "small/" . $image)){
		return tep_image(DIR_WS_CATALOG_IMAGES . "small/" . $image,$title,'','',$parameters);
	} else if (file_exists(DIR_FS_CATALOG_IMAGES . "big/" . $image)){
		return tep_image(DIR_WS_CATALOG_IMAGES . "big/" . $image,$title,SMALL_IMAGE_WIDTH,SMALL_IMAGE_HEIGHT,$parameters);
	} else if (file_exists(DIR_FS_CATALOG_IMAGES . $image)){
		return tep_image(DIR_WS_CATALOG_IMAGES . $image,$title,SMALL_IMAGE_WIDTH,SMALL_IMAGE_HEIGHT,$parameters);
	} else { 
		return TEXT_IMAGE_DOES_NOT_EXIST;
	}
  }
  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_CATALOG . DIR_WS_IMAGES . "small/" . $image . '" width=50 height=50>';
	} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
		return '<img src="' . HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . "big/" . $image . '" width=50 height=50>';
	} else if(file_exists(HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . $image)) {
		return '<img src="' . HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . $image . '" width=50 height=50>';
	} else {
		return tep_image(DIR_WS_IMAGES . 'pixel_trans.gif','', '50','50');
	}
  }	
  function tep_get_products_stock($products_id) {
    $products_id = tep_get_prid($products_id);
    $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
    $stock_values = tep_db_fetch_array($stock_query);

    return $stock_values['products_quantity'];
  }

////
// Check if the required stock is available
// If insufficent stock is available return an out of stock message
  function tep_check_stock($products_id, $products_quantity) {
    $stock_left = tep_get_products_stock($products_id) - $products_quantity;
    $out_of_stock = '';

    if ($stock_left < 0) {
      $out_of_stock = '<span class="markProductOutOfStock">' . STOCK_MARK_PRODUCT_OUT_OF_STOCK . '</span>';
    }

    return $out_of_stock;
  }
  
    function tep_get_attributes_stock($products_id,$attribute_id) {
    $products_id = tep_get_prid($products_id);
	$attribute_id=tep_get_sorted_attribute_ids($attribute_id);
	$stock_sql = "select products_quantity from " . TABLE_PRODUCTS_STOCK . " where products_id = '" . (int)$products_id . "' and attributes_id='". $attribute_id."'";
	$stock_query = tep_db_query($stock_sql);
	//echo "select products_attributes_quantity from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "' and options_id='".$options_id."' and options_values_id='".$values_id."'";
    $stock_values = tep_db_fetch_array($stock_query);
    return $stock_values['products_quantity'];
  }
  
  
  // Add an option in Products Expected to email all customers 
  //who have been waiting for news about an out of stock item. 

 
   function tep_productsexpected($products_id){
   
   $prod_att=tep_db_query("select pa.products_id,pa.attributes_id from " . TABLE_PRODUCTS_STOCK ." pa where pa.products_id='". $products_id ."' group by pa.attributes_id ,pa.products_id");
				$num_rows=tep_db_num_rows($prod_att);
				if ($num_rows>0) {    
					  while ($prod_att_result = tep_db_fetch_array($prod_att)) {
					  
					  $att_id=$prod_att_result['attributes_id'];
					 
					  $id_splt=split("-",$att_id);
					  for($inc=0;$inc<count($id_splt);$inc++)
					  {
					  $option_values=split('{',$id_splt[$inc]);
					 
					  $att_value=tep_db_query("select po.products_options_name,po.products_options_id,pov.products_options_values_name,pov.products_options_values_id from " . TABLE_PRODUCTS_OPTIONS ." po ," . TABLE_PRODUCTS_OPTIONS_VALUES . " pov ," . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " povp, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where po.products_options_id=povp.products_options_id and pov.products_options_values_id=povp.products_options_values_id and pa.options_id=po.products_options_id and pa.options_values_id=pov.products_options_values_id and pa.products_id='".$prod_att_result['products_id']."' and po.products_options_id = '".$option_values[0]."' and pov.products_options_values_id='".$option_values[1]. "' ");
                      $att_value_result = tep_db_fetch_array($att_value);
					  $att_op_name.= $att_value_result['products_options_name'].'-'.$att_value_result['products_options_values_name'].'<br>';
				
					  }
					  }
					  }
					  else 
					  {
					  $att_op_name="No Attributes";
					  }
					  
					
    return $att_op_name;
   }
  
////
// Check if the required stock is available
// If insufficent stock is available return an out of stock message
  function tep_check_attribute_stock($products_id, $attribute_id,$products_quantity) {
    $stock_left = tep_get_attributes_stock($products_id,$attribute_id) - $products_quantity;
    $out_of_stock = '';

    if ($stock_left <0) {
      $out_of_stock = '<span class="markProductOutOfStock">' . STOCK_MARK_PRODUCT_OUT_OF_STOCK . '</span>';
    }
    return $out_of_stock;
  }
  
function tep_get_sorted_attribute_ids($att_ids)
{
	$attribute_array=split('-',$att_ids);
	for($inc=0;$inc<count($attribute_array);$inc++)
	{
		$option_values=split('{',$attribute_array[$inc]);
		$attrb_list[$option_values[0]]=substr($option_values[1],0,-1);
	}
	ksort($attrb_list);
	reset($attrb_list);
	$attribute_id="";
	while (list($key,$value)=each($attrb_list))
		$attribute_id.=$key . '{' . $value . '}-';
	$attribute_id=substr($attribute_id,0,-1);
	return $attribute_id;
}

 function tep_cfg_pull_down_prod_view($config_value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$details_arr=array(array("id"=>"BACKORDER","text"=>"BackOrder"),array("id"=>"PARTIALSHIP","text"=>"PartialShip"),array("id"=>"HOLDORDER","text"=>"Hold Order"),array("id"=>"NOBACKORDER ","text"=>"NoBackOrder"));
  	$result=tep_draw_pull_down_menu($name,$details_arr,$config_value);
	return $result;
  }

  /*function tep_get_subscription_array_single($first=''){
	
		global $languages_id;
		$subscription_array=array();
		$subscription_query=tep_db_query("SELECT su.subscription_id,sud.subscription_name from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id and language_id='" . $languages_id . "' " . SUBSCRIPTION_CONDITION_STATUS . " order by sud.subscription_name");
		
		while($subscription_result=tep_db_fetch_array($subscription_query)){
			$subscription_array[]=array('id'=>$subscription_result['subscription_id'],'text'=>$subscription_result['subscription_name']);
		}
		return $subscription_array;
	} 
	// Output a form pull down menu
	function tep_draw_subscription_select_menu($name, $values,$selected_vals,  $parameters = '', $required = false) {
		global $selected_name,$events_link;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= ' >';
		$field .= '<option style="color:#000000" value="-1">' . TEXT_ALL_SUBSCRIPTION . '</option>';
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		
		tep_get_subscription_output_tree(0,$content,$selected_vals);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}*/
	/*function tep_get_subscription_output_tree($parent_id = '0',&$content,$default) {
    global $languages_id,$selected_name,$login_id,$login_groups_type,$events_link;

	 if($events_link) $subscription_type=" and su.subscription_type in('C','S')";
	// iterate with nested category

	$subscription_category_query = tep_db_query("select suc.subscription_categories_id, sucd.subscription_categories_name, suc.parent_id from " . TABLE_SUBSCRIPTION_CATEGORIES . " suc, " . TABLE_SUBSCRIPTION_CATEGORIES_DESCRIPTION . " sucd where suc.subscription_categories_id = sucd.subscription_categories_id and sucd.language_id = '" . (int)$languages_id . "' and suc.parent_id = '" . (int)$parent_id . "' order by suc.sort_order, sucd.subscription_categories_name");
	while ($subscription_category = tep_db_fetch_array($subscription_category_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . tep_output_string($subscription_category['subscription_categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		tep_get_subscription_output_tree($subscription_category['subscription_categories_id'], $content,$default);
		$content.='</optgroup>';
	}

	// select the list of subscription of particular category
    $subscription_query=tep_db_query("select sud.subscription_name,sud.subscription_id from " . TABLE_SUBSCRIPTIONS . ' su, ' . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud, " . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sucd where sucd.subscription_categories_id='" . (int)$parent_id . "' and sud.language_id = " . (int)$languages_id . " " . SUBSCRIPTION_CONDITION_STATUS. " and su.subscription_id=sucd.subscription_id and su.subscription_id=sud.subscription_id ".$subscription_type." order by sud.subscription_name");
	while ($subscription=tep_db_fetch_array($subscription_query))
    {
		$content .= '<option style="color:#000000" value="' . tep_output_string($subscription['subscription_id']) . '"';
		if (is_array($default))
		{
		  for ($j=0; $j<sizeof($default); $j++) {
				if ($default[$j]['id'] == $subscription['subscription_id'])
				{
			        $content .= ' SELECTED';
				}
			}
		}
		elseif($default == $subscription['subscription_id']){
			$selected_name=$subscription['subscription_name'];
			$content .= ' SELECTED';
		}
		$content .= '>' . tep_output_string($subscription['subscription_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
    }    
}*/
  function tep_get_products_array_single($first=''){
		global $customer_id,$languages_id;//$customers_group_id
		$customers_group_id=tep_get_customers_groups_id($customer_id);
		if($customers_group_id == '')$customers_group_id = 0;
		if($customer_id == '')$customer_id = 0;
		$products_array=array();
		/*$products_sql = "select pd.products_name,pd.products_id from  " . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd " . 
		" where p.products_id = pd.products_id and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "' and (p.restrict_to_customers like '%," . $customer_id . ",%' OR p.restrict_to_groups like '%," . $customers_group_id . ",%' " . 
		" OR (p.restrict_to_customers = '' AND p.restrict_to_groups = ''))";*/
		$products_sql = "select pd.products_name,pd.products_id from  " . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd " . 
		" where p.products_id = pd.products_id and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "' " . 
		" OR (p.restrict_to_customers like '%," . $customer_id . ",%' OR p.restrict_to_groups like '%," . $customers_group_id . ",%') " . 
		" and ((p.restrict_to_customers='' OR ISNULL(p.restrict_to_customers)) AND (p.restrict_to_groups='' OR ISNULL(p.restrict_to_groups)))";
		" and (" . 
				"(p.restrict_to_customers = '' OR ISNULL(p.restrict_to_customers))" . 
				"and(p.restrict_to_groups = '' OR ISNULL(p.restrict_to_groups))" . 
				"OR(p.restrict_to_customers like '%," . $customer_id . ",%' OR p.restrict_to_groups like '%," . $customers_group_id . ",%')" . 
		")";
		//echo $products_sql;

		$products_query=tep_db_query($products_sql);
		while($products_result=tep_db_fetch_array($products_query)){
			$products_array[]=array('id'=>$products_result['products_id'],'text'=>$products_result['products_name']);
		}
		return $products_array;
	} 
	
	function tep_get_products_output_tree($parent_id = '0',&$content,$default,$product_category_id=0) {
    global $customer_id,$languages_id,$selected_name,$login_id,$login_groups_type; //$customer_group_id
	$customers_group_id=tep_get_customers_groups_id($customer_id);

	// iterate with nested category
	
	$products_where = "";
	if($product_category_id>0)$products_where = " and c.categories_id='" . $product_category_id . "' ";
	$categories_sql = "select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' and c.parent_id = '" . (int)$parent_id . "' " . $products_where . " order by c.sort_order, cd.categories_name";
	$categories_query = tep_db_query($categories_sql);
	while ($products_category = tep_db_fetch_array($categories_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_category_space($products_category['categories_id']) . tep_output_string($products_category['categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of products of particular category
		if($customers_group_id == '')$customers_group_id = 0;
		if($customer_id == '')$customer_id = 0;
		$products_sql = "select pd.products_name,pd.products_id from " . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd " . 
		" where p.products_id=pd.products_id and  pcd.categories_id='" . $products_category['categories_id'] . "' " . 
		" and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "' " . 
		//" and (p.restrict_to_customers like '%," . $customer_id . ",%' OR p.restrict_to_groups like '%," . $customer_group_id . ",%' OR (p.restrict_to_customers = '' AND p.restrict_to_groups = ''))";
		/*$products_sql = "select pd.products_name,pd.products_id from  " . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd " . 
		"where p.products_id = pd.products_id and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "' " . 
		*/" and (" . 
				"(p.restrict_to_customers = '' OR ISNULL(p.restrict_to_customers))" . 
				"and(p.restrict_to_groups = '' OR ISNULL(p.restrict_to_groups))" . 
				"OR(p.restrict_to_customers like '%," . $customer_id . ",%' OR p.restrict_to_groups like '%," . $customers_group_id . ",%')" . 
		")";
		$products_query=tep_db_query($products_sql);
		while ($products = tep_db_fetch_array($products_query))
		{
			$content .= '<option style="color:#000000" value="' . tep_output_string($products['products_id']) . '"';
			if (is_array($default))
			{
			  for ($j=0; $j<sizeof($default); $j++) {
					if ($default[$j]['id'] == $products['products_id'])
					{
						$content .= ' SELECTED';
					}
				}
			}
			elseif($default == $products['products_id']){
				$selected_name=$products['products_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . write_category_space($products_category['categories_id']) . tep_output_string($products['products_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}
		$content.='</optgroup>';
		tep_get_products_output_tree($products_category['categories_id'],$content,$default);
	}
}
	function write_category_space($category_id){
	    global $languages_id,$selected_name,$login_id,$login_groups_type;
		$sql = "select parent_id,c.categories_id,categories_name from " . TABLE_CATEGORIES . " c," . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id=cd.categories_id and cd.language_id = '" . (int)$languages_id . "' and c.categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_products_select_menu($name, $values,$selected_vals,  $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.=' class="inputNormal" onBlur="javascript:toggle_focus(this,1);" onFocus="javascript:toggle_focus(this,2);"';
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_ALL_PRODUCTS . '</option>';
	
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		
		tep_get_products_output_tree($initial_parent_id,$content,$selected_vals,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
function tep_cfg_pull_down_weight_unit_title($id){
  if($id=='kg')
  	$value=TEXT_KILOGRAMS;
  else if($id=='lb'	)
  	$value=TEXT_POUNDS;
	return $value;
  }
function tep_cfg_pull_down_weight_unit($id,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$weight_unit=array(array('id' => TEXT_KG,'text' =>TEXT_KILOGRAMS),array('id' =>TEXT_LP,'text' =>TEXT_POUNDS));
	    return tep_draw_pull_down_menu($name, $weight_unit, $id);

  }
  function tep_cfg_pull_down_shop_weight_unit($unit_id, $key = '') {
   $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$unit_array = array(array("id"=>"KG","text" =>TEXT_KILOGRAMS),array("id"=>"OZ","text"=>TEXT_OUNCES));
  return tep_draw_pull_down_menu($name, $unit_array, $unit_id);
 }

 function tep_cfg_pull_down_shop_weight_unit_title($unit_id){
	if($unit_id==TEXT_KG){
		return TEXT_KILOGRAMS;
	}else if($unit_id==TEXT_OZ){
		return TEXT_OUNCES;
	}
 }
////
// Break a word in a string if it is longer than a specified length ($len)

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_sku_ids($products_id,$attribute_ids=''){
		if($products_id=='') return;
		$sku_ids="";
		if($attribute_ids!=""){
			$sku_query=tep_db_query("select sku from ".TABLE_PRODUCTS_STOCK." where products_id=$products_id and attributes_id='$attribute_ids'");
			if(tep_db_num_rows($sku_query)>0){
				$sku=tep_db_fetch_array($sku_query);
				$sku_ids=$sku['sku'];
			}
		}else if($attribute_ids==""){
			$sku_query=tep_db_query("select products_sku from ".TABLE_PRODUCTS." where products_id=$products_id");
		   if(tep_db_num_rows($sku_query)>0){	
				$sku=tep_db_fetch_array($sku_query);
				$sku_ids=$sku['products_sku'];	
			}	
		}
		return $sku_ids;		
	}	
	
	// it return the new location if needed it can update the location
	function tep_template_box_align($template_id,$new_location,$column,$mode="add",$change_column=false){
		$check_query=tep_db_query("select location from " . TABLE_INFOBOX_CONFIGURATION . " where location=" . (int)$new_location . " and display_in_column='" . $column . "' and template_id='". $template_id ."'");
		if ($mode=="add"){
			if (tep_db_num_rows($check_query)>0){
				tep_db_query("UPDATE ". TABLE_INFOBOX_CONFIGURATION . " set location=location+1 where location>=" . $new_location . " and display_in_column='" . $column . "' and template_id='". $template_id ."'");
			} else if ($change_column){
				$max_query=tep_db_query("select max(location) as new_location from " . TABLE_INFOBOX_CONFIGURATION . " where display_in_column='" . $column . "' and template_id='".$template_id ."'");
				$max_result=tep_db_fetch_array($max_query);
				$new_location=(int)$max_result["new_location"];
				$new_location++;
			}
			return $new_location;
		} else {
			if (tep_db_num_rows($check_query)>0){
				tep_db_query("UPDATE ". TABLE_INFOBOX_CONFIGURATION . " set location=location-1 where location>" . $new_location . " and display_in_column='" . $column . "' and template_id='" . $template_id . "'");
			}
		}
	}
	function tep_template_box_realign($template_id,$column){
		$location=1;
		$box_query=tep_db_query("select infobox_id from " . TABLE_INFOBOX_CONFIGURATION . " where display_in_column='" . $column ."' and template_id='" . $template_id . "' and infobox_display='yes' order by location asc ");
		while($box_result=tep_db_fetch_array($box_query)){
			tep_db_query("UPDATE ". TABLE_INFOBOX_CONFIGURATION . " set location=" . $location . " where infobox_id='" . $box_result["infobox_id"] ."' and template_id='". $template_id ."'");
			$location++;
		}
	}
	
	// function to retrieve the last used files
	function tep_get_last_access_file(){
	    global $PHP_SELF,$selected_box,$HTTP_GET_VARS,$login_groups_id;  
		//print_r($HTTP_GET_VARS);
			if (isset($HTTP_GET_VARS["top"])){
				$page=basename($PHP_SELF);
				$temp_params=tep_get_all_get_params();
				setcookie("store_file_name_" . $login_groups_id,$page.'?'.$temp_params,time()+60*60*24*30);
				
				// for quick links
				/*$query=tep_db_query("select * from " . TABLE_QUICK_LINKS. " where filename='". $page ."' and login_group_id='".$login_groups_id ."'");
				if(tep_db_num_rows($query) >0 ){
					tep_db_query("update ". TABLE_QUICK_LINKS ." set count=count+1 where filename='". $page . "' and login_group_id='" . $login_groups_id ."'" );
				} else {
					tep_db_query("insert into " . TABLE_QUICK_LINKS ." (login_group_id,params,filename,count) values('". $login_groups_id ."','". $temp_params . "','" . $page ."','1')" );
				}	*/
				
  			}
	}
		
	function tep_template_box_check($template_id){
	    $temp_query=tep_db_query("SELECT * from " . TABLE_INFOBOX_CONFIGURATION . " where template_id='" . $template_id . "' and display_in_column!='left' and display_in_column='right' limit 1");
		if (tep_db_num_rows($temp_query)>0){
			tep_db_query("UPDATE " . TABLE_INFOBOX_CONFIGURATION . " set display_in_column='left' where template_id='" . $template_id . "' and display_in_column!='left' and display_in_column!='right'");
		}
		$template_query=tep_db_query("SELECT count(*) as total_location,count(location) as total_location_sum,display_in_column from " . TABLE_INFOBOX_CONFIGURATION . " where template_id='" . $template_id . "' group by display_in_column");
		
		while($template_result=tep_db_fetch_array($template_query)){
			$total_location_sum=($template_result["total_location"]*($template_result["total_location"]+1))/2;
			if ($template_result["display_in_column"]!="" && $total_location_sum!=$template_result["total_location_sum"]){
				tep_template_box_realign($template_id,$template_result["display_in_column"]);
			}
		}
	}
	  $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_cfg_pull_down_encryption_type($value,$key='') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	   $encryp_type=array(
			array('id'=>'O','text'=>PASSWORD_OSCOMMRES),   
			array('id'=>'V','text'=>PASSWORD_VBULTIN)
  		 );
	$result=tep_draw_pull_down_menu($name,$encryp_type,$value) . '&nbsp;';
	return $result;
  }
  function  tep_get_encryption_name($type='O') { 
		$pass_type=array('O'=>PASSWORD_OSCOMMRES,'V'=>PASSWORD_VBULTIN);
		return $pass_type[$type];
  }
  
	function tep_cfg_pull_down_zone_except_countries($zone_id,$except_id, $key = '') {
		$name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');

		$result.='<input type="hidden" name="' . $name . '" value="" id="' . $name . '"><br><font color="red">Please select Payment Zone</font>';
		if ($zone_id=='' || $zone_id==0) return $result;
		$result='<input type="hidden" name="' . $name . '" value="' . $except_id . '" id="' . $name . '">';
		
		$except_id="," .$except_id .",";
		$country_query = tep_db_query("select distinct co.countries_name,co.countries_id from " . TABLE_ZONES_TO_GEO_ZONES . ' gz,' . TABLE_COUNTRIES  . " co where co.countries_id=gz.zone_country_id and gz.geo_zone_id in(" . $zone_id . ") order by countries_name");
	   

		$result.='<div style="height:100px;overflow:auto;width:260px;vertical-align:top"><table border="0" width="100%" cellpadding="0" cellspacing="0" valign="top"><tr><td valign="top" class="smallText">';
		$icnt=0;
		while ($country = tep_db_fetch_array($country_query)) {
			$checked='';
			if (strpos($except_id,"," . $country['countries_id'] . ",")!==FALSE) $checked=" checked ";
			$result.='<tr><td width="5"><input class="smallCheck" type=checkbox name="check_'  . $name . '" id="check_' . $icnt . '_' . $name . '" value="' . $country['countries_id'] .'"' . $checked . ' onClick="javascript:check_selected_values(this,\'' . $name . '\');"><td class="smallText" style="line-height:8pt">' . $country['countries_name'] . '</td></tr>';
			$icnt++;
		}
		$result.='<input type="hidden" id="count_' . $name . '" value="' . ($icnt-1) . '">';
		$result.='</tr>';
		$result.='</table>';
		$result.='</div>';
		return $result;
  }
  function tep_get_zone_except_country($except_id) {

		$except_country = '';
		if ($except_id!=""){
			// Code to check the mysql query error for Defect-137
			if($except_id{strlen($except_id)-1}==',')
				$except_id=substr($except_id,0,-1);
			if($except_id{0}==',')
				$except_id=substr($except_id,1,strlen($except_id));
				
			$except_id=str_replace(",,",",",$except_id);
			$country_sql = "select countries_name from " . TABLE_COUNTRIES . " where countries_id in(" . $except_id . ")";			
			$country_query = tep_db_query($country_sql);
	
			while($country_result = tep_db_fetch_array($country_query)){
				$except_country.=$country_result["countries_name"] . ",";
			}
		}		
		if($except_country=='')$except_country = TEXT_NONE;
		else $except_country=substr($except_country,0,-1);
		return $except_country;
  }
	function tep_check_module_status(&$module,$payment_zone,$except_zone_list,$except_country_list){
		global $order;
		return true;
	  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->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;
		$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->billing['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->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;
		
/*		echo "modules=" . "<br>";
		print_r($module);
		echo "<br> . payzone";
		print_r($payment_zone);
		echo "<br>";
		print_r($except_zone_list);
		echo "<br>";
*/		
	  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_sql = "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";
        $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->delivery['zone_id']) {
            $check_flag = true;
            break;
          }
        }

        if ($check_flag == false) {
          $module->enabled = false;
        }
      }
	}
  function tep_send_products_status_change_email($order_id,$status,$orders_products_id="",$comments="") {
  		if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;

		if ((int)$order_id<=0)	return;
		
		if($status=="") return;
				
		if($status=='2') {
			$type='PRE';
		}	
		else if($status=='3') {
			$type='PRS';	
		}	
			// get mail template details
			$details_r=array();
			$details_r['type']=$type;
			$details_r['table']=TABLE_EMAIL_MESSAGES;
			tep_get_template($details_r);
	
		$add_option="";
		if($orders_products_id!="") 
			$add_option=" and op.orders_products_id='" . $orders_products_id . "' ";
		$status_query=tep_db_query("Select o.orders_status, c.customers_firstname, c.customers_lastname,c.customers_email_address, o.date_purchased, op.products_id,op.products_name, 
									op.products_price, op.products_quantity, op.orders_products_status from " . TABLE_ORDERS . " o, " .  
									TABLE_ORDERS_PRODUCTS . " op,  " . TABLE_CUSTOMERS . " c where o.orders_id='" . $order_id . "' 
									and o.orders_id=op.orders_id " . $add_option . " and op.products_type='P' and o.customers_id=c.customers_id ");
		
		
		if(tep_db_num_rows($status_query)<=0) return;
		$product_detail='<table cellpadding="0" cellspacing="0" width="100%" border="0"><tr><td>Products Name</td><td>Products Price</td><td>Products Quantity</td></tr>';
		while($status_result=tep_db_fetch_array($status_query)) {
			if($orders_products_id!="")
				$product_status=tep_get_order_status_name($status_result['orders_products_status']);
			else
				$product_status=tep_get_order_status_name($status_result['orders_status']);	
			$product_detail.='<tr><td>' . $status_result['products_name'] . '</td><td>' . $status_result['products_price'] . '</td><td>' . $status_result['products_quantity'] . '</td></tr>' ; 
			$firstname=$status_result['customers_firstname'];
			$lastname=$status_result['customers_lastname'];	
			$date_purchased=$status_result['date_purchased'];
			$to_name=$status_result['customers_firstname'] . ' ' . $status_result['customers_lastname'];
			$email_address=$status_result['customers_email_address'];		
		}
		
			$product_detail.='</table>';
			$replace_array=array(CUST_CF=>$firstname,
								 CUST_CL=>$lastname,
								 ORDR_NO=>$order_id,
								 ORDR_OP=>$date_purchased,
								 ORDR_PD=>$product_detail,
								 TEXT_P_STATUS=>$product_status,	
								 TEXT_SN=>STORE_OWNER,
								 TEXT_SM=>STORE_NAME,
								 TEXT_SE=>STORE_OWNER_EMAIL_ADDRESS,
								 TEXT_OC=>(($comments!="")?$comments:''),
								);											
			if ($details_r['html_text']!='') {
			 $replace_array=str_replace('�', " ", $replace_array);
					tep_replace_template($details_r,$replace_array);
					$details_r=str_replace('�', " ", $details_r);
					tep_strip_html($details_r);
					$details_r['to_name']=$to_name;
					$details_r['to_email']=$email_address;
					$details_r['from_name']=STORE_OWNER;
					$details_r['from_email']=STORE_OWNER_EMAIL_ADDRESS;	
					tep_send_email($details_r);				
			}
 	 }
	
 function tep_cfg_sku_length_count_option($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
 	 $sku_array=array();
 	 for($i=1;$i<=20;$i++){
 	 	$sku_array[]=array('id'=>$i,'text'=>$i);
 	 }
 	 return tep_draw_pull_down_menu($name,$sku_array,$value);
  }
  function tep_content_title_top($title,$funname='false',$hide_prev=false,$show_hidden=false,$params="",$align=false,$expand=0){


  	$heding=$title;
  	$title=str_replace(" ","_",$title);
  	$title=str_replace("\"","",$title);
	$title=str_replace("'","",$title);
  	$title=trim($title);
	/*echo '<tr>
            <td colspan="2">' . tep_draw_separator('pixel_trans.gif', '1', '15') . '</td>
          </tr>';*/
  	echo '<tr>
			<td valign="top" colspan="2">
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr height="20">' ;
					echo '<td id="img_' . $title . '" class="contentTitle" style="cursor:hand;" onClick="javascript:toggle_panel(\'' . $title .'\',\''. $funname.'\',\'' . $hide_prev . '\',\''. $expand . '\');' . $params . '">' . $heding . '</td>';
				echo '</tr>';
	if($show_hidden)
			echo '<tr id="panel_' . $title . '" style="display:none">';
	else
			echo '<tr id="panel_' . $title . '">';
				
				if($align)
					echo '<td colspan="2">';
				else
					echo'<td>';
					
				echo '<table border="0" cellpadding="0" cellspacing="0" width="100%">
			';
  }
  function tep_content_title_bottom(){
  	echo '
					</table>
				</td>
			</tr>
  			</table>
			</td>
		  </tr>';
  }
  function tep_content_title1_top($title,$funname='false',$hide_prev=false,$show_hidden=false,$params="",$align=false,$expand=0,$left_pane=0){
  		$heding=$title;
  	$title=str_replace(" ","_",$title);
  	$title=str_replace("\"","",$title);
	$title=str_replace("'","",$title);
  	$title=trim($title);
	/*echo '<tr>
            <td colspan="2">' . tep_draw_separator('pixel_trans.gif', '1', '15') . '</td>
          </tr>';*/
  	echo '<tr>
			<td valign="top" colspan="2">
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr height="20">' ;
				//if($expand>0)
					echo '<td class="contentTitle1" style="cursor:hand;" onClick="javascript:toggle_panel1(\'' . $title .'\',\''. $funname.'\',\'' . $hide_prev . '\',\''. $expand . '\');"' . $params . '"><span style="background:#FFFFFF;padding-right:5px;' . ($left_pane>0?"padding-left:$left_pane px":'') . '">' . $heding . '</span></td><td width="15" align="right"><a href="javascript:toggle_panel1(\'' . $title .'\',\''. $funname.'\',\'' . $hide_prev . '\',\''. $expand . '\');' . $params . '"><img src="images/template/panel_down.gif" id="img_' . $title . '" border="0"></a></td>';
				//else
					//echo '<td class="contentTitle1" style="cursor:hand;" onClick="javascript:toggle_panel1(\'' . $title .'\',\''. $funname.'\',\'' . $hide_prev . '\',\''. $expand . '\');"' . $params . '"><span style="background:#FFFFFF;padding-right:5px;' . ($left_pane>0?"padding-left:$left_pane px":'') . '">' . $heding . '</span></td><td width="15" align="right"><a href="javascript:toggle_panel(\'' . $title .'\',\''. $funname.'\',\'' . $hide_prev . '\',\''. $expand . '\');' . $params . '"><img src="images/template/panel_down.gif" id="img_' . $title . '" border="0"></a></td>';
				echo '</tr>
				<tr height="10">
					<td></td>
				</tr>';
	/*if($show_hidden)
			echo '<tr id="panel_' . $title .'" style="display:none">';
	else
			echo '<tr id="panel_' . $title .'">';*/
				
				if($align)
					echo '<td colspan="2">';
				else
					echo'<td>';
					
				echo '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td id="panel_' . $title .'">';
  }
  function tep_content_title1_bottom(){
  	echo '
			   </td></tr></table>
			   </td>
			  </tr>
  			 </table>
			</td>
		  </tr>';
  }
  // Get tax rate from tax description
  function tep_get_tax_rate_from_desc($tax_desc) {
    $tax_query = tep_db_query("select tax_rate from " . TABLE_TAX_RATES . " where tax_description = '" . $tax_desc . "'");
    $tax = tep_db_fetch_array($tax_query);
    return $tax['tax_rate'];
  }
  
	function load_menu($parent,$level=1,$path=""){
		global $menu_arr,$login_groups_id,$navig_list;
		$show_items=SHOP_SELL_ITEMS;
		
		$menu_query=tep_db_query("SELECT m.menu_id,md.menu_text,m.filename,params from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.parent_id='" . $parent. "' and m.menu_id=md.menu_id and '" .$show_items . "' like concat('%',menu_item_type,'%') order by m.menu_pos");
		//echo "SELECT m.menu_id,md.menu_text,m.filename,params from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.parent_id='" . $parent. "' and m.menu_id=md.menu_id and '" .$show_items . "' like concat('%',menu_item_type,'%') order by m.menu_pos";
		
		if (tep_db_num_rows($menu_query)<=0) return;
		if ($path!="") $path.="_";
		$icnt=1;
		while($menu_result=tep_db_fetch_array($menu_query)){
			$menu_arr[$level][$menu_result["menu_id"]]=array("text"=>$menu_result["menu_text"],"path"=>$path . $menu_result["menu_id"],"file"=>$menu_result["filename"],"params"=>$menu_result["params"]);
			if ($GLOBALS["l" . $level]==$menu_result["menu_id"]){
				$menu_arr[$level][$menu_result["menu_id"]]["select"]=1;
			}
			if ($level>1 && $GLOBALS["l" . ($level-1)]==$parent){
				$menu_arr[$level][$menu_result["menu_id"]]["show"]=1;
			}
			if ($level>1) {
				$navig_list[substr($path,0,-1)][]=$menu_result["menu_id"];
			}
			load_menu($menu_result["menu_id"],$level+1,$path . $menu_result["menu_id"]);
			if ($level>1 && $menu_arr[$level][$menu_result["menu_id"]]["file"]!="" && $menu_arr[$level-1][$parent]["file"]==""){
				$menu_arr[$level-1][$parent]["file"]=$menu_arr[$level][$menu_result["menu_id"]]["file"];
				$menu_arr[$level-1][$parent]["params"]=$menu_arr[$level][$menu_result["menu_id"]]["params"];
				$menu_arr[$level-1][$parent]["path"]=$menu_arr[$level][$menu_result["menu_id"]]["path"];
			}
			$icnt++;
		}
		mysql_free_result($menu_query);
   }

	function get_current_menu_path(){
		global $CURRENT_MENU,$PHP_SELF,$menu_path;
		if ($CURRENT_MENU && $CURRENT_MENU!=''){
			$menu_query=tep_db_query("select m.menu_id,m.parent_id from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.menu_id=md.menu_id and md.menu_text='" . $CURRENT_MENU ."'");
		} else {
			$menu_query=tep_db_query("select m.menu_id,m.parent_id from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.menu_id=md.menu_id and m.filename='" . basename($PHP_SELF) ."'");
			//$menu_query=tep_db_query("select m.menu_id,m.parent_id from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.menu_id=md.menu_id and m.filename='customers.php'");
		}
		if (tep_db_num_rows($menu_query)<=0) return;
		$menu_result=tep_db_fetch_array($menu_query);
		$path=$menu_result["menu_id"];
		get_recursive_path($menu_result["parent_id"],$path);
		return $path;
	}
	function get_recursive_path($menu_id,&$path){
		if ($menu_id<=0) return;
		$path=$menu_id ."_" . $path;
		$menu_query=tep_db_query("select m.menu_id,m.parent_id from " . TABLE_ADMIN_MENUS . " m," . TABLE_ADMIN_MENUS_DESCRIPTION . " md where m.menu_id=md.menu_id and m.menu_id='" . $menu_id ."'");
		if (tep_db_num_rows($menu_query)<=0) return $path;
		$menu_result=tep_db_fetch_array($menu_query);
		get_recursive_path($menu_result["parent_id"],$path);
	}
	function draw_panel_handle_start($panelname,$icon){
		$panelname1=str_replace(" ","_",strtolower($panelname));
		echo '
				<table border="0" width="100%" cellpadding="0" cellspacing="0">
					<tr>
						<td valign="top" class="cell_bg_navig_l4">
						<table border="0" cellpadding="2" cellspacing="0" width="100%">
							<tr>
								<td width="18" align="right"><img src="images/template/' . $icon . '"/></td>
								<td>' . $panelname . '</td>
								<td width="10" onClick="javascript:toggle_left_panel(\'' . $panelname1 . '\');" style="cursor:pointer;cursor:hand"><img src="images/template/ico_arrow_up.gif" id="img_' . $panelname1 . '"></td>
							</tr>
						</table>
						</td>
					</tr>
					<tr id="panel_' . $panelname1 .'">
						<td>
						<table border="0" width="100%" cellpadding="0" cellspacing="0">
			';
	}
	function draw_panel_handle_end(){
		echo '
						</table>
						</td>
					</tr>
				</table>
			';
	}
	function tep_get_expanded_params($params){
		$params_splt=split('&',$params);
		$new_params='';
		for ($icnt=0,$n=count($params_splt);$icnt<$n;$icnt++){
			if (substr($params_splt[$icnt],0,1)=='$'){
				$new_params.=substr($params_splt[$icnt],1) . '=' .$GLOBALS[substr($params_splt[$icnt],1)] .'&';
			} else if ($params_splt[$icnt]!=''){
				$new_params.=$params_splt[$icnt] . '&';
			}
		}
		return $new_params;
	}
	// get the information display tree
  /*function tep_get_information_display_tree($parent_id = '0', $spacing = '', $exclude = '', $information_tree_array = '', $include_itself = false) {
    global $languages_id;

    if (!is_array($information_tree_array)) $information_tree_array = array();
    if ( (sizeof($information_tree_array) < 1) && ($exclude != '0') ) $information_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);

    if ($include_itself) { 
      $information_query = tep_db_query("select pd.page_name from " . TABLE_MAINPAGE_DESCRIPTIONS . " pd where pd.language_id = '" . (int)$languages_id . "' and pd.page_id = '" . (int)$parent_id . "'");
      $information = tep_db_fetch_array($information_query);
      $information_tree_array[] = array('id' => $parent_id, 'text' => $information['page_name']);
    }
    $information_query = tep_db_query("select p.page_id, pd.page_name, p.parent_id from " . TABLE_MAINPAGE . " p, " . TABLE_MAINPAGE_DESCRIPTIONS . " pd where p.page_id = pd.page_id and pd.language_id = '" . (int)$languages_id . "' and p.parent_id = '" . (int)$parent_id . "' order by p.sort_order, pd.page_name");
    while ($informations = tep_db_fetch_array($information_query)) {
      if ($exclude != $informations['page_id']) $information_tree_array[] = array('id' => $infomations['page_id'], 'text' => $spacing . $informations['page_name']);
      $information_tree_array = tep_get_information_display_tree($informations['page_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $information_tree_array);
    }
   /* $products_query=tep_db_query("select pd.products_name,pd.products_id from " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd where pcd.categories_id='" . (int)$parent_id . "' and pd.products_id=pcd.products_id and pd.language_id = '" . (int)$languages_id . "'");
    while ($products=tep_db_fetch_array($products_query))
    {
        $category_tree_array[] = array('id' => $products['products_id'], 'text' => $spacing . $products['products_name'] . '(product)');
    }*/
  /*  return $information_tree_array;
  }*/
  
	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); 
			if($tot_average<=40)
				return false;
			else
				return true;
				
	}
function tep_check_error($error){
	if($error=='') return false;
	
	$errors = '<div align="center" >' .
			  '<table border="0" cellspacing="0" cellpadding="1" width="100%">'	.
			  '<tr height="30"> <td class="error"></td>' . '<td class="error">' . '<img src="../admin/images/error_info.jpg ">'.'&nbsp;&nbsp;&nbsp;' . $error . '</td>' . '<td></td>' .
			  '</tr></table></div>';
	
	return $errors;

}
// products tree structure
	
	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.=' class="inputNormal" onBlur="javascript:toggle_focus(this,1);" onFocus="javascript:toggle_focus(this,2);"';
		$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_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_display_weight($weight){
		return $weight . '&nbsp;' . tep_get_unit_name();
	}
	function tep_count_shipping_modules() {
		return tep_count_modules(MODULE_SHIPPING_INSTALLED);
	}	 
	function tep_cfg_skynet_zone_settings(){
		return '<a href="'.tep_href_link(FILENAME_SKYNET_ZONESETTINGS).'"><img src="images/template/img_edit.gif" alt="Edit" title="Edit" border="0"></a>';
	}   
  
	function product_prices($products_id,$return_type='content'){
		global $currencies,$cart;
		$products_price_break_sql = "select * from " . TABLE_PRODUCTS_PRICE_BREAK . " ppb where products_id = '" . $products_id . "' order by quantity";
		$products_price_break_query = tep_db_query($products_price_break_sql);
		$products_price_sql = "select products_price,products_tax_class_id from " . TABLE_PRODUCTS . " p where products_id = '" . $products_id . "'";
		$products_price_query = tep_db_query($products_price_sql);
		$products_price_result = tep_db_fetch_array($products_price_query);
		$return_string = "<tr><td align='center' class='dataTableContent'><b>Quantity</td><td align='left' class='dataTableContent'><b>Price</td></tr>";
		$return_string .= "<tr class='moduleRow' onClick='javascript:setQuantity(this,1)' onmouseout='javascript:rowOutEffect2(this);' onmouseover='javascript:rowOverEffect2(this);'><td align='center' class='dataTableContent'>1</td><td align='left' class='dataTableContent'>" . $currencies->format(tep_add_tax($products_price_result['products_price'],tep_get_tax_rate($products_price_result["products_tax_class_id"]))) . "</td></tr>";
		while($products_price_break_result = tep_db_fetch_array($products_price_break_query)){
			$return_string .= "<tr class='moduleRow' onClick='javascript:setQuantity(this," . $products_price_break_result['quantity'] . ")' onmouseout='javascript:rowOutEffect2(this);' onmouseover='javascript:rowOverEffect2(this);'>";
			$return_string .= "<td align='center' class='dataTableContent'>";
			$return_string .= $products_price_break_result['quantity'];
			$return_string .= "</td>";
			$return_string .= "<td align='left' class='dataTableContent'>";
			$return_string .= $currencies->format($products_price_break_result['quantity']*tep_add_tax(($products_price_result['products_price'] - $products_price_break_result['discount_per_item']),tep_get_tax_rate($products_price_result["products_tax_class_id"])));
			$return_string .= "</td>";
			$return_string .= "</tr>";
		}
		$return_string .= "<tr height='20'><td colspan='2' align='left' class='dataTableContent'></tr>";
		return $return_string;
	}
   //=====================today============
  function tep_get_upgrade_alert_text($val)
  {
  	if($val=="d")
		return(TEXT_DEVELOPER_ALERT);
	else
		return(TEXT_NEW_USER_ALERT);
  }
  function tep_cfg_upgrade_alerts($value,$key='')
  {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_radio_field($name,'n',($value=="n"?true:false)) . '&nbsp;' . TEXT_NEW_USER_ALERT_TEXT . '<br>';
	$result.=tep_draw_radio_field($name,'d',($value=="d"?true:false)) . '&nbsp;' . TEXT_DEVELOPER_ALERT_TEXT . '&nbsp;';
	return $result;
  }
  function tep_cfg_email_alerts($value,$key='')
  {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
	$result=tep_draw_radio_field($name,'true',($value=="true"?true:false),'','onclick=javascript:show_email_field(1);') . '&nbsp;' . TEXT_TRUE . '<br>';
	if($value==true)
	{
   		$configuration_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'SECURITY_ALERT_EMAIL_ADDRESS'");        
		$row= tep_db_fetch_array($configuration_query);
		$email=$row['configuration_value'];
	}
	else
		$email='';
	$result.="<span id='show_email'" . ($value=="true"?"":" style=display:none") . ">Email Address : " .tep_draw_input_field('email_address',$email) . '<br>';
	$result.="Confirm Email : " .tep_draw_input_field('cemail_address',$email) . '<br></span>';
	$result.=tep_draw_radio_field($name,'false',($value=="false"?true:false),'','onclick=javascript:show_email_field(2);') . '&nbsp;' . TEXT_FALSE . '&nbsp;';
	return $result;
  }
  
  
   require('wallet_general.php');
?>